Example #1
0
  @Override
  public IFeature getFeature(String name) {
    for (IFeature f : features) {
      if (f.getName().equals(name)) {
        return f;
      }
    }
    LinkedList<IClass> queue = new LinkedList<>(this.getExtends());
    if (queue.isEmpty()) {
      return null;
    }

    Set<IClass> processed = new HashSet<>();
    processed.add(this);
    processed.addAll(queue);
    while (!queue.isEmpty()) {
      IClass next = queue.remove();
      for (IFeature f : next.getFeatures()) {
        if (f.getName().equals(name)) {
          return f;
        }
      }
      for (IClass cl : next.getExtends()) {
        if (!processed.contains(cl)) {
          processed.add(cl);
          queue.add(cl);
        }
      }
    }
    return null;
  }
Example #2
0
 /**
  * Output conflict list as XML.
  *
  * @param ch Content handler to output the conflict to.
  * @throws SAXException precolated up from the content handler
  */
 public void writeConflicts(ContentHandler ch) throws SAXException {
   AttributesImpl atts = new AttributesImpl();
   ch.startDocument();
   ch.startElement("", "", "conflictlist", atts);
   if (!conflicts.isEmpty()) {
     atts = new AttributesImpl();
     ch.startElement("", "", "conflicts", atts);
     for (Iterator i = conflicts.iterator(); i.hasNext(); )
       outputConflict((ConflictEntry) i.next(), ch);
     ch.endElement("", "", "conflicts");
   }
   if (!warnings.isEmpty()) {
     atts = new AttributesImpl();
     ch.startElement("", "", "warnings", atts);
     for (Iterator i = warnings.iterator(); i.hasNext(); )
       outputConflict((ConflictEntry) i.next(), ch);
     ch.endElement("", "", "warnings");
   }
   ch.endElement("", "", "conflictlist");
   if (!conflicts.isEmpty())
     System.err.println("MERGE FAILED: " + conflicts.size() + " conflicts.");
   if (!warnings.isEmpty())
     System.err.println("Warning: " + warnings.size() + " conflict warnings.");
   ch.endDocument();
 }
 /**
  * Returns the next available packet. The method call will block (not return) until a packet is
  * available or the <tt>timeout</tt> has elapased. If the timeout elapses without a result,
  * <tt>null</tt> will be returned.
  *
  * @param timeout the amount of time to wait for the next packet (in milleseconds).
  * @return the next available packet.
  */
 public synchronized Packet nextResult(long timeout) {
   // Wait up to the specified amount of time for a result.
   if (resultQueue.isEmpty()) {
     long waitTime = timeout;
     long start = System.currentTimeMillis();
     try {
       // Keep waiting until the specified amount of time has elapsed,
       // or
       // a packet is available to return.
       while (resultQueue.isEmpty()) {
         if (waitTime <= 0) {
           break;
         }
         wait(waitTime);
         final long now = System.currentTimeMillis();
         waitTime -= (now - start);
         start = now;
       }
     } catch (final InterruptedException ie) {
       // Ignore.
     }
     // Still haven't found a result, so return null.
     if (resultQueue.isEmpty()) {
       return null;
     }
     // Return the packet that was found.
     else {
       return resultQueue.removeLast();
     }
   }
   // There's already a packet waiting, so return it.
   else {
     return resultQueue.removeLast();
   }
 }
  @Override
  public final boolean incrementToken() throws IOException {
    if (!tokens.isEmpty()) {
      assert current != null;
      CompoundToken token = tokens.removeFirst();
      restoreState(current); // keep all other attributes untouched
      termAtt.setEmpty().append(token.txt);
      offsetAtt.setOffset(token.startOffset, token.endOffset);
      posIncAtt.setPositionIncrement(0);
      return true;
    }

    current = null; // not really needed, but for safety
    if (input.incrementToken()) {
      // Only words longer than minWordSize get processed
      if (termAtt.length() >= this.minWordSize) {
        decompose();
        // only capture the state if we really need it for producing new tokens
        if (!tokens.isEmpty()) {
          current = captureState();
        }
      }
      // return original token:
      return true;
    } else {
      return false;
    }
  }
 public void adjustAdjacency(int src, int tgt) {
   int[] passed = new int[edges.size()];
   for (int i = 0; i < edges.size(); i++) passed[i] = 0;
   ArrayList<ArrayList<Integer>> reverseAdj = new ArrayList<ArrayList<Integer>>(nodes.size());
   for (int i = 0; i < nodes.size(); i++) reverseAdj.add(new ArrayList<Integer>());
   for (int i = 0; i < srcs.size(); i++) reverseAdj.get(tgts.get(i)).add(i);
   LinkedList<Integer> nodeQueue = new LinkedList<Integer>();
   nodeQueue.add(src);
   while (!nodeQueue.isEmpty()) {
     int node = nodeQueue.remove();
     for (int i = 0; i < adjacency.get(node).size(); i++) {
       int edge = adjacency.get(node).get(i);
       passed[edge]++;
       nodeQueue.add(tgts.get(edge));
     }
     adjacency.get(node).clear();
   }
   adjacency = reverseAdj;
   nodeQueue.add(tgt);
   while (!nodeQueue.isEmpty()) {
     int node = nodeQueue.remove();
     for (int i = 0; i < adjacency.get(node).size(); i++) {
       int edge = adjacency.get(node).get(i);
       passed[edge]++;
       nodeQueue.add(srcs.get(edge));
     }
     adjacency.get(node).clear();
   }
   for (int n = 0; n < nodes.size(); n++) adjacency.get(n).clear();
   for (int e = 0; e < edges.size(); e++) if (passed[e] == 2) adjacency.get(srcs.get(e)).add(e);
 }
