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:com.facebook.TestUtils.java

private static boolean areEqual(final JSONObject expected, final JSONObject actual) {
    // JSONObject.equals does not do an order-independent comparison, so let's roll our own  :(
    if (expected == actual) {
        return true;
    }//from  ww w  . j  a v a2 s .  c  om
    if ((expected == null) || (actual == null)) {
        return false;
    }

    final Iterator<String> expectedKeysIterator = expected.keys();
    final HashSet<String> expectedKeys = new HashSet<String>();
    while (expectedKeysIterator.hasNext()) {
        expectedKeys.add(expectedKeysIterator.next());
    }

    final Iterator<String> actualKeysIterator = actual.keys();
    while (actualKeysIterator.hasNext()) {
        final String key = actualKeysIterator.next();
        if (!areEqual(expected.opt(key), actual.opt(key))) {
            return false;
        }
        expectedKeys.remove(key);
    }
    return expectedKeys.size() == 0;
}

From source file:com.wellsandwhistles.android.redditsp.reddit.api.RedditAPICommentAction.java

public static void onActionMenuItemSelected(final RedditRenderableComment renderableComment,
        final RedditCommentView commentView, final AppCompatActivity activity,
        final CommentListingFragment commentListingFragment, final RedditCommentAction action,
        final RedditChangeDataManager changeDataManager) {

    final RedditComment comment = renderableComment.getParsedComment().getRawComment();

    switch (action) {

    case UPVOTE:/*from  w ww  .j  a  v a 2  s.  co  m*/
        action(activity, comment, RedditAPI.ACTION_UPVOTE, changeDataManager);
        break;

    case DOWNVOTE:
        action(activity, comment, RedditAPI.ACTION_DOWNVOTE, changeDataManager);
        break;

    case UNVOTE:
        action(activity, comment, RedditAPI.ACTION_UNVOTE, changeDataManager);
        break;

    case SAVE:
        action(activity, comment, RedditAPI.ACTION_SAVE, changeDataManager);
        break;

    case UNSAVE:
        action(activity, comment, RedditAPI.ACTION_UNSAVE, changeDataManager);
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        action(activity, comment, RedditAPI.ACTION_REPORT, changeDataManager);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, comment.getIdAndType());
        intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY,
                StringEscapeUtils.unescapeHtml4(comment.body));
        activity.startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(activity, CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.getIdAndType());
        intent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(comment.body));
        activity.startActivity(intent);
        break;
    }

    case DELETE: {
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        action(activity, comment, RedditAPI.ACTION_DELETE, changeDataManager);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.body) + "\r\n\r\n"
                + comment.getContextUrl().generateNonJsonUri().toString());

        activity.startActivityForResult(Intent.createChooser(mailer, activity.getString(R.string.action_share)),
                1);

        break;

    case COPY_TEXT: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.body));
        break;
    }

    case COPY_URL: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(comment.getContextUrl().context(null).generateNonJsonUri().toString());
        break;
    }

    case COLLAPSE: {
        commentListingFragment.handleCommentVisibilityToggle(commentView);
        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(comment.author).toString());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment).show(activity.getSupportFragmentManager(), null);
        break;

    case GO_TO_COMMENT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().context(null).toString());
        break;
    }

    case CONTEXT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().toString());
        break;
    }
    case ACTION_MENU:
        showActionMenu(activity, commentListingFragment, renderableComment, commentView, changeDataManager,
                comment.isArchived());
        break;

    case BACK:
        activity.onBackPressed();
        break;
    }
}

From source file:com.termmed.utils.FileHelper.java

/**
 * Complete file from array./*www  .  ja va  2  s .co m*/
 *
 * @param filesArray the files array
 * @param fileName the file name
 * @return the string
 */
public static String completeFileFromArray(HashSet<String> filesArray, String fileName) {
    HashSet<File> fileSet = new HashSet<File>();
    for (String sfile : filesArray) {
        File file = new File(sfile);
        if (file.exists()) {
            fileSet.add(file);
        }
    }
    if (fileSet.size() > 0) {
        File outputFile = new File(fileName);
        CommonUtils.concatFile(fileSet, outputFile);
        return outputFile.getAbsolutePath();
    }
    return null;
}

From source file:main.java.repartition.SimpleTr.java

