Example usage for com.google.common.collect Sets intersection

List of usage examples for com.google.common.collect Sets intersection

Introduction

In this page you can find the example usage for com.google.common.collect Sets intersection.

Prototype

public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) 

Source Link

Document

Returns an unmodifiable view of the intersection of two sets.

Usage

From source file:kr.debop4j.data.hibernate.tools.EntityTool.java

/**
 * Assert not circular hierarchy./*from   w  ww  .  j  av a2 s .c o  m*/
 *
 * @param child  the child
 * @param parent the parent
 */
public static <T extends IHierarchyEntity<T>> void assertNotCircularHierarchy(T child, T parent) {
    if (child == parent)
        throw new IllegalArgumentException("Child and Parent are same.");

    if (child.getDescendents().contains(parent))
        throw new IllegalArgumentException("child  parent ? ??  .");

    if (Sets.intersection(parent.getAncestors(), child.getDescendents()).size() > 0)
        throw new IllegalArgumentException(
                "parent? ? child? ?? ? ?  ?.");
}

From source file:pl.edu.icm.cermine.metadata.extraction.enhancers.AuthorTitleSplitterEnhancer.java

@Override
protected boolean enhanceMetadata(BxDocument document, DocumentMetadata metadata) {
    for (BxZone zone : document.getFirstChild()) {
        if (BxZoneLabel.MET_TITLE.equals(zone.getLabel())) {
            return false;
        }/*from www . j  a  v a 2 s.  c  o m*/
    }

    ReadingOrderResolver roResolver = new HierarchicalReadingOrderResolver();

    BxZone toDel = null;
    BxZone toAdd1 = null;
    BxZone toAdd2 = null;

    for (BxZone zone : filterZones(document.getFirstChild())) {
        BxZone z1 = new BxZone();
        z1.setLabel(BxZoneLabel.MET_TITLE);
        BxBoundsBuilder b1 = new BxBoundsBuilder();
        BxZone z2 = new BxZone();
        z2.setLabel(BxZoneLabel.MET_AUTHOR);
        BxBoundsBuilder b2 = new BxBoundsBuilder();
        boolean wasAuthor = false;
        BxLine prev = null;
        for (BxLine line : zone) {
            if (prev != null && Sets.intersection(prev.getFontNames(), line.getFontNames()).isEmpty()) {
                String[] words = line.toText().split(" ");
                int cWordsCount = 0;
                int wordsCount = 0;
                for (String s : words) {
                    if (s.matches(".*[a-zA-Z].*")) {
                        wordsCount++;
                    }
                    if (s.matches("[A-Z].*")) {
                        cWordsCount++;
                    }
                }
                if (line.toText().contains(",") && (double) cWordsCount / (double) wordsCount > 0.7) {
                    wasAuthor = true;
                }
            }
            if (wasAuthor) {
                z2.addLine(line);
                b2.expand(line.getBounds());
            } else {
                z1.addLine(line);
                b1.expand(line.getBounds());
            }
            prev = line;
        }
        z1.setBounds(b1.getBounds());
        z2.setBounds(b2.getBounds());
        if (z1.hasChildren() && z2.hasChildren()) {
            toDel = zone;
            toAdd1 = z1;
            toAdd2 = z2;
        }
    }

    if (toDel != null) {
        List<BxZone> list = new ArrayList<BxZone>();
        list.addAll(Lists.newArrayList(document.getFirstChild()));
        list.remove(toDel);
        list.add(toAdd1);
        list.add(toAdd2);
        document.getFirstChild().setZones(list);
        try {
            roResolver.resolve(document);
        } catch (AnalysisException ex) {
        }
    }

    return false;
}

From source file:org.jclouds.googlecomputeengine.predicates.NetworkFirewallPredicates.java

public static Predicate<Firewall> providesIpPermission(final IpPermission permission) {
    return new Predicate<Firewall>() {
        @Override/*from  w ww  . j av  a  2  s  . c om*/
        public boolean apply(Firewall input) {
            boolean groupsMatchTags = (permission.getGroupIds().isEmpty() && input.getSourceTags().isEmpty())
                    || !Sets.intersection(permission.getGroupIds(), input.getSourceTags()).isEmpty();
            boolean cidrsMatchRanges = (permission.getCidrBlocks().isEmpty()
                    && input.getSourceRanges().isEmpty())
                    || !Sets.intersection(permission.getCidrBlocks(), input.getSourceRanges()).isEmpty();
            boolean firewallHasPorts = hasProtocol(permission.getIpProtocol()).apply(input)
                    && ((permission.getFromPort() == 0 && permission.getToPort() == 0)
                            || hasPortRange(Range.closed(permission.getFromPort(), permission.getToPort()))
                                    .apply(input));

            return groupsMatchTags && cidrsMatchRanges && firewallHasPorts;
        }
    };
}

