Example #1
0
  /** Utility function for encoding a length as a BER byte sequence */
  public static byte[] encodeLength(int length) {
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();

    // see if can be represented in single byte
    // don't forget the first bit is the "long field test" bit!!
    if (length < 128) {
      byte[] len = {(byte) length};
      outBytes.write(len, 0, 1);
    } else {
      // too big for one byte
      // see how many are needed:
      int numBytes = 0;
      int temp = length;
      while (temp > 0) {
        ++numBytes;
        temp = (int) Math.floor(temp / 256);
      }

      byte num = (byte) numBytes;
      num += 128; // set the "long format" bit
      outBytes.write(num);

      byte[] len = new byte[numBytes];
      for (int i = numBytes - 1; i >= 0; --i) {
        len[i] = (byte) (length % 256);
        length = (int) Math.floor(length / 256);
      }
      outBytes.write(len, 0, numBytes);
    }

    return outBytes.toByteArray();
  }
  private byte[] encodeValue(long v) {
    // see how many bytes are needed: each value uses just
    // 7 bits of each byte, with high-order bit functioning as
    // a continuation marker
    int numBytes = 0;
    long temp = v;

    do {
      ++numBytes;
      temp = (long) Math.floor(temp / 128);
    } while (temp > 0);

    byte[] enc = new byte[numBytes];
    // encode lowest-order byte, without setting high bit
    enc[numBytes - 1] = (byte) (v % 128);
    v = (long) Math.floor(v / 128);

    // .encode other bytes with high bit set
    for (int i = numBytes - 2; i >= 0; --i) {
      enc[i] = (byte) ((v % 128) + 128);
      v = (long) Math.floor(v / 128);
    }

    return enc;
  }
Example #3
0
  public void testParallelMAP() throws IOException {

    int maxHits = 1000;
    IndexReader reader = IndexReader.open(FSDirectory.open(new File(indexPath)));
    ParallelImageSearcher searcher;
    searcher = new ParallelImageSearcher(maxHits, CEDD.class, DocumentBuilder.FIELD_NAME_CEDD);
    Pattern p = Pattern.compile("([0-9]+).jpg");
    double map = 0;
    double errorRate = 0d;
    for (int i = 0; i < sampleQueries.length; i++) {
      int id = sampleQueries[i];
      //            System.out.println("id = " + id + ": " + "("+i+")");
      String file = testExtensive + "/" + id + ".jpg";
      String[] files = {
        id + ".jpg", (id + 1) + ".jpg", (id + 2) + ".jpg", (id + 3) + ".jpg", (id + 4) + ".jpg"
      };
      ImageSearchHits[] hits = searcher.search(findDocs(reader, files), reader);
      for (int k = 0; k < hits.length; k++) {
        int currentID = id + k;
        ImageSearchHits h = hits[k];
        int goodOnes = 0;
        double avgPrecision = 0;
        for (int j = 0; j < h.length(); j++) {
          Document d = h.doc(j);
          String hitsId = d.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
          Matcher matcher = p.matcher(hitsId);
          if (matcher.find()) hitsId = matcher.group(1);
          else fail("Did not get the number ...");
          int testID = Integer.parseInt(hitsId);
          if ((testID != currentID)
              && ((int) Math.floor(id / 100) == (int) Math.floor(testID / 100))) {
            goodOnes++;
            // Only if there is a change in recall
            avgPrecision += (double) goodOnes / (double) (j + 1);
            //                    System.out.print("x");
          } else {
            if (j == 1) { // error rate
              errorRate++;
            }
          }
          //                System.out.print(" (" + testID + ") ");
        }
        assertTrue(goodOnes > 0);
        avgPrecision = avgPrecision / goodOnes;
        assertTrue(avgPrecision > 0);
        map += avgPrecision;
        //                System.out.println(" " + avgPrecision + " (" + map / (i + 1) + ")");
      }
    }
    assertTrue(sampleQueries.length > 0);
    map = map / sampleQueries.length;
    errorRate = errorRate / sampleQueries.length;
    System.out.println("map = " + map);
    System.out.println("errorRate = " + errorRate);
  }
