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

The following examples show how to use java.util.TreeSet#last() . 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: unitime   File: ExamVerificationReport.java    License: Apache License 2.0 6 votes vote down vote up
public String getMessage(Class_ clazz, boolean hasCourseExam, boolean hasSectionExam, Hashtable<Long,ClassEvent> class2event) {
    TreeSet<ExamAssignmentInfo> exams = getExams(clazz);
    if (!exams.isEmpty()) return "";
    String message = "** NO EXAM **";
    if (hasCourseExam && !hasSectionExam) message = ""; // Has other exam
    if (!hasSectionExam && !clazz.getSchedulingSubpart().getItype().isOrganized()) message = "Not organized instructional type";
    else {
        ClassEvent event = class2event.get(clazz.getUniqueId());
        if (event==null || event.getMeetings().isEmpty()) {
            message = "Class not organized";
        } else if (!isFullTerm(event)) {
            TreeSet meetings = new TreeSet(event.getMeetings());
            Meeting first = (Meeting)meetings.first();
            Meeting last = (Meeting)meetings.last();
            SimpleDateFormat df = new SimpleDateFormat("MM/dd");
            message = "Class not full-term ("+df.format(first.getMeetingDate())+(first.getMeetingDate().equals(last.getMeetingDate())?"":" - "+df.format(last.getMeetingDate()))+")";
        }
    }
    return message;
}
 
Example 2
Source Project: pumpernickel   File: BarChartRenderer.java    License: MIT License 6 votes vote down vote up
public DataRow(String groupLabel, Map<String, Long> data) {
	this.groupLabel = groupLabel;
	groupLabelRect = getTextSize(groupLabel);

	TreeSet<Long> sortedLongs = new TreeSet<>(data.values());
	maxValue = sortedLongs.last();
	Iterator<Long> iter = sortedLongs.descendingIterator();
	while (iter.hasNext()) {
		Long z = iter.next();
		for (Entry<String, Long> e : data.entrySet()) {
			if (e.getValue().equals(z)) {
				this.data.put(e.getKey(), e.getValue());
			}
		}
	}
}
 
Example 3
public AnimationData extractAnimation(){
	String rootNode = findRootJointName();
	TreeSet<Float> times = getKeyTimes();
	float duration = times.last();
	List<Float> keyTimes = new ArrayList<Float>(times);
	KeyFrameData[] keyFrames = initKeyFrames(keyTimes);
	List<XmlNode> animationNodes = animationData.getChildren("animation");
	for(XmlNode jointNode : animationNodes){
		if (jointNode.getChild("animation") != null){
			jointNode = jointNode.getChild("animation");
		}
		loadJointTransforms(keyTimes, keyFrames, jointNode, rootNode);
	}
	Log.i("AnimationLoader","Animation duration: "+duration+", key frames("+keyFrames.length+"):"+times);
	return new AnimationData(duration, keyFrames);
}
 
Example 4
Source Project: JDeodorant   File: PreconditionExaminer.java    License: MIT License 6 votes vote down vote up
private PDGNode findSwitchCaseAfter(TreeSet<PDGNode> allNodesInSubTreePDG, PDG pdg) {
	PDGNode last = allNodesInSubTreePDG.last();
	PDGNode switchCaseAfter = null;
	boolean nextSwitchCaseShouldBeReturned = false;
	for(GraphNode node : pdg.getNodes()) {
		PDGNode pdgNode = (PDGNode)node;
		if(pdgNode.getStatement().getType().equals(StatementType.SWITCH_CASE)) {
			switchCaseAfter = pdgNode;
			if(nextSwitchCaseShouldBeReturned) {
				return switchCaseAfter;
			}
		}
		if(pdgNode.equals(last)) {
			nextSwitchCaseShouldBeReturned = true;
		}
	}
	return null;
}
 
Example 5
/**
 * Verifies that jobId don't present on JobScheduler pending jobs. If jobId present on
 * JobScheduler pending jobs generates a new one.
 *
 * @param allPendingJobs List of current pending jobs.
 * @param jobId JobService id.
 * @return jobId if jobId don't present on JobScheduler pending jobs
 */
