Java Code Examples for java.util.BitSet#cardinality()

The following examples show how to use java.util.BitSet#cardinality() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlockUtils.java    From Box with Apache License 2.0 6 votes vote down vote up
public static BlockNode getPathCross(MethodNode mth, BlockNode b1, BlockNode b2) {
	if (b1 == null || b2 == null) {
		return null;
	}
	if (b1.getDomFrontier() == null || b2.getDomFrontier() == null) {
		return null;
	}
	BitSet b = new BitSet();
	b.or(b1.getDomFrontier());
	b.and(b2.getDomFrontier());
	b.clear(b1.getId());
	b.clear(b2.getId());
	if (b.cardinality() == 1) {
		BlockNode end = mth.getBasicBlocks().get(b.nextSetBit(0));
		if (isPathExists(b1, end) && isPathExists(b2, end)) {
			return end;
		}
	}
	if (isPathExists(b1, b2)) {
		return b2;
	}
	if (isPathExists(b2, b1)) {
		return b1;
	}
	return null;
}
 
Example 2
Source File: FingerprintSubset.java    From ReactionDecoder with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
     * Determine if this set is an (improper) superset of another.
     *
     * @param source the set we are testing for.
     * @param destination the set we are testing against.
     * @return source is a superset of destination, yes then return true else
     * false
     * @throws CDKException
     */
    public static boolean isSuperSet(BitSet source, BitSet destination) throws CDKException {
        boolean flag = false;
        if (source.cardinality() >= destination.cardinality()) {

            not_null(source);

            /* make a copy of the source set */
            BitSet copy_other = (BitSet) source.clone();

            /* and or in */
            copy_other.and(destination);

            /* if it hasn't changed, we were a subset */
            flag = copy_other.equals(destination);
//            flag = copy_other.equals(destination);
        }
        return flag;
    }
 
Example 3
Source File: BitSetStreamTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRandomStream() {
    final int size = 1024 * 1024;
    final int[] seeds = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
            43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
    final byte[] bytes = new byte[size];
    for (int seed : seeds) {
        final Random random = new Random(seed);
        random.nextBytes(bytes);
        final BitSet bitSet = BitSet.valueOf(bytes);
        final int cardinality = bitSet.cardinality();
        final IntStream stream = bitSet.stream();
        final int[] array = stream.toArray();
        assertEquals(array.length, cardinality);
        int nextSetBit = -1;
        for (int i=0; i < cardinality; i++) {
            nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
            assertEquals(array[i], nextSetBit);
        }
    }
}
 
Example 4
Source File: RegisterSpecList.java    From J2ME-Loader with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance, which contains a subset of the elements
 * specified by the given BitSet. Indexes in the BitSet with a zero
 * are included, while indexes with a one are excluded. Mutability
 * of the result is inherited from the original.
 *
 * @param exclusionSet {@code non-null;} set of registers to exclude
 * @return {@code non-null;} an appropriately-constructed instance
 */
public RegisterSpecList subset(BitSet exclusionSet) {
    int newSize = size() - exclusionSet.cardinality();

    if (newSize == 0) {
        return EMPTY;
    }

    RegisterSpecList result = new RegisterSpecList(newSize);

    int newIndex = 0;
    for (int oldIndex = 0; oldIndex < size(); oldIndex++) {
        if (!exclusionSet.get(oldIndex)) {
            result.set0(newIndex, get0(oldIndex));
            newIndex++;
        }
    }

    if (isImmutable()) {
        result.setImmutable();
    }

    return result;
}
 
Example 5
Source File: FixedPartitioningTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Hydra task to do region operations, then stop scheduling.
 */
public static void HydraTask_doOps() {
  BitSet availableOps = new BitSet(operations.length);
  availableOps.flip(FIRST_OP, LAST_OP + 1);
  ((FixedPartitioningTest)testInstance).doOps(availableOps);
  Log.getLogWriter().info("Cardinality is " + availableOps.cardinality());
  if (availableOps.cardinality() == 0) {
    ParRegBB.getBB().getSharedCounters().increment(ParRegBB.TimeToStop);
    throw new StopSchedulingTaskOnClientOrder("Finished with ops");
  }
}
 
Example 6
Source File: FunctionServiceTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Hydra task to execute region functions, then stop scheduling (For HA).
 */
public static void HydraTask_doFunctionExecution_HA() {
  BitSet availableOps = new BitSet(operations.length);
  availableOps.flip(FUNC_HA_FIRST_OP, FUNC_HA_LAST_OP + 1);
  ((FunctionServiceTest)testInstance).doFunctionExecution(availableOps);
  Log.getLogWriter().info("Cardinality is " + availableOps.cardinality());
  if (availableOps.cardinality() == 0) {
    ParRegBB.getBB().getSharedCounters().increment(ParRegBB.TimeToStop);
    throw new StopSchedulingTaskOnClientOrder("Finished with ops");
  }
}
 
