Beispiel #1
0
  public long removeMessage(final List<MessageExt> msgs) {
    long result = -1;
    final long now = System.currentTimeMillis();
    try {
      this.lockTreeMap.writeLock().lockInterruptibly();
      this.lastConsumeTimestamp = now;
      try {
        if (!msgTreeMap.isEmpty()) {
          result = this.queueOffsetMax + 1;
          int removedCnt = 0;
          for (MessageExt msg : msgs) {
            MessageExt prev = msgTreeMap.remove(msg.getQueueOffset());
            if (prev != null) {
              removedCnt--;
            }
          }
          msgCount.addAndGet(removedCnt);

          if (!msgTreeMap.isEmpty()) {
            result = msgTreeMap.firstKey();
          }
        }
      } finally {
        this.lockTreeMap.writeLock().unlock();
      }
    } catch (Throwable t) {
      log.error("removeMessage exception", t);
    }

    return result;
  }
  @Override
  public boolean next(RecordIdentifier recordIdentifier, OrcStruct prev) throws IOException {
    boolean keysSame = true;
    while (keysSame && primary != null) {

      // The primary's nextRecord is the next value to return
      OrcStruct current = primary.nextRecord;
      recordIdentifier.set(primary.key);

      // Advance the primary reader to the next record
      primary.next(extraValue);

      // Save the current record as the new extraValue for next time so that
      // we minimize allocations
      extraValue = current;

      // now that the primary reader has advanced, we need to see if we
      // continue to read it or move to the secondary.
      if (primary.nextRecord == null || primary.key.compareTo(secondaryKey) > 0) {

        // if the primary isn't done, push it back into the readers
        if (primary.nextRecord != null) {
          readers.put(primary.key, primary);
        }

        // update primary and secondaryKey
        Map.Entry<ReaderKey, ReaderPair> entry = readers.pollFirstEntry();
        if (entry != null) {
          primary = entry.getValue();
          if (readers.isEmpty()) {
            secondaryKey = null;
          } else {
            secondaryKey = readers.firstKey();
          }
        } else {
          primary = null;
        }
      }

      // if this transaction isn't ok, skip over it
      if (!validTxnList.isTxnValid(((ReaderKey) recordIdentifier).getCurrentTransactionId())) {
        continue;
      }

      // if we are collapsing, figure out if this is a new row
      if (collapse) {
        keysSame = prevKey.compareRow(recordIdentifier) == 0;
        if (!keysSame) {
          prevKey.set(recordIdentifier);
        }
      } else {
        keysSame = false;
      }

      // set the output record by fiddling with the pointers so that we can
      // avoid a copy.
      prev.linkFields(current);
    }
    return !keysSame;
  }
  /**
   * Skip a specified number of entries and return the resulting position.
   *
   * @param startPosition the current position
   * @param entriesToSkip the numbers of entries to skip
   * @return the new position
   */
  protected synchronized Position skipEntries(Position startPosition, int entriesToSkip) {
    log.debug("[{}] Skipping {} entries from position {}", va(name, entriesToSkip, startPosition));
    long ledgerId = startPosition.getLedgerId();
    entriesToSkip += startPosition.getEntryId();

    while (entriesToSkip > 0) {
      if (currentLedger != null && ledgerId == currentLedger.getId()) {
        checkArgument(entriesToSkip <= (currentLedger.getLastAddConfirmed() + 1));
        return new Position(ledgerId, entriesToSkip);
      } else {
        LedgerStat ledger = ledgers.get(ledgerId);
        if (ledger == null) {
          checkArgument(!ledgers.isEmpty());
          ledgerId = ledgers.ceilingKey(ledgerId);
          continue;
        }

        if (entriesToSkip < ledger.getEntriesCount()) {
          return new Position(ledgerId, entriesToSkip);
        } else {
          // Move to next ledger
          entriesToSkip -= ledger.getEntriesCount();
          ledgerId = ledgers.ceilingKey(ledgerId + 1);
        }
      }
    }

    return new Position(ledgerId, 0);
  }
