Java Code Examples for java.util.TreeSet#first()

The following examples show how to use java.util.TreeSet#first() . These examples are extracted from open source projects. 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 Project: xio   File: RendezvousHash.java    License: Apache License 2.0 6 votes vote down vote up
public List<T> get(byte[] key, int listSize) {
  Map<Long, T> hashMap = Maps.newTreeMap();
  List<T> nodes = new ArrayList<>(listSize);

  nodeList.forEach(
      node ->
          hashMap.put(
              hasher.newHasher().putBytes(key).putObject(node, nodeFunnel).hash().asLong(),
              node));

  TreeSet<Long> set = Sets.newTreeSet(hashMap.keySet());

  for (int i = 0; i < listSize; i++) {
    Long x = set.first();
    nodes.add(i, hashMap.remove(x));
    set.remove(x);
  }

  return nodes;
}
 
Example 2
@Test
public void testSimplifyDecision2() 
throws InvalidInputException, DecisionException, InvalidOperandException, InvalidTypeException {
    // true |- (A > 0) && (A <= 1)
    Term A = this.calc.valTerm(Type.INT, "A");
    Expression e = (Expression) this.calc.push(A).gt(this.calc.valInt(0)).pop();
    e = (Expression) this.calc.push(e).and(this.calc.push(A).le(this.calc.valInt(1)).pop()).pop();
    TreeSet<DecisionAlternative_IFX> d = new TreeSet<>(this.cmp.get(DecisionAlternative_IFX.class));
    this.dec.decide_IFX(e, d);

    //expected: {T_nonconcrete, F_nonconcrete}
    assertEquals(2, d.size());
    DecisionAlternative_IFX dai1 = d.first();
    d.remove(dai1);
    DecisionAlternative_IFX dai2 = d.first();
    assertFalse(dai1.concrete());
    assertFalse(dai2.concrete());
    assertThat(dai1, instanceOf(DecisionAlternative_IFX_True.class));
    assertThat(dai2, instanceOf(DecisionAlternative_IFX_False.class));
}
 
Example 3
Source Project: k8s-fleetman   File: DataBasicInMemoryImpl.java    License: MIT License 6 votes vote down vote up
private BigDecimal calculateSpeedInMph(String vehicleName, VehiclePosition newPosition)
{	
	TreeSet<VehiclePosition> positions = positionDatabase.get(vehicleName);
	if (positions.isEmpty()) return null;
	
	VehiclePosition posB = newPosition;
	VehiclePosition posA = positions.first(); // confusing - this is actually the last report recorded
	
	long timeAinMillis = posA.getTimestamp().getTime();
	long timeBinMillis = posB.getTimestamp().getTime();
	long timeInMillis = timeBinMillis - timeAinMillis;
	if (timeInMillis == 0) return new BigDecimal("0");
	
	BigDecimal timeInSeconds = new BigDecimal(timeInMillis / 1000.0);
			
	GlobalPosition pointA = new GlobalPosition(posA.getLat().doubleValue(), posA.getLongitude().doubleValue(), 0.0);
	GlobalPosition pointB = new GlobalPosition(posB.getLat().doubleValue(), posB.getLongitude().doubleValue(), 0.0);

	double distance = geoCalc.calculateGeodeticCurve(Ellipsoid.WGS84, pointA, pointB).getEllipsoidalDistance(); // Distance between Point A and Point B
	BigDecimal distanceInMetres = new BigDecimal (""+ distance);
	
	BigDecimal speedInMps = distanceInMetres.divide(timeInSeconds, RoundingMode.HALF_UP);
	BigDecimal milesPerHour = speedInMps.multiply(MPS_TO_MPH_FACTOR);
	return milesPerHour;
}
 
Example 4
@Test
public void testInsertDeletes() {
    final ByteIterable value = value("value");
    final TreeSet<String> keys = new TreeSet<>();
    tm = createMutableTree(false, 1);
    for (int i = 0; i < 10000; ++i) {
        final String key = rndString();
        if (keys.add(key)) {
            Assert.assertTrue(tm.add(key(key), value));
        }
        if (keys.size() > 1000) {
            final String obsoleteKey = keys.first();
            keys.remove(obsoleteKey);
            Assert.assertTrue(tm.delete(key(obsoleteKey)));
        }
    }
    testCursorOrder(keys);
}
 
Example 5
Source Project: fnlp   File: Chars.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 得到字符串类型
 * @param str
 * @return
 * @see Chars#char2StringType(CharType)
 */
public static StringType getStringType(String str) {
	TreeSet<CharType> set = getTypeSet(str);
	if(set.size()==1){
		CharType c = set.first();
		return char2StringType(c);
	}
	return StringType.M;		
}
 
