Example #1
1
  public static void removeCommon() {
    lx.sort(
        new Comparator<Integer>() {

          @Override
          public int compare(Integer o1, Integer o2) {
            if (o1 < o2) {
              return -1;
            } else if (o1 > o2) {
              return 1;
            }
            return 0;
          }
        });
    ly.sort(
        new Comparator<Integer>() {

          @Override
          public int compare(Integer o1, Integer o2) {
            if (o1 < o2) {
              return -1;
            } else if (o1 > o2) {
              return 1;
            }
            return 0;
          }
        });
  }
Example #2
1
 void sortTransactionByDate() {
   List<Transaction> tr = new ArrayList<Transaction>(transactions.values());
   tr.sort(Transaction.DateComparator);
   for (Transaction t : tr) {
     t.displayTransaction();
   }
 }
Example #3
1
 void sortbyAccount() {
   List<Accounts> ac = new ArrayList<Accounts>(accounts.values());
   ac.sort(Accounts.AccountComparator);
   for (Accounts a : ac) {
     a.dispaly();
   }
 }
Example #4
1
  public void writeTasks(OutputStream output) {
    try {
      output.write("[\n".getBytes());
      boolean needComma = false;
      File[] files = tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter());
      List<Integer> numbers = new ArrayList<>();
      for (File directory : files) {
        try {
          numbers.add(Integer.valueOf(directory.getName()));
        } catch (Throwable ignored) {

        }
      }
      numbers.sort(Comparator.<Integer>reverseOrder());
      numbers = numbers.subList(0, Math.min(100, numbers.size()));
      for (int taskId : numbers) {
        File infoFile = new File(new File(tasksDirectory, String.valueOf(taskId)), "info.json");
        if (!infoFile.exists()) {
          continue;
        }
        if (needComma) {
          output.write(",\n".getBytes());
        } else {
          needComma = true;
        }
        try (FileInputStream fis = new FileInputStream(infoFile)) {
          IOUtils.copy(fis, output);
        }
      }
      output.write("]\n".getBytes());
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }
Example #5
1
  static void lambdaTest() {
    Runnable r = () -> System.out.print("hello lambda");
    r.run();
    List<String> list = Arrays.asList("t1", "t2", "t334", "t4", "t567");
    list.parallelStream().filter(s -> s.length() == 2).forEach(System.out::println);

    list = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "15", "17");
    Map<String, Integer> integers =
        list.stream()
            .map(Integer::new)
            .filter(e -> e % 2 != 0)
            .distinct()
            .collect(Collectors.toMap(Object::toString, e -> e));
    System.out.println(integers);
    Stream.generate(Math::random).limit(10).forEach(System.out::println);

    new Thread(() -> System.out.println("hello lambda")).start();
    new Thread(
            () -> {
              System.out.println("hello lambda");
            })
        .start();

    List<String> words = Lists.newArrayList("ren", "wang", "li", "zhao", "ma");
    words.sort((w1, w2) -> Integer.compare((w1.length()), w2.length()));

    List<Integer> ints = Ints.asList(1, 2, 3, 4, 5);
    ints.sort(Integer::compare);

    //        words.forEach(e -> System.out.print(e));
    words.forEach(System.out::println);

    //        words.stream().map(w -> w.length());
    words.stream().map(String::length);

    //        words.stream().map(w -> new StringBuilder(w));
    words.stream().map(StringBuilder::new);

    Converter<String, Integer> converter; // (f) -> Integer.valueOf(f);
    converter = Integer::valueOf;
    Integer converted = converter.convert("123");
    System.out.println(converted);

    String[] arrayStr = new String[] {"a", "ab", "abc", "abcd"};

    Arrays.sort(arrayStr, (first, second) -> Integer.compare(first.length(), second.length()));
  }
 /** Fetches available package versions using JSON API of PyPI. */
 @NotNull
 private List<String> getPackageVersionsFromPyPI(@NotNull String packageName, boolean force)
     throws IOException {
   final PackageDetails details = refreshAndGetPackageDetailsFromPyPI(packageName, force);
   final List<String> result = details.getReleases();
   result.sort(PackageVersionComparator.VERSION_COMPARATOR.reversed());
   return Collections.unmodifiableList(result);
 }
