Example usage for java.util Set contains

List of usage examples for java.util Set contains

Introduction

In this page you can find the example usage for java.util Set contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:com.cloudant.sync.query.IndexCreator.java

/**
 * Iterate candidate indexNames generated from the indexNameRandom generator
 * until we find one which doesn't already exist.
 *
 * We make sure the generated name is not an index already by the list
 * of index names returned by {@link #listIndexesInDatabaseQueue()} method.
 * This is because we avoid knowing about how indexes are stored in SQLite, however
 * this means that it is not thread safe, it is possible for a new index with the same
 * name to be created after a copy of the indexes has been taken from the database.
 *
 * We allow up to 200 random name generations, which should give us many millions
 * of indexes before a name fails to be generated and makes sure this method doesn't
 * loop forever.//from ww  w  . ja va2 s  . com
 *
 * @param existingIndexNames The names of the indexes that exist in the database.
 *
 * @return The generated index name or {@code null} if it failed.
 *
 */
private static String generateIndexName(Set<String> existingIndexNames)
        throws ExecutionException, InterruptedException {

    String indexName = null;
    Hex hex = new Hex();

    int tries = 0;
    byte[] randomBytes = new byte[20];
    while (tries < 200 && indexName == null) {
        indexNameRandom.nextBytes(randomBytes);
        String candidate = new String(hex.encode(randomBytes), Charset.forName("UTF-8"));

        if (!existingIndexNames.contains(candidate)) {
            indexName = candidate;
        }
        tries++;
    }

    if (indexName != null) {
        return indexName;
    } else {
        return null;
    }
}

From source file:com.linkedin.pinot.common.utils.request.RequestUtils.java

/**
 * Helper method to check whether all columns in predicates are materialized dimensions, and all predicates are
 * conjoined by AND. This is a pre-requisite in order to use star tree.
 *///  w ww .j  a  v a 2  s.  co  m
private static boolean checkPredicatesForStarTree(FilterQueryTree filterNode, Set<String> metrics,
        Set<String> unMaterializedDimensions) {
    FilterOperator operator = filterNode.getOperator();
    if (operator == FilterOperator.OR) {
        return false;
    }
    if (operator == FilterOperator.AND) {
        for (FilterQueryTree child : filterNode.getChildren()) {
            if (!checkPredicatesForStarTree(child, metrics, unMaterializedDimensions)) {
                return false;
            }
        }
        return true;
    }
    String column = filterNode.getColumn();
    return !metrics.contains(column) && !unMaterializedDimensions.contains(column);
}

From source file:edu.stanford.muse.groups.SimilarGroupMethods.java

