/**
   * this is the core if the h2_OwnPreferences is not the first for CMP to call
   *
   * @param candidatesKB
   */
  public HashMap<Integer, RuleEngine> core(HashMap<Integer, rule_engine.RuleEngine> candidatesKB) {

    ArrayList<Integer> preference_count = new ArrayList<>();
    ArrayList<Integer> candidateID = new ArrayList<>();
    ArrayList<Integer> toberemoved = new ArrayList<>();
    for (int i : candidatesKB.keySet()) {
      if (!preference_count.isEmpty()) {
        if (countActiveOwnPreferences(candidatesKB.get(i)) < Collections.min(preference_count)) {
          preference_count.removeAll(preference_count);
          candidateID.removeAll(candidateID);
          preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
          candidateID.add(i);
        } else if (countActiveOwnPreferences(candidatesKB.get(i))
            == Collections.min(preference_count)) {
          preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
          candidateID.add(i);
        }
      } else {
        preference_count.add(countActiveOwnPreferences(candidatesKB.get(i)));
        candidateID.add(i);
      }
    }
    for (int i : candidatesKB.keySet()) {
      if (!candidateID.contains(i)) {

        toberemoved.add(i);
      }
    }
    for (int i : toberemoved) {
      candidatesKB.remove(i);
    }
    return candidatesKB;
  }
  private void getDataToPlot() {
    switch (position) {
      case 0: // Humidity
        dataToPlot = humidityData;
        min = Collections.min(humidityData);
        max = Collections.max(humidityData);
        break;

      case 1: // Light
        dataToPlot = lightData;
        min = Collections.min(lightData);
        max = Collections.max(lightData);
        break;

      case 2: // Moisture
        dataToPlot = moistureData;
        min = Collections.min(moistureData);
        max = Collections.max(moistureData);
        break;

      case 3: // Temperature
        dataToPlot = temperatureData;
        min = Collections.min(temperatureData);
        max = Collections.max(temperatureData);
        break;
    }
  }
  private GASolution<int[]> algorithmRun() {
    GASolution<int[]> best = null;
    for (int iter = 0; iter < maxiter; iter++) {
      gBestChanged = false;

      population = makeChildren();

      best = Collections.min(population.getSols());
      if (globalBest == null || best.compareTo(globalBest) < 0) {
        globalBest = best;
        gBestChanged = true;
      }
      if (Math.abs(globalBest.fitness) < minFit) {
        return globalBest;
      }
      if (gBestChanged) {
        //				System.out.println((iter + 1) + ": " + best.fitness + " -> " + best.toString());
        System.out.println((iter + 1) + ": " + best.fitness);
      }
    }
    best = Collections.min(population.getSols());
    if (best.compareTo(globalBest) < 0) {
      globalBest = best;
    }
    return globalBest;
  }
  static void displayStats() {
    if (training_time_stats.size() > 0)
      // TODO format floating point
      System.out.println(
          "Iteration time: min="
              + Collections.min(training_time_stats)
              + ", max="
              + Collections.max(training_time_stats)
              + ", avg="
              + Utils.average(training_time_stats)
              + " seconds");

    if (eval_time_stats.size() > 0)
      System.out.println(
          "Evaluation time: min="
              + Collections.min(eval_time_stats)
              + ", max="
              + Collections.max(eval_time_stats)
              + ", avg="
              + Utils.average(eval_time_stats)
              + " seconds");

    if (compute_fit && fit_time_stats.size() > 0)
      System.out.println(
          "fit_time: min="
              + Collections.min(fit_time_stats)
              + ", max="
              + Collections.max(fit_time_stats)
              + ", avg="
              + Utils.average(fit_time_stats)
              + " seconds");

    System.out.println("Memory: " + Memory.getUsage() + " MB");
  }
  // NEED TO FIX LOGIC FROM LEFT
  private String getIncidenceDirection(Article a, Article b) {

    double pL = a.getX(); // left
    double pR = pL + a.getWidth(); // right
    double pT = a.getY(); // bottom
    double pB = pT + a.getHeight();
    double tL = b.getX(); // left
    double tR = tL + b.getWidth();
    double tT = b.getY();
    double tB = tT + b.getHeight();
    String[] directions = {"Left", "Right", "Bottom", "Top"};
    Double inf = Double.MAX_VALUE;
    List<Double> intersect_diffs = new ArrayList<Double>(Arrays.asList(inf, inf, inf, inf));
    if (pR > tL && pL < tL)
      // Player on left
      intersect_diffs.remove(0);
    intersect_diffs.add(0, Math.abs(pR - tL));
    if (pL < tR && pR > tR) // Player on Right
    intersect_diffs.remove(1);
    intersect_diffs.add(1, Math.abs(tR - pL));
    if (pT > tB && pB < tB) // Player on Bottom
    intersect_diffs.remove(2);
    intersect_diffs.add(2, Math.abs(pT - tB));
    if (pB < tT && pT > tT) // Player on Top
    intersect_diffs.remove(3);
    intersect_diffs.add(3, Math.abs(tT - pB));
    Collections.min(intersect_diffs);
    // return the closest intersection
    return directions[intersect_diffs.indexOf(Collections.min(intersect_diffs))];
  }
