Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

In this page you can find the example usage for java.util HashSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:net.tomp2p.simgrid.Utils.java

public static int countHosts(String string) throws IOException {
    File file = new File(string);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = null;//from ww  w  . j ava2  s . c om
    HashSet<String> hosts = new HashSet<String>();
    while ((line = br.readLine()) != null) {
        String markerStr = "host=\"";
        String markerEnd = "\"";
        int start = line.indexOf(markerStr);
        int end = line.indexOf(markerEnd, start + markerStr.length() + 1);
        if (start > 0 & end > 0) {
            hosts.add(line.substring(start + markerStr.length(), end));
        }
    }
    br.close();
    return hosts.size();
}

From source file:EndmemberExtraction.java

public static void exemplarFrequency(int[] exemplarLabel, double curThresholdAbundance) {
    int[] exemplarFreq = new int[100];
    HashSet<Integer> uniqueExemplars = new HashSet<>();
    int totalExemplars = 0;
    for (int i = 0; i < exemplarLabel.length; i++) {
        if (exemplarLabel[i] != -1) {
            exemplarFreq[exemplarLabel[i]]++;
            totalExemplars++;//from   w ww .  j av a 2s.c o  m
            uniqueExemplars.add(exemplarLabel[i]);
        }
    }

    int nExemplar = uniqueExemplars.size();
    double[] fracAbundance = new double[nExemplar];
    boolean[] isRejected = new boolean[nExemplar];
    for (boolean i : isRejected) {
        i = false;
    }
    //System.out.println("nExemplar="+nExemplar);

    //System.out.println("Fractional abundance:");
    for (int i = 0; i < nExemplar; i++) {
        fracAbundance[i] = (double) exemplarFreq[i] / totalExemplars;

        if (fracAbundance[i] < curThresholdAbundance) {
            isRejected[i] = true;
        }
        //System.out.println(i+" : "+(fracAbundance[i]*100));
    }
    //System.out.println();
    int count = 0;
    for (int i = 0; i < exemplarLabel.length; i++) {
        if (exemplarLabel[i] != -1) {
            if (isRejected[exemplarLabel[i]]) {
                exemplarLabel[i] = -1;
            }
        }
    }
}

From source file:org.apache.accumulo.server.util.VerifyTabletAssignments.java

private static void checkTable(final String user, final String pass, String table, HashSet<KeyExtent> check,
        boolean verbose)
        throws AccumuloException, AccumuloSecurityException, TableNotFoundException, InterruptedException {

    if (check == null)
        System.out.println("Checking table " + table);
    else// w ww. j a  v a2  s  .c om
        System.out.println("Checking table " + table + " again, failures " + check.size());

    Map<KeyExtent, String> locations = new TreeMap<KeyExtent, String>();
    SortedSet<KeyExtent> tablets = new TreeSet<KeyExtent>();

    MetadataTable.getEntries(HdfsZooInstance.getInstance(),
            new AuthInfo(user, ByteBuffer.wrap(pass.getBytes()), HdfsZooInstance.getInstance().getInstanceID()),
            table, false, locations, tablets);

    final HashSet<KeyExtent> failures = new HashSet<KeyExtent>();

    for (KeyExtent keyExtent : tablets)
        if (!locations.containsKey(keyExtent))
            System.out.println(" Tablet " + keyExtent + " has no location");
        else if (verbose)
            System.out.println(" Tablet " + keyExtent + " is located at " + locations.get(keyExtent));

    Map<String, List<KeyExtent>> extentsPerServer = new TreeMap<String, List<KeyExtent>>();

    for (Entry<KeyExtent, String> entry : locations.entrySet()) {
        List<KeyExtent> extentList = extentsPerServer.get(entry.getValue());
        if (extentList == null) {
            extentList = new ArrayList<KeyExtent>();
            extentsPerServer.put(entry.getValue(), extentList);
        }

        if (check == null || check.contains(entry.getKey()))
            extentList.add(entry.getKey());
    }

    ExecutorService tp = Executors.newFixedThreadPool(20);

    for (final Entry<String, List<KeyExtent>> entry : extentsPerServer.entrySet()) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    checkTabletServer(user, ByteBuffer.wrap(pass.getBytes()), entry, failures);
                } catch (Exception e) {
                    System.err.println("Failure on ts " + entry.getKey() + " " + e.getMessage());
                    e.printStackTrace();
                    failures.addAll(entry.getValue());
                }
            }

        };

        tp.execute(r);
    }

    tp.shutdown();

    while (!tp.awaitTermination(1, TimeUnit.HOURS)) {
    }

    if (failures.size() > 0)
        checkTable(user, pass, table, failures, verbose);
}

