Java Code Examples for java.util.HashSet#size()

The following examples show how to use java.util.HashSet#size() . 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: P11KeyStore.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: eQtlsInRepeatData.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example 3
Source File: TomatoLinearClassifierDemo.java    From COMP3204 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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;
}
 
Example 4
Source File: RandomUtilsTest.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 5
Source File: WalaCallgraphConstructor.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 6
Source File: Bee.java    From unleashed-pixel-dungeon with GNU General Public License v3.0 5 votes vote down vote up
@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 ;
	}
}
 
Example 7
Source File: CompositionalAnalysis.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
@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;
	}
 
Example 8
Source File: DynamicDispatch.java    From Rel with Apache License 2.0 5 votes vote down vote up
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.");
}
 
Example 9
Source File: NotificationDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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;
	}
}
 
Example 10
Source File: RecentFilesHandler.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/**
  * 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;
 }
 
Example 11
Source File: WeakCache.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
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);
	}
}
 
Example 12
Source File: Cheeses.java    From android-SwipeRefreshLayoutBasic with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source File: JavaDirectTalosStreamSuite.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 14
Source File: JsonToElasticsearchBulk.java    From metafacture-core with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 15
Source File: GatherSumApplyConfigurationITCase.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(HashSet<Long> newValue, HashSet<Long> currentValue) {
	newValue.addAll(currentValue);
	if (newValue.size() > currentValue.size()) {
		setResult(newValue);
	}
}
 
Example 16
Source File: MDAG.java    From MDAG with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 17
Source File: HashSetWrapper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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 );
}
 
Example 18
Source File: OutputColsHelper.java    From Alink with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Source File: SourceBuilder.java    From es6draft with MIT License 4 votes vote down vote up
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)";
    }
}
 
Example 20
Source File: ColumnTypeDetector.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
/**
 * 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]);
}