Example #4
0
  public boolean transform(ProgressListener progressListener) {

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    pitchFreqSet = pitchSet.getFreqSet();
    audioFTPower = new double[timeRange * (pitchRange + 1)];

    int startSample = timeSet.getStartSample();
    int endSample = timeSet.getEndSample();
    int sampleLength = (int) Math.floor((endSample - startSample) / ((double) resolution));
    double[] audioSamples = new double[sampleLength];

    for (int i = 0; i < sampleLength; i++) {
      audioSamples[i] = (double) audioData[startSample + i * resolution];
    }

    int sampleIndexSize =
        (int) Math.floor((double) timeSet.getSampleIndexSize() / (double) resolution);

    double dt = (double) resolution / sampleRate;
    if (transformMode == TRANSFORM_MODE_JAVA) {
      wavelet.convert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    } else {

      WaveletJNI waveletJNI = new WaveletJNI();

      waveletJNI.waveletConvert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    }

    return true;
  }
Example #5
0
  public void setNeighbours(Message message) {

    String msg = message.message;
    String[] msg_data = msg.split(" ");
    int neigh_count = Integer.parseInt(msg_data[2]);
    if (neigh_count == 9999 || neigh_count == 9998 || neigh_count == 9997 || neigh_count == 9996) {

      System.out.println("Registration failed..!!!");
    }
    if (neigh_count == 1) {

      Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));

    } else if (neigh_count == 2) {

      Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      Configuration.setNeighbor(msg_data[6], Integer.parseInt(msg_data[7]));

      joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      joinWithNeighbor(msg_data[6], Integer.parseInt(msg_data[7]));

    } else if (neigh_count > 2) {

      int rand = (int) Math.floor(Math.random() * neigh_count);

      Configuration.setNeighbor(msg_data[3 * rand + 3], Integer.parseInt(msg_data[3 * rand + 4]));
      int neigh_port_1 = Integer.parseInt(msg_data[3 * rand + 4]), neigh_port_2;
      String neigh_ip_1 = msg_data[3 * rand + 3], neigh_ip_2;

      joinWithNeighbor(neigh_ip_1, neigh_port_1);

      while (true) {
        rand = (int) Math.floor(Math.random() * neigh_count);
        neigh_ip_2 = msg_data[3 * rand + 3];
        neigh_port_2 = Integer.parseInt(msg_data[3 * rand + 4]);

        if (neigh_ip_1.equals(neigh_ip_2) && neigh_port_1 == neigh_port_2) continue;
        else {
          Configuration.setNeighbor(neigh_ip_2, neigh_port_2);
          joinWithNeighbor(neigh_ip_2, neigh_port_2);
          break;
        }
      }
      for (int x = 0; x < neigh_count; x++) {
        Configuration.setBackUpNeighbor(msg_data[3 * x + 3], Integer.parseInt(msg_data[3 * x + 4]));
      }
    }
  }
  /** Initialize all the data structures relevant to the domain */
  private void _initializeDataStructures() {
    this.possibleOperators = new Operator[this.numCakes];
    // Initialize the operators (according to the updated position of the pancake)
    for (int i = 0; i < this.numCakes; ++i) {
      this.possibleOperators[i] = new PancakeOperator(i + 1);
    }
    // Set the maximum index (if it is not already defined)
    if (Pancakes.MAX_PANCAKE_FOR_PDB == -1) {
      this.maxPancakeForPDB = this.numCakes - 1;
    } else {
      this.maxPancakeForPDB = Pancakes.MAX_PANCAKE_FOR_PDB;
    }
    // calculate the bits and bitmask to store single pancake
    this.bitsForSinglePancake = Utils.bits(this.numCakes);
    this.maskForSinglePancake = Utils.mask(this.bitsForSinglePancake);
    // System.out.println("mask: " + this.maskForSinglePancake);
    this.packedCakesInSingleLong =
        Math.min(this.numCakes, (int) Math.floor(64.0d / this.bitsForSinglePancake));
    // System.out.println("packedCakesInSingleLong: " + this.packedCakesInSingleLong);
    this.packedLongsCount = (int) Math.ceil(this.numCakes * this.bitsForSinglePancake / 64.0d);
    // System.out.println("packedLongsCount: " + this.packedLongsCount);

    // Current debugs ..
    // assert(this.bitsForSinglePancake == 5);
    // assert this.packedLongsCount == 2;
  }