@TargetApi(21)
private static int verifyJobId(List<JobInfo> allPendingJobs, int jobId) {
  if (allPendingJobs != null && !allPendingJobs.isEmpty()) {
    TreeSet<Integer> idsSet = new TreeSet<>();
    for (JobInfo jobInfo : allPendingJobs) {
      idsSet.add(jobInfo.getId());
    }
    if (idsSet.contains(jobId)) {
      if (idsSet.first() > Integer.MIN_VALUE) {
        jobId = idsSet.first() - 1;
      } else if (idsSet.last() < Integer.MIN_VALUE) {
        jobId = idsSet.last() + 1;
      } else {
        while (idsSet.contains(jobId)) {
          jobId = new Random().nextInt();
        }
      }
    }
  }
  return jobId;
}
 
Example 6
Source Project: iceroot   File: IceUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * map连续键值为空补0
 * 
 * @param map 原始map
 * @return 转换后的map
 * @version 2.0.4
 */
public static Map<String, Long> dateListFillZero(Map<String, Long> map) {
    Map<String, Long> result = new LinkedHashMap<String, Long>();
    if (map == null || map.isEmpty()) {
        return result;
    }
    TreeSet<String> set = new TreeSet<String>(map.keySet());
    String first = set.first();
    String last = set.last();
    List<String> continuityDate = continuityDate(first, last);
    if (continuityDate == null || continuityDate.isEmpty()) {
        return result;
    }
    for (int i = 0; i < continuityDate.size(); i++) {
        String currentDate = continuityDate.get(i);
        Long value = map.get(currentDate);
        if (value == null) {
            result.put(currentDate, 0L);
        } else {
            result.put(currentDate, value);
        }
    }
    return result;
}
 
Example 7
Source Project: Word2Vec   File: Word2Vec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取相似词语
 * @param word
 * @param maxReturnNum
 * @return
 */
public Set<WordEntry> getSimilarWords(String word, int maxReturnNum) {
    if (loadModel == false)
        return null;
    float[] center = getWordVector(word);
    if (center == null) {
        return Collections.emptySet();
    }
    int resultSize = vec.getWords() < maxReturnNum ? vec.getWords() : maxReturnNum;
    TreeSet<WordEntry> result = new TreeSet<WordEntry>();
    double min = Double.MIN_VALUE;
    for (Map.Entry<String, float[]> entry : vec.getWordMap().entrySet()) {
        float[] vector = entry.getValue();
        float dist = calDist(center, vector);
        if (result.size() <= resultSize) {
            result.add(new WordEntry(entry.getKey(), dist));
            min = result.last().score;
        } else {
            if (dist > min) {
                result.add(new WordEntry(entry.getKey(), dist));
                result.pollLast();
                min = result.last().score;
            }
        }
    }
    result.pollFirst();
    return result;
}
 
Example 8
private List/* <LoadHolder> */findBestServers(Map groupServers,
    Set excludedServers, int count) {
  TreeSet bestEntries = new TreeSet(new Comparator() {
    public int compare(Object o1, Object o2) {
      LoadHolder l1 = (LoadHolder)o1;
      LoadHolder l2 = (LoadHolder)o2;
      int difference = Float.compare(l1.getLoad(), l2.getLoad());
      if (difference != 0) {
        return difference;
      }
      ServerLocation sl1 = l1.getLocation();
      ServerLocation sl2 = l2.getLocation();
      return sl1.compareTo(sl2);
    }
  });

  float lastBestLoad = Float.MAX_VALUE;
  for (Iterator itr = groupServers.entrySet().iterator(); itr.hasNext();) {
    Map.Entry next = (Entry)itr.next();
    ServerLocation location = (ServerLocation)next.getKey();
    if (excludedServers.contains(location)) {
      continue;
    }
    LoadHolder nextLoadReference = (LoadHolder)next.getValue();
    float nextLoad = nextLoadReference.getLoad();

    if (bestEntries.size() < count || count == -1 || nextLoad < lastBestLoad) {
      bestEntries.add(nextLoadReference);
      if (count != -1 && bestEntries.size() > count) {
        bestEntries.remove(bestEntries.last());
      }
      LoadHolder lastBestHolder = (LoadHolder)bestEntries.last();
      lastBestLoad = lastBestHolder.getLoad();
    }
  }

  return new ArrayList(bestEntries);
}
 
