Пример #1
0
  private static Stream<String> apps() {
    if (cl instanceof URLClassLoader) {
      URLClassLoader ucl = (URLClassLoader) cl;

      return Stream.of(ucl.getURLs())
          .map(propagating(url -> Paths.get(url.toURI())))
          .flatMap(
              propagating(
                  path -> {
                    if (Files.isRegularFile(path)) {
                      return zipContents(path);
                    } else if (Files.isDirectory(path)) {
                      return Files.walk(path)
                          .map(subpath -> path.relativize(subpath))
                          .map(subpath -> subpath.toString())
                          .filter(subpath -> subpath.endsWith(".class"))
                          .map(Scanner::toClassName);
                    } else {
                      return Stream.empty();
                    }
                  }))
          .filter(x -> !x.startsWith("com.cakemanny.app."))
          .filter(implementsInterface(App.class));
    } else {
      return Stream.empty();
    }
  }
Пример #2
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
  /**
   * If <code>usePrimary</code> is true the segments are the primary segments but only those that
   * exist in targetSegments. However if <code>usePrimary</code> is false then <code>targetSegments
   * </code> must be provided and non null and this will be used specifically.
   *
   * @param ch
   * @param targetSegments
   * @param excludedKeys
   * @param usePrimary determines whether we should utilize the primary segments or not.
   * @return
   */
  protected Supplier<Stream<CacheEntry>> supplierForSegments(
      ConsistentHash ch,
      Set<Integer> targetSegments,
      Set<Object> excludedKeys,
      boolean usePrimary) {
    if (!ch.getMembers().contains(localAddress)) {
      return Stream::empty;
    }
    Set<Integer> segments;
    if (usePrimary) {
      segments = ch.getPrimarySegmentsForOwner(localAddress);
      if (targetSegments != null) {
        segments.retainAll(targetSegments);
      }
    } else {
      segments = targetSegments;
    }

    return () -> {
      if (segments.isEmpty()) {
        return Stream.empty();
      }

      CacheStream<CacheEntry> stream = supplier.get().filterKeySegments(segments);
      if (keysToFilter != null) {
        stream = stream.filterKeys(keysToFilter);
      }
      if (excludedKeys != null) {
        return stream.filter(e -> !excludedKeys.contains(e.getKey()));
      }
      // Make sure the stream is set to be parallel or not
      return parallel ? stream.parallel() : stream.sequential();
    };
  }
Пример #4
0
 public static <T> Stream<T> traverse(
     Function<T, Iterator<T>> iteratorBuilder, boolean includeParent, @Nullable T obj) {
   return ((obj != null)
       ? StreamSupport.stream(
           new TraversingSpliterator<>(iteratorBuilder, includeParent, obj), false)
       : Stream.empty());
 }
 private static Stream<ElmReference> getReferencesFromSingleId(ElmUpperCaseId element) {
   if (ElmCoreLibrary.isBuiltIn(element.getText())) {
     return Stream.empty();
   } else {
     return Stream.of(new ElmTypeReference(element));
   }
 }
  @Test
  public void optionalTAndListTEmptyStream() {

    OptionalTValue<Integer> opt = OptionalT.fromValue(Maybe.just(Optional.of(10)));
    ListTSeq<Integer> list = ListT.fromStream(Stream.empty());
    assertThat(For.Publishers.each2(list, a -> opt, (a, b) -> a + b).toList(), equalTo(ListX.of()));
  }
Пример #7
0
 @Override
 public Stream<IdxPref> getIidxPreferences(int iidx) {
   if (iidxList.get(iidx) == null) {
     return Stream.empty();
   } else {
     return iidxList.get(iidx).stream();
   }
 }
Пример #8
0
  public List<Triangle> parseFile(InputStream is) {
    try {
      VTDGen vg = new VTDGen();
      vg.setDoc(IOUtils.toByteArray(is));
      vg.parse(false);
      VTDNav vn = vg.getNav();
      NODE_PATH.resetXPath();
      NODE_PATH.bind(vn); // This is important state for the later method calls!
      NODE_REF_PATH.resetXPath();
      NODE_REF_PATH.bind(vn);
      BUILDING_WAY_PATH.resetXPath();
      BUILDING_WAY_PATH.bind(vn);
      BUILDING_MULTIPOLYGON_PATH.resetXPath();
      BUILDING_MULTIPOLYGON_PATH.bind(vn);
      MEMBER_WAY_PATH.resetXPath();
      MEMBER_WAY_PATH.bind(vn);
      WAY_PATH.resetXPath();
      WAY_PATH.bind(vn);

      // A hash from node ids to actual node positions
      Hashtable<Long, Point2D> nodes = new Hashtable<>();
      // A hash from way refs referenced from multipolygons to their actual list of node refs
      Hashtable<Long, List<Long>> multipolygonWays = new Hashtable<>();

      // The following call initializes accessed node refs in nodes to a dummy value.
      List<List<Long>> buildingWays = extractWaysOfBuildings(vn, nodes);
      // The following call initializes accessed way refs from multipolygons to a dummy value.
      List<List<Tuple2<WayRole, Long>>> multipolygonWayRefs =
          extractWayRefsOfMultipolygons(vn, multipolygonWays);
      // This will extract all referenced multipolygon multipolygonWays, excluding the building
      // multipolygonWays
      // Also adds referenced nodes to nodes
      extractReferencedWays(vn, multipolygonWays, nodes);
      // This will extract all referenced nodes, but no more.
      extractReferencedNodes(vn, nodes);
      // Finally build the polygon list by following the node refs in wayRefs.
      // Triangulate each polygon and return the flattened list of triangles.
      // This way, poly2tri's types will not leak out of this class and we operate
      // on triangles anyway.
      return buildPolygons(nodes, buildingWays, multipolygonWays, multipolygonWayRefs)
          .flatMap(
              p -> {
                try {
                  p.ComplexToSimplePolygon();
                  EarClipping ec = new EarClipping(p.SimplePolygon);
                  return ec.Triangulation().stream();
                } catch (RuntimeException ignored) {
                }
                return Stream.empty();
              })
          .toList();
    } catch (XPathEvalException | NavException | IOException | ParseException e) {
      e.printStackTrace();
      return new ArrayList<>();
    }
  }
