List of usage examples for java.util HashSet retainAll
boolean retainAll(Collection<?> c);
From source file:org.jactr.core.module.declarative.search.local.DefaultSearchSystem.java
/** * this implementation fails fast/*w ww . java 2s. co m*/ * * @see org.jactr.core.module.declarative.search.ISearchSystem#findExact(ChunkTypeRequest, * java.util.Comparator) */ public Collection<IChunk> findExact(ChunkTypeRequest pattern, Comparator<IChunk> sortRule) { /* * second pass, ditch all those that don't match our chunktype */ HashSet<IChunk> candidates = new HashSet<IChunk>(); IChunkType chunkType = pattern.getChunkType(); if (chunkType != null) candidates.addAll(chunkType.getSymbolicChunkType().getChunks()); /* * first things first, find all the candidates based on the content of the * pattern */ boolean first = chunkType == null; for (IConditionalSlot slot : pattern.getConditionalSlots()) { if (first) { candidates.addAll(find(slot)); first = false; } else candidates.retainAll(find(slot)); if (candidates.size() == 0) break; } if (LOGGER.isDebugEnabled()) LOGGER.debug("First pass candidates for " + pattern + " chunks: " + candidates); if (sortRule != null) { /* * finally, we sort them */ TreeSet<IChunk> sortedResults = new TreeSet<IChunk>(sortRule); sortedResults.addAll(candidates); return sortedResults; } return candidates; }
From source file:ch.unil.genescore.pathway.GeneSetLibrary.java
License:asdf
public void computeApproxPathwayCorrelationLowerBound() { DenseMatrix corMat = new DenseMatrix(geneSets_.size(), geneSets_.size()); for (int i = 0; i < geneSets_.size(); i++) { HashSet<Gene> leftSet = geneSets_.get(i).genes_; double leftSize = leftSet.size(); for (int j = 0; j < geneSets_.size(); j++) { HashSet<Gene> rightSet = geneSets_.get(j).genes_; double rightSize = rightSet.size(); HashSet<Gene> copyLeftSet = new HashSet<Gene>(leftSet); copyLeftSet.retainAll(rightSet); double count = copyLeftSet.size(); double corr = count / Math.sqrt(leftSize * rightSize); //double corr = count; corMat.set(i, j, corr);//from ww w .j a va2 s .c o m } } pathwayCorMat_ = corMat; }
From source file:ch.unil.genescore.pathway.GeneSetLibrary.java
License:asdf
public void computeApproxPathwayCorrelation() { DenseMatrix corMat = new DenseMatrix(geneSets_.size(), geneSets_.size()); for (int i = 0; i < geneSets_.size(); i++) { GeneSet leftSet = geneSets_.get(i); double leftSize = leftSet.genes_.size(); for (int j = 0; j < geneSets_.size(); j++) { GeneSet rightSet = geneSets_.get(j); double rightSize = rightSet.genes_.size(); HashSet<Gene> unpackedMetaGenes = new HashSet<Gene>(); HashSet<Gene> allRightGenes = new HashSet<Gene>(); if (null != rightSet.getMetaGenes()) for (MetaGene mg : rightSet.getMetaGenes()) { unpackedMetaGenes.addAll(mg.getGenes()); }//from ww w .j a va 2s .c o m allRightGenes.addAll(unpackedMetaGenes); allRightGenes.addAll(rightSet.genes_); allRightGenes.removeAll(rightSet.getMetaGenes()); HashSet<Gene> copiedLeftGenes = new HashSet<Gene>(leftSet.genes_); copiedLeftGenes.retainAll(allRightGenes); double count = copiedLeftGenes.size(); if (null != leftSet.getMetaGenes()) for (MetaGene mg : leftSet.getMetaGenes()) { TreeSet<Gene> mgSetCopy = new TreeSet<Gene>(mg.getGenes()); mgSetCopy.retainAll(allRightGenes); if (!mgSetCopy.isEmpty()) { count++; } } double corr = count / Math.sqrt(leftSize * rightSize); corMat.set(i, j, corr); //corMat.set(j, i, corr); } } pathwayCorMat_ = corMat; }
From source file:net.itransformers.topologyviewer.gui.GraphViewerPanel.java
private G transformCurrentGraph(final FilterType filter, Map<String, DataMatcher> matcherMap, final Integer hops, final Set<String> pickedVertexes) { final Map<String, GraphMLMetadata<String>> edgeMetadatas1 = graphmlLoader.getEdgeMetadatas(); EdgePredicateFilter<String, String> edgeFilter = EdgeFilterFactory.createEdgeFilter(filter, matcherMap, edgeMetadatas1);//from ww w. j a va2 s . c om final Graph<String, String> graph1 = edgeFilter.transform(currentGraph); VertexPredicateFilter<String, String> filterV = VertexFilterFactory.createVertexFilter(filter, matcherMap, graphmlLoader.getVertexMetadatas(), graph1); G graph2 = (G) filterV.transform(graph1); HashSet<String> set = new HashSet<String>(graph2.getVertices()); if (pickedVertexes != null) { if (pickedVertexes.size() != 0) { set.retainAll(pickedVertexes); } } KNeighborhoodFilter<String, String> f = new KNeighborhoodFilter<String, String>(set, hops, KNeighborhoodFilter.EdgeType.IN_OUT); return (G) f.transform(graph2); }
From source file:net.itransformers.topologyviewer.gui.GraphViewerPanel.java
private G transformGraph(final FilterType filter, final Integer hops, final Set<String> pickedVertexes) { final Map<String, GraphMLMetadata<String>> edgeMetadatas1 = graphmlLoader.getEdgeMetadatas(); Map<String, DataMatcher> matcherMap = new HashMap<String, DataMatcher>(); List<DataMatcherType> matcherList = viewerConfig.getDataMatcher(); for (DataMatcherType dataMatcherType : matcherList) { String className = dataMatcherType.getClazz(); Class clazz = null;// ww w . j a va 2s. c o m try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { logger.error("Can not find class: " + className, e); } try { DataMatcher dataMatcher = (DataMatcher) clazz.newInstance(); matcherMap.put(dataMatcherType.getName(), dataMatcher); } catch (InstantiationException e) { logger.error("Can not instantiate class: " + className, e); } catch (IllegalAccessException e) { logger.error("Can not access constructor class: " + className, e); } } EdgePredicateFilter<String, String> edgeFilter = EdgeFilterFactory.createEdgeFilter(filter, matcherMap, edgeMetadatas1); final Graph<String, String> graph1 = edgeFilter.transform(entireGraph); VertexPredicateFilter<String, String> filterV = VertexFilterFactory.createVertexFilter(filter, matcherMap, graphmlLoader.getVertexMetadatas(), graph1); G graph2 = (G) filterV.transform(graph1); HashSet<String> set = new HashSet<String>(graph2.getVertices()); if (pickedVertexes != null) { if (pickedVertexes.size() != 0) { set.retainAll(pickedVertexes); } } KNeighborhoodFilter<String, String> f = new KNeighborhoodFilter<String, String>(set, hops, KNeighborhoodFilter.EdgeType.IN_OUT); return (G) f.transform(graph2); }
From source file:me.mneri.rice.Connection.java
private void initCallbacks() { // Cambi di stato on(REGISTER, event -> {/*from w w w . ja v a 2s. com*/ if (mAutoJoin.size() > 0) { for (String channel : mAutoJoin) join(channel); mAutoJoin.clear(); } else { for (Conversation conversation : mConversations.values()) { if (conversation.getType() == Conversation.Type.CHANNEL) join(conversation.getName()); } } }); on(CLOSE, event -> { OutputInterfaceFactory f = OutputInterfaceFactory.instance(); //@formatter:off try { mSocket.close(); } catch (Exception ignored) { } finally { mSocket = null; } try { mInputThread.quit(); } catch (Exception ignored) { } finally { mInputThread = null; } try { f.release(mOutputInterface); } catch (Exception ignored) { } finally { mOutputInterface = null; } //@formatter:on mCapabilities.clear(); mCurrentHost = null; mHostCapabilities.clear(); mHostIrcdVersion = null; }); // Ricezione messaggi on(AUTHENTICATE, event -> { String body = mWantedNick + "\0" + mUser + "\0" + mPass; sendRawString("AUTHENTICATE " + new String(Base64.encodeBase64(body.getBytes())) + "\r\n"); }); on(AWAY, (Event event) -> { Message message = (Message) event.data; if (message.params.size() > 0) { // TODO: User is away } else { // TODO: User is returned } }); on(CAP, event -> { Message message = (Message) event.data; String sub = message.params.get(1); if (sub.equals("ACK")) { ArrayList<String> caps = new ArrayList<>(Arrays.asList(message.params.get(2).split("\\s+"))); for (String cap : caps) { if (cap.startsWith("-")) mCapabilities.remove(cap.substring(1)); else mCapabilities.add(cap.replaceAll("[-~=]", "")); } } }); on(CAP, event -> { Message message = (Message) event.data; String sub = message.params.get(1); if (mState == State.CONNECTED) { ArrayList<String> caps = new ArrayList<>(Arrays.asList(message.params.get(2).split("\\s+"))); switch (sub) { case "ACK": if (caps.contains("sasl")) sendRawString("AUTHENTICATE PLAIN\r\n"); else cap("END"); break; case "LS": mHostCapabilities.addAll(caps); HashSet<String> wanted = new HashSet<>(mWantedCapabilities); wanted.retainAll(caps); if (TextUtils.isEmpty(mPass)) wanted.remove("sasl"); if (wanted.isEmpty()) { cap("END"); } else { StringBundler requesting = new StringBundler(); for (String s : wanted) requesting.append(s).append(" "); cap("REQ", requesting.toString()); } } } }); on(ERR_NICKNAMEINUSE, new Callback() { private int mTries; @Override public void performAction(Event event) { if (mState == State.CONNECTED && mAutoNickChange) nick(mWantedNick + (++mTries)); } }); on(JOIN, event -> { Message message = (Message) event.data; User user = mUsers.get(message.nick); if (mUser == null) user = new User(message.nick, message.user, message.host); if (mCapabilities.contains("extended-join")) { user.setAccount(message.params.get(1)); user.setReal(message.params.get(2)); } String channel = message.params.get(0); }); on(MODE, event -> { Message message = (Message) event.data; String target = message.params.get(0); String specs = message.params.get(1); // Ci interessa solo la nostra user mode if (target.equals(mNick)) { char mode; boolean value = false; for (int i = 0; i < specs.length(); i++) { mode = specs.charAt(i); //@formatter:off if (mode == '+') value = true; else if (mode == '-') value = false; else if (mode != ' ') mUserMode.put(mode, value); //@formatter:on } } }); on(NICK, event -> { Message message = (Message) event.data; if (TextUtils.compareIgnoreCase(mNick, message.nick, mCaseMapping) == 0) mNick = message.params.get(0); }); on(PING, event -> { Message message = (Message) event.data; pong(message.params.get(0)); }); on(RPL_ISUPPORT, event -> { Message message = (Message) event.data; Pattern pattern = Pattern.compile("Try server (.+), port (\\d+)"); Matcher matcher = pattern.matcher(message.params.get(1)); boolean isRplBounce = matcher.find(); if (isRplBounce) { mIsupportCompilant = false; try { if (mAutoBounce) { mHost = matcher.group(1); mPort = Integer.parseInt(matcher.group(2)); emit(new Event(BOUNCE, this)); stop(); start(); } } catch (Exception ignored) { } } else { mIsupportCompilant = true; pattern = Pattern.compile("([A-Z]+)(=(\\S+))?"); for (int i = 1; i < message.params.size(); i++) { matcher = pattern.matcher(message.params.get(i)); while (matcher.find()) { String key = matcher.group(1); String value = matcher.group(3); try { switch (key) { case "CASEMAPPING": if (value.equals("ascii")) mCaseMapping = CaseMapping.ASCII; else if (value.equals("strict-rfc1459")) mCaseMapping = CaseMapping.STRICT_RFC1459; break; case "NETWORK": mNetwork = value; break; } } catch (Exception ignored) { } } } } }); on(RPL_MYINFO, event -> { Message message = (Message) event.data; mCurrentHost = message.params.get(1); mHostIrcdVersion = message.params.get(2); String userModes = message.params.get(3); String channelModes = message.params.get(4); for (int i = 0; i < userModes.length(); i++) mUserMode.put(userModes.charAt(i), false); for (int i = 0; i < channelModes.length(); i++) mAvailChannelModes.add(channelModes.charAt(i)); mState = State.REGISTERED; emit(new Event(REGISTER, this)); }); on(RPL_SASLSUCCESS, event -> { if (mState == State.CONNECTED) cap("END"); }); on(RPL_WELCOME, (Event event) -> { Message message = (Message) event.data; mNick = message.params.get(0); }); // Stato delle conversazioni on(JOIN, event -> { Message message = (Message) event.data; String target = message.params.get(0); Conversation conversation = mConversations.get(target); if (conversation == null) { conversation = new Conversation(target, mFactory); mConversations.put(target, conversation); emit(new Event(NEW_CONVERSATION, conversation)); } conversation.addUser(message.nick); }); on(new String[] { KICK, PART }, event -> { Message message = (Message) event.data; String conversationName = message.params.get(0); String target; if (message.command.equals(PART)) target = message.nick; else target = message.params.get(1); if (TextUtils.compareIgnoreCase(target, mNick, mCaseMapping) == 0) { Conversation conversation = mConversations.remove(conversationName); emit(new Event(REMOVE_CONVERSATION, conversation)); } else { Conversation conversation = mConversations.get(conversationName); if (conversation == null) { conversation = new Conversation(conversationName, mFactory); mConversations.put(conversationName, conversation); emit(new Event(NEW_CONVERSATION, conversation)); } conversation.removeUser(target); conversation.putMessage(message); } }); on(new String[] { JOIN, NOTICE, PRIVMSG }, event -> { Message message = (Message) event.data; String target = message.params.get(0); if (message.command.equals(PRIVMSG) || message.command.equals(NOTICE)) { if (mState == State.REGISTERED) { if (TextUtils.compareIgnoreCase(target, mNick, mCaseMapping) == 0) target = message.nick; } } Conversation conversation = mConversations.get(target); if (conversation == null) { conversation = new Conversation(target, mFactory); mConversations.put(target, conversation); emit(new Event(NEW_CONVERSATION, conversation)); } conversation.putMessage(message); }); on(NICK, event -> { Message message = (Message) event.data; for (Conversation conversation : mConversations.values()) { if (conversation.contains(message.nick)) { conversation.removeUser(message.nick); conversation.addUser(message.params.get(0)); conversation.putMessage(message); } } }); on(new String[] { RPL_NAMREPLY, RPL_ENDOFNAMES }, new Callback() { StringBundler sb; @Override public void performAction(Event event) { Message message = (Message) event.data; switch (message.command) { case RPL_NAMREPLY: if (sb == null) sb = new StringBundler(); sb.append(" "); sb.append(message.params.get(3)); break; case RPL_ENDOFNAMES: String target = message.params.get(1); Conversation conversation = mConversations.get(target); if (conversation == null) { conversation = new Conversation(target, mFactory); mConversations.put(target, conversation); emit(new Event(NEW_CONVERSATION, conversation)); } conversation.clearUsers(); conversation.addUsers(Arrays.asList(sb.toString().split("\\s+"))); sb = null; } } }); on(RPL_WHOREPLY, event -> { Message message = (Message) event.data; String user = message.params.get(2); String host = message.params.get(3); String server = message.params.get(4); String nick = message.params.get(5); boolean away = message.params.get(6).equals("G"); }); on(QUIT, event -> { Message message = (Message) event.data; for (Conversation conversation : mConversations.values()) { if (conversation.contains(message.nick)) { conversation.removeUser(message.nick); conversation.putMessage(message); } } }); }
From source file:exm.stc.frontend.ASTWalker.java
private void waitStmt(Context context, SwiftAST tree) throws UserException { Wait wait = Wait.fromAST(context, tree); ArrayList<Var> waitEvaled = new ArrayList<Var>(); for (SwiftAST expr : wait.getWaitExprs()) { Type waitExprType = TypeChecker.findExprType(context, expr); if (Types.isUnion(waitExprType)) { // Choose first alternative type for (Type alt : UnionType.getAlternatives(waitExprType)) { if (Types.canWaitForFinalize(alt)) { waitExprType = alt;//w w w .jav a2 s . co m break; } } } if (!Types.canWaitForFinalize(waitExprType)) { throw new TypeMismatchException(context, "Waiting for type " + waitExprType.typeName() + " is not supported"); } Var res = exprWalker.eval(context, expr, waitExprType, false, null); waitEvaled.add(res); } ArrayList<Var> keepOpenVars = new ArrayList<Var>(); summariseBranchVariableUsage(context, Arrays.asList(wait.getBlock().getVariableUsage()), keepOpenVars); // Quick sanity check to see we're not directly blocking // on any arrays written inside HashSet<String> waitVarSet = new HashSet<String>(Var.nameList(waitEvaled)); waitVarSet.retainAll(Var.nameList(keepOpenVars)); if (waitVarSet.size() > 0) { throw new UserException(context, "Deadlock in wait statement. The following arrays are written " + "inside the body of the wait: " + waitVarSet.toString()); } backend.startWaitStatement(context.getFunctionContext().constructName("explicit-wait"), VarRepr.backendVars(waitEvaled), WaitMode.WAIT_ONLY, true, wait.isDeepWait(), ExecTarget.nonDispatchedControl()); block(LocalContext.fnSubcontext(context), wait.getBlock()); backend.endWaitStatement(); }
From source file:org.epics.archiverappliance.config.DefaultConfigService.java
@Override public Set<String> getPVsForApplianceMatchingRegex(String nameToMatch) { logger.debug("Finding matching names for " + nameToMatch); LinkedList<String> fixedStringParts = new LinkedList<String>(); String[] parts = this.pvName2KeyConverter.breakIntoParts(nameToMatch); Pattern fixedStringParttern = Pattern.compile("[a-zA-Z_0-9-]+"); for (String part : parts) { if (fixedStringParttern.matcher(part).matches()) { logger.debug("Fixed string part " + part); fixedStringParts.add(part);//from w ww .j av a2 s . com } else { logger.debug("Regex string part " + part); } } if (fixedStringParts.size() > 0) { HashSet<String> ret = new HashSet<String>(); HashSet<String> namesSubset = new HashSet<String>(); // This reverse is probably specific to SLAC's namespace rules but it does make a big difference. // Perhaps we can use a more intelligent way of choosing the specific path thru the trie. Collections.reverse(fixedStringParts); for (String fixedStringPart : fixedStringParts) { ConcurrentSkipListSet<String> pvNamesForPart = parts2PVNamesForThisAppliance.get(fixedStringPart); if (pvNamesForPart != null) { if (namesSubset.isEmpty()) { namesSubset.addAll(pvNamesForPart); } else { namesSubset.retainAll(pvNamesForPart); } } } logger.debug("Using fixed string path matching against names " + namesSubset.size()); Pattern pattern = Pattern.compile(nameToMatch); for (String pvName : namesSubset) { if (pattern.matcher(pvName).matches()) { ret.add(pvName); } } return ret; } else { // The use pattern did not have any fixed elements at all. // In this case we do brute force matching; should take longer. // This is also not optimal but probably don't want yet another list of PV's Pattern pattern = Pattern.compile(nameToMatch); HashSet<String> allNames = new HashSet<String>(); HashSet<String> ret = new HashSet<String>(); logger.debug("Using brute force pattern matching against names"); for (ConcurrentSkipListSet<String> pvNamesForPart : parts2PVNamesForThisAppliance.values()) { allNames.addAll(pvNamesForPart); } for (String pvName : allNames) { if (pattern.matcher(pvName).matches()) { ret.add(pvName); } } return ret; } }
From source file:dao.UserpageDaoDb.java
/** * this method returns the second degree of friends * @param userpage - the userpage// w w w .j a v a2 s.c o m * @param friend1 - the friend1 * @param friend2 - the friend2 * @throws BaseDaoException - when error occurs */ private void getMySecondFriends(Userpage userpage, String friend1, String friend2, int accessFlag) throws BaseDaoException { if ((userpage == null) || (friend1 == null) || (friend2 == null)) { userpage.setSecondFriends(null); return; } /** * friend1 */ Hdlogin hdlogin = getLoginid(friend1); if (hdlogin == null) { return; } String friendid1 = hdlogin.getValue(DbConstants.LOGIN_ID); /** * friend2 */ hdlogin = getLoginid(friend2); if (hdlogin == null) { return; } /** * first query */ String friendid2 = hdlogin.getValue(DbConstants.LOGIN_ID); Object[] params = { (Object) friendid1, (Object) friendid1 }; List result = null; /** * hdlogin, pendingfriends - no partitioned */ /* String sourceName = null; sourceName = scalabilityManager.getReadZeroScalability(); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException("ds null " + sourceName); } */ String queryName = null; if (accessFlag == 1) { queryName = scalabilityManager.getWriteZeroScalability("friendcheckquery"); } else { queryName = scalabilityManager.getReadZeroScalability("friendcheckquery"); } friendCheckQuery = getQueryMapper().getQuery(queryName); try { result = friendCheckQuery.execute(params); } catch (Exception e) { throw new BaseDaoException("error executing Query" + friendCheckQuery.getSql(), e); } HashSet hs1 = new HashSet(); if ((result != null) && (result.size() > 0)) { for (int i = 0; i < result.size(); i++) { hs1.add(((Friend) result.get(i)).getValue(DbConstants.FID)); } } Iterator it1; it1 = hs1.iterator(); /** * second query */ params[0] = friendid2; params[1] = friendid2; List result2 = null; try { result2 = friendCheckQuery.execute(params); } catch (Exception e) { throw new BaseDaoException("error executing Query", e); } HashSet hs2 = new HashSet(); if (result2 != null) { if (result2.size() > 0) { for (int i = 0; i < result2.size(); i++) { hs2.add(((Friend) result2.get(i)).getValue(DbConstants.FID)); } } } /** return the intersection of the two sets */ boolean f = hs1.retainAll(hs2); if (hs1.size() == 0) return; /** get the friendids and get the login names */ Iterator it3; it3 = hs1.iterator(); HashSet friendSet = new HashSet(); Hdlogin friendLogin = null; while (it3.hasNext()) { //HdloginidQuery hQuery = new HdloginidQuery(ds); // friendResult = hdloginidQuery.execute(myParams); friendLogin = getLoginid((String) it3.next()); if (friendLogin != null) { friendSet.add(friendLogin); } } userpage.setSecondFriends(friendSet); }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public boolean myStudentPageGroupsOk(SimplePageItem item) { Group group = null;//from w ww. j a v a2 s . c o m String groupId = null; if (item.isGroupOwned()) { // all groups we are a member of Collection<Group> groups = getCurrentSite().getGroupsWithMember(getCurrentUserId()); String allowedString = item.getOwnerGroups(); // if no group list specified, we're OK if user is in any groups if (allowedString == null || allowedString.length() == 0) return groups != null && groups.size() > 0; // otherwise have to check HashSet<String> allowedIds = new HashSet<String>(Arrays.asList(allowedString.split(","))); HashSet<String> inIds = new HashSet<String>(); for (Group g : groups) inIds.add(g.getId()); // see if overlap between allowed and in inIds.retainAll(allowedIds); return inIds.size() > 0; } // if not group owned, always OK return true; }