Example 7
Source File: NaiveFdExtender.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
@Override
public void executeAlgorithm(Map<BitSet, BitSet> fds) {
	System.out.println("Building the FDs' closures ...");
	for (Entry<BitSet, BitSet> entry : fds.entrySet()) {
		BitSet lhs = entry.getKey();
		BitSet rhs = entry.getValue();
		
		// Add the trivial fds to the current fd's rhs for the closure construction (we need to check against ALL the attributes in this fd to build its closure)
		rhs.or(lhs);
		
		// Extend rhs
		long rhsCardinality;
		do {
			rhsCardinality = rhs.cardinality();
			
			for (Entry<BitSet, BitSet> other : fds.entrySet())
				if (Utils.andNotCount(other.getKey(), rhs) == 0)
					rhs.or(other.getValue());
			
			// TODO: when we think of parallelizing the closure calculation
		//	closureFds.entrySet().stream()
		//		.filter(other -> {return Utils.andNotCount(other.getKey(), rhs) == 0;})
		//		.forEach(other -> rhs.and(other.getValue()));
		}
		while (rhsCardinality != rhs.cardinality());
		
		// Remove the trivial fds
		rhs.andNot(lhs);
	}
}
 
Example 8
Source File: Bitfield.java    From bt with Apache License 2.0 5 votes vote down vote up
/**
 * @return Number of pieces that have status different from {@link PieceStatus#COMPLETE_VERIFIED}
 *         and should NOT be skipped.
 * @since 1.0
 */
public int getPiecesRemaining() {
    lock.lock();
    try {
        if (skipped == null) {
            return getPiecesTotal() - getPiecesComplete();
        } else {
            BitSet bitmask = getBitmask();
            bitmask.or(skipped);
            return getPiecesTotal() - bitmask.cardinality();
        }
    } finally {
        lock.unlock();
    }
}
 
Example 9
Source File: BlockUtils.java    From jadx with Apache License 2.0 5 votes vote down vote up
@Nullable
public static BlockNode bitSetToOneBlock(MethodNode mth, BitSet bs) {
	if (bs == null || bs.cardinality() != 1) {
		return null;
	}
	return mth.getBasicBlocks().get(bs.nextSetBit(0));
}
 
Example 10
Source File: BinVector.java    From TarsosLSH with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int hammingDistance(BinVector other) {
	//clone the bit set of this object
	BitSet xored = (BitSet) bitSet.clone();
	
	//xor (modify) the bit set
	xored.xor(other.bitSet);
	//return the number of 1's
	return xored.cardinality();
}
 
Example 11
Source File: UCCSet.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public boolean contains(BitSet ucc) {
	int length = ucc.cardinality();
	
	if ((this.maxDepth > 0) && (length > this.maxDepth))
		return false;
	
	return this.uccLevels.get(length).contains(ucc);
}
 
Example 12
Source File: FDSet.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public boolean contains(BitSet fd) {
	int length = fd.cardinality();
	
	if ((this.maxDepth > 0) && (length > this.maxDepth))
		return false;
	
	return this.fdLevels.get(length).contains(fd);
}
 
Example 13
Source File: NodeBuilder.java    From openCypher with Apache License 2.0 5 votes vote down vote up
public void verifyRequiredAttributes( BitSet required )
{
    if ( required.cardinality() != 0 )
    {
        throw new IllegalArgumentException( required.stream().mapToObj( ( i ) -> attributes[i].name ).collect(
                Collectors.joining( ", ", "Missing required attributes: ", "" ) ) );
    }
}
 
Example 14
Source File: OzoneAcl.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for OzoneAcl.
 *
 * @param type   - Type
 * @param name   - Name of user
 * @param acls   - Rights
 * @param scope  - AclScope
 */