Beispiel #4
0
  /**
   * Return a color interpolated within the color list of this paint scale. The interpolation is a
   * linear one between the two colors in the list whose associated values frame the one given.
   */
  @Override
  public Color getPaint(double value) {
    if (colors.isEmpty()) return defaultColor;
    if (colors.size() == 1) return colors.get(colors.firstKey());

    if (value > upperBound) value = upperBound;
    if (value < lowerBound) value = lowerBound;
    Set<Double> keys = colors.keySet();
    double bottom = colors.firstKey();
    double top = colors.lastKey();
    for (double key : keys) {
      top = key;
      if (value < key) break;
      else bottom = top;
    }

    double alpha;
    if (top == bottom) alpha = 0; // we reached the end of the list
    else alpha = (value - bottom) / (top - bottom);

    Color colorBottom = colors.get(bottom);
    Color colorTop = colors.get(top);
    int red = (int) ((1 - alpha) * colorBottom.getRed() + alpha * colorTop.getRed());
    int green = (int) ((1 - alpha) * colorBottom.getGreen() + alpha * colorTop.getGreen());
    int blue = (int) ((1 - alpha) * colorBottom.getBlue() + alpha * colorTop.getBlue());
    return new Color(red, green, blue);
  }
  @Override
  public boolean onChildClick(
      ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    final IndexItem e =
        (IndexItem)
            ((DownloadIndexAdapter) getListAdapter()).getChild(groupPosition, childPosition);
    String key = e.getFileName();
    final CheckBox ch = (CheckBox) v.findViewById(R.id.check_download_item);

    if (ch.isChecked()) {
      ch.setChecked(!ch.isChecked());
      entriesToDownload.remove(key);
      if (entriesToDownload.isEmpty()) {
        int x = getListView().getScrollX();
        int y = getListView().getScrollY();
        findViewById(R.id.DownloadButton).setVisibility(View.GONE);
        getListView().scrollTo(x, y);
      }
      return true;
    }

    final DownloadEntry entry = e.createDownloadEntry(DownloadIndexActivity.this);
    if (entry != null) {
      // if(!fileToUnzip.exists()){
      // builder.setMessage(MessageFormat.format(getString(R.string.download_question), baseName,
      // extractDateAndSize(e.getValue())));
      entriesToDownload.put(e.getFileName(), entry);
      int x = getListView().getScrollX();
      int y = getListView().getScrollY();
      findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
      getListView().scrollTo(x, y);
      ch.setChecked(!ch.isChecked());
    }
    return true;
  }
Beispiel #6
0
  /**
   * Método para reconocer los tokens más simples
   *
   * @param regex
   * @param conjuntoAut
   * @return boolean true si se crea un token, false si no es aceptado por ninguno.
   */
  public boolean tokenSimple(String regex, ArrayList<Automata> conjuntoAut) {
    TreeMap<String, Automata> aceptados =
        new TreeMap(
            new Comparator<String>() {
              @Override
              public int compare(String o1, String o2) {
                Integer a1 = o1.length();
                Integer a2 = o2.length();
                return a2 - a1;
              }
            });

    for (Automata automata : conjuntoAut) {
      if (sim.simular(regex, automata)) {
        aceptados.put(regex, automata);
      }
    }
    if (!aceptados.isEmpty()) {
      tokens.add(
          new Token(
              aceptados.firstEntry().getValue().getTipo(),
              aceptados.firstKey(),
              aceptados.firstEntry().getValue().isExceptKeywords()));

      return true;
    }

    return false;
  }
 /**
  * ContainerRequests with locality relaxation cannot be made at the same priority as
  * ContainerRequests without locality relaxation.
  */
 private void checkLocalityRelaxationConflict(
     Priority priority, Collection<String> locations, boolean relaxLocality) {
   Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests =
       this.remoteRequestsTable.get(priority);
   if (remoteRequests == null) {
     return;
   }
   // Locality relaxation will be set to relaxLocality for all implicitly
   // requested racks. Make sure that existing rack requests match this.
   for (String location : locations) {
     TreeMap<Resource, ResourceRequestInfo> reqs = remoteRequests.get(location);
     if (reqs != null && !reqs.isEmpty()) {
       boolean existingRelaxLocality =
           reqs.values().iterator().next().remoteRequest.getRelaxLocality();
       if (relaxLocality != existingRelaxLocality) {
         throw new InvalidContainerRequestException(
             "Cannot submit a "
                 + "ContainerRequest asking for location "
                 + location
                 + " with locality relaxation "
                 + relaxLocality
                 + " when it has "
                 + "already been requested with locality relaxation "
                 + existingRelaxLocality);
       }
     }
   }
 }
