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

The following examples show how to use java.util.ArrayDeque#size() . 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
/**
 * Converts a list of checkpoints into an array of SerializedCheckpointData.
 *
 * @param checkpoints The checkpoints to be converted into IdsCheckpointData.
 * @param serializer The serializer to serialize the IDs.
 * @param outputBuffer The reusable serialization buffer.
 * @param <T> The type of the ID.
 * @return An array of serializable SerializedCheckpointData, one per entry in the queue.
 *
 * @throws IOException Thrown, if the serialization fails.
 */
public static <T> SerializedCheckpointData[] fromDeque(
		ArrayDeque<Tuple2<Long, Set<T>>> checkpoints,
		TypeSerializer<T> serializer,
		DataOutputSerializer outputBuffer) throws IOException {

	SerializedCheckpointData[] serializedCheckpoints = new SerializedCheckpointData[checkpoints.size()];

	int pos = 0;
	for (Tuple2<Long, Set<T>> checkpoint : checkpoints) {
		outputBuffer.clear();
		Set<T> checkpointIds = checkpoint.f1;

		for (T id : checkpointIds) {
			serializer.serialize(id, outputBuffer);
		}

		serializedCheckpoints[pos++] = new SerializedCheckpointData(
				checkpoint.f0, outputBuffer.getCopyOfBuffer(), checkpointIds.size());
	}

	return serializedCheckpoints;
}
 
Example 2
/**
 * Build an array containing the hierarchy from the root down to this destination.
 *
 * @return An array containing all of the ids from the root to this destination
 */
@NonNull
int[] buildDeepLinkIds() {
    ArrayDeque<NavDestination> hierarchy = new ArrayDeque<>();
    NavDestination current = this;
    do {
        NavGraph parent = current.getParent();
        if (parent == null || parent.getStartDestination() != current.getId()) {
            hierarchy.addFirst(current);
        }
        current = parent;
    } while (current != null);
    int[] deepLinkIds = new int[hierarchy.size()];
    int index = 0;
    for (NavDestination destination : hierarchy) {
        deepLinkIds[index++] = destination.getId();
    }
    return deepLinkIds;
}
 
Example 3
Source Project: flink   File: SerializedCheckpointData.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a list of checkpoints into an array of SerializedCheckpointData.
 *
 * @param checkpoints The checkpoints to be converted into IdsCheckpointData.
 * @param serializer The serializer to serialize the IDs.
 * @param outputBuffer The reusable serialization buffer.
 * @param <T> The type of the ID.
 * @return An array of serializable SerializedCheckpointData, one per entry in the queue.
 *
 * @throws IOException Thrown, if the serialization fails.
 */
public static <T> SerializedCheckpointData[] fromDeque(
		ArrayDeque<Tuple2<Long, Set<T>>> checkpoints,
		TypeSerializer<T> serializer,
		DataOutputSerializer outputBuffer) throws IOException {

	SerializedCheckpointData[] serializedCheckpoints = new SerializedCheckpointData[checkpoints.size()];

	int pos = 0;
	for (Tuple2<Long, Set<T>> checkpoint : checkpoints) {
		outputBuffer.clear();
		Set<T> checkpointIds = checkpoint.f1;

		for (T id : checkpointIds) {
			serializer.serialize(id, outputBuffer);
		}

		serializedCheckpoints[pos++] = new SerializedCheckpointData(
				checkpoint.f0, outputBuffer.getCopyOfBuffer(), checkpointIds.size());
	}

	return serializedCheckpoints;
}
 
Example 4
Source Project: flink   File: SerializedCheckpointData.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a list of checkpoints into an array of SerializedCheckpointData.
 *
 * @param checkpoints The checkpoints to be converted into IdsCheckpointData.
 * @param serializer The serializer to serialize the IDs.
 * @param outputBuffer The reusable serialization buffer.
 * @param <T> The type of the ID.
 * @return An array of serializable SerializedCheckpointData, one per entry in the queue.
 *
 * @throws IOException Thrown, if the serialization fails.
 */