Example #7
0
  public static void main(String... args) {
    List<String> releaseVersionList =
        Arrays.asList("r9.2", "r9.2.1", "r9.4", "main", "r9.1", "r9.3", "r9.3.1", "feature");

    releaseVersionList.sort(new VersionComparatorBad());
    System.out.println(releaseVersionList);

    releaseVersionList.sort(new VersionComparatorGood());
    System.out.println(releaseVersionList);
  }
Example #8
0
  @Test(dataProvider = "loadReadsADAM", groups = "spark")
  public void readsSinkADAMTest(String inputBam, String outputDirectoryName) throws IOException {
    // Since the test requires that we not create the actual output directory in advance,
    // we instead create its parent directory and mark it for deletion on exit. This protects
    // us from naming collisions across multiple instances of the test suite.
    final File outputParentDirectory = createTempDir(outputDirectoryName + "_parent");
    final File outputDirectory = new File(outputParentDirectory, outputDirectoryName);

    JavaSparkContext ctx = SparkContextFactory.getTestSparkContext();

    ReadsSparkSource readSource = new ReadsSparkSource(ctx);
    JavaRDD<GATKRead> rddParallelReads = readSource.getParallelReads(inputBam, null);
    SAMFileHeader header = ReadsSparkSource.getHeader(ctx, inputBam, null);

    ReadsSparkSink.writeReads(
        ctx, outputDirectory.getAbsolutePath(), rddParallelReads, header, ReadsWriteFormat.ADAM);

    JavaRDD<GATKRead> rddParallelReads2 =
        readSource.getADAMReads(outputDirectory.getAbsolutePath(), null, header);
    Assert.assertEquals(rddParallelReads.count(), rddParallelReads2.count());

    // Test the round trip
    List<GATKRead> samList = rddParallelReads.collect();
    List<GATKRead> adamList = rddParallelReads2.collect();
    Comparator<GATKRead> comparator = new ReadCoordinateComparator(header);
    samList.sort(comparator);
    adamList.sort(comparator);
    for (int i = 0; i < samList.size(); i++) {
      SAMRecord expected = samList.get(i).convertToSAMRecord(header);
      SAMRecord observed = adamList.get(i).convertToSAMRecord(header);
      // manually test equality of some fields, as there are issues with roundtrip BAM -> ADAM ->
      // BAM
      // see https://github.com/bigdatagenomics/adam/issues/823
      Assert.assertEquals(observed.getReadName(), expected.getReadName(), "readname");
      Assert.assertEquals(
          observed.getAlignmentStart(), expected.getAlignmentStart(), "getAlignmentStart");
      Assert.assertEquals(
          observed.getAlignmentEnd(), expected.getAlignmentEnd(), "getAlignmentEnd");
      Assert.assertEquals(observed.getFlags(), expected.getFlags(), "getFlags");
      Assert.assertEquals(
          observed.getMappingQuality(), expected.getMappingQuality(), "getMappingQuality");
      Assert.assertEquals(
          observed.getMateAlignmentStart(),
          expected.getMateAlignmentStart(),
          "getMateAlignmentStart");
      Assert.assertEquals(observed.getCigar(), expected.getCigar(), "getCigar");
    }
  }
