示例#1
0
    void startIdleState() {
      lock.lock();
      try {
        final Thread currentThread = Thread.currentThread();
        final Thread currentIdleThread = threadsRequestingIdle.peekFirst();
        if (currentIdleThread == currentThread) {
          assert idleStateCount > 0;
          ++idleStateCount;
          assert idleStateCount > 0;
          return;
        }

        threadsRequestingIdle.add(currentThread);

        while ((activitiyCount > 0) || (threadsRequestingIdle.getFirst() != currentThread))
          condition.awaitUninterruptibly();

        assert idleStateCount == 0;
        assert activitiyCount == 0;
        assert threadsRequestingIdle.getFirst() == currentThread;
        idleStateCount = 1;

      } finally {
        lock.unlock();
      }
    }
示例#2
0
  public void testGetMinTransaction() throws Exception {
    LinkedList list = new LinkedList();
    for (int i = 0; i < 100; i++) {
      TestClientTransaction tx = new TestClientTransaction();
      tx.sequenceID = new SequenceID(i);
      tx.txID = new TransactionID(i);
      tx.txnType = TxnType.NORMAL;
      list.add(tx);
      writer.addTransaction(tx);
    }

    writer.wait4AllTxns2Serialize();

    assertSame(
        ((ClientTransaction) list.getFirst()).getSequenceID(), writer.getMinTransactionSequence());

    // remove some from the middle and make sure the min is constant
    for (int i = 50; i < 55; i++) {
      ClientTransaction tx = (ClientTransaction) list.remove(i);
      writer.removeTransaction(tx.getTransactionID());
      assertSame(
          ((ClientTransaction) list.getFirst()).getSequenceID(),
          writer.getMinTransactionSequence());
    }

    // now remove the leastmost transaction and make sure the min increases.
    for (Iterator i = list.iterator(); i.hasNext(); ) {
      ClientTransaction tx = (ClientTransaction) i.next();
      assertSame(
          ((ClientTransaction) list.getFirst()).getSequenceID(),
          writer.getMinTransactionSequence());
      i.remove();
      writer.removeTransaction(tx.getTransactionID());
    }
  }
  private void initiateQuery(long bssid) {
    LinkedList<QuerySet> queryEntries = mBssQueues.get(bssid);
    if (queryEntries == null) {
      return;
    } else if (queryEntries.isEmpty()) {
      mBssQueues.remove(bssid);
      return;
    }

    QuerySet querySet = queryEntries.getFirst();
    QueryEntry queryEntry = querySet.peek();
    if (queryEntry.bumpRetry() >= RetryCount) {
      QueryEntry newEntry = querySet.pop();
      if (newEntry == null) {
        // No more entries in this QuerySet, advance to the next set.
        querySet.getOsuInfo().setIconStatus(OSUInfo.IconStatus.NotAvailable);
        queryEntries.removeFirst();
        if (queryEntries.isEmpty()) {
          // No further QuerySet on this BSSID, drop the bucket and bail.
          mBssQueues.remove(bssid);
          return;
        } else {
          querySet = queryEntries.getFirst();
          queryEntry = querySet.peek();
          queryEntry.bumpRetry();
        }
      }
    }
    mOSUManager.doIconQuery(bssid, queryEntry.getKey().getFileName());
  }
