コード例 #1
1
ファイル: Dom.java プロジェクト: hk2-project/hk2
  /**
   * Given a master list and the new sub list, replace the items in the master list with the
   * matching items from the new sub list. This process works even if the length of the new sublist
   * is different.
   *
   * <p>For example, givn:
   *
   * <pre>
   * replace A by A':
   *   M=[A,B,C], S=[A'] => [A',B,C]
   *   M=[A,B,A,B,C], S=[A',A'] => [A',B,A',B,C]
   *
   * when list length is different:
   *   M=[A,A,B,C], S=[] => [B,C]
   *   M=[A,B,C], S=[A',A'] => [A',A',B,C]
   *   M=[B,C], S=[A',A'] => [B,C,A',A']
   * </pre>
   */
  private static List<Child> stitchList(
      List<Child> list, String name, List<? extends Child> newSubList) {
    List<Child> removed = new LinkedList<Child>();
    // to preserve order, try to put new itesm where old items are found.
    // if the new list is longer than the current list, we put all the extra
    // after the last item in the sequence. That is,
    // given [A,A,B,C] and [A',A',A'], we'll update the list to [A',A',A',B,C]
    // The 'last' variable remembers the insertion position.
    int last = list.size();

    ListIterator<Child> itr = list.listIterator();
    ListIterator<? extends Child> jtr = newSubList.listIterator();
    while (itr.hasNext()) {
      Child child = itr.next();
      if (child.name.equals(name)) {
        if (jtr.hasNext()) {
          itr.set(jtr.next()); // replace
          last = itr.nextIndex();
          removed.add(child);
        } else {
          itr.remove(); // remove
          removed.add(child);
        }
      }
    }

    // new list is longer than the current one
    if (jtr.hasNext()) list.addAll(last, newSubList.subList(jtr.nextIndex(), newSubList.size()));

    return removed;
  }
コード例 #2
1
ファイル: List1.java プロジェクト: TopCombine/ThinkingInJava
 // Must move to an element after add():
 // it.next(); // Remove the element that was just produced:
 // it.remove(); // Must move to an element after remove():
 // it.next(); // Change the element that was just produced:
 // it.set("47");
 public static void testVisual(List a) {
   print(a);
   List b = new ArrayList();
   fill(b);
   System.out.print("b = ");
   print(b);
   a.addAll(b);
   a.addAll(fill(new ArrayList()));
   print(a);
   // Shrink the list by removing all the elements beyond the first 1/2 of the list
   System.out.println(a.size());
   System.out.println(a.size() / 2);
   // a.removeRange(a.size()/2, a.size()/2 + 2);
   print(a);
   // Insert, remove, and replace elements
   // using aListIterator:
   ListIterator x = a.listIterator(a.size() / 2);
   x.add("one");
   print(a);
   System.out.println(x.next());
   x.remove();
   System.out.println(x.next());
   x.set("47");
   print(a); // Traverse the list backwards:
   x = a.listIterator(a.size());
   while (x.hasPrevious()) System.out.print(x.previous() + " ");
   System.out.println();
   System.out.println("testVisual finished");
 }
コード例 #3
0
  void tryToDeleteSegment(Point p) {
    if (points.size() < 3) return;

    LatLon start;
    start = findBigSegment(p);
    ListIterator<LatLon> it = points.listIterator();
    LatLon pp;
    boolean f = false;
    int i = 0, idx = -1;
    while (it.hasNext()) {
      pp = it.next();
      if (f && (fixed.contains(pp))) {
        // if end of line fragment reached
        lastIdx = idx;
        return;
      }
      if (f && (!it.hasNext())) {
        // if end of whole line reached
        closedFlag = false;
        it.remove();
        lastIdx = points.size() - 1;
        return;
      }

      // if we are deleting this segment
      if (f) it.remove();
      if (pp == start) {
        f = true;
        idx = i;
      } // next node should be removed
      i++;
    }
    lastIdx = points.size() - 1;
  }
