@Override @NotNull public ClassId getClassId(int index) { LinkedList<String> packageFqName = new LinkedList<String>(); LinkedList<String> relativeClassName = new LinkedList<String>(); boolean local = false; while (index != -1) { QualifiedName proto = qualifiedNames.getQualifiedName(index); String shortName = strings.getString(proto.getShortName()); switch (proto.getKind()) { case CLASS: relativeClassName.addFirst(shortName); break; case PACKAGE: packageFqName.addFirst(shortName); break; case LOCAL: relativeClassName.addFirst(shortName); local = true; break; } index = proto.getParentQualifiedName(); } return new ClassId( FqName.fromSegments(packageFqName), FqName.fromSegments(relativeClassName), local); }
/** * Construct a GraphPath based on the given state by following back-edge fields all the way back * to the origin of the search. This constructs a proper Java list of states (allowing random * access etc.) from the predecessor information left in states by the search algorithm. * * <p>Optionally re-traverses all edges backward in order to remove excess waiting time from the * final itinerary presented to the user. * * @param s - the state for which a path is requested * @param optimize - whether excess waiting time should be removed * @param options - the traverse options used to reach this state */ public GraphPath(State s, boolean optimize) { this.rctx = s.getContext(); this.back = s.getOptions().isArriveBy(); /* Put path in chronological order, and optimize as necessary */ State lastState; walkDistance = s.getWalkDistance(); if (back) { lastState = optimize ? s.optimize() : s.reverse(); } else { lastState = optimize ? s.optimize().reverse() : s; } // DEBUG // lastState = s; /* * Starting from latest (time-wise) state, copy states to the head of a list in reverse * chronological order. List indices will thus increase forward in time, and backEdges will * be chronologically 'back' relative to their state. */ this.states = new LinkedList<State>(); this.edges = new LinkedList<Edge>(); for (State cur = lastState; cur != null; cur = cur.getBackState()) { states.addFirst(cur); if (cur.getBackEdge() != null) edges.addFirst(cur.getBackEdge()); } }
/** Sorts the static LinkedList mainlineLinks in the order they appear on the freeway */ private LinkedList<Link> recursiveLinkSort(LinkedList<Link> links2) { if (links2.size() == 1) { return links2; } else { boolean swapMade = false; ListIterator<Link> itr1 = links2.listIterator(); while (itr1.hasNext()) { Link temp = itr1.next(); int tempindex = itr1.nextIndex(); // if this loop makes any switches, set the flag to true if (links2.getFirst().getUpNode().getNodeID() == temp.getDownNode().getNodeID()) { swapMade = true; links2.addFirst(temp); links2.remove(tempindex); return this.recursiveLinkSort(links2); } } if (!swapMade) { // assign last n-1 links to links3 LinkedList<Link> links3 = new LinkedList<Link>(); Link temp = links2.getFirst(); links2.removeFirst(); links3 = this.recursiveLinkSort(links2); links3.addFirst(temp); return links3; } else { return links2; } } }
/** * Constructs a path to a given node, for a given set of predecessors. The result is a list of * alternating Node/Relationship. * * @param node The start node * @param predecessors The predecessors set * @param includeNode Boolean which determines if the start node should be included in the paths * @param backwards Boolean, if true the order of the nodes in the paths will be reversed * @return A path as a list of alternating Node/Relationship. */ public static List<PropertyContainer> constructSinglePathToNode( Node node, Map<Node, List<Relationship>> predecessors, boolean includeNode, boolean backwards) { LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>(); if (includeNode) { if (backwards) { path.addLast(node); } else { path.addFirst(node); } } Node currentNode = node; List<Relationship> currentPreds = predecessors.get(currentNode); // Traverse predecessors until we have added a node without predecessors while (currentPreds != null && currentPreds.size() != 0) { // Get next node Relationship currentRelationship = currentPreds.get(0); currentNode = currentRelationship.getOtherNode(currentNode); // Add current if (backwards) { path.addLast(currentRelationship); path.addLast(currentNode); } else { path.addFirst(currentRelationship); path.addFirst(currentNode); } // Continue with the next node currentPreds = predecessors.get(currentNode); } return path; }
private List<String> _getIconNames(String baseSelector) { LinkedList<String> names = new LinkedList<String>(); StringBuilder builder = new StringBuilder(64); builder.append(baseSelector); int suffixLength = SkinSelectors.ICON_SUFFIX.length(); int baseIndex = builder.length(); builder.append(SkinSelectors.ICON_SUFFIX); names.addFirst(builder.toString()); builder.delete(baseIndex, baseIndex + suffixLength); if (isActive() || isSelected()) { builder.append(_SUFFIX_ACTIVE); } else if (isVisited()) { builder.append(_SUFFIX_VISITED); } else { builder.append(_SUFFIX_UNVISITED); } baseIndex = builder.length(); builder.append(SkinSelectors.ICON_SUFFIX); names.addFirst(builder.toString()); builder.delete(baseIndex, baseIndex + suffixLength); if (isDisabled()) { builder.append(_SUFFIX_READ_ONLY); builder.append(SkinSelectors.ICON_SUFFIX); names.addFirst(builder.toString()); } return names; }
// create a complete binary tree based on the array Node createCompleteTree(int[] array) { // special cases if (array.length == 0) return null; if (array.length == 1) return new Node(array[0]); LinkedList<Node> Nodes = new LinkedList<>(); Node root = new Node(array[0]); Nodes.add(root); int index = 1; while (!Nodes.isEmpty()) { Node temp = Nodes.pollLast(); // add left child Node newNode = new Node(array[index]); temp.leftChild = newNode; Nodes.addFirst(newNode); index++; // check whether out of range if (index == array.length) break; // add right child newNode = new Node(array[index]); temp.rightChild = newNode; Nodes.addFirst(newNode); index++; // check whether out of range if (index == array.length) break; } return root; }
void mixLists( LinkedList<Integer> left, LinkedList<Integer> right, ArrayList<LinkedList<Integer>> mix, LinkedList<Integer> before) { if (before.isEmpty() || right.isEmpty()) { LinkedList<Integer> l = new LinkedList<>(); l = (LinkedList<Integer>) before.clone(); l.addAll(left); l.addAll(right); mix.add(l); return; } int hl = left.removeFirst(); before.addLast(hl); mixLists(left, right, mix, before); before.removeLast(); left.addFirst(hl); int hr = right.removeFirst(); before.addLast(hr); mixLists(left, right, mix, before); before.removeLast(); right.addFirst(hr); }
public void weavelists( LinkedList<Integer> first, LinkedList<Integer> second, ArrayList<LinkedList<Integer>> results, LinkedList<Integer> prefix) { if (first.size() == 0 || second.size() == 0) { LinkedList<Integer> result = (LinkedList<Integer>) prefix.clone(); result.addAll(first); result.addAll(second); results.add(result); return; } int headFirst = first.removeFirst(); prefix.addLast(headFirst); weavelists(first, second, results, prefix); prefix.removeLast(); first.addFirst(headFirst); int secondHead = second.removeFirst(); prefix.addLast(secondHead); weavelists(first, second, results, prefix); prefix.removeLast(); second.addFirst(secondHead); }
public void add(TaggedImage img, String label) { images.addFirst(img); labels.addFirst(label); while (images.size() > NUM_TO_CACHE) { images.removeLast(); labels.removeLast(); } }
/** * return a list of base classes of an {@link ProtocolClass}, parent classes first. The list * includes the class itself * * @param pc * @return */ private LinkedList<ProtocolClass> getBaseClasses(ProtocolClass pc) { LinkedList<ProtocolClass> classes = new LinkedList<ProtocolClass>(); classes.addFirst(pc); while (pc.getBase() != null) { pc = pc.getBase(); classes.addFirst(pc); } return classes; }
public void getCoordinates( LinkedList<Double> xCoords, LinkedList<Double> yCoords, BasicDiskTable in) { in.open(); for (String[] line = in.readLine(); line != null; line = in.readLine()) { xCoords.addFirst(Double.parseDouble(line[xCoordinateIndex])); yCoords.addFirst(Double.parseDouble(line[yCoordinateIndex])); } in.close(); }
/** * return a list of base classes of an {@link ActorClass}, parent classes first. The list includes * the class itself * * @param ac * @return */ private LinkedList<ActorClass> getBaseClasses(ActorClass ac) { LinkedList<ActorClass> classes = new LinkedList<ActorClass>(); if (ac != null) { classes.addFirst(ac); while (ac.getBase() != null) { ac = ac.getBase(); classes.addFirst(ac); } } return classes; }
private TreePath getPath(PsiElement element) { if (element == null) return null; LinkedList list = new LinkedList(); while (element != null && element != _rootElement) { list.addFirst(element); element = element.getParent(); } if (element != null) list.addFirst(element); TreePath treePath = new TreePath(list.toArray()); debug("root=" + _rootElement + ", treePath=" + treePath); return treePath; }
/** * Implemented as specified by {@link EventBus}. * * @see EventBus#post(AgentEvent) */ public void post(AgentEvent e) { if (e == null) throw new NullPointerException("No event."); switch (state) { case IDLE: state = DISPATCHING; eventQueue.addFirst(e); while (!eventQueue.isEmpty()) dispatch(); state = IDLE; break; case DISPATCHING: eventQueue.addFirst(e); } }
/** * add * * @param historyList * @param maxHistoryLength max. length of history or HISTORY_LENGTH_INFINTE * @param direction history direction order * @param addEntry */ private static void add( LinkedList<String> historyList, int maxHistoryLength, Directions direction, String addEntry) { switch (direction) { case ASCENDING: { String lastEntry = historyList.peekLast(); if ((lastEntry == null) || !lastEntry.equals(addEntry)) { historyList.add(addEntry); while (historyList.size() > maxHistoryLength) { historyList.removeFirst(); } } } break; case DESCENDING: { String firstEntry = historyList.peekFirst(); if ((firstEntry == null) || !firstEntry.equals(addEntry)) { historyList.addFirst(firstEntry); while (historyList.size() > maxHistoryLength) { historyList.removeLast(); } } } break; case SORTED: { boolean existsFlag = false; for (String entry : historyList) { if (entry.equals(addEntry)) { existsFlag = true; break; } } if (!existsFlag) { historyList.addFirst(addEntry); Collections.sort( historyList, new Comparator<String>() { public int compare(String data0, String data1) { return data0.compareTo(data1); } }); while (historyList.size() > maxHistoryLength) { historyList.removeLast(); } } } break; } }
private List<LocNode> getNodeList(String locStr) { LinkedList<LocNode> nodeList = new LinkedList<LocNode>(); // 查找符合locStr的节点 Element locElement = locData.select("[Name=" + locStr + "]").first(); if (locElement != null) { nodeList.addFirst(LocNode.parseNode(locElement)); while ((locElement = locElement.parent()) != null) { LocNode curNode = LocNode.parseNode(locElement); if (curNode != null) nodeList.addFirst(curNode); else break; } } return nodeList; }
// called under "this" lock private void mapAlertByGroupUid(Alert alert) { AlertGroup alertGroup = alertGroupByGroupUidMapping.get(alert.getGroupUid()); boolean needsNewAlertGroup = (alertGroup != null && alertGroup.isResolved()); if (alertGroup == null || needsNewAlertGroup) { alertGroup = new AlertGroup(); alertGroup.addAlert(alert); alertGroupByGroupUidMapping.put(alert.getGroupUid(), alertGroup); alertGroupList.addFirst(alertGroup); } else { alertGroup.addAlert(alert); alertGroupList.remove(alertGroup); alertGroupList.addFirst(alertGroup); } }
@SuppressWarnings("all") public String execute() { String classPathXml = params.get(SzjdeConstants.PARAM_CLASSPATHXML); String varNamesStr = params.get(SzjdeConstants.PARAM_VAR_NAMES); CompilerContext cc = getCompilerContext(classPathXml); ReflectAbleClassLoader classLoader = cc.getClassLoader(); String[] varNames = varNamesStr.split(","); StringBuilder sb = new StringBuilder(); LinkedList<Class> superClassList = new LinkedList<Class>(); for (String name : varNames) { Class aClass = null; try { aClass = classLoader.loadClass(name); } catch (ClassNotFoundException e) { } if (aClass == null) continue; Class tmpClass = aClass; while (true) { if (tmpClass == null) break; superClassList.addFirst(tmpClass); Class[] itfs = tmpClass.getInterfaces(); for (Class itf : itfs) { superClassList.addFirst(itf); } tmpClass = tmpClass.getSuperclass(); } } sb.append("Mandatory Methods:\n\n"); for (Class aClass : superClassList) { List<String> methods = addMethods(aClass, true); if (methods.size() == 0) continue; sb.append(" ").append(aClass.getName()).append("\n"); for (String method : methods) { sb.append(" ").append(method).append("\n"); } } sb.append("\n"); sb.append("Optional Methods:\n\n"); for (Class aClass : superClassList) { List<String> methods = addMethods(aClass, false); if (methods.size() == 0) continue; sb.append(" ").append(aClass.getName()).append("\n"); for (String method : methods) { sb.append(" ").append(method).append("\n"); } } return sb.toString(); }
/* * Returns a list of successor states for state u, since this is an * 8-way graph this list contains all of a cells neighbours. Unless * the cell is occupied, in which case it has no successors. */ private LinkedList<State> getSucc(State u) { LinkedList<State> s = new LinkedList<State>(); State tempState; if (occupied(u)) return s; // Generate the successors, starting at the immediate right, // Moving in a clockwise manner tempState = new State(u.x + 1, u.y, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x + 1, u.y + 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x, u.y + 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x - 1, u.y + 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x - 1, u.y, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x - 1, u.y - 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x, u.y - 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); tempState = new State(u.x + 1, u.y - 1, new Pair(-1.0, -1.0)); s.addFirst(tempState); return s; }
/** Enqueues the Runnable object, and executes it on a processor thread. */ public void dispatch(Runnable runner, boolean isLIFO) { isLIFO = false; synchronized (queue) { if (threadCount < maxThreadCount) { if (isLIFO) { queue.addFirst(runner); } else { queue.addLast(runner); } Thread processor = new Thread(this + " Processor") { public void run() { processEvents(); } }; threadCount++; // The processor thread must not be a daemon, // or else the Java VM might stop before // all runnables have been processed. try { processor.setDaemon(false); } catch (SecurityException e) { e.printStackTrace(); } try { processor.setPriority(priority); } catch (SecurityException e) { e.printStackTrace(); } processor.start(); return; } else if (blockingPolicy == ENQUEUE_WHEN_BLOCKED) { if (isLIFO) { queue.addFirst(runner); } else { queue.addLast(runner); } return; } } // implicit: if (threadCount >= maxThreadCount && blockingPolicy == RUN_WHEN_BLOCKED) runner.run(); }
/** * Reconstruct a path from start to goal using the parentMap * * @param parentMap the HashNode map of children and their parents * @param start The starting location * @param goal The goal location * @return The list of intersections that form the shortest path from start to goal (including * both start and goal). */ private List<GeographicPoint> reconstructPath( HashMap<MapNode, MapNode> parentMap, MapNode start, MapNode goal) { LinkedList<GeographicPoint> path = new LinkedList<GeographicPoint>(); MapNode current = goal; while (!current.equals(start)) { path.addFirst(current.getLocation()); current = parentMap.get(current); } // add start path.addFirst(start.getLocation()); return path; }
/* process field edge constraint */ public void process(FieldConstraint c) { Node csrc = c.src.getRep(); Node cdst = c.dst.getRep(); assert (csrc.graph == this); assert (cdst.graph == this); if (heapfix && csrc.isheap && !cdst.isheap) w.addFirst(new UnifyConstraint(csrc, cdst)); Collection<FieldEdge> fed = fedges.get(c.field); if (secondary_index[9]) { FieldEdge e = csrc.outfields.get(c.field); if (e != null) { if (e.dst != cdst) w.addFirst(new UnifyConstraint(e.dst, cdst)); return; } } else { if (fed != null) for (FieldEdge e : fed) { Node esrc = e.src.getRep(); Node edst = e.dst.getRep(); assert (e.field.equals(c.field)); if (esrc == csrc) { if (edst != cdst) w.addFirst(new UnifyConstraint(edst, cdst)); return; } } } FieldEdge e = new FieldEdge(csrc, cdst, c.field); if (fed == null) { fed = new ArrayList<FieldEdge>(); fedges.put(c.field, fed); } fed.add(e); if (secondary_index[1]) { csrc.outfields.put(e.field, e); addInField(cdst, e.field, e); } // Merge nodes according to Tag information Node find = Options.detailed.value ? reachesTag(csrc, cdst.tag, new HashSet<Node>()) : containsTag(cdst.tag); if (find != null) w.addFirst(new UnifyConstraint(cdst, find)); }
@Override public void addAssociationClass(AssociationClass component) { for (final IComponentsObserver c : observers) c.addAssociationClass(component); addComponent(component); entities.addFirst(component); }
/** * Get the resource name given a full filename. * * @param fileName the full filename (which must be inside the directory) * @return the resource name (i.e., the filename with the directory stripped off) */ String getResourceName(String fileName) { // FIXME: there is probably a more robust way to do this // Strip off the directory part. String dirPath = directory.getPath(); if (!fileName.startsWith(dirPath)) { throw new IllegalStateException("Filename " + fileName + " not inside directory " + dirPath); } // The problem here is that we need to take the relative part of the filename // and break it into components that we can then reconstruct into // a resource name (using '/' characters to separate the components). // Unfortunately, the File class does not make this task particularly easy. String relativeFileName = fileName.substring(dirPath.length()); File file = new File(relativeFileName); LinkedList<String> partList = new LinkedList<String>(); do { partList.addFirst(file.getName()); } while ((file = file.getParentFile()) != null); StringBuilder buf = new StringBuilder(); for (String part : partList) { if (buf.length() > 0) { buf.append('/'); } buf.append(part); } return buf.toString(); }
@Override public void addClass(ClassEntity component) { for (final IComponentsObserver c : observers) c.addClass(component); addComponent(component); entities.addFirst(component); }
/** This method cannot be called directly. */ public void keyTyped(KeyEvent e) { int keyCode = e.getKeyCode(); System.out.println(keyCode); switch (keyCode) { case KeyEvent.VK_W: // handle up System.out.println("up?"); break; case KeyEvent.VK_DOWN: // handle down break; case KeyEvent.VK_LEFT: // handle left break; case KeyEvent.VK_RIGHT: // handle right break; } System.out.println(e.getKeyChar()); if (e.getKeyChar() == KeyEvent.VK_UP) { System.out.println("up arrow pressed"); } synchronized (keyLock) { keysTyped.addFirst(e.getKeyChar()); } }
public List<StockInfo> findStockInfoBtw(StockInfo stock, int previousDays, int followingDays) { LinkedList<StockInfo> selected = new LinkedList<>(); int beginIndex = 0; List<StockInfo> stocks = getStocks(stock.getTicker()); for (int i = 0; i < stocks.size(); i++) { if (stocks.get(i).getTradeDate().equals(stock.getTradeDate())) { beginIndex = i; selected.add(stocks.get(beginIndex)); break; } } for (int i = 1; i <= previousDays; i++) { StockInfo addingStock = null; try { addingStock = stocks.get(beginIndex + i); selected.addFirst(addingStock); } catch (Exception e) { } } for (int i = 1; i <= followingDays; i++) { StockInfo addingStock = null; try { addingStock = stocks.get(beginIndex - i); } catch (Exception e) { } selected.addLast(addingStock); } return selected; }
@Override public synchronized List<T> getTopK() { Comparator<T> comparator = new Comparator<T>() { public int compare(T key1, T key2) { return Longs.compare(counts.get(key1), counts.get(key2)); } }; PriorityQueue<T> topK = new PriorityQueue<T>(k, comparator); for (Map.Entry<T, Long> entry : counts.entrySet()) { if (topK.size() < k) { topK.offer(entry.getKey()); } else if (entry.getValue() > counts.get(topK.peek())) { topK.offer(entry.getKey()); topK.poll(); } } LinkedList<T> sortedTopK = new LinkedList<T>(); while (!topK.isEmpty()) { sortedTopK.addFirst(topK.poll()); } return sortedTopK; }
/* process call edge constraint */ public void process(CallConstraint c) { Node csrc = c.ncaller.getRep(); Node cdst = c.ncallee.getRep(); assert (cdst.graph == this); if (heapfix && csrc.graph == this && !csrc.isheap && cdst.isheap) w.addFirst(new UnifyConstraint(csrc, cdst)); Collection<CallEdge> ced = cedges.get(c.call); if (ced != null) for (CallEdge e : ced) { Node esrc = e.src.getRep(); Node edst = e.dst.getRep(); if (edst == cdst && e.call.equals(c.call)) { if (esrc != csrc) { Graph g = esrc.graph; assert (g != this || !Options.mergeGraphs.value); g.w.addFirst(new UnifyConstraint(esrc, csrc)); } return; } } else { ced = new ArrayList<CallEdge>(); cedges.put(c.call, ced); } ced.add(new CallEdge(csrc, cdst, c.call)); }
public List<T> asSortedList() { LinkedList<T> list = new LinkedList<T>(); for (Iterator<T> i = elements.iterator(); i.hasNext(); ) { list.addFirst(i.next()); } return list; }