Example #7
0
 public void repeatFilter(ReadsByTaxa rbt, double ratio) {
   int[] tagCount = new int[2 * this.getSnpCount()];
   int[] clusterIndex = new int[2 * this.getSnpCount()];
   for (int i = 0; i < cls.length; i++) {
     if (!cls[i].ifSnp) {
       continue;
     }
     int totalA = 0, totalC = 0;
     for (int j = 0; j < rbt.taxaNum; j++) {
       totalA += rbt.hapDist[cls[i].queryIndex][j];
       totalC += rbt.hapDist[cls[i].hitIndex][j];
     }
     tagCount[2 * i] = totalA;
     clusterIndex[2 * i] = i;
     tagCount[2 * i + 1] = totalC;
     clusterIndex[2 * i + 1] = i;
   }
   for (int i = 0; i < tagCount.length - 1; i++) {
     for (int j = i + 1; j < tagCount.length; j++) {
       if (tagCount[i] > tagCount[j]) {
         int mid = tagCount[i];
         tagCount[i] = tagCount[j];
         tagCount[j] = mid;
         mid = clusterIndex[i];
         clusterIndex[i] = clusterIndex[j];
         clusterIndex[j] = mid;
       }
     }
   }
   int beginIndex = (int) Math.floor(clusterIndex.length * (1 - ratio));
   for (int i = beginIndex; i < clusterIndex.length; i++) {
     cls[clusterIndex[i]].ifSnp = false;
   }
 }
Example #8
0
 /**
  * Apply this operator (function) to the supplied argument
  *
  * @param value the argument
  * @return the result
  */
 protected double applyFunction(double value) {
   switch (m_operator) {
     case 'l':
       return Math.log(value);
     case 'b':
       return Math.abs(value);
     case 'c':
       return Math.cos(value);
     case 'e':
       return Math.exp(value);
     case 's':
       return Math.sqrt(value);
     case 'f':
       return Math.floor(value);
     case 'h':
       return Math.ceil(value);
     case 'r':
       return Math.rint(value);
     case 't':
       return Math.tan(value);
     case 'n':
       return Math.sin(value);
   }
   return Double.NaN;
 }
Example #9
0
  private void indexFiles(ArrayList<String> images, DocumentBuilder builder, String indexPath)
      throws IOException {
    // eventually check if the directory is there or not ...
    IndexWriter iw = LuceneUtils.createIndexWriter(testIndex, false);
    int count = 0;
    long time = System.currentTimeMillis();
    for (String identifier : images) {
      // TODO: cut toes from the image ... -> doesn't work out very well. Stable at first,
      // decreasing then.
      // TODO: Joint Histogram ...
      // TODO: LSA / PCA on the vectors ...-> this looks like a job for me :-D
      // TODO: local features ...
      Document doc = null;
      if (cutImages) {
        BufferedImage bimg =
            ImageUtils.cropImage(ImageIO.read(new FileInputStream(identifier)), 0, 0, 200, 69);
        doc = builder.createDocument(bimg, identifier);
      } else doc = builder.createDocument(new FileInputStream(identifier), identifier);
      iw.addDocument(doc);
      count++;
      if (count % 100 == 0) {
        int percent = (int) Math.floor(((double) count * 100.0) / (double) images.size());
        double timeTemp = (double) (System.currentTimeMillis() - time) / 1000d;
        int secsLeft =
            (int) Math.round(((timeTemp / (double) count) * (double) images.size()) - timeTemp);
        System.out.println(percent + "% finished (" + count + " files), " + secsLeft + " s left");
      }
    }
    long timeTaken = (System.currentTimeMillis() - time);
    float sec = ((float) timeTaken) / 1000f;

    System.out.println(sec + " seconds taken, " + (timeTaken / count) + " ms per image.");
    iw.commit();
    iw.close();
  }
