List of usage examples for java.util.function Predicate negate
default Predicate<T> negate()
From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java
private boolean hillClimbing(SolutionPerJob solPerJob, Technology technology) { boolean success = false; Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); if (maybeResult.isPresent()) { success = true;//from w ww . j a v a2 s .com PerformanceSolver currentSolver = dataProcessor.getPerformanceSolver(); Function<Double, Double> fromResult = currentSolver.transformationFromSolverResult(solPerJob, technology); Predicate<Double> feasibilityCheck = currentSolver.feasibilityCheck(solPerJob, technology); Consumer<Double> metricUpdater = currentSolver.metricUpdater(solPerJob, technology); final double tolerance = settings.getOptimization().getTolerance(); BiPredicate<Double, Double> incrementCheck; Function<Integer, Integer> updateFunction; Predicate<Double> stoppingCondition; Predicate<Integer> vmCheck; double responseTime = fromResult.apply(maybeResult.get()); if (feasibilityCheck.test(responseTime)) { updateFunction = n -> n - 1; stoppingCondition = feasibilityCheck.negate(); vmCheck = n -> n == 1; incrementCheck = (prev, curr) -> false; } else { updateFunction = n -> n + 1; stoppingCondition = feasibilityCheck; vmCheck = n -> false; incrementCheck = (prev, curr) -> Math.abs((prev - curr) / prev) < tolerance; } List<Triple<Integer, Optional<Double>, Boolean>> resultsList = alterUntilBreakPoint(solPerJob, updateFunction, fromResult, feasibilityCheck, stoppingCondition, incrementCheck, vmCheck); Optional<Triple<Integer, Optional<Double>, Boolean>> result = resultsList.parallelStream() .filter(t -> t.getRight() && t.getMiddle().isPresent()) .min(Comparator.comparing(Triple::getLeft)); result.ifPresent(triple -> triple.getMiddle().ifPresent(output -> { int nVM = triple.getLeft(); switch (technology) { case HADOOP: case SPARK: solPerJob.setThroughput(output); break; case STORM: break; default: throw new RuntimeException("Unexpected technology"); } solPerJob.updateNumberVM(nVM); double metric = fromResult.apply(output); metricUpdater.accept(metric); logger.info(String.format( "class%s-> MakeFeasible ended, result = %f, other metric = %f, obtained with: %d VMs", solPerJob.getId(), output, metric, nVM)); })); } else { logger.info("class" + solPerJob.getId() + "-> MakeFeasible ended with ERROR"); solPerJob.setFeasible(false); } return success; }
From source file:com.github.horrorho.liquiddonkey.cloud.Looter.java
void snapshot(HttpClient client, Core core, HttpAgent agent, Backup backup, int id) throws BadDataException, IOException, InterruptedException { boolean toReport = config.debug().toReport(); Path path = config.file().base().resolve(backup.backupUDID()).resolve(config.file().reportsDirectory()); Predicate<ICloud.MBSFile> nonUndecryptableFilter = file -> !file.getAttributes().hasEncryptionKey() || backup.keyBagManager().fileKey(file) != null; // Retrieve file list. int limit = config.client().listLimit(); Snapshot snapshot = agent// w w w .j a v a 2 s .c o m .execute((c, mmeAuthToken) -> Snapshots.from(c, core, mmeAuthToken, backup, id, limit)); if (snapshot == null) { logger.warn("-- snapshot() > snapshot not found: {}", id); return; } ICloud.MBSSnapshotAttributes attr = snapshot.mbsSnapshot().getAttributes(); logger.info("-- snapshot() > files: {}", snapshot.filesCount()); std.println(); std.println( "Retrieving snapshot: " + id + " (" + attr.getDeviceName() + " " + attr.getProductVersion() + ")"); // Total files. std.println("Files(total): " + snapshot.filesCount()); if (toReport) { csvWriter.files(sorted(snapshot), path.resolve("snapshot_" + id + "_files.csv")); } // Mode summary. Map<Mode, Long> modes = snapshot.files().stream() .collect(Collectors.groupingBy(Mode::mode, Collectors.counting())); logger.info("-- snapshot() > modes: {}", modes); // Non-empty files filter. snapshot = Snapshots.from(snapshot, file -> file.getSize() != 0 && file.hasSignature()); logger.info("-- snapshot() > filtered non empty, remaining: {}", snapshot.filesCount()); std.println("Files(non-empty): " + snapshot.filesCount()); // User filter snapshot = Snapshots.from(snapshot, filter); logger.info("-- snapshot() > filtered configured, remaining: {}", snapshot.filesCount()); std.println("Files(filtered): " + snapshot.filesCount()); if (toReport) { csvWriter.files(sorted(snapshot), path.resolve("snapshot_" + id + "_filtered.csv")); } // Undecryptable filter Snapshot undecryptable = Snapshots.from(snapshot, nonUndecryptableFilter.negate()); snapshot = Snapshots.from(snapshot, nonUndecryptableFilter); logger.info("-- snapshot() > filtered undecryptable, remaining: {}", snapshot.filesCount()); std.println("Files(non-undecryptable): " + snapshot.filesCount()); // Dump undecryptables // Map<ICloud.MBSFile, Outcome> undecryptableOutcomes = undecryptables.stream() // .collect(Collectors.toMap(Function.identity(), file -> Outcome.FAILED_DECRYPT_NO_KEY)); // outcomesConsumer.accept(undecryptableOutcomes); if (toReport) { csvWriter.files(sorted(undecryptable), path.resolve("snapshot_" + id + "_undecryptable.csv")); } // Local filter if (config.engine().toForceOverwrite()) { logger.debug("-- snapshot() > forced overwrite"); } else { long a = System.currentTimeMillis(); snapshot = LocalFileFilter.from(snapshot, config.file()).apply(snapshot); long b = System.currentTimeMillis(); logger.info("-- snapshot() > filtered local, remaining: {} delay(ms): {}", snapshot.filesCount(), b - a); std.println("Files(non-local): " + snapshot.filesCount()); } if (snapshot.filesCount() == 0) { return; } // Retrieve Outcomes outcomes = Outcomes.create(); OutcomesProgressPercentage progress = OutcomesProgressPercentage.from(snapshot, std); Consumer<Map<ICloud.MBSFile, Outcome>> outcomesConsumer = outcomes.andThen(progress); std.println(); std.println("Retrieving: " + Bytes.humanize(progress.totalBytes())); // Fetch files SnapshotDownloader.from(config.engine(), config.file()).download(agent, core, snapshot, outcomesConsumer); std.println(); std.println("Completed:"); outcomes.print(std); std.println(); }
From source file:alfio.controller.api.admin.EventApiController.java
@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);/*from w ww . j a va2 s. c o m*/ } writer.writeNext(fields.stream().map(f -> { if (f.startsWith(CUSTOM_FIELDS_PREFIX)) { return f.substring(CUSTOM_FIELDS_PREFIX.length()); } return f; }).toArray(String[]::new)); eventManager.findAllConfirmedTicketsForCSV(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())); } if (fields.contains("Confirmation")) { line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId) .toString()); } if (fields.contains("Billing Address")) { line.add(t.getTicketReservation().getBillingAddress()); } //obviously not optimized Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId()); fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)) .forEachOrdered(field -> { String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length()); line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", "")); }); return line.toArray(new String[line.size()]); }).forEachOrdered(writer::writeNext); writer.flush(); out.flush(); } }
From source file:org.apache.lens.cube.parse.SegmentationCandidate.java
private static <T> Predicate<T> not(Predicate<T> predicate) { return predicate.negate(); }
From source file:org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptorTest.java
public long filterPopulation(QueryResult<Variant> queryResult, Predicate<Variant> filterVariants, Predicate<Map<String, PopulationFrequency>> predicate) { queryResult.getResult().forEach(variant -> { assertNotNull(variant);// w ww. ja v a 2s. c o m assertNotNull("In " + variant, variant.getAnnotation()); // assertNotNull("In " + variant, variant.getAnnotation().getPopulationFrequencies()); }); Set<String> expectedVariants = allVariants.getResult().stream() .filter(filterVariants.and(variant -> variant.getAnnotation() != null)).filter(variant -> { Map<String, PopulationFrequency> map; if (variant.getAnnotation().getPopulationFrequencies() == null) { map = Collections.emptyMap(); } else { map = new HashMap<>(); for (PopulationFrequency p : variant.getAnnotation().getPopulationFrequencies()) { map.put(p.getStudy() + ":" + p.getPopulation(), p); } } return predicate.test(map); }).map(Variant::toString).collect(Collectors.toSet()); assertTrue("Expect to get at least one result", expectedVariants.size() > 0); for (String variant : expectedVariants) { Set<String> result = queryResult.getResult().stream().map(Variant::toString) .collect(Collectors.toSet()); if (!result.contains(variant)) { System.out.println("variant missing = " + variant); } } for (Variant variant : queryResult.getResult()) { if (!expectedVariants.contains(variant.toString())) { System.out.println("variant not suppose to be = " + variant); } } assertEquals(expectedVariants.size(), queryResult.getNumResults()); long count = queryResult.getResult().stream().map(variant -> { Map<String, PopulationFrequency> map; if (variant.getAnnotation().getPopulationFrequencies() == null) { map = Collections.emptyMap(); } else { map = new HashMap<>(); for (PopulationFrequency p : variant.getAnnotation().getPopulationFrequencies()) { map.put(p.getStudy() + ":" + p.getPopulation(), p); } } return map; }).filter(predicate.negate()).count(); assertEquals(0, count); return count; }
From source file:org.talend.tql.bean.BeanPredicateVisitor.java
@Override public Predicate<T> visit(NotExpression notExpression) { final Predicate<T> accept = notExpression.getExpression().accept(this); return accept.negate(); }