Example #6
0
  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);
  }
 @Override
 public String toString() {
   String str = "=================================================\n";
   str += "Freecells: ";
   for (LinkedList<Card> freecell : freecells) {
     if (freecell.isEmpty()) str += " ";
     else str += freecell.getLast().toString() + " ";
   }
   str += "\t\tFoundations: ";
   for (LinkedList<Card> foundation : foundations) {
     if (foundation.isEmpty()) str += " ";
     else str += foundation.getLast().toString() + "(" + foundation.size() + ") ";
   }
   str += "\n\n";
   for (LinkedList<Card> cascade : cascades) {
     if (cascade.isEmpty()) str += "\n";
     else {
       for (Card c : cascade) {
         str += c.toString() + " ";
       }
       str += "\n";
     }
   }
   str += "\nF: " + f + "\tG: " + g + "\tH: " + h + "\n";
   str += "=================================================\n";
   return str;
 }
  public void calculateHeuristicValue() {

    int h = 0;

    // penalty for every card not being in a cascade
    // higher penalty for lower cards

    int cardsNotInFoundationsPenalty = 0;

    for (LinkedList<Card> freecell : freecells) {
      if (!freecell.isEmpty()) {
        cardsNotInFoundationsPenalty += reverseWorthOfCards(freecell);
      }
    }

    for (LinkedList<Card> cascade : cascades) {
      if (!cascade.isEmpty()) {
        cardsNotInFoundationsPenalty += reverseWorthOfCards(cascade);
      }
    }

    // Penalty for cards not being in order

    int cardOrderPenalty = 0;

    for (LinkedList<Card> cascade : cascades) {
      cardOrderPenalty += orderingPenalty(cascade);
    }

    h = (int) Math.round(0.75 * cardsNotInFoundationsPenalty + 0.25 * cardOrderPenalty);

    setH(h);
  }
Example #9
0
  @Override
  public boolean handle(final Message m, final XMPPConnection connection) {
    if (m.getBody().toLowerCase().equals("where")) {
      final LinkedList<InetAddress> addrList = getNetworkAddresses();

      final StringBuilder buff = new StringBuilder("Locally, I'm at ");

      String addr = "";

      while (!addrList.isEmpty()) {
        addr = addrList.removeFirst().getHostAddress();
        buff.append(addr).append(addrList.isEmpty() ? "" : "\nor ");
      }

      SheevaSage.reply(m, buff.toString(), connection);

      final String wa = getWorldAddress();

      if (wa != null) {
        SheevaSage.reply(m, "Globally, I'm at " + wa, connection);
      }

      return true;
    }

    return false;
  }