コード例 #4
0
ファイル: Components.java プロジェクト: gotomypc/zk
  /**
   * Sorts the components in the list.
   *
   * @param list the list to be sorted
   * @param from the index of the first element (inclusive) to be sorted
   * @param to the index of the last element (exclusive) to be sorted
   * @param cpr the comparator to determine the order of the list.
   * @since 3.5.0
   */
  public static void sort(
      List<? extends Component> list, int from, int to, Comparator<? super Component> cpr) {
    final Component ary[] = CollectionsX.toArray(list, new Component[0], from, to);
    Arrays.sort(ary, cpr);

    ListIterator<? extends Component> it = list.listIterator(from);
    int j = 0, k = to - from;
    for (; it.hasNext() && --k >= 0; ++j) {
      if (it.next() != ary[j]) {
        it.remove();

        if (it.hasNext() && --k >= 0) {
          if (it.next() == ary[j]) continue;
          it.previous();
          ++k;
        }
        break;
      }
    }
    while (it.hasNext() && --k >= 0) {
      it.next();
      it.remove();
    }
    for (; j < ary.length; ++j) add(list, from + j, ary[j]);
  }
コード例 #5
0
  /**
   * Adds a new streaming source to the list. If another source in the list is already playing on
   * the same channel, it is stopped and removed from the list.
   *
   * @param source New source to stream.
   */
  public void watch(Source source) {
    // make sure the source exists:
    if (source == null) return;

    // make sure we aren't already watching this source:
    if (streamingSources.contains(source)) return;

    ListIterator<Source> iter;
    Source src;

    // Make sure noone else is accessing the list of sources:
    synchronized (listLock) {
      // Any currently watched source which is null or playing on the
      // same channel as the new source should be stopped and removed
      // from the list.
      iter = streamingSources.listIterator();
      while (iter.hasNext()) {
        src = iter.next();
        if (src == null) {
          iter.remove();
        } else if (source.channel == src.channel) {
          src.stop();
          iter.remove();
        }
      }

      // Add the new source to the list:
      streamingSources.add(source);
    }
  }
コード例 #6
0
ファイル: Segment.java プロジェクト: zhoufeng/HanLP
 /**
  * 合并数字
  *
  * @param termList
  */
 protected void mergeNumberQuantifier(List<Vertex> termList) {
   if (termList.size() < 4) return;
   StringBuilder sbQuantifier = new StringBuilder();
   ListIterator<Vertex> iterator = termList.listIterator();
   iterator.next();
   while (iterator.hasNext()) {
     Vertex pre = iterator.next();
     if (pre.hasNature(Nature.m)) {
       sbQuantifier.append(pre.realWord);
       Vertex cur = null;
       while (iterator.hasNext() && (cur = iterator.next()).hasNature(Nature.m)) {
         sbQuantifier.append(cur.realWord);
         iterator.remove();
       }
       if (cur != null
           && (cur.hasNature(Nature.q) || cur.hasNature(Nature.qv) || cur.hasNature(Nature.qt))) {
         sbQuantifier.append(cur.realWord);
         pre.attribute = new CoreDictionary.Attribute(Nature.mq);
         iterator.remove();
       }
       if (sbQuantifier.length() != pre.realWord.length()) {
         pre.realWord = sbQuantifier.toString();
         sbQuantifier.setLength(0);
       }
     }
   }
 }
コード例 #7
0
ファイル: ListenerManager.java プロジェクト: Unidata/IDV
  /**
   * Send an event to all registered listeners, except the named one.
   *
   * @param event the event to be sent: public void method_name( event_class event)
   */
  public void sendEventExcludeSource(java.util.EventObject event) {
    if (!hasListeners) {
      return;
    }

    Object source = event.getSource();
    Object[] args = new Object[1];
    args[0] = event;

    // send event to all listeners except the source
    ListIterator iter = listeners.listIterator();
    while (iter.hasNext()) {
      Object client = iter.next();
      if (client == source) {
        continue;
      }

      try {
        method.invoke(client, args);
      } catch (IllegalAccessException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalAccessException = " + e);
      } catch (IllegalArgumentException e) {
        iter.remove();
        System.err.println("ListenerManager IllegalArgumentException = " + e);
      } catch (InvocationTargetException e) {
        iter.remove();
        System.err.println("ListenerManager InvocationTargetException on " + method);
        System.err.println("   threw exception " + e.getTargetException());
        e.printStackTrace();
      }
    }
  }