Beispiel #6
0
  public static void evaluateCircuitSNR(LogicCircuit lc, Args options) {

    /*for(Gate g: lc.get_logic_gates()) {
        evaluateGateSNR(g, options);
    }
    for(Gate g: lc.get_output_gates()) {
        evaluateGateSNR(g, options);
    }*/

    ArrayList<Double> input_ons = new ArrayList<>();
    ArrayList<Double> input_offs = new ArrayList<>();

    for (Gate input : lc.get_input_gates()) {
      for (int i = 0; i < input.get_logics().size(); ++i) {
        if (input.get_logics().get(i) == 1) {
          input_ons.add(input.get_outreus().get(i));
        } else if (input.get_logics().get(i) == 0) {
          input_offs.add(input.get_outreus().get(i));
        }
      }
    }

    Double input_on_min = Collections.min(input_ons);
    Double input_off_max = Collections.max(input_offs);

    ArrayList<Double> output_ons = new ArrayList<>();
    ArrayList<Double> output_offs = new ArrayList<>();

    for (Gate output : lc.get_output_gates()) {
      for (int i = 0; i < output.get_logics().size(); ++i) {
        if (output.get_logics().get(i) == 1) {
          output_ons.add(output.get_outreus().get(i));
        } else if (output.get_logics().get(i) == 0) {
          output_offs.add(output.get_outreus().get(i));
        }
      }
    }

    Double output_on_min = Collections.min(output_ons);
    Double output_off_max = Collections.max(output_offs);

    Double out_snr =
        20 * Math.log10((Math.log10(output_on_min / output_off_max)) / (2 * Math.log10(3.2)));

    Double in_snr =
        20 * Math.log10((Math.log10(input_on_min / input_off_max)) / (2 * Math.log10(3.2)));

    Double dsnr = out_snr - in_snr;

    lc.get_scores().set_snr(out_snr);
    lc.get_scores().set_dsnr(dsnr);
  }
  @Test
  public void shouldHaveDifferentNotificationIDs() {
    for (int i = 0; i < 10; i++) {
      this.question.answer(this.andrew, "Answer " + i);
    }
    assertEquals(this.norbert.getNotifications().size(), 10);

    Notification first = Collections.max(this.norbert.getNotifications());
    assertEquals(this.norbert.getNotification(first.id()), first);
    // What is this about and why is it tested here? and #get(9) should
    // equal first?
    assertEquals(this.norbert.getNotifications().get(9), first);

    for (int i = 0; i < 9; i++) {
      assertTrue(
          this.norbert.getNotifications().get(i).id()
              > this.norbert.getNotifications().get(i + 1).id());
    }

    Notification last = Collections.min(this.norbert.getNotifications());
    assertEquals(this.norbert.getNotifications().get(0), last);
    assertEquals(this.norbert.getVeryRecentNewNotification(), last);

    last.unsetNew();
    assertEquals(
        this.norbert.getVeryRecentNewNotification(), this.norbert.getNotifications().get(1));

    assertNull(this.norbert.getNotification(-1));
  }
  /**
   * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
   * width and height are at least as large as the respective requested values, and whose aspect
   * ratio matches with the specified value.
   *
   * @param choices The list of sizes that the camera supports for the intended output class
   * @param width The minimum desired width
   * @param height The minimum desired height
   * @param aspectRatio The aspect ratio
   * @return The optimal {@code Size}, or an arbitrary one if none were big enough
   */
  private static Size chooseOptimalSize(
      final Size[] choices, final int width, final int height, final Size aspectRatio) {
    // Collect the supported resolutions that are at least as big as the preview Surface
    final List<Size> bigEnough = new ArrayList<Size>();

    final int minWidth = Math.max(width, MINIMUM_PREVIEW_SIZE);
    final int minHeight = Math.max(height, MINIMUM_PREVIEW_SIZE);

    for (final Size option : choices) {
      if (option.getHeight() >= minHeight && option.getWidth() >= minWidth) {
        LOGGER.i("Adding size: " + option.getWidth() + "x" + option.getHeight());
        bigEnough.add(option);
      } else {
        LOGGER.i("Not adding size: " + option.getWidth() + "x" + option.getHeight());
      }
    }

    // Pick the smallest of those, assuming we found any
    if (bigEnough.size() > 0) {
      final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea());
      LOGGER.i("Chosen size: " + chosenSize.getWidth() + "x" + chosenSize.getHeight());
      return chosenSize;
    } else {
      LOGGER.e("Couldn't find any suitable preview size");
      return choices[0];
    }
  }
