Exemple #1
1
  /** Compile a file. If you want a dump then give -out somefile. */
  public static int compilerPhases(List<String> args, Option<String> out, String phase)
      throws UserError, InterruptedException, IOException, RepositoryError {
    int return_code = 0;
    if (args.size() == 0) {
      throw new UserError("The " + phase + " command must be given a file.");
    }
    String s = args.get(0);
    List<String> rest = args.subList(1, args.size());

    if (s.startsWith("-")) {
      if (s.equals("-debug")) {
        rest = Debug.parseOptions(rest);
      } else if (s.equals("-out") && !rest.isEmpty()) {
        out = Option.<String>some(rest.get(0));
        rest = rest.subList(1, rest.size());
      } else if (s.equals("-compiler-lib")) {
        WellKnownNames.useCompilerLibraries();
        Types.useCompilerLibraries();
      } else if (s.equals("-typecheck-java")) {
        setScala(false);
      } else if (s.equals("-coercion")) {
        setTestCoercion(true);
      } else invalidFlag(s, phase);
      return_code = compilerPhases(rest, out, phase);
    } else {
      return_code = compileWithErrorHandling(s, out, false);
    }
    return return_code;
  }
  /**
   * Private helper method for performing fast intersection.
   *
   * @param <E>
   * @param sortedData
   * @param sortedQueries
   * @param result
   */
  private static <E extends Comparable<E>> void fastIntersect(
      List<E> sortedData, List<E> sortedQueries, SortedSet<E> result) {

    int medianQueryIndex = sortedQueries.size() / 2;
    E medianQuery = sortedQueries.get(medianQueryIndex);

    int index = Collections.binarySearch(sortedData, medianQuery);

    if (index >= 0) {
      result.add(medianQuery);
    } else {
      index = (-1 * index) + 1;
    }

    if (index - 1 >= 0 && medianQueryIndex - 1 >= 0) {
      fastIntersect(
          sortedData.subList(0, index), sortedQueries.subList(0, medianQueryIndex), result);
    }

    if (index + 1 < sortedData.size() && medianQueryIndex + 1 < sortedQueries.size()) {
      fastIntersect(
          sortedData.subList(index + 1, sortedData.size()),
          sortedQueries.subList(medianQueryIndex + 1, sortedQueries.size()),
          result);
    }
  }