static double getIncidentSpan(Transaction j, MigrationPlan m) {
    // Construct A -- for target transaction i
    Set<Integer> delta_i_A = new HashSet<Integer>();
    for (Integer s : m.fromSet)
        delta_i_A.addAll(m.serverDataSet.get(s));

    // Construct b -- for incident transaction j
    Set<Integer> delta_j_A = new HashSet<Integer>();
    for (Integer s : m.fromSet)
        if (j.getTr_serverSet().containsKey(s))
            delta_j_A.addAll(j.getTr_serverSet().get(s));

    // Set difference, delta = delta_j_A \ delta_i_A
    Set<Integer> delta = new HashSet<Integer>(delta_j_A);
    delta.removeAll(delta_i_A);/*ww w  .  j  a  v a  2  s  . c  o m*/

    HashSet<Integer> psi_delta = new HashSet<Integer>();
    for (Entry<Integer, HashSet<Integer>> entry : j.getTr_serverSet().entrySet())
        if (!Collections.disjoint(delta, entry.getValue())) // Returns true if the two specified collections have no elements in common.
            psi_delta.add(entry.getKey());

    // Calculate net span improvement for incident transaction j
    int incident_span = m.fromSet.size() - psi_delta.size();

    if (!j.getTr_serverSet().containsKey(m.to))
        incident_span -= 1;

    return (double) (incident_span) * (1 / j.getTr_period());
}

From source file:com.indivica.olis.Driver.java

private static void notifyOlisError(Provider provider, String errorMsg) {
    HashSet<String> sendToProviderList = new HashSet<String>();

    String providerNoTemp = "999998";
    sendToProviderList.add(providerNoTemp);

    if (provider != null) {
        // manual prompts always send to admin
        sendToProviderList.add(providerNoTemp);

        providerNoTemp = provider.getProviderNo();
        sendToProviderList.add(providerNoTemp);
    }//from   www .  j a v a  2s. c om

    // no one wants to hear about the problem
    if (sendToProviderList.size() == 0)
        return;

    String message = "OSCAR attempted to perform a fetch of OLIS data at " + new Date()
            + " but there was an error during the task.\n\nSee below for the error message:\n" + errorMsg;

    oscar.oscarMessenger.data.MsgMessageData messageData = new oscar.oscarMessenger.data.MsgMessageData();

    ArrayList<MsgProviderData> sendToProviderListData = new ArrayList<MsgProviderData>();
    for (String providerNo : sendToProviderList) {
        MsgProviderData mpd = new MsgProviderData();
        mpd.providerNo = providerNo;
        mpd.locationId = "145";
        sendToProviderListData.add(mpd);
    }

    String sentToString = messageData.createSentToString(sendToProviderListData);
    messageData.sendMessage2(message, "OLIS Retrieval Error", "System", sentToString, "-1",
            sendToProviderListData, null, null);
}

From source file:edu.cens.loci.classes.LociWifiFingerprint.java

/**
 * Calculated Tanimoto score between to Wifi fingerprints
 * @param sig1 is a Wifi fingerprint//from   ww  w .j a va  2s  .c o  m
 * @param sig2 is a Wifi fingerprint
 * @param repAP1 
 * @param repAP2
 * @param rrThreshold is used to filter low response rate APs
 * @param isDebugOn
 * @return
 */