示例#4
0
  /** 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;
      }
    }
  }
示例#5
0
  private void readGraph() throws IOException {
    InputStream is = ProgrammingSet4.class.getResourceAsStream("SCC.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    graph = new HashMap<Integer, List<Integer>>();
    rGraph = new HashMap<Integer, List<Integer>>();

    String l = null;
    while ((l = reader.readLine()) != null) {
      LinkedList<Integer> line = readEdge(l);

      List<Integer> edges = graph.get(line.getFirst());
      if (edges == null) {
        edges = new ArrayList<Integer>();
        graph.put(line.getFirst(), edges);
      }
      edges.add(line.getLast());

      List<Integer> rEdges = rGraph.get(line.getLast());
      if (rEdges == null) {
        rEdges = new ArrayList<Integer>();
        rGraph.put(line.getLast(), rEdges);
      }
      rEdges.add(line.getFirst());
    }

    reader.close();
  }
示例#6
0
  public void testWaitPolicyWithShutdownExecutor() throws Exception {
    assertEquals(0, SleepyTask.activeTasks.get());

    // wants to wait forever, but will fail immediately
    executor.setRejectedExecutionHandler(new LastRejectedWaitPolicy());
    executor.shutdown();

    // create a task
    List tasks = new ArrayList();
    tasks.add(new SleepyTask("rejected", 1000));

    // should fail and return immediately
    LinkedList submitters = this.execute(tasks);
    assertFalse(submitters.isEmpty());

    // let submitted tasks run
    Thread.sleep(1000);

    LinkedList exceptions = threadGroup.collectedExceptions();
    assertEquals(1, exceptions.size());

    Map.Entry threadFailure =
        (Map.Entry) ((Map) (exceptions.getFirst())).entrySet().iterator().next();
    assertEquals(submitters.getFirst(), threadFailure.getKey());
    assertEquals(RejectedExecutionException.class, threadFailure.getValue().getClass());
    assertEquals(0, SleepyTask.activeTasks.get());
  }
示例#7
0
  static boolean maybe(LinkedList<Item>[] buf, int d, int checkedRow, int checkedColumn) {

    LinkedList<Item> e;

    for (int row = 0; row < 9; row++) {
      if (checkedRow == row) continue;

      e = buf[row * 9 + checkedColumn];

      if (e.getFirst().value == d) {
        return false;
      }

      for (Item item : e) {
        if (item.value == d && item.canbe()) {
          return false;
        }
      }
    }
    for (int column = 0; column < 9; column++) {
      if (checkedColumn == column) continue;

      e = buf[checkedRow * 9 + column];

      if (e.getFirst().value == d) {
        return false;
      }

      for (Item item : e) {
        if (item.value == d && item.canbe()) {
          return false;
        }
      }
    }

    int subGridStartRow = checkedRow - checkedRow % 3;
    int subGridStartColumn = checkedColumn - checkedColumn % 3;

    for (int row = subGridStartRow; row < subGridStartRow + 3; row++) {
      for (int column = subGridStartColumn; column < subGridStartColumn + 3; column++) {
        e = buf[row * 9 + column];

        if (checkedColumn == column) continue;

        if (e.getFirst().value == d) {
          return false;
        }

        for (Item item : e) {
          if (item.value == d && item.canbe()) {
            return false;
          }
        }
      }
    }

    return true;
  }
示例#8
0
 protected Object getFirst() {
   Object object = null;
   if (data.size() > 0) {
     object = data.getFirst();
   } else if (stored.size() > 0) {
     object = readValue((String) stored.getFirst());
   }
   return object;
 }
示例#9
0
  private ArrayList<String> helper(WifiMapData unknown) {
    Vd2_3MapData unknownStat = new Vd2_3MapData(unknown);
    // debug("here stat");
    // debug(unknownStat, unknownStat.fullScan.size());
    LinkedList<LocationEvaluation> possible = new LinkedList<LocationEvaluation>();
    ArrayList<String> possibleLocations = new ArrayList<String>();

    for (String locationID : cache.keySet()) {
      LocationEvaluation eval = new LocationEvaluation(locationID);
      possible.add(eval);
    }

    if (possible.isEmpty()) {
      System.out.println("+++++++++++++++++++++++++++++++++");
      return possibleLocations;
    }

    {
      // Remove the ones that has too little low-var Aps
      for (LocationEvaluation eval : possible) {
        eval.score = nHavingLowVariance(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      // debug(possible);

      double min = possible.getFirst().score - maxAbsenceAP;
      while (!possible.isEmpty() && possible.getLast().score < min) possible.removeLast();
    }

    {
      // Remove the ones that miss too much Low-var APs
      for (LocationEvaluation eval : possible) {
        eval.score = nMissingLowVariance(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      // debug(possible);
      double min = possible.getFirst().score - maxAbsenceAP;
      while (!possible.isEmpty() && possible.getLast().score < min) possible.removeLast();
    }

    {
      // Sort the average this distance
      for (LocationEvaluation eval : possible) {
        eval.score = differenceAverage(cache.get(eval.name), unknownStat);
      }
      Collections.sort(possible);
      while (!possible.isEmpty() && possible.getLast().score < VERY_NEGATIVE) {
        possible.removeLast();
      }
    }

    for (int i = 0; i < possible.size(); ++i) {
      possibleLocations.add(possible.get(i).name);
    }

    return possibleLocations;
  }
示例#10
0
  @Override
  public int readData(
      int track, long positionUs, MediaFormatHolder formatHolder, SampleHolder sampleHolder) {
    Assertions.checkState(state == STATE_ENABLED);
    downstreamPositionUs = positionUs;

    if (pendingDiscontinuity || isPendingReset()) {
      return NOTHING_READ;
    }

    boolean haveSamples = !sampleQueue.isEmpty();
    BaseMediaChunk currentChunk = mediaChunks.getFirst();
    while (haveSamples
        && mediaChunks.size() > 1
        && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) {
      mediaChunks.removeFirst();
      currentChunk = mediaChunks.getFirst();
    }

    Format format = currentChunk.format;
    if (!format.equals(downstreamFormat)) {
      notifyDownstreamFormatChanged(format, currentChunk.trigger, currentChunk.startTimeUs);
    }
    downstreamFormat = format;

    if (haveSamples || currentChunk.isMediaFormatFinal) {
      MediaFormat mediaFormat = currentChunk.getMediaFormat();
      if (!mediaFormat.equals(downstreamMediaFormat)) {
        formatHolder.format = mediaFormat;
        formatHolder.drmInitData = currentChunk.getDrmInitData();
        downstreamMediaFormat = mediaFormat;
        return FORMAT_READ;
      }
      // If mediaFormat and downstreamMediaFormat are equal but different objects then the equality
      // check above will have been expensive, comparing the fields in each format. We update
      // downstreamMediaFormat here so that referential equality can be cheaply established during
      // subsequent calls.
      downstreamMediaFormat = mediaFormat;
    }

    if (!haveSamples) {
      if (loadingFinished) {
        return END_OF_STREAM;
      }
      return NOTHING_READ;
    }

    if (sampleQueue.getSample(sampleHolder)) {
      boolean decodeOnly = sampleHolder.timeUs < lastSeekPositionUs;
      sampleHolder.flags |= decodeOnly ? C.SAMPLE_FLAG_DECODE_ONLY : 0;
      onSampleRead(currentChunk, sampleHolder);
      return SAMPLE_READ;
    }

    return NOTHING_READ;
  }
示例#11
0
 public boolean removeAnd(SeqCond and) {
   for (Iterator<LinkedList<SeqCond>> it = sequenceCondition.iterator(); it.hasNext(); ) {
     LinkedList<SeqCond> list = it.next();
     if (list.size() == 1 && list.getFirst().id == and.id && list.getFirst().state == and.state) {
       sequenceCondition.remove(list);
       return true;
     }
   }
   return false;
 }
  public static boolean isBinaryTreeBST(BinaryTreeNode<Integer> tree) {
    LinkedList<QueueEntry> BFSQueue = new LinkedList<>();
    BFSQueue.addLast(new QueueEntry(tree, Integer.MIN_VALUE, Integer.MAX_VALUE));

    while (!BFSQueue.isEmpty()) {
      if (BFSQueue.getFirst().treeNode != null) {
        if (BFSQueue.getFirst().treeNode.getData() < BFSQueue.getFirst().lowerBound
            || BFSQueue.getFirst().treeNode.getData() > BFSQueue.getFirst().upperBound) {
          return false;
        }

        BFSQueue.addLast(
            new QueueEntry(
                BFSQueue.getFirst().treeNode.getLeft(),
                BFSQueue.getFirst().lowerBound,
                BFSQueue.getFirst().treeNode.getData()));
        BFSQueue.addLast(
            new QueueEntry(
                BFSQueue.getFirst().treeNode.getRight(),
                BFSQueue.getFirst().treeNode.getData(),
                BFSQueue.getFirst().upperBound));
      }
      BFSQueue.removeFirst();
    }
    return true;
  }
示例#13
0
 private void updateEtaAndSpeed() {
   long now = dates.getFirst();
   long past = dates.getLast();
   long loadedKbNow = loaded.getFirst();
   long loadedKbPast = loaded.getLast();
   long kiloBytesRemaining = max - loadedKbNow;
   // speed kb/
   speedKbPerSecond = (float) ((double) (loadedKbNow - loadedKbPast)) / ((now - past) / 1000);
   timeleft = (long) (kiloBytesRemaining / speedKbPerSecond);
   eta.setTime(now + timeleft * 1000);
 }
示例#14
0
  public final void testGetBlockListForFile() {
    HeaderBlock hBlock = tracker.getLatestHeaderBlockForFile(FILENAME);
    assertNotNull(hBlock);
    assertEquals(hBlock1.getBlockId(), hBlock.getBlockId());

    LinkedList<Long> blocksIds = hBlock.getAssociatedDataBlockId();
    assertEquals(2, blocksIds.size());
    assertEquals(dBlock1.getBlockId(), blocksIds.getLast().longValue());
    assertEquals(dBlock2.getBlockId(), blocksIds.getFirst().longValue());
    MetaDataBlock metaBlock = hBlock.getMetaDataForDataBlock(blocksIds.getFirst());
  }
  // Point : Forest to Tree
  //
  // While T has more than one component
  //  For each component C of T :
  //   Begin with an empty set of edges S
  //   For each vertex v in C :
  //    Find the cheapest edge from v to a vertex outside of C, and add it to S
  //   Add the cheapest edge in S to T
  public WeightUnDirectedGraph MSTBySollin() {

    LinkedList<WeightUnDirectedGraph> graphLinkedList = new LinkedList<>();

    for (int i = 0; i < vertices.size(); i++) {
      graphLinkedList.add(new WeightUnDirectedGraph());
    }

    // 각각의 vertex에 대해서 graph라고 만듦
    for (int i = 0; i < vertices.size(); i++) {
      graphLinkedList.get(i).insertVertex(new Data(vertices.get(i).getData().id));
    }

    int index = 0;
    WeightUnDirectedGraph currentGraph;

    // While T has more than one component:
    while (graphLinkedList.size() > 1) {

      if (index >= graphLinkedList.size()) index = 0;

      // For each component C of T:
      currentGraph = graphLinkedList.get(index);

      // Begin with an empty set of edges S
      LinkedList<Edge> edgeList = new LinkedList<>();

      // For each vertex v in C:
      for (Vertex currentVertex : currentGraph.vertices) {

        // Find the cheapest edge from v to a vertex outside of C, and add it to S

        // 현재 큰 그래프에서 찾음
        Vertex vertex = retrieveVertex(currentVertex.getData().id);

        for (Edge edge : vertex.getEdges()) {

          if (currentGraph.retrieveVertex(edge.getToVertex().getData().id) == null)
            insertEdgeToList(edgeList, edge);
        }
      }

      int graphIndex = findGraphIndex(graphLinkedList, edgeList.getFirst().getToVertex());

      // Add the cheapest edge in S to T
      if (mergeGraph(currentGraph, graphLinkedList.get(graphIndex), edgeList.removeFirst()))
        graphLinkedList.remove(graphIndex);

      index++;
    }

    return graphLinkedList.getFirst();
  }
示例#16
0
  public boolean addAnd(SeqCond and) {
    for (Iterator<LinkedList<SeqCond>> it = sequenceCondition.iterator(); it.hasNext(); ) {
      LinkedList<SeqCond> list = it.next();
      if (list.size() == 1 && list.getFirst().id == and.id && list.getFirst().state == and.state) {
        return false;
      }
    }
    LinkedList<SeqCond> s = new LinkedList<SeqCond>();
    s.add(and);

    sequenceCondition.add(s);
    return true;
  }
示例#17
0
  public static int[] maxInWindow(int[] array, int k) {
    if (k <= 0 || array == null || array.length == 0) {
      System.out.println("invalid input");
      return new int[0];
    }
    int len = array.length;
    int[] max = new int[len];
    if (k == 1) {
      System.arraycopy(array, 0, max, 0, len); // 复制一份,不影响原数组
    } else {
      LinkedList<Item> queue = new LinkedList<Item>();
      for (int i = 0; i < len; i++) {
        Item curItem = new Item(array[i], i);
        if (queue.isEmpty()) {
          queue.addLast(curItem);
        } else {
          Item head = queue.getFirst();
          int headIndex = head.getIndex();

          // 如果队首元素已不在窗口内,则删除
          if (headIndex < (i - k + 1)) {
            queue.removeFirst();
          }

          // 插入元素
          while (!queue.isEmpty()) {
            Item tail = queue.getLast();
            int tailValue = tail.getValue();
            if (tailValue < array[i]) {
              queue.removeLast();
              if (queue.isEmpty()) {
                queue.addLast(curItem);
                break;
              }
            } else if (tailValue > array[i]) {
              queue.addLast(curItem);
            } else {
              break;
            }
          }
        }

        // 每次操作后,队首元素为当前窗口的最大值
        if (!queue.isEmpty()) {
          max[i] = queue.getFirst().getValue();
        }
      }
    }
    return max;
  }
 @Override
 protected void onPostExecute(LinkedList<String> response) {
   if (dialog.isShowing()) dialog.dismiss();
   if (response.isEmpty()) {
     showMessage("Could not connect to server. Please try again later.");
   } else if (response.getFirst().equals("failure")) {
     Log.e(TAG, "failure querying open challenges from server");
   } else if (response.getFirst().equals("empty")) {
     showMessage("There are no challenges available at this time.");
   } else {
     String[] respStr = response.toArray(new String[0]);
     createChallengesCursor(respStr);
     populateChallengesList();
   }
 }
示例#19
0
  static void printGraph(String msg, LinkedList<Item>[] buf) {
    System.out.print("\n================================================\n" + msg);

    for (int row = 0; row < 9; row++) {
      System.out.println("\n");
      InnerFor:
      for (int column = 0; column < 9; column++) {
        System.out.print("\t");
        LinkedList<Item> e = buf[row * 9 + column];
        if (e.size() == 1) System.out.print("[" + e.getFirst().value + "]");
        else {
          for (Item t : e) {
            if (t.status == ItemStatus.ForceOK) {
              System.out.print("<" + t.value + ">");
              continue InnerFor;
            }
          }
          for (Item t : e) {
            if (t.status == ItemStatus.OK) {
              System.out.print("(" + t.value + ")");
              continue InnerFor;
            }
          }
          for (Item t : e) {
            if (t.status == ItemStatus.MaybeOK) System.out.print("" + t.value + "");
          }
          for (Item t : e) {
            if (t.status == ItemStatus.MaybeNot) System.out.print("-" + t.value + "");
          }
        }
      }
    }
  }
示例#20
0
  /**
   * maintains a list of last <i>committedLog</i> or so committed requests. This is used for fast
   * follower synchronization.
   *
   * @param request committed request
   */
  public void addCommittedProposal(Request request) {
    WriteLock wl = logLock.writeLock();
    try {
      wl.lock();
      if (committedLog.size() > commitLogCount) {
        committedLog.removeFirst();
        minCommittedLog = committedLog.getFirst().packet.getZxid();
      }
      if (committedLog.isEmpty()) {
        minCommittedLog = request.zxid;
        maxCommittedLog = request.zxid;
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
      try {
        request.getHdr().serialize(boa, "hdr");
        if (request.getTxn() != null) {
          request.getTxn().serialize(boa, "txn");
        }
        baos.close();
      } catch (IOException e) {
        LOG.error("This really should be impossible", e);
      }
      QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid, baos.toByteArray(), null);
      Proposal p = new Proposal();
      p.packet = pp;
      p.request = request;
      committedLog.add(p);
      maxCommittedLog = p.packet.getZxid();
    } finally {
      wl.unlock();
    }
  }
 static void testObjectSensitivity1() {
   LinkedList<String> list1 = new LinkedList<String>();
   LinkedList<String> list2 = new LinkedList<String>();
   list1.add(taintedString("abcd")); // source
   list2.add("123");
   assert (getTaint(list2.getFirst()) == 0);
 }
