Example usage for java.util BitSet size

List of usage examples for java.util BitSet size

Introduction

In this page you can find the example usage for java.util BitSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of bits of space actually in use by this BitSet to represent bit values.

Usage

From source file:inflor.core.singlets.SingletsModel.java

public BitSet scoreModel(double[] ratio) {
    final BitSet mask = new BitSet(ratio.length);
    for (int i = 0; i < mask.size(); i++) {
        if (ratio[i] <= ratioThreshold) {
            mask.set(i);// ww w.j av  a  2s .c om
        }
    }
    return mask;
}

From source file:com.joliciel.jochre.graphics.ShapeFillerImpl.java

BitSet fillBitSet(Shape shape, BitSet bitset, int neighbourBirthCount) {
    BitSet newBitSet = new BitSet(bitset.size());
    int baseIndex = 0;
    for (int y = 0; y < shape.getHeight(); y++) {
        for (int x = 0; x < shape.getWidth(); x++) {
            int index = baseIndex + x;
            if (bitset.get(index))
                newBitSet.set(index);//from   w ww .  j a va2  s  .  co  m
            else {
                int surroundingCount = 0;
                if (y > 0) {
                    if (x > 0)
                        surroundingCount += bitset.get(index - (shape.getWidth() + 1)) ? 1 : 0;
                    surroundingCount += bitset.get(index - (shape.getWidth())) ? 1 : 0;
                    if (x < shape.getWidth() - 1)
                        surroundingCount += bitset.get(index - (shape.getWidth() - 1)) ? 1 : 0;
                }
                if (x > 0)
                    surroundingCount += bitset.get(index - 1) ? 1 : 0;
                if (x < shape.getWidth() - 1)
                    surroundingCount += bitset.get(index + 1) ? 1 : 0;
                if (y < shape.getHeight() - 1) {
                    if (x > 0)
                        surroundingCount += bitset.get(index + (shape.getWidth() - 1)) ? 1 : 0;
                    surroundingCount += bitset.get(index + (shape.getWidth())) ? 1 : 0;
                    if (x < shape.getWidth() - 1)
                        surroundingCount += bitset.get(index + (shape.getWidth() + 1)) ? 1 : 0;
                }
                // if at least NEIGHBOUR_COUNT_BIRTH out of 8 surrounding pixels are on,
                // assume this one should be on
                if (surroundingCount >= NEIGHBOUR_COUNT_BIRTH)
                    newBitSet.set(index);
            }
        }
        baseIndex += shape.getWidth();
    }
    return newBitSet;
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * Create a BitSet instance,start index is 0
 * <p>//from   w w  w  .ja va2  s. c o m
 * example:
 * </p>
 * <pre>
 *    byte:   50
 *    binary: 0b110010
 *    bitSet.toString(): {2, 3, 6}
 *
 *    +--------+---+---+---+---+---+---+---+---+
 *    | bitset | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
 *    +--------+---+---+---+---+---+---+---+---+
 *    |  bits  | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 |
 *    +--------+---+---+---+---+---+---+---+---+
 *
 * </pre>
 *
 * @param bitSet BitSet
 * @return bytes
 */
public static byte[] bitValue(BitSet bitSet) {
    if (bitSet == null) {
        return null;
    }

    byte[] bytes = new byte[bitSet.size() / 8];

    int index, offset;
    for (int i = 0; i < bitSet.size(); i++) {
        index = i / 8;
        offset = 7 - i % 8;
        bytes[index] |= (bitSet.get(i) ? 1 : 0) << offset;
    }
    return bytes;
}

From source file:com.opengamma.analytics.math.minimization.UncoupledParameterTransforms.java

/**
 *
 * @param startValues fixed parameter values (if no parameters are fixed this is completely ignored)
 * @param transforms Array of ParameterLimitsTransform (which can be the NullTransform which does NOT transform the parameter) which transform
 * a constrained function parameter (e.g. must be between -1 and 1) to a unconstrained fit parameter.
 * @param fixed BitSet with an element set to <b>true</b> if that parameter is fixed
 *///from   www.  j a v  a 2  s. co  m
public UncoupledParameterTransforms(final DoubleMatrix1D startValues,
        final ParameterLimitsTransform[] transforms, final BitSet fixed) {
    ArgumentChecker.notNull(startValues, "null start values");
    ArgumentChecker.notEmpty(transforms, "must specify transforms");
    ArgumentChecker.notNull(fixed, "must specify what is fixed (even if none)");
    _nMP = startValues.getNumberOfElements();
    ArgumentChecker.isTrue(_nMP == transforms.length, "Have {}-dimensional start value but {} transforms", _nMP,
            transforms.length);
    _freeParameters = new boolean[_nMP];
    for (int i = 0; i < _nMP; i++) {
        if (i < fixed.size()) {
            _freeParameters[i] = !fixed.get(i);
        } else {
            _freeParameters[i] = true;
        }
    }
    final int count = fixed.cardinality();
    ArgumentChecker.isTrue(count < _nMP, "all parameters are fixed");
    _nFP = _nMP - count;
    _startValues = startValues;
    _transforms = transforms;
}

From source file:com.oltpbenchmark.benchmarks.seats.SEATSWorker.java

/**
 * Returns true if the given BitSet for a Flight has all of its seats reserved 
 * @param seats/*  w ww.  j  a  v  a 2  s.  c om*/
 * @return
 */
protected boolean isFlightFull(BitSet seats) {
    assert (FULL_FLIGHT_BITSET.size() == seats.size());
    return FULL_FLIGHT_BITSET.equals(seats);
}

From source file:com.asakusafw.runtime.stage.input.DefaultSplitCombiner.java

private String[] computeLocations(Environment env, List<SplitDef> splits) {
    String[] locationNames = env.locations;
    LocationAndTime[] pairs = new LocationAndTime[locationNames.length];
    for (int i = 0; i < pairs.length; i++) {
        pairs[i] = new LocationAndTime(i, 0);
    }/*ww  w.ja va2  s. c om*/
    double totalLocalTime = 0.0;
    for (SplitDef split : splits) {
        BitSet locations = split.locations;
        totalLocalTime += split.localTime;
        for (int i = locations.nextSetBit(0); i >= 0; i = locations.nextSetBit(i + 1)) {
            pairs[i].time += split.localTime;
        }
    }
    Arrays.sort(pairs);
    double first = pairs[0].time;
    if (first == 0) {
        return null;
    }
    List<String> locations = new ArrayList<>();
    locations.add(locationNames[pairs[0].location]);
    for (int i = 1; i < pairs.length; i++) {
        double totalScore = pairs[i].time / totalLocalTime;
        double comparisonScore = pairs[i].time / first;
        if (totalScore < LOCALITY_TOTAL_FACTOR) {
            break;
        }
        if (comparisonScore < LOCALITY_COMPARISON_FACTOR) {
            break;
        }
        locations.add(locationNames[pairs[i].location]);
    }
    return locations.toArray(new String[locations.size()]);
}

From source file:org.apache.ctakes.ytex.kernel.evaluator.SemanticTypeKernel.java

public Set<Integer> tuiToMainSui(BitSet tuis) {
    Set<Integer> mainSui = new HashSet<Integer>(tuis.size());
    for (int i = tuis.nextSetBit(0); i >= 0; i = tuis.nextSetBit(i + 1)) {
        String tui = this.tuiList.get(i);
        mainSui.add(getMainSem(Integer.parseInt(tui.substring(1))));
    }/* w  ww . j a v a2  s.c o m*/
    return mainSui;
}

From source file:org.apache.eagle.alert.engine.serialization.PartitionedEventSerializerTest.java

@Test
public void testBitSet() {
    BitSet bitSet = new BitSet();
    bitSet.set(0, true); // 1
    bitSet.set(1, false); // 0
    bitSet.set(2, true); // 1
    LOG.info("Bit Set Size: {}", bitSet.size());
    LOG.info("Bit Set Byte[]: {}", bitSet.toByteArray());
    LOG.info("Bit Set Byte[]: {}", bitSet.toLongArray());
    LOG.info("BitSet[0]: {}", bitSet.get(0));
    LOG.info("BitSet[1]: {}", bitSet.get(1));
    LOG.info("BitSet[1]: {}", bitSet.get(2));

    byte[] bytes = bitSet.toByteArray();

    BitSet bitSet2 = BitSet.valueOf(bytes);

    LOG.info("Bit Set Size: {}", bitSet2.size());
    LOG.info("Bit Set Byte[]: {}", bitSet2.toByteArray());
    LOG.info("Bit Set Byte[]: {}", bitSet2.toLongArray());
    LOG.info("BitSet[0]: {}", bitSet2.get(0));
    LOG.info("BitSet[1]: {}", bitSet2.get(1));
    LOG.info("BitSet[1]: {}", bitSet2.get(2));

    BitSet bitSet3 = new BitSet();
    bitSet3.set(0, true);/* w w  w  .  j a va2s .  c o m*/
    Assert.assertEquals(1, bitSet3.length());

    BitSet bitSet4 = new BitSet();
    bitSet4.set(0, false);
    Assert.assertEquals(0, bitSet4.length());
    Assert.assertFalse(bitSet4.get(1));
    Assert.assertFalse(bitSet4.get(2));
}

From source file:org.apache.jackrabbit.core.query.lucene.JahiaLuceneQueryFactoryImpl.java

/**
 * Override LuceneQueryFactory.execute()
 *///from   w  w  w. j  a  v a  2s.  co  m
@Override
public List<Row> execute(Map<String, PropertyValue> columns, Selector selector, Constraint constraint,
        Sort sort, boolean externalSort, long offsetIn, long limitIn) throws RepositoryException, IOException {
    final IndexReader reader = index.getIndexReader(true);
    final int offset = offsetIn < 0 ? 0 : (int) offsetIn;
    final int limit = limitIn < 0 ? Integer.MAX_VALUE : (int) limitIn;

    QueryHits hits = null;
    try {
        JackrabbitIndexSearcher searcher = new JackrabbitIndexSearcher(session, reader,
                index.getContext().getItemStateManager());
        searcher.setSimilarity(index.getSimilarity());

        Predicate filter = Predicate.TRUE;
        BooleanQuery query = new BooleanQuery();

        QueryPair qp = new QueryPair(query);

        query.add(create(selector), MUST);
        if (constraint != null) {
            String name = selector.getSelectorName();
            NodeType type = ntManager.getNodeType(selector.getNodeTypeName());
            filter = mapConstraintToQueryAndFilter(qp, constraint, Collections.singletonMap(name, type),
                    searcher, reader);
        }

        // Added by jahia
        Set<String> foundIds = new HashSet<String>();
        int hasFacets = FacetHandler.hasFacetFunctions(columns, session);
        CountHandler.CountType countType = CountHandler.hasCountFunction(columns, session);
        boolean isCount = countType != null;
        BitSet bitset = (hasFacets & FacetHandler.FACET_COLUMNS) == 0 ? null : new BitSet();
        // End

        List<Row> rowList = externalSort ? new LinkedList<Row>() : null;
        Map<String, Row> rows = externalSort ? null : new LinkedHashMap<String, Row>();
        hits = searcher.evaluate(qp.mainQuery, sort, offset + limit);
        int currentNode = 0;
        int addedNodes = 0;
        int resultCount = 0;
        int hitsSize = 0;

        ScoreNode node = hits.nextScoreNode();
        Map<String, Boolean> checkedAcls = new HashMap<String, Boolean>();

        while (node != null) {
            if (isCount && countType.isApproxCount()) {
                hitsSize++;
                if (hitsSize > countType.getApproxCountLimit()) {
                    if (hits.getSize() > 0) {
                        hitsSize = hits.getSize();
                        break;
                    } else {
                        node = hits.nextScoreNode();
                        continue;
                    }
                }
            }
            IndexedNodeInfo infos = getIndexedNodeInfo(node, reader, isCount && countType.isSkipChecks());
            if (foundIds.add(infos.getMainNodeUuid())) { // <-- Added by jahia
                if (isCount && countType.isSkipChecks()) {
                    resultCount++;
                } else {
                    try {
                        boolean canRead = true;
                        if (isAclUuidInIndex()) {
                            canRead = checkIndexedAcl(checkedAcls, infos);
                        }
                        boolean checkVisibility = "1".equals(infos.getCheckVisibility())
                                && Constants.LIVE_WORKSPACE.equals(session.getWorkspace().getName());

                        if (canRead && (!Constants.LIVE_WORKSPACE.equals(session.getWorkspace().getName())
                                || ((infos.getPublished() == null || "true".equals(infos.getPublished()))
                                        && (infos.getCheckInvalidLanguages() == null || getLocale() == null
                                                || !infos.getCheckInvalidLanguages()
                                                        .contains(getLocale().toString()))))) {
                            if (filter == Predicate.TRUE) { // <-- Added by jahia
                                if ((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) {
                                    Row row = null;

                                    if (checkVisibility || !isAclUuidInIndex()) {
                                        NodeImpl objectNode = getNodeWithAclAndVisibilityCheck(node,
                                                checkVisibility);
                                        if (isCount) {
                                            resultCount++;
                                        } else {
                                            row = new LazySelectorRow(columns, evaluator,
                                                    selector.getSelectorName(), objectNode, node.getScore());
                                        }
                                    } else {
                                        if (isCount) {
                                            resultCount++;
                                        } else {
                                            row = new LazySelectorRow(columns, evaluator,
                                                    selector.getSelectorName(), node.getNodeId(),
                                                    node.getScore());
                                        }
                                    }

                                    if (row == null) {
                                        continue;
                                    }

                                    if (externalSort) {
                                        rowList.add(row);
                                    } else {
                                        // apply limit and offset rules locally
                                        if (currentNode >= offset && currentNode - offset < limit) {
                                            rows.put(node.getNodeId().toString(), row);
                                            addedNodes++;
                                        }
                                        currentNode++;
                                        // end the loop when going over the limit
                                        if (addedNodes == limit) {
                                            break;
                                        }
                                    }
                                }
                                if ((hasFacets & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
                                    //Added by Jahia
                                    //can be added to bitset when ACL checked and not in live mode or no visibility rule to check
                                    if (isAclUuidInIndex() && !checkVisibility) {
                                        bitset.set(infos.getDocNumber());
                                    } else { //try to load nodeWrapper to check the visibility rules
                                        NodeImpl objectNode = getNodeWithAclAndVisibilityCheck(node,
                                                checkVisibility);
                                        bitset.set(infos.getDocNumber());
                                    }
                                    //!Added by Jahia
                                }
                            } else {
                                NodeImpl objectNode = session.getNodeById(node.getNodeId());
                                if (objectNode.isNodeType("jnt:translation")) {
                                    objectNode = (NodeImpl) objectNode.getParent();
                                }
                                if (isCount) {
                                    resultCount++;
                                } else {
                                    Row row = new SelectorRow(columns, evaluator, selector.getSelectorName(),
                                            objectNode, node.getScore());
                                    if (filter.evaluate(row)) {
                                        if ((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) {
                                            if (externalSort) {
                                                rowList.add(row);
                                            } else {
                                                // apply limit and offset rules locally
                                                if (currentNode >= offset && currentNode - offset < limit) {
                                                    rows.put(node.getNodeId().toString(), row);
                                                    addedNodes++;
                                                }
                                                currentNode++;
                                                // end the loop when going over the limit
                                                if (addedNodes == limit) {
                                                    break;
                                                }
                                            }
                                        }
                                        if ((hasFacets
                                                & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
                                            bitset.set(infos.getDocNumber()); // <-- Added by jahia
                                        }
                                    }
                                }
                            }
                        }
                    } catch (PathNotFoundException e) {
                    } catch (ItemNotFoundException e) {
                        // skip the node
                    }
                }
            } else {
                if (((hasFacets & FacetHandler.ONLY_FACET_COLUMNS) == 0) && !isCount && !externalSort
                        && !infos.getMainNodeUuid().equals(node.getNodeId().toString())
                        && rows.containsKey(infos.getMainNodeUuid())) {
                    // we've got the translation node -> adjusting the position of the original node in the result list
                    rows.put(infos.getMainNodeUuid(), rows.remove(infos.getMainNodeUuid()));
                }
            } // <-- Added by jahia
            node = hits.nextScoreNode();
        }

        if (rowList == null) {
            if (rows != null) {
                rowList = new LinkedList<Row>(rows.values());
            } else {
                rowList = new LinkedList<Row>();
            }
        }
        // Added by jahia
        if ((hasFacets & FacetHandler.FACET_COLUMNS) == FacetHandler.FACET_COLUMNS) {
            OpenBitSet docIdSet = new OpenBitSetDISI(new DocIdBitSet(bitset).iterator(), bitset.size());

            FacetHandler h = new FacetHandler(columns, selector, docIdSet, index, session, nsMappings);
            h.handleFacets(reader);
            rowList.add(0, h.getFacetsRow());
        } else if (isCount) {
            boolean wasApproxLimitReached = false;
            if (countType.isApproxCount() && hitsSize > countType.getApproxCountLimit()) {
                resultCount = hitsSize * resultCount / countType.getApproxCountLimit();
                resultCount = (int) Math.ceil(MathUtils.round(resultCount,
                        resultCount < 1000 ? -1 : (resultCount < 10000 ? -2 : -3), BigDecimal.ROUND_UP));
                wasApproxLimitReached = true;
            }
            rowList.add(0, CountHandler.createCountRow(resultCount, wasApproxLimitReached));
        }
        // End

        return rowList;
    } finally {
        if (hits != null) {
            hits.close();
        }
        Util.closeOrRelease(reader);
    }
}

From source file:org.apache.openjpa.kernel.DetachManager.java

/**
 * Flush or invoke pre-store callbacks on the given broker if
 * needed. Return true if flushed/stored, false otherwise.
 */// w ww .  j a  v a2 s. c o m
private static boolean flushDirty(StateManagerImpl sm) {
    if (!sm.isDirty() || !sm.getBroker().isActive())
        return false;

    // only flush if there are actually any dirty non-flushed fields
    BitSet dirtyFields = sm.getDirty();
    BitSet flushedFields = sm.getFlushed();
    for (int i = 0; i < dirtyFields.size(); i++) {
        if (dirtyFields.get(i) && !flushedFields.get(i)) {
            if (sm.getBroker().getRollbackOnly())
                sm.getBroker().preFlush();
            else
                sm.getBroker().flush();
            return true;
        }
    }
    return false;
}