コード例 #8
0
  /**
   * Calculate the bounds to paint the passed state. It takes into account states that have already
   * been set w/o changing the order. It also removes any unused states.
   *
   * @param bounds The token's bounds. All states are drawn inside this area.
   * @param token Rendering the states for this token.
   * @param state The state being rendered.
   * @return The bounds used to paint the state.
   */
  public Rectangle2D getStateBounds2D(Rectangle bounds, Token token, String state) {

    // Find the list of states already drawn on the token
    List<String> states = savedStates.get(token.getId());
    if (states == null) {
      states = new LinkedList<String>();
      savedStates.put(token.getId(), states);
    } // endif

    // Find the state in the list, make sure that all the states before it still exist.
    ListIterator<String> i = states.listIterator();
    boolean found = false;
    while (i.hasNext()) {
      String savedState = i.next();
      if (!found && savedState.equals(state)) {
        found = true;
      } else {
        Object stateValue = token.getState(savedState);
        if (stateValue == null) {
          i.remove();
        } else if (stateValue instanceof Boolean) {
          Boolean b = (Boolean) stateValue;
          if (b.booleanValue() == false) i.remove();
        } else if (stateValue instanceof BigDecimal) {
          BigDecimal bd = (BigDecimal) stateValue;
          if (bd.compareTo(BigDecimal.ZERO) == 0) i.remove();
        }
      } // endif
    } // endwhile

    // Find the index of the state, then convert it into row & column
    int index = states.size();
    if (found) {
      index = states.indexOf(state);
    } else {
      states.add(state);
    } // endif
    if (index >= gridSize * gridSize) {
      log.warn(
          "Overlapping states in grid size "
              + gridSize
              + " at "
              + index
              + " on token "
              + token.getName());
      index = index % (gridSize * gridSize);
    } // endif
    int row = gridSize - 1 - (index / gridSize); // Start at bottom
    int col = gridSize - 1 - (index % gridSize); // Start at right

    // Build the rectangle from the passed bounds
    return new Rectangle2D.Double(
        offsets[col] * bounds.width + bounds.x,
        offsets[row] * bounds.height + bounds.y,
        size * bounds.width,
        size * bounds.height);
  }
コード例 #9
0
  /**
   * Outputs filled with points listOfPointsToBeConnected. Finds the point with the lowest Y - that
   * will be the first point of the broken line. If It finds several points with equal Ys - makes a
   * line from the most left (lowest X) point to the most right point, then connects this point with
   * next point with the lowest Y from the remaining set. The last point of the broken line will be
   * the point with the highest Y, or if there will be several points with the highest Y - the point
   * with the highest X from this set.
   */
  void connectPoints() {

    ArrayList<MyPoint> pointsInOneRow =
        new ArrayList<MyPoint>(); // will store points with equal Ys.
    MyPoint currentPoint, nextPoint;
    ListIterator<MyPoint> itr;

    while (randomListOfPoints.size() > 0) {

      pointsInOneRow.clear(); // clear the pointsInOneRow.
      itr = randomListOfPoints.listIterator();
      // initialize list iterator and place it before the first element in the randomListOfPoints.
      currentPoint = itr.next(); // the first element from the randomListOfPoints.
      itr.remove(); // delete the first element from the randomListOfPoints.
      if (itr.hasNext()) { // if it's not the end of the randomListOfPoints.

        nextPoint = itr.next(); // the second element from the randomListOfPoints.

      } else {

        // the point not from the range of possible Xs and Ys, so we can be sure that its' Y won't
        // be equal to the currentPoints'.
        nextPoint = new MyPoint(-1, -1);
      }
      pointsInOneRow.add(
          currentPoint); // add current point to a list of points, that lies on one line.
      // if the currentPoint and the nextPoint are on the same line, that is parallel to the X axis.
      while (currentPoint.getY() == nextPoint.getY()) {

        pointsInOneRow.add(
            nextPoint); // add the nextPoint to a list of points, that lies on one line.
        itr.remove(); // delete the second element from the randomListOfPoints .
        currentPoint = nextPoint; // the currentPoint equals to the nextPoint now.
        if (itr.hasNext()) { // if it's not the end of the randomListOfPoints.

          nextPoint = itr.next(); // the second element from the randomListOfPoints.

        } else {

          // the point not from the range of possible Xs and Ys, so we can be sure that its' Y won't
          // be equal to the currentPoints'.
          nextPoint = new MyPoint(-1, -1);
        }
      }

      Collections.sort(
          pointsInOneRow, new XcoordSorterComparator()); // sort the pointsInOneRow by X
      /* add all elements from the pointsInOneRow to the end of the listOfPointsToBeConnected.
       * If the listOfPointsToBeConnected.size == 0 - the first element from the pointsInOneRow will be the start
       * of the broken line, if the listOfPointsToBeConnected.size != 0 - the first element from the
       * pointsInOneRow will be connected with the last element from the listOfPointsToBeConnected*/
      listOfPointsToBeConnected.addAll(listOfPointsToBeConnected.size(), pointsInOneRow);
    }

    System.out.println("\n\nList of connected points:\n" + listOfPointsToBeConnected);
  }