Example #10
0
  public void tttestMAPLocalFeatureHistogram() throws IOException {
    int maxSearches = 200;
    int maxHits = 100;
    IndexReader reader = IndexReader.open(FSDirectory.open(new File(indexPath)));
    IndexSearcher is = new IndexSearcher(reader);
    ImageSearcher searcher;
    //        searcher = new SiftLocalFeatureHistogramImageSearcher(maxHits);
    searcher = ImageSearcherFactory.createColorHistogramImageSearcher(maxHits);
    //        searcher = ImageSearcherFactory.createCEDDImageSearcher(maxHits);
    //        searcher = ImageSearcherFactory.createFCTHImageSearcher(maxHits);
    Pattern p = Pattern.compile("\\\\\\d+\\.jpg");
    double map = 0;
    for (int i = 0; i < sampleQueries.length; i++) {
      int id = sampleQueries[i];
      System.out.print("id = " + id + ": ");
      String file = testExtensive + "/" + id + ".jpg";

      ImageSearchHits hits = searcher.search(findDoc(reader, id + ".jpg"), reader);
      int goodOnes = 0;
      double avgPrecision = 0;
      for (int j = 0; j < hits.length(); j++) {
        Document d = hits.doc(j);
        String hitsId = d.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
        Matcher matcher = p.matcher(hitsId);
        if (matcher.find()) hitsId = hitsId.substring(matcher.start() + 1, hitsId.lastIndexOf("."));
        else fail("Did not get the number ...");
        int testID = Integer.parseInt(hitsId);
        //                System.out.print(". " + hitsId + "/"  +
        // d.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]+ " ");
        if ((int) Math.floor(id / 100) == (int) Math.floor(testID / 100)) {
          goodOnes++;
          System.out.print("x");
        } else {
          System.out.print("o");
        }
        //                System.out.print(" (" + testID + ") ");
        avgPrecision += (double) goodOnes / (double) (j + 1);
      }
      avgPrecision = avgPrecision / hits.length();
      map += avgPrecision;
      System.out.println(" " + avgPrecision + " (" + map / (i + 1) + ")");
    }
    map = map / sampleQueries.length;
    System.out.println("map = " + map);
  }
Example #11
0
  public static void compPlayer(ArrayList<Card> hand) {
    // how the computer plays the cards
    if (check(hand) > 0) {
      choice = (int) Math.floor(3 * Math.random() + 1);

      while (choice > check(hand)) {
        choice = (int) Math.floor(3 * Math.random() + 1);
      }
      // "playing" of the cards
      for (int i = 0; i < choice; i++) {
        for (int j = 0; j < hand.size(); j++) {
          if (hand.get(j).getRank() == currentRank) {
            temp = hand.get(j);
            pile.add(temp);
            hand.remove(temp);
          }
        }
      }
      // computer did not cheat
      lastPlayerCheated = false;

    } else {
      // if computer has to cheat
      choice = (int) Math.floor(3 * Math.random() + 1);

      while ((choice > 4) || (choice > hand.size())) {
        choice = (int) Math.floor(3 * Math.random() + 1);
      }
      // playing of the cards
      for (int i = 0; i < choice; i++) {
        temp = hand.get(0);
        pile.add(temp);
        hand.remove(temp);
      }
      // the computer did cheat
      lastPlayerCheated = true;
    }
    // getting the details for the last player
    lastPlayerHand = hand;
    lastPlayerRank = currentRank;
    lastPlayerNum = choice;
    // increase the rank
    increaseRank();
  }
