List of usage examples for java.util Set size
int size();
From source file:Main.java
public static <T> Set<T> merge(Set<T> c1, Set<T> c2) { if (c1 == null || c1.size() == 0) { return c2; }// w ww. j a v a 2s .c o m if (c2 == null || c2.size() == 0) { return c1; } Set<T> all = new HashSet<T>(c1.size() + c2.size()); all.addAll(c1); all.addAll(c2); return all; }
From source file:edu.stanford.muse.Main.java
public static GroupAssigner doGroups(AddressBook addressBook, Collection<EmailDocument> allDocs) throws CancelledException { Grouper<String> grouper = new Grouper<String>(); // we'll ignore the one-sies int threshold = 1; Set<Contact> contactsToIgnore = GroupUtils.contactsAtOrBelowThreshold(addressBook, allDocs, threshold); log.info(contactsToIgnore.size() + " contacts will be ignored because they are below threshold of " + threshold);/*from w w w .j a va2 s .co m*/ Map<Group<String>, Float> weightedInputMap = GroupUtils.convertEmailsToGroupsWeighted(addressBook, allDocs, contactsToIgnore); List<Pair<Group<String>, Float>> weightedInputList = Util.mapToListOfPairs(weightedInputMap); Util.sortPairsBySecondElement(weightedInputList); Map<String, Float> individualElementsValueMap = GroupUtils.getScoreForContacts(addressBook, allDocs, contactsToIgnore); individualElementsValueMap = Util.reorderMapByValue(individualElementsValueMap); // hierarchy = grouper.findGroups(input, 25); try { grouper.setAffinityMap(GroupUtils.computeAffinityMap(addressBook.allContacts())); grouper.setIndividualElementsValueMap(individualElementsValueMap); } catch (Throwable t) { log.warn("Exception trying to compute grouper affinity map " + t); Util.print_exception(t, log); } float errWeight = 0.4f; int nGroups = 20; GroupAssigner ca = new GroupAssigner(); GroupHierarchy<String> hierarchy = grouper.findGroupsWeighted(weightedInputList, nGroups - 1, errWeight); // err weight of 0.4 seems to work well. if (hierarchy != null) { List<SimilarGroup<String>> selectedGroups = SimilarGroupMethods.topGroups(hierarchy, nGroups - 1); ca.setupGroups(allDocs, selectedGroups, addressBook, 0); } return ca; }
From source file:edu.wpi.checksims.algorithm.output.SimilarityMatrix.java
/** * Fill the results matrix/*from w ww.ja va 2s . com*/ * * NOTE that this is inefficient; we calculate twice for each pair, as (i,j) and (j,i). * If speed optimizations are required, recommend starting here. * * @param submissions Submissions to generate results matrix from * @param algorithm Algorithm to use when detecting plagiarism * @return Array of algorithm results, with results[i,j] being the results of comparing students i and j */ public static SimilarityMatrix generate(Set<Submission> submissions, SimilarityDetector algorithm) { checkNotNull(submissions); checkArgument(submissions.size() >= 2); checkNotNull(algorithm); Logger logs = LoggerFactory.getLogger(SimilarityMatrix.class); float[][] results = new float[submissions.size()][submissions.size()]; logs.debug("Sorting submissions prior to algorithm pass..."); List<Submission> submissionsSorted = Ordering .from((Submission a, Submission b) -> a.getName().compareTo(b.getName())) .immutableSortedCopy(submissions); // Generate all possible unordered pairs of submissions Set<Submission> submissionsAsSet = ImmutableSet.copyOf(submissions); Set<Pair<Submission, Submission>> pairs = PairGenerator.generatePairs(submissionsAsSet); // Get results for all possible pairs of submissions Set<AlgorithmResults> algorithmResults = AlgorithmRunner.runAlgorithm(pairs, algorithm); // First, zero the diagonal of the results array for (int i = 0; i < submissionsSorted.size(); i++) { results[i][i] = 0.00f; // Same submission, ignore } // For each result, fill corresponding spots in the results matrix algorithmResults.stream().forEach((result) -> { int indexFirst = submissionsSorted.indexOf(result.a); int indexSecond = submissionsSorted.indexOf(result.b); if (indexFirst == -1) { throw new RuntimeException("Could not find index of submission " + result.a.getName()); } else if (indexSecond == -1) { throw new RuntimeException("Could not find index of submission " + result.b.getName()); } results[indexFirst][indexSecond] = result.percentMatchedA(); results[indexSecond][indexFirst] = result.percentMatchedB(); }); logs.info("Done performing similarity detection"); return new SimilarityMatrix(submissionsSorted, results); }
From source file:Main.java
/** * As {@link #getAllFields(Class)} but acts on a list of {@link Class}s and * uses only {@link Class#getDeclaredFields()}. * * @param classes The list of classes to reflect on * @return The complete list of fields//from w ww .j a v a 2s. c o m */ private static Field[] getAllFields(List<Class<?>> classes) { Set<Field> fields = new HashSet<Field>(); for (Class<?> clazz : classes) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } return fields.toArray(new Field[fields.size()]); }
From source file:io.cortical.rest.model.TestDataMother.java
/** * Create dummy {@link Fingerprint}.//from ww w .j a va2 s .c o m * * @return dummy fingerprint. */ public static Fingerprint createFingerprint() { Random random = new Random(); Set<Integer> positionSet = new HashSet<>(); while (positionSet.size() <= FINGERPRINT_LENGTH) { positionSet.add(random.nextInt(MAX_POSITION)); } Integer[] positionsInteger = new Integer[FINGERPRINT_LENGTH]; positionsInteger = positionSet.toArray(positionsInteger); sort(positionsInteger); return new Fingerprint(ArrayUtils.toPrimitive(positionsInteger)); }
From source file:TwitterClustering.java
public static float jaccardDistance(Set<String> a, Set<String> b) { if (a.size() == 0 || b.size() == 0) { return 0; }//from w w w . j av a 2 s . c o m Set<String> unionXY = new HashSet<String>(a); unionXY.addAll(b); Set<String> intersectionXY = new HashSet<String>(a); intersectionXY.retainAll(b); float retValue = (float) intersectionXY.size() / (float) unionXY.size(); return retValue; }
From source file:mml.handler.scratch.Scratch.java
/** * Get a version that may or may not be in scratch. If not put it there. * @param docid the docid //from w w w . j av a 2 s .co m * @param version the desired single version or null if default * @param dbase the database it is in * @return a ScratchVersion object or null * @throws MMLException */ public static ScratchVersion getVersion(String docid, String version, String dbase) throws MMLException { try { ScratchVersion sv = null; if (version != null) sv = getScratchVersion(docid, version, dbase); if (sv == null) { EcdosisMVD mvd = doGetMVD(dbase, docid); if (mvd != null) { if (version == null) version = mvd.getVersion1(); String base = Layers.stripLayer(version); HashMap<String, char[]> layers = new HashMap<String, char[]>(); int numVersions = mvd.numVersions(); for (int i = 1; i <= numVersions; i++) { String vName = mvd.getVersionId((short) i); if (vName.lastIndexOf(base) == 0) layers.put(vName, mvd.getVersion(i)); } if (!layers.isEmpty()) { Set<String> keys = layers.keySet(); String[] arr = new String[keys.size()]; keys.toArray(arr); Arrays.sort(arr); String[] all = mvd.getAllVersions(); short id = mvd.getVersionId(version); String longName = mvd.getVersionLongName(id); sv = new ScratchVersion(base, longName, docid, dbase, null, false); for (int i = 0; i < arr.length; i++) { String updatedName = Layers.upgradeLayerName(all, arr[i]); sv.addLayer(layers.get(arr[i]), ScratchVersion.layerNumber(updatedName)); } // save it for next time Connection conn = Connector.getConnection(); conn.putToDb(Database.SCRATCH, dbase, docid, version, sv.toJSON()); return sv; } } return null; } else return sv; } catch (DbException e) { throw new MMLException(e); } }
From source file:bayesGame.ui.painter.OrNodePainter.java
public static Image paintPercentage(Color gridColor, Color falseColor, int size, int squaresize, BayesNode node, Fraction parentNode1Probability, Fraction parentNode2Probability) { BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); NodePainter.graphicBackgroundPainter(g, 0, 0, size, size); // get non-zero truth table entries from the node List<Map<Object, Boolean>> nonZeroEntries = node.getNonZeroProbabilities(); // get the identities of its parents by taking the first map and querying it // for KeySet, subtracting the object representing the node itself Set<Object> nodeParents = nonZeroEntries.get(0).keySet(); nodeParents.remove(node.type);// ww w. ja v a 2 s . c o m if (nodeParents.size() > 2) { throw new IllegalArgumentException("OR node with more than 2 parents not yet implemented"); } Object[] nodeParentsArray = nodeParents.toArray(); Object parent1 = nodeParentsArray[0]; Object parent2 = nodeParentsArray[1]; // for each map, check the truth table entry it corresponds to and color // those appropriately boolean p1true_p2true = false; boolean p1true_p2false = false; boolean p1false_p2true = false; boolean p1false_p2false = false; for (Map<Object, Boolean> map : nonZeroEntries) { Boolean parent1truth = map.get(parent1); Boolean parent2truth = map.get(parent2); if (parent1truth && parent2truth) { p1true_p2true = true; } else if (parent1truth && !parent2truth) { p1true_p2false = true; } else if (!parent1truth && parent2truth) { p1false_p2true = true; } else if (!parent1truth && !parent2truth) { p1false_p2false = true; } } int XSize = parentNode1Probability.multiply(size).intValue(); int X_Size = size - XSize; int YSize = parentNode2Probability.multiply(size).intValue(); int Y_Size = size - YSize; if (p1true_p2true) { NodePainter.squarePainter(g, 0, 0, XSize, YSize, gridColor, Color.BLACK); } else { NodePainter.squarePainter(g, 0, 0, XSize, YSize, NodePainter.RECTANGLE_BOX_BACKGROUND_COLOR, Color.BLACK); } NodePainter.squarePainter(g, XSize, 0, X_Size, YSize, gridColor, Color.BLACK); NodePainter.squarePainter(g, 0, YSize, XSize, Y_Size, gridColor, Color.BLACK); if (p1false_p2false) { NodePainter.squarePainter(g, XSize, YSize, X_Size, Y_Size, falseColor, Color.BLACK); } else { NodePainter.squarePainter(g, XSize, YSize, X_Size, Y_Size, NodePainter.RECTANGLE_BOX_BACKGROUND_COLOR, Color.BLACK); } return img; }
From source file:Main.java
/** * Get a process definitions string like "1,2,3". *///from ww w. j a v a2s . co m private static String getProcessDefinitions(Set<Long> processDefinitions) { StringBuilder processDefs = new StringBuilder(); int count = 0; for (Long pd : processDefinitions) { processDefs.append(pd); count++; if (count < processDefinitions.size()) { processDefs.append(","); } } return processDefs.toString(); }
From source file:cooccurrence.Omer_Levy.java
/** * Method that will extract top D singular values from CoVariance Matrix * It will then identify the corresponding columns from U and V and add it to new matrices * @param U// w w w . j av a 2 s . c o m * @param V * @param coVariance * @param matrixUd * @param matrixVd * @param coVarD * @param indicesD */ private static void getTopD(RealMatrix U, RealMatrix V, RealMatrix coVariance, RealMatrix matrixUd, RealMatrix matrixVd, RealMatrix coVarD, ArrayList<Integer> indicesD) { TreeMap<Double, Set<Integer>> tmap = new TreeMap<>(); for (int i = 0; i < coVariance.getRowDimension(); i++) { double val = coVariance.getEntry(i, i); if (tmap.containsKey(val)) { Set<Integer> temp = tmap.get(val); temp.add(i); } else { Set<Integer> temp = new HashSet<>(); temp.add(i); tmap.put(val, temp); } } Iterator iter = tmap.keySet().iterator(); while (iter.hasNext()) { Double val = (Double) iter.next(); Set<Integer> indices = tmap.get(val); for (int i = 0; i < indices.size(); i++) { Iterator iterIndices = indices.iterator(); while (iterIndices.hasNext()) { int index = (Integer) iterIndices.next(); indicesD.add(index); coVarD.addToEntry(index, index, val); matrixUd.setColumnVector(index, U.getColumnVector(index)); matrixVd.setColumnVector(index, V.getColumnVector(index)); } } } }