Example 9
public ClassificationResult classify(IIndex testIndex, int docID) {
    ClassificationResult res = new ClassificationResult();
    res.documentID = docID;

    TreeSet<SingleClassificationResult> leafResults = new TreeSet<TreeRecommenderClassifier.SingleClassificationResult>();
    hierarchicallyClassification(Short.MIN_VALUE, testIndex, docID, 1, leafResults);

    int filled = 0;
    int numAutomaticallyAssigned = 0;
    SingleClassificationResult crBest = leafResults.last();
    while (filled < atLeastResults && leafResults.size() > 0) {
        SingleClassificationResult cr = leafResults.last();
        leafResults.remove(leafResults.last());
        res.categoryID.add(cr.catID);
        res.score.add(cr.score);
        if (cr.score >= cr.range.border) {
            numAutomaticallyAssigned++;
        }

        filled++;
    }

    if (atLeastOne && numAutomaticallyAssigned == 0) {
        // Force at least one category.
        res.score.set(0, crBest.range.border + 0.1);
    }

    return res;
}
 
Example 10
private List/* <LoadHolder> */findBestServers(Map groupServers,
    Set excludedServers, int count) {
  TreeSet bestEntries = new TreeSet(new Comparator() {
    public int compare(Object o1, Object o2) {
      LoadHolder l1 = (LoadHolder)o1;
      LoadHolder l2 = (LoadHolder)o2;
      int difference = Float.compare(l1.getLoad(), l2.getLoad());
      if (difference != 0) {
        return difference;
      }
      ServerLocation sl1 = l1.getLocation();
      ServerLocation sl2 = l2.getLocation();
      return sl1.compareTo(sl2);
    }
  });

  float lastBestLoad = Float.MAX_VALUE;
  for (Iterator itr = groupServers.entrySet().iterator(); itr.hasNext();) {
    Map.Entry next = (Entry)itr.next();
    ServerLocation location = (ServerLocation)next.getKey();
    if (excludedServers.contains(location)) {
      continue;
    }
    LoadHolder nextLoadReference = (LoadHolder)next.getValue();
    float nextLoad = nextLoadReference.getLoad();

    if (bestEntries.size() < count || count == -1 || nextLoad < lastBestLoad) {
      bestEntries.add(nextLoadReference);
      if (count != -1 && bestEntries.size() > count) {
        bestEntries.remove(bestEntries.last());
      }
      LoadHolder lastBestHolder = (LoadHolder)bestEntries.last();
      lastBestLoad = lastBestHolder.getLoad();
    }
  }

  return new ArrayList(bestEntries);
}
 
Example 11
Source Project: Word2Vec   File: Word2VEC.java    License: Apache License 2.0 5 votes vote down vote up
public Set<WordEntry> distance(List<String> words) {

		float[] center = null;
		for (String word : words) {
			center = sum(center, wordMap.get(word));
		}

		if (center == null) {
			return Collections.emptySet();
		}

		int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize;
		TreeSet<WordEntry> result = new TreeSet<WordEntry>();

		double min = Float.MIN_VALUE;
		for (Map.Entry<String, float[]> entry : wordMap.entrySet()) {
			float[] vector = entry.getValue();
			float dist = 0;
			for (int i = 0; i < vector.length; i++) {
				dist += center[i] * vector[i];
			}

			if (dist > min) {
				result.add(new WordEntry(entry.getKey(), dist));
				if (resultSize < result.size()) {
					result.pollLast();
				}
				min = result.last().score;
			}
		}
		result.pollFirst();

		return result;
	}
 
Example 12
public Set<WordEntry> distance(String queryWord) {

		float[] center = wordMap.get(queryWord);
		if (center == null) {
			return Collections.emptySet();
		}

		int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize;
		TreeSet<WordEntry> result = new TreeSet<WordEntry>();

		double min = Float.MIN_VALUE;
		for (Entry<String, float[]> entry : wordMap.entrySet()) {
			float[] vector = entry.getValue();
			float dist = 0;
			for (int i = 0; i < vector.length; i++) {
				dist += center[i] * vector[i];
			}

			if (dist > min) {
				result.add(new WordEntry(entry.getKey(), dist));
				if (resultSize < result.size()) {
					result.pollLast();
				}
				min = result.last().score;
			}
		}
		result.pollFirst();

		return result;
	}
 