Example #9
0
  /**
   * Goes through all the Areas a user has subscribed to and creates a list of contents published in
   * those areas, ordered by their modification times.
   *
   * @param person the person whose subscriptions will be used
   * @return list of the content in chronological order
   */
  public List<Content> createListOfSubscribedContents(Person person) {
    List<Content> newList = new ArrayList<>();

    // Builds new list without duplicates
    person
        .getSubscriptions()
        .stream()
        .forEach(
            (area) -> {
              area.getElements()
                  .stream()
                  .filter((content) -> (!newList.contains(content)))
                  .forEach(
                      (content) -> {
                        newList.add((Content) content);
                      });
            });

    // sorts new list to chronological order. Newest first.
    newList.sort(
        (Content x, Content y) -> {
          return y.getModifyTime().compareTo(x.getModifyTime());
        });

    return newList;
  }
  /**
   * Metodo que busca as classes de movimentacao e seu respectivo valor movimento, ou seja, a
   * somatoria de todos os rateios para a aquela classe
   *
   * @param period o periodo
   * @param direction qual tipo queremos, entrada ou saida
   * @return a lista de movimentos
   */
  public List<MovementClass> fetchTopClassesAndValues(
      FinancialPeriod period, MovementClassType direction) {

    final List<MovementClass> withValues = new ArrayList<>();

    // lista as classes sem pegar as bloqueadas
    final List<MovementClass> classes =
        this.movementClassRepository.listByTypeAndStatus(direction, Boolean.FALSE);

    // para cada classe pegamos o seu total em movimentacao
    classes
        .stream()
        .forEach(
            clazz -> {
              final BigDecimal total =
                  this.apportionmentRepository.totalMovementsPerClassAndPeriod(period, clazz);

              if (total != null) {
                clazz.setTotalMovements(total);
                withValues.add(clazz);
              }
            });

    // ordena do maior para o menor
    withValues.sort((c1, c2) -> c2.getTotalMovements().compareTo(c1.getTotalMovements()));

    // retorna somente os 10 primeiros resultados
    return withValues.size() > 10 ? withValues.subList(0, 10) : withValues;
  }
Example #11
0
  public Player(Vector<Card> cards) {
    for (int i = 0; i < 4; i++) {
      Vector<Rank> ranks = new Vector<Rank>();
      this.cards.add(ranks);
    }

    for (Card card : cards) {
      suits.add(card.getSuit());
      distinctRank.add(card.getRank());
    }

    List<Rank> myList = new ArrayList(distinctRank);
    myList.sort(new RankComparator());

    for (Rank rank : myList) {
      int count = 0;
      for (Card card : cards) {
        if (card.getRank().ordinal() == rank.ordinal()) count++;
      }

      if (count < 5 && count > 0) {
        if (this.cards.size() > 0) this.cards.get(count - 1).add(rank);
      }
    }

    mode = findPlayerMode();
  }
Example #12
0
  /** @return A list of the settable fields. */
  public static List<Field> getSettableFields() {
    // Init the search in the root package.
    Reflections reflections = new Reflections("org.saucistophe", new FieldAnnotationsScanner());
    Set<Field> annotatedFields = reflections.getFieldsAnnotatedWith(SettingsField.class);

    // Turn the set to a list to sort it.
    List<Field> fieldsList = new ArrayList<>(annotatedFields);
    fieldsList.sort(
        (Field field1, Field field2) -> {
          // Retrieve the fields info.
          SettingsField fieldInfo1 = field1.getAnnotation(SettingsField.class);
          SettingsField fieldInfo2 = field2.getAnnotation(SettingsField.class);

          // If the name wasn't set, get the field's declared name.
          String actualName1 = fieldInfo1.name().isEmpty() ? field1.getName() : fieldInfo1.name();
          String actualName2 = fieldInfo2.name().isEmpty() ? field2.getName() : fieldInfo2.name();

          // Elaborate a sortable string representation.
          String sortableString1 = fieldInfo1.category() + "." + actualName1;
          String sortableString2 = fieldInfo2.category() + "." + actualName2;

          return sortableString1.compareTo(sortableString2);
        });

    return fieldsList;
  }
  @Test
  public void builds_comparator_from_unary_function() throws Exception {
    final List<String> strings = asList("CCC", "A", "BB");
    strings.sort(Comparators.from(String::length));

    assertThat(strings, is(asList("A", "BB", "CCC")));
  }