Example #10
0
  private void dispatchMessages(Dispatch<? super T> dispatch) {
    while (true) {
      T message = null;
      lock.lock();
      try {
        while (state != State.Stopped && queue.isEmpty()) {
          try {
            condition.await();
          } catch (InterruptedException e) {
            throw new UncheckedException(e);
          }
        }
        if (!queue.isEmpty()) {
          message = queue.remove();
          condition.signalAll();
        }
      } finally {
        lock.unlock();
      }

      if (message == null) {
        // Have been stopped and nothing to deliver
        return;
      }

      dispatch.dispatch(message);
    }
  }
 public static ListNode reverseKGroup(ListNode head, int k) {
   if (head == null || head.next == null || k < 2) {
     return head;
   }
   LinkedList<ListNode> l = new LinkedList<ListNode>();
   int count = 0;
   ListNode pre = new ListNode(0);
   ListNode temp = pre;
   while (head != null) {
     if (count++ < k) {
       ListNode t = new ListNode(head.val);
       l.push(t);
       head = head.next;
     }
     if (count >= k) {
       count = 0;
       while (!l.isEmpty()) {
         temp.next = l.pop();
         temp = temp.next;
       }
     }
   }
   while (!l.isEmpty()) {
     temp.next = l.pollLast();
     temp = temp.next;
   }
   return pre.next;
 }
  public boolean incrementToken() throws IOException {
    if (!morphQueue.isEmpty()) {
      restoreState(currentState);
      setAttributesFromQueue(false);
      return true;
    }

    while (input.incrementToken()) {
      final String type = typeAtt.type();
      if (KOREAN_TYPE.equals(type)) {
        try {
          analysisKorean(termAtt.toString());
        } catch (MorphException e) {
          throw new RuntimeException(e);
        }
      } else {
        return true; // pass anything else thru
      }

      if (!morphQueue.isEmpty()) {
        setAttributesFromQueue(true);
        return true;
      }
    }

    return false;
  }
  public boolean hasMore() throws NamingException {
    // has been closed
    if (values == null) {
      return false;
    }

    if (!values.isEmpty()) {
      return true;
    }

    synchronized (values) {
      if (values.isEmpty() && !isFinished) {
        waitMoreElement();
        if (!values.isEmpty()) {
          return true;
        }
      }
    }

    close();

    if (exception != null) {
      throw exception;
    }

    if (!isFinished) {
      // ldap.31=Read LDAP response message time out
      throw new CommunicationException(Messages.getString("ldap.31")); // $NON-NLS-1$
    }

    return false;
  }
Example #14
0
  /** Parse the command string and split it into computations of connected operators */
  public static ArrayList<String> parseExpr(String in) throws BcException {
    LinkedList<String> tempStack = new LinkedList<String>();
    ArrayList<String> result = new ArrayList<String>();
    char currentChar;
    StringBuilder currentToken;

    for (int i = 0; i < in.length(); i++) {
      currentChar = in.charAt(i);
      if (currentChar == ' ') {
        continue;
      } else if (isOperator(currentChar)) {
        // operator
        currentToken = new StringBuilder();
        currentToken.append(currentChar);
        while (i + 1 < in.length() && isOperator(in.charAt(i + 1))) {
          i++;
          currentToken.append(in.charAt(i));
        }
        // if is negate
        if (currentToken.toString().equals("-")
            && (result.size() == 0 || (!tempStack.isEmpty() && i > 0 && in.charAt(i - 1) == '('))) {
          currentToken = new StringBuilder("--");
        }
        while (tempStack.size() > 0
            && priority(currentToken.toString()) <= priority(tempStack.peek()))
          result.add(tempStack.pop());
        tempStack.push(currentToken.toString());
      } else if (currentChar == '(') {
        tempStack.push(currentChar + "");
      } else if (currentChar == ')') {
        while (!tempStack.peek().equals('(' + "")) {
          if (tempStack.isEmpty()) {
            throw new BcException("");
          }
          result.add(tempStack.pop());
        }
        tempStack.pop();
      } else if (isDigitOrDot(currentChar)) {
        // operand
        currentToken = new StringBuilder();
        currentToken.append(currentChar);
        while (i + 1 < in.length() && isDigitOrDot(in.charAt(i + 1))) {
          i++;
          currentToken.append(in.charAt(i));
        }
        result.add(currentToken.toString());
      } else {
        throw new BcException("illegal character: " + currentChar);
      }
    }

    while (!tempStack.isEmpty()) {
      if (tempStack.peek().equals("(")) {
        throw new BcException("Unmatched bracket.");
      }
      result.add(tempStack.pop());
    }

    return result;
  }
  /**
   * Close a opened statistics log after all the statistics collection relating to that statistics
   * component is ended.
   *
   * @param statisticDataUnit statistic data unit with raw data
   * @return true if there are no open message logs in openLogs List
   */
  public synchronized boolean closeLog(StatisticDataUnit statisticDataUnit) {
    int componentLevel;

    if (haveAggregateLogs && statisticDataUnit.isAggregatePoint()) {
      haveAggregateLogs = false;
      Integer aggregateIndex = deleteAndGetAggregateIndexFromOpenLogs();
      if (aggregateIndex != null) {
        closeStatisticLog(aggregateIndex, statisticDataUnit.getTime());
        return openLogs.isEmpty();
      }
    }
    if (statisticDataUnit.getParentId() == null) {
      componentLevel =
          deleteAndGetComponentIndex(
              statisticDataUnit.getComponentId(), statisticDataUnit.getCloneId());
    } else {
      componentLevel =
          deleteAndGetComponentIndex(
              statisticDataUnit.getComponentId(),
              statisticDataUnit.getParentId(),
              statisticDataUnit.getCloneId());
    }
    // not closing the root statistic log as it will be closed be endAll method
    if (componentLevel > ROOT_LEVEL) {
      closeStatisticLog(componentLevel, statisticDataUnit.getTime());
    } else {
      componentLevel = deleteAndGetComponentIndex(statisticDataUnit.getComponentId());
      if (componentLevel > ROOT_LEVEL) {
        closeStatisticLog(componentLevel, statisticDataUnit.getTime());
      }
    }
    return openLogs.isEmpty();
  }
