下面列出了java.util.PriorityQueue#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Determine the k nearest neighbors for a test instance.
*
* @param testInstance
* The time series to determine the k nearest neighbors for.
* @return Queue of the k nearest neighbors as pairs (class, distance).
*/
protected PriorityQueue<Pair<Integer, Double>> calculateNearestNeigbors(final double[] testInstance) {
int numberOfTrainInstances = this.values.length;
// Priority queue of (class, distance)-pairs for nearest neigbors, sorted by
// distance ascending.
PriorityQueue<Pair<Integer, Double>> nearestNeighbors = new PriorityQueue<>(nearestNeighborComparator);
// Calculate the k nearest neighbors.
for (int i = 0; i < numberOfTrainInstances; i++) {
double d = this.distanceMeasure.distance(testInstance, this.values[i]);
Pair<Integer, Double> neighbor = new Pair<>(this.targets[i], d);
nearestNeighbors.add(neighbor);
if (nearestNeighbors.size() > this.k) {
nearestNeighbors.poll();
}
}
return nearestNeighbors;
}
private List<Recognition> getRecognition(final PriorityQueue<Recognition> priorityQueue) {
List<Recognition> recognitions = new ArrayList();
if (priorityQueue.size() > 0) {
// Best recognition
Recognition bestRecognition = priorityQueue.poll();
recognitions.add(bestRecognition);
for (int i = 0; i < Math.min(priorityQueue.size(), MAX_RESULTS); ++i) {
Recognition recognition = priorityQueue.poll();
boolean overlaps = false;
for (Recognition previousRecognition : recognitions) {
overlaps = overlaps || (getIntersectionProportion(previousRecognition.getLocation(),
recognition.getLocation()) > OVERLAP_THRESHOLD);
}
if (!overlaps) {
recognitions.add(recognition);
}
}
}
return recognitions;
}
/**
* java.util.PriorityQueue#PriorityQueue(Collection)
*/
public void test_ConstructorLjava_util_Colleciton_from_priorityqueue() {
String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
PriorityQueue<String> queue = new PriorityQueue<String>(4,
new MockComparatorStringByLength());
for (int i = 0; i < array.length; i++) {
queue.offer(array[i]);
}
Collection<String> c = queue;
PriorityQueue<String> constructedQueue = new PriorityQueue<String>(c);
assertEquals(queue.comparator(), constructedQueue.comparator());
while (queue.size() > 0) {
assertEquals(queue.poll(), constructedQueue.poll());
}
assertEquals(0, constructedQueue.size());
}
/**
* Get the top words under each topic given current Markov status.
*/
private ArrayList<PriorityQueue<Integer>> getTopWordsUnderEachTopicGivenCurrentMarkovStatus() {
ArrayList<PriorityQueue<Integer>> topWordIDList = new ArrayList<PriorityQueue<Integer>>();
int top_words = param.numberOfTopWordsUnderPriorTopicsForKnowledgeExtraction;
for (int t = 0; t < param.T; ++t) {
Comparator<Integer> comparator = new TopicalWordComparator(phi[t]);
PriorityQueue<Integer> pqueue = new PriorityQueue<Integer>(
top_words, comparator);
for (int w = 0; w < param.V; ++w) {
if (pqueue.size() < top_words) {
pqueue.add(w);
} else {
if (phi[t][w] > phi[t][pqueue.peek()]) {
pqueue.poll();
pqueue.add(w);
}
}
}
topWordIDList.add(pqueue);
}
return topWordIDList;
}
private PriorityQueue<IntermediateRecord> convertToIntermediateRecordsPQ(Map<Key, Record> recordsMap, int size,
Comparator<IntermediateRecord> comparator) {
PriorityQueue<IntermediateRecord> priorityQueue = new PriorityQueue<>(size, comparator);
for (Map.Entry<Key, Record> entry : recordsMap.entrySet()) {
IntermediateRecord intermediateRecord = getIntermediateRecord(entry.getKey(), entry.getValue());
if (priorityQueue.size() < size) {
priorityQueue.offer(intermediateRecord);
} else {
IntermediateRecord peek = priorityQueue.peek();
if (comparator.compare(peek, intermediateRecord) < 0) {
priorityQueue.poll();
priorityQueue.offer(intermediateRecord);
}
}
}
return priorityQueue;
}
private List<Recognition> getRecognition(final PriorityQueue<Recognition> priorityQueue) {
List<Recognition> recognitions = new ArrayList();
if (priorityQueue.size() > 0) {
// Best recognition
Recognition bestRecognition = priorityQueue.poll();
recognitions.add(bestRecognition);
for (int i = 0; i < Math.min(priorityQueue.size(), MAX_RESULTS); ++i) {
Recognition recognition = priorityQueue.poll();
boolean overlaps = false;
for (Recognition previousRecognition : recognitions) {
overlaps = overlaps || (getIntersectionProportion(previousRecognition.getLocation(),
recognition.getLocation()) > OVERLAP_THRESHOLD);
}
if (!overlaps) {
recognitions.add(recognition);
}
}
}
return recognitions;
}
private static void run(final AsyncServer server, final SelectorWrapper selector, final PriorityQueue<Scheduled> queue) {
// Log.i(LOGTAG, "****AsyncServer is starting.****");
// at this point, this local queue and selector are owned
// by this thread.
// if a stop is called, the instance queue and selector
// will be replaced and nulled respectively.
// this will allow the old queue and selector to shut down
// gracefully, while also allowing a new selector thread
// to start up while the old one is still shutting down.
while(true) {
try {
runLoop(server, selector, queue);
}
catch (AsyncSelectorException e) {
if (!(e.getCause() instanceof ClosedSelectorException))
Log.i(LOGTAG, "Selector exception, shutting down", e);
StreamUtility.closeQuietly(selector);
}
// see if we keep looping, this must be in a synchronized block since the queue is accessed.
synchronized (server) {
if (selector.isOpen() && (selector.keys().size() > 0 || queue.size() > 0))
continue;
shutdownEverything(selector);
if (server.mSelector == selector) {
server.mQueue = new PriorityQueue<Scheduled>(1, Scheduler.INSTANCE);
server.mSelector = null;
server.mAffinity = null;
}
break;
}
}
// Log.i(LOGTAG, "****AsyncServer has shut down.****");
}
private void addResultToPriorityQueue(
PriorityQueue<NodeInfo> topResults,
NodeInfo nodeInfo,
int maxNumResults) {
if (topResults.size() < maxNumResults) {
topResults.add(nodeInfo);
} else if (nodeInfo.getWeight() > topResults.peek().getWeight()) {
topResults.poll();
topResults.add(nodeInfo);
}
}
public int findKthLargest(int[] nums, int k) {
int len = nums.length;
// 最小堆
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k + 1, (a, b) -> (a - b));
for (int num : nums) {
priorityQueue.add(num);
if (priorityQueue.size() == k + 1) {
priorityQueue.poll();
}
}
return priorityQueue.peek();
}
private void testCustomAggregation(Double[] values, int n)
{
PriorityQueue<Double> heap = new PriorityQueue<>(n, (x, y) -> -Double.compare(x, y));
Arrays.stream(values).filter(x -> x != null).forEach(heap::add);
Double[] expected = new Double[heap.size()];
for (int i = heap.size() - 1; i >= 0; i--) {
expected[i] = heap.remove();
}
testAggregation(Arrays.asList(expected), createDoublesBlock(values), createLongRepeatBlock(n, values.length));
}
private static void run(final SocketServer server, final SelectorWrapper selector, final PriorityQueue<Scheduled> queue) {
log("****SocketServer is starting.****");
// at this point, this local queue and selector are owned by this thread.
// if a stop is called, the instance queue and selector
// will be replaced and nulled respectively.
// this will allow the old queue and selector to shut down
// gracefully, while also allowing a new selector thread
// to start up while the old one is still shutting down.
while (true) {
try {
runLoop(server, selector, queue);
} catch (AsyncSelectorException e) {
log("Selector exception, shutting down", e);
try {
// Util.closeQuiety is throwing ArrayStoreException?
selector.getSelector().close();
} catch (Exception ignore) {
}
}
// see if we keep looping, this must be in a synchronized block since the queue is accessed.
synchronized (server) {
if (selector.isOpen() && (selector.keys().size() > 0 || queue.size() > 0))
continue;
shutdownEverything(selector);
if (server.mSelector == selector) {
server.mQueue = new PriorityQueue<Scheduled>(1, Scheduler.INSTANCE);
server.mSelector = null;
server.serverThread = null;
}
break;
}
}
synchronized (servers) {
servers.remove(Thread.currentThread());
}
log("****SocketServer has shut down.****");
}
/**
* Add a neighborInfo to the priority queue when the queue is not full
* or the score of this neighborInfo is larger then the smallest score in the queue.
*
* @param topResults the priority queue
* @param neighborInfo the neighborInfo to be added
* @param maxNumResults the maximum capacity of the queue
*/
private void addResultToPriorityQueue(
PriorityQueue<NeighborInfo> topResults,
NeighborInfo neighborInfo,
int maxNumResults) {
if (topResults.size() < maxNumResults) {
topResults.add(neighborInfo);
} else if (neighborInfo.getScore() > topResults.peek().getScore()) {
topResults.poll();
topResults.add(neighborInfo);
}
}
/**
* Helper method to add a value to a {@link PriorityQueue}.
*
* @param value value to be added.
* @param queue priority queue.
* @param maxNumValues maximum number of values in the priority queue.
* @param <T> type for the value.
*/
public static <T> void addToPriorityQueue(T value, PriorityQueue<T> queue, int maxNumValues) {
if (queue.size() < maxNumValues) {
queue.add(value);
} else if (queue.comparator().compare(queue.peek(), value) < 0) {
queue.poll();
queue.offer(value);
}
}
/**
*
* @param vector
* @param n
* @return
* @throws IOException
*/
public List<SpaceResult> findFileSimilar(float[] vector, int n) throws IOException {
PriorityQueue<SpaceResult> queue = new PriorityQueue<>();
indexInput.seek(0);
String header = indexInput.readString(); //skip header
if ((header.equalsIgnoreCase("-dimensions"))) {
ObjectVector.vecLength = indexInput.readInt();
} else if (header.contains("-dimension")) {
int index = header.indexOf("-dimension");
ObjectVector.vecLength = Integer.parseInt(header.substring(index + 10).trim());
}
while (indexInput.getFilePointer() < indexInput.length()) {
String key = indexInput.readString();
float[] v = new float[ObjectVector.vecLength];
for (int k = 0; k < v.length; k++) {
v[k] = Float.intBitsToFloat(indexInput.readInt());
}
float score = VectorUtils.scalarProduct(vector, v);
if (queue.size() < n) {
queue.offer(new SpaceResult(key, score));
} else {
queue.poll();
queue.offer(new SpaceResult(key, score));
}
}
queue.poll();
List<SpaceResult> list = new ArrayList<>(queue);
Collections.sort(list);
return list;
}
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(stones.length, Collections.reverseOrder());
for (int stone : stones) {
heap.add(stone);
}
while (heap.size() > 1) {
int a = heap.poll(), b = heap.poll();
if (a != b) {
heap.add(a - b);
}
}
return heap.size() == 0 ? 0 : heap.poll();
}
public static void addResultToPriorityQueue(
PriorityQueue<NodeInfo> topResults,
NodeInfo nodeInfo,
int maxNumResults) {
if (topResults.size() < maxNumResults) {
topResults.add(nodeInfo);
} else if (nodeInfo.getWeight() > topResults.peek().getWeight()) {
topResults.poll();
topResults.add(nodeInfo);
}
}
public QueryTree (ParseTree T){
results = new ArrayList<ParseTree>();
PriorityQueue<ParseTree> Q = new PriorityQueue<ParseTree>();
Q.add(T);
HashMap<Integer, ParseTree> H = new HashMap<Integer, ParseTree>();
H.put(hashing(T), T);
T.setEdit(0);
while (Q.size() > 0){
ParseTree oriTree = Q.poll();
List<ParseTree> treeList = adjuster(oriTree);
double treeScore = evaluate(oriTree);
for (int i = 0; i < treeList.size(); i++){
ParseTree currentTree = treeList.get(i);
int hashValue = hashing(currentTree);
if (oriTree.getEdit()<10 && !H.containsKey(hashValue)){
H.put(hashValue, currentTree);
currentTree.setEdit(oriTree.getEdit()+1);
if (evaluate(currentTree) >= treeScore){
Q.add(currentTree);
results.add(currentTree);
}
}
}
}
}
/**
* Provide spelling corrections based on several parameters.
*
* @param term The term to suggest spelling corrections for
* @param numSug The maximum number of spelling corrections
* @param ir The index reader to fetch the candidate spelling corrections from
* @param docfreq The minimum document frequency a potential suggestion need to have in order to be included
* @param editDistance The maximum edit distance candidates are allowed to have
* @param accuracy The minimum accuracy a suggested spelling correction needs to have in order to be included
* @param spare a chars scratch
* @return a collection of spelling corrections sorted by <code>ScoreTerm</code>'s natural order.
* @throws IOException If I/O related errors occur
*/
protected Collection<ScoreTerm> suggestSimilar(Term term, int numSug, IndexReader ir, int docfreq, int editDistance,
float accuracy, final CharsRefBuilder spare) throws IOException {
Terms terms = MultiTerms.getTerms(ir, term.field());
if (terms == null) {
return Collections.emptyList();
}
FuzzyTermsEnum e = new FuzzyTermsEnum(terms, term, editDistance, Math.max(minPrefix, editDistance - 1), true);
final PriorityQueue<ScoreTerm> stQueue = new PriorityQueue<>();
BytesRef queryTerm = new BytesRef(term.text());
BytesRef candidateTerm;
ScoreTerm st = new ScoreTerm();
while ((candidateTerm = e.next()) != null) {
// For FuzzyQuery, boost is the score:
float score = e.getBoost();
// ignore uncompetitive hits
if (stQueue.size() >= numSug && score <= stQueue.peek().boost) {
continue;
}
// ignore exact match of the same term
if (queryTerm.bytesEquals(candidateTerm)) {
continue;
}
int df = e.docFreq();
// check docFreq if required
if (df <= docfreq) {
continue;
}
final String termAsString;
if (distance == INTERNAL_LEVENSHTEIN) {
// delay creating strings until the end
termAsString = null;
} else {
spare.copyUTF8Bytes(candidateTerm);
termAsString = spare.toString();
score = distance.getDistance(term.text(), termAsString);
}
if (score < accuracy) {
continue;
}
// add new entry in PQ
st.term = BytesRef.deepCopyOf(candidateTerm);
st.boost = score;
st.docfreq = df;
st.termAsString = termAsString;
st.score = score;
stQueue.offer(st);
// possibly drop entries from queue
st = (stQueue.size() > numSug) ? stQueue.poll() : new ScoreTerm();
e.setMaxNonCompetitiveBoost((stQueue.size() >= numSug) ? stQueue.peek().boost : Float.NEGATIVE_INFINITY);
}
return stQueue;
}
/**
* <p>
* We assume here that the passed-in inner LinkedHashMaps are already sorted
* in order of "Best Possible Correction".
* </p>
*/
public PossibilityIterator(
Map<Token,LinkedHashMap<String,Integer>> suggestions,
int maximumRequiredSuggestions, int maxEvaluations, boolean overlap) {
this.suggestionsMayOverlap = overlap;
for (Map.Entry<Token,LinkedHashMap<String,Integer>> entry : suggestions
.entrySet()) {
Token token = entry.getKey();
if (entry.getValue().size() == 0) {
continue;
}
List<SpellCheckCorrection> possibleCorrections = new ArrayList<>();
for (Map.Entry<String,Integer> entry1 : entry.getValue().entrySet()) {
SpellCheckCorrection correction = new SpellCheckCorrection();
correction.setOriginal(token);
correction.setCorrection(entry1.getKey());
correction.setNumberOfOccurences(entry1.getValue());
possibleCorrections.add(correction);
}
possibilityList.add(possibleCorrections);
}
int wrapSize = possibilityList.size();
if (wrapSize == 0) {
done = true;
} else {
correctionIndex = new int[wrapSize];
for (int i = 0; i < wrapSize; i++) {
int suggestSize = possibilityList.get(i).size();
if (suggestSize == 0) {
done = true;
break;
}
correctionIndex[i] = 0;
}
}
PriorityQueue<RankedSpellPossibility> rankedPossibilities = new PriorityQueue<>(
11, new RankComparator());
Set<RankedSpellPossibility> removeDuplicates = null;
if (suggestionsMayOverlap) {
removeDuplicates = new HashSet<>();
}
long numEvaluations = 0;
while (numEvaluations < maxEvaluations && internalHasNext()) {
RankedSpellPossibility rsp = internalNext();
numEvaluations++;
if (rankedPossibilities.size() >= maximumRequiredSuggestions
&& rsp.rank >= rankedPossibilities.peek().rank) {
continue;
}
if (!isSuggestionForReal(rsp)) {
continue;
}
if (removeDuplicates == null) {
rankedPossibilities.offer(rsp);
} else {
// Needs to be in token-offset order so that the match-and-replace
// option for collations can work.
Collections.sort(rsp.corrections, new StartOffsetComparator());
if (removeDuplicates.add(rsp)) {
rankedPossibilities.offer(rsp);
}
}
if (rankedPossibilities.size() > maximumRequiredSuggestions) {
RankedSpellPossibility removed = rankedPossibilities.poll();
if (removeDuplicates != null) {
removeDuplicates.remove(removed);
}
}
}
RankedSpellPossibility[] rpArr = new RankedSpellPossibility[rankedPossibilities
.size()];
for (int i = rankedPossibilities.size() - 1; i >= 0; i--) {
rpArr[i] = rankedPossibilities.remove();
}
rankedPossibilityIterator = Arrays.asList(rpArr).iterator();
}
public static void main(String[] args) throws Exception
{
System.out.println("BRouter 1.6.1 / 01032020");
if ( args.length != 5 && args.length != 6)
{
System.out.println("serve BRouter protocol");
System.out.println("usage: java RouteServer <segmentdir> <profiledir> <customprofiledir> <port> <maxthreads> [bindaddress]");
return;
}
ServiceContext serviceContext = new ServiceContext();
serviceContext.segmentDir = args[0];
serviceContext.profileDir = args[1];
System.setProperty( "profileBaseDir", serviceContext.profileDir );
String dirs = args[2];
StringTokenizer tk = new StringTokenizer( dirs, "," );
serviceContext.customProfileDir = tk.nextToken();
serviceContext.sharedProfileDir = tk.hasMoreTokens() ? tk.nextToken() : serviceContext.customProfileDir;
int maxthreads = Integer.parseInt( args[4] );
ProfileCache.setSize( 2*maxthreads );
PriorityQueue<RouteServer> threadQueue = new PriorityQueue<RouteServer>();
ServerSocket serverSocket = args.length > 5 ? new ServerSocket(Integer.parseInt(args[3]),100,InetAddress.getByName(args[5])) : new ServerSocket(Integer.parseInt(args[3]));
// stacksample for performance profiling
// ( caution: start stacksampler only after successfully creating the server socket
// because that thread prevents the process from terminating, so the start-attempt
// by the watchdog cron would create zombies )
File stackLog = new File( "stacks.txt" );
if ( stackLog.exists() )
{
StackSampler stackSampler = new StackSampler( stackLog, 1000 );
stackSampler.start();
System.out.println( "*** sampling stacks into stacks.txt *** ");
}
for (;;)
{
Socket clientSocket = serverSocket.accept();
RouteServer server = new RouteServer();
server.serviceContext = serviceContext;
server.clientSocket = clientSocket;
server.starttime = System.currentTimeMillis();
// kill an old thread if thread limit reached
cleanupThreadQueue( threadQueue );
if ( debug ) System.out.println( "threadQueue.size()=" + threadQueue.size() );
if ( threadQueue.size() >= maxthreads )
{
synchronized( threadPoolSync )
{
// wait up to 2000ms (maybe notified earlier)
// to prevent killing short-running threads
long maxage = server.starttime - threadQueue.peek().starttime;
long maxWaitTime = 2000L-maxage;
if ( debug ) System.out.println( "maxage=" + maxage + " maxWaitTime=" + maxWaitTime );
if ( debug )
{
for ( RouteServer t : threadQueue )
{
System.out.println( "age=" + (server.starttime - t.starttime) );
}
}
if ( maxWaitTime > 0 )
{
threadPoolSync.wait( maxWaitTime );
}
}
cleanupThreadQueue( threadQueue );
if ( threadQueue.size() >= maxthreads )
{
if ( debug ) System.out.println( "stopping oldest thread..." );
// no way... stop the oldest thread
threadQueue.poll().stopRouter();
}
}
threadQueue.add( server );
server.start();
if ( debug ) System.out.println( "thread started..." );
}
}