Example #12
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
Example #13
0
  public static void main(String[] args) {
    if (args.length != 1) {
      System.err.println("Usage: Generator number_of_data.");
      System.exit(-1);
    }

    Random rand = new Random();

    int numberOfObjects = new Integer(args[0]).intValue();
    HashMap data = new HashMap(numberOfObjects);

    for (int i = 0; i < numberOfObjects; i++) {
      MyRegion r =
          new MyRegion(rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
      data.put(new Integer(i), r);

      System.out.println(
          "1 " + i + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);
    }

    int A = (int) (Math.floor((double) numberOfObjects * 0.1));

    for (int T = 100; T > 0; T--) {
      System.err.println(T);
      HashSet examined = new HashSet();

      for (int a = 0; a < A; a++) {
        // find an id that is not yet examined.
        Integer id = new Integer((int) ((double) numberOfObjects * rand.nextDouble()));
        boolean b = examined.contains(id);

        while (b) {
          id = new Integer((int) ((double) numberOfObjects * rand.nextDouble()));
          b = examined.contains(id);
        }
        examined.add(id);
        MyRegion r = (MyRegion) data.get(id);

        System.out.println(
            "0 " + id + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);

        r =
            new MyRegion(
                rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
        data.put(id, r);

        System.out.println(
            "1 " + id + " " + r.m_xmin + " " + r.m_ymin + " " + r.m_xmax + " " + r.m_ymax);
      }

      double stx = rand.nextDouble();
      double sty = rand.nextDouble();
      System.out.println("2 9999999 " + stx + " " + sty + " " + (stx + 0.01) + " " + (sty + 0.01));
    }
  }
Example #14
0
 private double parseCoord(String value) {
   try {
     double d = Double.parseDouble(value);
     double deg = Math.floor(d / 100);
     double min = d - (deg * 100);
     return deg + (min / 60);
   } catch (Exception e) {
     this.main.warning("Cannot parse coord \"" + value + "\"", e);
     return Double.NaN;
   }
 }
Example #15
0
 public void makeAvatarOrder() {
   int nRand = (int) Math.floor((Math.random() + 1) + 0.5);
   String sOrder = "A,0|B,0|A,1|B,1|A,2|B,2|A,3|B,3|A,4|B,4";
   String sOrder2 = "B,0|A,0|B,1|A,1|B,2|A,2|B,3|A,3|B,4|A,4";
   if (nRand == 1) {
     makeAvatarOrder(sOrder);
     oConn.send("avatar order", sOrder2);
   } else {
     makeAvatarOrder(sOrder2);
     oConn.send("avatar order", sOrder);
   }
 }
Example #16
0
 boolean solve2() {
   int t = nextInt();
   if (t == 0) return false;
   int n = nextInt();
   Tower[] towers = new Tower[t];
   for (int i = 0; i < t; i++) {
     towers[i] = new Tower(new Point(nextInt(), nextInt()), nextInt());
   }
   n++;
   Point[] p = new Point[n];
   for (int i = 0; i < n; i++) {
     p[i] = new Point(nextInt(), nextInt());
   }
   // System.err.println(Arrays.toString(p));
   ArrayList<Point> points = new ArrayList<Point>();
   double r = 1;
   for (int i = 0; i < n - 1; i++) {
     double dist = p[i].dist(p[i + 1]) - (1 - r);
     int e = (int) Math.floor(dist + 1 - EPS);
     Point v = p[i + 1].subtract(p[i]).norm();
     for (int j = 0; j < e; j++) {
       points.add(p[i].add(v.multiply(j).add(v.multiply(1 - r))));
     }
     r = p[i + 1].dist(points.get(points.size() - 1));
   }
   if (p[n - 1].dist(points.get(points.size() - 1)) > 0.5 - EPS) {
     points.add(p[n - 1]);
   }
   // System.err.println(points);
   char last = 0;
   ArrayList<String> ans = new ArrayList<String>();
   for (int i = 0; i < points.size(); i++) {
     double maxP = Integer.MIN_VALUE;
     char here = 0;
     for (int j = 0; j < t; j++) {
       double w = towers[j].get(points.get(i));
       if (maxP < w - EPS) {
         maxP = w;
         here = (char) (j + 'A');
       }
     }
     if (here != last) {
       ans.add("(" + i + "," + here + ")");
     }
     last = here;
   }
   for (int i = 0; i < ans.size(); i++) {
     if (i != 0) out.print(" ");
     out.print(ans.get(i));
   }
   out.println();
   return true;
 }
Example #17
0
  public void run() {
    ArrayList<Double> output = new ArrayList();

    while (true) {
      int numStudents = Integer.parseInt(Main.ReadLn(1000000));

      double runningTotal = 0;
      double current = 0;
      double average = 0;
      double runningTransfer = 0;

      if (numStudents == 0) break;
      else if (numStudents > 1000) throw new NumberFormatException();
      else if (numStudents % 2 == 0) throw new NumberFormatException();

      ArrayList<Double> expenses = new ArrayList();

      for (int i = 0; i < numStudents; i++) {
        current = Double.parseDouble(Main.ReadLn(1000000));
        runningTotal = runningTotal + current;

        expenses.add(current);

        if (current > 10000 || current < 0) throw new NumberFormatException();
      }

      average = Math.floor((runningTotal * 100) / numStudents) / 100;

      for (Double d : expenses) {
        if (d.doubleValue() < average) {
          runningTransfer = runningTransfer + (average - d.doubleValue());
        }
      }

      output.add(runningTransfer);
    }

    Iterator it = output.iterator();
    StringBuilder builder = new StringBuilder();

    while (it.hasNext()) {
      builder.append("$" + String.format("%.2f", it.next()));

      if (it.hasNext()) {
        builder.append("\n");
      } else {
        break;
      }
    }

    System.out.println(builder);
  }
Example #18
0
 public void printDebug() {
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   System.out.println(
       "    " + StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1));
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     System.out.println(index + " (" + row + ")");
     i++;
   }
 }
  public Color getColorAt(double x, double y) {
    int col = img.getRGB((int) x, (int) y);
    double r = col >> 16 & 0xff;
    double g = col >> 8 & 0xff;
    double b = col & 0xff;

    int col_r = img.getRGB((int) x + 1, (int) y);
    double rr = col_r >> 16 & 0xff;
    double gr = col_r >> 8 & 0xff;
    double br = col_r & 0xff;

    double fact = x - Math.floor(x);

    double rf = r + (rr - r) * fact;
    double gf = g + (gr - g) * fact;
    double bf = b + (br - b) * fact;

    col = img.getRGB((int) x, (int) y + 1);
    r = col >> 16 & 0xff;
    g = col >> 8 & 0xff;
    b = col & 0xff;

    col_r = img.getRGB((int) x + 1, (int) y + 1);
    rr = col_r >> 16 & 0xff;
    gr = col_r >> 8 & 0xff;
    br = col_r & 0xff;

    double rf2 = r + (rr - r) * fact;
    double gf2 = g + (gr - g) * fact;
    double bf2 = b + (br - b) * fact;

    fact = y - Math.floor(y);

    double rff = rf + (rf2 - rf) * fact;
    double gff = gf + (gf2 - gf) * fact;
    double bff = bf + (bf2 - bf) * fact;

    return new Color((int) rff, (int) gff, (int) bff);
  }
  private void extractFromBEREncoding(byte[] enc) throws SNMPBadValueException {
    // note: masks must be ints; byte internal representation issue(?)
    int bitTest = 0x80; // test for leading 1
    int highBitMask = 0x7F; // mask out high bit for value

    // first, compute number of "digits";
    // will just be number of bytes with leading 0's
    int numInts = 0;
    for (int i = 0; i < enc.length; i++) {
      if ((enc[i] & bitTest) == 0) // high-order bit not set; count
      numInts++;
    }

    if (numInts > 0) {
      // create new int array to hold digits; since first value is 40*x + y,
      // need one extra entry in array to hold this.
      digits = new long[numInts + 1];

      int currentByte = -1; // will be incremented to 0

      long value = 0;

      // read in values 'til get leading 0 in byte
      do {
        currentByte++;
        value = value * 128 + (enc[currentByte] & highBitMask);
      } while ((enc[currentByte] & bitTest) > 0); // implies high bit set!

      // now handle 40a + b
      digits[0] = (long) Math.floor(value / 40);
      digits[1] = value % 40;

      // now read in rest!
      for (int i = 2; i < numInts + 1; i++) {
        // read in values 'til get leading 0 in byte
        value = 0;
        do {
          currentByte++;
          value = value * 128 + (enc[currentByte] & highBitMask);
        } while ((enc[currentByte] & bitTest) > 0);

        digits[i] = value;
      }

    } else {
      // no digits; create empty digit array
      digits = new long[0];
    }
  }
