Exemplo n.º 1
0
 @Override
 default int indexWhere(Predicate<? super T> predicate, int from) {
   Objects.requireNonNull(predicate, "predicate is null");
   int start = Math.max(from, 0);
   int n = start + segmentLength(predicate.negate(), start);
   return (n >= length()) ? -1 : n;
 }
  public static void main(String[] args) {
    List<Person> people = new TestDataFixture().getFakePeople();

    // Print males above 60
    System.out.println(filter(people, isMale.and(isOlderThan60)));

    // Print males OR person above 60
    System.out.println(filter(people, isMale.or(isOlderThan60)));

    // Print not males
    System.out.println(filter(people, isMale.negate()));
  }
  /**
   * Combine vcfs by from from ALL tumours. This is needed when generating the minibam for Normals
   * BAMs in a multi-tumour scenario.
   *
   * @param parents
   * @return
   */
  private Job combineVCFsByType(Job... parents) {
    PreprocessJobGenerator generator =
        new PreprocessJobGenerator(
            this.JSONlocation, this.JSONrepo, this.JSONfolderName, this.JSONfileName);
    List<VcfInfo> nonIndels =
        this.vcfs.stream().filter(p -> isIndel.negate().test(p)).collect(Collectors.toList());
    List<VcfInfo> indels = this.normalizedIndels.stream().collect(Collectors.toList());
    Consumer<VcfInfo> updateMergedVCFs = (v) -> this.mergedVcfs.add(v);
    Job vcfCombineJob =
        generator.combineVCFsByType(this, nonIndels, indels, updateMergedVCFs, parents);

    return vcfCombineJob;
  }
Exemplo n.º 4
0
/** Created by vishn_000 on 20.03.2014. */
public class Pred {

  // instead of TextUtils...
  public static Predicate<String> nonNull = s -> s != null;
  public static Predicate<String> emptyString = String::isEmpty;

  public static Predicate<String> combinePredicates = nonNull.and(emptyString.negate());

  public static void main(String[] args) {
    System.out.println(combinePredicates.test("test"));
    System.out.println(combinePredicates.test(""));
    System.out.println(combinePredicates.test(null));
  }
}
Exemplo n.º 5
0
 @Override
 default Seq<T> filterNot(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   return filter(predicate.negate());
 }
Exemplo n.º 6
0
 @Override
 default Seq<T> dropUntil(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   return dropWhile(predicate.negate());
 }
 public static <T> Predicate<T> not(Predicate<T> basePredicate) {
   return basePredicate.negate();
 }
Exemplo n.º 8
0
 @Override
 public Array<T> takeUntil(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   return takeWhile(predicate.negate());
 }
Exemplo n.º 9
0
 @Override
 public Tuple2<Array<T>, Array<T>> splitAt(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   final Array<T> init = takeWhile(predicate.negate());
   return Tuple.of(init, drop(init.length()));
 }
Exemplo n.º 10
0
 /**
  * Construct a stream which takes values from the source stream until one of them meets the
  * supplied condition, and then stops.
  *
  * @param source The source stream.
  * @param condition The condition to apply to elements of the source stream.
  * @param <T> The type over which the stream streams.
  * @return A condition-bounded stream.
  */
 public static <T> Stream<T> takeUntil(Stream<T> source, Predicate<T> condition) {
   return takeWhile(source, condition.negate());
 }
 /**
  * Returns a {@link Map} with every element for with the <code>predicate</code> provided returns
  * <code>false</code>. This is the opposite of {@link #findAll(Predicate)} / {@link
  * #filter(Predicate)}.
  */
 public default Collection<T> reject(Predicate<T> predicate) {
   return findAll(predicate.negate());
 }
public abstract class AbstractRestChannel implements RestChannel {

  private static final Predicate<String> INCLUDE_FILTER = f -> f.charAt(0) != '-';
  private static final Predicate<String> EXCLUDE_FILTER = INCLUDE_FILTER.negate();

  protected final RestRequest request;
  protected final boolean detailedErrorsEnabled;
  private final String format;
  private final String filterPath;
  private final boolean pretty;
  private final boolean human;

  private BytesStreamOutput bytesOut;