Beispiel #9
0
  public static void main(String args[]) {
    String os[] = {"GNU/Linux", "Windows 7", "Solaris", "Amiga OS", "FreeBSD", "Mac OS X"};

    LinkedList<String> al_operating_systems =
        new LinkedList<>(Arrays.asList(os)); // Lista di os
    Collections.sort(al_operating_systems); // ordina la collezione
    System.out.print("Collezione ordinata: ");
    System.out.println(al_operating_systems);

    int ix =
        Collections.binarySearch(
            al_operating_systems, "Be OS", null); // ricerca se presente l'elemento Be Os
    if (ix < 0) // se non è presente aggiungilo
    al_operating_systems.add(-(ix + 1), "Be OS");

    System.out.print("Collezione con elemento Be OS aggiunto: ");
    System.out.println(al_operating_systems);

    Collections.rotate(al_operating_systems, 3); // ruota gli elementi di 3 posizioni
    System.out.print("Collezione con elementi ruotati: ");
    System.out.println(al_operating_systems);

    System.out.print("Elemento della collezione minore: ["); // elemento più piccolo
    System.out.println(Collections.min(al_operating_systems) + "]");

    System.out.print("Elemento della collezione maggiore: ["); // elemento più grande
    System.out.println(Collections.max(al_operating_systems) + "]");
  }
  private String getClosestWord(final String word) throws IOException {
    InputStream is = null;
    is = getAssets().open("bip39-wordlist.txt");
    final List<String> words = new ArrayList<>();

    String line;

    try {
      final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
      while ((line = reader.readLine()) != null) {
        words.add(line);
      }
    } finally {
      is.close();
    }

    final List<Integer> scores = new ArrayList<>();
    for (final String w : words) {
      scores.add(new Integer(Integer.MAX_VALUE));
    }

    for (int i = 0; i < words.size(); ++i) {
      scores.set(i, levenshteinDistance(word, words.get(i)));
    }

    return words.get(scores.indexOf(Collections.min(scores)));
  }
  private void initializeTimeClasses() {
    int endOfTimeClass = 0;
    int classCounter = 0;
    double minTime = Collections.min(allDurDiffs);
    double maxTime = Collections.max(allDurDiffs);

    timeClasses.add(endOfTimeClass);

    while (endOfTimeClass <= maxTime) {
      endOfTimeClass = 100 * (int) Math.pow(2, classCounter);
      classCounter++;
      timeClasses.add(endOfTimeClass);
    }

    endOfTimeClass = 0;
    classCounter = 0;
    while (endOfTimeClass <= -minTime) {
      endOfTimeClass = 100 * (int) Math.pow(2, classCounter);
      classCounter++;
      timeClasses.add(-endOfTimeClass);
    }
    Collections.sort(timeClasses);
    ActivityType2DurationHandler.LOG.info(
        "Following activity duration classes are defined: " + timeClasses.toString());
  }