Example 6
/**
 * Write out a {@link SequenceFile} that can be read by
 * {@link TotalOrderPartitioner} that contains the split points in startKeys.
 */
@SuppressWarnings("deprecation")
private static void writePartitions(Configuration conf, Path partitionsPath, List<ImmutableBytesWritable> startKeys)
        throws IOException {
    LOG.info("Writing partition information to " + partitionsPath);
    if (startKeys.isEmpty()) {
        throw new IllegalArgumentException("No regions passed");
    }

    // We're generating a list of split points, and we don't ever
    // have keys < the first region (which has an empty start key)
    // so we need to remove it. Otherwise we would end up with an
    // empty reducer with index 0
    TreeSet<ImmutableBytesWritable> sorted = new TreeSet<ImmutableBytesWritable>(startKeys);

    ImmutableBytesWritable first = sorted.first();
    if (!Arrays.equals(first.get(), HConstants.EMPTY_BYTE_ARRAY)) {
        throw new IllegalArgumentException("First region of table should have empty start key. Instead has: "
                + Bytes.toStringBinary(first.get()));
    }
    sorted.remove(first);

    // Write the actual file
    FileSystem fs = partitionsPath.getFileSystem(conf);
    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, partitionsPath, ImmutableBytesWritable.class,
            NullWritable.class);

    try {
        for (ImmutableBytesWritable startKey : sorted) {
            writer.append(startKey, NullWritable.get());
        }
    } finally {
        writer.close();
    }
}
 
Example 7
Source Project: ongdb-lab-apoc   File: IKArbitrator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 歧义识别
 * @param lexemeCell 歧义路径链表头
 * @param fullTextLength 歧义路径文本长度
 * @return
 */
private LexemePath judge(QuickSortSet.Cell lexemeCell, int fullTextLength) {
    //候选路径集合
    TreeSet<LexemePath> pathOptions = new TreeSet<LexemePath>();
    //候选结果路径
    LexemePath option = new LexemePath();

    //对crossPath进行一次遍历,同时返回本次遍历中有冲突的Lexeme栈
    Stack<QuickSortSet.Cell> lexemeStack = this.forwardPath(lexemeCell, option);

    //当前词元链并非最理想的,加入候选路径集合
    pathOptions.add(option.copy());

    //存在歧义词,处理
    QuickSortSet.Cell c = null;
    while (!lexemeStack.isEmpty()) {
        c = lexemeStack.pop();
        //回滚词元链
        this.backPath(c.getLexeme(), option);
        //从歧义词位置开始,递归,生成可选方案
        this.forwardPath(c, option);
        pathOptions.add(option.copy());
    }

    //返回集合中的最优方案
    return pathOptions.first();

}
 
Example 8
Source Project: JDeodorant   File: ExtractedConcept.java    License: MIT License 5 votes vote down vote up
public int compareTo(ExtractedConcept other) {
	TreeSet<ExtractClassCandidateRefactoring> thisSet = new TreeSet<ExtractClassCandidateRefactoring>(this.conceptClusters);
	TreeSet<ExtractClassCandidateRefactoring> otherSet = new TreeSet<ExtractClassCandidateRefactoring>(other.conceptClusters);
	ExtractClassCandidateRefactoring thisFirst = thisSet.first();
	ExtractClassCandidateRefactoring otherFirst = otherSet.first();
	return thisFirst.compareTo(otherFirst);
}
 
Example 9
Source Project: lucene-solr   File: ConcurrentLRUCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns 'n' number of oldest accessed entries present in this cache.
 *
 * This uses a TreeSet to collect the 'n' oldest items ordered by ascending last access time
 *  and returns a LinkedHashMap containing 'n' or less than 'n' entries.
 * @param n the number of oldest items needed
 * @return a LinkedHashMap containing 'n' or less than 'n' entries
 */
public Map<K, V> getOldestAccessedItems(int n) {
  Map<K, V> result = new LinkedHashMap<>();
  if (n <= 0)
    return result;
  TreeSet<CacheEntry<K,V>> tree = new TreeSet<>();
  markAndSweepLock.lock();
  try {
    for (Map.Entry<Object, CacheEntry<K,V>> entry : map.entrySet()) {
      CacheEntry<K,V> ce = entry.getValue();
      ce.lastAccessedCopy = ce.lastAccessed;
      if (tree.size() < n) {
        tree.add(ce);
      } else {
        if (ce.lastAccessedCopy < tree.first().lastAccessedCopy) {
          tree.remove(tree.first());
          tree.add(ce);
        }
      }
    }
  } finally {
    markAndSweepLock.unlock();
  }
  for (CacheEntry<K,V> e : tree) {
    result.put(e.key, e.value);
  }
  return result;
}
 