Exemple #3
1
  /** UnParse a file. If you want a dump then give -out somefile. */
  private static void unparse(
      List<String> args, Option<String> out, boolean _unqualified, boolean _unmangle)
      throws UserError, InterruptedException, IOException {
    if (args.size() == 0) {
      throw new UserError("The unparse command needs a file to unparse.");
    }
    String s = args.get(0);
    List<String> rest = args.subList(1, args.size());
    boolean unqualified = _unqualified;
    boolean unmangle = _unmangle;

    if (s.startsWith("-")) {
      if (s.equals("-unqualified")) {
        unqualified = true;
      } else if (s.equals("-unmangle")) {
        unmangle = true;
      } else if (s.equals("-debug")) {
        rest = Debug.parseOptions(rest);
      } else if (s.equals("-out") && !rest.isEmpty()) {
        out = Option.<String>some(rest.get(0));
        rest = rest.subList(1, rest.size());
      } else invalidFlag(s, "unparse");

      unparse(rest, out, unqualified, unmangle);
    } else {
      unparse(s, out, unqualified, unmangle);
    }
  }
  public double scoreSentence(List<String> sentence) {
    double p = 0;
    int M = this.baseModel.getLmOrder();
    List<String> normalizedSentence = new ArrayList<String>();

    final List<String> sentenceWithBounds =
        new BoundedList<String>(
            sentence,
            baseModel.getWordIndexer().getStartSymbol(),
            baseModel.getWordIndexer().getEndSymbol());
    final int lmOrder = baseModel.getLmOrder() + 1;
    float sentenceScore = 0.0f;
    float previousScore = 0.0f;

    // beginnetje

    for (int i = 1; i < lmOrder - 1 && i <= sentenceWithBounds.size() + 1; ++i) {
      final List<String> ngram = sentenceWithBounds.subList(-1, i);
      final float scoreNgram = (float) getLogProb(ngram, previousScore);
      sentenceScore += scoreNgram;
      previousScore = scoreNgram;
    }

    // rest

    for (int i = lmOrder - 1; i < sentenceWithBounds.size() + 2; ++i) {
      final List<String> ngram = sentenceWithBounds.subList(i - lmOrder, i);
      final float scoreNgram = (float) getLogProb(ngram, previousScore);
      sentenceScore += scoreNgram;
      previousScore = scoreNgram;
    }

    return sentenceScore;
  }
  public void sort(List<Integer> array) {
    sum += array.size() - 1;
    if (array.size() == 1) return;

    // @BeforeRecursion
    Integer p = PIVOT_.choose(array);
    Collections.swap(array, 0, p);
    Integer i = PARTIONER_.partition(array, 0);

    // Если левая часть не пуста
    if (i != 0) {
      // Проверить инвариант
      /*Integer minLeft = Collections.max(array.subList(0, i));
      if (!(minLeft < array.get(i)))
        throw new RuntimeException("Left postcondition failed"); */
      sort(array.subList(0, i));
    }

    // Если правая не пуста
    if (i != array.size() - 1) {
      /*Integer minRight = Collections.min(array.subList(i+1, array.size()));

      if (!(minRight > array.get(i)))
        throw new RuntimeException("Right postcondition failed."); */
      sort(array.subList(i + 1, array.size()));
    }
  }
  public void testDroppingStatesAtCapacity() {
    List<ClusterState> states =
        randomStates(scaledRandomIntBetween(10, 300), "master1", "master2", "master3", "master4");
    Collections.shuffle(states, random());
    // insert half of the states
    final int numberOfStateToDrop = states.size() / 2;
    List<ClusterState> stateToDrop = states.subList(0, numberOfStateToDrop);
    final int queueSize = states.size() - numberOfStateToDrop;
    PendingClusterStatesQueue queue = createQueueWithStates(stateToDrop, queueSize);
    List<ClusterStateContext> committedContexts = randomCommitStates(queue);
    for (ClusterState state : states.subList(numberOfStateToDrop, states.size())) {
      queue.addPending(state);
    }

    assertThat(queue.pendingClusterStates().length, equalTo(queueSize));
    // check all committed states got a failure due to the drop
    for (ClusterStateContext context : committedContexts) {
      assertThat(((MockListener) context.listener).failure, notNullValue());
    }

    // all states that should have dropped are indeed dropped.
    for (ClusterState state : stateToDrop) {
      assertThat(queue.findState(state.stateUUID()), nullValue());
    }
  }
  public String resolveAsRelativePath(Object path) {
    List<String> basePath =
        Arrays.asList(StringUtils.split(baseDir.getAbsolutePath(), "/" + File.separator));
    File targetFile = resolve(path);
    List<String> targetPath =
        new ArrayList<String>(
            Arrays.asList(StringUtils.split(targetFile.getAbsolutePath(), "/" + File.separator)));

    // Find and remove common prefix
    int maxDepth = Math.min(basePath.size(), targetPath.size());
    int prefixLen = 0;
    while (prefixLen < maxDepth && basePath.get(prefixLen).equals(targetPath.get(prefixLen))) {
      prefixLen++;
    }
    basePath = basePath.subList(prefixLen, basePath.size());
    targetPath = targetPath.subList(prefixLen, targetPath.size());

    for (int i = 0; i < basePath.size(); i++) {
      targetPath.add(0, "..");
    }
    if (targetPath.isEmpty()) {
      return ".";
    }
    return CollectionUtils.join(File.separator, targetPath);
  }
  @Override
  public ContentValues[] next() {
    ContentValues[] values = null;
    if (hasNext()) {
      if (mUnprocessedPersistables.size() == 0) {
        identifyPersistablesForNextClass();
      }

      List<Persistable> next;
      if (mUnprocessedPersistables.size() > ITERATION_LIMIT) {
        next = mUnprocessedPersistables.subList(0, ITERATION_LIMIT);
        mUnprocessedPersistables =
            mUnprocessedPersistables.subList(ITERATION_LIMIT, mUnprocessedPersistables.size());
      } else {
        next = new ArrayList<>(mUnprocessedPersistables);
        mUnprocessedPersistables = new ArrayList<>();
      }

      values = new ContentValues[next.size()];
      for (int i = 0; i < next.size(); i++) {
        values[i] = next.get(i).getContentValues();
      }
    }

    return values;
  }