Example #16
0
  public static void update() {
    Statistics.colonyReset();

    for (Mouse mouse : mice) {
      mouse.update();
      if (!mouse.isAlive()) deadMice.add(mouse);

      Statistics.colonyInclude(mouse);
    }

    Statistics.colonyReady();

    while (!deadMice.isEmpty()) {
      Mouse deadMouse = deadMice.remove();

      mice.remove(deadMouse);
      Stream.history("Colony Size: " + mice.size());
      MouseSim.getWorld().getWorldNode(deadMouse.getPosition()).remove(deadMouse);

      if (mice.size() == 1) {
        Stream.update(mice.get(0) + " is the last mouse alive! x_x");
      }
    }

    while (!bornMice.isEmpty()) {
      Mouse bornMouse = bornMice.remove();
      mice.add(bornMouse);
      Stream.history("Colony Size: " + mice.size());
    }

    if (mice.isEmpty()) {
      MouseSim.endGame("all the mice have died.");
    }
  }
  /**
   * Combines and returns queued messages combined into a single string. Combines as many messages
   * as possible, while staying under MAX_PAYLOAD_SIZE. Returns null if the queue is empty.
   */
  public String popAndEncode(boolean fromOnlineEvent) {
    synchronized (this) {
      registeredListeners[activeListenerIndex].notifyOfFlush(fromOnlineEvent);
      if (queue.isEmpty()) {
        return null;
      }
      int totalPayloadLen = 0;
      int numMessagesToSend = 0;
      for (JsMessage message : queue) {
        int messageSize = calculatePackedMessageLength(message);
        if (numMessagesToSend > 0
            && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE
            && MAX_PAYLOAD_SIZE > 0) {
          break;
        }
        totalPayloadLen += messageSize;
        numMessagesToSend += 1;
      }

      StringBuilder sb = new StringBuilder(totalPayloadLen);
      for (int i = 0; i < numMessagesToSend; ++i) {
        JsMessage message = queue.removeFirst();
        packMessage(message, sb);
      }

      if (!queue.isEmpty()) {
        // Attach a char to indicate that there are more messages pending.
        sb.append('*');
      }
      String ret = sb.toString();
      return ret;
    }
  }