  protected AbstractRestChannel(RestRequest request, boolean detailedErrorsEnabled) {
    this.request = request;
    this.detailedErrorsEnabled = detailedErrorsEnabled;
    this.format = request.param("format", request.header("Accept"));
    this.filterPath = request.param("filter_path", null);
    this.pretty = request.paramAsBoolean("pretty", false);
    this.human = request.paramAsBoolean("human", false);
  }

  @Override
  public XContentBuilder newBuilder() throws IOException {
    return newBuilder(request.hasContent() ? request.content() : null, true);
  }

  @Override
  public XContentBuilder newErrorBuilder() throws IOException {
    // Disable filtering when building error responses
    return newBuilder(request.hasContent() ? request.content() : null, false);
  }

  @Override
  public XContentBuilder newBuilder(@Nullable BytesReference autoDetectSource, boolean useFiltering)
      throws IOException {
    XContentType contentType = XContentType.fromMediaTypeOrFormat(format);
    if (contentType == null) {
      // try and guess it from the auto detect source
      if (autoDetectSource != null) {
        contentType = XContentFactory.xContentType(autoDetectSource);
      }
    }
    if (contentType == null) {
      // default to JSON
      contentType = XContentType.JSON;
    }

    Set<String> includes = Collections.emptySet();
    Set<String> excludes = Collections.emptySet();
    if (useFiltering) {
      Set<String> filters = Strings.splitStringByCommaToSet(filterPath);
      includes = filters.stream().filter(INCLUDE_FILTER).collect(toSet());
      excludes = filters.stream().filter(EXCLUDE_FILTER).map(f -> f.substring(1)).collect(toSet());
    }

    XContentBuilder builder =
        new XContentBuilder(
            XContentFactory.xContent(contentType), bytesOutput(), includes, excludes);
    if (pretty) {
      builder.prettyPrint().lfAtEnd();
    }

    builder.humanReadable(human);
    return builder;
  }

  /** A channel level bytes output that can be reused. It gets reset on each call to this method. */
  @Override
  public final BytesStreamOutput bytesOutput() {
    if (bytesOut == null) {
      bytesOut = newBytesOutput();
    } else {
      bytesOut.reset();
    }
    return bytesOut;
  }

  protected BytesStreamOutput newBytesOutput() {
    return new BytesStreamOutput();
  }

  @Override
  public RestRequest request() {
    return this.request;
  }

  @Override
  public boolean detailedErrorsEnabled() {
    return detailedErrorsEnabled;
  }
}
public class World {
  public World evolve() {
    return new World(locationsOfSurvivingCells(), locationsOfNewbornCells());
  }

  // Creation Methods
  // ///////////////////////////////////////////////////////////////////////////////////////////

  public static World empty() {
    return new World();
  }

  public static World withCellsAt(Location... locations) {
    return new World(Arrays.asList(locations));
  }

  public static World withCellsAt(List<Location>... groupsOfLocations) {
    return new World(groupsOfLocations);
  }

  // Predicates
  // /////////////////////////////////////////////////////////////////////////////////////////////////

  public boolean hasLiveCellAt(Location location) {
    return liveCellLocations.contains(location);
  }

  public boolean isEmpty() {
    return liveCellLocations.isEmpty();
  }

  // Overridden Object methods
  // //////////////////////////////////////////////////////////////////////////////////

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    World world = (World) o;