Beispiel #8
0
 /**
  * Obtains a {@code PeriodFields} from an amount and unit, by extending any fractional remainder
  * onto smaller units.
  *
  * <p>The parameters represent the two parts of a phrase like 'one-and-a-half Hours'. The
  * fractional parts will be distributed into the smaller units, and rounded down when no smaller
  * units exist. If the {@code fractionalAmount} is negative, the amount of the biggest unit will
  * be negative, the rest will be positive.
  *
  * @param fractionalAmount the amount of create with, positive or negative
  * @param unit the period unit, not null
  * @return the {@code PeriodFields} instance, not null
  */
 public static PeriodFields of(double fractionalAmount, PeriodUnit unit) {
   checkNotNull(unit, "PeriodUnit must not be null");
   PeriodUnit currentUnit = unit;
   double fudge = 0.000000000000001d;
   TreeMap<PeriodUnit, PeriodField> internalMap = createMap();
   do {
     long floor = (long) Math.floor(fractionalAmount + fudge);
     if (floor != 0) {
       internalMap.put(currentUnit, PeriodField.of(floor, currentUnit));
     }
     double remainder = fractionalAmount - floor; // will be positive
     PeriodField nextEquivalent = currentUnit.getNextEquivalentPeriod();
     if (nextEquivalent != null) {
       currentUnit = nextEquivalent.getUnit();
       fractionalAmount = remainder * nextEquivalent.getAmount();
       fudge *= nextEquivalent.getAmount();
     } else {
       // No smaller units exist, we're done
       currentUnit = null;
     }
   } while (currentUnit != null && Math.abs(fractionalAmount) > fudge);
   if (internalMap.isEmpty()) {
     return of(0L, unit);
   } else {
     return create(internalMap);
   }
 }
Beispiel #9
0
 // Pull the next message that needs an IGNORING response.  Once this
 // starts returning messages, poll() will always return null
 public VoltMessage drain() {
   if (!m_mustDrain || m_replayEntries.isEmpty()) {
     return null;
   }
   VoltMessage head = m_replayEntries.firstEntry().getValue().drain();
   while (head == null) {
     m_replayEntries.pollFirstEntry();
     if (!m_replayEntries.isEmpty()) {
       // This will end up null if the next ReplayEntry was just a sentinel.
       // We'll keep going.
       head = m_replayEntries.firstEntry().getValue().drain();
     } else {
       break;
     }
   }
   return head;
 }
Beispiel #10
0
    @Override
    public int propose(int value) {
      int myId = system.getProcessId();
      boolean amIAlive;
      if (amIAlive = alives.isEmpty()) alives.put(myId, value);

      for (int neighbour : system.getProcessNeighbourhood())
        system.sendMessage(neighbour, round, amIAlive ? value : null);

      while (awaitingMessages > 0) system.yield();

      int numOfAlives = alives.size();
      while (true) {
        if (alives.size() == 1) return alives.firstEntry().getValue();

        round++;

        if (alives.size() > 0) numOfAlives = alives.size();
        awaitingMessages = numOfAlives;

        if (!receivedForTheNextRounds.isEmpty())
          for (Map.Entry<Integer, Integer> entry :
              receivedForTheNextRounds.removeFirst().entrySet()) {
            awaitingMessages--;
            if (entry.getValue() == null) alives.remove(entry.getKey());
            else alives.put(entry.getKey(), entry.getValue());
          }

        if (amIAlive) {
          awaitingMessages--;
          if (random.nextInt(numOfAlives) == 0) {
            alives.put(myId, value);
            for (int neighbour : system.getProcessNeighbourhood())
              system.sendMessage(neighbour, round, value);
          } else {
            alives.remove(myId);
            for (int neighbour : system.getProcessNeighbourhood())
              system.sendMessage(neighbour, round, null);
          }
        }

        while (awaitingMessages > 0) system.yield();

        if (!alives.isEmpty() && !alives.containsKey(myId)) amIAlive = false;
      }
    }