Example #21
0
  public boolean load(File file) {

    this.file = file;

    if (file != null && file.isFile()) {
      try {
        errStr = null;
        audioInputStream = AudioSystem.getAudioInputStream(file);

        fileName = file.getName();

        format = audioInputStream.getFormat();

      } catch (Exception ex) {
        reportStatus(ex.toString());
        return false;
      }
    } else {
      reportStatus("Audio file required.");
      return false;
    }

    numChannels = format.getChannels();
    sampleRate = (double) format.getSampleRate();
    sampleBitSize = format.getSampleSizeInBits();
    long frameLength = audioInputStream.getFrameLength();
    long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate());
    double audioFileDuration = milliseconds / 1000.0;

    if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION;
    else duration = audioFileDuration;

    frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength);

    try {
      audioBytes = new byte[(int) frameLength * format.getFrameSize()];
      audioInputStream.read(audioBytes);
    } catch (Exception ex) {
      reportStatus(ex.toString());
      return false;
    }

    getAudioData();

    return true;
  }
Example #22
0
 public static void main(String[] args) throws Exception {
   PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("decoder_bench.cmd")));
   writer.println("stepsize 2ns");
   writer.println("vector a a[5] a[4] a[3] a[2] a[1] a[0]");
   writer.println(
       "vector y y[63] y[62] y[61] y[60] y[59] y[58] y[57] y[56] y[55] y[54] y[53] y[52] y[51] y[50] y[49] y[48] y[47] y[46] y[45] y[44] y[43] y[42] y[41] y[40] y[39] y[38] y[37] y[36] y[35] y[34] y[33] y[32] y[31] y[30] y[29] y[28] y[27] y[26] y[25] y[24] y[23] y[22] y[21] y[20] y[19] y[18] y[17] y[16] y[15] y[14] y[13] y[12] y[11] y[10] y[9] y[8] y[7] y[6] y[5] y[4] y[3] y[2] y[1] y[0]");
   writer.println();
   final int aSize = 6;
   final int ySize = 64;
   StringBuffer a;
   StringBuffer y;
   int tally;
   int phN;
   char ph1;
   for (int i = 0; i < ySize; i++) {
     a = new StringBuffer();
     y = new StringBuffer();
     tally = i;
     for (int j = 0; j < aSize; j++) {
       if (tally % 2 == 0) {
         a.insert(0, 'l');
       } else {
         a.insert(0, 'h');
       }
       tally = (tally - (tally % 2)) / 2;
     }
     for (int j = 0; j < ySize - 1; j++) {
       y.append(0);
     }
     phN = (int) Math.floor(2 * Math.random());
     if (phN == 1) {
       ph1 = 'h';
       y.insert(63 - i, 1);
     } else {
       ph1 = 'l';
       y.insert(63 - i, 0);
     }
     writer.println("print iteration " + i + " ph1 set to " + ph1);
     writer.println("set a " + a);
     writer.println(ph1 + " ph1");
     writer.println("s 50");
     writer.println("assert y " + y);
     writer.println();
   }
   writer.close();
 }