Beispiel #12
0
 /**
  * Logs the time and the number of needed queries for a specific QSS type
  *
  * @param queries
  * @param times
  * @param type
  * @param statisticName
  */
 private void logStatistics(
     Map<QSSType, List<Double>> queries,
     Map<QSSType, DurationStat> times,
     QSSType type,
     String statisticName) {
   List<Double> queriesOfType = queries.get(type);
   double res = 0;
   for (Double qs : queriesOfType) {
     res += qs;
   }
   logger.info(
       statisticName
           + " needed time "
           + type
           + ": "
           + getStringTime(times.get(type).getOverall())
           + ", max "
           + getStringTime(times.get(type).getMax())
           + ", min "
           + getStringTime(times.get(type).getMin())
           + ", avg2 "
           + getStringTime(times.get(type).getMean())
           + ", Queries max "
           + Collections.max(queries.get(type))
           + ", min "
           + Collections.min(queries.get(type))
           + ", avg2 "
           + res / queriesOfType.size());
 }
  /**
   * Returns the lowest score below 0 if available; otherwise the highest score above 0.
   *
   * @param approvals the approvals found on the Gerrit review
   * @return the approval that is deemed the "most significant"
   * @deprecated This functionality can now be found in the velocity template
   */
  @Deprecated
  GerritApproval getMostSignificantScore(final List<GerritApproval> approvals) {
    if (approvals != null) {
      try {
        GerritApproval min = Collections.min(approvals);
        GerritApproval max = Collections.max(approvals);

        if (min == max) {
          // Means there was only 1 vote, so show that one.
          return max;
        }

        if (min.getValueAsInt() < 0) {
          // There exists a negative vote, so show that one.
          return min;
        } else {
          // NOTE: Technically not possible to have a 0-score, but if one exists, use it!
          // No negative votes, so show the highest positive vote
          return max;
        }
      } catch (NoSuchElementException nsee) {
        // Collection was empty
      }
    }

    return null;
  }
Beispiel #14
0
  /**
   * Returns mean, min, max, and variance of a collection of floats. This method takes a drop
   * parameter that drops the first <i>N</i> floats before computing the summary statistics.
   *
   * @param list collection of floats
   * @param drop exclude the first <code>drop</code> floats from the results
   * @return an array of {mean, min, max, variance, number of dropped floats}
   */
  protected final float[] summarizeFloats(Collection<Float> list, int drop) {
    if (list.isEmpty()) {
      return null;
    }

    if (list.size() <= 1 + drop) {
      drop = 0;
    }

    List<Float> retain = new ArrayList<Float>(list).subList(drop, list.size());
    final float mean = CollectionMath.sumFloat(retain) / (float) retain.size();
    float min = Collections.min(retain);
    float max = Collections.max(retain);

    float var =
        CollectionMath.sumFloat(
                FnIterable.from(retain)
                    .map(
                        new Lambda<Float, Float>() {
                          @Override
                          public Float call(Float x) {
                            return (x - mean) * (x - mean);
                          }
                        }))
            / (retain.size() - 1);

    float[] retval = new float[5];
    retval[0] = mean;
    retval[1] = min;
    retval[2] = max;
    retval[3] = var;
    retval[4] = retain.size();

    return retval;
  }
Beispiel #15
0
  /**
   * Returns mean, min, max, and variance of a collection of integers. This method takes a drop
   * parameter that drops the first <i>N</i> integers before computing the summary statistics.
   *
   * @param list collection of integers
   * @param drop exclude the first <code>drop</code> integers from the results
   * @return an array of {mean, min, max, variance, number of dropped integers}
   */
  protected final float[] summarizeInts(Collection<Integer> list, int drop) {
    if (list.isEmpty()) {
      return null;
    }

    if (list.size() <= 1 + drop) {
      drop = 0;
    }

    List<Integer> retain = new ArrayList<Integer>(list).subList(drop, list.size());
    final float mean = CollectionMath.sumInteger(retain) / (float) retain.size();
    int min = Collections.min(retain);
    int max = Collections.max(retain);

    float var =
        CollectionMath.sumFloat(
                FnIterable.from(retain)
                    .map(
                        new Lambda<Integer, Float>() {
                          @Override
                          public Float call(Integer x) {
                            return (x - mean) * (x - mean);
                          }
                        }))
            / (retain.size() - 1);

    float[] retval = new float[] {mean, min, max, var, retain.size()};

    return retval;
  }
 public Integer work(List<Integer> scores, TurnTrackerMinion mule) {
   if (mule.getCurrentMarker().equals(mule.getInitializerMarker())) {
     return Collections.max(scores);
   } else {
     return Collections.min(scores);
   }
 }