public static <T> SerializedCheckpointData[] fromDeque(
		ArrayDeque<Tuple2<Long, Set<T>>> checkpoints,
		TypeSerializer<T> serializer,
		DataOutputSerializer outputBuffer) throws IOException {

	SerializedCheckpointData[] serializedCheckpoints = new SerializedCheckpointData[checkpoints.size()];

	int pos = 0;
	for (Tuple2<Long, Set<T>> checkpoint : checkpoints) {
		outputBuffer.clear();
		Set<T> checkpointIds = checkpoint.f1;

		for (T id : checkpointIds) {
			serializer.serialize(id, outputBuffer);
		}

		serializedCheckpoints[pos++] = new SerializedCheckpointData(
				checkpoint.f0, outputBuffer.getCopyOfBuffer(), checkpointIds.size());
	}

	return serializedCheckpoints;
}
 
Example 5
Source Project: jlibs   File: XPathParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void endFunction() throws SAXPathException{
    ArrayDeque params = popFrame();
    javax.xml.namespace.QName name = (javax.xml.namespace.QName)params.pollFirst();
    if(name.getNamespaceURI().length()==0)
        push(createFunction(name.getLocalPart(), params).simplify());
    else{
        int noOfParams = params.size();
        XPathFunction function = functionResolver.resolveFunction(name, noOfParams);
        if(function==null)
            throw new SAXPathException("Unknown Function: "+name);
        FunctionCall functionCall = new FunctionCall(new Functions.UserFunction(name.getNamespaceURI(), name.getLocalPart(), function), noOfParams);
        for(int i=0; i<noOfParams; i++)
            functionCall.addMember(params.pollFirst(), i);
        push(functionCall);
    }
}
 
Example 6
Source Project: j2objc   File: ArrayDequeTest.java    License: Apache License 2.0 5 votes vote down vote up
void checkToArray2(ArrayDeque q) {
    int size = q.size();
    Integer[] a1 = (size == 0) ? null : new Integer[size - 1];
    Integer[] a2 = new Integer[size];
    Integer[] a3 = new Integer[size + 2];
    if (size > 0) Arrays.fill(a1, 42);
    Arrays.fill(a2, 42);
    Arrays.fill(a3, 42);
    Integer[] b1 = (size == 0) ? null : (Integer[]) q.toArray(a1);
    Integer[] b2 = (Integer[]) q.toArray(a2);
    Integer[] b3 = (Integer[]) q.toArray(a3);
    assertSame(a2, b2);
    assertSame(a3, b3);
    Iterator it = q.iterator();
    for (int i = 0; i < size; i++) {
        Integer x = (Integer) it.next();
        assertSame(b1[i], x);
        assertEquals(b1[0] + i, (int) x);
        assertSame(b2[i], x);
        assertSame(b3[i], x);
    }
    assertNull(a3[size]);
    assertEquals(42, (int) a3[size + 1]);
    if (size > 0) {
        assertNotSame(a1, b1);
        assertEquals(size, b1.length);
        for (int i = 0; i < a1.length; i++) {
            assertEquals(42, (int) a1[i]);
        }
    }
}
 
Example 7
private void addCompounds(final ArrayDeque<Term> terms, final boolean reverse) throws IOException {

        final CombineSuggestion[] combinations = suggestCombination(reverse
                ? terms.descendingIterator() : terms.iterator());

        if (combinations != null && combinations.length > 0) {

            final Term[] termArray;
            if (reverse) {
                termArray = new Term[terms.size()];
                int i = terms.size() - 1;
                final Iterator<Term> termIterator = terms.descendingIterator();
                while (termIterator.hasNext()) {
                    termArray[i--] = termIterator.next();
                }
            } else {
                termArray = terms.toArray(new Term[0]);
            }

            for (final CombineSuggestion suggestion : combinations) {
                // add compound to each sibling that is part of the compound to maintain mm logic
                Arrays.stream(suggestion.originalTermIndexes)
                        .mapToObj(idx -> termArray[idx])
                        .forEach(sibling -> nodesToAdd.add(
                                new Term(sibling.getParent(), sibling.getField(), suggestion.suggestion.string, true)));

            }

        }

    }
 