Example #23
0
 private static String doubleToString(double d, int decimal) {
   boolean neg = d < 0;
   d = Math.abs(d);
   long intp = (long) Math.floor(d);
   double rest = d - intp;
   StringBuffer sb = new StringBuffer();
   if (neg) sb.append('-');
   sb.append(intp);
   if (decimal > 0) {
     sb.append('.');
     for (int i = 0; i < decimal; i++) {
       rest *= 10;
       long digit = ((long) rest) % 10;
       sb.append(digit);
     }
   }
   return sb.toString();
 }
  public static void main(String[] args) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    // INPUT
    for (byte T = Byte.parseByte(br.readLine()); T > 0; --T) {
      String[] input = br.readLine().split(" ");
      int A = Integer.parseInt(input[0]);
      int B = Integer.parseInt(input[1]);

      // SOLVE
      int C = (int) (Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1);
      sb.append(C + "\n");
    }

    // OUTPUT
    System.out.print(sb);
  }
Example #25
0
 public String getDebugString() {
   StringBuilder buffer = new StringBuilder();
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   buffer
       .append("    ")
       .append(StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1))
       .append("\n");
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     row = row.replaceAll("\n", "\\\\n");
     row = row.replaceAll("\r", "\\\\r");
     buffer.append(index).append(" (").append(row).append(")\n");
     i++;
   }
   return buffer.toString();
 }