Example 13
/**
   * This method tests if the generator for new Annotation IDs is greather than the
   * maximum Annotation ID present in the GATE document. In oter words, it ensures that
   * new Annotations will receive an UNIQUE ID.
   *
   * @param aDoc The GATE document being tested
   */
  protected void verifyAnnotationIDGenerator(gate.Document aDoc){
    // Creates a MAP containing all the annotations of the document.
    // In doing so, it also tests if there are annotations with the same ID.
    Map<Integer,Annotation> id2AnnotationMap = buildID2AnnotMap(aDoc);

    if (id2AnnotationMap == null || id2AnnotationMap.isEmpty()){
      //System.out.println("No annotations found on the document! Nothing to test.");
      return;
    }

    // Get the key set of the Map and sort them
    Set<Integer> keysSet = id2AnnotationMap.keySet();
    TreeSet<Integer> sortedSet = new TreeSet<Integer>(keysSet);
    // Get the highest Annotation ID
    Integer maxAnnotId =  sortedSet.last();
    // Compare its value to the one hold by the document's ID generator
    Integer generatorId = ((DocumentImpl)aDoc).getNextAnnotationId();

//    System.out.println("maxAnnotid = " + maxAnnotId + " generatorID = " + generatorId);

    assertTrue("Annotation ID generator["+generatorId+"] on document [" + aDoc.getSourceUrl() +
            "] was equal or less than the MAX Annotation ID["+maxAnnotId+"] on the document."+
            " This may lead to Annotation ID conflicts.", generatorId.intValue() > maxAnnotId.intValue());


  }
 
Example 14
public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults,
    ParameterSet parameters) throws IOException {

  Range<Double> toleranceRange = mzTolerance.getToleranceRange(mass);

  String queryAddress = ymdbSearchAddress + "query_from=" + toleranceRange.lowerEndpoint()
      + "&query_to=" + toleranceRange.upperEndpoint();

  URL queryURL = new URL(queryAddress);

  // Submit the query
  logger.finest("Querying YMDB URL " + queryURL);
  String queryResult = InetUtils.retrieveData(queryURL);

  // Organize the IDs as a TreeSet to keep them sorted
  TreeSet<String> results = new TreeSet<String>();

  // Find IDs in the HTML data
  Pattern pat = Pattern.compile("/compounds/(YMDB[0-9]{5})");
  Matcher matcher = pat.matcher(queryResult);
  while (matcher.find()) {
    String ymdbID = matcher.group(1);
    results.add(ymdbID);
  }

  // Remove all except first numOfResults IDs. The reason why we first
  // retrieve all results and then remove those above numOfResults is to
  // keep the lowest YDMB IDs - these may be the most interesting ones.
  while (results.size() > numOfResults) {
    String lastItem = results.last();
    results.remove(lastItem);
  }

  return results.toArray(new String[0]);

}
 
Example 15
Source Project: lucene-solr   File: ConcurrentLRUCache.java    License: Apache License 2.0 5 votes vote down vote up
public Map<K,V> getLatestAccessedItems(int n) {
  Map<K,V> result = new LinkedHashMap<>();
  if (n <= 0)
    return result;
  TreeSet<CacheEntry<K,V>> tree = new TreeSet<>();
  // we need to grab the lock since we are changing lastAccessedCopy
  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.last().lastAccessedCopy) {
          tree.remove(tree.last());
          tree.add(ce);
        }
      }
    }
  } finally {
    markAndSweepLock.unlock();
  }
  for (CacheEntry<K,V> e : tree) {
    result.put(e.key, e.value);
  }
  return result;
}
 
Example 16
final public Enrolment getLatestDissertationEnrolment() {
    final TreeSet<Enrolment> result = new TreeSet<Enrolment>(Enrolment.COMPARATOR_BY_EXECUTION_PERIOD_AND_ID);
    result.addAll(getDissertationEnrolments());
    return result.isEmpty() ? null : result.last();
}
 
