List of usage examples for java.util HashSet size
public int size()
From source file:calliope.db.MongoConnection.java
/** * List all the documents in a Mongo collection * @param collName the name of the collection * @return a String array of document keys * @throws AeseException /*from w w w . jav a 2s. c om*/ */ @Override public String[] listCollection(String collName) throws AeseException { if (!collName.equals(Database.CORPIX)) { try { connect(); } catch (Exception e) { throw new AeseException(e); } DBCollection coll = getCollectionFromName(collName); BasicDBObject keys = new BasicDBObject(); keys.put(JSONKeys.DOCID, 1); DBCursor cursor = coll.find(new BasicDBObject(), keys); System.out.println("Found " + cursor.count() + " documents"); cursor.count(); if (cursor.length() > 0) { String[] docs = new String[cursor.length()]; Iterator<DBObject> iter = cursor.iterator(); int i = 0; while (iter.hasNext()) docs[i++] = (String) iter.next().get(JSONKeys.DOCID); return docs; } else { return new String[0]; } } else { GridFS gfs = new GridFS(db, collName); DBCursor curs = gfs.getFileList(); int i = 0; List<DBObject> list = curs.toArray(); HashSet<String> set = new HashSet<String>(); Iterator<DBObject> iter = list.iterator(); while (iter.hasNext()) { String name = (String) iter.next().get("filename"); set.add(name); } String[] docs = new String[set.size()]; set.toArray(docs); return docs; } }
From source file:com.iflytek.spider.util.EncodingDetector.java
private void findDisagreements(String url, List<EncodingClue> newClues) { HashSet<String> valsSeen = new HashSet<String>(); HashSet<String> sourcesSeen = new HashSet<String>(); boolean disagreement = false; for (int i = 0; i < newClues.size(); i++) { EncodingClue clue = newClues.get(i); if (!clue.isEmpty() && !sourcesSeen.contains(clue.source)) { if (valsSeen.size() > 0 && !valsSeen.contains(clue.value) && clue.meetsThreshold()) { disagreement = true;/*w ww .ja v a 2 s . c o m*/ } if (clue.meetsThreshold()) { valsSeen.add(clue.value); } sourcesSeen.add(clue.source); } } if (disagreement) { // dump all values in case of disagreement StringBuffer sb = new StringBuffer(); sb.append("Disagreement: " + url + "; "); for (int i = 0; i < newClues.size(); i++) { if (i > 0) { sb.append(", "); } sb.append(newClues.get(i)); } LOG.trace(sb.toString()); } }
From source file:afest.datastructures.tree.decision.erts.grower.AERTGrower.java
/** * Return k random attributes (non-constant) picked without replacement unless less then k attributes are non-constant. * @param constantAttributes attributes that are constant. * @param attributeList list of all attributes present in each point in the set. * @return k random attributes (non-constant) picked without replacement unless less then k attributes are non-constant. *//*from www . j a v a2 s . co m*/ private ArrayList<R> getKRandomAttributes(ArrayList<R> constantAttributes, ArrayList<R> attributeList) { ArrayList<R> kRandomAttributes = new ArrayList<R>(); HashSet<R> pickedAttributes = new HashSet<R>(constantAttributes); for (int k = 0; k < fK; k++) { // If all non-constant attributes have been picked and k is not reached yet, start resampling the non-constant attributes. if (pickedAttributes.size() == attributeList.size()) { pickedAttributes.clear(); pickedAttributes.addAll(constantAttributes); } // Count the number of attributes that are available for a pick int numNotPicked = attributeList.size() - pickedAttributes.size(); // get a random attribute int randomAttribute = fRandom.nextInt(numNotPicked); int count = 0; for (R aR : attributeList) { // If the attribute is not picked if (!pickedAttributes.contains(aR)) { // verify if it is the one corresponding to the random pick if (count == randomAttribute) { kRandomAttributes.add(aR); pickedAttributes.add(aR); break; } else // increase the count { count++; } } } } return kRandomAttributes; }
From source file:net.ontopia.topicmaps.nav.context.ThemeCategorizer.java
/** * Generate a ordered list of theme classes. * Use template strings to render result string, this approach * is used by the navigator framework 2nd generation. * Note: In every theme class there are at least one theme. *//*from w w w. j a va 2 s . c om*/ public String generateThemeList(HashMap themeClassMap, Collection selectedThemes, String templThemeClass, String templTheme, String templSelectedTheme) { if (themeClassMap == null || templThemeClass == null || templTheme == null) return ""; if (templSelectedTheme == null) templSelectedTheme = ""; StringBuilder strBuf = new StringBuilder(); // ----- loop over all themes classes List themeClassList = new ArrayList(themeClassMap.keySet()); Collections.sort(themeClassList, lexicalComparator); Iterator itThemeClasses = themeClassList.iterator(); String actThemeClass; HashSet actSet; List themeList; Iterator itRelThemes; TopicIF actTheme; String tmp; while (itThemeClasses.hasNext()) { actThemeClass = (String) itThemeClasses.next(); actSet = (HashSet) themeClassMap.get(actThemeClass); // only proceed if category name has related themes if (actSet.size() > 0) { // -- append string representation for theme class strBuf.append(StringUtils.replace(templThemeClass, "%className%", actThemeClass)); themeList = new ArrayList(actSet); Collections.sort(themeList, topicComparator); itRelThemes = themeList.iterator(); while (itRelThemes.hasNext()) { actTheme = (TopicIF) itRelThemes.next(); // a: replace theme name tmp = StringUtils.replace(templTheme, "%themeName%", stringifier.toString(actTheme)); // b: replace theme id tmp = StringUtils.replace(tmp, "%themeId%", actTheme.getObjectId()); // c: if selected, replace selected template if (selectedThemes != null && selectedThemes.contains(actTheme)) tmp = StringUtils.replace(tmp, "%selected%", templSelectedTheme); else tmp = StringUtils.replace(tmp, "%selected%", ""); // -- append string representation for theme strBuf.append(tmp); } // while itRelThemes } } // while itThemeClasses return strBuf.toString(); }
From source file:org.apache.zookeeper.graph.servlets.Throughput.java
public String handleRequest(JsonRequest request) throws Exception { long starttime = 0; long endtime = 0; long period = 0; long scale = 0; starttime = request.getNumber("start", 0); endtime = request.getNumber("end", 0); period = request.getNumber("period", 0); if (starttime == 0) { starttime = source.getStartTime(); }//from w w w .ja va2s. c om if (endtime == 0) { if (period > 0) { endtime = starttime + period; } else { endtime = source.getEndTime(); } } String scalestr = request.getString("scale", "minutes"); if (scalestr.equals("seconds")) { scale = MS_PER_SEC; } else if (scalestr.equals("hours")) { scale = MS_PER_HOUR; } else { scale = MS_PER_MIN; } LogIterator iter = source.iterator(starttime, endtime); long current = 0; long currentms = 0; HashSet<Long> zxids_ms = new HashSet<Long>(); long zxidcount = 0; JSONArray events = new JSONArray(); while (iter.hasNext()) { LogEntry e = iter.next(); if (e.getType() != LogEntry.Type.TXN) { continue; } TransactionEntry cxn = (TransactionEntry) e; long ms = cxn.getTimestamp(); long inscale = ms / scale; if (currentms != ms && currentms != 0) { zxidcount += zxids_ms.size(); zxids_ms.clear(); } if (inscale != current && current != 0) { JSONObject o = new JSONObject(); o.put("time", current * scale); o.put("count", zxidcount); events.add(o); zxidcount = 0; } current = inscale; currentms = ms; zxids_ms.add(cxn.getZxid()); } JSONObject o = new JSONObject(); o.put("time", current * scale); o.put("count", zxidcount); events.add(o); iter.close(); return JSONValue.toJSONString(events); }
From source file:com.bitranger.parknshop.common.service.ads.ItemAdService.java
/** /*from ww w . ja v a 2 s . co m*/ select AD.*, count(RTI.id_tag) as TAG_INTER from ps_item as IT inner join r_tag_item as RTI on RTI.id_item = IT.id inner join ps_promot_item as AD on AD.id_item = IT.id where IT.id = ? and RTI.id_tag in (???) order by TAG_INTER desc */ @SuppressWarnings("unchecked") @Override public List<PsPromotItem> forItemList(@Nullable final List<PsItem> items, final int limit, @Nullable PsCustomer customer) { if (customer != null) { return new CFilter().filter(items, limit, customer.getId()); } final HashSet<PsTag> tags = new HashSet<>(items.size() * 6); for (PsItem i : items) { tags.addAll(i.getPsTags()); } final StringBuilder b = new StringBuilder(512); b.append(" select AD.*, count(RTI.id_tag) as TAG_INTER from ps_item as IT " + " inner join r_tag_item as RTI on RTI.id_item = IT.id " + " inner join ps_promot_item as AD on AD.id_item = IT.id "); if (tags != null && tags.size() > 1) { b.append(" where RTI.id_tag in ( "); for (PsTag psTag : tags) { b.append(psTag.getId()).append(','); } b.setCharAt(b.length() - 1, ')'); } b.append(" order by TAG_INTER desc "); System.out.println(b.toString()); return psAdItemDAO.hibernate().executeFind(new HibernateCallback<List<PsPromotItem>>() { @Override public List<PsPromotItem> doInHibernate(Session session) throws HibernateException, SQLException { return session.createSQLQuery(b.toString()).addEntity(PsPromotItem.class).list(); } }); // Iterator<PsTag> i = tags.iterator(); // while (tags.size() > limit) { // i.remove(); // } }
From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java
public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity, final Action action) { switch (action) { case UPVOTE:/* w w w .j av a2 s . c o m*/ post.action(activity, RedditAPI.RedditAction.UPVOTE); break; case DOWNVOTE: post.action(activity, RedditAPI.RedditAction.DOWNVOTE); break; case UNVOTE: post.action(activity, RedditAPI.RedditAction.UNVOTE); break; case SAVE: post.action(activity, RedditAPI.RedditAction.SAVE); break; case UNSAVE: post.action(activity, RedditAPI.RedditAction.UNSAVE); break; case HIDE: post.action(activity, RedditAPI.RedditAction.HIDE); break; case UNHIDE: post.action(activity, RedditAPI.RedditAction.UNHIDE); 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() { public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.RedditAction.DELETE); } }).setNegativeButton(R.string.dialog_cancel, null).show(); 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() { public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.RedditAction.REPORT); // TODO update the view to show the result // TODO don't forget, this also hides } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case EXTERNAL: { final Intent intent = new Intent(Intent.ACTION_VIEW); String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl() : post.url; intent.setData(Uri.parse(url)); activity.startActivity(intent); break; } case SELFTEXT_LINKS: { final HashSet<String> linksInComment = LinkHandler .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext)); if (linksInComment.isEmpty()) { General.quickToast(activity, R.string.error_toast_no_urls_in_self); } else { final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setItems(linksArr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src); dialog.dismiss(); } }); final AlertDialog alert = builder.create(); alert.setTitle(R.string.action_selftext_links); alert.setCanceledOnTouchOutside(true); alert.show(); } break; } case SAVE_IMAGE: { final RedditAccount anon = RedditAccountManager.getAnon(); LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0, new GetImageInfoListener() { @Override public void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status, final String readableMessage) { final RRError error = General.getGeneralErrorForFailure(activity, type, t, status, post.url); General.showResultDialog(activity, error); } @Override public void onSuccess(final ImgurAPI.ImageInfo info) { CacheManager.getInstance(activity) .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon, null, Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false, false, false, activity) { @Override protected void onCallbackException(Throwable t) { BugReportActivity.handleGlobalError(context, t); } @Override protected void onDownloadNecessary() { General.quickToast(context, R.string.download_downloading); } @Override protected void onDownloadStarted() { } @Override protected void onFailure(RequestFailureType type, Throwable t, StatusLine status, String readableMessage) { final RRError error = General.getGeneralErrorForFailure(context, type, t, status, url.toString()); General.showResultDialog(activity, error); } @Override protected void onProgress(boolean authorizationInProgress, long bytesRead, long totalBytes) { } @Override protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp, UUID session, boolean fromCache, String mimetype) { File dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), General.uriFromString(info.urlOriginal).getPath()); if (dst.exists()) { int count = 0; while (dst.exists()) { count++; dst = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), count + "_" + General.uriFromString(info.urlOriginal) .getPath().substring(1)); } } try { final InputStream cacheFileInputStream = cacheFile.getInputStream(); if (cacheFileInputStream == null) { notifyFailure(RequestFailureType.CACHE_MISS, null, null, "Could not find cached image"); return; } General.copyFile(cacheFileInputStream, dst); } catch (IOException e) { notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file"); return; } activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dst.getAbsolutePath()))); General.quickToast(context, context.getString(R.string.action_save_image_success) + " " + dst.getAbsolutePath()); } }); } @Override public void onNotAnImage() { General.quickToast(activity, R.string.selected_link_is_not_image); } }); break; } case SHARE: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, post.title); mailer.putExtra(Intent.EXTRA_TEXT, post.url); activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share))); break; } case SHARE_COMMENTS: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title); mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString()); activity.startActivity( Intent.createChooser(mailer, activity.getString(R.string.action_share_comments))); break; } case COPY: { ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); manager.setText(post.url); break; } case GOTO_SUBREDDIT: { try { final Intent intent = new Intent(activity, PostListingActivity.class); intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri()); activity.startActivityForResult(intent, 1); } catch (RedditSubreddit.InvalidSubredditNameException e) { Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show(); } break; } case USER_PROFILE: LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString()); break; case PROPERTIES: PostPropertiesDialog.newInstance(post.src).show(activity.getFragmentManager(), null); break; case COMMENTS: ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK: ((RedditPostView.PostSelectionListener) activity).onPostSelected(post); break; case COMMENTS_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((RedditPostView.PostSelectionListener) activity).onPostSelected(post); break; case ACTION_MENU: showActionMenu(activity, post); break; case REPLY: final Intent intent = new Intent(activity, CommentReplyActivity.class); intent.putExtra("parentIdAndType", post.idAndType); activity.startActivity(intent); break; } }
From source file:nl.uva.expose.classification.MakeTextFile.java
public String getMemParty(Integer memIndexId) throws IOException { String aff = ""; HashSet<String> affiliations = this.miInfo.getDocAllTerm(memIndexId, "AFF"); ///*from w w w .j a va2 s.co m*/ if (affiliations.contains("nl.p.lidbontes")) return "nl.p.lidbontes"; if (affiliations.contains("nl.p.groepkortenoevenhernandez")) return "nl.p.groepkortenoevenhernandez"; if (affiliations.contains("nl.p.lidbrinkman")) return "nl.p.lidbrinkman"; if (affiliations.contains("nl.p.lidverdonk")) return "nl.p.lidverdonk"; // for (String s : affiliations) { aff = s; // break; } if (affiliations.size() > 1) { System.err.println("More than one affiliation: " + affiliations.toString() + " --> " + aff); } return aff.trim(); }
From source file:org.elasticsearch.common.geo.builders.BasePolygonBuilder.java
/** * Validates only 1 vertex is tangential (shared) between the interior and exterior of a polygon *//* w w w. j a v a2s. c o m*/ protected void validateHole(BaseLineStringBuilder shell, BaseLineStringBuilder hole) { HashSet exterior = Sets.newHashSet(shell.points); HashSet interior = Sets.newHashSet(hole.points); exterior.retainAll(interior); if (exterior.size() >= 2) { throw new InvalidShapeException( "Invalid polygon, interior cannot share more than one point with the exterior"); } }
From source file:org.commoncrawl.service.crawler.ParseQueue.java
private void fillQueue() throws IOException { LOG.info("In fillQueue"); int unitsForSmallDomains = workUnitsPerTimespan / 3; // figure out timespan units int unitsRemaining = workUnitsPerTimespan; // make two passes to populate queues ... for (int pass = 0; pass < 2; ++pass) { // figure out queue name based on pass byte[] queueName = (pass == 0) ? REDIS_PRIORITY_QUEUE_LT10_KEY : REDIS_PRIORITY_QUEUE_GT10_KEY; // get up to max possible keys ... Set<byte[]> keys = redis.zrange(queueName, 0, unitsRemaining); // figure out units to try and acquire int unitsToAcquire = Math.min(unitsRemaining, (pass == 0) ? unitsForSmallDomains : unitsRemaining); // special case .. if LT queue, see if go all out if large queue is empty ... if (pass == 0 && redis.zcard(REDIS_PRIORITY_QUEUE_GT10_KEY) == 0) { unitsToAcquire = unitsRemaining; }/*from ww w . ja va2 s. com*/ LOG.info("Pass:" + pass + " redisSetSize: " + keys.size() + " unitsToAcquire:" + unitsToAcquire); // keep counts by domain HashMap<byte[], Integer> counts = new HashMap<byte[], Integer>(); HashSet<byte[]> emptyDomainSet = new HashSet<byte[]>(); int itemsAcquiredThisPass = 0; while (unitsToAcquire > 0 && emptyDomainSet.size() != keys.size()) { // walk keys ... for (byte[] domainKey : keys) { if (!emptyDomainSet.contains(domainKey)) { // pop item from database ... Item item = popNextItemFromDatabase(domainKey); if (item != null) { // schedule it... _scheduledItems.add(item); // decerement aggregate count ... unitsToAcquire--; itemsAcquiredThisPass++; // increment localized count .. Integer existingCount = counts.get(domainKey); if (existingCount == null) { counts.put(domainKey, 1); } else { counts.put(domainKey, existingCount.intValue() + 1); } if (unitsToAcquire == 0) break; } else { // add to empty domain set ... emptyDomainSet.add(domainKey); } } } } unitsRemaining -= itemsAcquiredThisPass; LOG.info("update RedisQueues for pass:" + pass + " itemsAcquired:" + itemsAcquiredThisPass + " unitsRemaining:" + unitsRemaining); // ok clear redis counts for domains operated on .. updateRedisQueues(queueName, counts); } }