size ( )源码实例Demo

java.util.HashSet#size ( )源码实例Demo

下面列出了java.util.HashSet#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: steady   文件: WalaCallgraphConstructor.java
/**
 * check whether all entrypoints are existing in callgraph
 *
 * @throws CallgraphConstructException
 */
private void checkEntrypoints(boolean _policy) throws CallgraphConstructException {
    HashSet<com.sap.psr.vulas.shared.json.model.ConstructId> ep_diff = new HashSet<com.sap.psr.vulas.shared.json.model.ConstructId>();
    com.sap.psr.vulas.shared.json.model.ConstructId cid = null;
    ep_diff.addAll(this.filteredEP);
    for (CGNode node : this.callgraph.getEntrypointNodes()) {
        cid = getCid(node.getMethod());
        ep_diff.remove(cid);
    }
    if (_policy && (!ep_diff.isEmpty()))
        throw new CallgraphConstructException("Strict policy applied; terminating as there are [" + ep_diff.size() + "] entry points missing in call graph", null);
    if (ep_diff.size() == this.filteredEP.size())
        throw new CallgraphConstructException("[0/" + ep_diff.size() + "] entry points found in call graph", null);

    if ((!_policy) && (!ep_diff.isEmpty())) {
        WalaCallgraphConstructor.log.warn("There should be [" + this.filteredEP.size() + "] entrypoints set; but [" +
                ep_diff.size() + "] entrypoints are missing in the call graph");
        for (com.sap.psr.vulas.shared.json.model.ConstructId m : ep_diff)
            WalaCallgraphConstructor.log.warn("  [" + m.getQname() + "] is missing");
    } else {
        WalaCallgraphConstructor.log.info("All [" + this.filteredEP.size() + "] entrypoints exist in the call graph");
    }
}
 
源代码2 项目: yuzhouwan   文件: RandomUtilsTest.java
@Test
public void testNativeUUID() {
    int count = 0, len = 100, lost = 0;
    HashSet<String> set = new HashSet<>(len);
    int size;
    long time = 0;
    long begin, end;
    String uuid;
    while (count < len) {
        size = set.size();
        begin = System.nanoTime();
        uuid = uuid2();
        end = System.nanoTime();
        time += (end - begin);
        set.add(uuid);
        if (set.size() == size) lost++;
        count++;
    }
    assertEquals(0, lost);
    // Count: 100_0000, Time: 1294.214348 ms
    _log.info("Count: {}, Time: {} ms", count, time / Math.pow(10, 6));
}
 
源代码3 项目: COMP3204   文件: TomatoLinearClassifierDemo.java
private Float[] doClassify(double[] mean) {
	final HashSet<Integer> clzCount = new HashSet<Integer>();
	clzCount.addAll(classes);

	if (points.size() > 0 && clzCount.size() == 2) {
		final double[] p1 = new double[] { 0, 0 };
		p1[1] = (float) classifier.computeHyperplanePoint(0);

		final double[] p2 = new double[] { 1, 0 };
		p2[1] = (float) classifier.computeHyperplanePoint(1);

		image.drawLine(projectPoint(p1), projectPoint(p2), 3, RGBColour.BLACK);

		imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg));

		final int pred = classifier.predict(mean);
		guess.setText(this.classType.getItemAt(pred));
		return COLOURS[pred];
	}
	guess.setText("unknown");
	return RGBColour.MAGENTA;
}
 
源代码4 项目: openjdk-jdk9   文件: P11KeyStore.java
private boolean mapTrustedCert(String certLabel,
                            AliasInfo aliasInfo,
                            HashSet<AliasInfo> infoSet) {

    boolean sharedLabel = false;

    aliasInfo.type = ATTR_CLASS_CERT;
    aliasInfo.trusted = true;
    if (infoSet.size() == 1) {
        // unique CKA_LABEL - use certLabel as alias
        aliasMap.put(certLabel, aliasInfo);
    } else {
        // create new alias
        sharedLabel = true;
        aliasMap.put(getID(certLabel, aliasInfo.cert), aliasInfo);
    }

    return sharedLabel;
}
 
