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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the difference of two sets.

Usage

From source file:uk.ac.ebi.atlas.model.differential.DifferentialProfileComparator.java

public double getExpressionLevelFoldChange(DifferentialProfile differentialProfile) {

    Set<Contrast> nonSelectedQueryContrasts = Sets.difference(allQueryContrasts, selectedQueryContrasts);

    double minExpressionLevelOnNonSelectedQueryContrasts = differentialProfile
            .getStrongestExpressionLevelOn(nonSelectedQueryContrasts);

    double averageExpressionLevelOnSelectedQueryContrasts = differentialProfile
            .getAverageExpressionLevelOn(selectedQueryContrasts);

    if (averageExpressionLevelOnSelectedQueryContrasts == 0) {
        return minExpressionLevelOnNonSelectedQueryContrasts / Double.MIN_VALUE;
    }//from w  w w  . j  a v  a2 s.com

    return minExpressionLevelOnNonSelectedQueryContrasts / averageExpressionLevelOnSelectedQueryContrasts;
}

From source file:io.bazel.rules.closure.webfiles.WebfilesValidatorProgram.java

private int run(Iterable<String> args) throws IOException {
    Webfiles target = null;// w ww .java 2s .  c  o m
    List<Webfiles> directDeps = new ArrayList<>();
    final List<Path> transitiveDeps = new ArrayList<>();
    Iterator<String> flags = args.iterator();
    Set<String> suppress = new HashSet<>();
    while (flags.hasNext()) {
        String flag = flags.next();
        switch (flag) {
        case "--dummy":
            Files.write(fs.getPath(flags.next()), new byte[0]);
            break;
        case "--target":
            target = loadWebfilesPbtxt(fs.getPath(flags.next()));
            break;
        case "--direct_dep":
            directDeps.add(loadWebfilesPbtxt(fs.getPath(flags.next())));
            break;
        case "--transitive_dep":
            transitiveDeps.add(fs.getPath(flags.next()));
            break;
        case "--suppress":
            suppress.add(flags.next());
            break;
        default:
            throw new RuntimeException("Unexpected flag: " + flag);
        }
    }
    if (target == null) {
        output.println(ERROR_PREFIX + "Missing --target flag");
        return 1;
    }
    Multimap<String, String> errors = validator.validate(target, directDeps,
            Suppliers.memoize(new Supplier<ImmutableList<Webfiles>>() {
                @Override
                public ImmutableList<Webfiles> get() {
                    ImmutableList.Builder<Webfiles> builder = new ImmutableList.Builder<>();
                    for (Path path : transitiveDeps) {
                        try {
                            builder.add(loadWebfilesPbtxt(path));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return builder.build();
                }
            }));
    Set<String> superfluous = Sets.difference(suppress, Sets.union(errors.keySet(), NEVER_SUPERFLUOUS));
    if (!superfluous.isEmpty()) {
        errors.put(SUPERFLUOUS_SUPPRESS_ERROR, "Superfluous suppress codes: " + joinWords(superfluous));
    }
    return displayErrors(suppress, errors);
}

From source file:org.jclouds.codegen.ec2.queryapi.parser.AmazonEC2QueryAPIValidator.java

public AmazonEC2QueryAPIValidator validateCategories() {
    checkState(Sets.difference(getModel().getCategories().keySet(), expectedQueryNamesForCategoryName.keySet())
            .size() == 0);/*  w ww.  ja  va2  s .c om*/
    checkState(getModel().getCategories().keySet().size() == expectedQueryNamesForCategoryName.keySet().size());
    return this;
}

From source file:com.facebook.buck.cxx.CxxBinaryDescription.java

@SuppressWarnings("PMD.PrematureDeclaration")
@Override//  w ww  .  j  ava  2  s .c  om
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params,
        BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {

    // We explicitly remove some flavors below from params to make sure rule
    // has the same output regardless if we will strip or not.
    Optional<StripStyle> flavoredStripStyle = StripStyle.FLAVOR_DOMAIN.getValue(params.getBuildTarget());
    Optional<LinkerMapMode> flavoredLinkerMapMode = LinkerMapMode.FLAVOR_DOMAIN
            .getValue(params.getBuildTarget());
    params = CxxStrip.removeStripStyleFlavorInParams(params, flavoredStripStyle);
    params = LinkerMapMode.removeLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode);

    // Extract the platform from the flavor, falling back to the default platform if none are
    // found.
    ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(params.getBuildTarget().getFlavors());
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(flavors).orElse(defaultCxxPlatform);
    if (flavors.contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)) {
        flavors = ImmutableSet.copyOf(
                Sets.difference(flavors, ImmutableSet.of(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)));
        BuildTarget target = BuildTarget.builder(params.getBuildTarget().getUnflavoredBuildTarget())
                .addAllFlavors(flavors).build();
        BuildRuleParams typeParams = params.copyWithChanges(target, params.getDeclaredDeps(),
                params.getExtraDeps());

        return createHeaderSymlinkTreeBuildRule(typeParams, resolver, cxxPlatform, args);
    }

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    if (flavors.contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
        BuildRuleParams paramsWithoutFlavor = params.withoutFlavor(CxxCompilationDatabase.COMPILATION_DATABASE);
        CxxLinkAndCompileRules cxxLinkAndCompileRules = CxxDescriptionEnhancer
                .createBuildRulesForCxxBinaryDescriptionArg(paramsWithoutFlavor, resolver, cxxBuckConfig,
                        cxxPlatform, args, flavoredStripStyle, flavoredLinkerMapMode);
        return CxxCompilationDatabase.createCompilationDatabase(params, pathResolver,
                cxxLinkAndCompileRules.compileRules);
    }

    if (flavors.contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)) {
        return CxxDescriptionEnhancer
                .createUberCompilationDatabase(cxxPlatforms.getValue(flavors).isPresent() ? params
                        : params.withFlavor(defaultCxxPlatform.getFlavor()), resolver);
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER.get())) {
        return CxxInferEnhancer.requireInferAnalyzeAndReportBuildRuleForCxxDescriptionArg(params, resolver,
                pathResolver, cxxBuckConfig, cxxPlatform, args, inferBuckConfig,
                new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get())) {
        return CxxInferEnhancer.requireInferAnalyzeBuildRuleForCxxDescriptionArg(params, resolver, pathResolver,
                cxxBuckConfig, cxxPlatform, args, inferBuckConfig, new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get())) {
        return CxxInferEnhancer.requireAllTransitiveCaptureBuildRules(params, resolver, cxxBuckConfig,
                cxxPlatform, inferBuckConfig, new CxxInferSourceFilter(inferBuckConfig), args);
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ONLY.get())) {
        return CxxInferEnhancer.requireInferCaptureAggregatorBuildRuleForCxxDescriptionArg(params, resolver,
                pathResolver, cxxBuckConfig, cxxPlatform, args, inferBuckConfig,
                new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR)) {
        return CxxDescriptionEnhancer.createSandboxTreeBuildRule(resolver, args, cxxPlatform, params);
    }

    CxxLinkAndCompileRules cxxLinkAndCompileRules = CxxDescriptionEnhancer
            .createBuildRulesForCxxBinaryDescriptionArg(params, resolver, cxxBuckConfig, cxxPlatform, args,
                    flavoredStripStyle, flavoredLinkerMapMode);

    // Return a CxxBinary rule as our representative in the action graph, rather than the CxxLink
    // rule above for a couple reasons:
    //  1) CxxBinary extends BinaryBuildRule whereas CxxLink does not, so the former can be used
    //     as executables for genrules.
    //  2) In some cases, users add dependencies from some rules onto other binary rules, typically
    //     if the binary is executed by some test or library code at test time.  These target graph
    //     deps should *not* become build time dependencies on the CxxLink step, otherwise we'd
    //     have to wait for the dependency binary to link before we could link the dependent binary.
    //     By using another BuildRule, we can keep the original target graph dependency tree while
    //     preventing it from affecting link parallelism.

    params = CxxStrip.restoreStripStyleFlavorInParams(params, flavoredStripStyle);
    params = LinkerMapMode.restoreLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode);
    CxxBinary cxxBinary = new CxxBinary(
            params.appendExtraDeps(cxxLinkAndCompileRules.executable.getDeps(ruleFinder)), resolver,
            pathResolver, ruleFinder, cxxLinkAndCompileRules.getBinaryRule(), cxxLinkAndCompileRules.executable,
            args.frameworks, args.tests, params.getBuildTarget().withoutFlavors(cxxPlatforms.getFlavors()));
    resolver.addToIndex(cxxBinary);
    return cxxBinary;
}