/** This is the alternative group algorithm, described in the IUI-2011 paper */
public static <T extends Comparable<? super T>> GroupHierarchy<T> findContactGroupsIUI(List<Group<T>> input,
        int MINCOUNT, int MIN_GROUP_SIZE, float MAX_SUBSUMPTION_ERROR, float MIN_MERGE_GROUP_SIM,
        String utilityType, float UTILITY_MULTIPLIER, GroupAlgorithmStats<T> stats) {
    log.info(//from ww w  .j  ava2 s.  co  m
            "-----------------------------------------------   GROUPER  -----------------------------------------------\n");

    long startTimeMillis = System.currentTimeMillis();
    // copy over the alg. parameters so everything is in one place
    stats.MIN_GROUP_SIZE = MIN_GROUP_SIZE;
    stats.MIN_FREQ = MINCOUNT;
    stats.MAX_SUBSUMPTION_ERROR = MAX_SUBSUMPTION_ERROR;
    stats.MIN_MERGE_GROUP_SIM = MIN_MERGE_GROUP_SIM;
    int MAX_EDGES = 1000;
    Set<T> hypers = Grouper.findHyperConnectedElementsRaw(input, MAX_EDGES);

    for (Group<T> g : input) {
        for (Iterator<T> it = g.elements.iterator(); it.hasNext();) {
            T t = it.next();
            if (hypers.contains(t))
                it.remove();
            if (g.elements.size() == 0)
                continue;
        }
    }

    List<SimilarGroup<T>> exactGroups = Grouper.convertToSimilarGroups(input);

    //int nUniqueGroups = exactGroups.size();
    stats.startingGroups = new GroupStats<T>(exactGroups);
    //   dumpGroupsForDebug("Starting Groups", exactGroups);

    Set<SimilarGroup<T>> candidates = selectGroupsWithMinSize(exactGroups, MIN_GROUP_SIZE);
    stats.groupsWithMinSize = new GroupStats<T>(candidates);
    //   dumpGroupsForDebug("Groups with min size " + MIN_GROUP_SIZE, candidates);

    log.warn("Intersections are disabled because taking too long for Ken Lay!!");
    //candidates // returns (log, result)
    //= SimilarGroupMethods.intersectGroups(candidates, MIN_GROUP_SIZE, stats);
    stats.groupsAfterIntersections = new GroupStats<T>(candidates);
    //   dumpGroupsForDebug("Groups after intersections ", candidates);

    // verify
    for (SimilarGroup<T> sg : candidates) {
        Util.softAssert(candidates.contains(sg));
        Util.softAssert(sg.size() >= MIN_GROUP_SIZE);
    }

    // now filter based on min freq
    computeGroupFrequencies(input, candidates);
    candidates = SimilarGroupMethods.selectGroupsWithMinFreq(candidates, MINCOUNT);
    stats.groupsWithMinFreqAndMinSize = new GroupStats<T>(candidates);
    //   dumpGroupsForDebug("Groups with min. freq. " + MINCOUNT, candidates);

    // compute utilities
    // Map<T, Integer> indivFreqs =
    // SimilarGroupMethods.computeIndivFreqs(input);
    for (SimilarGroup<T> sg : candidates) {
        if ("linear".equals(utilityType))
            sg.computeLinearUtility();
        else if ("square".equals(utilityType))
            sg.computeSquareUtility();
        else
            sg.computeExpUtility(UTILITY_MULTIPLIER);

        // sg.computeZScore(indivFreqs, input.size());
    }

    // convert candidates from set to list now, because we need sorting etc

    List<SimilarGroup<T>> candidateList = new ArrayList<SimilarGroup<T>>();
    candidateList.addAll(candidates);

    // remove subsumed groups
    List<SimilarGroup<T>> selectedGroups = SimilarGroupMethods.selectGroupsNotSubsumed(candidateList,
            MAX_SUBSUMPTION_ERROR);
    stats.groupsAfterSubsumption = new GroupStats<T>(selectedGroups);
    //   dumpGroupsForDebug("Groups after subsumption with error "
    //                      + MAX_SUBSUMPTION_ERROR, selectedGroups);

    // now compute hierarchy, just to identify the root groups
    GroupHierarchy<T> hierarchy = new GroupHierarchy<T>(selectedGroups);
    // Map<SimilarGroup<T>, List<SimilarGroup<T>>> parentToChildGroupMap
    // = hierarchy.parentToChildrenMap;
    Set<SimilarGroup<T>> rootGroups = hierarchy.rootGroups;
    log.info("hierarchy: #root groups = " + rootGroups.size());

    // add supergroups. supergroups never subsume other subgroups
    Set<SimilarSuperGroup<T>> manufacturedGroups = SimilarGroupMethods.manufactureSuperGroups(input, rootGroups,
            MAX_SUBSUMPTION_ERROR, MIN_MERGE_GROUP_SIM);
    stats.manufacturedGroups = new GroupStats(manufacturedGroups);
    selectedGroups.addAll(manufacturedGroups);
    stats.finalGroups = new GroupStats<T>(selectedGroups);
    //   dumpGroupsForDebug("Final groups " + MAX_SUBSUMPTION_ERROR, selectedGroups);

    // recompute hierarchy. its easier than
    // trying to update the existing hierarchy
    hierarchy = new GroupHierarchy<T>(selectedGroups);
    rootGroups = hierarchy.rootGroups;
    stats.finalRootGroups = new GroupStats(rootGroups);
    long endTimeMillis = System.currentTimeMillis();
    stats.executionTimeMillis = endTimeMillis - startTimeMillis;
    return hierarchy;
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

private static void checkAllowedOptions(Set<? extends OpenOption> allowed, OpenOption... options) {
    if (options == null)
        return;//from  w  w  w.j a  v  a  2s  . co  m
    for (OpenOption opt : options) {
        if (!allowed.contains(opt)) {
            throw new UnsupportedOperationException(opt.toString() + " options not allowed");
        }
    }
}

From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.JSONGenerator.java

/**
 * @param node//from  w w  w  . j  a  va2 s  .c om
 * @param opts
 * @param out
 * @throws RepositoryException
 * @throws IOException 
 * @throws JSONException
 */
private static void outputChildNodes(Node node, ChecksumGeneratorOptions opts, JsonWriter out)
        throws RepositoryException, IOException {
    Set<String> nodeTypeExcludes = opts.getExcludedNodeTypes();

    NodeIterator nodeIterator = node.getNodes();

    TreeMap<String, Node> childSortMap = new TreeMap<String, Node>();
    boolean hasOrderedChildren = false;
    try {
        hasOrderedChildren = node.getPrimaryNodeType().hasOrderableChildNodes();
    } catch (Exception expected) {
        // ignore
    }
    while (nodeIterator.hasNext()) {
        Node child = nodeIterator.nextNode();
        if (!nodeTypeExcludes.contains(child.getPrimaryNodeType().getName())) {
            if (hasOrderedChildren) {
                //output child node if parent is has orderable children
                out.name(child.getName());
                out.beginObject();
                generateSubnodeJSON(child, opts, out);
                out.endObject();
            } else {
                // otherwise put the child nodes into a sorted map
                // to output them with consistent ordering
                childSortMap.put(child.getName(), child);
            }
        }
    }
    // output the non-ordered child nodes in sorted order (lexicographically)
    for (Node child : childSortMap.values()) {
        out.name(child.getName());
        out.beginObject();
        generateSubnodeJSON(child, opts, out);
        out.endObject();
    }
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static Method findGetter(Class<?> clazz, String propName) {
    Set<String> expectedNames = new HashSet<>(
            Arrays.asList("get" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1),
                    "is" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1) //bool props
            ));/*from  w w w  . j a va2  s  . c o  m*/
    for (Method method : clazz.getMethods()) {
        String methodName = method.getName();
        if (!expectedNames.contains(methodName)) {
            continue;
        }
        if (method.getParameterCount() != 0) {
            continue; //getters take no arguments
        }
        Type returnType = method.getGenericReturnType();
        if (returnType.equals(void.class)) {
            continue; //getters return something
        }
        if (methodName.startsWith("is")
                && !(returnType.equals(Boolean.class) || returnType.equals(boolean.class))) {
            continue; //isSomething() only valid for booleans
        }
        return method;
    }
    return null;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Copy non-null bean properties from one object to another.
 * //from  w w  w  .j  a  v a 2s. c om
 * @param src the object to copy values from
 * @param dest the object to copy values to
 * @param ignore a set of property names to ignore (optional)
 * @param emptyStringToNull if <em>true</em> then String values that 
 * are empty or contain only whitespace will be treated as if they
 * where <em>null</em>
 */
public static void copyBeanProperties(Object src, Object dest, Set<String> ignore, boolean emptyStringToNull) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper to = PropertyAccessorFactory.forBeanPropertyAccess(dest);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null || (emptyStringToNull && (propValue instanceof String)
                && !StringUtils.hasText((String) propValue))) {
            continue;
        }
        if (to.isWritableProperty(propName)) {
            to.setPropertyValue(propName, propValue);
        }
    }
}