示例#22
0
  /** The sensor manager determines what all of the sensors are able to confirm. */
  @Override
  public Environment apply(Environment t) {

    /*
     * If we have any omniscient sensors, they will be the first sensor on
     * the list.
     */
    Sensor firstSensor = sensors.peek();
    if (firstSensor instanceof OmniscientSensor) {
      return firstSensor.apply(t);
    }

    /*
     * Otherwise, extract the different types of sensor
     */
    LinkedList<ProximitySensor> proximitySensors = new LinkedList<>();
    for (Sensor sensor : sensors) {
      if (sensor instanceof ProximitySensor) {
        proximitySensors.add((ProximitySensor) sensor);
      }
    }

    /*
     * If we have no other sensors, throw a problem
     */
    if (proximitySensors.size() == 0) {
      throw new RuntimeException("Sensor was not omniscient!");
    }

    return proximitySensors.getFirst().apply(t);
  }
    /**
     * Find the maximum weight matching of a path using dynamic programming.
     *
     * @param path a list of edges. The code assumes that the list of edges is a valid simple path,
     *     and that is not a cycle.
     * @return a maximum weight matching of the path
     */
    public Pair<Double, Set<E>> getMaximumWeightMatching(Graph<V, E> g, LinkedList<E> path) {
      int pathLength = path.size();

      // special cases
      switch (pathLength) {
        case 0:
          // special case, empty path
          return Pair.of(Double.valueOf(0d), Collections.emptySet());
        case 1:
          // special case, one edge
          E e = path.getFirst();
          double eWeight = g.getEdgeWeight(e);
          if (comparator.compare(eWeight, 0d) > 0) {
            return Pair.of(eWeight, Collections.singleton(e));
          } else {
            return Pair.of(Double.valueOf(0d), Collections.emptySet());
          }
      }

      // make sure work array has enough space
      if (a.length < pathLength + 1) {
        a = new double[pathLength + 1];
      }

      // first pass to find solution
      Iterator<E> it = path.iterator();
      E e = it.next();
      double eWeight = g.getEdgeWeight(e);
      a[0] = 0d;
      a[1] = (comparator.compare(eWeight, 0d) > 0) ? eWeight : 0d;
      for (int i = 2; i <= pathLength; i++) {
        e = it.next();
        eWeight = g.getEdgeWeight(e);
        if (comparator.compare(a[i - 1], a[i - 2] + eWeight) > 0) {
          a[i] = a[i - 1];
        } else {
          a[i] = a[i - 2] + eWeight;
        }
      }

      // reverse second pass to build solution
      Set<E> matching = new HashSet<>();
      it = path.descendingIterator();
      int i = pathLength;
      while (i >= 1) {
        e = it.next();
        if (comparator.compare(a[i], a[i - 1]) > 0) {
          matching.add(e);
          // skip next edge
          if (i > 1) {
            e = it.next();
          }
          i--;
        }
        i--;
      }

      // return solution
      return Pair.of(a[pathLength], matching);
    }
 private boolean bfs_cirle(boolean[] visited, Map<Integer, ArrayList<Integer>> graph, int i) {
   LinkedList<Integer> queue = new LinkedList<>();
   if (visited[i]) {
     return true;
   }
   visited[i] = true;
   queue.addLast(i);
   int top;
   List<Integer> edges;
   while (!queue.isEmpty()) {
     top = queue.getFirst();
     queue.removeFirst();
     edges = graph.get(top);
     if (edges != null) {
       for (int j = 0; j < edges.size(); j++) {
         if (visited[edges.get(j)]) {
           return true;
         } else {
           visited[edges.get(j)] = true;
           queue.add(edges.get(j));
         }
       }
     }
   }
   return false;
 }
  /**
   * Caches the path that was just found.
   *
   * @param smiod
   * @param endNode
   * @param startNode
   */
  private void cachePath(StreetMobilityInfoOD smiod, SegmentNode startNode, SegmentNode endNode) {
    if (hm != null && smiod.path.size() > MIN_CACHED_PATH_LENGTH) {
      Location startPoint = startNode.point;

      LinkedList ll = (LinkedList) hm.get(startPoint);
      if (ll == null) {
        ll = new LinkedList();
      }
      // make sure that path doesn't already exist...
      // must iterate through all of them...
      ListIterator li = ll.listIterator();
      boolean found = false;
      while (li.hasNext()) {
        LinkedList existingPath = (LinkedList) li.next();
        if (existingPath.getFirst().equals(startNode)
            && existingPath.getLast().equals(smiod.path.getLast())) {
          found = true;
          break;
        }
      }
      if (!found) {
        LinkedList newPath = (LinkedList) smiod.path.clone();
        newPath.addFirst(startNode);
        ll.add(newPath);
        hm.put(startPoint, ll);
      }
    }
  }
  /** Specified in Node */
  protected Node removeNeighbour(Node neighbour) {
    Iterator it = edges.iterator();
    Edge next;
    while (it.hasNext()) {
      next = (Edge) it.next();
      if (next.to == neighbour) {
        it.remove();
        break;
      }
    }

    // collapse this node if it has degree 2 after removal of neighbour
    if (edges.size() == 2) {
      Edge e1 = (Edge) edges.getFirst();
      Edge e2 = (Edge) edges.getLast();
      Edge ne1, ne2;

      ne1 = e1.to.addNeighbour(e2.to);
      ne2 = e2.to.addNeighbour(e1.to);
      ne1.backedge = ne2;
      ne2.backedge = ne1;
      e1.to.removeNeighbour(this);
      return e2.to.removeNeighbour(this);
    }
    return this;
  }
