List of usage examples for java.util ArrayDeque pop
public E pop()
From source file:Main.java
public static void main(String[] args) { ArrayDeque<Integer> deque = new ArrayDeque<Integer>(8); deque.add(25);/* w w w . j a v a 2 s . c om*/ deque.add(2); deque.add(1); deque.add(18); System.out.println(deque); int retval = deque.pop(); System.out.println("Element removed is " + retval); System.out.println(deque); }
From source file:edu.oregonstate.eecs.mcplan.domains.tamarisk.TamariskParameters.java
public static void main(final String[] argv) { // for( int i = 0; i < 1000; ++i ) { // final int Nreaches = 4; // final int Nhabitats = 4; // final RandomGenerator rng = new MersenneTwister( 42 ); // final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g // = new TamariskParameters( rng, Nreaches, Nhabitats ).createRandomGraph( 42 + i, true ); // }//w w w . ja v a 2 s. c o m final int Nreaches = 10; final int Nhabitats = 4; final RandomGenerator rng = new MersenneTwister(42); final TamariskParameters params = new TamariskParameters(rng, Nreaches, Nhabitats); // final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g = params.createRandomGraph( 42, true ); final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g = params.createBalancedGraph(3); final double[][] K = params.calculateDispersionKernel(g); for (int i = 0; i < K.length; ++i) { System.out.println(Arrays.toString(K[i])); } final JGraphModelAdapter adapter = new JGraphModelAdapter(g); final JGraph jgraph = new JGraph(adapter); // final JGraphLayoutAlgorithm layout = new SugiyamaLayoutAlgorithm(); final JFrame frame = new JFrame(); frame.setSize(480, 360); frame.getContentPane().add(new JGraph(new JGraphModelAdapter(g))); frame.setVisible(true); final TamariskState state = new TamariskState(rng, params, g); final TamariskSimulator sim = new TamariskSimulator(state); System.out.println(state); System.out.println(); final int T = 30; final ArrayDeque<String> hist = new ArrayDeque<String>(); for (int t = 0; t < T; ++t) { sim.takeAction(new JointAction<TamariskAction>(new NothingAction())); System.out.println(state); System.out.println(); hist.push(state.toString()); } for (int t = 0; t < T; ++t) { final String forward = hist.pop(); final String backward = sim.state().toString(); assert (forward.equals(backward)); sim.untakeLastAction(); } }
From source file:org.datagator.tools.importer.Main.java
public static void main(String[] args) throws IOException { int columnHeaders = 0; // cli input int rowHeaders = 0; // cli input try {//from w w w . ja va 2 s .c o m CommandLine cmds = parser.parse(opts, args); if (cmds.hasOption("filter")) { throw new UnsupportedOperationException("Not supported yet."); } if (cmds.hasOption("layout")) { String[] layout = cmds.getOptionValues("layout"); if ((layout == null) || (layout.length != 2)) { throw new IllegalArgumentException("Bad layout."); } try { columnHeaders = Integer.valueOf(layout[0]); rowHeaders = Integer.valueOf(layout[1]); if ((columnHeaders < 0) || (rowHeaders < 0)) { throw new IllegalArgumentException("Bad layout."); } } catch (NumberFormatException ex) { throw new IllegalArgumentException(ex); } } if (cmds.hasOption("help")) { help.printHelp("importer", opts, true); System.exit(EX_OK); } // positional arguments, i.e., input file name(s) args = cmds.getArgs(); } catch (ParseException ex) { throw new IllegalArgumentException(ex); } catch (IllegalArgumentException ex) { help.printHelp("importer", opts, true); throw ex; } JsonGenerator jg = json.createGenerator(System.out, JsonEncoding.UTF8); jg.setPrettyPrinter(new StandardPrinter()); final Extractor extractor; if (args.length == 1) { extractor = new FileExtractor(new File(args[0])); } else if (args.length > 1) { throw new UnsupportedOperationException("Not supported yet."); } else { throw new IllegalArgumentException("Missing input."); } int columnsCount = -1; int matrixCount = 0; ArrayDeque<String> stack = new ArrayDeque<String>(); AtomType token = extractor.nextAtom(); while (token != null) { switch (token) { case FLOAT: case INTEGER: case STRING: case NULL: jg.writeObject(extractor.getCurrentAtomData()); break; case START_RECORD: jg.writeStartArray(); break; case END_RECORD: int _numFields = (Integer) extractor.getCurrentAtomData(); if (columnsCount < 0) { columnsCount = _numFields; } else if (columnsCount != _numFields) { throw new RuntimeException(String.format("row %s has different length than previous rows", String.valueOf(_numFields - 1))); } jg.writeEndArray(); break; case START_GROUP: stack.push(String.valueOf(extractor.getCurrentAtomData())); jg.writeStartObject(); jg.writeStringField("kind", "datagator#Matrix"); jg.writeNumberField("columnHeaders", columnHeaders); jg.writeNumberField("rowHeaders", rowHeaders); jg.writeFieldName("rows"); jg.writeStartArray(); break; case END_GROUP: int rowsCount = (Integer) extractor.getCurrentAtomData(); if (rowsCount == 0) { jg.writeStartArray(); jg.writeEndArray(); rowsCount = 1; columnsCount = 0; } jg.writeEndArray(); jg.writeNumberField("rowsCount", rowsCount); jg.writeNumberField("columnsCount", columnsCount); jg.writeEndObject(); matrixCount += 1; stack.pop(); break; default: break; } token = extractor.nextAtom(); } jg.close(); System.exit(EX_OK); }
From source file:io.selendroid.server.model.internal.AbstractNativeElementContext.java
/** visible for testing */ protected static List<AndroidElement> searchViews(AbstractNativeElementContext context, List<View> roots, Predicate predicate, boolean findJustOne) { List<AndroidElement> elements = new ArrayList<AndroidElement>(); if (roots == null || roots.isEmpty()) { return elements; }/*from ww w . j ava 2 s .c om*/ ArrayDeque<View> queue = new ArrayDeque<View>(); for (View root : roots) { queue.add(root); while (!queue.isEmpty()) { View view = queue.pop(); if (predicate.apply(view)) { elements.add(context.newAndroidElement(view)); if (findJustOne) { break; } } if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; int childrenCount = group.getChildCount(); for (int index = 0; index < childrenCount; index++) { queue.add(group.getChildAt(index)); } } } } return elements; }
From source file:org.apache.hadoop.hbase.thrift.TestMutationWriteToWAL.java
@Test public void testMutationWriteToWAL() throws Exception { HBaseTestingUtility.setThreadNameFromMethod(); final Configuration conf = TEST_UTIL.getConfiguration(); FileSystem fs = FileSystem.get(conf); List<String> expectedLogEntries = new ArrayList<String>(); try {/*from www . j av a 2s . c om*/ Hbase.Client client = createClient(); client.createTable(HTestConst.DEFAULT_TABLE_BYTE_BUF, HTestConst.DEFAULT_COLUMN_DESC_LIST); int expectedEntriesForRow[] = new int[NUM_ROWS]; for (int i = NUM_ROWS - 1; i >= 0; --i) { final String row = getRow(i); List<Mutation> mutations = new ArrayList<Mutation>(); // writeToWAL cannot depend on column, only on the row boolean writeToWAL = i % 3 == 0; for (int j = 0; j < NUM_COLS_PER_ROW; ++j) { final String qual = getCol(j); boolean isDelete = shouldDelete(i, j); if (!isDelete) { expectedEntriesForRow[i]++; } final String value = isDelete ? "" : getValue(i, j); Mutation m = new Mutation(false, ByteBuffer.wrap(Bytes.toBytes(HTestConst.DEFAULT_CF_STR + ":" + qual)), ByteBuffer.wrap(Bytes.toBytes(value)), writeToWAL, HConstants.LATEST_TIMESTAMP); m.isDelete = isDelete; mutations.add(m); if (writeToWAL) { expectedLogEntries.add(row + "," + qual + "," + value + "," + m.isDelete); } } final ByteBuffer rowBuf = ByteBuffer.wrap(Bytes.toBytes(row)); // Exercise both APIs. if (i % 2 == 0) { client.mutateRow(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBuf, mutations, null, null); } else { List<BatchMutation> rowBatches = new ArrayList<BatchMutation>(); BatchMutation bm = new BatchMutation(rowBuf, mutations); rowBatches.add(bm); client.mutateRows(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBatches, null, null); } } client.disableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF); client.enableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF); // Check that all the data is there for (int i = 0; i < NUM_ROWS; ++i) { final String row = getRow(i); List<TRowResult> results = client.getRow(HTestConst.DEFAULT_TABLE_BYTE_BUF, ByteBuffer.wrap(Bytes.toBytes(row)), null); TRowResult result = results.get(0); assertEquals("No results found for row " + row, expectedEntriesForRow[i], result.getColumnsSize()); Map<ByteBuffer, TCell> sortedColumns = new TreeMap<ByteBuffer, TCell>(result.getColumns()); int j = -1; for (Map.Entry<ByteBuffer, TCell> entry : sortedColumns.entrySet()) { ++j; while (shouldDelete(i, j)) { ++j; } assertEquals(HTestConst.DEFAULT_CF_STR + ":" + getCol(j), Bytes.toStringBinaryRemaining(entry.getKey())); assertEquals(getValue(i, j), Bytes.toStringBinary(entry.getValue().getValue())); } } } finally { closeClientSockets(); } TEST_UTIL.shutdownMiniHBaseCluster(); final Path baseDir = new Path(conf.get(HConstants.HBASE_DIR)); final Path oldLogDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME); int nLogFilesRead = 0; List<String> actualLogEntries = new ArrayList<String>(); ArrayDeque<FileStatus> checkQueue = new ArrayDeque<FileStatus>( java.util.Arrays.asList(fs.listStatus(oldLogDir))); while (!checkQueue.isEmpty()) { FileStatus logFile = checkQueue.pop(); if (logFile.isDir()) { checkQueue.addAll(java.util.Arrays.asList(fs.listStatus(logFile.getPath()))); continue; } HLog.Reader r = HLog.getReader(fs, logFile.getPath(), conf); LOG.info("Reading HLog: " + logFile.getPath()); HLog.Entry entry = null; while ((entry = r.next(entry)) != null) { if (!Bytes.equals(entry.getKey().getTablename(), HTestConst.DEFAULT_TABLE_BYTES)) { continue; } for (KeyValue kv : entry.getEdit().getKeyValues()) { if (Bytes.equals(kv.getRow(), HLog.METAROW)) { continue; } actualLogEntries.add(Bytes.toStringBinary(kv.getRow()) + "," + Bytes.toStringBinary(kv.getQualifier()) + "," + Bytes.toStringBinary(kv.getValue()) + "," + (kv.getType() == KeyValue.Type.DeleteColumn.getCode())); } } r.close(); ++nLogFilesRead; } assertTrue(nLogFilesRead > 0); Collections.sort(expectedLogEntries); Collections.sort(actualLogEntries); LOG.info("Expected log entries: " + expectedLogEntries.size() + ", actual log entries: " + actualLogEntries.size()); assertEquals(expectedLogEntries.toString(), actualLogEntries.toString()); }
From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java
private void handleChanges(State startingState, List<TreeNode> changes) { ArrayDeque<State> check = new ArrayDeque<>(); check.add(startingState);//w w w . j av a2 s. c o m while (!check.isEmpty()) { State next = check.pop(); TreeNode match = Utils.find(next.needle, next.haystack); if (match != null) { for (TreeNode current : next.needle.getChildren()) { check.add(new State(current, match.getChildren())); } } else { changes.add(next.needle); } } }
From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java
public void updateTree(List<TreeNode> add, List<TreeNode> remove) { Set<TreeItem<TreeNode>> updated = new HashSet<>(); ArrayDeque<TreeNode> queue = new ArrayDeque<>(); queue.addAll(add);//from ww w. j av a2 s . c o m while (!queue.isEmpty()) { TreeNode thisNode = queue.pop(); TreeItem<TreeNode> parent; if (thisNode.getParent() == null) { parent = rootItem; } else { parent = itemMap.get(thisNode.getParent()); } updated.add(parent); TreeItem<TreeNode> thisItem = new TreeItem<>(thisNode); thisItem.addEventHandler(TreeItem.<TreeNode>branchExpandedEvent(), event -> { if (thisItem.getChildren().size() == 1) { thisItem.getChildren().get(0).setExpanded(true); } }); thisItem.setGraphic(new ImageView(new Image(getIconForTreeItem(thisNode)))); FutureTask<Void> call = new FutureTask<>(() -> { parent.getChildren().add(thisItem); return null; }); Platform.runLater(call); try { call.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } itemMap.put(thisNode, thisItem); queue.addAll(thisNode.getChildren()); } for (TreeItem<TreeNode> parent : updated) { if (parent.getChildren().size() > 1) { FutureTask<Void> call = new FutureTask<>(() -> { parent.getChildren().sort((a, b) -> { int ac = a.getValue().getChildren().size(); int bc = b.getValue().getChildren().size(); if (ac == 0 && bc != 0) return 1; else if (ac != 0 && bc == 0) return -1; return a.getValue().getDisplayName().compareTo(b.getValue().getDisplayName()); }); return null; }); Platform.runLater(call); try { call.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } queue.addAll(remove); while (!queue.isEmpty()) { TreeNode thisNode = queue.pop(); TreeItem<TreeNode> thisItem = itemMap.remove(thisNode); thisItem.getParent().getChildren().remove(thisItem); queue.addAll(thisNode.getChildren()); } }
From source file:edu.oregonstate.eecs.mcplan.domains.planetwars.PwSimulator.java
@Override public void untakeLastAction() { final ArrayDeque<PwEvent> frame = event_history.pop(); final int frame_size = frame.size(); while (!frame.isEmpty()) { final PwEvent e = frame.pop(); e.undoAction(s);// w ww .ja va 2s . c o m } s.t -= 1; depth_ -= frame_size; }
From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java
public void testPop() { Object o1 = new Object(); Object o2 = new Object(); ArrayDeque<Object> deque = new ArrayDeque<>(); try {//from w w w.ja va 2 s . c o m deque.pop(); fail(); } catch (NoSuchElementException expected) { } deque.add(o1); assertEquals(o1, deque.pop()); assertTrue(deque.isEmpty()); deque.add(o1); deque.add(o2); assertEquals(o1, deque.pop()); checkDequeSizeAndContent(deque, o2); assertEquals(o2, deque.pop()); assertTrue(deque.isEmpty()); try { deque.pop(); fail(); } catch (NoSuchElementException expected) { } }
From source file:com.rammelkast.anticheatreloaded.config.yaml.CommentedConfiguration.java
@Override public String saveToString() { yamlOptions.setIndent(options().indent()); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // String header = buildHeader(); - CommentedConfiguration String dump = yaml.dump(getValues(false)); if (dump.equals(BLANK_CONFIG)) { dump = ""; }/* w w w . j a v a 2 s . com*/ // Begin CommentedConfiguration StringBuilder builder = new StringBuilder(); String[] lines = dump.split("\n"); ArrayDeque<String> queue = new ArrayDeque<String>(); for (String string : lines) { queue.add(string); } int i = 0; while (queue.size() > 0) { if (comments.containsKey(i)) { builder.append(comments.get(i)); // Handle subsequent comments int b = i; while (true) { b++; if (comments.containsKey(b)) { builder.append('\n'); builder.append(comments.get(b)); } else { break; } } builder.append('\n'); i = b; } builder.append(queue.getFirst()); builder.append('\n'); queue.pop(); i++; } // End CommentedConfiguration return builder.toString(); }