Пример #9
0
  @Test
  public void _02_스트림_생성() {
    // 배열로 부터~
    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));

    // 가변 인자로..
    Stream<String> song = Stream.of("gently", "down", "the", "stream");

    // 빈 스트림
    Stream<String> silence = Stream.empty();
  }
 private static <T, R> Function<T, Stream<R>> guarded(FailingFunction<T, R> f) {
   return t -> {
     try {
       return Stream.of(f.apply(t));
     } catch (RuntimeException x) {
       throw x;
     } catch (Exception x) {
       return Stream.empty();
     }
   };
 }
  public Stream<ElmReference> getReferencesStream() {
    PsiElement parent = this.getParent();
    if (parent instanceof ElmImportClause) {
      return this.getReferencesInImport();
    } else if (parent instanceof ElmModuleDeclaration) {
      return Stream.empty();
    }

    List<ElmUpperCaseId> children =
        Arrays.stream(this.getChildren())
            .filter(e -> e instanceof ElmUpperCaseId)
            .map(e -> (ElmUpperCaseId) e)
            .collect(Collectors.toList());
    int size = children.size();
    if (size == 1) {
      return getReferencesFromSingleId(children.get(0));
    } else if (size >= 2) {
      return getReferencesFromNonSinglePath(children);
    }

    return Stream.empty();
  }
 @Way
 public static List<URL> step_2_flatmap(List<String> strings) {
   return strings
       .stream()
       .flatMap(
           string -> {
             try {
               return Stream.of(new URL(string));
             } catch (MalformedURLException ignored) {
               return Stream.empty();
             }
           })
       .collect(toList());
 }
Пример #13
0
  @Override
  public Stream<Entity> findAll(Query q) {
    if (q.getRules().isEmpty()) {
      return getEntities().stream();
    }

    if ((q.getRules().size() != 1) || (q.getRules().get(0).getOperator() != Operator.EQUALS)) {
      throw new MolgenisDataException("The only query allowed on this Repository is gene EQUALS");
    }

    String geneSymbol = (String) q.getRules().get(0).getValue();
    List<Entity> entities = getEntitiesByGeneSymbol().get(geneSymbol);

    return entities != null ? entities.stream() : Stream.empty();
  }
 private List<Location> locationsOfNewbornCells() {
   return liveCellLocations
       .stream()
       .flatMap(
           l1 ->
               liveCellLocations
                   .stream()
                   .flatMap(
                       l2 ->
                           liveCellLocations
                               .stream()
                               .flatMap(
                                   l3 ->
                                       areInNeighbourhoodOfSomeCell(l1, l2, l3)
                                           ? emptyLocationsWithLiveNeighboursInAllAndOnlyLocations(
                                               l1, l2, l3)
                                           : Stream.empty())))
       .collect(toList());
 }
Пример #15
0
  private Optional<Map<String, String>> variablesFor(String source) {
    List<Map<String, String>> satisfyingVars =
        sources
            .stream()
            .flatMap(
                s ->
                    s.variablesFor(source, potentials, Collections.emptyMap())
                        .map(Stream::of)
                        .orElse(Stream.empty()))
            .collect(Collectors.toList());

    if (satisfyingVars.isEmpty()) {
      return Optional.empty();
    }

    Map<String, String> allVariables = new HashMap<>();
    satisfyingVars.forEach(allVariables::putAll);
    return Optional.of(allVariables);
  }