    return liveCellLocations.equals(world.liveCellLocations);
  }

  @Override
  public int hashCode() {
    return liveCellLocations.hashCode();
  }

  @Override
  public String toString() {
    return toString(buildGridOfLocations());
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // Private
  // ////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

  // Member fields
  // //////////////////////////////////////////////////////////////////////////////////////////////
  private final HashSet<Location> liveCellLocations;

  // Constructors
  // ///////////////////////////////////////////////////////////////////////////////////////////////
  private World(List<Location>... groupsOfLocations) {

    liveCellLocations = new HashSet<>();

    stream(groupsOfLocations).flatMap(List::stream).forEach(liveCellLocations::add);
  }

  // Location of Surviving Cells
  // ////////////////////////////////////////////////////////////////////////////////

  private List<Location> locationsOfSurvivingCells() {
    return liveCellLocations.stream().filter(aCellWillSurviveAt).collect(toList());
  }

  private Predicate<Location> aCellWillSurviveAt =
      location -> NEIGHBOUR_COUNTS_ALLOWING_SURVIVAL.contains(countOfNeighbouringCellsAt(location));

  private long countOfNeighbouringCellsAt(Location location) {
    return neighboursOf(location).stream().filter(isPopulated).count();
  }

  // Locations of Newborn Cells
  // /////////////////////////////////////////////////////////////////////////////////

  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());
  }

  private boolean areInNeighbourhoodOfSomeCell(Location... locations) {
    return distinct(locations) && distantAtMostOneCell(locations);
  }

  private boolean distinct(Location... locations) {
    long numberOfLocations = locations.length;
    long numberOfDistinctLocations = stream(locations).distinct().count();
    return numberOfDistinctLocations == numberOfLocations;
  }

  private boolean distantAtMostOneCell(Location... locations) {
    return stream(locations)
        .allMatch(l1 -> stream(locations).allMatch(l2 -> l1.distanceFrom(l2) <= 2));
  }

  private Stream<Location> emptyLocationsWithLiveNeighboursInAllAndOnlyLocations(
      Location... locations) {
    return emptyLocationsThatAreSharedNeighboursOf(locations)
        .stream()
        .filter(hasNeighbouringLiveCellsInAllAndOnlyThese(locations));
  }

  private List<Location> emptyLocationsThatAreSharedNeighboursOf(Location[] locations) {
    return stream(locations)
        .map(emptyLocationsThatAreNeighboursOf)
        .reduce(intersection)
        .orElseGet(Collections::emptyList);
  }

  private Predicate<Location> isPopulated = this::hasLiveCellAt;
  private Predicate<Location> isNotPopulated = isPopulated.negate();

  private Function<Location, List<Location>> emptyLocationsThatAreNeighboursOf =
      location -> neighboursOf(location).stream().filter(isNotPopulated).collect(toList());

  private BinaryOperator<List<Location>> intersection =
      (xs, ys) -> xs.stream().filter(ys::contains).collect(toList());

  private Predicate<Location> hasNeighbouringLiveCellsInAllAndOnlyThese(Location... locations) {
    return location -> areTheSameLocations(liveNeighboursOf(location), locations);
  }

  private boolean areTheSameLocations(List<Location> locations, Location[] otherLocations) {
    Set<Location> setOne = new HashSet<>(locations);
    Set<Location> setTwo = stream(otherLocations).collect(toSet());
    return setOne.equals(setTwo);
  }

  private List<Location> liveNeighboursOf(Location location) {
    return neighboursOf(location).stream().filter(isPopulated).collect(toList());
  }

  private List<Location> neighboursOf(Location location) {
    return asList(
        location.northWest(),
        location.north(),
        location.northEast(),
        location.west(), /*  location  */
        location.east(),
        location.southWest(),
        location.south(),
        location.southEast());
  }

  // Displaying Worlds
  // ///////////////////////////////////////////////////////////////////////////////////////////////

  private String toString(List<List<Location>> grid) {
    return grid.stream().map(convertRowOfLocationsToString).collect(joining());
  }

  private Function<List<Location>, String> convertRowOfLocationsToString =
      row ->
          row.stream()
              .map(location -> liveCellPresentAt(location) ? "O" : "_")
              .collect(joining(NO_DELIMITER, NO_PREFIX, NEWLINE_SUFFIX));

  private boolean liveCellPresentAt(Location location) {
    return hasLiveCellAt(location);
  }

  private List<List<Location>> buildGridOfLocations() {
    List<Location> northMostFirst = liveCellLocations.stream().sorted().collect(toList());
    Location northMost = northMostFirst.get(0);
    Location southMost = northMostFirst.get(northMostFirst.size() - 1);

    List<Location> westMostFirst =
        liveCellLocations.stream().sorted(byWestMostFirst).collect(toList());
    Location westMost = westMostFirst.get(0);
    Location eastMost = westMostFirst.get(westMostFirst.size() - 1);

    Location topLeft = getTopLeft(northMost, westMost);
    Location topRight = getTopRight(northMost, eastMost);
    Location bottomLeft = getBottomLeft(northMost, southMost);

    List<Location> topRow = topRowWith(topLeft, topRight);

    return gridWith(topRow, topLeft, bottomLeft);
  }

  private static final Comparator<? super Location> byWestMostFirst =
      (aLocation, anotherLocation) ->
          aLocation.isWestOf(anotherLocation) ? -1 : (aLocation.isEastOf(anotherLocation) ? 1 : 0);

  private static final Location getBottomLeft(Location northMost, Location southMost) {
    return Stream.iterate(northMost, Location::south)
        .filter(location -> !southMost.isSouthOf(location))
        .findFirst()
        .get();
  }

  private static final Location getTopRight(Location northMost, Location eastMost) {
    return Stream.iterate(northMost, Location::east)
        .filter(location -> !eastMost.isEastOf(location))
        .findFirst()
        .get();
  }

  private static final Location getTopLeft(Location northMost, Location westMost) {
    return Stream.iterate(northMost, Location::west)
        .filter(location -> !westMost.isWestOf(location))
        .findFirst()
        .get();
  }

  private static final List<List<Location>> gridWith(
      List<Location> topRow, Location topLeft, Location bottomLeft) {
    int rowCount = topLeft.equals(bottomLeft) ? 1 : topLeft.distanceFrom(bottomLeft) + 1;
    return Stream.iterate(topRow, row -> row.stream().map(Location::south).collect(toList()))
        .limit(rowCount)
        .collect(toList());
  }

  private static final List<Location> topRowWith(Location topLeft, Location topRight) {
    int columnCount = topLeft.equals(topRight) ? 1 : topLeft.distanceFrom(topRight) + 1;
    return Stream.iterate(topLeft, Location::east).limit(columnCount).collect(toList());
  }

  // Constants
  // //////////////////////////////////////////////////////////////////////////////////////////////////

  private static final List<Long> NEIGHBOUR_COUNTS_ALLOWING_SURVIVAL = asList(2L, 3L);
  private static final String NEWLINE_SUFFIX = System.getProperty("line.separator");
  private static final String NO_PREFIX = "";
  private static final String NO_DELIMITER = "";
}
  /**
   * This method returns a stream of RDF triples associated with this target resource
   *
   * @param limit is the number of child resources returned in the response, -1 for all
   * @return {@link RdfStream}
   */
  protected RdfStream getResourceTriples(final int limit) {
    // use the thing described, not the description, for the subject of descriptive triples
    if (resource() instanceof NonRdfSourceDescription) {
      resource = ((NonRdfSourceDescription) resource()).getDescribedResource();
    }
    final PreferTag returnPreference;

    if (prefer != null && prefer.hasReturn()) {
      returnPreference = prefer.getReturn();
    } else if (prefer != null && prefer.hasHandling()) {
      returnPreference = prefer.getHandling();
    } else {
      returnPreference = PreferTag.emptyTag();
    }

    final LdpPreferTag ldpPreferences = new LdpPreferTag(returnPreference);

    final RdfStream rdfStream = new RdfStream();

    final Predicate<Triple> tripleFilter =
        ldpPreferences.prefersServerManaged() ? x -> true : IS_MANAGED_TRIPLE.negate();

    if (ldpPreferences.prefersServerManaged()) {
      rdfStream.concat(getTriples(LdpRdfContext.class));
    }

    rdfStream.concat(filter(getTriples(TypeRdfContext.class), tripleFilter::test));

    rdfStream.concat(filter(getTriples(PropertiesRdfContext.class), tripleFilter::test));

    if (!returnPreference.getValue().equals("minimal")) {

      // Additional server-managed triples about this resource
      if (ldpPreferences.prefersServerManaged()) {
        rdfStream.concat(getTriples(AclRdfContext.class));
        rdfStream.concat(getTriples(RootRdfContext.class));
        rdfStream.concat(getTriples(ContentRdfContext.class));
        rdfStream.concat(getTriples(ParentRdfContext.class));
      }

      // containment triples about this resource
      if (ldpPreferences.prefersContainment()) {
        rdfStream.concat(getTriples(ChildrenRdfContext.class).limit(limit));
      }

      // LDP container membership triples for this resource
      if (ldpPreferences.prefersMembership()) {
        rdfStream.concat(getTriples(LdpContainerRdfContext.class));
        rdfStream.concat(getTriples(LdpIsMemberOfRdfContext.class));
      }

      // Embed all hash and blank nodes
      // using IS_MANAGED_TRIPLE directly to avoid Prefer header logic (we never want them for hash
      // fragments)
      rdfStream.concat(filter(getTriples(HashRdfContext.class), IS_MANAGED_TRIPLE.negate()::test));
      rdfStream.concat(filter(getTriples(SkolemNodeRdfContext.class), tripleFilter::test));

      // Include inbound references to this object
      if (ldpPreferences.prefersReferences()) {
        rdfStream.concat(getTriples(ReferencesRdfContext.class));
      }

      // Embed the children of this object
      if (ldpPreferences.prefersEmbed()) {

        final Iterator<FedoraResource> children = resource().getChildren();

        rdfStream.concat(
            filter(
                concat(
                    transform(
                        children,
                        child ->
                            child.getTriples(
                                translator(),
                                ImmutableList.of(
                                    TypeRdfContext.class,
                                    PropertiesRdfContext.class,
                                    SkolemNodeRdfContext.class)))),
                tripleFilter::test));
      }
    }

    if (httpTripleUtil != null && ldpPreferences.prefersServerManaged()) {
      httpTripleUtil.addHttpComponentModelsForResourceToStream(
          rdfStream, resource(), uriInfo, translator());
    }

    return rdfStream;
  }