From source file:org.oscarehr.util.TrackingBasicDataSource.java

private static Connection trackConnection(Connection c) {
    c = new TrackingJdbcConnection(c);

    debugMap.put(c, Thread.currentThread().getStackTrace());

    HashSet<Connection> threadConnections = connections.get();
    if (threadConnections == null) {
        threadConnections = new HashSet<Connection>();
        connections.set(threadConnections);
    }//  w w  w  . j  a va 2  s  . co  m

    threadConnections.add(c);

    if (threadConnections.size() > MAX_CONNECTION_WARN_SIZE) {
        String msg = "Thread is currently using " + threadConnections.size()
                + " separate jdbc connections, it souldn't need more than " + MAX_CONNECTION_WARN_SIZE;
        logger.warn(msg);
        logger.debug(msg, new Exception(msg));
    }

    return (c);
}

From source file:com.addthis.hydra.job.alert.JobAlertUtil.java

/**
 * Count the total number of hits along a certain path in a tree object
 * @param jobId The job to query//from   w  w w.j  a v  a  2  s  . c  o  m
 * @param checkPath The path to check, e.g.
 * @return The number of hits along the specified path
 */
public static long getQueryCount(String jobId, String checkPath) {
    String queryURL = getQueryURL(jobId, checkPath, defaultOps, defaultOps);

    HashSet<String> result = new JSONFetcher.SetLoader(queryURL)
            .setContention(alertQueryTimeout, alertQueryRetries, alertQueryBackoff).load();
    if (result == null || result.isEmpty()) {
        log.warn("Found no data for job={} checkPath={}; returning zero", jobId, checkPath);
        return 0;
    } else if (result.size() > 1) {
        log.warn("Found multiple results for job={} checkPath={}; using first row", jobId, checkPath);
    }
    String raw = result.iterator().next();
    return Long.parseLong(QUERY_TRIM_PATTERN.matcher(raw).replaceAll("")); // Trim [] characters and parse as long

}

From source file:fr.mixit.android.io.JSONHandler.java

/**
 * Returns those id's from a {@link android.net.Uri} that were not found in a given set.
 */// ww w .  j a  v  a2 s.  com
protected static HashSet<String> getLostIds(Set<String> ids, Uri uri, String[] projection, int idColumnIndex,
        ContentResolver resolver) {
    final HashSet<String> lostIds = Sets.newHashSet();

    final Cursor cursor = resolver.query(uri, projection, null, null, null);
    try {
        while (cursor.moveToNext()) {
            final String id = cursor.getString(idColumnIndex);
            if (!ids.contains(id)) {
                lostIds.add(id);
            }
        }
    } finally {
        cursor.close();
    }

    if (!lostIds.isEmpty()) {
        Log.d(TAG, "Found " + lostIds.size() + " for " + uri.toString() + " that need to be removed.");
    }

    return lostIds;
}

From source file:com.evolveum.midpoint.common.policy.PasswordPolicyUtils.java

/**
 * Check provided password against provided policy
 * /* www .  j a  v a2  s  .  c o m*/
 * @param password
 *            - password to check
 * @param pp
 *            - Password policy used
 * @return - Operation result of this validation
 */