Exemple #9
0
 @Action(
     value = CENTER,
     results = {@Result(name = SUCCESS, location = BaseAction.FOREPART + CENTER + JSP)})
 public String center() {
   /** ************************ TT ****************************************** */
   List<User> focusUserList =
       userService.getFocusList(User.class, (User) getSessionMap().get("user"));
   if (focusUserList.size() > 9) {
     focusUserList = focusUserList.subList(0, 9);
   }
   getRequestMap().put("focusUserList", focusUserList);
   List<Club> focusClubList =
       userService.getFocusList(Club.class, (User) getSessionMap().get("user"));
   if (focusClubList.size() > 9) {
     focusClubList = focusClubList.subList(0, 9);
   }
   getRequestMap().put("focusClubList", focusClubList);
   List<Merchant> focusMerchantList =
       userService.getFocusList(Merchant.class, (User) getSessionMap().get("user"));
   if (focusMerchantList.size() > 9) {
     focusMerchantList = focusMerchantList.subList(0, 9);
   }
   getRequestMap().put("focusMerchantList", focusMerchantList);
   super.getRequestMap().put("allUsers", userService.allUsers());
   user = (User) getSessionMap().get("user");
   /** ************************ 相册 ****************************************** */
   page = pictureService.getRelativeByHql(eachPageNumber, currentPage, totalPageNumber);
   pics = pictureService.findRelativePictureByHql(page);
   /** *********************** 相关说说 ****************************************** */
   page = talkingService.getRelativePageByHql(user, eachPageNumber, currentPage, 1);
   taks = talkingService.findRelativeTalkingByHql(page, user);
   return SUCCESS;
 }
  public void testGetSigningBlessingNames() throws VException {
    VContext context = V.init();
    VPrincipal p = VSecurity.newPrincipal();
    ECPublicKey pk = p.publicKey();
    List<Caveat> passingCaveats =
        ImmutableList.of(
            VSecurity.newExpiryCaveat(DateTime.now().plusDays(1)),
            VSecurity.newExpiryCaveat(DateTime.now().plusYears(1)));
    List<Caveat> failingCaveats =
        ImmutableList.of(
            VSecurity.newMethodCaveat("MethodName"), VSecurity.newExpiryCaveat(DateTime.now()));

    Blessings b1 = p.blessSelf("alice");
    Blessings b2 = p.blessSelf("alice");
    Blessings passing =
        p.bless(
            pk,
            b1,
            "passing",
            passingCaveats.get(0),
            passingCaveats.subList(1, passingCaveats.size()).toArray(new Caveat[0]));
    Blessings failing =
        p.bless(
            pk,
            b2,
            "failing",
            failingCaveats.get(0),
            failingCaveats.subList(1, failingCaveats.size()).toArray(new Caveat[0]));
    Blessings union = VSecurity.unionOfBlessings(new Blessings[] {passing, failing});
    VSecurity.addToRoots(p, passing);

    String[] signingBlessingNames = VSecurity.getSigningBlessingNames(context, p, union);
    assertThat(Arrays.asList(signingBlessingNames)).containsExactly("alice:passing");
  }
  /** {@inheritDoc} */
  protected PagingResult<Site> computeFavoriteSites(ListingContext listingContext) {
    List<Site> result = getFavoriteSites();

    if (listingContext != null) {
      Collections.sort(
          result,
          new AlphaComparator(listingContext.isSortAscending(), listingContext.getSortProperty()));
    }

    Boolean hasMoreItems = false;
    if (listingContext != null) {
      int fromIndex =
          (listingContext.getSkipCount() > result.size())
              ? result.size()
              : listingContext.getSkipCount();

      // Case if skipCount > result size
      if (listingContext.getSkipCount() < result.size()) {
        fromIndex = listingContext.getSkipCount();
      }

      // Case if skipCount > result size
      if (listingContext.getMaxItems() + fromIndex >= result.size()) {
        result = result.subList(fromIndex, result.size());
        hasMoreItems = false;
      } else {
        result = result.subList(fromIndex, listingContext.getMaxItems() + fromIndex);
        hasMoreItems = true;
      }
    }
    return new PagingResultImpl<Site>(result, hasMoreItems, result.size());
  }
 // opposite to non-key item: item with valid property declaration and
 // perhaps some comment lines
 private void createKeyItem(List<String> lines, int commentLinesCount) {
   Item item =
       new Item(
           lines.subList(0, commentLinesCount), lines.subList(commentLinesCount, lines.size()));
   addItem(item, false);
   lines.clear();
 }
  @SuppressWarnings("unchecked")
  public double crossValidationError(int n, Approach approach) throws IOException {
    List<String> queries = QueryLoader.loadQueries(queryFile);
    int partSize = queries.size() / n;
    List<List<String>> partitions = new ArrayList<>(n);
    for (int i = 0; i < (n - 1); i++) {
      partitions.add(queries.subList(i * partSize, (i + 1) * partSize));
    }
    partitions.add(queries.subList((n - 1) * partSize, queries.size()));

    Model model = readModel(MODEL_FILE);
    LOGGER.info("Generating expected counts...");
    ObjectIntOpenHashMap<String> gsResults[] = countResources(partitions, model);

    double rootMeanSquareSum = 0;
    double foldErrors[] = new double[n];
    List<String> training, predicted;
    for (int i = 0; i < n; i++) {
      LOGGER.info("Starting fold " + i + "...");
      training = generateTrainingSet(i, partitions);
      predicted = approach.generateResourceRanking(training, model);
      foldErrors[i] = RMSD.getRMSD(predicted, generateExpectedResult(i, gsResults));
      LOGGER.info("Error of fold " + i + " = " + foldErrors[i]);
      rootMeanSquareSum += foldErrors[i];
    }
    LOGGER.info("Error of folds " + Arrays.toString(foldErrors));
    return rootMeanSquareSum / n;
  }
 public static <ELEMENT> List<ELEMENT> moveElementToIndex(
     List<ELEMENT> list, int fromIndex, int toIndex) {
   assertObjectNotNull("list", list);
   if (fromIndex == toIndex) {
     String msg = "The argument 'fromIndex' and 'toIndex' should not be same:";
     msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex;
     throw new IllegalArgumentException(msg);
   }
   if (fromIndex < 0 || toIndex < 0) {
     String msg = "The argument 'fromIndex' and 'toIndex' should not be minus:";
     msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex;
     throw new IllegalArgumentException(msg);
   }
   final boolean fromLess = fromIndex < toIndex;
   final List<ELEMENT> movedList = new ArrayList<ELEMENT>();
   final int firstIndex = fromLess ? fromIndex : toIndex;
   final int secondIndex = !fromLess ? fromIndex : toIndex;
   final List<ELEMENT> first = list.subList(0, firstIndex);
   final ELEMENT element = list.get(fromIndex);
   final int adjustmentIndex = fromLess ? 1 : 0;
   final List<ELEMENT> middle =
       list.subList(firstIndex + adjustmentIndex, secondIndex + adjustmentIndex);
   final List<ELEMENT> last = list.subList(secondIndex + 1, list.size());
   movedList.addAll(first);
   if (!fromLess) {
     movedList.add(element);
   }
   movedList.addAll(middle);
   if (fromLess) {
     movedList.add(element);
   }
   movedList.addAll(last);
   return movedList;
 }
  public void loadNextFiveTransactions() {

    index = lv_Transactions.getFirstVisiblePosition();

    View v = lv_Transactions.getChildAt(0);

    top = (v == null) ? 0 : v.getTop();

    FINAL += 5;

    if (FINAL > listOfAllTransactions.size()) {
      FINAL = listOfAllTransactions.size();
      savingsAccountTransactionsListAdapter =
          new SavingsAccountTransactionsListAdapter(
              getActivity(), listOfAllTransactions.subList(INITIAL, FINAL));
      savingsAccountTransactionsListAdapter.notifyDataSetChanged();
      lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter);
      lv_Transactions.setSelectionFromTop(index, top);
      return;
    }

    savingsAccountTransactionsListAdapter =
        new SavingsAccountTransactionsListAdapter(
            getActivity(), listOfAllTransactions.subList(INITIAL, FINAL));
    savingsAccountTransactionsListAdapter.notifyDataSetChanged();
    lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter);
    lv_Transactions.setSelectionFromTop(index, top);
  }