Example 8
@Override
public void free() //NOTE: DO NOT double free
{
	ArrayDeque<CachedBuffer> pool = (buf.isDirect() ? directBuffers : heapBuffers).get()[getIdx(buf.capacity())];
	if (pool.size() < maxPoolSize)
	{
		pool.addFirst(this);
		freeCount.getAndIncrement();
	}
}
 
Example 9
Source Project: trufflesqueak   File: ObjectGraphUtils.java    License: MIT License 5 votes vote down vote up
@TruffleBoundary
public static AbstractCollection<AbstractSqueakObjectWithHash> allInstances(final SqueakImageContext image) {
    final ArrayDeque<AbstractSqueakObjectWithHash> seen = new ArrayDeque<>(lastSeenObjects + ADDITIONAL_SPACE);
    final ObjectTracer pending = new ObjectTracer(image);
    AbstractSqueakObjectWithHash currentObject;
    while ((currentObject = pending.getNextPending()) != null) {
        if (currentObject.tryToMark(pending.getCurrentMarkingFlag())) {
            seen.add(currentObject);
            pending.tracePointers(currentObject);
        }
    }
    lastSeenObjects = seen.size();
    return seen;
}
 
Example 10
public int getQueueSize() {
    int size = pending.size();
    for (ArrayDeque<TaskHandler> queue : queueMap.values()) {
        size += queue.size();
    }
    return size;
}
 
Example 11
Source Project: pravega   File: BlockingDrainingQueue.java    License: Apache License 2.0 5 votes vote down vote up
@GuardedBy("contents")
private Queue<T> fetch(int maxCount) {
    int count = Math.min(maxCount, this.contents.size());
    ArrayDeque<T> result = new ArrayDeque<>(count);
    while (result.size() < count) {
        result.addLast(this.contents.pollFirst());
    }

    return result;
}
 
Example 12
public int getQueueSize() {
    int size = pending.size();
    for (ArrayDeque<TaskHandler> queue : queueMap.values()) {
        size += queue.size();
    }
    return size;
}
 
Example 13
@Override
public void onNext(T t) {
    ArrayDeque<T> bs = buffer;

    if (bs.size() == n) {
        bs.poll();
    }
    bs.offer(t);
}
 
Example 14
Source Project: j2objc   File: ArrayDequeTest.java    License: Apache License 2.0 5 votes vote down vote up
void checkToArray(ArrayDeque q) {
    int size = q.size();
    Object[] o = q.toArray();
    assertEquals(size, o.length);
    Iterator it = q.iterator();
    for (int i = 0; i < size; i++) {
        Integer x = (Integer) it.next();
        assertEquals((Integer)o[0] + i, (int) x);
        assertSame(o[i], x);
    }
}
 
Example 15
Source Project: pnc   File: DefaultFileTranser.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public StringBuffer downloadFileToStringBuilder(StringBuffer logsAggregate, URI uri) throws TransferException {
    try {
        logger.debug("Downloading file to String Buffer from {}", uri);

        ArrayDeque<String> logLines = new ArrayDeque<>();

        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);

        Consumer<String> removedLines = (removedLine) -> {
            fullyDownloaded = false;
            logger.debug("Dropped log line from URI {}: {}.", uri, removedLine);
        };

        try (InputStream inputStream = connection.getInputStream()) {
            Charset charset = Charset.forName(ENCODING);
            StringUtils.readStream(inputStream, charset, logLines, maxDownloadSize, removedLines);
        }

        logsAggregate.append("==== ").append(uri.toString()).append(" ====\n");
        while (true) {
            String line = logLines.pollFirst();
            if (line == null) {
                break;
            }
            logsAggregate.append(line + "\n");
        }
        if (logLines.size() > 0) {
            logger.warn("Log buffer was not fully drained for URI: {}", uri);
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Downloaded log: {}.", logsAggregate);
        }
        return logsAggregate;
    } catch (IOException e) {
        throw new TransferException("Could not obtain log file: " + uri.toString(), e);
    }
}
 