Exemplo n.º 15
0
 public static <T> Predicate<T> not(Predicate<T> methodRef) {
   return methodRef.negate();
 }
Exemplo n.º 16
0
 @Override
 public FilterIterator<T> filterDrop(final Predicate<T> f) {
   return new FilterIterator<>(f.negate(), this);
 }
Exemplo n.º 17
0
  @RequestMapping("/events/{eventName}/export.csv")
  public void downloadAllTicketsCSV(
      @PathVariable("eventName") String eventName,
      HttpServletRequest request,
      HttpServletResponse response,
      Principal principal)
      throws IOException {
    List<String> fields =
        Arrays.asList(
            Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
    Event event = loadEvent(eventName, principal);
    Map<Integer, TicketCategory> categoriesMap =
        eventManager
            .loadTicketCategories(event)
            .stream()
            .collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
    ZoneId eventZoneId = event.getZoneId();

    Predicate<String> contains = FIXED_FIELDS::contains;

    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv");

    try (ServletOutputStream out = response.getOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {

      for (int marker :
          BOM_MARKERS) { // UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks
                         // to alexr http://stackoverflow.com/a/4192897
        out.write(marker);
      }

      writer.writeNext(fields.toArray(new String[fields.size()]));

      eventManager
          .findAllConfirmedTickets(eventName, principal.getName())
          .stream()
          .map(
              t -> {
                List<String> line = new ArrayList<>();
                if (fields.contains("ID")) {
                  line.add(t.getUuid());
                }
                if (fields.contains("creation")) {
                  line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
                }
                if (fields.contains("category")) {
                  line.add(categoriesMap.get(t.getCategoryId()).getName());
                }
                if (fields.contains("event")) {
                  line.add(eventName);
                }
                if (fields.contains("status")) {
                  line.add(t.getStatus().toString());
                }
                if (fields.contains("originalPrice")) {
                  line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
                }
                if (fields.contains("paidPrice")) {
                  line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
                }
                if (fields.contains("discount")) {
                  line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
                }
                if (fields.contains("vat")) {
                  line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
                }
                if (fields.contains("reservationID")) {
                  line.add(t.getTicketsReservationId());
                }
                if (fields.contains("Full Name")) {
                  line.add(t.getFullName());
                }
                if (fields.contains("First Name")) {
                  line.add(t.getFirstName());
                }
                if (fields.contains("Last Name")) {
                  line.add(t.getLastName());
                }
                if (fields.contains("E-Mail")) {
                  line.add(t.getEmail());
                }
                if (fields.contains("locked")) {
                  line.add(String.valueOf(t.getLockedAssignment()));
                }
                if (fields.contains("Language")) {
                  line.add(String.valueOf(t.getUserLanguage()));
                }

                // obviously not optimized
                Map<String, String> additionalValues =
                    ticketFieldRepository.findAllValuesForTicketId(t.getId());

                fields
                    .stream()
                    .filter(contains.negate())
                    .forEachOrdered(
                        field -> {
                          line.add(additionalValues.getOrDefault(field, "").replaceAll("\"", ""));
                        });

                return line.toArray(new String[line.size()]);
              })
          .forEachOrdered(writer::writeNext);
      writer.flush();
      out.flush();
    }
  }