Example #18
0
 private boolean repOkColors() {
   // RedHasOnlyBlackChildren
   java.util.LinkedList workList = new java.util.LinkedList();
   workList.add(root);
   while (!workList.isEmpty()) {
     Node current = (Node) workList.removeFirst();
     Node cl = current.left;
     Node cr = current.right;
     if (current.color == RED) {
       if (cl != null && cl.color == RED) return debug("RedHasOnlyBlackChildren1");
       if (cr != null && cr.color == RED) return debug("RedHasOnlyBlackChildren2");
     }
     if (cl != null) workList.add(cl);
     if (cr != null) workList.add(cr);
   }
   // SimplePathsFromRootToNILHaveSameNumberOfBlackNodes
   int numberOfBlack = -1;
   workList = new java.util.LinkedList();
   workList.add(new Pair(root, 0));
   while (!workList.isEmpty()) {
     Pair p = (Pair) workList.removeFirst();
     Node e = p.e;
     int n = p.n;
     if (e != null && e.color == BLACK) n++;
     if (e == null) {
       if (numberOfBlack == -1) numberOfBlack = n;
       else if (numberOfBlack != n)
         return debug("SimplePathsFromRootToNILHaveSameNumberOfBlackNodes");
     } else {
       workList.add(new Pair(e.left, n));
       workList.add(new Pair(e.right, n));
     }
   }
   return true;
 }
Example #19
0
  private void rebentaEstrela(Estrela estrela) {

    ArrayList<Estrela> estrelasARemover = null;
    ArrayList<Estrela> estrelasAAdicionar = null;

    if (estrelasARemover == null) {
      estrelasARemover = new ArrayList<>();
    }
    estrelasARemover.add(estrela);
    int diametroAtual = estrela.getDiametro();
    if (estrela.getDiametro() > 20) {
      if (estrelasAAdicionar == null) {
        estrelasAAdicionar = new ArrayList<>();
      }
      estrelasAAdicionar.add(estrela.criaMenor(diametroAtual - 20, false));
      estrelasAAdicionar.add(estrela.criaMenor(diametroAtual - 20, true));
    }

    if (estrelasARemover != null) {
      for (Estrela estrelaARemover : estrelasARemover) {
        estrelas.remove(estrelaARemover);
        pintaveis.remove(estrelaARemover);
      }
    }
    if (estrelasAAdicionar != null) {
      for (Estrela estrelaAAdicionar : estrelasAAdicionar) {
        estrelas.add(estrelaAAdicionar);
        pintaveis.add(estrelaAAdicionar);
      }
    }
    if (estrelas.isEmpty() && bolas.isEmpty()) fimNivel();
  }
 private void expandSelect() {
   if (fPathToSelect == null) return;
   if (fPathToSelect.isEmpty()) {
     fPathToSelect = null;
     fFileToSelect = null;
     return;
   }
   do {
     String name = fPathToSelect.getFirst();
     if (name.length() == 0) {
       fPathToSelect.removeFirst();
       continue;
     }
     FileInfo info = findFileInfo(fLastSelectedFileInfo, name);
     if (info == null) break;
     TreeItem item = findItem(info);
     if (item == null) break;
     fPathToSelect.removeFirst();
     if (fPathToSelect.isEmpty()) {
       fileTree.setSelection(item);
       fileTree.showItem(item);
     } else {
       item.setExpanded(true);
       fileTree.showItem(item);
     }
     fLastSelectedFileInfo = info;
   } while (!fPathToSelect.isEmpty());
 }
Example #21
0
 private static void moveSomewhere() throws GameActionException {
   while (!defendQueue.isEmpty()) {
     int next = defendQueue.element();
     if (teamMemberNeedsHelp[next] > 0 && rc.getRoundNum() - teamMemberNeedsHelp[next] < 200) {
       if (rc.isCoreReady()) {
         Nav.goTo(teamLocations[next]);
       }
       return;
     }
     defendQueue.remove();
   }
   if (!moveQueue.isEmpty()) {
     MapLocation next = moveQueue.element();
     if (rc.isCoreReady()) {
       Nav.goTo(next);
     }
     if (rc.canSense(next) && rc.senseRobotAtLocation(next) == null) {
       moveQueue.remove();
     }
     return;
   }
   if (rc.isCoreReady()) {
     Nav.goTo(personalHQ);
     return;
   }
 }
Example #22
0
  public void bfs_traverse_double_queue(mapNode root) {
    LinkedList<mapNode> next = new LinkedList<>();
    LinkedList<mapNode> current = new LinkedList<>();
    HashSet<mapNode> visited = new HashSet<>();

    int level = 0;

    current.push(root);
    visited.add(root);
    while (!current.isEmpty()) {
      level++;
      while (!current.isEmpty()) {
        mapNode cur = current.poll();
        System.out.println(cur.getData());
        ArrayList<mapNode> chl = cur.getChildren();
        if (chl != null) {
          for (mapNode node : chl) {
            next.add(node);
          }
        }
      }
      LinkedList<mapNode> temp = new LinkedList<>();
      temp = current;
      current = next;
      next = temp;
    }
    System.out.println('\n' + "level: " + level);
  }
  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());
  }