From source file:io.druid.segment.indexing.DataSchema.java

@JsonIgnore
public InputRowParser getParser() {
    if (parser == null) {
        log.warn("No parser has been specified");
        return null;
    }/*from www .ja v a2s.  c  o m*/

    final InputRowParser inputRowParser = jsonMapper.convertValue(this.parser, InputRowParser.class);

    final Set<String> dimensionExclusions = Sets.newHashSet();
    for (AggregatorFactory aggregator : aggregators) {
        dimensionExclusions.addAll(aggregator.requiredFields());
    }

    if (inputRowParser.getParseSpec() != null) {
        final DimensionsSpec dimensionsSpec = inputRowParser.getParseSpec().getDimensionsSpec();
        final TimestampSpec timestampSpec = inputRowParser.getParseSpec().getTimestampSpec();

        // exclude timestamp from dimensions by default, unless explicitly included in the list of dimensions
        if (timestampSpec != null) {
            final String timestampColumn = timestampSpec.getTimestampColumn();
            if (!(dimensionsSpec.hasCustomDimensions()
                    && dimensionsSpec.getDimensions().contains(timestampColumn))) {
                dimensionExclusions.add(timestampColumn);
            }
        }
        if (dimensionsSpec != null) {
            final Set<String> metSet = Sets.newHashSet();
            for (AggregatorFactory aggregator : aggregators) {
                metSet.add(aggregator.getName());
            }
            final Set<String> dimSet = Sets.newHashSet(dimensionsSpec.getDimensions());
            final Set<String> overlap = Sets.intersection(metSet, dimSet);
            if (!overlap.isEmpty()) {
                throw new IAE(
                        "Cannot have overlapping dimensions and metrics of the same name. Please change the name of the metric. Overlap: %s",
                        overlap);
            }

            return inputRowParser.withParseSpec(inputRowParser.getParseSpec().withDimensionsSpec(
                    dimensionsSpec.withDimensionExclusions(Sets.difference(dimensionExclusions, dimSet))));
        } else {
            return inputRowParser;
        }
    } else {
        log.warn("No parseSpec in parser has been specified.");
        return inputRowParser;
    }
}

