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:com.spotify.trickle.TraverseState.java

void addBindings(Map<Input<?>, Object> newBindings) {
    Sets.SetView<Input<?>> intersection = Sets.intersection(bindings.keySet(), newBindings.keySet());
    checkState(intersection.isEmpty(), "Duplicate binding for inputs: %s", intersection);
    bindings.putAll(newBindings);// w w w.j a v  a2s .co  m
}

From source file:com.github.lukaszkusek.xml.comparator.comparators.order.XMLCheckChildrenOrderComparator.java

private Sets.SetView<String> intersection(List<String> list1, List<String> list2) {
    return Sets.intersection(Sets.<String>newHashSet(list1), Sets.<String>newHashSet(list2));
}

From source file:no.ssb.vtl.script.expressions.FunctionExpression.java

@VisibleForTesting
static Map<String, VTLExpression> mergeArguments(VTLFunction.Signature signature, List<VTLExpression> arguments,
        Map<String, VTLExpression> namedArguments) {

    // Check unnamed arguments count.
    checkArgument(arguments.size() <= signature.size(), TOO_MANY_ARGUMENTS, signature.size(), arguments.size());

    ImmutableMap.Builder<String, VTLExpression> builder = ImmutableMap.builder();

    // Match the list with the signature names.
    Iterator<String> namesIterator = signature.keySet().iterator();
    for (VTLExpression argument : arguments) {
        builder.put(namesIterator.next(), argument);
    }//  ww  w  . ja v  a2 s. c  om

    // Check for duplicates
    Set<String> duplicates = Sets.intersection(namedArguments.keySet(), builder.build().keySet());
    checkArgument(duplicates.isEmpty(), DUPLICATE_ARGUMENTS, String.join(", ", duplicates));

    ImmutableMap<String, VTLExpression> computedArguments = builder.putAll(namedArguments).build();

    // Check for unknown arguments.
    Set<String> unknown = Sets.difference(computedArguments.keySet(), signature.keySet());
    checkArgument(unknown.isEmpty(), UNKNOWN_ARGUMENTS, String.join(", ", unknown));

    // Check for missing arguments
    Set<String> required = Maps.filterValues(signature, VTLFunction.Argument::isRequired).keySet();
    Set<String> missing = Sets.difference(required, computedArguments.keySet());
    checkArgument(missing.isEmpty(), MISSING_ARGUMENTS, String.join(", ", missing));

    return computedArguments;
}

From source file:org.dllearner.learningproblems.PosNegLP.java

@Override
public void init() throws ComponentInitException {
    // check if some positive examples have been set
    if (positiveExamples.isEmpty()) {
        throw new ComponentInitException("No positive examples have been set.");
    }/*w w w.j a v a 2  s . c om*/

    // check if some negative examples have been set and give warning if not
    if (negativeExamples.isEmpty()) {
        logger.warn("No negative examples have been set, but you decided to use the positive-negative learning"
                + "problem. We recommend to use the positive-only learning problem for the case of no negative examples instead.");
    }

    // check if there is some overlap between positive and negative examples and give warning
    // in that case
    SetView<OWLIndividual> overlap = Sets.intersection(positiveExamples, negativeExamples);
    if (!overlap.isEmpty()) {
        logger.warn("You declared some individuals as both positive and negative examples.");
    }

    allExamples = Sets.union(positiveExamples, negativeExamples);

    if (accuracyMethod == null) {
        accuracyMethod = new AccMethodPredAcc(true);
    }
    if (accuracyMethod instanceof AccMethodApproximate) {
        ((AccMethodApproximate) accuracyMethod).setReasoner(reasoner);
    }

    // sanity check whether examples are contained in KB
    if (reasoner != null && !reasoner.getIndividuals().containsAll(allExamples)
            && !reasoner.getClass().isAssignableFrom(SPARQLReasoner.class)) {
        Set<OWLIndividual> missing = Sets.difference(allExamples, reasoner.getIndividuals());
        double percentage = missing.size() / allExamples.size();
        percentage = Math.round(percentage * 1000) / 1000;
        String str = "The examples (" + (percentage * 100)
                + " % of total) below are not contained in the knowledge base (check spelling and prefixes)\n";
        str += missing.toString();
        if (missing.size() == allExamples.size()) {
            throw new ComponentInitException(str);
        }
        if (percentage < 0.10) {
            logger.warn(str);
        } else {
            logger.error(str);
        }
    }
}

From source file:com.qcadoo.mes.technologies.tree.TechnologyTreeValidationServiceImpl.java

private void collectChildrenProducingTheSameParentInputs(final Map<String, Set<Entity>> parentToProductsMap,
        final EntityTreeNode parentOperation) {
    final Set<Long> parentInProdIds = getProductIdsFromOperationComponent(parentOperation,
            OPERATION_PRODUCT_IN_COMPONENTS);

    Map<Long, Set<Long>> intersections = Maps.newHashMap();

    for (EntityTreeNode subOperation : parentOperation.getChildren()) {
        final Set<Long> childOutProdIds = getProductIdsFromOperationComponent(subOperation,
                OPERATION_PRODUCT_OUT_COMPONENTS);

        Set<Long> intersection = Sets.intersection(parentInProdIds, childOutProdIds);
        intersections.put(subOperation.getId(), intersection);
    }/* ww w.  ja  v a 2 s.  com*/

    for (Entry<Long, Set<Long>> entry : intersections.entrySet()) {
        for (Entry<Long, Set<Long>> entry1 : intersections.entrySet()) {
            if (entry.getKey().equals(entry1.getKey())) {
                continue;
            }

            Set<Long> commonProds = Sets.intersection(entry.getValue(), entry1.getValue());
            if (!commonProds.isEmpty()) {
                appendProductsToMap(parentToProductsMap, parentOperation, commonProds);
            }
        }
    }

    for (EntityTreeNode subOperation : parentOperation.getChildren()) {
        collectChildrenProducingTheSameParentInputs(parentToProductsMap, subOperation);
    }
}