Beispiel #17
0
  public double calculaGasolina(Cromossoma temp, ArrayList<Vertex> listabombas) {
    AStar as = new AStar(nodes);
    double result = 0;
    for (int i = 0; i < temp.size() - 2; i += 2) {
      int begin = temp.get(i).convertToInt();
      int end = temp.get(i + 2).convertToInt();
      if (temp.get(i + 1).isBomba()) {
        ArrayList<Double> escolhas = new ArrayList<Double>();
        for (int j = 0; j < listabombas.size(); j++) {
          double d;
          LinkedList<Integer> x = as.calculateFitness(begin, listabombas.get(j).getId());
          d = calcularDistancia(x);

          x = as.calculateFitness(listabombas.get(j).getId(), end);
          d += calcularDistancia(x);
          escolhas.add(d);
        }
        result += Collections.min(escolhas);
        result -= adicionarCombustivel;
      } else {
        LinkedList<Integer> x = as.calculateFitness(begin, end);
        result += calcularDistancia(x);
      }
    }
    return result;
  }
  protected void createSortableTextField(String name, String[] values) {
    if (values.length == 0) {
      return;
    }

    createSortableTextField(name, Collections.min(Arrays.asList(values)));
  }
  public TableLevelWatermarker(State state) {
    this.tableWatermarks = Maps.newHashMap();

    // Load previous watermarks in case of sourceState
    if (state instanceof SourceState) {
      SourceState sourceState = (SourceState) state;
      for (Map.Entry<String, Iterable<WorkUnitState>> datasetWorkUnitStates :
          sourceState.getPreviousWorkUnitStatesByDatasetUrns().entrySet()) {

        // Use the minimum of all previous watermarks for this dataset
        List<LongWatermark> previousWatermarks =
            FluentIterable.from(datasetWorkUnitStates.getValue())
                .filter(Predicates.not(PartitionLevelWatermarker.WATERMARK_WORKUNIT_PREDICATE))
                .transform(
                    new Function<WorkUnitState, LongWatermark>() {
                      @Override
                      public LongWatermark apply(WorkUnitState w) {
                        return w.getActualHighWatermark(LongWatermark.class);
                      }
                    })
                .toList();

        if (!previousWatermarks.isEmpty()) {
          this.tableWatermarks.put(
              datasetWorkUnitStates.getKey(), Collections.min(previousWatermarks));
        }
      }
      log.info("Loaded table watermarks from previous state " + this.tableWatermarks);
    }
  }
Beispiel #20
0
  private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(filename);
    Iterator<String> itr = scoremap.keySet().iterator();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<Float> scores = new ArrayList<Float>();

    while (itr.hasNext()) {
      String key = itr.next();
      if (scores.size() < num) {
        scores.add(scoremap.get(key));
        urls.add(key);
      } else {
        int index = scores.indexOf(Collections.min(scores));
        if (scores.get(index) < scoremap.get(key)) {
          scores.set(index, scoremap.get(key));
          urls.set(index, key);
        }
      }
    }

    while (scores.size() > 0) {
      int index = scores.indexOf(Collections.max(scores));
      out.println(urls.get(index) + "\t" + scores.get(index));
      urls.remove(index);
      scores.remove(index);
    }
    out.close();
  }