源代码5 项目: systemsgenetics   文件: eQtlsInRepeatData.java
public HashSet<String> getSharedProbes(String eQtlProbeFile, String permutationDataLocation)throws IOException{
	HashSet<String> eqtlProbes = makeProbesList(eQtlProbeFile);
	HashSet<String> permutationProbes = new HashSet<String>();
	for(int n=1;n<=100;n++){
		HashSet<String> tmpProbes = makeProbesList(permutationDataLocation + "PermutedEQTLsPermutationRound" + n + ".txt.gz");
		if(n > 1){
			permutationProbes.retainAll(tmpProbes);
		}
		else{
			permutationProbes = tmpProbes;
		}
	}
	
	if(eqtlProbes.size() > permutationProbes.size()){
		eqtlProbes.retainAll(permutationProbes);
		return eqtlProbes;
	}
	else{
		permutationProbes.retainAll(eqtlProbes);
		return permutationProbes;
	}
}
 
源代码6 项目: MDAG   文件: MDAG.java
private int countNodes(MDAGNode originNode, HashSet<Integer> nodeIDHashSet)
{
    if(originNode != sourceNode) nodeIDHashSet.add(originNode.id);
    
    TreeMap<Character, MDAGNode> transitionTreeMap = originNode.getOutgoingTransitions();
    
    for(Entry<Character, MDAGNode> transitionKeyValuePair : transitionTreeMap.entrySet()) 
        countNodes(transitionKeyValuePair.getValue(), nodeIDHashSet);

    return nodeIDHashSet.size();
}
 
源代码7 项目: ctsms   文件: NotificationDaoImpl.java
@Override
protected Notification handleAddNotification(ECRFFieldStatusEntry ecrfFieldStatusEntry, Date today, Map messageParameters) throws Exception {
	org.phoenixctms.ctsms.enumeration.NotificationType notificationType = org.phoenixctms.ctsms.enumeration.NotificationType.NEW_ECRF_FIELD_STATUS;
	ServiceUtil.cancelNotifications(ecrfFieldStatusEntry.getNotifications(), this, notificationType);
	Notification notification = Notification.Factory.newInstance();
	Department department = null;
	Trial trial = ecrfFieldStatusEntry.getListEntry().getTrial();
	HashSet<Staff> trialMembers = addTrialTeamMemberRecipients(notification, trial, false, false, false, false, false, true, false);
	if (trialMembers.size() == 0) {
		department = trial.getDepartment();
		notification.setDepartment(department);
	}
	notification.setEcrfFieldStatusEntry(ecrfFieldStatusEntry);
	ecrfFieldStatusEntry.addNotifications(notification);
	if (messageParameters == null) {
		messageParameters = CoreUtil.createEmptyTemplateModel();
	}
	messageParameters.put(NotificationMessageTemplateParameters.ECRF_INPUT_FIELD_VALUE_ADAPTER, ECRF_INPUT_FIELD_VALUE_ADAPTER);
	if (setRemainingFields(notification, today, notificationType, messageParameters)) {
		notification = this.create(notification);
		createNotificationRecipients(notification, trialMembers);
		return notification;
	} else {
		ecrfFieldStatusEntry.removeNotifications(notification);
		return null;
	}
}
 
源代码8 项目: unleashed-pixel-dungeon   文件: Bee.java
@Override
protected Char chooseEnemy() {
	//if the pot is no longer present, target the hero
	if (potHolder == -1 && potPos == -1)
		return Dungeon.hero;

	//if something is holding the pot, target that
	else if (Actor.findById(potHolder) != null)
		return (Char)Actor.findById(potHolder);

	//if the pot is on the ground
	else {

		//if already targeting something, and that thing is still alive and near the pot, keeping targeting it.
		if (enemy != null && enemy.isAlive() && Level.distance(enemy.pos, potPos) <= 3) return enemy;

		//find all mobs near the pot
		HashSet<Char> enemies = new HashSet<Char>();
		for (Mob mob : Dungeon.level.mobs)
			if (!(mob instanceof Bee) && Level.distance(mob.pos, potPos) <= 3 && (mob.hostile || mob.ally))
				enemies.add(mob);

		//pick one, if there are none, check if the hero is near the pot, go for them, otherwise go for nothing.
		if (enemies.size() > 0) return Random.element(enemies);
		else return (Level.distance(Dungeon.hero.pos, potPos) <= 3) ? Dungeon.hero : null ;
	}
}
 
源代码9 项目: iBioSim   文件: CompositionalAnalysis.java
@SuppressWarnings("unused")
	private static boolean equivalentOutgoing(Set<Transition> enabled1, List<Transition> enabled2){
//		enabled2.containsAll(enabled1) && enabled1.containsAll(enabled2)
		HashSet<Transition> enabled2Set = new HashSet<Transition>();
		enabled2Set.addAll(enabled2);
		
		if(enabled2Set.size() == enabled1.size() && enabled1.containsAll(enabled2Set))
			return true;
		
		return false;
	}
 