From source file:ai.grakn.graql.internal.reasoner.atom.Atom.java

/**
 * compute resolution priority based on provided substitution variables
 * @param subbedVars variables having a substitution
 * @return resolution priority value/*from ww  w  .j  a va 2 s.co m*/
 */
public int computePriority(Set<Var> subbedVars) {
    int priority = 0;
    priority += Sets.intersection(getVarNames(), subbedVars).size() * ResolutionStrategy.PARTIAL_SUBSTITUTION;
    priority += isRuleResolvable() ? ResolutionStrategy.RULE_RESOLVABLE_ATOM : 0;
    priority += isRecursive() ? ResolutionStrategy.RECURSIVE_ATOM : 0;

    priority += getTypeConstraints().size() * ResolutionStrategy.GUARD;
    Set<Var> otherVars = getParentQuery().getAtoms().stream().filter(a -> a != this)
            .flatMap(at -> at.getVarNames().stream()).collect(Collectors.toSet());
    priority += Sets.intersection(getVarNames(), otherVars).size() * ResolutionStrategy.BOUND_VARIABLE;
    return priority;
}

From source file:org.apache.storm.daemon.logviewer.utils.ResourceAuthorizer.java

/**
 * Checks whether user is authorized to access file. Checks regardless of UI filter.
 *
 * @param user username// w  w  w.j  a v  a2  s  .c o m
 * @param fileName file name to access
 */
public boolean isAuthorizedLogUser(String user, String fileName) {
    if (StringUtils.isEmpty(user) || StringUtils.isEmpty(fileName)
            || getLogUserGroupWhitelist(fileName) == null) {
        return false;
    } else {
        LogUserGroupWhitelist whitelist = getLogUserGroupWhitelist(fileName);

        List<String> logsUsers = new ArrayList<>();
        logsUsers.addAll(ObjectReader.getStrings(stormConf.get(DaemonConfig.LOGS_USERS)));
        logsUsers.addAll(ObjectReader.getStrings(stormConf.get(Config.NIMBUS_ADMINS)));
        logsUsers.addAll(whitelist.getUserWhitelist());

        List<String> logsGroups = new ArrayList<>();
        logsGroups.addAll(ObjectReader.getStrings(stormConf.get(DaemonConfig.LOGS_GROUPS)));
        logsGroups.addAll(whitelist.getGroupWhitelist());

        String userName = principalToLocal.toLocal(user);
        Set<String> groups = getUserGroups(userName);

        return logsUsers.stream().anyMatch(u -> u.equals(userName))
                || Sets.intersection(groups, new HashSet<>(logsGroups)).size() > 0;
    }
}

From source file:net.derquinse.bocas.AbstractGuavaCachingBocas.java

@Override
public final Set<ByteString> contained(Iterable<ByteString> keys) {
    Set<K> ikRequested = toInternalKeySet(keys);
    if (ikRequested.isEmpty()) {
        return ImmutableSet.of();
    }//from  w  w  w . jav  a2 s . c o  m
    Set<K> ikCached = Sets.intersection(ikRequested, cache.asMap().keySet()).immutableCopy();
    Set<K> ikNotCached = Sets.difference(ikRequested, ikCached).immutableCopy();
    Set<ByteString> kCached = toKeySet(ikCached);
    if (ikNotCached.isEmpty()) {
        return kCached;
    }
    Set<ByteString> kFound = bocas.contained(toKeySet(ikNotCached));
    return Sets.union(kCached, kFound).immutableCopy();
}

From source file:org.apache.oozie.service.JvmPauseMonitorService.java

private String formatMessage(long extraSleepTime, Map<String, GcTimes> gcTimesAfterSleep,
        Map<String, GcTimes> gcTimesBeforeSleep) {
    Set<String> gcBeanNames = Sets.intersection(gcTimesAfterSleep.keySet(), gcTimesBeforeSleep.keySet());
    List<String> gcDiffs = Lists.newArrayList();
    for (String name : gcBeanNames) {
        GcTimes diff = gcTimesAfterSleep.get(name).subtract(gcTimesBeforeSleep.get(name));
        if (diff.gcCount != 0) {
            gcDiffs.add("GC pool '" + name + "' had collection(s): " + diff.toString());
        }/*w  w  w . j a va  2 s  .co m*/
    }

    String ret = "Detected pause in JVM or host machine (eg GC): pause of approximately " + extraSleepTime
            + "ms\n";
    if (gcDiffs.isEmpty()) {
        ret += "No GCs detected";
    } else {
        ret += Joiner.on("\n").join(gcDiffs);
    }
    return ret;
}

From source file:org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.impl.LdapAuthAsyncRule.java

private boolean checkIfUserHasAccess(LdapUser user, LdapAuthDefinition authDefinition) {
    return authDefinition.accessGroups.isEmpty() || !Sets.intersection(authDefinition.accessGroups,
            user.getGroups().stream().map(LdapGroup::getName).collect(Collectors.toSet())).isEmpty();
}