Beispiel #11
0
  // Return the next correctly sequenced message or null if none exists.
  public VoltMessage poll() {
    if (m_mustDrain || m_replayEntries.isEmpty()) {
      return null;
    }
    if (m_replayEntries.firstEntry().getValue().isEmpty()) {
      m_replayEntries.pollFirstEntry();
    }
    // All the drain conditions depend on being blocked, which
    // we will only really know for sure when we try to poll().
    checkDrainCondition();
    if (m_mustDrain || m_replayEntries.isEmpty()) {
      return null;
    }

    VoltMessage m = m_replayEntries.firstEntry().getValue().poll();
    updateLastPolledTxnId(m_replayEntries.firstEntry().getKey(), (TransactionInfoBaseMessage) m);
    return m;
  }
  // 2: get the first collision
  public void resolveAllCollisionPrediction(long time, long dtms) {
    while (!collisionDetected.isEmpty()) {
      Entry<Long, CollisionPrediction> predEntry = collisionDetected.pollFirstEntry();
      //			Entry<Long, CollisionPrediction> nextEntry = collisionDetected.firstEntry();

      // check if this collision occur before any one else
      boolean first = true;
      for (Entry<Long, CollisionPrediction> pred2Check : collisionDetected.entrySet()) {
        if (predEntry.getKey() + predEntry.getValue().maxMomentError
            >= pred2Check.getKey() - pred2Check.getValue().maxMomentError) {
          first = false;
          break;
        }
      }

      // if first, then we can resolve this collision
      if (first) {
        // if it's too late, nothing to resolve, really.
        System.out.println("RESOLVEALL:  before " + predEntry.getKey() + ">" + time);
        long newTimePred = predEntry.getKey();
        if (predEntry.getValue().precisionMoment == Precision.INITIAL) {
          System.out.println("RESOLVEALL: increase rpecision first ");
          newTimePred = increaseCollisionPrecision(predEntry.getValue(), time, dtms);
        }
        System.out.println("RESOLVEALL:  after " + newTimePred + ">" + time);
        if (newTimePred > time) {
          System.out.println("RESOLVEALL: too late:" + newTimePred + ">" + time);
          return;
        }
        resolveCollisionPrediction(predEntry.getValue(), time, dtms);
      } else {
        // sinon, il faut améliorer la précision des différentes collisions
        HashMap<Long, CollisionPrediction> toReAdd = new HashMap<>();
        Iterator<Entry<Long, CollisionPrediction>> it = collisionDetected.entrySet().iterator();
        while (it.hasNext()) {
          Entry<Long, CollisionPrediction> pred2Check = it.next();
          // si la précision des autres m'empeche de me considérer premier
          if (predEntry.getKey() >= pred2Check.getKey() - pred2Check.getValue().maxMomentError
              && pred2Check.getValue().precisionMoment == Precision.INITIAL) {
            long newTimePred = increaseCollisionPrecision(pred2Check.getValue(), time, dtms);
            if (pred2Check.getValue().precisionMoment == Precision.CANTFIND)
              toReAdd.put(newTimePred, pred2Check.getValue());
            it.remove();
          }
        }
        collisionDetected.putAll(toReAdd);
        if (toReAdd.isEmpty()) {
          // si ma précision est le problème
          long newTimePred = increaseCollisionPrecision(predEntry.getValue(), time, dtms);
          if (predEntry.getValue().precisionMoment == Precision.CANTFIND)
            collisionDetected.put(newTimePred, predEntry.getValue());
        } else {
          collisionDetected.put(predEntry.getKey(), predEntry.getValue());
        }
      }
    }
  }
 private void updateBounds() {
   if (constantsMap.isEmpty()) {
     lowerBounds = null;
     upperBounds = null;
     return;
   }
   lowerBounds = ((Number) constantsMap.firstKey()).doubleValue();
   upperBounds = ((Number) constantsMap.lastKey()).doubleValue();
 }
 synchronized void clearPointerCaches(String url, VirtualFilePointerListener listener) {
   TreeMap<String, VirtualFilePointerImpl> urlToPointer = myUrlToPointerMaps.get(listener);
   if (urlToPointer == null && ApplicationManager.getApplication().isUnitTestMode()) return;
   assert urlToPointer != null;
   urlToPointer.remove(VfsUtil.urlToPath(url));
   if (urlToPointer.isEmpty()) {
     myUrlToPointerMaps.remove(listener);
   }
 }
  /**
   * Update the dialog contents.
   *
   * @param jheader The job portion of the dialog header.
   * @param job The queue job.
   * @param info The current job status information.
   */
  public void updateContents(
      String jheader, QueueJob job, QueueJobInfo info, SubProcessExecDetails details) {
    ActionAgenda agenda = job.getActionAgenda();
    QueueJobResults results = info.getResults();

    String dir = "-";
    if ((agenda != null) && (info.getOsType() != null))
      dir = agenda.getTargetPath(info.getOsType()).toString();

    String hostname = "";
    if (info.getHostname() != null) hostname = (" [" + info.getHostname() + "]");

    String command = "-";
    if (details != null) command = details.getCommand();

    TreeMap<String, String> env = new TreeMap<String, String>();
    if (details != null) env = details.getEnvironment();

    setHeader("Execution Details -" + jheader + hostname);

    pWorkingDirField.setText(dir);

    BaseAction action = job.getAction();
    pCommandLineLabel.setText(
        "Action Command:  " + action.getName() + " (v" + action.getVersionID() + ")");
    pCommandLineArea.setText(command);

    {
      Component comps[] = UIFactory.createTitledPanels();
      {
        JPanel tpanel = (JPanel) comps[0];
        JPanel vpanel = (JPanel) comps[1];

        if (!env.isEmpty()) {
          String last = env.lastKey();
          for (String key : env.keySet()) {
            String value = env.get(key);

            JTextField field =
                UIFactory.createTitledTextField(tpanel, key + ":", sTSize, vpanel, value, sVSize);
            field.setHorizontalAlignment(JLabel.LEFT);

            if (!key.equals(last)) UIFactory.addVerticalSpacer(tpanel, vpanel, 3);
          }
        } else {
          tpanel.add(Box.createRigidArea(new Dimension(sTSize, 0)));
          vpanel.add(Box.createHorizontalGlue());
        }
      }

      pEnvLabel.setText("Toolset Environment:  " + agenda.getToolset());
      pEnvScroll.setViewportView(comps[2]);
    }
  }
