下面列出了java.util.ArrayDeque#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void initialSunlight(Area area) {
try (LightWorldSection worldSection = new LightWorldSection(area)) {
ArrayDeque<LightNode> lightQueue = new ArrayDeque<>();
int max = 15;
for (int x = 0; x < SIZE_BLOCKS; x++) {
for (int z = 0; z < SIZE_BLOCKS; z++) {
int hmRef = getHeightMapRef(x, z);
int h = area.heightmap[hmRef] + 1;
int ref = getRef(x, h, z);
for (int y = 0; y <= (area.maxY - h); y++) {
int r = ref + (y * MAX_Y_OFFSET);
area.light[r] = (byte) ((area.light[r] & 0xF) | (max << 4));
}
lightQueue.add(new LightNode(x + area.minBlockX, h, z + area.minBlockZ, max));
}
}
propagateAdd(lightQueue, worldSection);
}
}
int _countStates(DfaState<?>... starts)
{
ArrayDeque<DfaState<?>> togo = new ArrayDeque<>();
HashSet<DfaState<?>> checkSet = new HashSet<>();
for (DfaState<?> start : starts)
{
if (checkSet.add(start))
{
togo.add(start);
}
}
while(!togo.isEmpty())
{
DfaState<?> scanst = togo.removeFirst();
scanst.enumerateTransitions((c1,c2,newstate)->{
if (checkSet.add(newstate))
{
togo.add(newstate);
}
});
}
return checkSet.size();
}
/**
* descendingIterator.remove() removes current element
*/
public void testDescendingIteratorRemove() {
final ArrayDeque q = new ArrayDeque();
final Random rng = new Random();
for (int iters = 0; iters < 100; ++iters) {
int max = rng.nextInt(5) + 2;
int split = rng.nextInt(max - 1) + 1;
for (int j = max; j >= 1; --j)
q.add(new Integer(j));
Iterator it = q.descendingIterator();
for (int j = 1; j <= split; ++j)
assertEquals(it.next(), new Integer(j));
it.remove();
assertEquals(it.next(), new Integer(split + 1));
for (int j = 1; j <= split; ++j)
q.remove(new Integer(j));
it = q.descendingIterator();
for (int j = split + 1; j <= max; ++j) {
assertEquals(it.next(), new Integer(j));
it.remove();
}
assertFalse(it.hasNext());
assertTrue(q.isEmpty());
}
}
/**
* descendingIterator.remove() removes current element
*/
public void testDescendingIteratorRemove() {
final ArrayDeque q = new ArrayDeque();
final Random rng = new Random();
for (int iters = 0; iters < 100; ++iters) {
int max = rng.nextInt(5) + 2;
int split = rng.nextInt(max - 1) + 1;
for (int j = max; j >= 1; --j)
q.add(new Integer(j));
Iterator it = q.descendingIterator();
for (int j = 1; j <= split; ++j)
assertEquals(it.next(), new Integer(j));
it.remove();
assertEquals(it.next(), new Integer(split + 1));
for (int j = 1; j <= split; ++j)
q.remove(new Integer(j));
it = q.descendingIterator();
for (int j = split + 1; j <= max; ++j) {
assertEquals(it.next(), new Integer(j));
it.remove();
}
assertFalse(it.hasNext());
assertTrue(q.isEmpty());
}
}
public void test_forEachRemaining_CME() throws Exception {
ArrayDeque<String> adq = new ArrayDeque<>();
adq.add("foo");
// The ArrayDeque forEachRemaining implementation doesn't use a precise check
// for concurrent modifications.
adq.iterator().forEachRemaining(s -> adq.add(s));
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
ArrayDeque q = new ArrayDeque();
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.removeFirst();
q.removeFirst();
assertTrue(q.isEmpty());
}
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
// 特判
if (len == 0) {
return new int[]{};
}
// 结果集
List<Integer> res = new ArrayList<>();
// 滑动窗口,注意:保存的是索引值
ArrayDeque<Integer> deque = new ArrayDeque<>(k);
for (int i = 0; i < len; i++) {
// 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值
// 那么将它弹出
if (i >= k && i - k == deque.getFirst()) {
deque.pollFirst();
}
// 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大
// 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日)
// 将它们弹出
while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
deque.pollLast();
}
deque.add(i);
// 队首一定是滑动窗口的最大值的索引
if (i >= k - 1) {
res.add(nums[deque.peekFirst()]);
}
}
int size = res.size();
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = res.get(i);
}
return result;
}
private ArrayDeque<long[]> findBoundaries(Strategy config, Gen<T> gen) {
ArrayDeque<long[]> ordered = new ArrayDeque<>();
PrecursorDataPair<T> startPoint = generate(gen, config, new long[0]);
ordered.add(startPoint.precursor().shrinkTarget());
ordered.add(startPoint.precursor().minLimit());
ordered.add(startPoint.precursor().maxLimit());
return ordered;
}
protected void compound(final Term term) {
if (!previousTerms.isEmpty()) {
boolean reverseCompound = false;
// calculate the compounds based on term and the previous term,
// also possibly including its predecessor if the term before was a "compound reversal" trigger
final Iterator<Term> previousTermsIterator = new TermsFromFieldIterator(previousTerms.descendingIterator(),
term.getField());
Term previousTerm = null;
while (previousTermsIterator.hasNext() && previousTerm == null) {
final Term maybePreviousTerm = previousTermsIterator.next();
if (isReverseCompoundTriggerWord(maybePreviousTerm)) {
reverseCompound = true;
} else {
previousTerm = maybePreviousTerm;
}
}
if (previousTerm != null) {
final ArrayDeque<Term> compoundTerms = new ArrayDeque<>(2);
compoundTerms.add(previousTerm);
compoundTerms.add(term);
try {
addCompounds(compoundTerms, false);
if (reverseCompound || alwaysAddReverseCompounds) {
addCompounds(compoundTerms, true);
}
} catch (final IOException e) {
throw new RuntimeException("Error while compounding " + term, e);
}
}
}
}
private String dependencyPathToArtifacts(
ResolvedComponentResult componentResult, Set<ClassPathEntry> classPathEntries) {
ImmutableSet<String> targetCoordinates =
classPathEntries.stream()
.map(ClassPathEntry::getArtifact)
.map(Artifacts::toCoordinates)
.collect(toImmutableSet());
StringBuilder output = new StringBuilder();
ArrayDeque<ResolvedComponentResult> stack = new ArrayDeque<>();
stack.add(componentResult);
ImmutableListMultimap.Builder<String, String> coordinatesToDependencyPaths =
ImmutableListMultimap.builder();
recordDependencyPaths(coordinatesToDependencyPaths, stack, targetCoordinates);
ImmutableListMultimap<String, String> dependencyPaths = coordinatesToDependencyPaths.build();
for (String coordinates : dependencyPaths.keySet()) {
output.append(coordinates + " is at:\n");
for (String dependencyPath : dependencyPaths.get(coordinates)) {
output.append(" " + dependencyPath + "\n");
}
}
return output.toString();
}
private static void tryPropagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue, LightWorldSection w, int x, int y, int z, int l) {
Area a = w.getArea(CoordinateConverter.area(x), CoordinateConverter.area(z));
int ref = getRef(x - a.minBlockX, y, z - a.minBlockZ);
if (!a.isReady() || y > a.maxY || !TransparencyManager.isTransparent(a.blocks[ref])) return;
int p = ((a.light[ref] >> 4) & 0xF);
if (p != 0 && p < l) {
a.light[ref] = (byte) (a.light[ref] & 0xF); // same as ((a.light[ref] & 0xF0) | (0 << 4))
a.updateRender(y / SIZE_BLOCKS);
a.modify();
removeQueue.add(new LightNode(x, y, z, p));
} else if (p >= l) {
addQueue.add(new LightNode(x, y, z, p));
}
}
private static void tryPropagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue, LightWorldSection w, int x, int y, int z, int l) {
Area a = w.getArea(CoordinateConverter.area(x), CoordinateConverter.area(z));
int ref = getRef(x - a.minBlockX, y, z - a.minBlockZ);
if (!a.isReady() || y > a.maxY || !TransparencyManager.isTransparent(a.blocks[ref])) return;
int p = a.light[ref] & 0xF;
if (p != 0 && p < l) {
a.light[ref] = (byte) (a.light[ref] & 0xF0); // same as ((a.light[ref] & 0xF0) | 0)
a.updateRender(y / SIZE_BLOCKS);
a.modify();
removeQueue.add(new LightNode(x, y, z, p));
} else if (p >= l) {
addQueue.add(new LightNode(x, y, z, p));
}
}
public void send(Row row) throws InterruptedException {
for (ArrayDeque<Row> queue : queues) {
queue.add(row);
}
}
/**
* Iterates over the provided records and tests whether {@link SpanningRecordSerializer} and {@link RecordDeserializer}
* interact as expected.
*
* <p>Only a single {@link MemorySegment} will be allocated.
*
* @param records records to test
* @param segmentSize size for the {@link MemorySegment}
*/
private static void testSerializationRoundTrip(
Iterable<SerializationTestType> records,
int segmentSize,
RecordSerializer<SerializationTestType> serializer,
RecordDeserializer<SerializationTestType> deserializer)
throws Exception {
final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>();
// -------------------------------------------------------------------------------------------------------------
BufferAndSerializerResult serializationResult = setNextBufferForSerializer(serializer, segmentSize);
int numRecords = 0;
for (SerializationTestType record : records) {
serializedRecords.add(record);
numRecords++;
// serialize record
serializer.serializeRecord(record);
if (serializer.copyToBufferBuilder(serializationResult.getBufferBuilder()).isFullBuffer()) {
// buffer is full => start deserializing
deserializer.setNextBuffer(serializationResult.buildBuffer());
numRecords -= DeserializationUtils.deserializeRecords(serializedRecords, deserializer);
// move buffers as long as necessary (for long records)
while ((serializationResult = setNextBufferForSerializer(serializer, segmentSize)).isFullBuffer()) {
deserializer.setNextBuffer(serializationResult.buildBuffer());
}
}
}
// deserialize left over records
deserializer.setNextBuffer(serializationResult.buildBuffer());
while (!serializedRecords.isEmpty()) {
SerializationTestType expected = serializedRecords.poll();
SerializationTestType actual = expected.getClass().newInstance();
RecordDeserializer.DeserializationResult result = deserializer.getNextRecord(actual);
Assert.assertTrue(result.isFullRecord());
Assert.assertEquals(expected, actual);
numRecords--;
}
// assert that all records have been serialized and deserialized
Assert.assertEquals(0, numRecords);
Assert.assertFalse(serializer.hasSerializedData());
Assert.assertFalse(deserializer.hasUnfinishedData());
}
/**
* The results of emitting records via BroadcastPartitioner or broadcasting records directly are the same,
* that is all the target channels can receive the whole outputs.
*
* @param isBroadcastEmit whether using {@link RecordWriter#broadcastEmit(IOReadableWritable)} or not
*/
private void emitRecordWithBroadcastPartitionerOrBroadcastEmitRecord(boolean isBroadcastEmit) throws Exception {
final int numberOfChannels = 4;
final int bufferSize = 32;
final int numValues = 8;
final int serializationLength = 4;
@SuppressWarnings("unchecked")
final Queue<BufferConsumer>[] queues = new Queue[numberOfChannels];
for (int i = 0; i < numberOfChannels; i++) {
queues[i] = new ArrayDeque<>();
}
final TestPooledBufferProvider bufferProvider = new TestPooledBufferProvider(Integer.MAX_VALUE, bufferSize);
final ResultPartitionWriter partitionWriter = new CollectingPartitionWriter(queues, bufferProvider);
final ChannelSelector selector = new OutputEmitter(ShipStrategyType.BROADCAST, 0);
final RecordWriter<SerializationTestType> writer = RecordWriter.createRecordWriter(partitionWriter, selector, 0, "test");
final RecordDeserializer<SerializationTestType> deserializer = new SpillingAdaptiveSpanningRecordDeserializer<>(
new String[]{ tempFolder.getRoot().getAbsolutePath() });
final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>();
final Iterable<SerializationTestType> records = Util.randomRecords(numValues, SerializationTestTypeFactory.INT);
for (SerializationTestType record : records) {
serializedRecords.add(record);
if (isBroadcastEmit) {
writer.broadcastEmit(record);
} else {
writer.emit(record);
}
}
final int requiredBuffers = numValues / (bufferSize / (4 + serializationLength));
for (int i = 0; i < numberOfChannels; i++) {
assertEquals(requiredBuffers, queues[i].size());
final ArrayDeque<SerializationTestType> expectedRecords = serializedRecords.clone();
int assertRecords = 0;
for (int j = 0; j < requiredBuffers; j++) {
Buffer buffer = buildSingleBuffer(queues[i].remove());
deserializer.setNextBuffer(buffer);
assertRecords += DeserializationUtils.deserializeRecords(expectedRecords, deserializer);
}
Assert.assertEquals(numValues, assertRecords);
}
}
void createNinjaActions() throws GenericParsingException {
// Traverse the action graph starting from the targets, specified by the user.
// Only create the required actions.
Set<PathFragment> visitedPaths = Sets.newHashSet();
Set<NinjaTarget> visitedTargets = Sets.newHashSet();
visitedPaths.addAll(pathsToBuild);
ArrayDeque<PathFragment> queue = new ArrayDeque<>(pathsToBuild);
Consumer<Collection<PathFragment>> enqueuer =
paths -> {
for (PathFragment input : paths) {
if (visitedPaths.add(input)) {
queue.add(input);
}
}
};
while (!queue.isEmpty()) {
PathFragment fragment = queue.remove();
NinjaTarget target = targetsMap.get(fragment);
if (target != null) {
// If the output is already created by a symlink action created from specifying that
// file in output_root_inputs attribute of the ninja_graph rule, do not create other
// actions that output that same file, since that will result in an action conflict.
if (!outputRootInputsSymlinks.contains(fragment)) {
if (visitedTargets.add(target)) {
createNinjaAction(target);
}
enqueuer.accept(target.getAllInputs());
} else {
// Sanity check that the Ninja action we're skipping (because its outputs are already
// being symlinked using output_root_inputs) has only symlink outputs specified in
// output_root_inputs. Otherwise we might skip some other outputs.
List<PathFragment> outputsInOutputRootInputsSymlinks = new ArrayList<>();
List<PathFragment> outputsNotInOutputRootInputsSymlinks = new ArrayList<>();
for (PathFragment output : target.getAllOutputs()) {
if (outputRootInputsSymlinks.contains(output)) {
outputsInOutputRootInputsSymlinks.add(output);
} else {
outputsNotInOutputRootInputsSymlinks.add(output);
}
}
if (!outputsNotInOutputRootInputsSymlinks.isEmpty()) {
throw new GenericParsingException(
"Ninja target "
+ target.getRuleName()
+ " has "
+ "outputs in output_root_inputs and other outputs not in output_root_inputs:\n"
+ "Outputs in output_root_inputs:\n "
+ Joiner.on(" \n").join(outputsInOutputRootInputsSymlinks)
+ "\nOutputs not in output_root_inputs:\n "
+ Joiner.on(" \n").join(outputsNotInOutputRootInputsSymlinks));
}
}
} else {
PhonyTarget phonyTarget = phonyTargets.get(fragment);
// Phony target can be null, if the path in neither regular or phony target,
// but the source file.
if (phonyTarget != null) {
phonyTarget.visitExplicitInputs(phonyTargets, enqueuer::accept);
}
}
}
}
public void send(Row row) throws InterruptedException {
for (ArrayDeque<Row> queue : queues) {
queue.add(row);
}
}
@Override
public void writeAttribute(final RoutingContext exchange, final String newValue) throws ReadOnlyAttributeException {
final ArrayDeque<String> value = new ArrayDeque<>();
value.add(newValue);
exchange.queryParams().set(parameter, value);
}
/**
* This test verifies that checkpoint barriers and barrier buffers work correctly with
* concurrent checkpoint barriers where one checkpoint is "overtaking" another checkpoint, i.e.
* some inputs receive barriers from an earlier checkpoint, thereby blocking,
* then all inputs receive barriers from a later checkpoint.
*/
@Test
public void testOvertakingCheckpointBarriers() throws Exception {
try (StreamTaskMailboxTestHarness<String> testHarness =
new MultipleInputStreamTaskTestHarnessBuilder<>(MultipleInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO)
.addInput(BasicTypeInfo.STRING_TYPE_INFO, 2)
.addInput(BasicTypeInfo.INT_TYPE_INFO, 2)
.addInput(BasicTypeInfo.DOUBLE_TYPE_INFO, 2)
.setupOutputForSingletonOperatorChain(new MapToStringMultipleInputOperatorFactory())
.build()) {
ArrayDeque<Object> expectedOutput = new ArrayDeque<>();
long initialTime = 0L;
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0);
// These elements should be forwarded, since we did not yet receive a checkpoint barrier
// on that input, only add to same input, otherwise we would not know the ordering
// of the output since the Task might read the inputs in any order
testHarness.processElement(new StreamRecord<>("Witam-0-1", initialTime), 0, 1);
testHarness.processElement(new StreamRecord<>(42, initialTime), 1, 1);
testHarness.processElement(new StreamRecord<>(1.0d, initialTime), 2, 1);
expectedOutput.add(new StreamRecord<>("Witam-0-1", initialTime));
expectedOutput.add(new StreamRecord<>("42", initialTime));
expectedOutput.add(new StreamRecord<>("1.0", initialTime));
// we should not yet see the barrier, only the two elements from non-blocked input
assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));
// Now give a later barrier to all inputs, this should unblock the first channel
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1);
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0);
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1);
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 0);
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 1);
testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0);
expectedOutput.add(new CancelCheckpointMarker(0));
expectedOutput.add(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()));
assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));
// Then give the earlier barrier, these should be ignored
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1);
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0);
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1);
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 0);
testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 1);
testHarness.waitForTaskCompletion();
assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));
}
}
private void buildElement(PresentationEnvironment env, FormElements elements, ArrayDeque<MetaAttribute> attributePath) {
MetaAttribute lastAttribute = attributePath.getLast();
MetaType type = lastAttribute.getType();
if (isIgnored(attributePath, env)) {
return;
}
String label = PresentationBuilderUtils.getLabel(attributePath);
if (type instanceof MetaDataObject && !lastAttribute.isAssociation()) {
for (MetaAttribute nestedAttribute : type.asDataObject().getAttributes()) {
if (!attributePath.contains(nestedAttribute)) {
ArrayDeque nestedPath = new ArrayDeque();
nestedPath.addAll(attributePath);
nestedPath.add(nestedAttribute);
buildElement(env, elements, nestedPath);
}
}
} else {
PresentationEnvironment elementEnv = env.clone();
elementEnv.setAttributePath(attributePath);
elementEnv.setAcceptedTypes(Arrays.asList(PresentationType.FORM_ELEMENT, PresentationType.DISPLAY));
elementEnv.setType(type);
PresentationElement element = env.createElement(elementEnv);
PathSpec pathSpec = PathSpec.of(attributePath.stream().map(it -> it.getName()).collect(Collectors.toList()));
//String valuePath = PresentationBuilderUtils.getValuePath(attributePath);
String id = pathSpec.toString(); //valuePath.join(valuePath, '.');
FormElement formElement = new FormElement();
formElement.setId(id);
formElement.setComponentId("form");
formElement.setLabel(label);
formElement.setAttributePath(pathSpec);
formElement.setEditable(env.isEditable());
formElement.setComponent(element);
//column.setEditComponent();
// column.setFilter
// column.setWidth
// column.setTyleClass
elements.add(formElement);
}
}