List of usage examples for java.util Set addAll
boolean addAll(Collection<? extends E> c);
From source file:hrytsenko.csv.IO.java
/** * Saves records into CSV file.//from w w w.j a va 2 s.c o m * * <p> * If file already exists, then it will be overridden. * * @param args * the named arguments {@link IO}. * * @throws IOException * if file could not be written. */ public static void save(Map<String, ?> args) throws IOException { Path path = getPath(args); LOGGER.info("Save: {}.", path.getFileName()); @SuppressWarnings("unchecked") Collection<Record> records = (Collection<Record>) args.get("records"); if (records.isEmpty()) { LOGGER.info("No records to save."); return; } try (Writer dataWriter = newBufferedWriter(path, getCharset(args), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { Set<String> columns = new LinkedHashSet<>(); List<Map<String, String>> rows = new ArrayList<>(); for (Record record : records) { Map<String, String> values = record.values(); columns.addAll(values.keySet()); rows.add(values); } CsvSchema.Builder csvSchema = getSchema(args).setUseHeader(true); for (String column : columns) { csvSchema.addColumn(column); } CsvMapper csvMapper = new CsvMapper(); ObjectWriter csvWriter = csvMapper.writer().withSchema(csvSchema.build()); csvWriter.writeValue(dataWriter, rows); } }
From source file:com.jaredrummler.android.devices.Main.java
private static void writeJavaSwitchStatement(List<String[]> devices) throws IOException { StringBuilder sb = new StringBuilder(); Map<String, Set<String>> deviceMap = new TreeMap<>((o1, o2) -> { return o1.compareToIgnoreCase(o2); });//from w w w . j a v a 2s . co m for (String name : POPULAR_DEVICES) { List<String> list = new ArrayList<>(); Set<String> codenames = new HashSet<>(); devices.stream().filter(arr -> arr[1].equals(name)).forEach(arr -> { list.add(arr[2]); }); Collections.sort(list); codenames.addAll(list); deviceMap.put(name, codenames); } // TODO: Use JavaPoet and create a working class. sb.append("public static String getDeviceName(String codename, String fallback) {\n"); sb.append(" switch (codename) {\n"); for (Map.Entry<String, Set<String>> entry : deviceMap.entrySet()) { Set<String> codenames = entry.getValue(); for (String codename : codenames) { sb.append(" case \"" + codename + "\":\n"); } sb.append(" return \"" + entry.getKey() + "\";\n"); } sb.append(" default:\n"); sb.append(" return fallback;\n\t}\n}"); System.out.println(sb.toString()); new File("json").mkdirs(); FileUtils.write(new File("json/gist.txt"), sb.toString()); }
From source file:edu.stanford.muse.lens.Lens.java
/** gets details from index for the given term */ public static JSONObject detailsForTerm(String term, float pageScore, Archive archive, AddressBook ab, String baseURL, Collection<EmailDocument> allDocs) throws JSONException, IOException, GeneralSecurityException { if (term.length() <= 2) return null; term = JSPHelper.convertRequestParamToUTF8(term); JSONObject json = new JSONObject(); json.put("text", term); json.put("pageScore", pageScore); int NAME_IN_ADDRESS_BOOK_WEIGHT = 100; // look up term in 2 places -- AB and in the index List<EmailDocument> docsForNameInAddressBook = (List) IndexUtils.selectDocsByPersonsAsList(ab, allDocs, new String[] { term }); List<EmailDocument> docsForTerm = (List) new ArrayList<Document>( archive.docsForQuery("\"" + term + "\"", -1, Indexer.QueryType.FULL)); // weigh any docs for name in addressbook hugely more! double termScore = docsForNameInAddressBook.size() * NAME_IN_ADDRESS_BOOK_WEIGHT + docsForTerm.size(); json.put("indexScore", termScore); Set<EmailDocument> finalDocSet = new LinkedHashSet<EmailDocument>(); finalDocSet.addAll(docsForNameInAddressBook); finalDocSet.addAll(docsForTerm);/*w ww. jav a 2s . com*/ List<EmailDocument> finalDocList = new ArrayList<EmailDocument>(finalDocSet); json.put("nMessages", finalDocList.size()); // score people Map<String, Float> peopleScores = new LinkedHashMap<String, Float>(); for (EmailDocument ed : finalDocSet) { Collection<String> addrs = ed.getParticipatingAddrsExcept(ab.getOwnAddrs()); for (String s : addrs) { if ("user".equals(s)) continue; float weight = 1.0f / addrs.size(); // weight = 1/size String c = ab.getCanonicalAddr(s); Float F = peopleScores.get(c); if (F == null) peopleScores.put(c, weight); else peopleScores.put(c, F + weight); } } // add the top people int MAX_PEOPLE = 5; List<Pair<String, Float>> pairs = Util.sortMapByValue(peopleScores); JSONArray people = new JSONArray(); Contact own = ab.getContactForSelf(); int count = 0; for (Pair<String, Float> p : pairs) { if (count > MAX_PEOPLE) break; JSONObject person = new JSONObject(); String email = p.getFirst(); String displayName = email; Contact c = ab.lookupByEmail(email); if (c != null) displayName = c.pickBestName(); if (c == own) continue; // ignore own name person.put("person", displayName); person.put("score", p.getSecond()); people.put(count, person); count++; } json.put("people", people); if (finalDocList.size() > 0 && log.isDebugEnabled()) log.debug("Term: " + term + " content hits: " + docsForTerm.size() + " header hits: " + docsForNameInAddressBook.size() + " total: " + finalDocList.size()); String url = baseURL + "/browse?term=\"" + term + "\""; json.put("url", url); JSONArray messages = new JSONArray(); // put up to 5 teasers in the json response int N_TEASERS = 5; for (int i = 0; i < finalDocList.size() && i < N_TEASERS; i++) { JSONObject message = finalDocList.get(i).toJSON(0); messages.put(i, message); } json.put("messages", messages); return json; }
From source file:edu.usu.sdl.openstorefront.common.util.StringProcessor.java
public static String cleanFileName(String badFileName) { if (StringUtils.isNotBlank(badFileName)) { List<Integer> bads = Arrays.asList(34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47); Set<Integer> badChars = new HashSet<>(); badChars.addAll(bads); StringBuilder cleanName = new StringBuilder(); for (int i = 0; i < badFileName.length(); i++) { int c = (int) badFileName.charAt(i); if (badChars.contains(c) == false) { cleanName.append((char) c); }//ww w . ja va2 s. c o m } return cleanName.toString(); } return badFileName; }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesCacheDataConverter.java
public static CacheData mergeCacheData(CacheData current, CacheData added) { String id = current.getId();// ww w .j a v a2 s . com Map<String, Object> attributes = new HashMap<>(); attributes.putAll(added.getAttributes()); attributes.putAll(current.getAttributes()); // Behavior is: if no ttl is set on either, the merged key won't expire int ttl = Math.min(current.getTtlSeconds(), added.getTtlSeconds()); Map<String, Collection<String>> relationships = new HashMap<>(); relationships.putAll(current.getRelationships()); added.getRelationships().entrySet() .forEach(entry -> relationships.merge(entry.getKey(), entry.getValue(), (a, b) -> { Set<String> result = new HashSet<>(); result.addAll(a); result.addAll(b); return result; })); return new DefaultCacheData(id, ttl, attributes, relationships); }
From source file:com.metamx.druid.merger.common.task.MergeTask.java
private static DataSegment computeMergedSegment(final String dataSource, final String version, final List<DataSegment> segments) { final Interval mergedInterval = computeMergedInterval(segments); final Set<String> mergedDimensions = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER); final Set<String> mergedMetrics = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER); for (DataSegment segment : segments) { mergedDimensions.addAll(segment.getDimensions()); mergedMetrics.addAll(segment.getMetrics()); }//from w ww .j a v a2 s . c o m return DataSegment.builder().dataSource(dataSource).interval(mergedInterval).version(version) .shardSpec(new NoneShardSpec()).dimensions(Lists.newArrayList(mergedDimensions)) .metrics(Lists.newArrayList(mergedMetrics)).build(); }
From source file:net.lldp.checksims.algorithm.similaritymatrix.SimilarityMatrix.java
/** * Generate a Similarity Matrix with archive submissions. * * The result is not a square matrix. Only the input submissions are on the X axis, but the Y axis contains both * input and archive submissions.//from w ww.j a va 2 s . c o m * * @param inputSubmissions Submissions used to generate matrix * @param archiveSubmissions Archive submissions - only compared to input submissions, not to each other * @param results Results used to build matrix * @return Similarity matrix built from given results * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input */ public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions, Set<Submission> archiveSubmissions, Set<AlgorithmResults> results) throws InternalAlgorithmError { checkNotNull(inputSubmissions); checkNotNull(archiveSubmissions); checkNotNull(results); checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from"); checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!"); Set<Submission> setOfBoth = new HashSet<>(); setOfBoth.addAll(inputSubmissions); setOfBoth.addAll(archiveSubmissions); checkArgument(setOfBoth.size() == (archiveSubmissions.size() + inputSubmissions.size()), "Some submissions were found in both archive and input submissions!"); // If there are no archive submissions, just generate using the other function if (archiveSubmissions.isEmpty()) { return generateMatrix(inputSubmissions, results); } List<Submission> xSubmissions = Ordering.natural().immutableSortedCopy(inputSubmissions); List<Submission> ySubmissions = new ArrayList<>(); ySubmissions.addAll(Ordering.natural().immutableSortedCopy(inputSubmissions)); ySubmissions.addAll(Ordering.natural().immutableSortedCopy(archiveSubmissions)); AlgorithmResults[][] matrix = new AlgorithmResults[xSubmissions.size()][ySubmissions.size()]; // Generate the matrix // First, handle identical submissions for (Submission xSub : xSubmissions) { // Get the X index int xIndex = xSubmissions.indexOf(xSub); int yIndex = ySubmissions.indexOf(xSub); matrix[xIndex][yIndex] = new AlgorithmResults(Pair.of(xSub, xSub), Real.ONE, Real.ONE); } // Now iterate through all given algorithm results for (AlgorithmResults result : results) { int aXCoord = xSubmissions.indexOf(result.a); int bXCoord = xSubmissions.indexOf(result.b); if (aXCoord == -1 && bXCoord == -1) { throw new InternalAlgorithmError("Neither submission \"" + result.a.getName() + "\" nor \"" + result.b.getName() + "\" were found in input submissions!"); } if (aXCoord != -1) { int bYCoord = ySubmissions.indexOf(result.b); matrix[aXCoord][bYCoord] = result.inverse(); } if (bXCoord != -1) { int aYCoord = ySubmissions.indexOf(result.a); matrix[bXCoord][aYCoord] = result; } } // Verification pass - ensure we built a matrix with no nulls for (int x = 0; x < xSubmissions.size(); x++) { for (int y = 0; y < ySubmissions.size(); y++) { if (matrix[x][y] == null) { throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \"" + xSubmissions.get(x).getName() + "\" and \"" + ySubmissions.get(y).getName() + "\""); } } } return new SimilarityMatrix(matrix, xSubmissions, ySubmissions, results); }
From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.options.RequestChecksumGeneratorOptions.java
public static Set<String> getPaths(SlingHttpServletRequest request) throws IOException { Set<String> paths = new HashSet<String>(); // Add Paths/*from w ww . j a va 2 s. com*/ if (request.getParameterValues(PATHS) != null) { String[] pathArr = request.getParameterValues(PATHS); for (String path : pathArr) { if (path.length() > 0) { paths.add(path); } } } paths.addAll(getPathsFromQuery(request.getResourceResolver(), request.getParameter(QUERY_TYPE), request.getParameter(QUERY))); RequestParameter data = request.getRequestParameter(DATA); if (data != null && data.getInputStream() != null) { paths.addAll(getPathsFromInputstream(data.getInputStream(), request.getCharacterEncoding())); } return paths; }
From source file:common.Utilities.java
public static double getJaccardSim(Map<Integer, Integer> targetMap, Map<Integer, Integer> nMap) { Set<Integer> unionSet = new HashSet<Integer>(targetMap.keySet()); Set<Integer> intersectSet = new HashSet<Integer>(targetMap.keySet()); unionSet.addAll(nMap.keySet()); intersectSet.retainAll(nMap.keySet()); return (double) intersectSet.size() / (double) unionSet.size(); }
From source file:common.Utilities.java
public static double getJaccardFloatSim(Map<Integer, Double> targetMap, Map<Integer, Double> nMap) { Set<Integer> unionSet = new HashSet<Integer>(targetMap.keySet()); Set<Integer> intersectSet = new HashSet<Integer>(targetMap.keySet()); unionSet.addAll(nMap.keySet()); intersectSet.retainAll(nMap.keySet()); return (double) intersectSet.size() / (double) unionSet.size(); }