Beispiel #16
0
 private int[] toArray(TreeMap<Integer, Integer> map) {
   int[] rv = new int[map.lastKey() + 1];
   for (int i = 0; i < rv.length; i++) {
     rv[i] = -1;
   }
   while (!map.isEmpty()) {
     Entry<Integer, Integer> e = map.pollFirstEntry();
     rv[e.getKey()] = e.getValue();
   }
   return rv;
 }
Beispiel #17
0
  /**
   * Given a token that may or may not be exactly equal to one of the endpoint's tokens, returns the
   * token of the endpoint that is responsible for storing this token.
   *
   * @throws NoSuchElementException if there are no known tokens
   */
  BigInteger getResponsibleToken(BigInteger token) {
    if (tokenToEndPointMap_.isEmpty()) {
      throw new NoSuchElementException("No tokens in ring!");
    }

    // find smallest key >= token
    BigInteger ctoken = tokenToEndPointMap_.ceilingKey(token);

    if (ctoken != null) return ctoken;

    return tokenToEndPointMap_.firstKey();
  }
  @Test
  public void test2Categorias() {
    TreeMap<CategoryRestaurant, CategoryRestaurantRanking> list = ranking.getList();

    Assert.assertEquals(crA, list.firstEntry().getKey());
    list.remove(crA);

    Assert.assertEquals(crB, list.firstEntry().getKey());
    list.remove(crB);

    Assert.assertTrue(list.isEmpty());
  }