源代码10 项目: Rel   文件: DynamicDispatch.java
void locateAndInvoke(Context context) {
	// TODO - improve performance by caching operators for given run-time invocationSignatureS.  Cache should be cleared if type hierarchy changes.
	Value[] operands = context.peek(invocationSignature.getParmCount());
	for (int i=0; i<invocationSignature.getParmCount(); i++)
		if (operands[i] instanceof ValueAlpha) {
			Type argumentType = ((ValueAlpha)operands[i]).getType(generator.getDatabase());
			invocationSignature.setParameterType(i, argumentType);
		}
	HashSet<OperatorSignature> possibleTargets = generator.getPossibleTargetSignatures(inOperator, invocationSignature);
	if (possibleTargets.size() == 0)
		throw new ExceptionSemantic("RS0278: No run-time invocation targets found for " + invocationSignature);
	int closestDistance = Integer.MAX_VALUE;
	OperatorSignature closestSignature = null;
	for (OperatorSignature signature: possibleTargets) {
		int distance = signature.getInvocationDistance(invocationSignature);
		if (distance <= closestDistance) {
			closestDistance = distance;
			closestSignature = signature;
		}
	}
	OperatorDefinition operator = generator.locateOperator(inOperator, closestSignature);
	if (operator != null) {
		invoke(operator, context);
		return;
	}			
	throw new ExceptionSemantic("RS0279: Operator '" + closestSignature + "' has not been defined, nor has any compatible operator of the same name.");
}
 
源代码11 项目: meka   文件: RecentFilesHandler.java
/**
  * Determines the minimum number of parent directories that need to be
  * included in the filename to make the filenames in the menu distinguishable.
  *
  * @return		the minimum number of parent directories, -1 means
  * 			full path
  */
 protected synchronized int determineMinimumNumberOfParentDirs() {
   int			result;
   HashSet<String> files;
   int			num;
   int			i;
   int			max;

   result = -1;

   max = 0;
   for (i = 0; i < m_RecentItems.size(); i++)
     max = Math.max(max, FileUtils.getDirectoryDepth(m_RecentItems.get(i)));

   num = 0;
   do {
     files = new HashSet<String>();
     for (i = 0; i < m_RecentItems.size(); i++)
files.add(FileUtils.createPartialFilename(m_RecentItems.get(i), num));
     if (files.size() == m_RecentItems.size())
result = num;
     else
num++;
   }
   while ((files.size() < m_RecentItems.size()) && (num <= max));

   return result;
 }
 
源代码12 项目: RedReader   文件: WeakCache.java
public synchronized void performRequest(final Collection<K> keys, final TimestampBound timestampBound,
										final RequestResponseHandler<HashMap<K, V>, F> handler) {

	final HashSet<K> keysRemaining = new HashSet<>(keys);
	final HashMap<K, V> cacheResult = new HashMap<>(keys.size());
	long oldestTimestamp = Long.MAX_VALUE;

	for(final K key : keys) {

		final CacheEntry entry = cached.get(key);
		if(entry != null) {

			final V value = entry.data.get();
			if(value != null && timestampBound.verifyTimestamp(value.getTimestamp())) {
				keysRemaining.remove(key);
				cacheResult.put(key, value);
				oldestTimestamp = Math.min(oldestTimestamp, value.getTimestamp());
			}
		}
	}

	if(keysRemaining.size() > 0) {

		final long outerOldestTimestamp = oldestTimestamp;

		cacheDataSource.performRequest(keysRemaining, timestampBound, new RequestResponseHandler<HashMap<K, V>, F>() {
			public void onRequestFailed(F failureReason) {
				handler.onRequestFailed(failureReason);
			}

			public void onRequestSuccess(HashMap<K, V> result, long timeCached) {
				cacheResult.putAll(result);
				handler.onRequestSuccess(cacheResult, Math.min(timeCached, outerOldestTimestamp));
			}
		});

	} else {
		handler.onRequestSuccess(cacheResult, oldestTimestamp);
	}
}
 
源代码13 项目: android-SwipeRefreshLayoutBasic   文件: Cheeses.java
/**
 * Return a list of random cheeses.
 *
 * @param count the amount of cheeses to return.
 */