public OzoneAcl(ACLIdentityType type, String name, BitSet acls,
    AclScope scope) {
  Objects.requireNonNull(type);
  Objects.requireNonNull(acls);

  if(acls.cardinality() > ACLType.getNoOfAcls()) {
    throw new IllegalArgumentException("Acl bitset passed has unexpected " +
        "size. bitset size:" + acls.cardinality() + ", bitset:"
        + acls.toString());
  }
  this.aclBitSet = (BitSet) acls.clone();

  this.name = name;
  this.type = type;
  if (type == ACLIdentityType.WORLD || type == ACLIdentityType.ANONYMOUS) {
    if (!name.equals(ACLIdentityType.WORLD.name()) &&
        !name.equals(ACLIdentityType.ANONYMOUS.name()) &&
        name.length() != 0) {
      throw new IllegalArgumentException("Unexpected name:{" + name +
          "} for type WORLD, ANONYMOUS. It should be WORLD & " +
          "ANONYMOUS respectively.");
    }
    // For type WORLD and ANONYMOUS we allow only one acl to be set.
    this.name = type.name();
  }
  if (((type == ACLIdentityType.USER) || (type == ACLIdentityType.GROUP))
      && (name.length() == 0)) {
    throw new IllegalArgumentException("User or group name is required");
  }
  aclScope = scope;
}
 
Example 15
Source File: ExecutionAndColocationTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Hydra task to execute functions, then stop scheduling.
 */
public static void HydraTask_doFunctionExecution() {
  PdxTest.initClassLoader();
  BitSet availableOps = new BitSet(operations.length);
  availableOps.flip(FIRST_OP, LAST_OP + 1);
  ((ExecutionAndColocationTest)testInstance)
      .doFunctionExecution(availableOps);
  if (availableOps.cardinality() == 0) {
    ParRegBB.getBB().getSharedCounters().increment(ParRegBB.TimeToStop);
    throw new StopSchedulingTaskOnClientOrder("Finished with ops");
  }
}
 
Example 16
Source File: DatanodeDescriptor.java    From big-c with Apache License 2.0 5 votes vote down vote up
public int updateBlockReportContext(BlockReportContext context) {
  if (curBlockReportId != context.getReportId()) {
    curBlockReportId = context.getReportId();
    curBlockReportRpcsSeen = new BitSet(context.getTotalRpcs());
  }
  curBlockReportRpcsSeen.set(context.getCurRpc());
  return curBlockReportRpcsSeen.cardinality();
}
 
Example 17
Source File: SsaToRop.java    From Box with Apache License 2.0 5 votes vote down vote up
/**
 * @return rop-form basic block list
 */
private BasicBlockList convertBasicBlocks() {
    ArrayList<SsaBasicBlock> blocks = ssaMeth.getBlocks();

    // Exit block may be null.
    SsaBasicBlock exitBlock = ssaMeth.getExitBlock();

    BitSet reachable = ssaMeth.computeReachability();
    int ropBlockCount = reachable.cardinality();

    // Don't count the exit block, if it exists and is reachable.
    if (exitBlock != null && reachable.get(exitBlock.getIndex())) {
        ropBlockCount -= 1;
    }

    BasicBlockList result = new BasicBlockList(ropBlockCount);

    // Convert all the reachable blocks except the exit block.
    int ropBlockIndex = 0;
    for (SsaBasicBlock b : blocks) {
        if (reachable.get(b.getIndex()) && b != exitBlock) {
            result.set(ropBlockIndex++, convertBasicBlock(b));
        }
    }

    // The exit block, which is discarded, must do nothing.
    if (exitBlock != null && !exitBlock.getInsns().isEmpty()) {
        throw new RuntimeException(
                "Exit block must have no insns when leaving SSA form");
    }

    return result;
}
 
Example 18
Source File: LhsUtils.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public static List<BitSet> generateLhsSubsets(BitSet lhs) {
    List<BitSet> results = new LinkedList<>();
    for (int i = lhs.nextSetBit(0); i >= 0; i = lhs.nextSetBit(i + 1)) {
        BitSet subset = (BitSet) lhs.clone();
        subset.flip(i);
        if (subset.cardinality() > 0) {
            results.add(subset);
        }
    }
    return results;
}
 