From source file:eu.crydee.alignment.aligner.ae.EvaluatorC.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    JCas jcasEle;/*from w  w  w  .  j a  va2s .  co  m*/
    try {
        jcasEle = jcas.getView(nameEle);
    } catch (CASException ex) {
        throw new AnalysisEngineProcessException(ex);
    }
    int tp = 0, fp = 0, fn = 0;
    for (Sentence s : JCasUtil.select(jcasEle, Sentence.class)) {
        Set<Sentence> gold = new HashSet<>(), found = new HashSet<>();
        if (s.getGoldSimilarities() == null) {
            continue;
        }
        for (int i = 0, l = s.getGoldSimilarities().size(); i < l; ++i) {
            gold.add(s.getGoldSimilarities(i));
        }
        for (int i = 0, l = s.getFoundSimilarities().size(); i < l; ++i) {
            found.add(s.getFoundSimilarities(i));
        }
        int goldSize = gold.size(), foundSize = found.size(),
                commonSize = Sets.intersection(gold, found).size();
        cm.addTruePositives(commonSize);
        cm.addFalsePositive(foundSize - commonSize);
        cm.addFalseNegatives(goldSize - commonSize);
    }
}

From source file:com.google.gerrit.server.extensions.webui.UiCommands.java

public static <R extends RestResource> Iterable<UiCommandDetail> from(DynamicMap<RestView<R>> views,
        final R resource, final EnumSet<UiCommand.Place> places) {
    return Iterables
            .filter(Iterables.transform(views, new Function<DynamicMap.Entry<RestView<R>>, UiCommandDetail>() {
                @Override/*ww w .  j av a 2  s.  com*/
                @Nullable
                public UiCommandDetail apply(DynamicMap.Entry<RestView<R>> e) {
                    int d = e.getExportName().indexOf('.');
                    if (d < 0) {
                        return null;
                    }

                    String method = e.getExportName().substring(0, d);
                    String name = e.getExportName().substring(d + 1);
                    RestView<R> view;
                    try {
                        view = e.getProvider().get();
                    } catch (RuntimeException err) {
                        log.error(String.format("error creating view %s.%s", e.getPluginName(),
                                e.getExportName()), err);
                        return null;
                    }

                    if (!(view instanceof UiCommand)) {
                        return null;
                    }

                    UiCommand<R> cmd = (UiCommand<R>) view;
                    if (Sets.intersection(cmd.getPlaces(), places).isEmpty() || !cmd.isVisible(resource)) {
                        return null;
                    }

                    UiCommandDetail dsc = new UiCommandDetail();
                    dsc.id = e.getPluginName() + '~' + name;
                    dsc.method = method;
                    dsc.label = cmd.getLabel(resource);
                    dsc.title = cmd.getTitle(resource);
                    dsc.enabled = cmd.isEnabled(resource);
                    dsc.confirmationMessage = cmd.getConfirmationMessage(resource);
                    return dsc;
                }
            }), Predicates.notNull());
}

From source file:com.facebook.buck.cli.OwnersReport.java

OwnersReport updatedWith(OwnersReport other) {
    SetMultimap<TargetNode<?, ?>, Path> updatedOwners = TreeMultimap.create(owners);
    updatedOwners.putAll(other.owners);//w  ww. j  av a 2s. c  om

    return new OwnersReport(updatedOwners, Sets.intersection(inputsWithNoOwners, other.inputsWithNoOwners),
            Sets.union(nonExistentInputs, other.nonExistentInputs),
            Sets.union(nonFileInputs, other.nonFileInputs));
}

From source file:org.mitre.oauth2.service.impl.DefaultIntrospectionResultAssembler.java