Beispiel #21
0
 public static void main(String[] args) {
   ArrayList nums = new ArrayList();
   nums.add(2);
   nums.add(-5);
   nums.add(3);
   nums.add(0);
   // 输出:[2, -5, 3, 0]
   System.out.println(nums);
   // 输出最大元素,将输出3
   System.out.println(Collections.max(nums));
   // 输出最小元素,将输出-5
   System.out.println(Collections.min(nums));
   // 将nums中的0使用1来代替
   Collections.replaceAll(nums, 0, 1);
   // 输出:[2, -5, 3, 1]
   System.out.println(nums);
   // 判断-5 在List集合中出现的次数,返回1
   System.out.println(Collections.frequency(nums, -5));
   // 对nums集合排序
   Collections.sort(nums);
   // 输出:[-5, 1, 2, 3]
   System.out.println(nums);
   // 只有排序后的List集合才可用二分法查询,输出3
   System.out.println(Collections.binarySearch(nums, 3));
 }
 private static File findFileForFont(Font font, final boolean matchStyle) {
   final String normalizedFamilyName =
       font.getFamily().toLowerCase(Locale.getDefault()).replace(" ", "");
   final int fontStyle = font.getStyle();
   File[] files =
       new File(System.getProperty("user.home"), "Library/Fonts")
           .listFiles(
               new FilenameFilter() {
                 @Override
                 public boolean accept(File file, String name) {
                   String normalizedName = name.toLowerCase(Locale.getDefault());
                   return normalizedName.startsWith(normalizedFamilyName)
                       && (normalizedName.endsWith(".otf") || normalizedName.endsWith(".ttf"))
                       && (!matchStyle
                           || fontStyle == ComplementaryFontsRegistry.getFontStyle(name));
                 }
               });
   if (files == null || files.length == 0) return null;
   // to make sure results are predictable we return first file in alphabetical order
   return Collections.min(
       Arrays.asList(files),
       new Comparator<File>() {
         @Override
         public int compare(File file1, File file2) {
           return file1.getName().compareTo(file2.getName());
         }
       });
 }
Beispiel #23
0
 static boolean isNumberMinimal(final List<String> names, Integer number) {
   List<Integer> numbers = new ArrayList<Integer>();
   for (final String name : names) {
     numbers.add(extractNodeNumber(name));
   }
   return Collections.min(numbers) == number;
 }
Beispiel #24
0
  public static void evaluateGateSNR(Gate g, Args options) {

    if (g.Type == GateType.INPUT) {
      return;
    }

    ArrayList<Double> ons = new ArrayList<>();
    ArrayList<Double> offs = new ArrayList<>();

    // get ons and offs
    for (int i = 0; i < g.get_logics().size(); ++i) {
      if (g.get_logics().get(i) == 1) {
        ons.add(g.get_outreus().get(i));
      } else if (g.get_logics().get(i) == 0) {
        offs.add(g.get_outreus().get(i));
      }
    }

    ArrayList<Double> child_ons = new ArrayList<>();
    ArrayList<Double> child_offs = new ArrayList<>();

    for (Gate child : g.getChildren()) {
      for (int i = 0; i < child.get_logics().size(); ++i) {
        if (child.get_logics().get(i) == 1) {
          child_ons.add(child.get_outreus().get(i));
        } else if (child.get_logics().get(i) == 0) {
          child_offs.add(child.get_outreus().get(i));
        }
      }
    }

    Double on_min = Collections.min(ons);
    Double off_max = Collections.max(offs);

    Double child_on_min = Collections.min(child_ons);
    Double child_off_max = Collections.max(child_offs);

    Double out_snr = 20 * Math.log10((Math.log10(on_min / off_max)) / (2 * Math.log10(3.2)));

    Double in_snr =
        20 * Math.log10((Math.log10(child_on_min / child_off_max)) / (2 * Math.log10(3.2)));

    Double dsnr = out_snr - in_snr;

    g.get_scores().set_snr(out_snr);
    g.get_scores().set_dsnr(dsnr);
  }
  private static void printBounds(Point[] points) {

    List<Integer> xCoordinates = getXCoordinates(points);
    List<Integer> yCoordinates = getYCoordinates(points);
    System.out.println(
        "Lower bounds are ("
            + Collections.min(xCoordinates)
            + ","
            + Collections.min(yCoordinates)
            + ")");
    System.out.println(
        "Upper bounds are ("
            + Collections.max(xCoordinates)
            + ","
            + Collections.max(yCoordinates)
            + ")");
  }
Beispiel #26
0
 public int minDepth(TreeNode root) {
   List<Integer> level = new ArrayList<>();
   if (root == null) level.add(0);
   traversal_min(level, root, 1);
   int min = Collections.min(level);
   System.out.println(min);
   return min;
 }