Exemple #16
0
 // Walk through the batch, process sub-batches, and collect results.
 // For now the batch size for custom (ad hoc) SQL is 1 since that's
 // how it's being handled anyway, plus it simplifies the logic here.
 // This can change if we implement support for larger custom batches.
 private static VoltTable[] executeQueuedSQL(
     final List<QueuedSQL> batch, FragmentExecutor executor) {
   int iFrom = 0;
   int iTo = 0;
   List<VoltTable> results = new ArrayList<VoltTable>();
   VoltTable[] subResults;
   for (; iTo < batch.size(); iTo++) {
     final QueuedSQL qs = batch.get(iTo);
     if (qs.stmt.plan != null) {
       if (iTo > iFrom) {
         // Flush preceding pre-planned work before handling unplanned.
         subResults =
             executor.onExecutePrePlanned(batch.subList(iFrom, iTo), iTo == batch.size() - 1);
         results.addAll(Arrays.asList(subResults));
         iFrom = iTo;
       }
       subResults =
           executor.onExecuteUnplanned(batch.subList(iTo, iTo + 1), iTo == batch.size() - 1);
       iFrom++;
       results.addAll(Arrays.asList(subResults));
     }
   }
   if (iTo > iFrom) {
     subResults = executor.onExecutePrePlanned(batch.subList(iFrom, iTo), true);
     results.addAll(Arrays.asList(subResults));
   }
   return results.toArray(new VoltTable[results.size()]);
 }
 /** @return */
 private IPath goToClosestUnseenBuilding() {
   Collection<EntityID> unsearched = worldModel.getUnknownBuildings();
   if (unsearched.size() > 0) {
     IPath path = routingModule.findShortestPath(myself, unsearched);
     if (path.isValid()) {
       List<EntityID> locations = path.getLocations();
       List<PositionXY> positions = path.getXYPath();
       locations = locations.subList(0, locations.size() - 1);
       positions = positions.subList(0, positions.size() - 1);
       if (LOGGER.isDebugEnabled()) {
         LOGGER.debug(
             "Going outside unsafe building "
                 + worldModel
                     .getEntity(path.getLocations().get(path.getLocations().size() - 1))
                     .getFullDescription()
                 + " from "
                 + worldModel.getEntity(myself).getFullDescription()
                 + " using path: "
                 + path.toString());
       }
       // System.out.println("GOing outside unsafe bulding: " +
       // path.getLocations().get(path.getLocations().size()-1));
       return new Path(locations, positions);
     }
   }
   return Path.INVALID_PATH;
 }
  @Override
  public List<Pedido> listaPagPedidos(String username, int paginaActual, int resultadosPorPagina) {

    session = sessionFactory.openSession();
    Usuario usuario = (Usuario) session.get(Usuario.class, username);
    List<Pedido> p =
        session
            .createCriteria(Pedido.class)
            .add(Restrictions.eq("usuario", usuario))
            .add(Restrictions.eq("confirmado", true))
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .addOrder(Order.desc("idpedido"))
            .list();
    session.close();

    int primer_resultado = paginaActual * resultadosPorPagina - resultadosPorPagina;
    int max_resultados =
        paginaActual * resultadosPorPagina - resultadosPorPagina + resultadosPorPagina;

    List<Pedido> pe;

    if (p.subList(primer_resultado, p.size()).size() < resultadosPorPagina)
      pe = p.subList(primer_resultado, p.size());
    else pe = p.subList(primer_resultado, max_resultados);

    return pe;
  }