Example 17
Source Project: gemfirexd-oss   File: BucketRegionQueue.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void initialize(InputStream snapshotInputStream,
    InternalDistributedMember imageTarget,
    InternalRegionArguments internalRegionArgs) throws TimeoutException,
    IOException, ClassNotFoundException {

  super.initialize(snapshotInputStream, imageTarget, internalRegionArgs);

  //take initialization writeLock inside the method after synchronizing on tempQueue
  loadEventsFromTempQueue();
  
  getInitializationLock().writeLock().lock();
  try {
    if (!this.keySet().isEmpty()) {
      if (getPartitionedRegion().getColocatedWith() == null) {
        List<EventID> keys = new ArrayList<EventID>(this.keySet());
        Collections.sort(keys, new Comparator<EventID>() {
          @Override
          public int compare(EventID o1, EventID o2) {
            int compareMem = new ByteComparator().compare(
                o1.getMembershipID(), o2.getMembershipID());
            if (compareMem == 1) {
              return 1;
            } else if (compareMem == -1) {
              return -1;
            } else {
              if (o1.getThreadID() > o2.getThreadID()) {
                return 1;
              } else if (o1.getThreadID() < o2.getThreadID()) {
                return -1;
              } else {
                return o1.getSequenceID() < o2.getSequenceID() ? -1 : o1
                    .getSequenceID() == o2.getSequenceID() ? 0 : 1;
              }
            }
          }
        });
        for (EventID eventID : keys) {
          eventSeqNumQueue.add(eventID);
        }
      } else {
        TreeSet<Long> sortedKeys = new TreeSet<Long>(this.keySet());
        //although the empty check for this.keySet() is done above, 
        //do the same for sortedKeys as well because the keySet() might have become 
        //empty since the above check was made (keys might have been destroyed through BatchRemoval)
        //fix for #49679 NoSuchElementException thrown from BucketRegionQueue.initialize
        if (!sortedKeys.isEmpty()) {
          for (Long key : sortedKeys) {
            eventSeqNumQueue.add(key);
          }
          lastKeyRecovered = sortedKeys.last();
          if (this.getEventSeqNum() != null) {
            getEventSeqNum().setIfGreater(lastKeyRecovered);
          }
        }
      }

      if (getLogWriterI18n().fineEnabled()) {
        getLogWriterI18n().fine(
            "For bucket " + getId() + " ,total keys recovered are : "
                + eventSeqNumQueue.size() + " last key recovered is : "
                + lastKeyRecovered + " and the seqNo is " + getEventSeqNum());
      }
    }
    this.initialized = true;
  }
  finally {
    notifyEventProcessor();
    getInitializationLock().writeLock().unlock();
  }
}
 
Example 18
/**
 * 欠けているカラム番号がある場合、その番号を持つダミーのカラムを追加する。
 * @param beanType Beanタイプ
 * @param list カラム情報の一覧
 * @param partialAnno Beanに設定されているアノテーション{@link CsvPartial}の情報。
 * @param suppliedHeaders 提供されたヘッダー。提供されてない場合は、長さ0の配列。
 * @return
 */
public static TreeSet<Integer> supplyLackedNumberMappingColumn(final Class<?> beanType, final List<ColumnMapping> list,
        final Optional<CsvPartial> partialAnno, final String[] suppliedHeaders) {
    
    final TreeSet<Integer> checkedNumber = list.stream()
            .filter(col -> col.isDeterminedNumber())
            .map(col -> col.getNumber())
            .collect(Collectors.toCollection(TreeSet::new));
    
    // 定義されている列番号の最大値
    final int maxColumnNumber = checkedNumber.last();
    
    // Beanに定義されていない欠けているカラム番号の取得
    final TreeSet<Integer> lackedNumbers = new TreeSet<Integer>();
    for(int i=1; i <= maxColumnNumber; i++) {
        if(!checkedNumber.contains(i)) {
            lackedNumbers.add(i);
        }
    }
    
    // 定義されているカラム番号より、大きなカラム番号を持つカラム情報の補足
    if(partialAnno.isPresent()) {
        
        final int partialColumnSize = partialAnno.get().columnSize();
        if(maxColumnNumber > partialColumnSize) {
            throw new SuperCsvInvalidAnnotationException(partialAnno.get(), MessageBuilder.create("anno.CsvPartial.columSizeMin")
                    .var("property", beanType.getName())
                    .var("columnSize", partialColumnSize)
                    .var("maxColumnNumber", maxColumnNumber)
                    .format());
            
        }
        
        if(maxColumnNumber < partialColumnSize) {
            for(int i= maxColumnNumber+1; i <= partialColumnSize; i++) {
                lackedNumbers.add(i);
            }
        }
        
    }
    
    // 不足分のカラムがある場合は、部分的な読み書き用カラムとして追加する
    if(lackedNumbers.size() > 0) {
        
        for(int number : lackedNumbers) {
            list.add(createPartialColumnMapping(number, partialAnno, getSuppliedHeaders(suppliedHeaders, number)));
        }
        
        list.sort(null);
    }
    
    return lackedNumbers;
    
}
 
Example 19
Source Project: jaamsim   File: MappedTreeSet.java    License: Apache License 2.0 4 votes vote down vote up
public V last(Object key) {
	TreeSet<V> subSet = subsetMap.get(key);
	if (subSet == null)
		return null;
	return subSet.last();
}
 
Example 20
private Integer mapGet(T value) {
  TreeSet<Integer> set = map.get(value);
  if (set != null) return set.last();
  return null;
}