Example 16
Source Project: doov   File: AstJavascriptVisitor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This function manage the different parameters of the predicate
 *
 * @param stack A deque of the predicate parameters
 */
private void manageStack(ArrayDeque<Element> stack) {
    while (stack.size() > 0) {
        Element e = stack.pollFirst();
        switch (e.getType()) {
            case FIELD:
                write(e.toString());
                break;
            case OPERATOR:
                manageOperator((DefaultOperator) e.getReadable(), stack);
                break;
            case VALUE:
                if (StringUtils.isNumeric(e.toString())) {
                    write(e.toString());
                } else {
                    write("\'" + e.toString() + "\'");
                }
                break;
            case STRING_VALUE:
                if (use_regexp == 1) {
                    String tmp = e.toString();
                    if (is_match == 1) {
                        is_match = 0;
                    } else {
                        tmp = formatRegexp(tmp);
                    }
                    write(tmp);
                    if (start_with_count > 0) {
                        write(".*");
                        start_with_count--;
                    } else if (end_with_count > 0) {
                        write("$");
                        end_with_count--;
                    }
                    write("/");
                    use_regexp = 0;
                } else {
                    write("\'" + e.toString() + "\'");
                }
                break;
            case PARENTHESIS_LEFT:
            case PARENTHESIS_RIGHT:
            case UNKNOWN:
            default:
                break;
        }
    }
}
 
Example 17
Source Project: VanetSim   File: Vehicle.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Instantiates a new vehicle. You will get an exception if the destinations don't contain at least two <b>valid</b> elements.<br>
 * Elements are considered as invalid if
 * <ul>
 * <li>no route can be found between them and the first destination</li>
 * <li>the destination is on the same street as the first destination</li>
 * </ul>
 * 
 * @param destinations		an <code>ArrayDeque</code> with at least 2 elements (start and target) indicating where to move.
 * @param vehicleLength		the vehicle length
 * @param maxSpeed			the maximum speed of this vehicle in cm/s
 * @param maxCommDist		the maximum distance in cm this vehicle can communicate
 * @param wiFiEnabled		<code>true</code> if this vehicle has a communication device (WiFi), else <code>false</code>
 * @param emergencyVehicle	<code>true</code> vehicle is an emergency vehicle
 * @param brakingRate		the braking rate in cm/s^2
 * @param accelerationRate	the acceleration rate in cm/s^2
 * @param color				the color of the vehicle, if empty the default (color.black) is used
 * @param timeDistance		the time distance
 * @param politeness		the politeness
 * @throws ParseException an Exception indicating that you did not supply a valid destination list.
 */