Exemple #19
0
 // This test stems from a real bug found by andrewk
 public void testAsList_subList_toArray_roundTrip() {
   float[] array = {(float) 0, (float) 1, (float) 2, (float) 3};
   List<Float> list = Floats.asList(array);
   assertTrue(
       Arrays.equals(new float[] {(float) 1, (float) 2}, Floats.toArray(list.subList(1, 3))));
   assertTrue(Arrays.equals(new float[] {}, Floats.toArray(list.subList(2, 2))));
 }
Exemple #20
0
 /**
  * Creates the output root data.
  *
  * @return the output root data, not null
  */
 protected FlexiBean createRootData() {
   FlexiBean out = super.createRootData();
   HolidayDocument latestDoc = data().getHoliday();
   HolidayDocument versionedHoliday = data().getVersioned();
   out.put("latestHolidayDoc", latestDoc);
   out.put("latestHoliday", latestDoc.getHoliday());
   out.put("holidayDoc", versionedHoliday);
   out.put("holiday", versionedHoliday.getHoliday());
   out.put("deleted", !latestDoc.isLatest());
   List<Pair<Year, List<LocalDate>>> map = new ArrayList<Pair<Year, List<LocalDate>>>();
   List<LocalDate> dates = versionedHoliday.getHoliday().getHolidayDates();
   if (dates.size() > 0) {
     int year = dates.get(0).getYear();
     int start = 0;
     int pos = 0;
     for (; pos < dates.size(); pos++) {
       if (dates.get(pos).getYear() == year) {
         continue;
       }
       map.add(Pair.of(Year.of(year), dates.subList(start, pos)));
       year = dates.get(pos).getYear();
       start = pos;
     }
     map.add(Pair.of(Year.of(year), dates.subList(start, pos)));
   }
   out.put("holidayDatesByYear", map);
   return out;
 }
  @Test
  public void testHeadTail() {
    List<Integer> ints = IntStreamEx.range(1000).boxed().toList();
    checkShortCircuitCollector("tail(0)", Arrays.asList(), 0, ints::stream, MoreCollectors.tail(0));
    checkCollector("tail(1)", Arrays.asList(999), ints::stream, MoreCollectors.tail(1));
    checkCollector("tail(2)", Arrays.asList(998, 999), ints::stream, MoreCollectors.tail(2));
    checkCollector("tail(500)", ints.subList(500, 1000), ints::stream, MoreCollectors.tail(500));
    checkCollector("tail(999)", ints.subList(1, 1000), ints::stream, MoreCollectors.tail(999));
    checkCollector("tail(1000)", ints, ints::stream, MoreCollectors.tail(1000));
    checkCollector("tail(MAX)", ints, ints::stream, MoreCollectors.tail(Integer.MAX_VALUE));

    checkShortCircuitCollector("head(0)", Arrays.asList(), 0, ints::stream, MoreCollectors.head(0));
    checkShortCircuitCollector(
        "head(1)", Arrays.asList(0), 1, ints::stream, MoreCollectors.head(1));
    checkShortCircuitCollector(
        "head(2)", Arrays.asList(0, 1), 2, ints::stream, MoreCollectors.head(2));
    checkShortCircuitCollector(
        "head(500)", ints.subList(0, 500), 500, ints::stream, MoreCollectors.head(500));
    checkShortCircuitCollector(
        "head(999)", ints.subList(0, 999), 999, ints::stream, MoreCollectors.head(999));
    checkShortCircuitCollector("head(1000)", ints, 1000, ints::stream, MoreCollectors.head(1000));
    checkShortCircuitCollector(
        "head(MAX)", ints, 1000, ints::stream, MoreCollectors.head(Integer.MAX_VALUE));

    checkShortCircuitCollector(
        "head(10000)",
        IntStreamEx.rangeClosed(1, 10000).boxed().toList(),
        10000,
        () -> Stream.iterate(1, x -> x + 1),
        MoreCollectors.head(10000),
        true);
  }
  SparkSubmitCommandBuilder(List<String> args) {
    this.allowsMixedArguments = false;

    boolean isExample = false;
    List<String> submitArgs = args;
    if (args.size() > 0 && args.get(0).equals(PYSPARK_SHELL)) {
      this.allowsMixedArguments = true;
      appResource = PYSPARK_SHELL_RESOURCE;
      submitArgs = args.subList(1, args.size());
    } else if (args.size() > 0 && args.get(0).equals(SPARKR_SHELL)) {
      this.allowsMixedArguments = true;
      appResource = SPARKR_SHELL_RESOURCE;
      submitArgs = args.subList(1, args.size());
    } else if (args.size() > 0 && args.get(0).equals(RUN_EXAMPLE)) {
      isExample = true;
      submitArgs = args.subList(1, args.size());
    }

    this.sparkArgs = new ArrayList<>();
    this.isExample = isExample;

    OptionParser parser = new OptionParser();
    parser.parse(submitArgs);
    this.printInfo = parser.infoRequested;
  }
 private long quickSort(List<Integer> arrayInput) {
   if (arrayInput.size() <= 1) return 0;
   int pivotIndex = partition(arrayInput);
   long compLess = quickSort(arrayInput.subList(0, pivotIndex));
   long compMore = quickSort(arrayInput.subList(pivotIndex + 1, arrayInput.size()));
   return compLess + compMore + arrayInput.size() - 1;
 }