From source file:Main.java

/**
 * Reorder a list of elements by another list. Trying to keep absolute order of initial list in alphabetical order
 * but reorder regarding to provided relative order list.
 * E.g. initial was [1, 2, 3, 4, 5] - calling reorder with list [2, 5, 4] will generate list
 * [1, 2, 3, 5, 4]/*  w w w  . jav  a  2  s.  c om*/
 * @param elements - initial list
 * @param order - list describing relative order
 * @param <T> - Class of comparable object
 * @return - new reordered list
 */
public static <T extends Comparable> List<T> mergeReorder(List<T> elements, List<T> order) {
    if (order.size() == 0) {
        return elements;
    }
    if (elements.size() == 0) {
        return order;
    }
    Set<T> merged = new LinkedHashSet<>();
    Set<T> elementsSet = new HashSet<>(elements);
    int i = 0;
    int j = 0;
    T currElement = elements.get(i);
    T currOrder = order.get(j);
    while (i < elements.size() || j < order.size()) {
        if (j >= order.size()) {
            merged.addAll(elements.subList(i, elements.size()));
            break;
        }
        currElement = i < elements.size() ? elements.get(i) : currElement;
        currOrder = j < order.size() ? order.get(j) : currOrder;
        if (currElement.compareTo(currOrder) < 0) {
            merged.add(currElement);
            i++;
        }
        if (currOrder.compareTo(currElement) < 0 || i >= elements.size()) {
            if (merged.contains(currOrder)) {
                merged.remove(currOrder);
            }
            if (elementsSet.contains(currOrder)) {
                merged.add(currOrder);
            }
            j++;
        }
        if (currElement.compareTo(currOrder) == 0) {
            merged.add(currElement);
            i++;
            j++;
        }
    }
    return new ArrayList<>(merged);
}