Example 10
Source Project: k8s-fleetman   File: DataBasicInMemoryImpl.java    License: MIT License 5 votes vote down vote up
@Override
public VehiclePosition getLatestPositionFor(String vehicleName) throws VehicleNotFoundException
{
	TreeSet<VehiclePosition> reportsForThisVehicle = positionDatabase.get(vehicleName);
	if (reportsForThisVehicle == null) throw new VehicleNotFoundException();
	return reportsForThisVehicle.first();
}
 
Example 11
/**
 * Returns either the next value, or the first value of the tree if the
 * given value is the last one of the tree.
 */
private static double nextValue(TreeSet<Double> tree, double value) {
	if (tree.higher(value) == null)
		return tree.first();
	else
		return tree.higher(value);
}
 
Example 12
Source Project: kylin   File: HFileOutputFormat3.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Write out a {@link SequenceFile} that can be read by
 * {@link TotalOrderPartitioner} that contains the split points in startKeys.
 */
@SuppressWarnings("deprecation")
private static void writePartitions(Configuration conf, Path partitionsPath, List<ImmutableBytesWritable> startKeys)
        throws IOException {
    LOG.info("Writing partition information to " + partitionsPath);
    if (startKeys.isEmpty()) {
        throw new IllegalArgumentException("No regions passed");
    }

    // We're generating a list of split points, and we don't ever
    // have keys < the first region (which has an empty start key)
    // so we need to remove it. Otherwise we would end up with an
    // empty reducer with index 0
    TreeSet<ImmutableBytesWritable> sorted = new TreeSet<ImmutableBytesWritable>(startKeys);

    ImmutableBytesWritable first = sorted.first();
    if (!Arrays.equals(first.get(), HConstants.EMPTY_BYTE_ARRAY)) {
        throw new IllegalArgumentException("First region of table should have empty start key. Instead has: "
                + Bytes.toStringBinary(first.get()));
    }
    sorted.remove(first);

    // Write the actual file
    FileSystem fs = partitionsPath.getFileSystem(conf);
    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, partitionsPath, ImmutableBytesWritable.class,
            NullWritable.class);

    try {
        for (ImmutableBytesWritable startKey : sorted) {
            writer.append(startKey, NullWritable.get());
        }
    } finally {
        writer.close();
    }
}
 
Example 13
Source Project: JAADAS   File: SetTestCode.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void concreteWriteReadNegativeTest(){
	String tainted = TelephonyManager.getDeviceId();
	TreeSet<String> notRelevantList = new TreeSet<String>();
	TreeSet<String> list = new TreeSet<String>();
	list.add("neutral");
	notRelevantList.add(tainted);
	String taintedElement = notRelevantList.first();
	String untaintedElement = list.first();
	taintedElement.toString();
	
	ConnectionManager cm = new ConnectionManager();
	cm.publish(untaintedElement);
}
 
Example 14
@Test
public void testProcessReportDetectNewAndMissingContainers() throws
    SCMException {
  Node2ContainerMap map = new Node2ContainerMap();
  UUID key = getFirstKey();
  TreeSet<ContainerID> values = testData.get(key);
  map.insertNewDatanode(key, values);

  Set<ContainerID> insertedSet = new TreeSet<>();
  // Insert nodes from 1..30
  for (int x = 1; x <= 30; x++) {
    insertedSet.add(new ContainerID(x));
  }


  final int removeCount = 100;
  Random r = new Random();

  ContainerID first = values.first();
  TreeSet<ContainerID> removedContainers = new TreeSet<>();

  // Pick a random container to remove it is ok to collide no issues.
  for (int x = 0; x < removeCount; x++) {
    int startBase = (int) first.getId();
    long cTemp = r.nextInt(values.size());
    removedContainers.add(new ContainerID(cTemp + startBase));
  }

  Set<ContainerID> newSet = new TreeSet<>(values);
  newSet.addAll(insertedSet);
  newSet.removeAll(removedContainers);

  ReportResult result = map.processReport(key, newSet);


  Assert.assertEquals(
          ReportResult.ReportStatus.MISSING_AND_NEW_ENTRIES_FOUND,
      result.getStatus());
  Assert.assertEquals(removedContainers.size(),
      result.getMissingEntries().size());


  // Assert that the Container IDs are the same as we added new.
  Assert.assertTrue("All missing containers not found.",
      result.getMissingEntries().removeAll(removedContainers));

  Assert.assertEquals(insertedSet.size(),
      result.getNewEntries().size());

  // Assert that the Container IDs are the same as we added new.
  Assert.assertTrue("All inserted containers are not found.",
      result.getNewEntries().removeAll(insertedSet));
}
 