Пример #16
0
  /**
   * Base solution is assumed to be satisfiable. if cacheQuads is empty and queryQuads is non-empty
   * the baseSolution is returned
   *
   * @param cacheQuads
   * @param queryQuads
   * @param baseSolution
   * @return
   */
  public static Stream<Map<Var, Var>> createSolutions(
      Collection<Quad> cacheQuads, Collection<Quad> queryQuads, Map<Var, Var> baseSolution) {
    Stream<Map<Var, Var>> result;

    if (cacheQuads.isEmpty() && !queryQuads.isEmpty()) {
      result = Stream.of(baseSolution);
    } else {
      TriFunction<Map<Var, Var>, Quad, Quad, Stream<Map<Var, Var>>> solutionCombiner =
          (s, a, b) -> {
            Stream<Map<Var, Var>> r;
            try {
              // HashBiMap<Var, Var> d = HashBiMap.create();
              Map<Var, Var> d = new HashMap<>();
              Map<Var, Var> contib = Utils2.createVarMap(a, b);

              d.putAll(contib);
              d.putAll(s);

              r = Stream.of(d);
            } catch (IllegalArgumentException e) {
              // Indicates inconsistent variable mapping
              r = Stream.empty();
            }

            return r;
          };

      result =
          StateCombinatoricCallback.createKPermutationsOfN(
                  cacheQuads, queryQuads, baseSolution, solutionCombiner)
              .map(stack -> stack.getValue().getSolution());
    }
    return result;

    //        Stream<Map<Var, Var>> result = IsoMapUtils.createSolutionStream(
    //                    cacheQuads,
    //                    queryQuads,
    //                    (a, b, c) -> Stream.of(Utils2.createVarMap(a, b)),
    //                    baseSolution);
    //
    //        return result;
  }
Пример #17
0
  private Stream<VirtualMachine> attach(VirtualMachineDescriptor vmDescriptor) {
    try {
      com.sun.tools.attach.VirtualMachine vm =
          com.sun.tools.attach.VirtualMachine.attach(vmDescriptor);
      String vmArgs = vm.getAgentProperties().getProperty(VM_ARGS);

      String id = vmDescriptor.id();
      String displayName = vmDescriptor.displayName();
      boolean agentLoaded = vmArgs.contains(AGENT_NAME);
      String userDir = getUserDir(vm);

      return Stream.of(new VirtualMachine(id, displayName, agentLoaded, userDir));
    } catch (AttachNotSupportedException e) {
      logger.warn(e.getMessage());
    } catch (IOException e) {
      if (!noSuchProcess(e)) {
        logger.warn(e.getMessage(), e);
      }
    }
    return Stream.empty();
  }
 @Test
 public void deleteStream() {
   Stream<Entity> entities = Stream.empty();
   entityListenerRepositoryDecorator.delete(entities);
   verify(decoratedRepository, times(1)).delete(entities);
 }
Пример #19
0
 @NotNull
 public static <T> Stream<T> toStream(@Nullable T... items) {
   return items == null ? Stream.empty() : Stream.of(items);
 }
Пример #20
0
  @Test
  public void collectEmptyNSArrayWhenStreamReturnsNoElements() throws Exception {
    NSArray<?> result = Stream.empty().collect(toNSArray());

    assertThat(result.isEmpty(), is(true));
  }
 @Test
 public void addStream() {
   Stream<Entity> entities = Stream.empty();
   when(decoratedRepository.add(entities)).thenReturn(Integer.valueOf(123));
   assertEquals(entityListenerRepositoryDecorator.add(entities), Integer.valueOf(123));
 }
Пример #22
0
 public Stream<Map.Entry<String, JsonValue>> entryStream() {
   return Stream.empty();
 }
Пример #23
0
 public Stream<JsonValue> valueStream() {
   return Stream.empty();
 }
Пример #24
0
 public Stream<String> keyStream() {
   return Stream.empty();
 }
Пример #25
0
 protected Stream<String> stringPathStream(String path) {
   return Stream.empty();
 }
Пример #26
0
 @NotNull
 public static <T> Stream<T> notNullize(@Nullable Stream<T> items) {
   return ObjectUtils.notNull(items, Stream.empty());
 }
 @Test(expected = NullPointerException.class)
 public void ctorThrowsIfNullArg() {
   newBuilder(null, Stream.empty());
 }
 private Stream<ElmReference> getReferencesInImport() {
   return this.getText().startsWith("Native.")
       ? Stream.empty()
       : Stream.of(new ElmFullPathModuleReference(this));
 }
Пример #29
0
 /**
  * Subclasses may override this method to provide objects that the {@link
  * #read(ResourceLocation...) read} method will return if no resource data can be found in all of
  * the specified resource locations.
  *
  * @return the fall-back objects to use.
  */
 public Stream<T> getFallback() {
   return Stream.empty();
 }
Пример #30
0
 /**
  * There probably could be some performance issues if there is lots of streams to concat. See
  * http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010659.html for some details.
  *
  * <p>Also see {@link Stream#concat(Stream, Stream)} documentation for other possible issues of
  * concatenating large number of streams.
  */
 @NotNull
 public static <T> Stream<T> concat(@NotNull Stream<T>... streams) {
   return toStream(streams).reduce(Stream.empty(), Stream::concat);
 }