Example #14
0
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("Profiling result: \n");

    List<SectionData> sorted = new ArrayList<>(sections.values());
    sorted.sort((lhs, rhs) -> Float.compare(lhs.timeTotal, rhs.timeTotal));

    float total = 0.0f;

    for (SectionData data : sorted) {
      sb.append(String.format("[%s]: %.2fs (%d times) ", data.section, data.timeTotal, data.times));
      if (data.calculating) {
        sb.append("Calculating\n");
      } else {
        sb.append("\n");
      }

      total += data.timeTotal;
    }

    sb.append(String.format("Time total: %.2fs. \n", total));

    return sb.toString();
  }
Example #15
0
  public void render(Renderer renderer) {
    // Find renderables and sort them by depth
    List<Renderable> renderables = new ArrayList<>();

    for (GameObject actor : actors) {
      if (actor instanceof Renderable) {
        renderables.add((Renderable) actor);
      }
    }

    renderables.sort((o1, o2) -> (int) (Integer.MAX_VALUE * (o2.getDepth() - o1.getDepth())));

    // Apply camera
    renderer.pushMatrix();
    if (camera != null) {
      camera.applyTransforms(renderer);
    }

    // render objects
    for (Renderable renderable : renderables) {
      renderable.render(renderer);
    }

    renderer.popMatrix();
  }