Beispiel #19
0
 /**
  * Find the IP address of the node that has the specified file
  *
  * @param FileName name of the file that has to be found
  * @return null if no nodes in the system, else return IP address of the node.
  */
 public InetAddress getLocation(String FileName) {
   if (NodeList.isEmpty()) {
     return null;
   }
   Hasher myHasher = new Hasher();
   int fileID = myHasher.Hash(FileName);
   Integer NodeID = NodeList.ceilingKey(fileID);
   if (NodeID == null) {
     NodeID = NodeList.firstKey();
   }
   return NodeList.get(NodeID);
 }
  public static <T> T getNextKnownValue(
      Integer packetNumber, Unit unit, Map<Unit, TreeMap<Integer, T>> histogramMap) {
    TreeMap<Integer, T> packetNumberTMap = histogramMap.get(unit);

    if (packetNumberTMap == null) return null;

    if (packetNumberTMap.isEmpty()) return null;

    Map.Entry<Integer, T> entry = packetNumberTMap.ceilingEntry(packetNumber);

    if (entry != null) return entry.getValue();
    else return null;
  }
 @Override
 public InetSocketAddress route(byte[] key, int partition) {
   TreeMap<Integer, InetSocketAddress> circle = circleMap.get(partition);
   if (circle == null || circle.isEmpty()) {
     return null;
   }
   int hash = (int) hashProvider.hash(key);
   if (!circle.containsKey(hash)) {
     SortedMap<Integer, InetSocketAddress> tailMap = circle.tailMap(hash);
     hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
   }
   return circle.get(hash);
 }
  private NetconfOperationExecution getNetconfOperationWithHighestPriority(
      Document message, NetconfSession session) {

    TreeMap<HandlingPriority, NetconfOperation> sortedByPriority =
        getSortedNetconfOperationsWithCanHandle(message, session);

    Preconditions.checkArgument(
        sortedByPriority.isEmpty() == false,
        "No %s available to handleWithNoSubsequentOperations message %s",
        NetconfOperation.class.getName(),
        XmlUtil.toString(message));

    return NetconfOperationExecution.createExecutionChain(
        sortedByPriority, sortedByPriority.lastKey());
  }
Beispiel #23
0
 boolean getSetData() {
   inputKeyColName = new TreeMap<String, String>();
   aimKeyColName = new TreeMap<String, String>();
   Collection<CyColumn> columnList = wgs.net.getDefaultNodeTable().getColumns();
   CyColumn col = null;
   Iterator<CyColumn> iter = columnList.iterator();
   while (iter.hasNext()) {
     col = iter.next();
     String colName;
     if (col.getType() != Double.class) continue;
     else colName = col.getName();
     if (colName.length() > lengthID) {
       if (colName.substring(0, lengthID).equals(inputSetID))
         inputKeyColName.put(colName.substring(lengthID), colName);
       if (colName.substring(0, lengthID).equals(outputAimID))
         aimKeyColName.put(colName.substring(lengthID), colName);
     }
   }
   if (inputKeyColName.isEmpty()) return false;
   Iterator<String> setIt = inputKeyColName.keySet().iterator();
   Iterator<String> aimIt = aimKeyColName.keySet().iterator();
   while (setIt.hasNext() & aimIt.hasNext()) if (!setIt.next().equals(aimIt.next())) return false;
   activIn = new double[inputKeyColName.keySet().size()][];
   activAim = new double[aimKeyColName.keySet().size()][];
   int set = 0;
   for (String key : inputKeyColName.keySet()) {
     activIn[set] = new double[wgs.nodes.size()];
     for (int n = 0; n < wgs.nodes.size(); n++) {
       Double d = wgs.net.getRow(wgs.nodes.get(n)).get(inputKeyColName.get(key), Double.class);
       if (d != null) {
         activIn[set][n] = d;
         if (d != 0.0) menuUtils.srcDialog.add(n);
       } else activIn[set][n] = 0.0;
     }
     activAim[set] = new double[wgs.nodes.size()];
     for (int n = 0; n < wgs.nodes.size(); n++) {
       Double d = wgs.net.getRow(wgs.nodes.get(n)).get(aimKeyColName.get(key), Double.class);
       if (d != null) activAim[set][n] = d;
       else activAim[set][n] = 0.0;
     }
     set++;
   }
   activOk = new int[inputKeyColName.keySet().size()];
   activNo = new int[inputKeyColName.keySet().size()];
   inhibOk = new int[inputKeyColName.keySet().size()];
   inhibNo = new int[inputKeyColName.keySet().size()];
   return true;
 }