public static ArrayList<String> randomList(int count) {
    Random random = new Random();
    HashSet<String> items = new HashSet<String>();

    // Make sure that don't infinity loop
    count = Math.min(count, CHEESES.length);

    while (items.size() < count) {
        items.add(CHEESES[random.nextInt(CHEESES.length)]);
    }

    return new ArrayList<String>(items);
}
 
@Test
public void testDirectStream() throws InterruptedException {
    HashSet<String> sentMessages = new HashSet<String>();
    for (int i = 1; i <= 100; i++)
        sentMessages.add(i + "");
    talosTestUtils.sendMessagesAndWaitForReceive(topic, sentMessages);
    JavaPairDStream<String, String> stream = TalosUtils.createDirectStream(
            ssc, talosTestUtils.javaTalosParams(), talosTestUtils.credential(), new HashSet<String>() {{
                add(topic);
            }}
    );
    final Set<String> result = Collections.synchronizedSet(new HashSet<String>());
    stream.foreachRDD(
            new Function<JavaPairRDD<String, String>, Void>() {
                public Void call(JavaPairRDD<String, String> rdd) throws Exception {
                    Iterator<Tuple2<String, String>> iterator = rdd.collect().iterator();
                    while (iterator.hasNext()) {
                        result.add(iterator.next()._2);
                    }
                    return null;
                }
            }
    );
    ssc.start();
    long startTime = System.currentTimeMillis();
    boolean matches = false;
    while (!matches && System.currentTimeMillis() - startTime < 20000) {
        matches = sentMessages.size() == result.size();
        Thread.sleep(50);
    }
    Assert.assertEquals(sentMessages, result);
    ssc.stop();
}
 
源代码15 项目: metafacture-core   文件: JsonToElasticsearchBulk.java
@Override
public Object put(String key, Object value) {
    if (containsKey(key)) {
        Object oldValue = get(key);
        if (oldValue instanceof Set) {
            @SuppressWarnings("unchecked")
            Set<Object> vals = ((Set<Object>) oldValue);
            vals.add(value);
            return super.put(key, vals);
        }
        HashSet<Object> set = new HashSet<>(Arrays.asList(oldValue, value));
        return super.put(key, set.size() == 1 ? value : set);
    }
    return super.put(key, value);
}
 
源代码16 项目: flink   文件: GatherSumApplyConfigurationITCase.java
@Override
public void apply(HashSet<Long> newValue, HashSet<Long> currentValue) {
	newValue.addAll(currentValue);
	if (newValue.size() > currentValue.size()) {
		setResult(newValue);
	}
}
 
源代码17 项目: Alink   文件: OutputColsHelper.java
/**
 * The constructor.
 *
 * @param inputSchema      Schema of input data being predicted or transformed.
 * @param outputColNames   Output column names of the prediction/transformation operator.
 * @param outputColTypes   Output column types of the prediction/transformation operator.
 * @param reservedColNames Reserved column names, which is a subset of input data's column names that we want to preserve.
 */
public OutputColsHelper(TableSchema inputSchema, String[] outputColNames, TypeInformation[] outputColTypes,
                        String[] reservedColNames) {
    this.inputColNames = inputSchema.getFieldNames();
    this.inputColTypes = inputSchema.getFieldTypes();
    this.outputColNames = outputColNames;
    this.outputColTypes = outputColTypes;

    HashSet<String> toReservedCols = new HashSet<>(
        Arrays.asList(reservedColNames == null ? this.inputColNames : reservedColNames)
    );
    //the indices of the columns which need to be reserved.
    ArrayList<Integer> reservedColIndices = new ArrayList<>(toReservedCols.size());
    ArrayList<Integer> reservedColToResultIndex = new ArrayList<>(toReservedCols.size());
    outputColsPosInResult = new int[outputColNames.length];
    Arrays.fill(outputColsPosInResult, -1);
    int index = 0;
    for (int i = 0; i < inputColNames.length; i++) {
        int key = ArrayUtils.indexOf(outputColNames, inputColNames[i]);
        if (key >= 0) {
            outputColsPosInResult[key] = index++;
            continue;
        }
        //add these interested column.
        if (toReservedCols.contains(inputColNames[i])) {
            reservedColIndices.add(i);
            reservedColToResultIndex.add(index++);
        }
    }
    for (int i = 0; i < outputColsPosInResult.length; i++) {
        if (outputColsPosInResult[i] == -1) {
            outputColsPosInResult[i] = index++;
        }
    }
    //write reversed column information in array.
    this.reservedCols = new int[reservedColIndices.size()];
    this.reservedColsPosInResult = new int[reservedColIndices.size()];
    for (int i = 0; i < this.reservedCols.length; i++) {
        this.reservedCols[i] = reservedColIndices.get(i);
        this.reservedColsPosInResult[i] = reservedColToResultIndex.get(i);
    }
}
 