Example #16
0
  public <T> void exportToCsv(String fileName, Iterator<T> data) {
    try {
      Files.createDirectories(Paths.get(DIR));
      StringBuilder content = new StringBuilder();

      List<Method> getters = null;
      while (data.hasNext()) {
        T t = data.next();
        if (getters == null) {
          getters = ReflectionUtil.getAllGetters(t.getClass());
          getters.sort((a, b) -> a.getName().length() - b.getName().length());
        }
        for (Method getter : getters) {
          try {
            String value = String.valueOf(getter.invoke(t));
            content.append(value).append(',');
          } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
          }
        }
        content.append('\n');
      }

      Files.write(
          Paths.get(DIR + fileName),
          content.toString().getBytes("UTF-8"),
          CREATE,
          WRITE,
          StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Override
  List<Coin> sort(List<Coin> cash) {
    List<Coin> defensiveCopy = new ArrayList<>(cash);
    defensiveCopy.sort((c1, c2) -> c1.value().compareTo(c2.value()));

    return defensiveCopy;
  }
 public List<Album> getAlbums(boolean forceReloadFromPlex) throws DuckException {
   if (forceReloadFromPlex || albums == null) {
     Context.getPlexServer().loadAlbums(this);
     albums.sort(Comparator.comparing((Album::getName), new CaseInsensitiveStringComparator()));
   }
   return albums;
 }
  /**
   * Creates a new instance of {@link SpringApplication}.
   *
   * @return spring application
   */
  @SuppressWarnings("unchecked")
  public static SpringApplication newApplication() {
    //
    List<Object> applicationSources = Lists.newArrayList();

    try {
      //
      Class<?> applicationSourceProviderClass = Class.forName(APPLICATION_SOURCE_PROVIDER_CLASS);
      Method getSourcesMethod = applicationSourceProviderClass.getDeclaredMethod("getSources");

      //
      ServiceLoader<?> loader = newServiceLoader(applicationSourceProviderClass);
      for (Object sourceProvider : ImmutableList.copyOf(loader.iterator())) {
        applicationSources.addAll((Collection<Object>) getSourcesMethod.invoke(sourceProvider));
      }
    } catch (Exception ex) {
      log.warn("Failed to load application sources", ex);
    }

    //
    if (applicationSources.isEmpty()) {
      log.warn(
          "no application source found, using fallback. some functionalities may work properly");
      applicationSources.add(FallbackApplicationSource.class);
    } else {
      applicationSources.sort(Comparator.comparing(SpringApplicationUtils::getOrder));
    }

    //
    return new SpringApplication(applicationSources.toArray());
  }
Example #20
0
 public List<Stage> getAllStages() {
   List<Stage> temp = new ArrayList<Stage>(getStageValues());
   temp.sort((s1, s2) -> s1.compareTo(s2));
   // Uncomment this next line and comment the two above to disable sorting
   // List<Stage> temp = Collections.unmodifiableList(getStageValues());
   return temp;
 }
  public String solve() {
    PriorityQueue<Neighbor> copy = new PriorityQueue<Neighbor>(neighbors);

    // Mencari jumlah masing-masing kelas pada priority queue Neighbor
    Iterator<Neighbor> itr = copy.iterator();
    while (itr.hasNext()) {
      Neighbor n = itr.next();

      boolean found = false;
      int j = 0;
      while ((j < classes.size()) && !found) {
        // Jika kelas yang sama sudah ada, maka counter hanya akan bertambah
        if (data.get(n.index).get(data.get(n.index).size() - 1).equals(classes.get(j).classData)) {
          classes.get(j).addCounter();
          found = true;
        } else {
          j++;
        }
      }
      // Jika kelas belum ada pada list, maka kelas akan ditambahkan
      if (!found) {
        DataClass newData = new DataClass(data.get(n.index).get(data.get(n.index).size() - 1));
        classes.add(newData);
      }
    }
    classes.sort(
        new Comparator<DataClass>() {
          @Override
          public int compare(DataClass d1, DataClass d2) {
            return (d1.count <= d2.count ? 1 : -1);
          }
        });

    return classes.get(0).classData;
  }
  protected void sortWords() {
    List<Word> lWords = wordGraph.getWords();
    lWords.sort((w1, w2) -> w1.word.compareToIgnoreCase(w2.word));

    words = wordGraph.convertWordsToArray();
    similarity = wordGraph.convertSimilarityToArray();
  }
 public List<String> testSorted(List<String> list) {
   List<String> result = new ArrayList<>();
   for (String s : list) {
     result.add(s);
   }
   result.sort(null);
   return result.toArray(new String[0]);
 }
  @NotNull
  public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) {

    JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();

    List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>();

    // prevent adding duplicate version on alias names
    Set<String> aliasBranches = new HashSet<>();

    // get alias version, in most common order
    for (String s : new String[] {"latest", "lts"}) {
      JsonElement asJsonObject = jsonObject.get(s);
      if (asJsonObject == null) {
        continue;
      }

      String asString = asJsonObject.getAsString();
      aliasBranches.add(asString);

      symfonyInstallerVersions.add(
          new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s)));
    }

    List<SymfonyInstallerVersion> branches = new ArrayList<>();
    Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
    for (Map.Entry<String, JsonElement> entry : entries) {
      if (!entry.getKey().matches("^\\d+\\.\\d+$")) {
        continue;
      }

      // "2.8.0-dev", "2.8.0-DEV" is not supported
      String asString = entry.getValue().getAsString();
      if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) {
        continue;
      }

      branches.add(
          new SymfonyInstallerVersion(
              asString, String.format("%s (%s)", entry.getKey(), asString)));
    }

    branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion));

    Collections.reverse(branches);

    symfonyInstallerVersions.addAll(branches);

    // we need reverse order for sorting them on version string
    List<SymfonyInstallerVersion> installableVersions = new ArrayList<>();
    for (JsonElement installable : jsonObject.getAsJsonArray("installable")) {
      installableVersions.add(new SymfonyInstallerVersion(installable.getAsString()));
    }
    Collections.reverse(installableVersions);

    symfonyInstallerVersions.addAll(installableVersions);
    return symfonyInstallerVersions;
  }
  @Override
  public PagerResult<GeneratorInstance> search(GeneratorInstanceSearchRequest request) {
    Long userId = request.getUserId();
    String name = StringUtils.hasText(request.getName()) ? request.getName() : null;
    List<GeneratorInstance> records =
        generatorInstanceRepository.filter(
            generatorInstance -> {
              if (generatorInstance.getIsDelete()) {
                return false;
              }
              if (name != null) {
                if (!generatorInstance.getName().contains(name)) {
                  return false;
                }
              }
              if (userId != null) {
                if (!userId.equals(generatorInstance.getUser().getId())) {
                  return false;
                }
              }
              return true;
            });
    Integer page = request.getPage();
    Integer pageSize = request.getPageSize();
    Integer fromIndex = (page - 1) * pageSize;
    Integer toIndex = fromIndex + pageSize > records.size() ? records.size() : fromIndex + pageSize;
    List<GeneratorInstance> limitRecords = records.subList(fromIndex, toIndex);
    List<GeneratorInstance> result = new ArrayList<>();
    for (GeneratorInstance g : limitRecords) {
      GeneratorInstance generatorInstance = new GeneratorInstance();
      generatorInstance.setId(g.getId());
      generatorInstance.setName(g.getName());
      generatorInstance.setCreateDate(g.getCreateDate());
      generatorInstance.setModifyDate(g.getModifyDate());
      generatorInstance.setIsDelete(g.getIsDelete());
      User userPersistence = userRepository.selectById(g.getUser().getId());
      generatorInstance.setUser(userPersistence);
      Generator generatorPersistence = generatorRepository.selectById(g.getGenerator().getId());
      if (generatorPersistence == null) {
        throw new AppException("生成器不存在");
      }
      generatorInstance.setGenerator(generatorPersistence);
      generatorInstance.setDataModel(g.getDataModel());
      generatorInstance.setVersion(g.getVersion());
      result.add(generatorInstance);
    }

    String sortField = request.getSortField();
    String sortDirection = request.getSortDirection();
    if ("modifyDate".equals(sortField)) {
      if ("DESC".equalsIgnoreCase(sortDirection)) {
        result.sort(
            (g1, g2) -> (int) (g2.getModifyDate().getTime() - g1.getModifyDate().getTime()));
      }
    }

    return new PagerResult<>(result, (long) records.size());
  }