public Vehicle(ArrayDeque<WayPoint> destinations, int vehicleLength, int maxSpeed, int maxCommDist, boolean wiFiEnabled, boolean emergencyVehicle, int brakingRate, int accelerationRate, int timeDistance, int politeness, int speedDeviation, Color color, boolean fakingMessages, String fakeMessageType) throws ParseException {
	if(destinations != null && destinations.size()>1){
		originalDestinations_ = destinations; 
		destinations_ = originalDestinations_.clone();			
		ID_ = RANDOM.nextLong();
		steadyID_ = steadyIDCounter++;
		vehicleLength_ = vehicleLength;
		maxSpeed_ = maxSpeed;
		emergencyVehicle_ = emergencyVehicle;
		color_ = color;
		brakingRate_ = brakingRate;
		accelerationRate_ = accelerationRate;
		timeDistance_ = timeDistance;
		politeness_ = politeness;
		maxBrakingDistance_ = maxSpeed_ + maxSpeed_ * maxSpeed_ / (2 * brakingRate_);	// see http://de.wikipedia.org/wiki/Bremsweg
		startingWayPoint_ = destinations_.pollFirst();		// take the first element and remove it from the destinations!
		wiFiEnabled_ = wiFiEnabled;
		speedDeviation_ = speedDeviation;
		ownRandom_ = new Random(RANDOM.nextLong());
		curX_ = startingWayPoint_.getX();
		curY_ = startingWayPoint_.getY();
		curPosition_ = startingWayPoint_.getPositionOnStreet();
		curStreet_ = startingWayPoint_.getStreet();
		curWaitTime_ = startingWayPoint_.getWaittime();
		
		fakingMessages_ = fakingMessages;
		fakeMessageType_ = fakeMessageType;
		curRegion_ = Map.getInstance().getRegionOfPoint(curX_,curY_);
		maxCommDistance_ = maxCommDist;
		curSpeed_ = brakingRate_/2;
		newSpeed_ = curSpeed_;
		if(curStreet_.isOneway()){
			while(!destinations_.isEmpty() && (destinations_.peekFirst().getStreet() == curStreet_ || !calculateRoute(true, false))){
				curWaitTime_ = destinations_.pollFirst().getWaittime();
			}
		} else {
			while(!destinations_.isEmpty() && (destinations_.peekFirst().getStreet() == curStreet_ || !calculateRoute(false, false))){
				curWaitTime_ = destinations_.pollFirst().getWaittime();
			}
		}
		if(destinations_.size() == 0) throw new ParseException(Messages.getString("Vehicle.errorNotEnoughDestinations"),0); //$NON-NLS-1$
		if(curWaitTime_ == 0){
			active_ = true;
			curStreet_.addLaneObject(this, curDirection_);
		}
		calculatePosition();
		
		//set the countdowns so that not all fire at the same time!
		beaconCountdown_ = (int)Math.round(curPosition_)%beaconInterval_;
		communicationCountdown_ = (int)Math.round(curPosition_)%communicationInterval_;
		mixCheckCountdown_ = (int)Math.round(curPosition_)%MIX_CHECK_INTERVAL;
		knownVehiclesTimeoutCountdown_ = (int)Math.round(curPosition_)%KNOWN_VEHICLES_TIMEOUT_CHECKINTERVAL;
		knownPenaltiesTimeoutCountdown_ = (int)Math.round(curPosition_)%KNOWN_PENALTIES_TIMEOUT_CHECKINTERVAL;
	

		knownRSUsTimeoutCountdown_ = (int)Math.round(curPosition_)%KNOWN_RSUS_TIMEOUT_CHECKINTERVAL;
		speedFluctuationCountdown_ = (int)Math.round(curPosition_)%SPEED_FLUCTUATION_CHECKINTERVAL;
		fakeMessageCountdown_ = (int)Math.round(curPosition_)%fakeMessagesInterval_;
		emergencyBrakingCountdown_ = ownRandom_.nextInt(emergencyBrakingInterval_)+1;
		
		EVAMessageDelay_ = minEVAMessageDelay_ + ownRandom_.nextInt(maxEVAMessageDelay_);
	} else throw new ParseException(Messages.getString("Vehicle.errorNotEnoughDestinations"),0); //$NON-NLS-1$
}
 
Example 18
Source Project: first-stories-twitter   File: Bucket.java    License: MIT License 4 votes vote down vote up
private boolean isArrayListFull(ArrayDeque<Tweet> queue)
{
    return (queue.size()==queueSize);
}
 
Example 19
Source Project: jlibs   File: XPathParser.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void endLocationPath(int scope, ArrayDeque steps){
    LocationPath path = new LocationPath(scope, steps.size());
    steps.toArray(path.steps);
    push(LocationPathAnalyzer.simplify(path));
}
 
Example 20
Source Project: Cubes   File: ChatActor.java    License: MIT License 4 votes vote down vote up
private void trim(ArrayDeque<ChatMessage> messages, int maxLength) {
  while (messages.size() > maxLength) {
    messages.removeLast();
  }
}