Exemple #24
0
  public static List<Point> simplify(List<Point> list, double tolerance) {
    int index = 0;
    double dmax = 0;
    double squareTolerance = tolerance * tolerance;
    int lastIndex = list.size() - 1;

    // Find the point with the maximum distance
    for (int i = 1; i < list.size() - 1; i++) {
      double d = pointToLineDistance(list.get(0), list.get(lastIndex), list.get(i));
      if (d > dmax) {
        index = i;
        dmax = d;
      }
    }

    // If max distance is greater than epsilon, recursively simplify
    List<Point> ResultList = new ArrayList<Point>();
    if (dmax > squareTolerance) {
      // Recursive call
      List<Point> recResults1 = simplify(list.subList(0, index + 1), tolerance);
      List<Point> recResults2 = simplify(list.subList(index, lastIndex + 1), tolerance);

      // Build the result list
      recResults1.remove(recResults1.size() - 1);
      ResultList.addAll(recResults1);
      ResultList.addAll(recResults2);
    } else {
      ResultList.add(list.get(0));
      ResultList.add(list.get(lastIndex));
    }

    // Return the result
    return ResultList;
  }
Exemple #25
0
  /**
   * 按照mul的值进行排序,从大到小排序
   *
   * @param list1
   * @param list2
   */
  private static void combineLists(
      List<IDistanceDensityMul> list1, List<IDistanceDensityMul> list2) {
    List<IDistanceDensityMul> allList = new ArrayList<IDistanceDensityMul>();
    int sizeOne = list1.size();
    int sizeTwo = list2.size();

    int i, j;
    for (i = 0, j = 0; i < sizeOne && j < sizeTwo; ) {
      if (list1.get(i).greater(list2.get(j))) {
        allList.add(list1.get(i++));
      } else {
        allList.add(list2.get(j++));
      }
    }
    if (i < sizeOne) { // list1 has not finished
      allList.addAll(list1.subList(i, sizeOne));
    }
    if (j < sizeTwo) { // list2 has not finished
      allList.addAll(list2.subList(j, sizeTwo));
    }
    // 重新赋值
    list1.clear();
    list1.addAll(allList);
    allList.clear();
  }
  @Test
  public void report_FacilityUsage_asOperator2() {
    final ReportParameters params = baseParams();
    params.interval = 3 * 60;
    registerMockFacilityUsages(facility1, apiUser);
    registerMockFacilityUsages(facility2, apiUser2);

    final Response whenPostingToReportUrl = postToReportUrl(params, "FacilityUsage", operator2User);

    // If this succeeds, the response was a valid excel file
    final Workbook workbook = readWorkbookFrom(whenPostingToReportUrl);
    assertThat(getSheetNames(workbook)).containsExactly("Käyttöasteraportti", "Selite");

    final Sheet usages = workbook.getSheetAt(0);
    // Header and one for each usage type
    assertThat(usages.getPhysicalNumberOfRows()).isEqualTo(3);

    // Only operator2 visible
    assertThat(getDataFromColumn(usages, 3))
        .containsOnly("Operaattori", operator2.name.fi)
        .doesNotContain(operator1.name.fi);

    final List<String> headers = getDataFromRow(usages, 0);
    assertThat(headers.subList(FACILITYUSAGE_FIRST_TIME_COLUMN, headers.size()))
        .containsExactly("00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00");

    // Get the hourly utilizations for CAR
    // Results are not interpolated.
    final List<String> row = getDataFromRow(usages, 1);
    assertThat(row.subList(FACILITYUSAGE_FIRST_TIME_COLUMN, row.size()))
        .containsExactly("24", "24", "24", "24", "0", "0", "0", "24");
  }
  public RowsDto getRows(
      final int sortColumnIndex,
      boolean isSort,
      final int sortDirection,
      boolean doFilter,
      String[] searchCriteria,
      int beginRecord,
      int endRecord) {

    RowsDto rowsDto = null;

    if (isSort) {
      RowDataComparator comparator = new RowDataComparator(sortColumnIndex, sortDirection);
      Collections.sort(ROW_DATA_LIST, comparator);
      rowsDto = new RowsDto(ROW_DATA_LIST, ROW_DATA_LIST.size());
    }

    if (doFilter) {
      RowData searchObject = new RowData(searchCriteria);
      List<RowData> interimList = createSearchList(ROW_DATA_LIST, searchObject);
      if (endRecord > interimList.size()) ;
      endRecord = interimList.size();
      rowsDto = new RowsDto(interimList.subList(beginRecord, endRecord), interimList.size());
    }

    if ((!doFilter) && (!isSort)) {
      rowsDto = new RowsDto(ROW_DATA_LIST.subList(beginRecord, endRecord), ROW_DATA_LIST.size());
    }

    return rowsDto;
  }
  @NotNull
  @Override
  public List<? extends SoftWrap> getSoftWrapsForRange(int start, int end) {
    if (!isSoftWrappingEnabled() || end < start) {
      return Collections.emptyList();
    }

    List<? extends SoftWrap> softWraps = myStorage.getSoftWraps();

    int startIndex = myStorage.getSoftWrapIndex(start);
    if (startIndex < 0) {
      startIndex = -startIndex - 1;
      if (startIndex >= softWraps.size() || softWraps.get(startIndex).getStart() > end) {
        return Collections.emptyList();
      }
    }

    int endIndex = myStorage.getSoftWrapIndex(end);
    if (endIndex >= 0) {
      return softWraps.subList(startIndex, endIndex + 1);
    } else {
      endIndex = -endIndex - 1;
      return softWraps.subList(startIndex, endIndex);
    }
  }
 private void drawAlternatingLine(List<Integer> numbers, boolean horizontal) {
   while (numbers.size() > 0) {
     addCommand(numbers.subList(0, 1), new CharStringCommand(horizontal ? 6 : 7));
     numbers = numbers.subList(1, numbers.size());
     horizontal = !horizontal;
   }
 }