Example 19
Source File: ResourceAllocationIndexPlugin.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
    final boolean includeConnectionsIn = parameters.getBooleanValue(INCLUDE_CONNECTIONS_IN_PARAMETER_ID);
    final boolean includeConnectionsOut = parameters.getBooleanValue(INCLUDE_CONNECTIONS_OUT_PARAMETER_ID);
    final boolean treatUndirectedBidirectional = parameters.getBooleanValue(TREAT_UNDIRECTED_BIDIRECTIONAL_PARAMETER_ID);
    final int minCommonFeatures = parameters.getParameters().get(MINIMUM_COMMON_FEATURES_PARAMETER_ID).getIntegerValue();
    final boolean selectedOnly = parameters.getBooleanValue(SELECTED_ONLY_PARAMETER_ID);
    final boolean community = parameters.getBooleanValue(COMMUNITY_PARAMETER_ID);

    final int vertexSelectedAttributeId = VisualConcept.VertexAttribute.SELECTED.get(graph);

    // map each vertex to its neighbour count
    final int vertexCount = graph.getVertexCount();
    final BitSet[] neighbours = new BitSet[vertexCount];
    final BitSet update = new BitSet(vertexCount);
    final BitSet selected = new BitSet(vertexCount);
    for (int vertexPosition = 0; vertexPosition < vertexCount; vertexPosition++) {
        final int vertexId = graph.getVertex(vertexPosition);
        neighbours[vertexPosition] = new BitSet(vertexCount);
        for (int vertexNeighbourPosition = 0; vertexNeighbourPosition < graph.getVertexNeighbourCount(vertexId); vertexNeighbourPosition++) {
            final int neighbourId = graph.getVertexNeighbour(vertexId, vertexNeighbourPosition);
            final int neighbourPosition = graph.getVertexPosition(neighbourId);

            if (vertexPosition == neighbourPosition) {
                continue;
            }

            final int linkId = graph.getLink(vertexId, neighbourId);
            for (int linkEdgePosition = 0; linkEdgePosition < graph.getLinkEdgeCount(linkId); linkEdgePosition++) {
                final int edgeId = graph.getLinkEdge(linkId, linkEdgePosition);
                final int edgeDirection = graph.getEdgeDirection(edgeId);
                final boolean isRequestedDirection = (treatUndirectedBidirectional && edgeDirection == GraphConstants.UNDIRECTED
                        || includeConnectionsIn && graph.getEdgeDestinationVertex(edgeId) == neighbourId
                        || includeConnectionsOut && graph.getEdgeSourceVertex(edgeId) == neighbourId);
                if (isRequestedDirection) {
                    if (!SimilarityUtilities.checkEdgeTypes(graph, edgeId)) {
                        continue;
                    }
                    neighbours[vertexPosition].set(neighbourPosition, true);
                    update.set(vertexPosition, true);
                }
            }
        }
        final boolean vertexSelected = graph.getBooleanValue(vertexSelectedAttributeId, vertexId);
        selected.set(vertexPosition, vertexSelected);
    }

    // calculate resource allocation index for every pair of vertices on the graph
    final Map<Tuple<Integer, Integer>, Float> raiScores = new HashMap<>();
    for (int vertexOnePosition = update.nextSetBit(0); vertexOnePosition >= 0; vertexOnePosition = update.nextSetBit(vertexOnePosition + 1)) {
        for (int vertexTwoPosition = update.nextSetBit(0); vertexTwoPosition >= 0; vertexTwoPosition = update.nextSetBit(vertexTwoPosition + 1)) {
            if (!selectedOnly || (selected.get(vertexOnePosition) || selected.get(vertexTwoPosition))) {
                if (vertexOnePosition >= vertexTwoPosition) {
                    continue;
                }

                if (community && (!selected.get(vertexOnePosition) || !selected.get(vertexTwoPosition))) {
                    continue;
                }

                final BitSet intersection = (BitSet) neighbours[vertexOnePosition].clone();
                intersection.and(neighbours[vertexTwoPosition]);
                intersection.set(vertexOnePosition, false);
                intersection.set(vertexTwoPosition, false);

                if (intersection.cardinality() < minCommonFeatures) {
                    continue;
                }

                final int vertexOneId = graph.getVertex(vertexOnePosition);
                final int vertexTwoId = graph.getVertex(vertexTwoPosition);
                float sum = 0f;
                for (int commonNeighbour = intersection.nextSetBit(0); commonNeighbour >= 0; commonNeighbour = intersection.nextSetBit(commonNeighbour + 1)) {
                    sum += (1f / graph.getVertexNeighbourCount(graph.getVertex(commonNeighbour)));
                }

                raiScores.put(Tuple.create(vertexOneId, vertexTwoId), sum);
            }
        }
    }

    // update the graph with resource allocation index values
    SimilarityUtilities.addScoresToGraph(graph, raiScores, RESOURCE_ALLOCATION_INDEX_ATTRIBUTE);
    // complete with schema
    PluginExecution.withPlugin(VisualSchemaPluginRegistry.COMPLETE_SCHEMA).executeNow(graph);
}
 
Example 20
Source File: NormiConversion.java    From metanome-algorithms with Apache License 2.0 4 votes vote down vote up
public List<FunctionalDependency> toFunctionalDependencies(BitSet lhs, BitSet rhs) {
	List<FunctionalDependency> fds = new ArrayList<>(rhs.cardinality());
	for (int rhsAttr = rhs.nextSetBit(0); rhsAttr >= 0; rhsAttr = rhs.nextSetBit(rhsAttr + 1))
		fds.add(this.toFunctionalDependency(lhs, rhsAttr));
	return fds;
}