コード例 #10
0
  /** Test remove() for an immutable ListIterator. */
  public void testUnmodifiableListIteratorImmutability() {
    ListIterator listIterator = getImmutableListIterator();

    try {
      listIterator.remove();
      // We shouldn't get to here.
      fail("remove() should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }

    try {
      listIterator.set("a");
      // We shouldn't get to here.
      fail("set(Object) should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }

    try {
      listIterator.add("a");
      // We shouldn't get to here.
      fail("add(Object) should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }

    listIterator.next();

    try {
      listIterator.remove();
      // We shouldn't get to here.
      fail("remove() should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }

    try {
      listIterator.set("a");
      // We shouldn't get to here.
      fail("set(Object) should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }

    try {
      listIterator.add("a");
      // We shouldn't get to here.
      fail("add(Object) should throw an UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
      // This is correct; ignore the exception.
    }
  }
コード例 #11
0
ファイル: ZStyledText.java プロジェクト: rmcbee/arduino
 /**
  * Set the attribute to be applied to a range of characters starting at beginIdx and ending with
  * endIdx-1.
  *
  * @param type attribute type
  * @param value attribute value
  * @param beginIdx the index of the first character (inclusive)
  * @param endIdx the index of the last character (exclusive)
  */
 public void addAttribute(Attribute type, Object value, int beginIdx, int endIdx) {
   value = validateTextAttributeColor((TextAttribute) type, value);
   AttributeRun ar = new AttributeRun(type, value, beginIdx, endIdx);
   // If we already have attributes try and rationalize the number by merging
   // runs if possible and removing runs that no longer have a visible effect.
   if (atrun.size() > 0) {
     ListIterator<AttributeRun> iter = atrun.listIterator(atrun.size());
     while (iter.hasPrevious()) {
       AttributeRun a = iter.previous();
       int action = ar.intersectionWith(a);
       int intersect = action & I_MODES;
       int combiMode = action & COMBI_MODES;
       if (combiMode == MERGE_RUNS) {
         switch (intersect) {
           case I_TL:
           case I_CL:
             ar.start = a.start;
             iter.remove();
             break;
           case I_TR:
           case I_CR:
             ar.end = a.end;
             iter.remove();
             break;
         }
       } else if (combiMode == CLIP_RUN) {
         switch (intersect) {
           case I_CL:
             a.end = ar.start;
             break;
           case I_CR:
             a.start = ar.end;
             break;
         }
       }
       switch (intersect) {
         case I_INSIDE:
           iter.remove();
           break;
         case I_COVERED:
           ar = null;
           break;
       }
     }
   }
   // If the run is still effective then add it
   if (ar != null) atrun.addLast(ar);
   applyAttributes();
   invalidLayout = true;
 }
コード例 #12
0
  public synchronized void act() {
    g = AsteroidsFrame.getGBuff();
    ListIterator<Misile> iter = theMisiles.listIterator();
    while (iter.hasNext()) {
      Misile m = iter.next();
      if (m.needsRemoval()) iter.remove();
      else m.act(g);
    }

    iter = toBeAdded.listIterator();
    while (iter.hasNext()) {
      theMisiles.add(iter.next());
      iter.remove();
    }
  }
コード例 #13
0
ファイル: ParseSelected.java プロジェクト: pedbet/QuickSERVE
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.parseselected);

    text = (TextView) findViewById(R.id.parsedtext);
    Intent intent = getIntent();
    customerOrder = (Order) intent.getSerializableExtra("com.example.quickserve.Order.class");

    burgers = customerOrder.getBurgers();
    toppings = customerOrder.getToppings();
    sides = customerOrder.getSides();
    ListIterator<String> it = burgers.listIterator();
    ListIterator<String> it2 = toppings.listIterator();
    ListIterator<String> it3 = sides.listIterator();
    String a = "enditem";
    while (!burgers.isEmpty()) {
      text.append("Burger: ");
      text.append(it.next()); // first one
      it.remove(); // remove it
      text.append(" "); // space

      text.append(it.next()); // second one
      it.remove(); // remove it
      text.append(" "); // space

      text.append(it.next()); // third one
      it.remove(); // remove it
      text.append(" "); // space
      text.append("\n");
      text.append("Toppings: ");
      while (!toppings.isEmpty()) {
        text.append(" "); // space
        String b = it2.next();
        it2.remove();
        if (b.compareTo(a) == 0) break;
        text.append(b);
      }
    } // end outter while
    text.append("\n");
    text.append("Sides: ");
    while (!sides.isEmpty()) {
      text.append(" "); // space
      String c = it3.next();
      it3.remove();
      text.append(c);
    }
  }
コード例 #14
0
ファイル: SargRexAnalyzer.java プロジェクト: norrislee/optiq
    // implement CallConvertlet
    public void convert(RexCall call) {
      // REVIEW jvs 18-Mar-2006:  The test for variableSeen
      // here and elsewhere precludes predicates like where
      // (boolean_col AND (int_col > 10)).  Should probably
      // support bare boolean columns as predicates with
      // coordinate TRUE.

      if (variableSeen || (coordinate != null)) {
        failed = true;
      }

      if (failed) {
        return;
      }

      int nOperands = call.getOperands().size();
      assert (exprStack.size() >= nOperands);

      SargSetExpr expr = factory.newSetExpr(boundInputRef.getType(), setOp);

      // Pop the correct number of operands off the stack
      // and transfer them to the new set expression.
      ListIterator<SargExpr> iter = exprStack.listIterator(exprStack.size() - nOperands);
      while (iter.hasNext()) {
        expr.addChild(iter.next());
        iter.remove();
      }

      exprStack.add(expr);
    }
コード例 #15
0
  public void updateRound() {
    ListIterator<Action> actionIterator = actions.listIterator();
    while (actionIterator.hasNext()) {
      Action a = actionIterator.next();
      if (currentRound >= (a.roundStarted + a.length)) {
        actionIterator.remove();
      }
    }

    aliveRounds += 1;

    updateDrawLoc();

    broadcast = (broadcast << 1) & 0x000FFFFF;
    if (regen > 0) regen--;

    Iterator<Map.Entry<Animation.AnimationType, Animation>> it = animations.entrySet().iterator();
    Map.Entry<Animation.AnimationType, Animation> entry;
    while (it.hasNext()) {
      entry = it.next();
      entry.getValue().updateRound();
      if (!entry.getValue().isAlive()) {
        if (entry.getKey() != DEATH_EXPLOSION) it.remove();
      }
    }
    currentRound++;
  }
コード例 #16
0
 @Override
 public void run() {
   try {
     boolean running = true;
     while (running) {
       try {
         // block on event availability
         ThreadBoundEvent event = queue.take();
         // add to the batch, and see if we can add more
         batch.add(event);
         if (maxBatchSize > 0) {
           queue.drainTo(batch, maxBatchSize);
         }
         // check for the stop condition (and remove it)
         // treat batches of 1 (the most common case) specially
         if (batch.size() > 1) {
           ListIterator<ThreadBoundEvent> itr = batch.listIterator();
           while (itr.hasNext()) {
             ThreadBoundEvent next = itr.next();
             if (next.getClass().equals(ShutdownTask.class)) {
               running = false;
               ((ShutdownTask) next).latch.countDown();
               itr.remove();
             }
           }
           eventProcessor.process(batch);
         } else {
           // just the one event, no need to iterate
           if (event.getClass().equals(ShutdownTask.class)) {
             running = false;
             ((ShutdownTask) event).latch.countDown();
           } else {
             eventProcessor.process(batch);
           }
         }
       } catch (InterruptedException e) {
         LOG.warn(
             String.format(
                 "Consumer on queue %s interrupted.", Thread.currentThread().getName()));
         // ignore
       } catch (Throwable exception) {
         LOG.error(
             String.format(
                 "exception on queue %s while executing events",
                 Thread.currentThread().getName()),
             exception);
       } finally {
         // reset the batch
         batch.clear();
       }
     }
   } catch (Throwable unexpectedThrowable) {
     // we observed some cases where trying to log the inner exception threw an error
     // don't use the logger here as that seems to be causing the problem in the first place
     System.err.println("Caught and unexpected Throwable while logging");
     System.err.println(
         "This problem happens when jar files change at runtime, JVM might be UNSTABLE");
     unexpectedThrowable.printStackTrace(System.err);
   }
 }
コード例 #17
0
  @Override
  void replaceChild(
      @SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) {
    // Replace child
    if (this._quad_ == oldChild) {
      setQuad((TQuad) newChild);
      return;
    }

    for (ListIterator<TId> i = this._path_.listIterator(); i.hasNext(); ) {
      if (i.next() == oldChild) {
        if (newChild != null) {
          i.set((TId) newChild);
          newChild.parent(this);
          oldChild.parent(null);
          return;
        }

        i.remove();
        oldChild.parent(null);
        return;
      }
    }

    if (this._id_ == oldChild) {
      setId((TId) newChild);
      return;
    }

    throw new RuntimeException("Not a child.");
  }
コード例 #18
0
  @Override
  void replaceChild(
      @SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) {
    // Replace child
    if (this._classOrInterfaceType_ == oldChild) {
      setClassOrInterfaceType((PClassOrInterfaceType) newChild);
      return;
    }

    for (ListIterator<PDim> i = this._dim_.listIterator(); i.hasNext(); ) {
      if (i.next() == oldChild) {
        if (newChild != null) {
          i.set((PDim) newChild);
          newChild.parent(this);
          oldChild.parent(null);
          return;
        }

        i.remove();
        oldChild.parent(null);
        return;
      }
    }

    if (this._arrayInitializer_ == oldChild) {
      setArrayInitializer((PArrayInitializer) newChild);
      return;
    }

    throw new RuntimeException("Not a child.");
  }
コード例 #19
0
  public void pruneOldTextureFX(ITexturePack var1, List<TextureFX> effects) {
    ListIterator<TextureFX> li = addedTextureFX.listIterator();

    while (li.hasNext()) {
      TextureFX tex = li.next();

      if (tex instanceof FMLTextureFX) {
        if (((FMLTextureFX) tex).unregister(client.renderEngine, effects)) {
          li.remove();
        }
      } else {
        effects.remove(tex);
        li.remove();
      }
    }
  }
コード例 #20
0
  /**
   * Overlays this fragment list by some {@link Fragment}. That means that parts that overlap are
   * taken from the fragment passed.
   *
   * @param fragment The fragment.
   * @return A fragment list storing the overlay result.
   */
  public FragmentList overlayBy(final Fragment fragment) {
    final FragmentList result = new FragmentList();
    try {
      result.addFragment(fragment);
    } catch (final IncompatibleFragmentException e) {
      throw new Error(e);
    }

    final PositionInText posTo = fragment.getTo();
    final ListIterator<Fragment> it = this.fragments.listIterator();
    while (it.hasNext()) {
      final Fragment oldFragment = it.next();
      if (posTo.lessThan(oldFragment.getFrom())) {
        break;
      }

      final ListIterator<Fragment> fIt = result.fragments.listIterator();
      while (fIt.hasNext()) {
        final Fragment f = fIt.next();
        final FragmentList rest = f.subtract(oldFragment);
        fIt.remove();
        for (final Fragment newFragment : rest.fragments) {
          fIt.add(newFragment);
        }
      }
    }

    try {
      result.addFragmentList(this);
    } catch (final IncompatibleFragmentException e) {
      throw new Error(e);
    }

    return result;
  }
コード例 #21
0
 void destroyChildren() {
   getThreadManager().interruptAll();
   for (final ListIterator<WebWindowImpl> iter = childWindows_.listIterator(); iter.hasNext(); ) {
     iter.next().destroyChildren();
     iter.remove();
   }
 }
コード例 #22
0
ファイル: GraphSaver.java プロジェクト: quintopia/ArcNode
  public static void saveGraph(Graph g, File f) throws FileNotFoundException, SecurityException {
    ArrayList<GraphEdge> edgemarks = new ArrayList<GraphEdge>();

    PrintStream p = new PrintStream(new FileOutputStream(f));
    try {
      Iterator<GraphNode> n = g.getNodeIterator();
      int count = 1;
      while (n.hasNext()) {
        GraphNode node = n.next();
        ListIterator<GraphEdge> e = node.getEdgeIterator();
        while (e.hasNext()) {
          GraphEdge edge = e.next();
          if (g.getNodeById(edge.getTarget().getId()) == null) {
            e.remove();
            continue;
          }
          if (!edgemarks.contains(edge))
            p.println(
                ""
                    + (node.getId() + 1)
                    + " "
                    + (edge.getTarget().getId() + 1)
                    + " "
                    + edge.getWeight());
          edgemarks.add(edge.getTarget().getEdgeByTargetId(node.getId()));
          edgemarks.add(edge);
        }
        if (count % 100 == 0) System.out.println("Saving. . ." + count++);
      }
    } finally {
      p.close();
    }
  }
コード例 #23
0
  @Override
  @Test
  public void listIterator() {
    super.listIterator();
    CompositeFastList<String> composite = new CompositeFastList<String>();
    FastList<String> firstBit = FastList.newListWith("one", "two");
    FastList<String> secondBit = FastList.newListWith("three");
    composite.addAll(firstBit);
    composite.addAll(secondBit);

    ListIterator<String> listIterator = composite.listIterator();
    listIterator.add("four");
    Verify.assertSize(4, composite);
    Assert.assertTrue(listIterator.hasNext());
    String element = listIterator.next();

    Assert.assertEquals("one", element);

    String element3 = listIterator.next();

    Assert.assertEquals("two", element3);

    String element2 = listIterator.previous();
    Assert.assertEquals("two", element2);

    String element1 = listIterator.next();

    Assert.assertEquals("two", element1);

    listIterator.remove();

    Verify.assertSize(3, composite);
  }
コード例 #24
0
 /**
  * Removes overloaded methods from the contents list and adds them to the overloadedMethods list
  * of the first overloaded method encountered.
  *
  * @param contents
  * @param doExtractedMethods
  */
 private static void cullOverloadedMethods(
     List<ClassContentsEntry> contents, boolean doExtractedMethods) {
   List<ClassContentsEntry> copy = new ArrayList<ClassContentsEntry>(contents);
   for (ClassContentsEntry o : copy) {
     if (o instanceof RelatableEntry) {
       MethodEntry me = (MethodEntry) o;
       if ((me.isRelatedMethod() == doExtractedMethods) && !me.isOverloadedMethod) {
         String meName = me.myEnd.toString();
         // search contents list for methods with identical name, and attach them as overloaded
         // methods.
         ListIterator<ClassContentsEntry> contentIterator = contents.listIterator();
         while (contentIterator.hasNext()) {
           Object o1 = contentIterator.next();
           if (o1 instanceof RelatableEntry) {
             MethodEntry me2 = (MethodEntry) o1;
             if (me2 == me) {
               continue;
             }
             String me2Name = me2.myEnd.toString();
             if (meName.equals(me2Name)) {
               contentIterator.remove();
               me.myOverloadedMethods.add(me2);
               me2.isOverloadedMethod = true; // set flag so array copy will skip this entry.
             }
           }
         }
       }
     }
   }
 }
コード例 #25
0
ファイル: URIBroker.java プロジェクト: qmdx/citrus
  protected final void clearPathSegment(int segment) {
    assertSegment(segment);

    int index = pathSegmentIndexes[segment];
    int previousIndex = segment > 0 ? pathSegmentIndexes[segment - 1] : 0;
    int removedCount = index - previousIndex;
    boolean isTruncate = index == pathSegmentIndexes[pathSegmentIndexes.length - 1];

    if (removedCount > 0) {
      ListIterator<String> i = path.listIterator(index);

      for (int j = 0; j < removedCount; j++) {
        i.previous();
        i.remove();
      }

      for (int j = segment; j < pathSegmentIndexes.length; j++) {
        pathSegmentIndexes[j] -= removedCount;
      }

      if (isTruncate) {
        renderer.truncatePathBuffer(removedCount);
      } else {
        renderer.clearPathBuffer();
      }
    }
  }
コード例 #26
0
    @Override
    protected void invalidateNode(SNode sNode) {
      NodePath affPath = NodePath.forSNode(sNode);
      SModel containingModel = sNode.getContainingModel();
      if (containingModel == null) return;

      SModelReference mref = containingModel.getReference();
      List<NodePath> nodePaths = nodePaths(mref);
      ListIterator<NodePath> npathIt = nodePaths.listIterator();
      while (npathIt.hasNext()) {
        NodePath path = npathIt.next();
        NodePath lcp = affPath.findLowestCommonParent(path);
        if (lcp != null) {
          if (lcp.equals(path)) break;
          // replace with the LCP and stop
          npathIt.remove();
          npathIt.add(lcp);
          break;
        }
      }
      if (!npathIt.hasNext()) {
        // not found -> just add
        nodePaths.add(affPath);
      }
    }
コード例 #27
0
  private synchronized void trim() {
    for (int i = 0; i < 3; ++i) {
      if (maxSize == 0 || size <= maxSize) return;

      LinkedList<String> files = database.getFilesForTrim(size - maxSize);

      while (size > maxSize) {
        File oldest = null;
        for (ListIterator<String> it = files.listIterator(); it.hasNext(); ) {
          File file = pathToFile(it.next());
          if (isPageFile(file) && pagesSize < maxPagesSize) continue;
          it.remove();
          oldest = file;
          break;
        }
        if (oldest == null) {
          Logger.e(TAG, "No files to trim");
          break;
        } else {
          Logger.d(TAG, "Deleting " + oldest.getPath());
          if (!delete(oldest)) {
            Logger.e(TAG, "Cannot delete cache file: " + oldest.getPath());
            break;
          }
        }
      }
    }
  }
コード例 #28
0
  @Override
  void replaceChild(
      @SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) {
    // Replace child
    if (this._deNum_ == oldChild) {
      setDeNum((TNumeroInteiro) newChild);
      return;
    }

    if (this._ateNum_ == oldChild) {
      setAteNum((TNumeroInteiro) newChild);
      return;
    }

    for (ListIterator<PComandos> i = this._comandos_.listIterator(); i.hasNext(); ) {
      if (i.next() == oldChild) {
        if (newChild != null) {
          i.set((PComandos) newChild);
          newChild.parent(this);
          oldChild.parent(null);
          return;
        }

        i.remove();
        oldChild.parent(null);
        return;
      }
    }

    throw new RuntimeException("Not a child.");
  }
コード例 #29
0
 @Override
 public synchronized void removeFilter(final Subscription sub, final Object object) {
   final Collection<MessageType> types = sub.filter.getMessageTypes();
   if (types == null) {
     return;
   }
   for (final MessageType tt : types) {
     final Map<Object, List<Subscription>> objectMap = this.messageTypes.get(tt);
     if (objectMap == null) {
       continue;
     }
     final List<Subscription> subList = objectMap.get(object);
     if (subList == null) {
       continue;
     }
     final ListIterator<Subscription> iterator = subList.listIterator();
     while (iterator.hasNext()) {
       final Subscription ss = iterator.next();
       if (ss.subId == sub.subId) {
         iterator.remove();
         break;
       }
     }
     if (subList.size() != 0) {
       continue;
     }
     objectMap.remove(object);
   }
 }
コード例 #30
0
ファイル: SETOSession.java プロジェクト: joninvski/Appia
 /** Tries to deliver Uniform messages. */
 private void deliverUniform() {
   log.debug("Trying to deliver FINAL messages!");
   ListIterator it = G.listIterator();
   while (it.hasNext()) {
     ListSEQContainer nextMsg = (ListSEQContainer) it.next();
     if (isUniform(nextMsg.header)) {
       ListContainer msgContainer = getRemoveMessage(nextMsg.header, R);
       log.debug("Resending message to Appl: " + msgContainer.event);
       log.debug(
           "["
               + ls.my_rank
               + "] Delivering final "
               + msgContainer.header.id
               + ":"
               + msgContainer.header.sn
               + " timestamp "
               + timeProvider.currentTimeMillis());
       try {
         // deliver uniform notification
         UniformServiceEvent use =
             new UniformServiceEvent(
                 msgContainer.event.getChannel(),
                 Direction.UP,
                 this,
                 msgContainer.event.getMessage());
         use.go();
       } catch (AppiaEventException e) {
         e.printStackTrace();
       }
       it.remove();
     }
   }
 }