From source file:com.google.devtools.build.lib.testutil.BazelPackageBuilderHelperForTesting.java

private synchronized void sanityCheckBazelPackageLoader(Package pkg, RuleClassProvider ruleClassProvider,
        SkylarkSemantics skylarkSemantics) {
    PackageIdentifier pkgId = pkg.getPackageIdentifier();
    if (pkgId.equals(Label.EXTERNAL_PACKAGE_IDENTIFIER) || !pkg.getPackageIdentifier().getRepository().isMain()
            || PackageFunction.isDefaultsPackage(pkg.getPackageIdentifier())) {
        // TODO(nharmata): Support these packages.
        return;/*w ww.  j a va2  s.  com*/
    }
    int numNameSegments = pkg.getNameFragment().segmentCount();
    PathFragment fullFilenameFragment = pkg.getFilename().asFragment();
    int numFullFilenameFragmentSegments = fullFilenameFragment.segmentCount();
    Path workspaceRoot = pkg.getFilename().getFileSystem().getPath(
            fullFilenameFragment.subFragment(0, numFullFilenameFragmentSegments - (numNameSegments + 1)));
    PackageLoader packageLoader = BazelPackageLoader.builder(workspaceRoot)
            .setSkylarkSemantics(skylarkSemantics).setRuleClassProvider(ruleClassProvider).build();
    Package newlyLoadedPkg;
    try {
        newlyLoadedPkg = packageLoader.loadPackage(pkg.getPackageIdentifier());
    } catch (InterruptedException e) {
        return;
    } catch (NoSuchPackageException e) {
        throw new IllegalStateException(e);
    }
    ImmutableSet<Label> targetsInPkg = ImmutableSet
            .copyOf(Iterables.transform(pkg.getTargets().values(), TARGET_TO_LABEL));
    ImmutableSet<Label> targetsInNewlyLoadedPkg = ImmutableSet
            .copyOf(Iterables.transform(newlyLoadedPkg.getTargets().values(), TARGET_TO_LABEL));
    if (!targetsInPkg.equals(targetsInNewlyLoadedPkg)) {
        throw new IllegalStateException(String.format(
                "The Package for %s had a different set of targets (<targetsInPkg> - "
                        + "<targetsInNewlyLoadedPkg> = %s, <targetsInNewlyLoadedPkg> - <targetsInPkg> = %s) when "
                        + "loaded normally during execution of the current test than it did when loaded via "
                        + "BazelPackageLoader (done automatically by the BazelPackageBuilderHelperForTesting "
                        + "hook). This either means: (i) Skyframe package loading semantics have diverged from "
                        + "BazelPackageLoader semantics (ii) The test in question is doing something that "
                        + "confuses BazelPackageBuilderHelperForTesting.",
                pkgId, Sets.difference(targetsInPkg, targetsInNewlyLoadedPkg),
                Sets.difference(targetsInNewlyLoadedPkg, targetsInPkg)));
    }
}