public static double tanimotoScore(LociWifiFingerprint sig1, LociWifiFingerprint sig2, HashSet<String> repAP1,
        HashSet<String> repAP2, double rrThreshold, boolean isDebugOn) {

    if (repAP1 == null)
        MyLog.i(LociConfig.D.Classes.LOG_WIFI, TAG, "tanimotoScore: use all.");
    else
        MyLog.i(LociConfig.D.Classes.LOG_WIFI, TAG, "tanimotoScore: use rep.");

    // use every beacon when repAP is empty
    if (repAP1 == null || repAP1.isEmpty())
        repAP1 = sig1.getBssids();
    if (repAP2 == null || repAP2.isEmpty())
        repAP2 = sig2.getBssids();

    // use only the union of both representative set
    HashSet<String> union = new HashSet<String>(repAP1);
    union.addAll(repAP2);

    // two arrays to save RSS values 
    double a[] = new double[union.size()];
    double b[] = new double[union.size()];

    // fill in the arrays with RSS values
    Iterator<String> iterator = union.iterator();
    int cnt = 0;

    String debugSsids = "   ";
    String debugRssA = "rss (a) : ";
    String debugRssB = "rss (b) : ";
    String debugNorA = "nor (a) : ";
    String debugNorB = "nor (b) : ";
    String debugCntA = "cnt (a) : ";
    String debugCntB = "cnt (b) : ";
    String debugRRA = "rr  (a) : ";
    String debugRRB = "rr  (b) : ";

    while (iterator.hasNext()) {
        String bssid = iterator.next();

        int aIntVal = sig1.getAvgRss(bssid);
        int bIntVal = sig2.getAvgRss(bssid);
        double rr1 = sig1.getResponseRate(bssid);
        double rr2 = sig2.getResponseRate(bssid);

        if (rr1 >= rrThreshold)
            a[cnt] = raw2normal(aIntVal, pMinRss, pMaxRss);
        else
            a[cnt] = raw2normal(0, pMinRss, pMaxRss);

        if (rr2 >= rrThreshold)
            b[cnt] = raw2normal(bIntVal, pMinRss, pMaxRss);
        else
            b[cnt] = raw2normal(0, pMinRss, pMaxRss);

        cnt++;

        if (isDebugOn) {
            String ssid = sig1.getSsid(bssid);
            if (ssid == null)
                ssid = sig2.getSsid(bssid);
            if (ssid == null)
                ssid = "unknown";

            int count1 = sig1.getCount(bssid);
            int count2 = sig2.getCount(bssid);

            debugSsids = debugSsids + String.format("%10s", ssid.substring(0, Math.min(ssid.length(), 9)));
            debugRssA = debugRssA + String.format("%10d", aIntVal);
            debugRssB = debugRssB + String.format("%10d", bIntVal);
            debugNorA = debugNorA + String.format("%10.2f", a[cnt - 1]);
            debugNorB = debugNorB + String.format("%10.2f", b[cnt - 1]);
            debugCntA = debugCntA + String.format("%10d", count1);
            debugCntB = debugCntB + String.format("%10d", count2);
            debugRRA = debugRRA + String.format("%10.2f", rr1);
            debugRRB = debugRRB + String.format("%10.2f", rr2);
        }
    }

    MyLog.d(isDebugOn, TAG, debugSsids);
    MyLog.d(isDebugOn, TAG, debugRssA);
    MyLog.d(isDebugOn, TAG, debugRssB);
    MyLog.d(isDebugOn, TAG, debugNorA);
    MyLog.d(isDebugOn, TAG, debugNorB);
    MyLog.d(isDebugOn, TAG, debugCntA);
    MyLog.d(isDebugOn, TAG, debugCntB);
    MyLog.d(isDebugOn, TAG, debugRRA);
    MyLog.d(isDebugOn, TAG, debugRRB);

    return tanimotoSimilarity(a, b);
}

From source file:com.oneis.javascript.Runtime.java

/**
 * Initialize the shared JavaScript environment. Loads libraries and removes
 * methods of escaping the sandbox./*from  www  .j a  v a2 s. c o  m*/
 */