Example #24
0
  /**
   * Compose write and append print updates. The type write or append as well as the order of the
   * updates are taken into account.
   *
   * @param compAPI
   */
  private void composeAppend(PluginCompositionAPI compAPI) {
    for (Location l : compAPI.getAffectedLocations()) {
      if (!FILE_OUTPUT_FUNC_NAME.equals(l.name)) continue;
      LinkedList<Element> elems1 = new LinkedList<>();
      LinkedList<Element> elems2 = new LinkedList<>();
      Set<Element> contributingAgents = new HashSet<Element>();
      Set<ScannerInfo> contributingNodes = new HashSet<ScannerInfo>();
      String action = APPEND_ACTION;

      // if the second set does not have a basic update,
      // add all the updates from the first set as well
      if (!compAPI.isLocUpdatedWithActions(2, l, Update.UPDATE_ACTION)) {
        for (Update update : compAPI.getLocUpdates(1, l)) {
          if (APPEND_ACTION.equals(update.action) || WRITE_ACTION.equals(update.action)) {
            Element value = update.value;
            if (!(update.value instanceof ListElement))
              value = new ListElement(Arrays.asList(new Element[] {value}));
            ListElement list = (ListElement) value;
            elems1.addAll(list.getList());
            contributingAgents.addAll(update.agents);
            contributingNodes.addAll(update.sources);
          }
          if (WRITE_ACTION.equals(update.action)) action = WRITE_ACTION;
        }
      }
      for (Update update : compAPI.getLocUpdates(2, l)) {
        if (APPEND_ACTION.equals(update.action) || WRITE_ACTION.equals(update.action)) {
          Element value = update.value;
          if (!(update.value instanceof ListElement))
            value = new ListElement(Arrays.asList(new Element[] {value}));
          ListElement list = (ListElement) value;
          elems2.addAll(list.getList());
          contributingAgents.addAll(update.agents);
          contributingNodes.addAll(update.sources);
        }
        if (WRITE_ACTION.equals(update.action)) {
          action = WRITE_ACTION;
          elems1.clear();
        }
      }
      if (!elems1.isEmpty() || !elems2.isEmpty()) {
        LinkedList<Element> outputResult = elems1;
        if (outputResult.isEmpty()) outputResult = elems2;
        else if (!elems2.isEmpty()) {
          outputResult = new LinkedList<>();
          outputResult.addAll(elems1);
          outputResult.addAll(elems2);
        }
        compAPI.addComposedUpdate(
            new Update(
                l,
                new ListElement(new ArrayList<Element>(outputResult)),
                action,
                contributingAgents,
                contributingNodes),
            this);
      }
    }
  }
Example #25
0
 protected void rebentaBola(BolaQJ bola) {
   bolas.remove(bola);
   pintaveis.remove(bola);
   adicBolasRebentamento(bola);
   if (bolas.isEmpty() && estrelas.isEmpty()) {
     fimNivel();
   }
 }
Example #26
0
        public void handleTag(
            final boolean opening,
            final String tag,
            final Editable output,
            final XMLReader xmlReader) {
          if (TAG_DEL.equalsIgnoreCase(tag)) {
            if (opening) startSpan(new StrikethroughSpan(), output);
            else endSpan(StrikethroughSpan.class, output);
            return;
          }

          if (TAG_UL.equalsIgnoreCase(tag) || TAG_OL.equalsIgnoreCase(tag)) {
            if (opening) {
              listElements.add(new ListSeparator(TAG_OL.equalsIgnoreCase(tag)));
            } else if (!listElements.isEmpty()) {
              listElements.removeLast();
            }

            if (!opening && listElements.isEmpty()) output.append('\n');
            return;
          }

          if (TAG_LI.equalsIgnoreCase(tag) && opening && !listElements.isEmpty()) {
            listElements.getLast().append(output, listElements.size());
            return;
          }

          if (TAG_CODE.equalsIgnoreCase(tag)) {
            if (opening) startSpan(new TypefaceSpan("monospace"), output);
            else endSpan(TypefaceSpan.class, output);
          }

          if (TAG_PRE.equalsIgnoreCase(tag)) {
            output.append('\n');
            if (opening) startSpan(new TypefaceSpan("monospace"), output);
            else endSpan(TypefaceSpan.class, output);
          }

          if ((TAG_ROOT.equalsIgnoreCase(tag) || TAG_HTML.equalsIgnoreCase(tag)) && !opening) {
            // Remove leading newlines
            while (output.length() > 0 && output.charAt(0) == '\n') output.delete(0, 1);

            // Remove trailing newlines
            int last = output.length() - 1;
            while (last >= 0 && output.charAt(last) == '\n') {
              output.delete(last, last + 1);
              last = output.length() - 1;
            }

            QuoteSpan[] quoteSpans = output.getSpans(0, output.length(), QuoteSpan.class);
            for (QuoteSpan span : quoteSpans) {
              int start = output.getSpanStart(span);
              int end = output.getSpanEnd(span);
              output.removeSpan(span);
              output.setSpan(new ReplySpan(), start, end, SPAN_EXCLUSIVE_EXCLUSIVE);
            }
          }
        }