From source file:org.opendaylight.controller.config.facade.xml.osgi.YangStoreService.java

void notifyListeners(final YangStoreSnapshot previous, final YangStoreSnapshot current) {
    final Set<Module> prevModules = previous.getModules();
    final Set<Module> currModules = current.getModules();
    final Set<Module> removed = Sets.difference(prevModules, currModules);
    final Set<Module> added = Sets.difference(currModules, prevModules);

    final Set<Capability> addedCaps = toCapabilities(added, current);
    final Set<Capability> removedCaps = toCapabilities(removed, current);

    synchronized (listeners) {
        for (final ModuleListener listener : listeners) {
            listener.onCapabilitiesChanged(addedCaps, removedCaps);
        }//  w w  w. j a  va2 s  .  c  o m
    }
}

From source file:se.sics.nstream.torrent.connMngr.TorrentConnMngr.java

public ConnResult attemptSlot(FileId fileId, int blockNr, Optional<BlockDetails> irregularBlock) {
    FileConnection fileConnection = fileConnections.get(fileId);
    if (fileConnection == null) {
        throw new RuntimeException("ups");
    }/*w  ww.  j  a va2s.c o m*/
    if (!fileConnection.available()) {
        return new FileConnectionBusy();
    }
    //check through already established peer-file connections
    Collection<FilePeerConnection> fileConnEstablished = fileConnection.getPeerConnections();
    Set<Identifier> checked = new HashSet<>();
    for (FilePeerConnection fpc : fileConnEstablished) {
        KAddress peer = fpc.getPeerConnection().getPeer();
        if (fileConnection.available(peer.getId()) && fpc.getPeerConnection().available(fileId)) {
            return new UseFileConnection(TorrentIds.connId(fileId, peer.getId(), true), peer, blockNr,
                    irregularBlock);
        }
        checked.add(peer.getId());
    }
    //check through already established peer connections - that are not established on a peer-file yet (maybe used by other files)
    Set<Identifier> peerConnEstablished = Sets.difference(peerConnections.keySet(), checked);
    for (Identifier peerId : peerConnEstablished) {
        PeerConnection peerConnection = peerConnections.get(peerId);
        if (peerConnection.available(fileId)) {
            return new NewFileConnection(TorrentIds.connId(fileId, peerId, true), peerConnection.getPeer(),
                    blockNr, irregularBlock);
        }
        checked.add(peerId);
    }

    //establish a connection to a candidate peer
    if (!connCandidates.isEmpty()) {
        KAddress peer = connCandidates.poll();
        return new NewPeerConnection(TorrentIds.connId(fileId, peer.getId(), true), peer, blockNr,
                irregularBlock);
    }
    return new NoConnections();
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.preferences.PostProcessorPreferencePage.java

@Override
public boolean performOk() {
    Set<IItemDescriptor<Descriptor>> postProcessorDescriptors = Sets.newLinkedHashSet(
            EMFCompareRCPPlugin.getDefault().getPostProcessorDescriptorRegistry().getItemDescriptors());
    SetView<IItemDescriptor<Descriptor>> postProcessorToDisable = Sets.difference(postProcessorDescriptors,
            dataHolder.getData());//  www .  ja va  2  s.c  om
    setEnginePreferences(EMFComparePreferences.DISABLED_POST_PROCESSOR, postProcessorToDisable);

    if (TracingConstant.CONFIGURATION_TRACING_ACTIVATED) {
        StringBuilder traceMessage = new StringBuilder("Post processor preference serialization:\n"); //$NON-NLS-1$
        String prefDelimiter = " :\n"; //$NON-NLS-1$
        String newLine = "\n"; //$NON-NLS-1$
        traceMessage.append(EMFComparePreferences.DISABLED_POST_PROCESSOR).append(prefDelimiter)
                .append(getPreferenceStore().getString(EMFComparePreferences.DISABLED_POST_PROCESSOR))
                .append(newLine);
        EMFCompareRCPPlugin.getDefault().log(IStatus.INFO, traceMessage.toString());
    }

    return super.performOk();
}

From source file:ai.grakn.graql.internal.query.QueryAnswer.java

@Override
public Answer filterVars(Set<Var> vars) {
    QueryAnswer filteredAnswer = new QueryAnswer(this);
    Set<Var> varsToRemove = Sets.difference(this.keySet(), vars);
    varsToRemove.forEach(filteredAnswer::remove);

    return filteredAnswer.setExplanation(this.getExplanation());
}