List of usage examples for java.util Set isEmpty
boolean isEmpty();
From source file:hoot.services.models.osm.Node.java
/** * Returns the nodes specified in the collection of nodes IDs * * @param mapId/*from w ww . j a v a 2 s .c o m*/ * ID of the map the nodes belong to * @param nodeIds * a collection of node IDs * @param dbConn * JDBC Connection * @return a collection of node records */ static List<CurrentNodes> getNodes(long mapId, Set<Long> nodeIds, Connection dbConn) { // This seems redundant when compared to Element::getElementRecords if (!nodeIds.isEmpty()) { return new SQLQuery<>(dbConn, DbUtils.getConfiguration(mapId)).select(currentNodes).from(currentNodes) .where(currentNodes.id.in(nodeIds)).fetch(); } return new ArrayList<>(); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step4MTurkOutputCollector.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDirWithArgumentPairs = args[0]; File[] resultFiles;// ww w .j ava2 s. c om if (args[1].contains("*")) { File path = new File(args[1]); File directory = path.getParentFile(); String regex = path.getName().replaceAll("\\*", ""); List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { regex }, false)); resultFiles = new File[files.size()]; for (int i = 0; i < files.size(); i++) { resultFiles[i] = files.get(i); } } else { // result file is a comma-separated list of CSV files from MTurk String[] split = args[1].split(","); resultFiles = new File[split.length]; for (int i = 0; i < split.length; i++) { resultFiles[i] = new File(split[i]); } } File outputDir = new File(args[2]); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new IOException("Cannot create directory " + outputDir); } } // error if output folder not empty to prevent any confusion by mixing files if (!FileUtils.listFiles(outputDir, null, false).isEmpty()) { throw new IllegalArgumentException("Output dir " + outputDir + " is not empty"); } // collected assignments with empty reason for rejections Set<String> assignmentsWithEmptyReason = new HashSet<>(); // parse with first line as header MTurkOutputReader mTurkOutputReader = new MTurkOutputReader(resultFiles); Collection<File> files = FileUtils.listFiles(new File(inputDirWithArgumentPairs), new String[] { "xml" }, false); if (files.isEmpty()) { throw new IOException("No xml files found in " + inputDirWithArgumentPairs); } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Map<String, Integer>> assignmentsPerHits = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); String hitTypeId = record.get("hittypeid"); if (!wasRejected) { // update statistics if (!assignmentsPerHits.containsKey(hitTypeId)) { assignmentsPerHits.put(hitTypeId, new HashMap<String, Integer>()); } if (!assignmentsPerHits.get(hitTypeId).containsKey(hitID)) { assignmentsPerHits.get(hitTypeId).put(hitID, 0); } assignmentsPerHits.get(hitTypeId).put(hitID, assignmentsPerHits.get(hitTypeId).get(hitID) + 1); } } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Integer> approvedAssignmentsPerHit = new HashMap<>(); Map<String, Integer> rejectedAssignmentsPerHit = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean approved = "Approved".equals(record.get("assignmentstatus")); boolean rejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); if (approved) { // update statistics if (!approvedAssignmentsPerHit.containsKey(hitID)) { approvedAssignmentsPerHit.put(hitID, 0); } approvedAssignmentsPerHit.put(hitID, approvedAssignmentsPerHit.get(hitID) + 1); } else if (rejected) { // update statistics if (!rejectedAssignmentsPerHit.containsKey(hitID)) { rejectedAssignmentsPerHit.put(hitID, 0); } rejectedAssignmentsPerHit.put(hitID, rejectedAssignmentsPerHit.get(hitID) + 1); } else { throw new IllegalStateException( "Unknown state: " + record.get("assignmentstatus") + " HITID: " + hitID); } } // System.out.println("Approved: " + approvedAssignmentsPerHit); // System.out.println("Rejected: " + rejectedAssignmentsPerHit); System.out.println("Approved (values): " + new HashSet<>(approvedAssignmentsPerHit.values())); System.out.println("Rejected (values): " + new HashSet<>(rejectedAssignmentsPerHit.values())); // rejection statistics int totalRejected = 0; for (Map.Entry<String, Integer> rejectionEntry : rejectedAssignmentsPerHit.entrySet()) { totalRejected += rejectionEntry.getValue(); } System.out.println("Total rejections: " + totalRejected); /* // generate .success files for adding more annotations for (File resultFile : resultFiles) { String hitTypeID = mTurkOutputReader.getHitTypeIdForFile().get(resultFile); // assignments for that hittypeid (= file) Map<String, Integer> assignments = assignmentsPerHits.get(hitTypeID); prepareUpdateHITsFiles(assignments, hitTypeID, resultFile); } */ int totalSavedPairs = 0; // load all previously prepared argument pairs for (File file : files) { List<ArgumentPair> argumentPairs = (List<ArgumentPair>) XStreamTools.getXStream().fromXML(file); List<AnnotatedArgumentPair> annotatedArgumentPairs = new ArrayList<>(); for (ArgumentPair argumentPair : argumentPairs) { AnnotatedArgumentPair annotatedArgumentPair = new AnnotatedArgumentPair(argumentPair); // is there such an answer? String key = "Answer." + argumentPair.getId(); // iterate only if there is such column to save time if (mTurkOutputReader.getColumnNames().contains(key)) { // now find the results for (Map<String, String> record : mTurkOutputReader) { if (record.containsKey(key)) { // extract the values AnnotatedArgumentPair.MTurkAssignment assignment = new AnnotatedArgumentPair.MTurkAssignment(); boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); // only non-rejected (if required) if (!wasRejected) { String hitID = record.get("hitid"); String workerID = record.get("workerid"); String assignmentId = record.get("assignmentid"); try { assignment.setAssignmentAcceptTime( DATE_FORMAT.parse(record.get("assignmentaccepttime"))); assignment.setAssignmentSubmitTime( DATE_FORMAT.parse(record.get("assignmentsubmittime"))); assignment.setHitComment(record.get("Answer.feedback")); assignment.setHitID(hitID); assignment.setTurkID(workerID); assignment.setAssignmentId(assignmentId); // and answer specific fields String valueRaw = record.get(key); // so far the label has had format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only true label String label = valueRaw.split("_")[2]; assignment.setValue(label); String reason = record.get(key + "_reason"); // missing reason if (reason == null) { assignmentsWithEmptyReason.add(assignmentId); } else { assignment.setReason(reason); // get worker's stance String stanceRaw = record.get(key + "_stance"); if (stanceRaw != null) { // parse stance String stance = stanceRaw.split("_stance_")[1]; assignment.setWorkerStance(stance); } // we take maximal 5 assignments Collections.sort(annotatedArgumentPair.mTurkAssignments, new Comparator<AnnotatedArgumentPair.MTurkAssignment>() { @Override public int compare(AnnotatedArgumentPair.MTurkAssignment o1, AnnotatedArgumentPair.MTurkAssignment o2) { return o1.getAssignmentAcceptTime() .compareTo(o2.getAssignmentAcceptTime()); } }); if (annotatedArgumentPair.mTurkAssignments .size() < MAXIMUM_ASSIGNMENTS_PER_HIT) { annotatedArgumentPair.mTurkAssignments.add(assignment); } } } catch (IllegalArgumentException | NullPointerException ex) { System.err.println("Malformed annotations for HIT " + hitID + ", worker " + workerID + ", assignment " + assignmentId + "; " + ex.getMessage() + ", full record: " + record); } } } } } // and if there are some annotations, add it to the result set if (!annotatedArgumentPair.mTurkAssignments.isEmpty()) { annotatedArgumentPairs.add(annotatedArgumentPair); } } if (!annotatedArgumentPairs.isEmpty()) { File outputFile = new File(outputDir, file.getName()); XStreamTools.toXML(annotatedArgumentPairs, outputFile); System.out.println("Saved " + annotatedArgumentPairs.size() + " annotated pairs to " + outputFile); totalSavedPairs += annotatedArgumentPairs.size(); } } System.out.println("Total saved " + totalSavedPairs + " pairs"); // print assignments with empty reasons if (!assignmentsWithEmptyReason.isEmpty()) { System.out.println( "== Assignments with empty reason:\nassignmentIdToReject\tassignmentIdToRejectComment"); for (String assignmentId : assignmentsWithEmptyReason) { System.out.println( assignmentId + "\t\"Dear worker, you did not fill the required field with a reason.\""); } } }
From source file:com.delicious.deliciousfeeds4J.DeliciousUtil.java
public static Set<User> deserializeUsersFromJson(String json) throws Exception { logger.debug("Trying to deserialize JSON to Users..."); logger.trace("Deserializing JSON: " + json); //Check if empty or null if (json == null || json.isEmpty()) { logger.debug("Nothing to deserialize. JSON-string was empty!"); return null; }/*w w w . j a v a 2s. c om*/ //Actually deserialize final Set<User> users = ((Set<User>) objectMapper.readValue(json, new TypeReference<Set<User>>() { })); if (users == null || users.isEmpty()) { logger.debug("No users found. Collection was empty."); return null; } logger.info("Successfully deserialized {} users!", users.size()); return users; }
From source file:org.jclouds.demo.tweetstore.config.SpringServletConfig.java
private static Iterable<String> getBlobstoreContexts(Properties props) { Set<String> contexts = new CredentialsCollector().apply(props).keySet(); String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); if (explicitContexts != null) { contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); }//from ww w. j a v a 2 s . c o m checkState(!contexts.isEmpty(), "no credentials available for any requested context"); return contexts; }
From source file:com.taobao.android.builder.dependency.diff.DependencyCompareUtils.java
/** * ?//from ww w . j ava 2 s. co m * * @param baseDependencyJson * @param newDependencyJson * @return */ public static DependencyDiff diff(DependencyJson baseDependencyJson, DependencyJson newDependencyJson) { DependencyDiff diffResult = new DependencyDiff(); // 1. dex?remove?? List<String> baseMainDependecies = baseDependencyJson.getMainDex(); List<String> newMainDependecies = newDependencyJson.getMainDex(); diffResult.setMainDexDiffs(getDiffDependencies(baseMainDependecies, newMainDependecies)); if (!diffResult.getMainDexDiffs().isEmpty()) { for (String line : diffResult.getMainDexDiffs()) { diffResult.getMainDexDiffs().add(line); } logger.info("[Diff]MainBundle,Diff:" + StringUtils.join(diffResult.getMainDexDiffs(), ",")); } // 2. awb? Map<String, AwbDependency> baseAwbs = toAwbDependencies(baseDependencyJson.getAwbs()); Map<String, AwbDependency> newAwbs = toAwbDependencies(newDependencyJson.getAwbs()); Set<String> baseAwbBundles = new HashSet<String>(); for (String bundleName : newAwbs.keySet()) { AwbDependency newAwbDeps = newAwbs.get(bundleName); AwbDependency baseAwbDeps = baseAwbs.get(bundleName); if (null != baseAwbDeps) { if (baseAwbDeps.version.equals(newAwbDeps.version)) { Set<String> awbDiffs = getDiffDependencies(baseAwbDeps.dependencies, newAwbDeps.dependencies); if (!awbDiffs.isEmpty()) { System.out.println("[DiffAwb]" + bundleName + ",Diff:" + StringUtils.join(awbDiffs, ",")); diffResult.getAwbDiffs().add(bundleName); // ? diffResult.getModifyLines().add(bundleName + "(" + newAwbDeps.version + ")"); for (String awbDiff : awbDiffs) { diffResult.getModifyLines().add(" " + awbDiff); } } } else { logger.info("[DiffAwb]" + bundleName + ",baseVersion:" + baseAwbDeps.version + ",newVersion:" + newAwbDeps.version); // ? diffResult.getModifyLines() .add(bundleName + "(" + baseAwbDeps.version + "=>" + newAwbDeps.version + ")"); Set<String> awbDiffs = getDiffDependencies(baseAwbDeps.dependencies, newAwbDeps.dependencies); if (!awbDiffs.isEmpty()) { // ? for (String awbDiff : awbDiffs) { diffResult.getModifyLines().add(" " + awbDiff); } } diffResult.getAwbDiffs().add(bundleName); } } else { System.out.println("[NewAwb]" + bundleName + ",newVersion:" + newAwbs.get(bundleName).version); diffResult.getAwbDiffs().add(bundleName); diffResult.getNewAwbs().add(bundleName); diffResult.getModifyLines().add(bundleName + "(0=>" + newAwbDeps.version + ")"); // ?bundle if (!baseAwbBundles.contains(bundleName)) { diffResult.getNewAwbs().add(bundleName); } } } return diffResult; }
From source file:com.github.rinde.rinsim.scenario.measure.Metrics.java
static ImmutableList<Double> sum(long st, List<LoadPart> parts, int num) { checkArgument(num >= 1);/*from w ww .ja va 2s.c om*/ final ImmutableList.Builder<Double> builder = ImmutableList.builder(); long i = st; final Set<LoadPart> partSet = newLinkedHashSet(parts); while (!partSet.isEmpty()) { double currentLoadVal = 0d; final List<LoadPart> toRemove = newArrayList(); for (final LoadPart lp : partSet) { if (lp.isIn(i)) { currentLoadVal += lp.get(i); } if (!lp.isBeforeEnd(i)) { toRemove.add(lp); } } partSet.removeAll(toRemove); if (!partSet.isEmpty()) { if (num > 1) { currentLoadVal /= num; } builder.add(currentLoadVal); i++; } } return builder.build(); }
From source file:ca.uhn.fhir.rest.method.ElementsParameter.java
public static Set<String> getElementsValueOrNull(RequestDetails theRequest) { String[] summary = theRequest.getParameters().get(Constants.PARAM_ELEMENTS); if (summary != null && summary.length > 0) { Set<String> retVal = new HashSet<String>(); for (String next : summary) { StringTokenizer tok = new StringTokenizer(next, ","); while (tok.hasMoreTokens()) { String token = tok.nextToken(); if (isNotBlank(token)) { retVal.add(token);//from w w w . j a va 2s.c om } } } if (retVal.isEmpty()) { return null; } // Always include the meta element even for subsetted values retVal.add("meta"); return retVal; } else { return null; } }
From source file:annis.gui.ExampleQueriesPanel.java
/** * Loads the available example queries for a specific corpus. * * @param corpusNames Specifies the corpora example queries are fetched for. * If it is null or empty all available example queries are fetched. *///from w ww . j a va2 s . c om private static List<ExampleQuery> loadExamplesFromRemote(Set<String> corpusNames) { List<ExampleQuery> result = new LinkedList<>(); WebResource service = Helper.getAnnisWebResource(); try { if (corpusNames == null || corpusNames.isEmpty()) { result = service.path("query").path("corpora").path("example-queries") .get(new GenericType<List<ExampleQuery>>() { }); } else { String concatedCorpusNames = StringUtils.join(corpusNames, ","); result = service.path("query").path("corpora").path("example-queries") .queryParam("corpora", concatedCorpusNames).get(new GenericType<List<ExampleQuery>>() { }); } } catch (UniformInterfaceException ex) { // ignore } catch (ClientHandlerException ex) { log.error("problems with getting example queries from remote for {}", corpusNames, ex); } return result; }
From source file:com.netflix.genie.core.jpa.specifications.JpaCommandSpecs.java
/** * Get all the clusters given the specified parameters. * * @param applicationId The id of the application that is registered with these commands * @param statuses The status of the commands * @return The specification//from ww w . ja v a2 s .c o m */ public static Specification<CommandEntity> findCommandsForApplication(final String applicationId, final Set<CommandStatus> statuses) { return (final Root<CommandEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> { final List<Predicate> predicates = new ArrayList<>(); final Join<CommandEntity, ApplicationEntity> application = root.join(CommandEntity_.applications); predicates.add(cb.equal(application.get(ApplicationEntity_.id), applicationId)); if (statuses != null && !statuses.isEmpty()) { final List<Predicate> orPredicates = statuses.stream() .map(status -> cb.equal(root.get(CommandEntity_.status), status)) .collect(Collectors.toList()); predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; }
From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaClusterSpecs.java
/** * Get all the clusters given the specified parameters. * * @param commandId The id of the command that is registered with this cluster * @param statuses The status of the cluster * @return The specification/* www .j a v a 2 s. com*/ */ public static Specification<ClusterEntity> findClustersForCommand(final String commandId, @Nullable final Set<ClusterStatus> statuses) { return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> { final List<Predicate> predicates = new ArrayList<>(); final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands); predicates.add(cb.equal(commands.get(CommandEntity_.uniqueId), commandId)); if (statuses != null && !statuses.isEmpty()) { //Could optimize this as we know size could use native array predicates.add( cb.or(statuses.stream().map(status -> cb.equal(root.get(ClusterEntity_.status), status)) .toArray(Predicate[]::new))); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; }