public static OperationResult validatePassword(String password, ValuePolicyType pp) {

    Validate.notNull(pp, "Password policy must not be null.");

    OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
    ret.addParam("policyName", pp.getName());
    normalize(pp);

    if (password == null && pp.getMinOccurs() != null
            && XsdTypeMapper.multiplicityToInteger(pp.getMinOccurs()) == 0) {
        // No password is allowed
        ret.recordSuccess();
        return ret;
    }

    if (password == null) {
        password = "";
    }

    LimitationsType lims = pp.getStringPolicy().getLimitations();

    StringBuilder message = new StringBuilder();

    // Test minimal length
    if (lims.getMinLength() == null) {
        lims.setMinLength(0);
    }
    if (lims.getMinLength() > password.length()) {
        String msg = "Required minimal size (" + lims.getMinLength()
                + ") of password is not met (password length: " + password.length() + ")";
        ret.addSubresult(
                new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR, msg));
        message.append(msg);
        message.append("\n");
    }
    //      else {
    //         ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
    //               OperationResultStatus.SUCCESS, "PASSED"));
    //      }

    // Test maximal length
    if (lims.getMaxLength() != null) {
        if (lims.getMaxLength() < password.length()) {
            String msg = "Required maximal size (" + lims.getMaxLength()
                    + ") of password was exceeded (password length: " + password.length() + ").";
            ret.addSubresult(
                    new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
    }
    // Test uniqueness criteria
    HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
    if (lims.getMinUniqueChars() != null) {
        if (lims.getMinUniqueChars() > tmp.size()) {
            String msg = "Required minimal count of unique characters (" + lims.getMinUniqueChars()
                    + ") in password are not met (unique characters in password " + tmp.size() + ")";
            ret.addSubresult(new OperationResult("Check minimal count of unique chars",
                    OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            ret.addSubresult(new OperationResult(
        //                  "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
    }

    // check limitation
    HashSet<String> allValidChars = new HashSet<String>(128);
    ArrayList<String> validChars = null;
    ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);

    if (lims.getLimit() == null || lims.getLimit().isEmpty()) {
        if (message.toString() == null || message.toString().isEmpty()) {
            ret.computeStatus();
        } else {
            ret.computeStatus(message.toString());

        }

        return ret;
    }
    for (StringLimitType l : lims.getLimit()) {
        OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
        if (null != l.getCharacterClass().getValue()) {
            validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
        } else {
            validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(
                    pp.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
        }
        // memorize validChars
        allValidChars.addAll(validChars);

        // Count how many character for this limitation are there
        int count = 0;
        for (String s : passwd) {
            if (validChars.contains(s)) {
                count++;
            }
        }

        // Test minimal occurrence
        if (l.getMinOccurs() == null) {
            l.setMinOccurs(0);
        }
        if (l.getMinOccurs() > count) {
            String msg = "Required minimal occurrence (" + l.getMinOccurs() + ") of characters ("
                    + l.getDescription() + ") in password is not met (occurrence of characters in password "
                    + count + ").";
            limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
                    OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }

        // Test maximal occurrence
        if (l.getMaxOccurs() != null) {

            if (l.getMaxOccurs() < count) {
                String msg = "Required maximal occurrence (" + l.getMaxOccurs() + ") of characters ("
                        + l.getDescription()
                        + ") in password was exceeded (occurrence of characters in password " + count + ").";
                limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
                        OperationResultStatus.FATAL_ERROR, msg));
                message.append(msg);
                message.append("\n");
            }
            //            else {
            //               limitResult.addSubresult(new OperationResult(
            //                     "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
            //                     "PASSED"));
            //            }
        }
        // test if first character is valid
        if (l.isMustBeFirst() == null) {
            l.setMustBeFirst(false);
        }
        // we check mustBeFirst only for non-empty passwords
        if (StringUtils.isNotEmpty(password) && l.isMustBeFirst()
                && !validChars.contains(password.substring(0, 1))) {
            String msg = "First character is not from allowed set. Allowed set: " + validChars.toString();
            limitResult.addSubresult(
                    new OperationResult("Check valid first char", OperationResultStatus.FATAL_ERROR, msg));
            message.append(msg);
            message.append("\n");
        }
        //         else {
        //            limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
        //                  OperationResultStatus.SUCCESS, "PASSED"));
        //         }
        limitResult.computeStatus();
        ret.addSubresult(limitResult);
    }

    // Check if there is no invalid character
    StringBuilder sb = new StringBuilder();
    for (String s : passwd) {
        if (!allValidChars.contains(s)) {
            // memorize all invalid characters
            sb.append(s);
        }
    }
    if (sb.length() > 0) {
        String msg = "Characters [ " + sb + " ] are not allowed in password";
        ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
                OperationResultStatus.FATAL_ERROR, msg));
        message.append(msg);
        message.append("\n");
    }
    //      else {
    //         ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
    //               OperationResultStatus.SUCCESS, "PASSED"));
    //      }

    if (message.toString() == null || message.toString().isEmpty()) {
        ret.computeStatus();
    } else {
        ret.computeStatus(message.toString());

    }

    return ret;
}

From source file:org.apache.hadoop.hdfs.StripedFileTestUtil.java

/**
 * Verify that blocks in striped block group are on different nodes, and every
 * internal blocks exists.//from ww  w  .j  a v a2s.  co m
 */
public static void verifyLocatedStripedBlocks(LocatedBlocks lbs, int groupSize) {
    for (LocatedBlock lb : lbs.getLocatedBlocks()) {
        assert lb instanceof LocatedStripedBlock;
        HashSet<DatanodeInfo> locs = new HashSet<>();
        Collections.addAll(locs, lb.getLocations());
        assertEquals(groupSize, lb.getLocations().length);
        assertEquals(groupSize, locs.size());

        // verify that every internal blocks exists
        byte[] blockIndices = ((LocatedStripedBlock) lb).getBlockIndices();
        assertEquals(groupSize, blockIndices.length);
        HashSet<Integer> found = new HashSet<>();
        for (int index : blockIndices) {
            assert index >= 0;
            found.add(index);
        }
        assertEquals(groupSize, found.size());
    }
}

From source file:com.google.android.gm.ay.java

private static Bundle g(final Context context, final Account account) {
    final Bundle bundle = new Bundle();
    final Account[] ax = com.android.mail.utils.a.ax(context);
    final HashSet<String> set = new HashSet<String>();
    for (int length = ax.length, i = 0; i < length; ++i) {
        set.add(com.google.android.gm.c.c.i(context, ax[i]));
    }//from w  ww. j a v  a2 s .c o  m
    if (set.size() > 0) {
        bundle.putString("all-account-domains", TextUtils.join((CharSequence) "/", (Iterable) set));
    }
    if (account != null) {
        bundle.putString("current-account-domain", com.google.android.gm.c.c.i(context, account));
    }
    return bundle;
}

From source file:net.sf.jabref.bibtex.DuplicateCheck.java

public static double compareEntriesStrictly(BibEntry one, BibEntry two) {
    HashSet<String> allFields = new HashSet<>();
    allFields.addAll(one.getFieldNames());
    allFields.addAll(two.getFieldNames());

    int score = 0;
    for (String field : allFields) {
        Object en = one.getField(field);
        Object to = two.getField(field);
        if (((en != null) && (to != null) && en.equals(to)) || ((en == null) && (to == null))) {
            score++;/*www .  j  a v a  2 s  . c  om*/
        }
    }
    if (score == allFields.size()) {
        return 1.01; // Just to make sure we can
        // use score>1 without
        // trouble.
    }
    return (double) score / allFields.size();
}