Beispiel #24
0
  /** Code completion. */
  private void complete() {
    if (selected()) return;

    // find first character
    final int caret = editor.pos(), startPos = editor.completionStart();
    final String prefix = string(substring(editor.text(), startPos, caret));
    if (prefix.isEmpty()) return;

    // find insertion candidates
    final TreeMap<String, String> tmp = new TreeMap<>();
    for (final Entry<String, String> entry : REPLACE.entrySet()) {
      final String key = entry.getKey();
      if (key.startsWith(prefix)) tmp.put(key, entry.getValue());
    }

    if (tmp.size() == 1) {
      // insert single candidate
      complete(tmp.values().iterator().next(), startPos);
    } else if (!tmp.isEmpty()) {
      // show popup menu
      final JPopupMenu pm = new JPopupMenu();
      final ActionListener al =
          new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent ae) {
              complete(ae.getActionCommand().replaceAll("^.*?\\] ", ""), startPos);
            }
          };

      for (final Entry<String, String> entry : tmp.entrySet()) {
        final JMenuItem mi = new JMenuItem("[" + entry.getKey() + "] " + entry.getValue());
        pm.add(mi);
        mi.addActionListener(al);
      }
      pm.addSeparator();
      final JMenuItem mi = new JMenuItem(Text.INPUT + Text.COLS + prefix);
      mi.setEnabled(false);
      pm.add(mi);

      final int[] cursor = rend.cursor();
      pm.show(this, cursor[0], cursor[1]);

      // highlight first entry
      final MenuElement[] me = {pm, (JMenuItem) pm.getComponent(0)};
      MenuSelectionManager.defaultManager().setSelectedPath(me);
    }
  }
 protected void write(Writer writer, String prefix) throws IOException {
   if (m_name == null) {
     this.writeEncoded(writer, m_contents);
     return;
   }
   writer.write(prefix + '<');
   writer.write(m_name);
   if (!m_attributeMap.isEmpty()) {
     for (String key : m_attributeNames) {
       String value = getAttributeInternal(key);
       if (value != null) {
         writer.write(' ');
         writer.write(key);
         writer.write('=');
         writer.write('"');
         this.writeEncoded(writer, value);
         writer.write('"');
       }
     }
   }
   if (!m_children.isEmpty()) {
     writer.write('>');
     writer.write("\n");
     Iterator<?> en = this.getChildren().iterator();
     while (en.hasNext()) {
       SimpleXmlElement child = (SimpleXmlElement) en.next();
       child.write(writer, prefix + "  ");
     }
     writer.write(prefix + '<');
     writer.write('/');
     writer.write(m_name);
     writer.write('>');
     writer.write("\n");
   } else if ((m_contents != null) && (m_contents.length() > 0)) {
     writer.write('>');
     this.writeEncoded(writer, m_contents);
     writer.write('<');
     writer.write('/');
     writer.write(m_name);
     writer.write('>');
     writer.write("\n");
   } else { // this.children.isEmpty()
     writer.write('/');
     writer.write('>');
     writer.write("\n");
   }
 }
  public String nextCommand() {
    String nextCommand = "WAIT";

    if (!rotationMap.isEmpty()) {
      Room rotatedRoom = rotationMap.remove(rotationMap.firstKey());

      if (rotatedRoom.getRotation() > 0) {
        rotatedRoom.rotateRightActType();

        nextCommand = rotatedRoom.getPosition() + " RIGHT";
      } else if (rotatedRoom.getRotation() < 0) {
        rotatedRoom.rotateLeftActType();

        nextCommand = rotatedRoom.getPosition() + " LEFT";
      }
    }

    return nextCommand;
  }
Beispiel #27
0
 private void checkDrainCondition() {
   // Don't ever go backwards once the drain decision is made.
   if (m_mustDrain) {
     return;
   }
   // if we've got things to sequence, check to if we're blocked
   if (!m_replayEntries.isEmpty()) {
     ReplayEntry head = m_replayEntries.firstEntry().getValue();
     if (!head.isReady()) {
       // if we're blocked, see if we have a sentinel or a fragment.
       // we know we have one or the other but not both.  Neither
       // means we wouldn't exist, and both would make us ready.
       // if it's the sentinel, see if the MPI's command log is done
       if (head.hasSentinel() && m_mpiEOLReached) {
         m_mustDrain = true;
       }
     }
   }
 }