Example #26
0
 void sortAccountByType() {
   List<Accounts> ac = new ArrayList<Accounts>(accounts.values());
   ac.sort(Accounts.TypeComparator);
   ac.stream()
       .forEach(
           (a) -> {
             a.dispaly();
           });
 }
Example #27
0
 void setServlets(List<Servlet> servlets) {
   this.servlets = servlets;
   servlets.sort(
       Comparator.<Servlet>comparingInt(
           s -> {
             Servlet.Priority priority = s.getClass().getAnnotation(Servlet.Priority.class);
             return priority == null ? 0 : priority.value();
           }));
 }
 @Override
 public List<Module> getMostRecentlyUsed() {
   List<ModuleUsage> used = dataStore.getUsages();
   used.sort((a, b) -> Long.compare(b.getLastSeen(), a.getLastSeen()));
   return used.stream()
       .map(u -> modulesMap.get(u.getModuleId()))
       .filter(m -> m != null)
       .collect(toList());
 }
  public static void main(String[] args) {

    List<String> palavras = Arrays.asList("julio", "cesar", "nunes", "de", "souza");

    // sintaxes mais enxuta
    palavras.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));

    palavras.forEach(palavra -> System.out.println(palavra));
  }
Example #30
0
  /**
   * Demo.
   *
   * @param args not used.
   */
  public static void main(String[] args) {
    final List<Mountain> mountains = new ArrayList<>();

    mountains.add(new Mountain("Weisshorn", 2653)); // Arosa
    mountains.add(new Mountain("Weisshorn", 4505)); // Wallis
    mountains.add(new Mountain("Pilatus", 2128));
    mountains.add(new Mountain("Rigi", 1797));
    mountains.add(new Mountain("Stanserhorn", 1898));
    mountains.add(new Mountain("Titlis", 3238));
    mountains.add(new Mountain("Bürgenstock", 1128));
    System.out.println("\nEingabereihenfolge: \n " + mountains);

    mountains.sort(null);
    System.out.println("\nAlfabetisch nach Namen\n " + mountains);

    mountains.sort(new HeightComparator());
    System.out.println("\nnach aufsteigender Höhe: \n " + mountains);
  }