public static void initializeSharedEnvironment(String frameworkRoot) throws java.io.IOException {
    // Don't allow this to be called twice
    if (sharedScope != null) {
        return;
    }

    long startTime = System.currentTimeMillis();

    final Context cx = Runtime.enterContext();
    try {
        final ScriptableObject scope = cx.initStandardObjects(null,
                false /* don't seal the standard objects yet */);

        if (!scope.has("JSON", scope)) {
            throw new RuntimeException(
                    "Expecting built-in JSON support in Rhino, check version is at least 1.7R3");
        }

        if (standardTemplateLoader == null) {
            throw new RuntimeException("StandardTemplateLoader for Runtime hasn't been set.");
        }
        String standardTemplateJSON = standardTemplateLoader.standardTemplateJSON();
        scope.put("$STANDARDTEMPLATES", scope, standardTemplateJSON);

        // Load the library code
        FileReader bootScriptsFile = new FileReader(frameworkRoot + "/lib/javascript/bootscripts.txt");
        LineNumberReader bootScripts = new LineNumberReader(bootScriptsFile);
        String scriptFilename = null;
        while ((scriptFilename = bootScripts.readLine()) != null) {
            FileReader script = new FileReader(frameworkRoot + "/" + scriptFilename);
            cx.evaluateReader(scope, script, scriptFilename, 1, null /* no security domain */);
            script.close();
        }
        bootScriptsFile.close();

        // Load the list of allowed globals
        FileReader globalsWhitelistFile = new FileReader(
                frameworkRoot + "/lib/javascript/globalswhitelist.txt");
        HashSet<String> globalsWhitelist = new HashSet<String>();
        LineNumberReader whitelist = new LineNumberReader(globalsWhitelistFile);
        String globalName = null;
        while ((globalName = whitelist.readLine()) != null) {
            String g = globalName.trim();
            if (g.length() > 0) {
                globalsWhitelist.add(g);
            }
        }
        globalsWhitelistFile.close();

        // Remove all the globals which aren't allowed, using a whitelist            
        for (Object propertyName : scope.getAllIds()) // the form which includes the DONTENUM hidden properties
        {
            if (propertyName instanceof String) // ConsString is checked
            {
                // Delete any property which isn't in the whitelist
                if (!(globalsWhitelist.contains(propertyName))) {
                    scope.delete((String) propertyName); // ConsString is checked
                }
            } else {
                // Not expecting any other type of property name in the global namespace
                throw new RuntimeException(
                        "Not expecting global JavaScript scope to contain a property which isn't a String");
            }
        }

        // Run through the globals again, just to check nothing escaped
        for (Object propertyName : scope.getAllIds()) {
            if (!(globalsWhitelist.contains(propertyName))) {
                throw new RuntimeException("JavaScript global was not destroyed: " + propertyName.toString());
            }
        }
        // Run through the whilelist, and make sure that everything in it exists
        for (String propertyName : globalsWhitelist) {
            if (!scope.has(propertyName, scope)) {
                // The whitelist should only contain non-host objects created by the JavaScript source files.
                throw new RuntimeException(
                        "JavaScript global specified in whitelist does not exist: " + propertyName);
            }
        }
        // And make sure java has gone, to check yet again that everything expected has been removed
        if (scope.get("java", scope) != Scriptable.NOT_FOUND) {
            throw new RuntimeException("JavaScript global 'java' escaped destruction");
        }

        // Seal the scope and everything within in, so nothing else can be added and nothing can be changed
        // Asking initStandardObjects() to seal the standard library doesn't actually work, as it will leave some bits
        // unsealed so that decodeURI.prototype.pants = 43; works, and can pass information between runtimes.
        // This recursive object sealer does actually work. It can't seal the main host object class, so that's
        // added to the scope next, with the (working) seal option set to true.
        HashSet<Object> sealedObjects = new HashSet<Object>();
        recursiveSealObjects(scope, scope, sealedObjects, false /* don't seal the root object yet */);
        if (sealedObjects.size() == 0) {
            throw new RuntimeException("Didn't seal any JavaScript globals");
        }

        // Add the host object classes. The sealed option works perfectly, so no need to use a special seal function.
        defineSealedHostClass(scope, KONEISHost.class);
        defineSealedHostClass(scope, KObjRef.class);
        defineSealedHostClass(scope, KScriptable.class);
        defineSealedHostClass(scope, KLabelList.class);
        defineSealedHostClass(scope, KLabelChanges.class);
        defineSealedHostClass(scope, KLabelStatements.class);
        defineSealedHostClass(scope, KDateTime.class);
        defineSealedHostClass(scope, KObject.class);
        defineSealedHostClass(scope, KText.class);
        defineSealedHostClass(scope, KQueryClause.class);
        defineSealedHostClass(scope, KQueryResults.class);
        defineSealedHostClass(scope, KPluginAppGlobalStore.class);
        defineSealedHostClass(scope, KPluginResponse.class);
        defineSealedHostClass(scope, KTemplatePartialAutoLoader.class);
        defineSealedHostClass(scope, KAuditEntry.class);
        defineSealedHostClass(scope, KAuditEntryQuery.class);
        defineSealedHostClass(scope, KUser.class);
        defineSealedHostClass(scope, KUserData.class);
        defineSealedHostClass(scope, KWorkUnit.class);
        defineSealedHostClass(scope, KWorkUnitQuery.class);
        defineSealedHostClass(scope, KEmailTemplate.class);
        defineSealedHostClass(scope, KBinaryData.class);
        defineSealedHostClass(scope, KUploadedFile.class);
        defineSealedHostClass(scope, KStoredFile.class);
        defineSealedHostClass(scope, KJob.class);
        defineSealedHostClass(scope, KSessionStore.class);

        defineSealedHostClass(scope, KSecurityRandom.class);
        defineSealedHostClass(scope, KSecurityBCrypt.class);
        defineSealedHostClass(scope, KSecurityDigest.class);
        defineSealedHostClass(scope, KSecurityHMAC.class);

        defineSealedHostClass(scope, JdNamespace.class);
        defineSealedHostClass(scope, JdTable.class);
        defineSealedHostClass(scope, JdSelectClause.class);
        defineSealedHostClass(scope, JdSelect.class, true /* map inheritance */);

        defineSealedHostClass(scope, KGenerateTable.class);
        defineSealedHostClass(scope, KGenerateXLS.class, true /* map inheritance */);

        defineSealedHostClass(scope, KRefKeyDictionary.class);
        defineSealedHostClass(scope, KRefKeyDictionaryHierarchical.class, true /* map inheritance */);
        defineSealedHostClass(scope, KCheckingLookupObject.class);

        defineSealedHostClass(scope, KCollaborationService.class);
        defineSealedHostClass(scope, KCollaborationFolder.class);
        defineSealedHostClass(scope, KCollaborationItemList.class);
        defineSealedHostClass(scope, KCollaborationItem.class);

        defineSealedHostClass(scope, KAuthenticationService.class);

        // Seal the root now everything has been added
        scope.sealObject();

        // Check JavaScript TimeZone
        checkJavaScriptTimeZoneIsGMT();

        sharedScope = scope;
    } finally {
        cx.exit();
    }

    initializeSharedEnvironmentTimeTaken = System.currentTimeMillis() - startTime;
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

/** Writes the class information to a file in SOMLib format. */
public static void writeAsSOMLib(HashMap<String, String> classInfo, HashSet<String> classNames, String fileName)
        throws IOException, SOMLibFileFormatException {
    ArrayList<String> classNamesList = new ArrayList<String>(classNames);
    Collections.sort(classNamesList);

    PrintWriter writer = FileUtils.openFileForWriting("SOMLib class info", fileName);
    writer.println("$TYPE class_information");

    writer.println("$NUM_CLASSES " + classNames.size());
    writer.println("$CLASS_NAMES " + StringUtils.toString(classNamesList, "", "", " "));
    writer.println("$XDIM 2");
    writer.println("$YDIM " + classInfo.size());
    for (String key : classInfo.keySet()) {
        writer.println(key + " " + classNamesList.indexOf(classInfo.get(key)));
    }//from   w w w  . j  a v a 2s  .  c  o m

    writer.flush();
    writer.close();
}

From source file:com.battlelancer.seriesguide.util.TraktTools.java

private static void applyEpisodeFlagChanges(Context context, List<TvShow> remoteShows,
        HashSet<Integer> localShows, String episodeFlagColumn, boolean clearExistingFlags) {
    HashSet<Integer> skippedShows = new HashSet<>(localShows);

    // loop through shows on trakt, update the ones existing locally
    for (TvShow tvShow : remoteShows) {
        if (tvShow == null || tvShow.tvdb_id == null || !localShows.contains(tvShow.tvdb_id)) {
            // does not match, skip
            continue;
        }//  w  ww .ja va2  s  .co m

        applyEpisodeFlagChanges(context, tvShow, episodeFlagColumn, clearExistingFlags);

        skippedShows.remove(tvShow.tvdb_id);
    }

    // clear flags on all shows not synced
    if (clearExistingFlags && skippedShows.size() > 0) {
        clearFlagsOfShow(context, episodeFlagColumn, skippedShows);
    }
}

From source file:gr.scify.newsum.Utils.java

/**
 * Counts the number of different Sources the Summary refers to
 * @param Summary The summary of interest
 * @return The number of different sources that the summary comes from
 *//*from  ww w.  j a va2 s  .c  o  m*/
public static int countDiffArticles(String[] Summary) {
    // Init string set for sources
    HashSet<String> hsSources = new HashSet<String>();
    // Get first entry, i.e. links and labels
    String sAllLinksAndLabels = Summary[0];
    // if only one link
    if (!sAllLinksAndLabels.contains(NewSumServiceClient.getSecondLevelSeparator())) {
        return 1;
    } else {
        // For every pair
        for (String sTmps : sAllLinksAndLabels.split(NewSumServiceClient.getSecondLevelSeparator())) {
            // Get the link (1st field out of 2)  
            hsSources.add(sTmps.split(NewSumServiceClient.getThirdLevelSeparator())[0]);
        }
    }
    // Return unique sources
    return hsSources.size();
}