task_type
stringclasses
4 values
code_task
stringclasses
15 values
start_line
int64
4
1.79k
end_line
int64
4
1.8k
before
stringlengths
79
76.1k
between
stringlengths
17
806
after
stringlengths
2
72.6k
reason_categories_output
stringlengths
2
2.24k
horizon_categories_output
stringlengths
83
3.99k
reason_freq_analysis
stringclasses
150 values
horizon_freq_analysis
stringlengths
23
185
completion_java
DoubleVectorTester
348
348
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented']
[' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);']
[' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[]
Library 'Math' used at line 348 is defined at line 3 and has a Long-Range dependency. Global_Variable 'myLength' used at line 348 is defined at line 307 and has a Long-Range dependency. Variable 'nonEmptyEls' used at line 348 is defined at line 341 and has a Short-Range dependency. Global_Variable 'baselineValue' used at line 348 is defined at line 304 and has a Long-Range dependency. Variable 'returnVal' used at line 348 is defined at line 340 and has a Short-Range dependency.
{}
{'Library Long-Range': 1, 'Global_Variable Long-Range': 2, 'Variable Short-Range': 2}
completion_java
DoubleVectorTester
354
354
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length']
[' if (getLength() != addToHim.getLength ()) {']
[' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[{'reason_category': 'If Condition', 'usage_line': 354}]
Function 'getLength' used at line 354 is defined at line 20 and has a Long-Range dependency. Variable 'addToHim' used at line 354 is defined at line 352 and has a Short-Range dependency.
{'If Condition': 1}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
DoubleVectorTester
367
367
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in']
[' addToHim.addToAll (baselineValue);']
[' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[]
Variable 'addToHim' used at line 367 is defined at line 352 and has a Medium-Range dependency. Global_Variable 'baselineValue' used at line 367 is defined at line 304 and has a Long-Range dependency.
{}
{'Variable Medium-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
DoubleVectorTester
377
377
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds']
[' if (whichOne >= myLength || whichOne < 0) {']
[' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[{'reason_category': 'If Condition', 'usage_line': 377}]
Variable 'whichOne' used at line 377 is defined at line 374 and has a Short-Range dependency. Global_Variable 'myLength' used at line 377 is defined at line 307 and has a Long-Range dependency.
{'If Condition': 1}
{'Variable Short-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
DoubleVectorTester
382
382
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up']
[' Double myVal = nonEmptyEntries.get (whichOne);']
[' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[]
Global_Variable 'nonEmptyEntries' used at line 382 is defined at line 300 and has a Long-Range dependency. Variable 'whichOne' used at line 382 is defined at line 374 and has a Short-Range dependency.
{}
{'Global_Variable Long-Range': 1, 'Variable Short-Range': 1}
completion_java
DoubleVectorTester
393
393
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds']
[' if (whichOne >= myLength || whichOne < 0) {']
[' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[{'reason_category': 'If Condition', 'usage_line': 393}]
Variable 'whichOne' used at line 393 is defined at line 390 and has a Short-Range dependency. Global_Variable 'myLength' used at line 393 is defined at line 307 and has a Long-Range dependency.
{'If Condition': 1}
{'Variable Short-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
DoubleVectorTester
398
398
['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in']
[' nonEmptyEntries.put (whichOne, setToMe - baselineValue);']
[' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', '']
[]
Global_Variable 'nonEmptyEntries' used at line 398 is defined at line 300 and has a Long-Range dependency. Variable 'whichOne' used at line 398 is defined at line 390 and has a Short-Range dependency. Variable 'setToMe' used at line 398 is defined at line 390 and has a Short-Range dependency. Global_Variable 'baselineValue' used at line 398 is defined at line 304 and has a Long-Range dependency.
{}
{'Global_Variable Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
63
63
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor"]
[' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {']
[' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 63}, {'reason_category': 'If Condition', 'usage_line': 63}]
Variable 'numToFactorize' used at line 63 is defined at line 34 and has a Medium-Range dependency. Global_Variable 'allPrimes' used at line 63 is defined at line 21 and has a Long-Range dependency. Variable 'curPosInAllPrimes' used at line 63 is defined at line 54 and has a Short-Range dependency.
{'Loop Body': 1, 'If Condition': 1}
{'Variable Medium-Range': 1, 'Global_Variable Long-Range': 1, 'Variable Short-Range': 1}
completion_java
FactorizationTester
68
69
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {']
[' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;']
[' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 68}, {'reason_category': 'If Body', 'usage_line': 68}, {'reason_category': 'Loop Body', 'usage_line': 69}, {'reason_category': 'If Body', 'usage_line': 69}]
Global_Variable 'resultStream' used at line 68 is defined at line 27 and has a Long-Range dependency. Global_Variable 'allPrimes' used at line 68 is defined at line 21 and has a Long-Range dependency. Variable 'curPosInAllPrimes' used at line 68 is defined at line 54 and has a Medium-Range dependency. Variable 'firstOne' used at line 69 is defined at line 58 and has a Medium-Range dependency.
{'Loop Body': 2, 'If Body': 2}
{'Global_Variable Long-Range': 2, 'Variable Medium-Range': 2}
completion_java
FactorizationTester
73
73
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {']
[' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);']
[' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 73}, {'reason_category': 'If Body', 'usage_line': 73}, {'reason_category': 'Else Reasoning', 'usage_line': 73}]
Global_Variable 'resultStream' used at line 73 is defined at line 27 and has a Long-Range dependency. Global_Variable 'allPrimes' used at line 73 is defined at line 21 and has a Long-Range dependency. Variable 'curPosInAllPrimes' used at line 73 is defined at line 54 and has a Medium-Range dependency.
{'Loop Body': 1, 'If Body': 1, 'Else Reasoning': 1}
{'Global_Variable Long-Range': 2, 'Variable Medium-Range': 1}
completion_java
FactorizationTester
77
77
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target']
[' numToFactorize /= allPrimes[curPosInAllPrimes];']
[' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 77}, {'reason_category': 'If Body', 'usage_line': 77}]
Global_Variable 'allPrimes' used at line 77 is defined at line 21 and has a Long-Range dependency. Variable 'curPosInAllPrimes' used at line 77 is defined at line 54 and has a Medium-Range dependency. Variable 'numToFactorize' used at line 77 is defined at line 34 and has a Long-Range dependency.
{'Loop Body': 1, 'If Body': 1}
{'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1, 'Variable Long-Range': 1}
completion_java
FactorizationTester
81
81
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {']
[' curPosInAllPrimes++;']
[' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 81}, {'reason_category': 'Else Reasoning', 'usage_line': 81}]
Variable 'curPosInAllPrimes' used at line 81 is defined at line 54 and has a Medium-Range dependency.
{'Loop Body': 1, 'Else Reasoning': 1}
{'Variable Medium-Range': 1}
completion_java
FactorizationTester
87
87
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {']
[' resultStream.format ("%d", numToFactorize);']
[" // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'If Body', 'usage_line': 87}]
Global_Variable 'resultStream' used at line 87 is defined at line 27 and has a Long-Range dependency. Variable 'numToFactorize' used at line 87 is defined at line 77 and has a Short-Range dependency.
{'If Body': 1}
{'Global_Variable Long-Range': 1, 'Variable Short-Range': 1}
completion_java
FactorizationTester
89
91
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'"]
[' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }']
[' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Else Reasoning', 'usage_line': 89}, {'reason_category': 'Else Reasoning', 'usage_line': 90}, {'reason_category': 'Else Reasoning', 'usage_line': 91}]
Variable 'numToFactorize' used at line 89 is defined at line 77 and has a Medium-Range dependency. Global_Variable 'resultStream' used at line 90 is defined at line 27 and has a Long-Range dependency. Variable 'numToFactorize' used at line 90 is defined at line 77 and has a Medium-Range dependency.
{'Else Reasoning': 3}
{'Variable Medium-Range': 2, 'Global_Variable Long-Range': 1}
completion_java
FactorizationTester
111
112
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially']
[' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];']
[' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Library 'Math' used at line 111 is defined at line 4 and has a Long-Range dependency. Global_Variable 'maxNumberToFactorize' used at line 111 is defined at line 107 and has a Short-Range dependency. Global_Variable 'upperBound' used at line 111 is defined at line 15 and has a Long-Range dependency. Global_Variable 'upperBound' used at line 112 is defined at line 111 and has a Short-Range dependency. Global_Variable 'allPrimes' used at line 112 is defined at line 21 and has a Long-Range dependency.
{}
{'Library Long-Range': 1, 'Global_Variable Short-Range': 2, 'Global_Variable Long-Range': 2}
completion_java
FactorizationTester
115
115
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.']
[' int numIntsInList = upperBound - 1;']
[' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Global_Variable 'upperBound' used at line 115 is defined at line 111 and has a Short-Range dependency.
{}
{'Global_Variable Short-Range': 1}
completion_java
FactorizationTester
123
124
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {']
[' allPrimes[i] = i + 2;', ' }']
[' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 123}, {'reason_category': 'Loop Body', 'usage_line': 124}]
Variable 'i' used at line 123 is defined at line 122 and has a Short-Range dependency. Global_Variable 'allPrimes' used at line 123 is defined at line 112 and has a Medium-Range dependency.
{'Loop Body': 2}
{'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1}
completion_java
FactorizationTester
130
130
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.']
[' int curPos = numPrimes + 1;']
[' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 130}]
Global_Variable 'numPrimes' used at line 130 is defined at line 118 and has a Medium-Range dependency.
{'Loop Body': 1}
{'Global_Variable Medium-Range': 1}
completion_java
FactorizationTester
137
140
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost"]
[' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }']
[' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 137}, {'reason_category': 'If Condition', 'usage_line': 137}, {'reason_category': 'Loop Body', 'usage_line': 138}, {'reason_category': 'If Body', 'usage_line': 138}, {'reason_category': 'Loop Body', 'usage_line': 139}, {'reason_category': 'If Body', 'usage_line': 139}, {'reason_category': 'Loop Body', 'usage_line': 140}, {'reason_category': 'If Body', 'usage_line': 140}]
Global_Variable 'allPrimes' used at line 137 is defined at line 112 and has a Medium-Range dependency. Variable 'i' used at line 137 is defined at line 133 and has a Short-Range dependency. Global_Variable 'numPrimes' used at line 137 is defined at line 118 and has a Medium-Range dependency. Global_Variable 'allPrimes' used at line 138 is defined at line 112 and has a Medium-Range dependency. Variable 'i' used at line 138 is defined at line 133 and has a Short-Range dependency. Variable 'curPos' used at line 138 is defined at line 130 and has a Short-Range dependency. Variable 'curPos' used at line 139 is defined at line 130 and has a Short-Range dependency.
{'Loop Body': 4, 'If Condition': 1, 'If Body': 3}
{'Global_Variable Medium-Range': 3, 'Variable Short-Range': 4}
completion_java
FactorizationTester
144
144
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to']
[' numIntsInList = curPos;']
[' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 144}]
Variable 'curPos' used at line 144 is defined at line 130 and has a Medium-Range dependency. Variable 'numIntsInList' used at line 144 is defined at line 115 and has a Medium-Range dependency.
{'Loop Body': 1}
{'Variable Medium-Range': 2}
completion_java
FactorizationTester
147
147
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime']
[' numPrimes++;']
[' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 147}]
Global_Variable 'numPrimes' used at line 147 is defined at line 118 and has a Medium-Range dependency.
{'Loop Body': 1}
{'Global_Variable Medium-Range': 1}
completion_java
FactorizationTester
196
197
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number']
[' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);']
['', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 196 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 196 is defined at line 170 and has a Medium-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 197 is defined at line 34 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Function Long-Range': 1}
completion_java
FactorizationTester
204
204
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results']
[' assertEquals (expected, result.toString());']
[' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Variable 'expected' used at line 204 is defined at line 200 and has a Short-Range dependency. Global_Variable 'result' used at line 204 is defined at line 165 and has a Long-Range dependency.
{}
{'Variable Short-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
FactorizationTester
209
219
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
['', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 210 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 210 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 211 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 215 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 215 is defined at line 214 and has a Short-Range dependency. Global_Variable 'result' used at line 215 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 218 is defined at line 214 and has a Short-Range dependency. Global_Variable 'result' used at line 218 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
223
233
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 224 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 224 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 225 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 229 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 229 is defined at line 228 and has a Short-Range dependency. Global_Variable 'result' used at line 229 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 232 is defined at line 228 and has a Short-Range dependency. Global_Variable 'result' used at line 232 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
237
247
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
['', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 238 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 238 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 239 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 243 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 243 is defined at line 242 and has a Short-Range dependency. Global_Variable 'result' used at line 243 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 246 is defined at line 242 and has a Short-Range dependency. Global_Variable 'result' used at line 246 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
251
261
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 252 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 252 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 253 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 257 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 257 is defined at line 256 and has a Short-Range dependency. Global_Variable 'result' used at line 257 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 260 is defined at line 256 and has a Short-Range dependency. Global_Variable 'result' used at line 260 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
265
275
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 266 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 266 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 267 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 271 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 271 is defined at line 270 and has a Short-Range dependency. Global_Variable 'result' used at line 271 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 274 is defined at line 270 and has a Short-Range dependency. Global_Variable 'result' used at line 274 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
279
289
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 280 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 280 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 281 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 285 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 285 is defined at line 284 and has a Short-Range dependency. Global_Variable 'result' used at line 285 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 288 is defined at line 284 and has a Short-Range dependency. Global_Variable 'result' used at line 288 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
293
295
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);']
['', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 294 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 294 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 295 is defined at line 34 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1}
completion_java
FactorizationTester
307
309
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);']
['', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 308 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 308 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 309 is defined at line 34 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1}
completion_java
FactorizationTester
320
322
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);']
['', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 321 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 321 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 322 is defined at line 34 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1}
completion_java
FactorizationTester
335
345
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
['', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 336 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 336 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 337 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 341 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 341 is defined at line 340 and has a Short-Range dependency. Global_Variable 'result' used at line 341 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 344 is defined at line 340 and has a Short-Range dependency. Global_Variable 'result' used at line 344 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
350
360
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
['', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 351 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 351 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 352 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 356 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 356 is defined at line 355 and has a Short-Range dependency. Global_Variable 'result' used at line 356 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 359 is defined at line 355 and has a Short-Range dependency. Global_Variable 'result' used at line 359 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
365
375
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 366 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 366 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 367 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 371 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 371 is defined at line 370 and has a Short-Range dependency. Global_Variable 'result' used at line 371 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 374 is defined at line 370 and has a Short-Range dependency. Global_Variable 'result' used at line 374 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
380
390
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
[' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 381 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 381 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 382 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 386 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 386 is defined at line 385 and has a Short-Range dependency. Global_Variable 'result' used at line 386 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 389 is defined at line 385 and has a Short-Range dependency. Global_Variable 'result' used at line 389 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
395
405
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }']
['', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 396 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 396 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 397 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 401 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 401 is defined at line 400 and has a Short-Range dependency. Global_Variable 'result' used at line 401 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 404 is defined at line 400 and has a Short-Range dependency. Global_Variable 'result' used at line 404 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
410
419
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {']
[' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());']
[' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[]
Class 'PrimeFactorizer' used at line 411 is defined at line 12 and has a Long-Range dependency. Global_Variable 'outputStream' used at line 411 is defined at line 170 and has a Long-Range dependency. Function 'PrimeFactorizer.printPrimeFactorization' used at line 412 is defined at line 34 and has a Long-Range dependency. Function 'printInfo' used at line 416 is defined at line 183 and has a Long-Range dependency. Variable 'expected' used at line 416 is defined at line 415 and has a Short-Range dependency. Global_Variable 'result' used at line 416 is defined at line 165 and has a Long-Range dependency. Variable 'expected' used at line 419 is defined at line 415 and has a Short-Range dependency. Global_Variable 'result' used at line 419 is defined at line 165 and has a Long-Range dependency.
{}
{'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2}
completion_java
FactorizationTester
452
453
['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result']
[' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());']
[' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}']
[{'reason_category': 'Loop Body', 'usage_line': 452}, {'reason_category': 'If Body', 'usage_line': 452}, {'reason_category': 'Loop Body', 'usage_line': 453}, {'reason_category': 'If Body', 'usage_line': 453}]
Variable 'expected' used at line 453 is defined at line 452 and has a Short-Range dependency. Global_Variable 'result' used at line 453 is defined at line 165 and has a Long-Range dependency.
{'Loop Body': 2, 'If Body': 2}
{'Variable Short-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
CounterTester
75
77
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically']
[' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }']
[" // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Condition', 'usage_line': 75}, {'reason_category': 'If Body', 'usage_line': 76}, {'reason_category': 'If Body', 'usage_line': 77}]
Variable 'w' used at line 75 is defined at line 72 and has a Short-Range dependency. Global_Variable 'myCount' used at line 75 is defined at line 14 and has a Long-Range dependency. Global_Variable 'myWord' used at line 76 is defined at line 13 and has a Long-Range dependency. Variable 'w' used at line 76 is defined at line 72 and has a Short-Range dependency.
{'If Condition': 1, 'If Body': 2}
{'Variable Short-Range': 2, 'Global_Variable Long-Range': 2}
completion_java
CounterTester
79
79
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'"]
[' return w.myCount - myCount;']
[' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Variable 'w' used at line 79 is defined at line 72 and has a Short-Range dependency. Global_Variable 'myCount' used at line 79 is defined at line 14 and has a Long-Range dependency.
{}
{'Variable Short-Range': 1, 'Global_Variable Long-Range': 1}
completion_java
CounterTester
107
110
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {']
[' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);']
[' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Body', 'usage_line': 107}, {'reason_category': 'If Body', 'usage_line': 108}, {'reason_category': 'If Body', 'usage_line': 109}, {'reason_category': 'If Body', 'usage_line': 110}]
Global_Variable 'ones' used at line 107 is defined at line 94 and has a Medium-Range dependency. Variable 'addMe' used at line 107 is defined at line 105 and has a Short-Range dependency. Class 'WordWrapper' used at line 108 is defined at line 11 and has a Long-Range dependency. Variable 'addMe' used at line 108 is defined at line 105 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 108 is defined at line 97 and has a Medium-Range dependency. Global_Variable 'wordsIHaveSeen' used at line 109 is defined at line 93 and has a Medium-Range dependency. Variable 'addMe' used at line 109 is defined at line 105 and has a Short-Range dependency. Variable 'temp' used at line 109 is defined at line 108 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 110 is defined at line 97 and has a Medium-Range dependency. Variable 'temp' used at line 110 is defined at line 108 and has a Short-Range dependency.
{'If Body': 4}
{'Global_Variable Medium-Range': 4, 'Variable Short-Range': 5, 'Class Long-Range': 1}
completion_java
CounterTester
114
114
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen']
[' if (wordsIHaveSeen.containsKey (addMe)) {']
[' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Condition', 'usage_line': 114}]
Global_Variable 'wordsIHaveSeen' used at line 114 is defined at line 93 and has a Medium-Range dependency. Variable 'addMe' used at line 114 is defined at line 105 and has a Short-Range dependency.
{'If Condition': 1}
{'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
116
117
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count']
[' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();']
['', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Body', 'usage_line': 116}, {'reason_category': 'If Body', 'usage_line': 117}]
Class 'WordWrapper' used at line 116 is defined at line 11 and has a Long-Range dependency. Global_Variable 'wordsIHaveSeen' used at line 116 is defined at line 93 and has a Medium-Range dependency. Variable 'addMe' used at line 116 is defined at line 105 and has a Medium-Range dependency. Variable 'temp' used at line 117 is defined at line 116 and has a Short-Range dependency.
{'If Body': 2}
{'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Medium-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
122
131
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ']
[' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }']
['', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Body', 'usage_line': 122}, {'reason_category': 'Loop Body', 'usage_line': 122}, {'reason_category': 'If Body', 'usage_line': 123}, {'reason_category': 'Loop Body', 'usage_line': 123}, {'reason_category': 'If Body', 'usage_line': 124}, {'reason_category': 'Loop Body', 'usage_line': 124}, {'reason_category': 'If Body', 'usage_line': 125}, {'reason_category': 'Loop Body', 'usage_line': 125}, {'reason_category': 'If Body', 'usage_line': 126}, {'reason_category': 'Loop Body', 'usage_line': 126}, {'reason_category': 'If Body', 'usage_line': 127}, {'reason_category': 'Loop Body', 'usage_line': 127}, {'reason_category': 'If Body', 'usage_line': 128}, {'reason_category': 'Loop Body', 'usage_line': 128}, {'reason_category': 'If Body', 'usage_line': 129}, {'reason_category': 'Loop Body', 'usage_line': 129}, {'reason_category': 'If Body', 'usage_line': 130}, {'reason_category': 'Loop Body', 'usage_line': 130}, {'reason_category': 'If Body', 'usage_line': 131}, {'reason_category': 'Loop Body', 'usage_line': 131}]
Global_Variable 'extractedWords' used at line 122 is defined at line 97 and has a Medium-Range dependency. Variable 'i' used at line 122 is defined at line 121 and has a Short-Range dependency. Function 'compareTo' used at line 122 is defined at line 72 and has a Long-Range dependency. Global_Variable 'extractedWords' used at line 123 is defined at line 97 and has a Medium-Range dependency. Variable 'i' used at line 123 is defined at line 121 and has a Short-Range dependency. Variable 'temp' used at line 123 is defined at line 116 and has a Short-Range dependency. Variable 'temp' used at line 124 is defined at line 123 and has a Short-Range dependency. Variable 'i' used at line 124 is defined at line 121 and has a Short-Range dependency. Class 'WordWrapper' used at line 126 is defined at line 11 and has a Long-Range dependency. Global_Variable 'extractedWords' used at line 126 is defined at line 97 and has a Medium-Range dependency. Variable 'i' used at line 126 is defined at line 121 and has a Short-Range dependency. Variable 'temp2' used at line 127 is defined at line 126 and has a Short-Range dependency. Variable 'i' used at line 127 is defined at line 121 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 129 is defined at line 97 and has a Long-Range dependency. Variable 'i' used at line 129 is defined at line 121 and has a Short-Range dependency. Variable 'temp2' used at line 129 is defined at line 126 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 130 is defined at line 97 and has a Long-Range dependency. Variable 'i' used at line 130 is defined at line 121 and has a Short-Range dependency. Variable 'temp' used at line 130 is defined at line 123 and has a Short-Range dependency.
{'If Body': 10, 'Loop Body': 10}
{'Global_Variable Medium-Range': 3, 'Variable Short-Range': 12, 'Function Long-Range': 1, 'Class Long-Range': 1, 'Global_Variable Long-Range': 2}
completion_java
CounterTester
135
135
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {']
[' ones.put (addMe, addMe);']
[' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Else Reasoning', 'usage_line': 135}]
Global_Variable 'ones' used at line 135 is defined at line 94 and has a Long-Range dependency. Variable 'addMe' used at line 135 is defined at line 105 and has a Medium-Range dependency.
{'Else Reasoning': 1}
{'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1}
completion_java
CounterTester
150
156
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {']
[' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;']
[' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Body', 'usage_line': 150}, {'reason_category': 'If Body', 'usage_line': 151}, {'reason_category': 'Define Stop Criteria', 'usage_line': 151}, {'reason_category': 'Loop Body', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 152}, {'reason_category': 'If Condition', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 153}, {'reason_category': 'Loop Body', 'usage_line': 153}, {'reason_category': 'If Body', 'usage_line': 154}, {'reason_category': 'Loop Body', 'usage_line': 154}, {'reason_category': 'If Body', 'usage_line': 155}, {'reason_category': 'Loop Body', 'usage_line': 155}, {'reason_category': 'If Body', 'usage_line': 156}]
Global_Variable 'extractedWords' used at line 150 is defined at line 97 and has a Long-Range dependency. Global_Variable 'ones' used at line 151 is defined at line 94 and has a Long-Range dependency. Variable 'which' used at line 152 is defined at line 150 and has a Short-Range dependency. Variable 'k' used at line 152 is defined at line 146 and has a Short-Range dependency. Variable 's' used at line 153 is defined at line 151 and has a Short-Range dependency. Variable 'which' used at line 154 is defined at line 150 and has a Short-Range dependency.
{'If Body': 7, 'Define Stop Criteria': 1, 'Loop Body': 4, 'If Condition': 1}
{'Global_Variable Long-Range': 2, 'Variable Short-Range': 4}
completion_java
CounterTester
160
160
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords']
[' return extractedWords.get (k).extractWord ();']
[' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Else Reasoning', 'usage_line': 160}]
Global_Variable 'extractedWords' used at line 160 is defined at line 97 and has a Long-Range dependency. Variable 'k' used at line 160 is defined at line 146 and has a Medium-Range dependency. Function 'extractWord' used at line 160 is defined at line 30 and has a Long-Range dependency.
{'Else Reasoning': 1}
{'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1, 'Function Long-Range': 1}
completion_java
CounterTester
147
162
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {']
['', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }']
['}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'If Condition', 'usage_line': 149}, {'reason_category': 'If Body', 'usage_line': 150}, {'reason_category': 'If Body', 'usage_line': 151}, {'reason_category': 'Define Stop Criteria', 'usage_line': 151}, {'reason_category': 'Loop Body', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 152}, {'reason_category': 'If Condition', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 153}, {'reason_category': 'Loop Body', 'usage_line': 153}, {'reason_category': 'If Body', 'usage_line': 154}, {'reason_category': 'Loop Body', 'usage_line': 154}, {'reason_category': 'If Body', 'usage_line': 155}, {'reason_category': 'Loop Body', 'usage_line': 155}, {'reason_category': 'If Body', 'usage_line': 156}, {'reason_category': 'Else Reasoning', 'usage_line': 157}, {'reason_category': 'Else Reasoning', 'usage_line': 158}, {'reason_category': 'Else Reasoning', 'usage_line': 159}, {'reason_category': 'Else Reasoning', 'usage_line': 160}, {'reason_category': 'Else Reasoning', 'usage_line': 161}]
Variable 'k' used at line 149 is defined at line 146 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 149 is defined at line 97 and has a Long-Range dependency. Global_Variable 'extractedWords' used at line 150 is defined at line 97 and has a Long-Range dependency. Global_Variable 'ones' used at line 151 is defined at line 94 and has a Long-Range dependency. Variable 'which' used at line 152 is defined at line 150 and has a Short-Range dependency. Variable 'k' used at line 152 is defined at line 146 and has a Short-Range dependency. Variable 's' used at line 153 is defined at line 151 and has a Short-Range dependency. Variable 'which' used at line 154 is defined at line 150 and has a Short-Range dependency. Global_Variable 'extractedWords' used at line 160 is defined at line 97 and has a Long-Range dependency. Variable 'k' used at line 160 is defined at line 146 and has a Medium-Range dependency. Function 'extractWord' used at line 160 is defined at line 30 and has a Long-Range dependency.
{'If Condition': 2, 'If Body': 7, 'Define Stop Criteria': 1, 'Loop Body': 4, 'Else Reasoning': 5}
{'Variable Short-Range': 5, 'Global_Variable Long-Range': 4, 'Variable Medium-Range': 1, 'Function Long-Range': 1}
completion_java
CounterTester
201
201
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {']
[' closeFiles();']
[' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'closeFiles' used at line 201 is defined at line 180 and has a Medium-Range dependency.
{}
{'Function Medium-Range': 1}
completion_java
CounterTester
237
237
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter."]
[' counter.insert(word);']
[' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 237}]
Variable 'counter' used at line 237 is defined at line 227 and has a Short-Range dependency. Variable 'word' used at line 237 is defined at line 232 and has a Short-Range dependency.
{'Loop Body': 1}
{'Variable Short-Range': 2}
completion_java
CounterTester
259
261
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method."]
[' if (word == null) {', ' return;', ' }']
[' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 259}, {'reason_category': 'If Condition', 'usage_line': 259}, {'reason_category': 'Loop Body', 'usage_line': 260}, {'reason_category': 'If Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 261}, {'reason_category': 'If Body', 'usage_line': 261}]
Variable 'word' used at line 259 is defined at line 257 and has a Short-Range dependency.
{'Loop Body': 3, 'If Condition': 1, 'If Body': 2}
{'Variable Short-Range': 1}
completion_java
CounterTester
265
267
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.']
[' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }']
['', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 265}, {'reason_category': 'If Condition', 'usage_line': 265}, {'reason_category': 'Loop Body', 'usage_line': 266}, {'reason_category': 'If Body', 'usage_line': 266}, {'reason_category': 'Loop Body', 'usage_line': 267}, {'reason_category': 'If Body', 'usage_line': 267}]
Variable 'i' used at line 265 is defined at line 256 and has a Short-Range dependency. Variable 'counter' used at line 266 is defined at line 253 and has a Medium-Range dependency. Variable 'j' used at line 266 is defined at line 255 and has a Medium-Range dependency.
{'Loop Body': 3, 'If Condition': 1, 'If Body': 2}
{'Variable Short-Range': 1, 'Variable Medium-Range': 2}
completion_java
CounterTester
270
271
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100']
[' if (j == 100)', ' j = 0;']
[' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 270}, {'reason_category': 'If Condition', 'usage_line': 270}, {'reason_category': 'Loop Body', 'usage_line': 271}, {'reason_category': 'If Body', 'usage_line': 271}]
Variable 'j' used at line 270 is defined at line 255 and has a Medium-Range dependency. Variable 'j' used at line 271 is defined at line 255 and has a Medium-Range dependency.
{'Loop Body': 2, 'If Condition': 1, 'If Body': 1}
{'Variable Medium-Range': 2}
completion_java
CounterTester
291
295
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {']
[' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;']
[' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 291}, {'reason_category': 'Loop Body', 'usage_line': 292}, {'reason_category': 'Loop Body', 'usage_line': 293}, {'reason_category': 'Loop Body', 'usage_line': 294}, {'reason_category': 'Loop Body', 'usage_line': 295}]
Variable 'counter' used at line 291 is defined at line 289 and has a Short-Range dependency. Variable 'start' used at line 291 is defined at line 289 and has a Short-Range dependency. Variable 'start' used at line 293 is defined at line 289 and has a Short-Range dependency. Variable 'expected' used at line 293 is defined at line 289 and has a Short-Range dependency. Variable 'i' used at line 293 is defined at line 290 and has a Short-Range dependency. Variable 'actual' used at line 293 is defined at line 291 and has a Short-Range dependency. Variable 'expected' used at line 294 is defined at line 289 and has a Short-Range dependency. Variable 'i' used at line 294 is defined at line 290 and has a Short-Range dependency. Variable 'actual' used at line 294 is defined at line 291 and has a Short-Range dependency. Variable 'start' used at line 295 is defined at line 289 and has a Short-Range dependency.
{'Loop Body': 5}
{'Variable Short-Range': 10}
completion_java
CounterTester
310
311
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice']
[' counter.insert("pizza");', ' counter.insert("pizza");']
[' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'WordCounter.insert' used at line 310 is defined at line 105 and has a Long-Range dependency. Function 'WordCounter.insert' used at line 311 is defined at line 105 and has a Long-Range dependency.
{}
{'Function Long-Range': 2}
completion_java
CounterTester
356
356
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"']
[' openFile("allWordsBig");']
[' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'openFile' used at line 356 is defined at line 209 and has a Long-Range dependency.
{}
{'Function Long-Range': 1}
completion_java
CounterTester
358
358
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words']
[' readWords(counter, 100);']
[' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'readWords' used at line 358 is defined at line 227 and has a Long-Range dependency. Variable 'counter' used at line 358 is defined at line 354 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
367
367
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");']
[' readWords(counter, 100);']
[' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'readWords' used at line 367 is defined at line 227 and has a Long-Range dependency. Variable 'counter' used at line 367 is defined at line 365 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
369
369
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};']
[' checkExpected(counter, 0, expected1);']
['', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'checkExpected' used at line 369 is defined at line 289 and has a Long-Range dependency. Variable 'counter' used at line 369 is defined at line 365 and has a Short-Range dependency. Variable 'expected1' used at line 369 is defined at line 368 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
completion_java
CounterTester
374
374
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};']
[' checkExpected(counter, 0, expected2);']
['', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'checkExpected' used at line 374 is defined at line 289 and has a Long-Range dependency. Variable 'counter' used at line 374 is defined at line 365 and has a Short-Range dependency. Variable 'expected2' used at line 374 is defined at line 373 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
completion_java
CounterTester
387
387
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words']
[' readWords(counter, 300);']
[' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'readWords' used at line 387 is defined at line 227 and has a Long-Range dependency. Variable 'counter' used at line 387 is defined at line 384 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
389
389
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};']
[' checkExpected(counter, 14, expected);']
[' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'checkExpected' used at line 389 is defined at line 289 and has a Long-Range dependency. Variable 'counter' used at line 389 is defined at line 384 and has a Short-Range dependency. Variable 'expected' used at line 389 is defined at line 388 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
completion_java
CounterTester
396
396
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");']
[' readWords(counter, 300);']
[' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'readWords' used at line 396 is defined at line 227 and has a Long-Range dependency. Variable 'counter' used at line 396 is defined at line 394 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
400
402
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */']
[' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));']
[' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'WordCounter.getKthMostFrequent' used at line 400 is defined at line 146 and has a Long-Range dependency. Function 'WordCounter.getKthMostFrequent' used at line 401 is defined at line 146 and has a Long-Range dependency. Function 'WordCounter.getKthMostFrequent' used at line 402 is defined at line 146 and has a Long-Range dependency.
{}
{'Function Long-Range': 3}
completion_java
CounterTester
405
405
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.']
[' assertNull(counter.getKthMostFrequent(125));']
[' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'WordCounter.getKthMostFrequent' used at line 405 is defined at line 146 and has a Long-Range dependency.
{}
{'Function Long-Range': 1}
completion_java
CounterTester
410
412
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");']
[' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);']
[' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Class 'WordCounter' used at line 410 is defined at line 89 and has a Long-Range dependency. Function 'openFile' used at line 411 is defined at line 209 and has a Long-Range dependency. Function 'readWords' used at line 412 is defined at line 227 and has a Long-Range dependency. Variable 'counter1' used at line 412 is defined at line 410 and has a Short-Range dependency.
{}
{'Class Long-Range': 1, 'Function Long-Range': 2, 'Variable Short-Range': 1}
completion_java
CounterTester
431
431
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words']
[' readWords(counter, 6000000);']
[' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[]
Function 'readWords' used at line 431 is defined at line 227 and has a Long-Range dependency. Variable 'counter' used at line 431 is defined at line 428 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
completion_java
CounterTester
445
445
['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {']
[' counter.getKthMostFrequent(i);']
[' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}']
[{'reason_category': 'Loop Body', 'usage_line': 445}]
Function 'WordCounter.getKthMostFrequent' used at line 445 is defined at line 146 and has a Long-Range dependency. Variable 'i' used at line 445 is defined at line 444 and has a Short-Range dependency.
{'Loop Body': 1}
{'Function Long-Range': 1, 'Variable Short-Range': 1}
infilling_python
Image_Filtering
10
22
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):']
[' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel']
['', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'sigma' used at line 10 is defined at line 9 and has a Short-Range dependency. Variable 'kernel_size' used at line 11 is defined at line 9 and has a Short-Range dependency. Variable 'size_x' used at line 13 is defined at line 11 and has a Short-Range dependency. Variable 'size_y' used at line 14 is defined at line 11 and has a Short-Range dependency. Library 'np' used at line 16 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 16 is defined at line 10 and has a Short-Range dependency. Variable 'size_x' used at line 16 is defined at line 13 and has a Short-Range dependency. Library 'np' used at line 17 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_y' used at line 17 is defined at line 10 and has a Short-Range dependency. Variable 'size_y' used at line 17 is defined at line 14 and has a Short-Range dependency. Library 'np' used at line 19 is imported at line 1 and has a Medium-Range dependency. Variable 'x' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_x' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'y' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_y' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 20 is defined at line 19 and has a Short-Range dependency. Library 'np' used at line 20 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'sigma_y' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 21 is defined at line 20 and has a Short-Range dependency. Variable 'kernel' used at line 22 is defined at line 21 and has a Short-Range dependency.
{}
{'Variable Short-Range': 17, 'Library Medium-Range': 4}
infilling_python
Image_Filtering
14
14
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1']
[' size_y = int(size_y) // 2 * 2 + 1']
['', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'size_y' used at line 14 is defined at line 11 and has a Short-Range dependency.
{}
{'Variable Short-Range': 1}
infilling_python
Image_Filtering
16
22
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '']
[' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel']
['', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'np' used at line 16 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 16 is defined at line 10 and has a Short-Range dependency. Variable 'size_x' used at line 16 is defined at line 13 and has a Short-Range dependency. Library 'np' used at line 17 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_y' used at line 17 is defined at line 10 and has a Short-Range dependency. Variable 'size_y' used at line 17 is defined at line 14 and has a Short-Range dependency. Library 'np' used at line 19 is imported at line 1 and has a Medium-Range dependency. Variable 'x' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_x' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'y' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_y' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 20 is defined at line 19 and has a Short-Range dependency. Library 'np' used at line 20 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'sigma_y' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 21 is defined at line 20 and has a Short-Range dependency. Variable 'kernel' used at line 22 is defined at line 21 and has a Short-Range dependency.
{}
{'Library Medium-Range': 4, 'Variable Short-Range': 13}
infilling_python
Image_Filtering
16
17
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '']
[' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))']
[' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'np' used at line 16 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 16 is defined at line 10 and has a Short-Range dependency. Variable 'size_x' used at line 16 is defined at line 13 and has a Short-Range dependency. Library 'np' used at line 17 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_y' used at line 17 is defined at line 10 and has a Short-Range dependency. Variable 'size_y' used at line 17 is defined at line 14 and has a Short-Range dependency.
{}
{'Library Medium-Range': 2, 'Variable Short-Range': 4}
infilling_python
Image_Filtering
17
17
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),']
[' np.linspace(-3*sigma_y, 3*sigma_y, size_y))']
[' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'np' used at line 17 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_y' used at line 17 is defined at line 10 and has a Short-Range dependency. Variable 'size_y' used at line 17 is defined at line 14 and has a Short-Range dependency.
{}
{'Library Medium-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
19
22
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ']
[' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel']
['', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'np' used at line 19 is imported at line 1 and has a Medium-Range dependency. Variable 'x' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_x' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'y' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_y' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 20 is defined at line 19 and has a Short-Range dependency. Library 'np' used at line 20 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'sigma_y' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 21 is defined at line 20 and has a Short-Range dependency. Variable 'kernel' used at line 22 is defined at line 21 and has a Short-Range dependency.
{}
{'Library Medium-Range': 2, 'Variable Short-Range': 9}
infilling_python
Image_Filtering
19
19
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ']
[' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))']
[' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'np' used at line 19 is imported at line 1 and has a Medium-Range dependency. Variable 'x' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_x' used at line 19 is defined at line 10 and has a Short-Range dependency. Variable 'y' used at line 19 is defined at line 16 and has a Short-Range dependency. Variable 'sigma_y' used at line 19 is defined at line 10 and has a Short-Range dependency.
{}
{'Library Medium-Range': 1, 'Variable Short-Range': 4}
infilling_python
Image_Filtering
20
22
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))']
[' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel']
['', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'kernel' used at line 20 is defined at line 19 and has a Short-Range dependency. Library 'np' used at line 20 is imported at line 1 and has a Medium-Range dependency. Variable 'sigma_x' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'sigma_y' used at line 20 is defined at line 10 and has a Short-Range dependency. Variable 'kernel' used at line 21 is defined at line 20 and has a Short-Range dependency. Variable 'kernel' used at line 22 is defined at line 21 and has a Short-Range dependency.
{}
{'Variable Short-Range': 5, 'Library Medium-Range': 1}
infilling_python
Image_Filtering
21
22
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y']
[' kernel /= kernel.sum()', ' return kernel']
['', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'kernel' used at line 21 is defined at line 20 and has a Short-Range dependency. Variable 'kernel' used at line 22 is defined at line 21 and has a Short-Range dependency.
{}
{'Variable Short-Range': 2}
infilling_python
Image_Filtering
26
35
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)']
[' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image']
['', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'image' used at line 26 is defined at line 25 and has a Short-Range dependency. Variable 'w' used at line 28 is defined at line 26 and has a Short-Range dependency. Variable 'target_size' used at line 28 is defined at line 24 and has a Short-Range dependency. Variable 'h' used at line 29 is defined at line 26 and has a Short-Range dependency. Variable 'target_size' used at line 29 is defined at line 24 and has a Short-Range dependency. Variable 'left' used at line 31 is defined at line 28 and has a Short-Range dependency. Variable 'target_size' used at line 31 is defined at line 24 and has a Short-Range dependency. Variable 'top' used at line 32 is defined at line 29 and has a Short-Range dependency. Variable 'target_size' used at line 32 is defined at line 24 and has a Short-Range dependency. Variable 'image' used at line 34 is defined at line 25 and has a Short-Range dependency. Variable 'top' used at line 34 is defined at line 29 and has a Short-Range dependency. Variable 'bottom' used at line 34 is defined at line 32 and has a Short-Range dependency. Variable 'right' used at line 34 is defined at line 31 and has a Short-Range dependency. Variable 'cropped_image' used at line 35 is defined at line 34 and has a Short-Range dependency.
{}
{'Variable Short-Range': 14}
infilling_python
Image_Filtering
28
29
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '']
[' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2']
['', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'w' used at line 28 is defined at line 26 and has a Short-Range dependency. Variable 'target_size' used at line 28 is defined at line 24 and has a Short-Range dependency. Variable 'h' used at line 29 is defined at line 26 and has a Short-Range dependency. Variable 'target_size' used at line 29 is defined at line 24 and has a Short-Range dependency.
{}
{'Variable Short-Range': 4}
infilling_python
Image_Filtering
29
29
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2']
[' top = (h - target_size[1]) // 2']
['', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'h' used at line 29 is defined at line 26 and has a Short-Range dependency. Variable 'target_size' used at line 29 is defined at line 24 and has a Short-Range dependency.
{}
{'Variable Short-Range': 2}
infilling_python
Image_Filtering
31
32
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '']
[' right = left + target_size[0]', ' bottom = top + target_size[1]']
['', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'left' used at line 31 is defined at line 28 and has a Short-Range dependency. Variable 'target_size' used at line 31 is defined at line 24 and has a Short-Range dependency. Variable 'top' used at line 32 is defined at line 29 and has a Short-Range dependency. Variable 'target_size' used at line 32 is defined at line 24 and has a Short-Range dependency.
{}
{'Variable Short-Range': 4}
infilling_python
Image_Filtering
32
32
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]']
[' bottom = top + target_size[1]']
['', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'top' used at line 32 is defined at line 29 and has a Short-Range dependency. Variable 'target_size' used at line 32 is defined at line 24 and has a Short-Range dependency.
{}
{'Variable Short-Range': 2}
infilling_python
Image_Filtering
34
35
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '']
[' cropped_image = image[top:bottom, 0:right]', ' return cropped_image']
['', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'image' used at line 34 is defined at line 25 and has a Short-Range dependency. Variable 'top' used at line 34 is defined at line 29 and has a Short-Range dependency. Variable 'bottom' used at line 34 is defined at line 32 and has a Short-Range dependency. Variable 'right' used at line 34 is defined at line 31 and has a Short-Range dependency. Variable 'cropped_image' used at line 35 is defined at line 34 and has a Short-Range dependency.
{}
{'Variable Short-Range': 5}
infilling_python
Image_Filtering
44
45
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])']
['img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))']
['print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Function 'center_crop' used at line 44 is defined at line 24 and has a Medium-Range dependency. Library 'cv2' used at line 44 is imported at line 2 and has a Long-Range dependency. Variable 'img_a' used at line 44 is defined at line 37 and has a Short-Range dependency. Variable 'smallest_dim' used at line 44 is defined at line 43 and has a Short-Range dependency. Function 'center_crop' used at line 45 is defined at line 24 and has a Medium-Range dependency. Library 'cv2' used at line 45 is imported at line 2 and has a Long-Range dependency. Variable 'img_b' used at line 45 is defined at line 38 and has a Short-Range dependency. Variable 'smallest_dim' used at line 45 is defined at line 43 and has a Short-Range dependency.
{}
{'Function Medium-Range': 2, 'Library Long-Range': 2, 'Variable Short-Range': 4}
infilling_python
Image_Filtering
45
45
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))']
['img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))']
['print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Function 'center_crop' used at line 45 is defined at line 24 and has a Medium-Range dependency. Library 'cv2' used at line 45 is imported at line 2 and has a Long-Range dependency. Variable 'img_b' used at line 45 is defined at line 38 and has a Short-Range dependency. Variable 'smallest_dim' used at line 45 is defined at line 43 and has a Short-Range dependency.
{}
{'Function Medium-Range': 1, 'Library Long-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
54
54
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)']
['gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)']
['', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Function 'gaussian2D' used at line 54 is defined at line 9 and has a Long-Range dependency. Variable 'sigma_a' used at line 54 is defined at line 52 and has a Short-Range dependency. Variable 'kernel_size_a' used at line 54 is defined at line 53 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
56
58
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '']
['sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)']
['', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Function 'gaussian2D' used at line 58 is defined at line 9 and has a Long-Range dependency. Variable 'sigma_b' used at line 58 is defined at line 56 and has a Short-Range dependency. Variable 'kernel_size_b' used at line 58 is defined at line 57 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
58
58
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)']
['gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)']
['', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Function 'gaussian2D' used at line 58 is defined at line 9 and has a Long-Range dependency. Variable 'sigma_b' used at line 58 is defined at line 56 and has a Short-Range dependency. Variable 'kernel_size_b' used at line 58 is defined at line 57 and has a Short-Range dependency.
{}
{'Function Long-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
60
61
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '']
['blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)']
['', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'cv2' used at line 60 is imported at line 2 and has a Long-Range dependency. Variable 'img_a_gray' used at line 60 is defined at line 44 and has a Medium-Range dependency. Variable 'gaussian_kernel_a' used at line 60 is defined at line 54 and has a Short-Range dependency. Library 'cv2' used at line 61 is imported at line 2 and has a Long-Range dependency. Variable 'img_b_gray' used at line 61 is defined at line 45 and has a Medium-Range dependency. Variable 'gaussian_kernel_b' used at line 61 is defined at line 58 and has a Short-Range dependency.
{}
{'Library Long-Range': 2, 'Variable Medium-Range': 2, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
61
61
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)']
['blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)']
['', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Library 'cv2' used at line 61 is imported at line 2 and has a Long-Range dependency. Variable 'img_b_gray' used at line 61 is defined at line 45 and has a Medium-Range dependency. Variable 'gaussian_kernel_b' used at line 61 is defined at line 58 and has a Short-Range dependency.
{}
{'Library Long-Range': 1, 'Variable Medium-Range': 1, 'Variable Short-Range': 1}
infilling_python
Image_Filtering
63
64
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '']
['a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff']
['print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'img_a_gray' used at line 63 is defined at line 44 and has a Medium-Range dependency. Variable 'blur_a' used at line 63 is defined at line 60 and has a Short-Range dependency. Variable 'blur_b' used at line 64 is defined at line 61 and has a Short-Range dependency. Variable 'a_diff' used at line 64 is defined at line 63 and has a Short-Range dependency.
{}
{'Variable Medium-Range': 1, 'Variable Short-Range': 3}
infilling_python
Image_Filtering
73
73
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor']
[' new_width = width // factor']
['', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'width' used at line 73 is defined at line 71 and has a Short-Range dependency. Variable 'factor' used at line 73 is defined at line 67 and has a Short-Range dependency.
{}
{'Variable Short-Range': 2}
infilling_python
Image_Filtering
76
76
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:']
[' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)']
[' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'If Body', 'usage_line': 76}]
Library 'np' used at line 76 is imported at line 1 and has a Long-Range dependency. Variable 'new_height' used at line 76 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 76 is defined at line 73 and has a Short-Range dependency. Variable 'image' used at line 76 is defined at line 67 and has a Short-Range dependency.
{'If Body': 1}
{'Library Long-Range': 1, 'Variable Short-Range': 3}
infilling_python
Image_Filtering
78
78
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:']
[' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)']
['', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'Else Reasoning', 'usage_line': 78}]
Library 'np' used at line 78 is imported at line 1 and has a Long-Range dependency. Variable 'new_height' used at line 78 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 78 is defined at line 73 and has a Short-Range dependency.
{'Else Reasoning': 1}
{'Library Long-Range': 1, 'Variable Short-Range': 2}
infilling_python
Image_Filtering
80
83
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '']
[' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image']
['', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'Define Stop Criteria', 'usage_line': 80}, {'reason_category': 'Define Stop Criteria', 'usage_line': 81}, {'reason_category': 'Loop Body', 'usage_line': 82}]
Variable 'new_height' used at line 80 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 81 is defined at line 73 and has a Short-Range dependency. Variable 'downsampled_image' used at line 82 is defined at line 78 and has a Short-Range dependency. Variable 'i' used at line 82 is part of a Loop defined at line 80 and has a Short-Range dependency. Variable 'j' used at line 82 is part of a Loop defined at line 81 and has a Short-Range dependency. Variable 'image' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'factor' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'downsampled_image' used at line 83 is defined at line 78 and has a Short-Range dependency.
{'Define Stop Criteria': 2, 'Loop Body': 1}
{'Variable Short-Range': 4, 'Variable Loop Short-Range': 2, 'Variable Medium-Range': 2}
infilling_python
Image_Filtering
81
83
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):']
[' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image']
['', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'Define Stop Criteria', 'usage_line': 81}, {'reason_category': 'Loop Body', 'usage_line': 82}]
Variable 'new_width' used at line 81 is defined at line 73 and has a Short-Range dependency. Variable 'downsampled_image' used at line 82 is defined at line 78 and has a Short-Range dependency. Variable 'i' used at line 82 is part of a Loop defined at line 80 and has a Short-Range dependency. Variable 'j' used at line 82 is part of a Loop defined at line 81 and has a Short-Range dependency. Variable 'image' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'factor' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'downsampled_image' used at line 83 is defined at line 78 and has a Short-Range dependency.
{'Define Stop Criteria': 1, 'Loop Body': 1}
{'Variable Short-Range': 3, 'Variable Loop Short-Range': 2, 'Variable Medium-Range': 2}
infilling_python
Image_Filtering
82
83
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):']
[' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image']
['', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'Loop Body', 'usage_line': 82}]
Variable 'downsampled_image' used at line 82 is defined at line 78 and has a Short-Range dependency. Variable 'i' used at line 82 is part of a Loop defined at line 80 and has a Short-Range dependency. Variable 'j' used at line 82 is part of a Loop defined at line 81 and has a Short-Range dependency. Variable 'image' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'factor' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'downsampled_image' used at line 83 is defined at line 78 and has a Short-Range dependency.
{'Loop Body': 1}
{'Variable Short-Range': 2, 'Variable Loop Short-Range': 2, 'Variable Medium-Range': 2}
infilling_python
Image_Filtering
72
83
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]']
[' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image']
['', 'downsampling_factor = 4', 'downsampled_image = downsample_image(img_c, downsampling_factor)', 'print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[{'reason_category': 'If Condition', 'usage_line': 75}, {'reason_category': 'If Body', 'usage_line': 76}, {'reason_category': 'Else Reasoning', 'usage_line': 77}, {'reason_category': 'Else Reasoning', 'usage_line': 78}, {'reason_category': 'Define Stop Criteria', 'usage_line': 80}, {'reason_category': 'Define Stop Criteria', 'usage_line': 81}, {'reason_category': 'Loop Body', 'usage_line': 82}]
Variable 'height' used at line 72 is defined at line 71 and has a Short-Range dependency. Variable 'factor' used at line 72 is defined at line 67 and has a Short-Range dependency. Variable 'width' used at line 73 is defined at line 71 and has a Short-Range dependency. Variable 'factor' used at line 73 is defined at line 67 and has a Short-Range dependency. Variable 'image' used at line 75 is defined at line 67 and has a Short-Range dependency. Library 'np' used at line 76 is imported at line 1 and has a Long-Range dependency. Variable 'new_height' used at line 76 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 76 is defined at line 73 and has a Short-Range dependency. Variable 'image' used at line 76 is defined at line 67 and has a Short-Range dependency. Library 'np' used at line 78 is imported at line 1 and has a Long-Range dependency. Variable 'new_height' used at line 78 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 78 is defined at line 73 and has a Short-Range dependency. Variable 'new_height' used at line 80 is defined at line 72 and has a Short-Range dependency. Variable 'new_width' used at line 81 is defined at line 73 and has a Short-Range dependency. Variable 'downsampled_image' used at line 82 is defined at line 78 and has a Short-Range dependency. Variable 'i' used at line 82 is part of a Loop defined at line 80 and has a Short-Range dependency. Variable 'j' used at line 82 is part of a Loop defined at line 81 and has a Short-Range dependency. Variable 'image' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'factor' used at line 82 is defined at line 67 and has a Medium-Range dependency. Variable 'downsampled_image' used at line 83 is defined at line 78 and has a Short-Range dependency.
{'If Condition': 1, 'If Body': 1, 'Else Reasoning': 2, 'Define Stop Criteria': 2, 'Loop Body': 1}
{'Variable Short-Range': 14, 'Library Long-Range': 2, 'Variable Loop Short-Range': 2, 'Variable Medium-Range': 2}
infilling_python
Image_Filtering
86
86
['import numpy as np', 'import cv2', 'import matplotlib.pyplot as plt', 'from scipy.signal import convolve2d', 'from scipy.signal import butter, filtfilt', '', '# Task1', '# Gaussian blurring einstein monroe illusion', 'def gaussian2D(sigma, kernel_size):', ' sigma_x, sigma_y = sigma', ' size_x, size_y = kernel_size', '', ' size_x = int(size_x) // 2 * 2 + 1', ' size_y = int(size_y) // 2 * 2 + 1', '', ' x, y = np.meshgrid(np.linspace(-3*sigma_x, 3*sigma_x, size_x),', ' np.linspace(-3*sigma_y, 3*sigma_y, size_y))', ' ', ' kernel = np.exp(-(x**2 / (2*sigma_x**2) + y**2 / (2*sigma_y**2)))', ' kernel /= 2 * np.pi * sigma_x * sigma_y', ' kernel /= kernel.sum()', ' return kernel', '', 'def center_crop(image, target_size):', ' image = np.array(image)', ' h, w = image.shape[:2]', '', ' left = (w - target_size[0]) // 2', ' top = (h - target_size[1]) // 2', '', ' right = left + target_size[0]', ' bottom = top + target_size[1]', '', ' cropped_image = image[top:bottom, 0:right]', ' return cropped_image', '', "img_a = cv2.imread('./marilyn.jpeg')", "img_b = cv2.imread('./einstein.jpeg')", '', '# Part1', '# Reshape to ensure images are same size by center cropping to image with smallest dimension', '# Convert img to grayscale ', 'smallest_dim = min(img_a.shape[0],img_a.shape[1],img_b.shape[1],img_b.shape[1])', 'img_a_gray = center_crop(cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'img_b_gray = center_crop(cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY),(smallest_dim, smallest_dim))', 'print(np.array(img_a_gray))', 'print(np.array(img_b_gray))', '', '# Part2', '# Apply Gaussian filter to both images choose relevant sigma and kernel size to achieve desired results', '# Use custom gaussian2D function and use cv2.filter2D to apply the filter to the image', 'sigma_a = (1, 1)', 'kernel_size_a = (11, 11)', 'gaussian_kernel_a = gaussian2D(sigma_a, kernel_size_a)', '', 'sigma_b = (1, 1)', 'kernel_size_b = (11, 11)', 'gaussian_kernel_b = gaussian2D(sigma_b, kernel_size_b)', '', 'blur_a = cv2.filter2D(img_a_gray, -1, gaussian_kernel_a)', 'blur_b = cv2.filter2D(img_b_gray, -1, gaussian_kernel_b)', '', 'a_diff = img_a_gray - blur_a', 'img_c = blur_b + a_diff', 'print(img_c)', '', 'def downsample_image(image, factor):', ' if factor <= 0:', ' raise ValueError("Downsampling factor must be greater than 0.")', ' ', ' height, width = image.shape[:2]', ' new_height = height // factor', ' new_width = width // factor', '', ' if len(image.shape) == 3:', ' downsampled_image = np.zeros((new_height, new_width, image.shape[2]), dtype=np.uint8)', ' else:', ' downsampled_image = np.zeros((new_height, new_width), dtype=np.uint8)', '', ' for i in range(new_height):', ' for j in range(new_width):', ' downsampled_image[i, j] = image[i * factor, j * factor]', ' return downsampled_image', '', 'downsampling_factor = 4']
['downsampled_image = downsample_image(img_c, downsampling_factor)']
['print(np.array(downsampled_image))', '', '# Part3', '# Computer fourier magnitude for the final image, original grayscale images, ', '# the blurred second image and difference between grayscale first image and blurred first image', '', 'def compute_fourier_magnitude(image):', ' spectrum = np.abs(np.fft.fftshift(np.fft.fft2(image)))', ' log_spectrum = np.log(1 + spectrum)', ' return log_spectrum', '', 'spectrum_A = compute_fourier_magnitude(img_a_gray)', 'spectrum_B = compute_fourier_magnitude(img_b_gray)', 'spectrum_blurred_B = compute_fourier_magnitude(blur_b)', 'spectrum_A_blur_A = compute_fourier_magnitude(a_diff)', 'spectrum_C = compute_fourier_magnitude(img_c)', 'print(spectrum_A)', 'print(spectrum_B)', 'print(spectrum_A_blur_A)', 'print(spectrum_blurred_B)', 'print(spectrum_C)', '', '# Blend two images with a verticle blend in the middle with laplacian pyramids', '# Part 1 vertical blending halfway through image', "apple = cv2.imread('./apple.jpeg')", "orange = cv2.imread('./orange.jpeg')", 'A = cv2.resize(apple, (256,256), fx=0.5, fy=0.5)', 'B = cv2.resize(orange, (256,256), fx=0.5, fy=0.5)', '', 'G = A.copy()', 'gpA = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpA.append(G)', '', '# Gaussian pyramid for B', 'G = B.copy()', 'gpB = [G]', 'for i in range(6):', ' G = cv2.pyrDown(G)', ' gpB.append(G)', '', '# Laplacian Pyramid for A and B', 'lpA = [gpA[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpA[i])', ' L = cv2.subtract(gpA[i-1],GE)', ' lpA.append(L)', '', 'lpB = [gpB[5]]', 'for i in range(5,0,-1):', ' GE = cv2.pyrUp(gpB[i])', ' L = cv2.subtract(gpB[i-1],GE)', ' lpB.append(L)', '', '# Add left and right halves of images in each level', 'LS = []', 'for la,lb in zip(lpA,lpB):', ' rows,cols,dpt = la.shape', ' ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))', ' LS.append(ls)', '', '# Reconstruct', 'ls_ = LS[0]', 'for i in range(1,6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each half', 'real = np.hstack((A[:,:cols//2],B[:,cols//2:]))', '', 'blended_rgb = cv2.cvtColor(ls_, cv2.COLOR_BGR2RGB)', 'original_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(blended_rgb)', 'print(original_rgb)', '', '# Part 2', '# Blend the image diagonally in a strip following the same steps as above ', '# to accomplish diagnoal blending, use a diagonal mask ', '# Create diagonal mask', 'def create_diagonal_mask(shape, strip_width=200):', ' mask = np.zeros(shape, dtype=np.float32)', ' height, width, _ = mask.shape', ' for i in range(min(height, width)):', ' mask[i, max(0, i - strip_width // 2):min(width, i + strip_width // 2), :] = 1.0', ' return mask', '', '# Now blend images using the diagonal mask', 'LS = []', 'mask = create_diagonal_mask(A.shape)', 'M = mask.copy()', 'gpmask = [M]', 'for i in range(5):', ' M = cv2.pyrDown(M)', ' gpmask.append(M)', 'gpmask.reverse()', 'for i in range(len(gpmask)):', ' rows, cols, dpt = lpA[i].shape', ' ls = lpA[i] * gpmask[i] + lpB[i] * (1 - gpmask[i])', ' LS.append(ls)', '', '# Now reconstruct', 'ls_ = LS[0]', 'for i in range(1, 6):', ' ls_ = cv2.pyrUp(ls_)', ' ls_ = cv2.resize(ls_, (LS[i].shape[1], LS[i].shape[0])) ', ' ls_ = cv2.add(ls_, LS[i])', '', '# Image with direct connecting each diagonal half', 'real = np.hstack((A[:, :cols//2], B[:, cols//2:]))', 'ls_rgb = cv2.cvtColor(ls_.astype(np.uint8), cv2.COLOR_BGR2RGB)', 'real_rgb = cv2.cvtColor(real, cv2.COLOR_BGR2RGB)', '', 'print(ls_rgb)', 'print(real_rgb)', 'print(mask)', '', '', '# Task3', '# Part1', '# Read in a video file in .avi format, choose areas of the face to focus on via bounding box', '# Apply a bandpass filter to the specified regions of the interest based on a lower and upper bound', 'def read_video_into_numpy(filename):', ' cap = cv2.VideoCapture(filename)', ' frames = []', ' while cap.isOpened():', ' ret, frame = cap.read()', ' # if frame is read correctly ret is True', ' if not ret:', ' print("Can\'t receive frame (stream end?). Exiting ...")', ' break', '', ' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)', ' frames.append(frame)', '', ' cap.release()', ' # Converts to numpy array(T,H,W,C)', ' video = np.stack(frames, axis=0)', ' # (T,H,W,C)->(H,W,C,T)', ' video = np.transpose(video, (1,2,3,0))', ' return frames', '', 'def bandpass_filter(signal, low_cutoff, high_cutoff, fs, order):', ' nyquist = 0.5 * fs', ' low = low_cutoff / nyquist', ' high = high_cutoff / nyquist', " b, a = butter(order, [low, high], btype='band')", ' filtered_signal = filtfilt(b, a, signal)', ' return filtered_signal', '', "alice = './alice.avi'", 'video_frames = read_video_into_numpy(alice)', 'first_frame = video_frames[0]', '', '# Specify regions of interest', 'cheek_rect = [(220, 250), (320, 350)]', 'forehead_rect = [(220, 10), (500, 174)]', 'cheek_roi = first_frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', 'forehead_roi = first_frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', '', 'print(cheek_roi)', 'print(forehead_roi)', '', '# Part 2', '# Find the average green value for each frame in the cheek and forhead region of interest', 'cheek_avg_green_values = []', 'forehead_avg_green_values = []', '', 'for frame in video_frames:', ' cheek_roi = frame[cheek_rect[0][1]:cheek_rect[1][1], cheek_rect[0][0]:cheek_rect[1][0]]', ' forehead_roi = frame[forehead_rect[0][1]:forehead_rect[1][1], forehead_rect[0][0]:forehead_rect[1][0]]', ' cheek_avg_green = np.mean(cheek_roi[:, :, 1])', ' forehead_avg_green = np.mean(forehead_roi[:, :, 1])', ' cheek_avg_green_values.append(cheek_avg_green)', ' forehead_avg_green_values.append(forehead_avg_green)', '', 'print(cheek_avg_green_values)', 'print(forehead_avg_green_values)', '', '# Part3', '# Set a lower and upper threshold and apply a bandpass filter to the average green values of cheek and forward ', '# Set fs to 30', '', 'low_cutoff = 0.8', 'high_cutoff = 3', 'fs = 30', 'order = 1', '', 'cheek_filtered_signal = bandpass_filter(cheek_avg_green_values, low_cutoff, high_cutoff, fs, order)', 'forehead_filtered_signal = bandpass_filter(forehead_avg_green_values, low_cutoff, high_cutoff, fs, order)', '', 'print(cheek_filtered_signal)', 'print(forehead_filtered_signal)', '', '# Part4', '# Plot the Fourier magnitudes of these two signals using the DFT, where the x-axis is', '# frequency (in Hertz) and y-axis is amplitude. DFT coefficients are ordered in terms of', '# integer indices, so you will have to convert the indices into Hertz. For each index n = [-', '# N/2, N/2], the corresponding frequency is Fs * n / N, where N is the length of your signal', '# and Fs is the sampling rate of the signal (30 Hz in this case). You can also use', '# numpy.fft.fftfreq to do this conversion for you.', '', 'cheek_fft = np.fft.fft(cheek_filtered_signal)', 'forehead_fft = np.fft.fft(forehead_filtered_signal)', 'print(cheek_fft)', 'print(forehead_fft)', '', 'N = len(cheek_filtered_signal)', 'Fs = 30', 'freq_cheek = np.fft.fftfreq(N, d=1/Fs)', 'freq_forehead = np.fft.fftfreq(N, d=1/Fs)', 'print(np.abs(freq_cheek))', 'print(np.abs(freq_forehead))', '', '# Part5', "# Estimate the pulse rate by finding the index where np.abs(cheek_fft) is at it's maximum", '# Cheek heart rate will be aprox 60*freq_cheek[index of max np.abs(cheek_fft)] -> same idea with forhead', '', 'index_max_cheek = np.argmax(np.abs(cheek_fft))', 'index_max_forehead = np.argmax(np.abs(forehead_fft))', '', 'freq_max_cheek = freq_cheek[index_max_cheek]', 'freq_max_forehead = freq_forehead[index_max_forehead]', '', 'heart_rate_cheek = (freq_max_cheek) * 60', 'heart_rate_forehead = (freq_max_forehead) * 60', '', 'print(f"Heart Rate (Cheek): {heart_rate_cheek:.2f} beats per minute")', 'print(f"Heart Rate (Forehead): {heart_rate_forehead:.2f} beats per minute")']
[]
Variable 'img_c' used at line 86 is defined at line 64 and has a Medium-Range dependency. Variable 'downsampling_factor' used at line 86 is defined at line 85 and has a Short-Range dependency.
{}
{'Variable Medium-Range': 1, 'Variable Short-Range': 1}