Example #26
0
  /**
   * Draws a single arrow head
   *
   * @param aG the canvas to draw on;
   * @param aXpos the X position of the arrow head;
   * @param aYpos the (center) Y position of the arrow head;
   * @param aFactor +1 to have a left-facing arrow head, -1 to have a right-facing arrow head;
   * @param aArrowWidth the total width of the arrow head;
   * @param aArrowHeight the total height of the arrow head.
   */
  public static final void drawArrowHead(
      final Graphics2D aG,
      final int aXpos,
      final int aYpos,
      final int aFactor,
      final int aArrowWidth,
      final int aArrowHeight) {
    final double halfHeight = aArrowHeight / 2.0;
    final int x1 = aXpos + (aFactor * aArrowWidth);
    final int y1 = (int) Math.ceil(aYpos - halfHeight);
    final int y2 = (int) Math.floor(aYpos + halfHeight);

    final Polygon arrowHead = new Polygon();
    arrowHead.addPoint(aXpos, aYpos);
    arrowHead.addPoint(x1, y1);
    arrowHead.addPoint(x1, y2);

    aG.fill(arrowHead);
  }
  private static long toInteger(Object value, Class<?> type, double min, double max) {
    double d = toDouble(value);

    if (Double.isInfinite(d) || Double.isNaN(d)) {
      // Convert to string first, for more readable message
      reportConversionError(ScriptRuntime.toString(value), type);
    }

    if (d > 0.0) {
      d = Math.floor(d);
    } else {
      d = Math.ceil(d);
    }

    if (d < min || d > max) {
      // Convert to string first, for more readable message
      reportConversionError(ScriptRuntime.toString(value), type);
    }
    return (long) d;
  }
 public void run() {
   // do it ...
   try {
     IndexWriter indexWriter =
         LuceneUtils.createIndexWriter(
             indexPath, overwriteIndex, LuceneUtils.AnalyzerType.WhitespaceAnalyzer);
     for (Iterator<File> iterator = inputFiles.iterator(); iterator.hasNext(); ) {
       File inputFile = iterator.next();
       if (verbose) System.out.println("Processing " + inputFile.getPath() + ".");
       if (verbose) System.out.println("Counting images.");
       run = 0;
       readFile(indexWriter, inputFile);
       if (verbose) System.out.printf("%d images found in the data file.\n", docCount);
       int numberOfRepresentatives = 1000; // TODO: clever selection.
       // select a number of representative "fixed stars" randomly from file
       if (numberOfRepresentatives > Math.sqrt(docCount))
         numberOfRepresentatives = (int) Math.sqrt(docCount);
       if (verbose)
         System.out.printf(
             "Selecting %d representative images for hashing.\n", numberOfRepresentatives);
       representativesID = new HashSet<Integer>(numberOfRepresentatives);
       while (representativesID.size() < numberOfRepresentatives) {
         representativesID.add((int) Math.floor(Math.random() * (docCount - 1)));
       }
       representatives = new ArrayList<LireFeature>(numberOfRepresentatives);
       docCount = 0;
       run = 1;
       if (verbose) System.out.println("Now getting representatives from the data file.");
       readFile(indexWriter, inputFile);
       docCount = 0;
       run = 2;
       if (verbose) System.out.println("Finally we start the indexing process, please wait ...");
       readFile(indexWriter, inputFile);
       if (verbose) System.out.println("Indexing finished.");
     }
     indexWriter.commit();
     indexWriter.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #29
0
  /**
   * Returns a set of numerators k_i so that the following constraints are met:
   *
   * <p>1. k_i / 2^d is within range of target[i] +/- this.precision 2. sum_i k_i = 2^d
   *
   * <p>If no such selection of k's is possible, then returns null.
   */
  private int[] getRatios(int depth, double[] target) {
    // construct upper and lower bounds (inclusive) for each k
    int lowerSum = 0;
    int upperSum = 0;
    int[] lower = new int[target.length];
    int[] upper = new int[target.length];
    double unit = 1.0 / Math.pow(2, depth);
    for (int i = 0; i < target.length; i++) {
      lower[i] = (int) Math.ceil(Math.max(0.0, (target[i] - precision)) / unit);
      upper[i] = (int) Math.floor(Math.min(1.0, (target[i] + precision)) / unit);
      lowerSum += lower[i];
      upperSum += upper[i];
      // if there is not a single satisfying point in range,
      // then fail
      if (lower[i] > upper[i]) {
        return null;
      }
    }

    // if we can never get to sum to 2^d, then fail
    int targetSum = (int) Math.pow(2, depth);
    if (lowerSum > targetSum || upperSum < targetSum) {
      return null;
    }

    // now the problem is to select a number from each range so
    // that the total sums to 2^d.  Do this in a simple greedy way
    // -- start with lower bounds, and increase each numerator by
    // one (towards their upper bounds) until finding a combo that
    // is in range.
    while (lowerSum < targetSum) {
      for (int i = 0; i < target.length; i++) {
        if (lowerSum < targetSum && lower[i] < upper[i]) {
          lower[i]++;
          lowerSum++;
        }
      }
    }

    return lower;
  }
Example #30
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String s = in.next();

    int l = s.length();
    Double sqrl = Math.sqrt(l);
    Double low = Math.floor(sqrl);
    Double high = Math.ceil(sqrl);
    int r = 0;
    int c = 0;

    if (low == high) {
      r = low.intValue();
      c = low.intValue();
    } else if (low * high >= l) {
      r = low.intValue();
      c = high.intValue();
    } else {
      r = high.intValue();
      c = high.intValue();
    }

    //        System.out.println("Row: " + r);
    //        System.out.println("Col: " + c);

    StringBuilder sb = new StringBuilder();
    char en[] = s.toCharArray();
    for (int i = 0; i < c; i++) {
      for (int j = 0; j < r; j++) {
        if (j * c + i < l) {
          sb.append(en[j * c + i]);
        }
      }
      sb.append(" ");
    }

    System.out.println(sb.toString());
  }