@Override
public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo,
        Set<String> authScopes) {

    Map<String, Object> result = newLinkedHashMap();
    OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication();

    result.put(ACTIVE, true);//ww w  . j a  v a 2  s . c om

    if (accessToken.getPermissions() != null && !accessToken.getPermissions().isEmpty()) {

        Set<Object> permissions = Sets.newHashSet();

        for (Permission perm : accessToken.getPermissions()) {
            Map<String, Object> o = newLinkedHashMap();
            o.put("resource_set_id", perm.getResourceSet().getId().toString());
            Set<String> scopes = Sets.newHashSet(perm.getScopes());
            o.put("scopes", scopes);
            permissions.add(o);
        }

        result.put("permissions", permissions);

    } else {
        Set<String> scopes = Sets.intersection(authScopes, accessToken.getScope());

        result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes));

    }

    if (accessToken.getExpiration() != null) {
        try {
            result.put(EXPIRES_AT, dateFormat.valueToString(accessToken.getExpiration()));
            result.put(EXP, accessToken.getExpiration().getTime() / 1000L);
        } catch (ParseException e) {
            logger.error("Parse exception in token introspection", e);
        }
    }

    if (userInfo != null) {
        // if we have a UserInfo, use that for the subject
        result.put(SUB, userInfo.getSub());
    } else {
        // otherwise, use the authentication's username
        result.put(SUB, authentication.getName());
    }

    if (authentication.getUserAuthentication() != null) {
        result.put(USER_ID, authentication.getUserAuthentication().getName());
    }

    result.put(CLIENT_ID, authentication.getOAuth2Request().getClientId());

    result.put(TOKEN_TYPE, accessToken.getTokenType());

    return result;
}

From source file:grakn.core.graql.reasoner.plan.QueryCollectionBase.java

private Set<Equivalence.Wrapper<ReasonerQueryImpl>> getImmediateNeighbours(
        Equivalence.Wrapper<ReasonerQueryImpl> query) {
    ReasonerQueryImpl unwrappedQuery = query.get();
    Set<Variable> vars = unwrappedQuery != null ? unwrappedQuery.getVarNames() : new HashSet<>();
    return this.wrappedStream().filter(q2 -> !query.equals(q2)).map(Equivalence.Wrapper::get)
            .filter(Objects::nonNull).filter(q2 -> !Sets.intersection(vars, q2.getVarNames()).isEmpty())
            .map(q2 -> equality().wrap(q2)).collect(Collectors.toSet());
}

From source file:org.apache.james.mailetcontainer.impl.matchers.Xor.java

private Collection<MailAddress> performXor(Collection<MailAddress> collection1,
        Collection<MailAddress> collection2) {
    ImmutableSet<MailAddress> set1 = ImmutableSet.copyOf(collection1);
    ImmutableSet<MailAddress> set2 = ImmutableSet.copyOf(collection2);
    return Sets.difference(Sets.union(set1, set2), Sets.intersection(set1, set2)).immutableCopy();
}

From source file:com.google.devtools.build.lib.query2.engine.SomePathFunction.java

@Override
public <T> void eval(QueryEnvironment<T> env, VariableContext<T> context, QueryExpression expression,
        List<Argument> args, final Callback<T> callback) throws QueryException, InterruptedException {
    Set<T> fromValue = QueryUtil.evalAll(env, context, args.get(0).getExpression());
    Set<T> toValue = QueryUtil.evalAll(env, context, args.get(1).getExpression());

    // Implementation strategy: for each x in "from", compute its forward
    // transitive closure.  If it intersects "to", then do a path search from x
    // to an arbitrary node in the intersection, and return the path.  This
    // avoids computing the full transitive closure of "from" in some cases.

    env.buildTransitiveClosure(expression, fromValue, Integer.MAX_VALUE);

    // This set contains all nodes whose TC does not intersect "toValue".
    Uniquifier<T> uniquifier = env.createUniquifier();

    for (T x : uniquifier.unique(fromValue)) {
        Set<T> xtc = env.getTransitiveClosure(ImmutableSet.of(x));
        SetView<T> result;//from   w  w w .jav  a2 s  .com
        if (xtc.size() > toValue.size()) {
            result = Sets.intersection(toValue, xtc);
        } else {
            result = Sets.intersection(xtc, toValue);
        }
        if (!result.isEmpty()) {
            callback.process(env.getNodesOnPath(x, result.iterator().next()));
            return;
        }
        uniquifier.unique(xtc);
    }
    callback.process(ImmutableSet.<T>of());
}