Example #27
0
  /**
   * @param ver Version.
   * @param preferLoc Whether or not to prefer local candidates.
   */
  private void remove0(GridCacheVersion ver, boolean preferLoc) {
    if (preferLoc) {
      if (!remove0(locs, ver)) remove0(rmts, ver);
    } else if (!remove0(rmts, ver)) remove0(locs, ver);

    if (locs != null && locs.isEmpty()) locs = null;

    if (rmts != null && rmts.isEmpty()) rmts = null;
  }
Example #28
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;
  }
Example #29
0
  @EventHandler
  public void onPlayerDeath(PlayerDeathEvent event) {
    if (plugin.isBattleNight(event.getEntity())) return;

    boolean filledDeathChest = false;
    boolean filledSpawnChest = false;

    int originalDrops = event.getDrops().size();

    if (event.getDrops().isEmpty() && event.getDroppedExp() == 0) return;
    Player player = (Player) event.getEntity();

    int exp = player.getTotalExperience();

    LinkedList<ItemStack> toRemove = saveToDeathChest(player);
    filledDeathChest = !toRemove.isEmpty();

    if (exp != player.getTotalExperience()) {
      event.setDroppedExp(0);
    }

    for (ItemStack item : toRemove) event.getDrops().remove(item);

    if (event.getDrops().isEmpty()
        && (event.getDroppedExp() == 0 || plugin.getConfigManager().getEXPMulti() == 0)) return;

    if (!event.getDrops().isEmpty() || player.getTotalExperience() != 0) {
      toRemove = plugin.interactSpawnContainerController().createSpawnContainer(player);

      if (plugin.getConfigManager().getSpawnContainerUsage().equals(SpawnSign.class)
          && player.getTotalExperience() != exp) event.setDroppedExp(0);

      if (toRemove != null) {
        filledSpawnChest = !toRemove.isEmpty();

        for (ItemStack item : toRemove) event.getDrops().remove(item);
      }
    }

    if (event.getDrops().size() > 0 && filledDeathChest) {
      int maxTransfer = plugin.getChestContainer().getMaxTransferLimit(player);
      if (originalDrops > maxTransfer)
        player.sendMessage(
            ChatColor.RED
                + "Only "
                + maxTransfer
                + " items could be transfered. The rest is dropped at your death location.");
      else
        player.sendMessage(
            ChatColor.RED
                + "Your total inventory did not fit in the box. The rest items were dropped at your death location.");
    }

    if (!filledDeathChest && !filledSpawnChest && simplePermissionUse(player))
      player.sendMessage(ChatColor.RED + "You don't have a Chest set yet. Sorry for you. :(");
  }
Example #30
0
  /**
   * Appends all of the elements in the specified collection to the end of this list, in the order
   * that they are returned by the specified collection's Iterator.
   *
   * @param list1 the first list
   * @param list2 the second list
   * @return merged lists
   * @throws NullPointerException any of specified lists is null
   */
  public static <T> LinkedList<T> chain(LinkedList<T> list1, LinkedList<T> list2) {
    checkNotNull(list1, "list1 should not be null");
    checkNotNull(list2, "list2 should not be null");

    if (list1.isEmpty()) return list2;
    if (list2.isEmpty()) return list1;

    list1.addAll(list2);
    return list1;
  }