From source file:com.silverpeas.gallery.MediaHelper.java

/**
 * Sets the internal metadata. If metadata
 * @param handledImageFile/*from  ww  w  .j av  a2  s .co m*/
 * @param iMedia
 * @param supportedMimeTypes
 * @return true if internal data have been set, false otherwise.
 */
private static boolean setInternalMetadata(HandledFile handledImageFile, InternalMedia iMedia,
        final Set<MediaMimeType> supportedMimeTypes) throws Exception {
    File fileForData = handledImageFile.getFile();
    MediaMimeType mediaMimeType = MediaMimeType.fromFile(handledImageFile.getFile());
    if (supportedMimeTypes.contains(mediaMimeType)) {
        iMedia.setFileName(fileForData.getName());
        iMedia.setFileMimeType(mediaMimeType);
        iMedia.setFileSize(fileForData.length());
        com.silverpeas.util.MetaData metaData = MetadataExtractor.getInstance()
                .extractMetadata(handledImageFile.getFile());
        switch (iMedia.getType()) {
        case Photo:
            iMedia.getPhoto().setDefinition(metaData.getDefinition());
            break;
        case Video:
            iMedia.getVideo().setDefinition(metaData.getDefinition());
            break;
        }
        if (metaData.getDuration() != null) {
            switch (iMedia.getType()) {
            case Video:
                iMedia.getVideo().setDuration(metaData.getDuration().getTimeAsLong());
                break;
            case Sound:
                iMedia.getSound().setDuration(metaData.getDuration().getTimeAsLong());
                break;
            }
        }
        if (StringUtil.isNotDefined(iMedia.getTitle()) && StringUtil.isDefined(metaData.getTitle())) {
            iMedia.setTitle(metaData.getTitle());
        }
        return true;
    } else {
        iMedia.setFileName(null);
        try {
            throw new GalleryRuntimeException("MediaHelper.setInternalMetadata",
                    SilverpeasRuntimeException.ERROR,
                    "Mime-Type of " + handledImageFile.getFile().getName() + " is not supported ("
                            + FileUtil.getMimeType(handledImageFile.getFile().getPath()) + ")");
        } finally {
            handledImageFile.delete();
        }
    }
}

From source file:fr.landel.utils.commons.CollectionUtils2.java

/**
 * Check if the iterable contains specific types (all {@code null} values
 * and classes are excluded)/*from  w ww .  ja v  a 2  s .c  o m*/
 * 
 * @param iterable
 *            The iterable to check
 * @param classes
 *            The list of classes ({@code null}, returns false, all
 *            {@code null} classes are removed)
 * @param <T>
 *            The generic type of iterable
 * @return true, if all classes are found
 */
public static <T> boolean containsClasses(final Iterable<T> iterable, final Class<?>... classes) {
    if (classes != null && !IterableUtils.isEmpty(iterable)) {
        int found = 0;

        // remove null classes
        final Set<Class<?>> classRefSet = new HashSet<>();
        for (Class<?> clazz : classes) {
            if (clazz != null) {
                classRefSet.add(clazz);
            }
        }

        // list all classes in provided iterable
        final Set<Class<T>> classSet = getClasses(iterable);

        // count
        for (Class<?> clazz : classRefSet) {
            if (classSet.contains(clazz)) {
                found++;
            }
        }

        return found == classRefSet.size();
    }
    return false;
}