源代码18 项目: gemfirexd-oss   文件: HashSetWrapper.java
public void validate( Region region, Info info ) {
  HashSet obj = (HashSet) CacheUtil.get( region, info.getName() );
  if ( obj.size() != info.getUpdates() )
    throw new DLockTestException( "Object data is invalid for " + info.getName() +
                                     " with expected count " + info.getUpdates() + ": " + obj );
}
 
源代码19 项目: es6draft   文件: SourceBuilder.java
private String source(ExecutionContext cx, HashSet<ScriptObject> stack, Object value) {
    switch (Type.of(value)) {
    case Null:
        return "null";
    case Boolean:
        return Type.booleanValue(value) ? "true" : "false";
    case String:
        return Strings.quote(Type.stringValue(value).toString());
    case Symbol:
        return Type.symbolValue(value).toString();
    case Number:
        return ToFlatString(cx, value);
    case BigInt:
        return ToFlatString(cx, value) + "n";
    case SIMD:
        return Type.simdValue(value).toString();
    case Object:
        ScriptObject objValue = Type.objectValue(value);
        if (IsCallable(objValue)) {
            return ((Callable) objValue).toSource(cx);
        }
        if (stack.contains(objValue) || stack.size() > maxStackDepth) {
            return "« ... »";
        }
        stack.add(objValue);
        try {
            if (objValue instanceof DateObject) {
                return DatePrototype.Properties.toString(cx, value).toString();
            } else if (objValue instanceof RegExpObject) {
                return RegExpPrototype.Properties.toString(cx, value).toString();
            } else if (objValue instanceof ArrayObject) {
                return arrayToSource(cx, stack, objValue);
            } else {
                return objectToSource(cx, stack, objValue);
            }
        } finally {
            stack.remove(objValue);
        }
    case Undefined:
    default:
        return "(void 0)";
    }
}
 
源代码20 项目: tablesaw   文件: ColumnTypeDetector.java
/**
 * Estimates and returns the type for each column in the input text
 *
 * <p>The type is determined by checking a sample of the data. Because only a sample of the data
 * is checked, the types may be incorrect. If that is the case a Parse Exception will be thrown.
 *
 * <p>The method {@code printColumnTypes()} can be used to print a list of the detected columns
 * that can be corrected and used to explicitly specify the correct column types.
 */
public ColumnType[] detectColumnTypes(Iterator<String[]> rows, ReadOptions options) {
  boolean useSampling = options.sample();

  // to hold the results
  List<ColumnType> columnTypes = new ArrayList<>();

  // to hold the data read from the file
  List<List<String>> columnData = new ArrayList<>();

  int rowCount = 0; // make sure we don't go over maxRows

  int nextRow = 0;
  while (rows.hasNext()) {
    String[] nextLine = rows.next();
    // initialize the arrays to hold the strings. we don't know how many we need until we read the
    // first row
    if (rowCount == 0) {
      for (int i = 0; i < nextLine.length; i++) {
        columnData.add(new ArrayList<>());
      }
    }
    int columnNumber = 0;
    if (rowCount == nextRow) {
      for (String field : nextLine) {
        columnData.get(columnNumber).add(field);
        columnNumber++;
      }
      if (useSampling) {
        nextRow = nextRow(nextRow);
      } else {
        nextRow = nextRowWithoutSampling(nextRow);
      }
    }
    rowCount++;
  }

  // now detect
  for (List<String> valuesList : columnData) {
    ColumnType detectedType = detectType(valuesList, options);
    if (detectedType.equals(StringColumnType.STRING)
        && rowCount > STRING_COLUMN_ROW_COUNT_CUTOFF) {
      HashSet<String> unique = new HashSet<>(valuesList);
      double uniquePct = unique.size() / (valuesList.size() * 1.0);
      if (uniquePct > STRING_COLUMN_CUTOFF) {
        detectedType = TEXT;
      }
    }
    columnTypes.add(detectedType);
  }
  return columnTypes.toArray(new ColumnType[0]);
}