Example 15
Source Project: wasindoor   File: MapLocator.java    License: Apache License 2.0 4 votes vote down vote up
public Location locate(Measurement currentMeasurement) {

		if (debug) {
			loadParameters();
		}

		Location loc = null;

		// get all measurement in database
		List<Measurement> list = measurementHome.getAll(mapId);
		/* check for similarity */
		TreeSet<Measurement> hits = new TreeSet<Measurement>(
				new MeasurementComparator(currentMeasurement));

		for (Measurement m : list) {
			int level = measurementSimilarityLevel(m, currentMeasurement);

			if (debug) {
				// debug
				Fingerprint fp = fingerprintHome.getByMeasurementId(m.getId());

				if (fp != null) {
					Location l = (Location) fp.getLocation();
					if (l != null) {
						log.log(Level.FINE, "location \""
								+ l.getMap().getMapName() + l.getSymbolicID()
								+ "\" achieved similarity level " + level);
					}
				}
				// end debug
			}

			if (level > LOCATION_THRESHOLD) {
				hits.add(m);
			}
		}

		if (hits.size() > 0) {

			Measurement bestMatch = hits.first();

			Fingerprint f = fingerprintHome.getByMeasurementId(bestMatch
					.getId());

			if (f != null) {
				loc = (Location) f.getLocation();
				loc.setAccuracy(measurementSimilarityLevel(bestMatch,
						currentMeasurement));

				if (debug) {
					log.log(Level.FINE, "Best match: \""
							+ loc.getMap().getMapName() + loc.getSymbolicID()
							+ "\" achieved similarity level "
							+ loc.getAccuracy());
				}
			}

		}

		return loc;
	}
 
Example 16
public CycleType getFirstOrderedCycleType() {
    final TreeSet<CycleType> ordered = getOrderedCycleTypes();
    return ordered.isEmpty() ? null : ordered.first();
}
 
Example 17
Source Project: jaamsim   File: MappedTreeSet.java    License: Apache License 2.0 4 votes vote down vote up
public V first(Object key) {
	TreeSet<V> subSet = subsetMap.get(key);
	if (subSet == null)
		return null;
	return subSet.first();
}
 
Example 18
Source Project: RefactoringMiner   File: UMLModelDiff.java    License: MIT License 4 votes vote down vote up
public void checkForMovedClasses(Map<String, String> renamedFileHints, Set<String> repositoryDirectories, UMLClassMatcher matcher) throws RefactoringMinerTimedOutException {
 for(Iterator<UMLClass> removedClassIterator = removedClasses.iterator(); removedClassIterator.hasNext();) {
  UMLClass removedClass = removedClassIterator.next();
  TreeSet<UMLClassMoveDiff> diffSet = new TreeSet<UMLClassMoveDiff>(new ClassMoveComparator());
  for(Iterator<UMLClass> addedClassIterator = addedClasses.iterator(); addedClassIterator.hasNext();) {
   UMLClass addedClass = addedClassIterator.next();
   String removedClassSourceFile = removedClass.getSourceFile();
   String renamedFile =  renamedFileHints.get(removedClassSourceFile);
   String removedClassSourceFolder = "";
   if(removedClassSourceFile.contains("/")) {
	   removedClassSourceFolder = removedClassSourceFile.substring(0, removedClassSourceFile.lastIndexOf("/"));
   }
   if(!repositoryDirectories.contains(removedClassSourceFolder)) {
	   deletedFolderPaths.add(removedClassSourceFolder);
	   //add deleted sub-directories
	   String subDirectory = new String(removedClassSourceFolder);
	   while(subDirectory.contains("/")) {
		   subDirectory = subDirectory.substring(0, subDirectory.lastIndexOf("/"));
		   if(!repositoryDirectories.contains(subDirectory)) {
			   deletedFolderPaths.add(subDirectory);
		   }
	   }
   }
   if(matcher.match(removedClass, addedClass, renamedFile)) {
	   if(!conflictingMoveOfTopLevelClass(removedClass, addedClass)) {
		   UMLClassMoveDiff classMoveDiff = new UMLClassMoveDiff(removedClass, addedClass, this);
		   diffSet.add(classMoveDiff);
	   }
   }
  }
  if(!diffSet.isEmpty()) {
   UMLClassMoveDiff minClassMoveDiff = diffSet.first();
   minClassMoveDiff.process();
   classMoveDiffList.add(minClassMoveDiff);
   addedClasses.remove(minClassMoveDiff.getMovedClass());
   removedClassIterator.remove();
  }
 }

 List<UMLClassMoveDiff> allClassMoves = new ArrayList<UMLClassMoveDiff>(this.classMoveDiffList);
 Collections.sort(allClassMoves);

 for(int i=0; i<allClassMoves.size(); i++) {
  UMLClassMoveDiff classMoveI = allClassMoves.get(i);
  for(int j=i+1; j<allClassMoves.size(); j++) {
   UMLClassMoveDiff classMoveJ = allClassMoves.get(j);
   if(classMoveI.isInnerClassMove(classMoveJ)) {
	   innerClassMoveDiffList.add(classMoveJ);
   }
  }
 }
 this.classMoveDiffList.removeAll(innerClassMoveDiffList);
}
 