Beispiel #28
0
 /** @return Sorted list of warps with most recent players listed first */
 public Collection<UUID> listSortedWarps() {
   // Bigger value of time means a more recent login
   TreeMap<Long, UUID> map = new TreeMap<Long, UUID>();
   for (UUID uuid : warpList.keySet()) {
     // If never played, will be zero
     long lastPlayed = plugin.getServer().getOfflinePlayer(uuid).getLastPlayed();
     // This aims to avoid the chance that players logged off at exactly the same time
     if (!map.isEmpty() && map.containsKey(lastPlayed)) {
       lastPlayed = map.firstKey() - 1;
     }
     map.put(lastPlayed, uuid);
   }
   Collection<UUID> result = map.descendingMap().values();
   // Fire event
   WarpListEvent event = new WarpListEvent(plugin, result);
   plugin.getServer().getPluginManager().callEvent(event);
   // Get the result of any changes by listeners
   result = event.getWarps();
   return result;
 }
        @Override
        protected RevTree read(ObjectId id, BufferedReader reader, TYPE type) throws IOException {
          Preconditions.checkArgument(TYPE.TREE.equals(type), "Wrong type: %s", type.name());
          Builder<Node> features = ImmutableList.builder();
          Builder<Node> trees = ImmutableList.builder();
          TreeMap<Integer, Bucket> subtrees = Maps.newTreeMap();
          long size = Long.parseLong(parseLine(requireLine(reader), "size"));
          int numTrees = Integer.parseInt(parseLine(requireLine(reader), "numtrees"));
          String line;
          while ((line = reader.readLine()) != null) {
            Preconditions.checkArgument(!line.isEmpty(), "Empty tree element definition");
            ArrayList<String> tokens = Lists.newArrayList(Splitter.on('\t').split(line));
            String nodeType = tokens.get(0);
            if (nodeType.equals(TextWriter.TreeNode.REF.name())) {
              Node entryRef = parseNodeLine(line);
              if (entryRef.getType().equals(TYPE.TREE)) {
                trees.add(entryRef);
              } else {
                features.add(entryRef);
              }
            } else if (nodeType.equals(TextWriter.TreeNode.BUCKET.name())) {
              Preconditions.checkArgument(tokens.size() == 4, "Wrong bucket definition: %s", line);
              Integer idx = Integer.parseInt(tokens.get(1));
              ObjectId bucketId = ObjectId.valueOf(tokens.get(2));
              Envelope bounds = parseBBox(tokens.get(3));
              Bucket bucket = Bucket.create(bucketId, bounds);
              subtrees.put(idx, bucket);
            } else {
              throw new IllegalArgumentException("Wrong tree element definition: " + line);
            }
          }

          RevTree tree;
          if (subtrees.isEmpty()) {
            tree = RevTreeImpl.createLeafTree(id, size, features.build(), trees.build());
          } else {
            tree = RevTreeImpl.createNodeTree(id, size, numTrees, subtrees);
          }
          return tree;
        }
  protected synchronized void asyncReadEntries(OpReadEntry opReadEntry) {
    if (state == State.Fenced) {
      opReadEntry.failed(new ManagedLedgerFencedException());
      return;
    }

    LedgerHandle ledger = null;

    if (opReadEntry.readPosition.getLedgerId() == -1) {
      if (ledgers.isEmpty()) {
        // The ManagedLedger is completely empty
        opReadEntry.emptyResponse();
        return;
      }

      // Initialize the position on the first entry for the first ledger
      // in the set
      opReadEntry.readPosition = new Position(ledgers.firstKey(), 0);
    }

    long id = opReadEntry.readPosition.getLedgerId();

    if (id == currentLedger.getId()) {
      // Current writing ledger is not in the cache (since we don't want
      // it to be automatically evicted), and we cannot use 2 different
      // ledger handles (read & write)for the same ledger.
      ledger = currentLedger;
    } else {
      ledger = ledgerCache.getIfPresent(id);
      if (ledger == null) {
        // Open the ledger and cache the handle
        log.debug("[{}] Asynchronously opening ledger {} for read", name, id);
        bookKeeper.asyncOpenLedger(
            id, config.getDigestType(), config.getPassword(), this, opReadEntry);
        return;
      }
    }

    internalReadFromLedger(ledger, opReadEntry);
  }