Exemple #30
0
  /** 对IP_Net_To_Media进行探测 */
  private void doIPNetProbe() {
    if (DiscoverEngine.getInstance().getStopStatus() == 1) return;
    List ipNetTable =
        SnmpUtil.getInstance().getIpNetToMediaTable(this.getIpAddress(), this.getCommunity());

    if (ipNetTable == null || ipNetTable.size() == 0) // important
    {
      setDiscovered(true);
      return;
    }
    ipTotal = ipNetTable.size();
    int threadTotal = 0; // 线程总数
    SysLogger.info("PER_THREAD_IP===" + PER_THREAD_IP);
    if (ipTotal % PER_THREAD_IP == 0) // 每个线程对N个ip进行探测
    threadTotal = ipTotal / PER_THREAD_IP;
    else threadTotal = ipTotal / PER_THREAD_IP + 1;

    IPNetProbeThread probeThread = null;
    for (int i = 0; i < threadTotal; i++) {
      if (i == threadTotal - 1)
        probeThread = new IPNetProbeThread(this, ipNetTable.subList(i * PER_THREAD_IP, ipTotal));
      else
        probeThread =
            new IPNetProbeThread(
                this, ipNetTable.subList(i * PER_THREAD_IP, (i + 1) * PER_THREAD_IP));
      DiscoverEngine.getInstance().addThread(probeThread);
    }
  }