Beispiel #27
0
 /** testMinMax */
 public void testMinMax() {
   int min = 6;
   int max = 19;
   for (int i = min; i <= max; i++) {
     pset.add(i);
   }
   assertEquals(min, Collections.min(pset).intValue());
   assertEquals(max, Collections.max(pset).intValue());
 }
Beispiel #28
0
  @Managed
  public double getMin() {
    List<Long> values = sample.values();
    if (!values.isEmpty()) {
      return Collections.min(values);
    }

    return Double.NaN;
  }
  public void writeResults(String outputFile) {

    try {
      // Create file
      FileWriter fStream = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fStream);

      out.write(
          "Attribute Type"
              + SEPARATOR
              + "numberOfDiffValues"
              + SEPARATOR
              + "min"
              + SEPARATOR
              + "max"
              + SEPARATOR
              + "Example\n");
      for (Map.Entry<String, Set<String>> entry : attrByValue.entrySet()) {
        Set<String> attrValues = entry.getValue();
        String lineToWrite = entry.getKey();

        Collections.max(attrValues);

        String sampleValues = "";
        int maxNumberOfSampleValues = 0;

        for (String s : attrValues) {
          sampleValues = sampleValues + " " + s;
          if (maxNumberOfSampleValues > MAX_EXAMPLE_COUNT) break;
          maxNumberOfSampleValues++;
        }

        String max = Collections.max(attrValues);
        String min = Collections.min(attrValues);

        lineToWrite =
            lineToWrite
                + SEPARATOR
                + attrValues.size()
                + SEPARATOR
                + max
                + SEPARATOR
                + min
                + SEPARATOR
                + sampleValues.trim();

        out.write(lineToWrite + "\n");
      }

      out.flush();
      // Close the output stream
      out.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
Beispiel #30
0
  /** Test inserts using KeyRange query */
  @Test
  public void testKeyRangeWrites() throws Exception {
    Random random = new Random();
    VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
    vtgate.begin();
    String sql =
        "insert into vtgate_test "
            + "(id, name, keyspace_id, age) "
            + "values (:id, :name, :keyspace_id, :age)";
    int count = 20;
    // Insert 20 rows per shard
    for (String shardName : testEnv.shardKidMap.keySet()) {
      List<KeyspaceId> kids = testEnv.getKeyspaceIds(shardName);
      KeyspaceId minKid = Collections.min(kids);
      KeyspaceId maxKid = Collections.max(kids);
      KeyRange kr = new KeyRange(minKid, maxKid);
      for (int i = 0; i < count; i++) {
        KeyspaceId kid = kids.get(i % kids.size());
        Query query =
            new QueryBuilder(sql, testEnv.keyspace, "master")
                .addBindVar(
                    BindVariable.forULong(
                        "id", UnsignedLong.valueOf("" + Math.abs(random.nextInt()))))
                .addBindVar(BindVariable.forString("name", ("name_" + i)))
                .addBindVar(BindVariable.forULong("keyspace_id", (UnsignedLong) kid.getId()))
                .addBindVar(BindVariable.forNull("age"))
                .addKeyRange(kr)
                .build();
        vtgate.execute(query);
      }
    }
    vtgate.commit();
    vtgate.close();

    // Check 40 rows exist in total
    vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
    String selectSql = "select * from vtgate_test";
    Query allRowsQuery =
        new QueryBuilder(selectSql, testEnv.keyspace, "master")
            .setKeyspaceIds(testEnv.getAllKeyspaceIds())
            .build();
    Cursor cursor = vtgate.execute(allRowsQuery);
    Assert.assertEquals(count * 2, cursor.getRowsAffected());

    // Check 20 rows exist per shard
    for (String shardName : testEnv.shardKidMap.keySet()) {
      Query shardRows =
          new QueryBuilder(selectSql, testEnv.keyspace, "master")
              .setKeyspaceIds(testEnv.getKeyspaceIds(shardName))
              .build();
      cursor = vtgate.execute(shardRows);
      Assert.assertEquals(count, cursor.getRowsAffected());
    }

    vtgate.close();
  }