protected void handleMessageData(byte[] aData) { // grab last fragment, use if not complete WebSocketFragment fragment = pendingFragments.peek(); if (fragment == null || fragment.isValid()) { // assign web socket fragment since the last one was complete fragment = new WebSocketFragment(aData); pendingFragments.offer(fragment); } else if (fragment != null) { fragment.appendFragment(aData); if (fragment.canBeParsed()) { fragment.parseContent(); } } // if we have a complete fragment, handle it if (fragment.isValid()) { // handle complete fragment handleCompleteFragment(fragment); // if we have extra data, handle it if (aData.length > fragment.getMessageLength()) { handleMessageData( WebSocketUtil.copySubArray( aData, fragment.getMessageLength(), aData.length - fragment.getMessageLength())); } } }
private static PencilPosition findShortestRoute(int[][] maze) { // all found solutions to the maze PriorityQueue<PencilPosition> solutions = new PriorityQueue<PencilPosition>(5, new PencilPositionComparator()); // bread-first search queue Queue<PencilPosition> routes = new LinkedList<PencilPosition>(); // set of already visited positions Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>(); // add the starting positions, which is always (0,0) routes.add(new PencilPosition(0, 0, false, null)); while (!routes.isEmpty()) { PencilPosition position = routes.poll(); // if this is the destinations position then we've found a solution if (0 == maze[position.row][position.column]) { solutions.add(position); continue; } // if we haven't already visited this position if (!visitedPositions.contains(position)) { routes.addAll(findPossibleRoutes(position, maze)); visitedPositions.add(position); } } return solutions.poll(); }
public PreloadTarget next(int width, int height) { final PreloadTarget result = queue.poll(); queue.offer(result); result.photoWidth = width; result.photoHeight = height; return result; }
public Object evaluate(EditorAdaptor vim, Queue<String> command) { String next = command.poll(); int index = next.indexOf('='); if (index < 0) { noSuchOptionMessage(vim, next); return null; } String optName = next.substring(0, index).trim(); String value = next.substring(index + 1); if (command.size() > 0) { // restore preceding space and spaces between tokens value += " " + StringUtils.join(" ", command); } Option<String> strOpt; Option<Integer> intOpt; try { if ((strOpt = find(Options.STRING_OPTIONS, optName)) != null) set(vim, strOpt, value); else if ((intOpt = find(Options.INT_OPTIONS, optName)) != null) set(vim, intOpt, Integer.valueOf(value)); else noSuchOptionMessage(vim, optName); } catch (ValueException e) { invalidValueMessage(vim, value); } catch (NumberFormatException e) { invalidValueMessage(vim, value); } return null; }
private void pass() throws InterruptedException { if (!exitQueue.isEmpty()) { Visitor oldVisitor = exitQueue.poll(); System.out.println(oldVisitor + " left the museum"); // Thread.sleep(2000); } }
@Setup public synchronized void setup() { for (int i = 0; i < MAX_THREAD_COUNT; i++) { responseQueues[i] = new OneToOneConcurrentArrayQueue<>(RESPONSE_QUEUE_CAPACITY); } values = new Integer[burstLength]; for (int i = 0; i < burstLength; i++) { values[i] = -(burstLength - i); } consumerThread = new Thread( () -> { while (true) { final Integer value = sendQueue.poll(); if (null == value) { if (!running.get()) { break; } } else { final int intValue = value; if (intValue >= 0) { final Queue<Integer> responseQueue = responseQueues[value]; while (!responseQueue.offer(value)) { // busy spin } } } } }); consumerThread.setName("consumer"); consumerThread.start(); }
/** * 开始下载任务 * * @param downloadId * @param callback */ public void startTask(int downloadId, FileDownloaderCallback callback) { FileDownloaderModel model = getFileDownloaderModelById(downloadId); if (model != null) { BridgeListener bridgeListener = mListenerManager.getBridgeListener(downloadId); bridgeListener.addDownloadListener(callback); if (mDownloadingList.size() >= mConfiguration.getMaxDownloadingCount()) { // 下载中队列已满 if (!mWaitQueue.contains(model)) { mWaitQueue.offer(model); } bridgeListener.wait(downloadId); } else { mDownloadingList.add(model); final BaseDownloadTask task = FileDownloader.getImpl() .create(model.getUrl()) .setPath(model.getPath()) .setCallbackProgressTimes(100) .setAutoRetryTimes(mAutoRetryTimes) .setListener(bridgeListener); for (int i = 0; i < mHeaders.size(); i++) { task.addHeader(mHeaders.name(i), mHeaders.value(i)); } bridgeListener.setDownloadTask(task); task.start(); } } else { ILogger.e("Task does not exist!"); } }
public static int nextImportantEvent( Queue<OTH> othQueue, List<Instance> instanceList, CPUList cpuList) { int nextImportantTime = Integer.MAX_VALUE; int nextCpuTime; int nextOthTime; int nextNewTime; if (othQueue.isEmpty()) { nextOthTime = Integer.MAX_VALUE; } else { nextOthTime = othQueue.peek().getExitTime(); } nextCpuTime = cpuList.getNextFinishTime(); if (instanceList.isEmpty()) { nextNewTime = Integer.MAX_VALUE; } else { nextNewTime = instanceList.get(0).getStartTime(); } nextImportantTime = Math.min(nextOthTime, nextCpuTime); nextImportantTime = Math.min(nextImportantTime, nextNewTime); // System.out.println("\n################## NEXT IMPORTANT TIME: " + nextImportantTime); return nextImportantTime; }
static long maxFlow() { long totalFlow = 0; while (true) { Queue<Integer> q = new LinkedList<>(); int[] parent = new int[cap.length]; Arrays.fill(parent, -1); q.add(s); while (!q.isEmpty()) { int node = q.poll(); for (int j = 1; j <= n; j++) { if (cap[node][j] - flow[node][j] > 0 && parent[j] == -1) { parent[j] = node; q.add(j); } } } if (parent[t] == -1) break; long cflow = Long.MAX_VALUE; int current = t; while (current != s) { cflow = Math.min(cflow, cap[parent[current]][current] - flow[parent[current]][current]); current = parent[current]; } current = t; while (current != s) { flow[parent[current]][current] += cflow; flow[current][parent[current]] -= cflow; current = parent[current]; } totalFlow += cflow; } return totalFlow; }
/** @return true if there is still work to be processed. */ public boolean isBusyOld() { return !(mCreateMarkerTasks.isEmpty() && mOnScreenCreateMarkerTasks.isEmpty() && mOnScreenRemoveMarkerTasks.isEmpty() && mRemoveMarkerTasks.isEmpty() && mAnimationTasks.isEmpty()); }
public static int checkTimes( Queue<OTH> othQueue, List<Instance> instanceList, CPUList cpuList, int importantTime) { int nextCpuTime; int nextOthTime; int nextNewTime; if (othQueue.isEmpty()) { nextOthTime = Integer.MAX_VALUE; } else { nextOthTime = othQueue.peek().getExitTime(); } nextCpuTime = cpuList.getNextFinishTime(); if (instanceList.isEmpty()) { nextNewTime = Integer.MAX_VALUE; } else { nextNewTime = instanceList.get(0).getStartTime(); } if (importantTime == nextCpuTime) { return 0; } if (importantTime == nextOthTime) { return 1; } if (importantTime == nextNewTime) { return 2; } return -1; }
/** Sorts the index in the order of the date of publication of the posts. */ protected void sortIndexes() { for (SingleIndex s : indexList) { for (int i = 0; i < postsPerIndex && !queue.isEmpty(); i++) { s.getPosts().add(queue.remove()); } } }
/** * Using a serialized list of tree nodes to generate a binary tree. There is detail information: * https://leetcode.com/problems/binary-tree-inorder-traversal/ * * @param serializedTreeNode a serialized list of tree nodes * @return the node of tree root */ public static TreeNode generateTree(String serializedTreeNode) { String[] tokens = serializedTreeNode.split(","); if (tokens.length <= 0) return null; TreeNode root = new TreeNode(Integer.parseInt(tokens[0])); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int pos = 1; while (pos < tokens.length) { TreeNode temp = queue.remove(); if (!tokens[pos].equals("#")) { TreeNode left = new TreeNode(Integer.parseInt(tokens[pos])); temp.left = left; queue.add(left); } pos++; if (pos >= tokens.length) break; if (!tokens[pos].equals("#")) { TreeNode right = new TreeNode(Integer.parseInt(tokens[pos])); temp.right = right; queue.add(right); } pos++; } return root; }
public void process(String queueName) { XtrTask xtrTask; Queue gaeQueue = QueueFactory.getDefaultQueue(); log.info("Processing queue " + queueName); java.util.Queue<XtrTask> taskQueue = queues.get(queueName); if (taskQueue == null) { log.warning("Queue " + queueName + " does not exist"); return; } TaskHandle taskHandle = null; while ((xtrTask = taskQueue.poll()) != null) { taskHandle = gaeQueue.add( url("/webxtractor/task/".concat(queueName)) .param("payload", xtrTask.getPayload()) .method(TaskOptions.Method.GET)); log.info( "GA queue " + taskHandle.getQueueName() + " accepted task " + xtrTask.getName() + " as " + taskHandle.getName() + " estimated to run at " + taskHandle.getEtaMillis()); } }
@Test public void testBug58232() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.addApplicationListener(Bug54807Config.class.getName()); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Assert.assertEquals(LifecycleState.STARTED, ctx.getState()); SimpleClient client = new SimpleClient(); URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic"); try (Session session = wsContainer.connectToServer(client, uri); ) { CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); session.addMessageHandler(handler); session.getBasicRemote().sendText("echoBasic"); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); for (String message : messages) { Assert.assertEquals("echoBasic", message); } } }
/** * Locate each unexpanded Structure|Sequence and: 1. check that none of its fields is referenced * => do not expand 2. add all of its fields as leaves Note that #2 may end up adding additional * leaf structs &/or seqs */ public void expand() { // Create a queue of unprocessed leaf compounds Queue<DapVariable> queue = new ArrayDeque<DapVariable>(); for (int i = 0; i < variables.size(); i++) { DapVariable var = variables.get(i); if (!var.isTopLevel()) continue; // prime the queue if (var.getSort() == DapSort.STRUCTURE || var.getSort() == DapSort.SEQUENCE) { DapStructure struct = (DapStructure) var; // remember Sequence subclass Structure if (expansionCount(struct) == 0) queue.add(var); } } // Process the queue in prefix order while (queue.size() > 0) { DapVariable vvstruct = queue.remove(); DapStructure dstruct = (DapStructure) vvstruct; for (DapVariable field : dstruct.getFields()) { if (findVariableIndex(field) < 0) { // Add field as leaf this.segments.add(new Segment(field)); this.variables.add(field); } if (field.getSort() == DapSort.STRUCTURE || field.getSort() == DapSort.SEQUENCE) { if (expansionCount((DapStructure) field) == 0) queue.add(field); } } } this.expansion = Expand.EXPANDED; }
public void remove(MUFModule module) { if (playing) { delayRemove.offer(module); return; } // set to true playing = true; adding = false; moduleToBeRemoved = module; // exclude from layout modules.remove(module.getId()); GridData data = (GridData) module.self.getLayoutData(); data.exclude = true; module.self.setLayoutData(data); module.self.setVisible(false); if (content.isVisible()) { // get destination size frame = 1; Point newSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT); dx = Math.min(0, (newSize.x - oldSize.x) / FRAMES); dy = Math.min(0, (newSize.y - oldSize.y) / FRAMES); Display.getCurrent().timerExec(0, runnable); } else { oldSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT); playing = false; delayDispose.offer(module.self); } module.dispose(); }
public static void main(String[] args) throws IOException { int n = readInt(); int m = readInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for (int x = 0; x < n; x++) adj.add(new ArrayList<Integer>()); for (int x = 0; x < m; x++) { int a = readInt() - 1; int b = readInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } int k = readInt(); Queue<State> q = new LinkedList<State>(); boolean[] v = new boolean[n]; for (int x = 0; x < k; x++) { int a = readInt() - 1; v[a] = true; q.offer(new State(a, 0)); } int max = 0; while (!q.isEmpty()) { State curr = q.poll(); max = Math.max(max, curr.moves); for (Integer next : adj.get(curr.index)) { if (v[next]) continue; v[next] = true; q.offer(new State(next, curr.moves + 1)); } } System.out.println(max); }
public Map<Field, Object> next() { if (!hasNext()) { throw new NoSuchElementException(); } Map<Field, Object> pass = new HashMap<Field, Object>(); for (Entry<Field, Queue<? extends Object>> entry : queues.entrySet()) { final Field field = entry.getKey(); final Queue<? extends Object> queue = entry.getValue(); pass.put(field, queue.peek()); } for (Entry<Field, Queue<? extends Object>> entry : queues.entrySet()) { final Field field = entry.getKey(); final Queue<? extends Object> queue = entry.getValue(); queue.poll(); if (queue.isEmpty() && hasNext()) { List<? extends Object> parameter = parameters.get(field); queues.put(field, new LinkedList<Object>(parameter)); } else { break; } } return pass; }
/* Fill the bipartite graph if possible. */ boolean[] solve() { Map<Integer, List<Integer>> gr = makeGraph(); boolean[] truthTable = new boolean[count]; // keep track of which ones we've visited boolean[] visited = new boolean[count]; Queue<Integer> queue = new LinkedList<Integer>(); truthTable[0] = true; // assume the first person tells the truth queue.add(0); // Breadth first search on graph while (!queue.isEmpty()) { int next = queue.remove(); boolean truth = truthTable[next]; List<Integer> list = gr.get(next); // Go through list and toggle when needed for (int i = 0; i < list.size(); i++) { int node = list.get(i); if (!visited[node]) { visited[node] = true; truthTable[node] = !truth; queue.add(node); } } } return truthTable; }
/** * It is synchronized as it does merging of adjacent blocks. An easiest way to somewhat address * fragmentation problem. * * @param pointer2free */ private void freeAndMerge(Pointer pointer2free) { synchronized (pointers) { pointers.remove(pointer2free); // merge adjacent blocks if (null != pointer2free.getPrev() && pointer2free.getPrev().isFree()) { // Merge previous pointers.remove(pointer2free.getPrev()); pointer2free.setStart(pointer2free.getPrev().getStart()); pointer2free.setPrev(pointer2free.getPrev().getPrev()); // Recursive call freeAndMerge(pointer2free); } if (null != pointer2free.getNext() && pointer2free.getNext().isFree()) { // Merge Next pointers.remove(pointer2free.getNext()); pointer2free.setEnd(pointer2free.getNext().getEnd()); pointer2free.setNext(pointer2free.getNext().getNext()); // Recursive call freeAndMerge(pointer2free); } if (!pointer2free.isFree()) { pointer2free.setFree(true); pointer2free.setClazz(null); pointers.add(pointer2free); } } }
@Override public void update(GameContainer gc, int delta) throws SlickException { rand.nextDouble(); if (System.currentTimeMillis() - lastUpdate > simulationDelay) { lastUpdate = System.currentTimeMillis(); runSimulation(); } Airplane airplaneHandle; Iterator<Airplane> it; it = airQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.update(delta); } it = groundQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.update(delta); } airplaneHandle = runway.getCurrentAirplane(); if (airplaneHandle != null) airplaneHandle.update(delta); }
private void adjustIncomingPosition(Queue<PositionElement> longs, Queue<PositionElement> shorts) { if (mIncomingPosition.signum() == 1) { longs.add(new PositionElement(mIncomingPosition, mClosingPrice)); } else if (mIncomingPosition.signum() == -1) { shorts.add(new PositionElement(mIncomingPosition.negate(), mClosingPrice)); } }
@Override public void render(GameContainer gc, Graphics g) throws SlickException { backgroundImage.draw(); Airplane airplaneHandle; Iterator<Airplane> it; it = airQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.render(g, airplaneImage); } it = groundQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.render(g, airplaneImage); } airplaneHandle = runway.getCurrentAirplane(); if (airplaneHandle != null) airplaneHandle.render(g, airplaneImage); g.setColor(Color.white); g.drawString("Airport Simulator", gc.getWidth() - 170, 10); g.drawString("Update: " + currentUpdate, gc.getWidth() - 130, gc.getHeight() - 30); }
public int[] findOrder(int numCourses, int[][] prerequisites) { Map<Integer, Set<Integer>> graph = new HashMap<>(); Queue<Integer> queue = new LinkedList<>(); int[] visited = new int[numCourses]; for (int i = 0; i < numCourses; ++i) { graph.put(i, new HashSet<>()); } // build the graph first for (int i = 0; i < prerequisites.length; ++i) { graph.get(prerequisites[i][0]).add(prerequisites[i][1]); } boolean hasCycle = false; for (int i = 0; i < numCourses; ++i) { if (!dfs(graph, i, visited, queue)) { hasCycle = true; break; } } if (hasCycle) { return new int[0]; } else { int[] result = new int[numCourses]; for (int i = 0; i < numCourses; ++i) { result[i] = queue.poll(); } return result; } }
private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) throws IOException { Channel channel = ctx.channel(); Attribute<Boolean> attr = channel.attr(WRITE_ONCE); Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport()); if (!channel.isActive() || queue.isEmpty() || !attr.compareAndSet(null, true)) { promise.setSuccess(); return; } ByteBuf out = encoder.allocateBuffer(ctx.alloc()); Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get(); if (b64 != null && b64) { Integer jsonpIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get(); encoder.encodeJsonP(jsonpIndex, queue, out, ctx.alloc(), 50); String type = "application/javascript"; if (jsonpIndex == null) { type = "text/plain"; } sendMessage(msg, channel, out, type, promise); } else { encoder.encodePackets(queue, out, ctx.alloc(), 50); sendMessage(msg, channel, out, "application/octet-stream", promise); } }
@Override public String[] findFiles(final String folderName) { File folder = new File(folderName); if (!folder.exists()) { throw new IllegalArgumentException(); } List<String> foundFiles = new ArrayList<String>(); Queue<File> folders = new LinkedList<File>(); folders.add(folder); while (!folders.isEmpty()) { File currentFolder = folders.remove(); File[] currentFiles = currentFolder.listFiles(); for (File f : currentFiles) { if (f.isDirectory()) { folders.add(f); } else if (f.isFile()) { foundFiles.add(f.getAbsolutePath()); } else { throw new RuntimeException("It isn't file or folder"); } } } return foundFiles.toArray(new String[foundFiles.size()]); }
/** This is synchronized to ensure that we process the queue serially. */ private synchronized void complete(String message) { // This is a weird problem with writing stuff while idling. Need to investigate it more, but // for now just ignore it. if (MESSAGE_COULDNT_BE_FETCHED_REGEX.matcher(message).matches()) { log.warn( "Some messages in the batch could not be fetched for {}\n" + "---cmd---\n{}\n---wire---\n{}\n---end---\n", new Object[] {config.getUsername(), getCommandTrace(), getWireTrace()}); errorStack.push(new Error(completions.peek(), message, wireTrace.list())); throw new RuntimeException( "Some messages in the batch could not be fetched for user " + config.getUsername()); } CommandCompletion completion = completions.peek(); if (completion == null) { if ("+ idling".equalsIgnoreCase(message)) { synchronized (idleMutex) { idler.idleStart(); log.trace("IDLE entered."); idleAcknowledged.set(true); } } else { log.error("Could not find the completion for message {} (Was it ever issued?)", message); errorStack.push(new Error(null, "No completion found!", wireTrace.list())); } return; } if (completion.complete(message)) { completions.poll(); } }
/** * Dequeues all previously enqueued wrappers and writes them to the stream. * * @throws IOException If failed. */ void delayedWrite() throws IOException { if (wrappers != null) for (GridOptimizedWrapper w = wrappers.poll(); w != null; w = wrappers.poll()) w.delayedWriteExternal(this); wrappers = null; // GC. }
void checkIterationSanity(Queue q) { if (rnd.nextBoolean()) return; int size = q.size(); Object[] a = q.toArray(); Object[] b = new Object[size + 2]; Arrays.fill(b, Boolean.TRUE); Object[] c = q.toArray(b); equal(a.length, size); check(b == c); check(b[size] == null); check(b[size + 1] == Boolean.TRUE); equal(q.toString(), Arrays.toString(a)); Integer[] xx = null, yy = null; if (size > 0) { xx = new Integer[size - 1]; Arrays.fill(xx, 42); yy = ((Queue<Integer>) q).toArray(xx); for (Integer zz : xx) equal(42, zz); } Iterator it = q.iterator(); for (int i = 0; i < size; i++) { check(it.hasNext()); Object x = it.next(); check(x == a[i]); check(x == b[i]); if (xx != null) check(x == yy[i]); } check(!it.hasNext()); }