Example 19
Source Project: steady   File: MavenCentralWrapper.java    License: Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public Artifact getArtifactForDigest(String _sha1) throws RepoException {
	Artifact doc = null;
	try {
		// URL and params
		final StringBuilder query = new StringBuilder();
		query.append("1:\"").append(_sha1).append("\"");
		final Map<String,String> params = new HashMap<String,String>();
		params.put("q", query.toString());
		params.put("rows", "50");
		params.put("wt", "json");
		params.put("core", "gav");

		// Make the query
		final RestTemplate rest_template = new RestTemplate();
		final MavenVersionsSearch search = rest_template.getForObject(baseUrl, MavenVersionsSearch.class, params);

		// Return results
		final TreeSet<ResponseDoc> versions = new TreeSet<ResponseDoc>();
		versions.addAll(search.getResponse().getDocs());

		if(versions.isEmpty()) {
			log.info("No artifact found for SHA1 [" + _sha1 + "] in Maven Central");
		}
		else if(versions.size()==1) {
			ResponseDoc d = versions.first();
			doc=new Artifact(d.getG(),d.getA(),d.getV());
			doc.setPackaging(d.getP());
			doc.setClassifier(d.getC());
			doc.setTimestamp(d.getTimestamp());
			doc.setProgrammingLanguage(ProgrammingLanguage.JAVA);
			log.info("Found artifact " + versions.first() + " for SHA1 [" + _sha1 + "]");
		}
		else {
			log.error("Found [" + versions.size() + "] artifacts for SHA1 [" + _sha1 + "], should be none or one only");
			throw new RepoException("Found [" + versions.size() + "] artifacts for SHA1 [" + _sha1 + "], should be none or one only");
		} 
	}
	catch(Exception e) {
		log.error("Error when searching for [" + _sha1 + "] in repo [" + baseUrl + "]: " + e.getMessage(), e);
		e.printStackTrace();
		throw new RepoException("Error when searching for [" + _sha1 + "] in repo [" + baseUrl + "]: " + e.getMessage(), e);
	}
	return doc;

}
 
Example 20
Source Project: netbeans   File: InputOutputCache.java    License: Apache License 2.0 4 votes vote down vote up
private static CachedInputOutput getInputOutput(String name, List<Action> actions) {
    CachedInputOutput result = null;

    TreeSet<CachedInputOutput> candidates = new TreeSet<>(CachedInputOutput.DISPLAY_NAME_COMPARATOR);

    synchronized (InputOutputCache.class) {
        for (Iterator<Entry<InputOutput, CachedInputOutput>> it = AVAILABLE.entrySet().iterator(); it.hasNext();) {
            Entry<InputOutput, CachedInputOutput> entry = it.next();

            final InputOutput free = entry.getKey();
            final CachedInputOutput data = entry.getValue();

            if (free.isClosed()) {
                it.remove();
                continue;
            }

            if (isAppropriateName(name, data.getDisplayName())) {
                List<Action> candidateActions = data.getActions();
                if (candidateActions.isEmpty() && (actions == null || actions.isEmpty())) {
                    candidates.add(data);
                } else if (actions != null && candidateActions.size() == actions.size()) {
                    boolean differs = false;
                    for (int i = 0; i < candidateActions.size(); i++) {
                        if (candidateActions.get(i).getClass() != actions.get(i).getClass()) {
                            differs = true;
                            break;
                        }
                    }
                    if (!differs) {
                        candidates.add(data);
                    }
                } // continue to remove all closed tabs
            }

            LOGGER.log(Level.FINEST, "Pooled: {0}", data.getDisplayName());
        }

        if (!candidates.isEmpty()) {
            result = candidates.first();
            AVAILABLE.remove(result.getInputOutput());
            ACTIVE_DISPLAY_NAMES.add(result.getDisplayName());
        }
    }
    return result;
}