示例#27
0
  public String getLastPath() {
    if (mostRecentlyUsedHistory.isEmpty()) {
      return System.getProperty("user.home");
    }

    return mostRecentlyUsedHistory.getFirst();
  }
  @Test
  public void appenderStoresMessages() {
    MemoryAppender appender = new MemoryAppender();
    BasicConfigurator.configure(appender);

    Logger logger = Logger.getLogger(TEST_CATEGORY);
    logger.setLevel(Level.ERROR);

    logger.error(TEST_MESSAGE);

    LinkedList<LoggingEvent> events = appender.getEvents();
    assertEquals(1, events.size());

    LoggingEvent event = events.getFirst();
    assertEquals(Level.ERROR, event.getLevel());
    assertEquals(TEST_CATEGORY, event.getLoggerName());
    assertEquals(TEST_MESSAGE, event.getMessage());
    assertEquals(TEST_LOCATION, event.getLocationInformation().getClassName());

    appender.clear();
    assertEquals(0, events.size());

    logger.error(TEST_MESSAGE);
    assertEquals(1, appender.getEvents().size());
  }
 /**
  * Eat an identifier, possibly qualified (meaning that it is dotted). TODO AndyC Could create
  * complete identifiers (a.b.c) here rather than a sequence of them? (a, b, c)
  */
 private SpelNodeImpl eatPossiblyQualifiedId() {
   LinkedList<SpelNodeImpl> qualifiedIdPieces = new LinkedList<SpelNodeImpl>();
   Token node = peekToken();
   while (isValidQualifiedId(node)) {
     nextToken();
     if (node.kind != TokenKind.DOT) {
       qualifiedIdPieces.add(new Identifier(node.stringValue(), toPos(node)));
     }
     node = peekToken();
   }
   if (qualifiedIdPieces.isEmpty()) {
     if (node == null) {
       raiseInternalException(expressionString.length(), SpelMessage.OOD);
     }
     raiseInternalException(
         node.startpos,
         SpelMessage.NOT_EXPECTED_TOKEN,
         "qualified ID",
         node.getKind().toString().toLowerCase());
   }
   int pos =
       toPos(
           qualifiedIdPieces.getFirst().getStartPosition(),
           qualifiedIdPieces.getLast().getEndPosition());
   return new QualifiedIdentifier(
       pos, qualifiedIdPieces.toArray(new SpelNodeImpl[qualifiedIdPieces.size()]));
 }
  private static int getInitialY(EsbConnector connector, LinkedList<EsbNode> nodeList) {
    int y = 10;

    EObject eContainer = connector.eContainer();

    if (eContainer != null) {
      // FIXME : Remove hard-coded values
      if (eContainer instanceof ProxyService || eContainer instanceof APIResource) {
        y = 95; // Initial y of proxy, api resource output connector
      } else if (eContainer instanceof Sequences) {
        y = 146; // Initial y of sequence output connector
      } else {
        return y;
      }
      if (nodeList.size() > 0) {
        EditPart editpart = getEditpart(nodeList.getFirst());
        if (editpart != null) {
          if (!(editpart instanceof complexFiguredAbstractMediator)) {
            GraphicalEditPart gEditpart = (GraphicalEditPart) editpart;
            y = y - (gEditpart.getFigure().getPreferredSize().height / 2);
          }
        }
      }
    }

    return y;
  }