List of usage examples for com.google.common.collect Sets intersection
public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2)
From source file:org.dishevelled.venn.model.TernaryVennModelImpl.java
/** * Create a new ternary venn model with the specified sets. * * @param first first set, must not be null * @param second second set, must not be null * @param third third set, must not be null */// w ww . j a v a2 s. c om public TernaryVennModelImpl(final Set<? extends E> first, final Set<? extends E> second, final Set<? extends E> third) { if (first == null) { throw new IllegalArgumentException("first must not be null"); } if (second == null) { throw new IllegalArgumentException("second must not be null"); } if (third == null) { throw new IllegalArgumentException("third must not be null"); } // todo defensive copy? this.first = new ObservableSetImpl(first); this.second = new ObservableSetImpl(second); this.third = new ObservableSetImpl(third); // alias ObservableSet<E> f = this.first; ObservableSet<E> s = this.second; ObservableSet<E> t = this.third; firstOnly = Sets.difference(Sets.difference(f, s), t); // f - s - t secondOnly = Sets.difference(Sets.difference(s, f), t); // s - f - t thirdOnly = Sets.difference(Sets.difference(t, f), s); // t - f - s firstSecond = Sets.difference(Sets.intersection(f, s), t); // f n s - t firstThird = Sets.difference(Sets.intersection(f, t), s); // f n t - s secondThird = Sets.difference(Sets.intersection(s, t), f); // s n t - f intersection = Sets.intersection(f, Sets.intersection(s, t)); // f n s n t union = Sets.union(f, Sets.union(s, t)); // f u s u t selection = new SelectionView<E>(union, f, s, t); exclusives = new HashMap<ImmutableBitSet, Set<E>>(7); exclusives.put(toImmutableBitSet(0), firstOnly); exclusives.put(toImmutableBitSet(1), secondOnly); exclusives.put(toImmutableBitSet(2), thirdOnly); exclusives.put(toImmutableBitSet(0, 1), firstSecond); exclusives.put(toImmutableBitSet(0, 2), firstThird); exclusives.put(toImmutableBitSet(1, 2), secondThird); exclusives.put(toImmutableBitSet(0, 1, 2), intersection); }
From source file:com.siemens.sw360.portal.tags.CompareAttachments.java
private void renderAttachments(StringBuilder display, Set<Attachment> currentAttachments, Set<Attachment> updateAttachments) { Map<String, Attachment> currentAttachmentById = getAttachmentsById(currentAttachments); Map<String, Attachment> updateAttachmentById = getAttachmentsById(updateAttachments); Set<String> currentAttachmentIds = currentAttachmentById.keySet(); Set<String> updateAttachmentIds = updateAttachmentById.keySet(); Set<String> deletedAttachmentIds = Sets.difference(currentAttachmentIds, updateAttachmentIds); Set<String> addedAttachmentIds = Sets.difference(updateAttachmentIds, currentAttachmentIds); Set<String> commonAttachmentIds = Sets.intersection(currentAttachmentIds, updateAttachmentIds); renderAttachmentList(display, currentAttachmentById, deletedAttachmentIds, "Deleted"); renderAttachmentList(display, updateAttachmentById, addedAttachmentIds, "Added"); renderAttachmentComparison(display, currentAttachmentById, updateAttachmentById, commonAttachmentIds); }
From source file:grakn.core.graql.reasoner.cache.SemanticDifference.java
public boolean satisfiedBy(ConceptMap answer) { if (isEmpty()) return true; Map<Variable, Set<Role>> roleRequirements = this.definition.stream() .filter(vd -> !vd.playedRoles().isEmpty()) .collect(Collectors.toMap(VariableDefinition::var, VariableDefinition::playedRoles)); //check for role compatibility Iterator<Map.Entry<Variable, Set<Role>>> reqIterator = roleRequirements.entrySet().iterator(); Set<Relation> relations; if (reqIterator.hasNext()) { Map.Entry<Variable, Set<Role>> req = reqIterator.next(); relations = rolesToRels(req.getKey(), req.getValue(), answer); } else {//w w w .j a v a 2 s .c om relations = new HashSet<>(); } while (!relations.isEmpty() && reqIterator.hasNext()) { Map.Entry<Variable, Set<Role>> req = reqIterator.next(); relations = Sets.intersection(relations, rolesToRels(req.getKey(), req.getValue(), answer)); } if (relations.isEmpty() && !roleRequirements.isEmpty()) return false; return definition.stream().allMatch(vd -> { Variable var = vd.var(); Concept concept = answer.get(var); if (concept == null) return false; Type type = vd.type(); Role role = vd.role(); Set<ValuePredicate> vps = vd.valuePredicates(); return (type == null || type.subs().anyMatch(t -> t.equals(concept.asThing().type()))) && (role == null || role.subs().anyMatch(r -> r.equals(concept.asRole()))) && (vps.isEmpty() || vps.stream().allMatch(vp -> ValueExecutor.Operation.of(vp.getPredicate()) .test(concept.asAttribute().value()))); }); }
From source file:com.wrmsr.wava.transform.Outlining.java
public static OutlinedFunction outlineFunction(Function function, Node node, Name outlinedName, Index externalRetControl, Index externalRetValue, LocalAnalysis loa, ControlTransferAnalysis cfa, ValueTypeAnalysis vta, Map<Node, Optional<Node>> parentsByNode, Map<Name, Node> nodesByName) { final List<Index> allLocals; final List<Index> spilledOutLocalPuts; final List<Index> spilledInLocalGets; {//from w w w . jav a 2s . c o m ImSet<Index> entryLocalGets = loa.get(node).getLocalGets(); ImSet<Index> entryLocalPuts = loa.get(node).getLocalPuts(); ImSet<Index> nonEntryLocalGets = LocalAnalysis.EMPTY_LOCALS; ImSet<Index> nonEntryLocalPuts = LocalAnalysis.EMPTY_LOCALS; Optional<Node> cur = Optional.of(node); while (true) { Optional<Node> next = requireNonNull(parentsByNode.get(cur.get())); if (!next.isPresent()) { break; } for (Node sibling : next.get().getChildren()) { if (sibling == cur.get()) { continue; } nonEntryLocalGets = nonEntryLocalGets.union(loa.get(sibling).getLocalGets()); nonEntryLocalPuts = nonEntryLocalPuts.union(loa.get(sibling).getLocalPuts()); } cur = next; } Set<Index> entryLocals = Sets.union(entryLocalGets, entryLocalPuts); Set<Index> nonEntryLocals = Sets.union(nonEntryLocalGets, nonEntryLocalPuts); Set<Index> entryOnlyLocals = Sets.difference(entryLocals, nonEntryLocals); Set<Index> spilledOutLocalPutsSet = Sets.intersection(entryLocalPuts, nonEntryLocalGets); spilledOutLocalPuts = spilledOutLocalPutsSet.stream().sorted().collect(toImmutableList()); spilledInLocalGets = Sets.intersection(nonEntryLocalPuts, entryLocalGets).stream() .filter(i -> !spilledOutLocalPutsSet.contains(i)).sorted().collect(toImmutableList()); List<Index> entryOnlyLocalList = entryOnlyLocals.stream().sorted().collect(toImmutableList()); checkState( Sets.intersection(ImmutableSet.copyOf(spilledInLocalGets), ImmutableSet.copyOf(entryOnlyLocals)) .isEmpty()); allLocals = ImmutableList.<Index>builder().addAll(spilledOutLocalPuts).addAll(spilledInLocalGets) .addAll(entryOnlyLocalList).build(); } Map<Index, Index> localTranslationMap = enumerate(allLocals.stream()) .collect(toImmutableMap(i -> i.getItem(), i -> Index.of(i.getIndex()))); ControlTransferAnalysis.Entry maxCfa = cfa.get(node); List<ControlTransferAnalysis.Target> targets = ImmutableList.copyOf(maxCfa.getTargets()); Map<ControlTransferAnalysis.Target, Name> targetNameMap = enumerate(targets.stream()) .collect(toImmutableMap(i -> i.getItem(), i -> Name.of("_epilog$" + i.getIndex()))); ImmutableMap.Builder<ControlTransferAnalysis.Target, Type> targetTypesBuilder = ImmutableMap.builder(); for (ControlTransferAnalysis.Target target : targets) { if (target.equals(ControlTransferAnalysis.Target.RETURN)) { targetTypesBuilder.put(ControlTransferAnalysis.Target.RETURN, function.getResult()); } else if (target instanceof ControlTransferAnalysis.NameTarget) { Name name = ((ControlTransferAnalysis.NameTarget) target).getName(); Type type = vta.get(nodesByName.get(name)).getType(); targetTypesBuilder.put(target, type); } else { throw new IllegalStateException(); } } Map<ControlTransferAnalysis.Target, Type> targetTypes = targetTypesBuilder.build(); Node outlinedBody = node.accept(new Visitor<Void, Node>() { @Override protected Node visitNode(Node node, Void context) { return reconstructNode(node, node.getChildren().stream().map(child -> child.accept(this, context)).iterator()); } @Override public Node visitBreak(Break node, Void context) { ControlTransferAnalysis.Target target = ControlTransferAnalysis.Target.of(node.getTarget()); if (targetNameMap.containsKey(target)) { return new Break(targetNameMap.get(ControlTransferAnalysis.Target.of(node.getTarget())), node.getValue().accept(this, context)); } else { return super.visitBreak(node, context); } } @Override public Node visitBreakTable(BreakTable node, Void context) { return super.visitBreakTable(node, context); } @Override public Node visitGetLocal(GetLocal node, Void context) { return new GetLocal(localTranslationMap.get(node.getIndex()), node.getType()); } @Override public Node visitReturn(Return node, Void context) { return new Break(targetNameMap.get(ControlTransferAnalysis.Target.RETURN), node.getValue().accept(this, context)); } @Override public Node visitSetLocal(SetLocal node, Void context) { return new SetLocal(localTranslationMap.get(node.getIndex()), node.getType(), node.getValue().accept(this, context)); } }, null); Index internalRetControl = Index.of(allLocals.size()); Index internalRetValue = Index.of(allLocals.size() + 1); ValueTypeAnalysis.Entry maxVta = vta.get(node); if (maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH) { if (maxVta.getType() != Type.NONE) { outlinedBody = new Block(ImmutableList.of( new SetLocal(internalRetValue, Type.I64, packI64(outlinedBody, maxVta.getType())), new Break(Name.of("_epilog$"), new Nop()))); } else { outlinedBody = new Block(ImmutableList.of(outlinedBody, new Break(Name.of("_epilog$"), new Nop()))); } } for (int i = 0; i < targets.size(); ++i) { ControlTransferAnalysis.Target target = targets.get(i); Name name = targetNameMap.get(target); Type type = targetTypes.get(target); outlinedBody = new Label(name, outlinedBody); switch (type) { case NONE: break; case I32: case I64: case F32: case F64: outlinedBody = new SetLocal(internalRetValue, Type.I64, packI64(outlinedBody, type)); break; default: throw new IllegalStateException(); } outlinedBody = new Block(ImmutableList.of(new Block(ImmutableList.of(outlinedBody, new SetLocal(internalRetControl, Type.I32, new Const(Literal.of(i))), new Break(Name.of("_epilog$"), new Nop()))))); } Node returnValueSpiller = new Call(new Call.HostTarget(HostOp.SpillPut, Optional.empty()), HostOp.SpillPut.getSignature(), ImmutableList.of(new Const(Literal.of(0)), new GetLocal(internalRetValue, Type.I64))); List<Node> localSpillers = enumerate(spilledOutLocalPuts.stream()).map(i -> { Type type = function.getLocals().getLocal(i.getItem()).getType(); return new Call(new Call.HostTarget(HostOp.SpillPut, Optional.empty()), HostOp.SpillPut.getSignature(), ImmutableList.of(new Const(Literal.of(i.getIndex() + 1)), packI64(new GetLocal(localTranslationMap.get(i.getItem()), type), type))); }).collect(toImmutableList()); outlinedBody = new Block(ImmutableList.of( new Label(Name.of("_epilog$"), outlinedBody), new Block(Stream .concat(Stream.of(returnValueSpiller), localSpillers.stream()).collect(toImmutableList())), new Return(new GetLocal(internalRetControl, Type.I32)))); List<Local> localList = ImmutableList.<Local>builder().addAll(allLocals.stream().map(l -> { Local o = function.getLocals().getLocal(l); return new Local(o.getName(), localTranslationMap.get(l), o.getType()); }).iterator()).add(new Local(Name.of("_internal$control"), internalRetControl, Type.I32)) .add(new Local(Name.of("_internal$value"), internalRetValue, Type.I64)).build(); int argCount = spilledOutLocalPuts.size() + spilledInLocalGets.size(); Function outlinedFunction = new Function(outlinedName, Type.I32, argCount, new Locals(localList), outlinedBody); Node outlinedCall = new SetLocal(externalRetControl, Type.I32, new Call(new Call.DirectTarget(outlinedName), outlinedFunction.getSignature(), Stream.concat(spilledOutLocalPuts.stream(), spilledInLocalGets.stream()) .map(i -> new GetLocal(i, function.getLocals().getLocal(i).getType())) .collect(toImmutableList()))); Node returnValueUnspiller = new SetLocal(externalRetValue, Type.I64, new Call(new Call.HostTarget(HostOp.SpillGet, Optional.empty()), HostOp.SpillGet.getSignature(), ImmutableList.of(new Const(Literal.of(0))))); List<Node> localUnspillers = enumerate(spilledOutLocalPuts.stream()).map(i -> { Type type = function.getLocals().getLocal(i.getItem()).getType(); return new SetLocal(i.getItem(), type, unpackI64(new Call(new Call.HostTarget(HostOp.SpillGet, Optional.empty()), HostOp.SpillGet.getSignature(), ImmutableList.of(new Const(Literal.of(i.getIndex() + 1)))), type)); }).collect(toImmutableList()); Node controlSwitch = new Switch(new GetLocal(externalRetControl, Type.I32), Stream.concat(enumerate(targets.stream()).map(i -> { if (i.getItem().equals(ControlTransferAnalysis.Target.RETURN)) { return new Switch.Entry(ImmutableList.of(Switch.Value.of(i.getIndex() + 1)), new Return( unpackI64(new GetLocal(externalRetValue, Type.I64), function.getResult()))); } else if (i.getItem() instanceof ControlTransferAnalysis.NameTarget) { Name name = ((ControlTransferAnalysis.NameTarget) i.getItem()).getName(); Type type = vta.get(nodesByName.get(name)).getType(); Node value = type != Type.NONE ? unpackI64(new GetLocal(externalRetValue, Type.I64), function.getResult()) : new Nop(); return new Switch.Entry(ImmutableList.of(Switch.Value.of(i.getIndex() + 1)), new Break(name, value)); } else { throw new IllegalStateException(); } }), Stream.concat( Stream.of(new Switch.Entry(ImmutableList.of(Switch.Value.DEFAULT), new Unreachable())), maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH ? Stream.of(new Switch.Entry(ImmutableList.of(Switch.Value.of(0)), new Nop())) : Stream.empty())) .collect(toImmutableList())); Node callsite = new Block(ImmutableList.<Node>builder().add(outlinedCall).add(returnValueUnspiller) .addAll(localUnspillers).add(controlSwitch) .add(maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH ? unpackI64(new GetLocal(externalRetControl, Type.I64), maxVta.getType()) : new Nop()) .build()); return new OutlinedFunction(callsite, outlinedFunction); }
From source file:indigo.specification.AbstractSpecification.java
@Override public Invariant invariantFor(Collection<String> ops, AnalysisContext context) { Invariant res;/*from www.j av a2 s .c o m*/ Set<Invariant> ss = null; for (String op : ops) { Set<Invariant> si = Sets.newHashSet(); context.getOperationEffects(op, false, false).forEach(e -> { si.addAll(predicate2Invariants.get(e)); }); context.getOperationPreConditions(op, false, false).forEach(e -> { si.addAll(predicate2Invariants.get(e)); }); ss = Sets.intersection(ss != null ? ss : si, si); } if (ss.isEmpty()) { res = newEmptyInv(); } else { res = ss.stream().reduce(null, (mergeAcc, next) -> { if (mergeAcc == null) { return next; } else { try { return new GenericInvariant(mergeAcc.mergeClause(next)); } catch (Exception e) { e.printStackTrace(); } return mergeAcc; } }); } analysisLog.fine("\n; -----------------------------------------------------------------------"); analysisLog.fine("Operations:"); analysisLog.fine("; " + ops); analysisLog.fine("; Simplified Invariant for " + ops + " --> " + res); return res; }
From source file:org.apache.gobblin.metastore.DatabaseJobHistoryStore.java
private static VersionedDatabaseJobHistoryStore findVersionedDatabaseJobHistoryStore( MigrationVersion requiredVersion) throws IllegalAccessException, InstantiationException, ClassNotFoundException { Class<?> foundClazz = null; Class<?> defaultClazz = null; MigrationVersion defaultVersion = MigrationVersion.EMPTY; for (Class<?> clazz : Sets.intersection(reflections.getTypesAnnotatedWith(SupportedDatabaseVersion.class), reflections.getSubTypesOf(VersionedDatabaseJobHistoryStore.class))) { SupportedDatabaseVersion annotation = clazz.getAnnotation(SupportedDatabaseVersion.class); String version = annotation.version(); MigrationVersion actualVersion = MigrationVersion .fromVersion(Strings.isNullOrEmpty(version) ? null : version); if (annotation.isDefault() && actualVersion.compareTo(defaultVersion) > 0) { defaultClazz = clazz;/*from ww w. j a v a 2 s. c o m*/ defaultVersion = actualVersion; } if (actualVersion.compareTo(requiredVersion) == 0) { foundClazz = clazz; } } if (foundClazz == null) { foundClazz = defaultClazz; } if (foundClazz == null) { throw new ClassNotFoundException( String.format("Could not find an instance of %s which supports database " + "version %s.", VersionedDatabaseJobHistoryStore.class.getSimpleName(), requiredVersion.toString())); } return (VersionedDatabaseJobHistoryStore) foundClazz.newInstance(); }
From source file:org.aksw.simba.bengal.triple2nl.gender.TypeAwareGenderDetector.java
private boolean isPerson(String uri) { if (personTypes.isEmpty()) { return true; } else {/*from w ww . ja v a2 s . c o m*/ // g et types of URI Set<String> types = new HashSet<>(); try { String query = "SELECT ?type WHERE {<" + uri + "> a ?type.}"; try (QueryExecution qe = qef.createQueryExecution(query)) { ResultSet rs = qe.execSelect(); while (rs.hasNext()) { types.add(rs.next().getResource("type").getURI()); } } } catch (Exception e) { int code = ((QueryExceptionHTTP) e.getCause()).getResponseCode(); logger.warn("SPARQL query execution failed: " + code + " - " + HttpSC.getCode(code).getMessage()); } // check for overlap between types of entity and person types return !Sets.intersection(personTypes, types).isEmpty(); } }
From source file:org.apache.hadoop.hbase.util.FSHDFSUtils.java
/** * @param conf the Configuration of HBase * @param srcFs//from w w w .ja v a 2 s. c o m * @param desFs * @return Whether srcFs and desFs are on same hdfs or not */ public static boolean isSameHdfs(Configuration conf, FileSystem srcFs, FileSystem desFs) { // By getCanonicalServiceName, we could make sure both srcFs and desFs // show a unified format which contains scheme, host and port. String srcServiceName = srcFs.getCanonicalServiceName(); String desServiceName = desFs.getCanonicalServiceName(); if (srcServiceName == null || desServiceName == null) { return false; } if (srcServiceName.equals(desServiceName)) { return true; } if (srcFs instanceof DistributedFileSystem && desFs instanceof DistributedFileSystem) { //If one serviceName is an HA format while the other is a non-HA format, // maybe they refer to the same FileSystem. //For example, srcFs is "ha-hdfs://nameservices" and desFs is "hdfs://activeNamenode:port" Set<InetSocketAddress> srcAddrs = getNNAddresses((DistributedFileSystem) srcFs, conf); Set<InetSocketAddress> desAddrs = getNNAddresses((DistributedFileSystem) desFs, conf); if (Sets.intersection(srcAddrs, desAddrs).size() > 0) { return true; } } return false; }
From source file:ome.services.blitz.repo.path.FilePathRestrictions.java
/** * Combine sets of rules to form a set that satisfies them all. * @param rules at least one set of rules * @return the intersection of the given rules *//*from ww w .j av a 2 s . c om*/ private static FilePathRestrictions combineRules(FilePathRestrictions... rules) { if (rules.length == 0) { throw new IllegalArgumentException("cannot combine an empty list of rules"); } int index = 0; FilePathRestrictions product = rules[index++]; while (index < rules.length) { final FilePathRestrictions toCombine = rules[index++]; final Set<Character> safeCharacters = Sets.intersection(product.safeCharacters, toCombine.safeCharacters); if (safeCharacters.isEmpty()) { throw new IllegalArgumentException("cannot combine safe characters"); } final Set<Integer> allKeys = Sets.union(product.transformationMatrix.keySet(), toCombine.transformationMatrix.keySet()); final ImmutableMap<Integer, Collection<Integer>> productMatrixMap = product.transformationMatrix .asMap(); final ImmutableMap<Integer, Collection<Integer>> toCombineMatrixMap = toCombine.transformationMatrix .asMap(); final SetMultimap<Integer, Integer> newTransformationMatrix = HashMultimap.create(); for (final Integer key : allKeys) { final Collection<Integer> values; if (!productMatrixMap.containsKey(key)) { values = toCombineMatrixMap.get(key); } else if (!toCombineMatrixMap.containsKey(key)) { values = productMatrixMap.get(key); } else { final Set<Integer> valuesSet = new HashSet<Integer>(productMatrixMap.get(key)); valuesSet.retainAll(toCombineMatrixMap.get(key)); if (valuesSet.isEmpty()) { throw new IllegalArgumentException( "cannot combine transformations for Unicode code point " + key); } values = valuesSet; } for (final Integer value : values) { newTransformationMatrix.put(key, value); } } final SetMultimap<Integer, Integer> entriesRemoved = HashMultimap.create(); boolean transitiveClosing; do { transitiveClosing = false; for (final Entry<Integer, Integer> transformation : newTransformationMatrix.entries()) { final int to = transformation.getValue(); if (newTransformationMatrix.containsKey(to)) { final int from = transformation.getKey(); if (!entriesRemoved.put(from, to)) { throw new IllegalArgumentException( "cyclic transformation involving Unicode code point " + from); } newTransformationMatrix.remove(from, to); newTransformationMatrix.putAll(from, newTransformationMatrix.get(to)); transitiveClosing = true; break; } } } while (transitiveClosing); product = new FilePathRestrictions(newTransformationMatrix, Sets.union(product.unsafePrefixes, toCombine.unsafePrefixes), Sets.union(product.unsafeSuffixes, toCombine.unsafeSuffixes), Sets.union(product.unsafeNames, toCombine.unsafeNames), safeCharacters); } return product; }
From source file:com.google.appengine.tools.cloudstorage.ExceptionHandler.java
private ExceptionHandler(Builder builder) { retriableExceptions = builder.retriableExceptions.build(); nonRetriableExceptions = builder.nonRetriableExceptions.build(); Preconditions.checkArgument(Sets.intersection(retriableExceptions, nonRetriableExceptions).isEmpty(), "Same exception was found in both retriable and non-retriable sets"); for (Class<? extends Exception> exception : retriableExceptions) { addToRetryInfos(retryInfos, new RetryInfo(exception, true)); }// w w w .j av a 2 s . c o m for (Class<? extends Exception> exception : nonRetriableExceptions) { addToRetryInfos(retryInfos, new RetryInfo(exception, false)); } }