/**
   * Returns submap of x and y values according to the given start and end
   *
   * @param start start x value
   * @param stop stop x value
   * @return a submap of x and y values
   */
  public synchronized SortedMap<Double, Double> getRange(
      double start, double stop, int beforeAfterPoints) {
    // we need to add one point before the start and one point after the end (if
    // there are any)
    // to ensure that line doesn't end before the end of the screen

    // this would be simply: start = mXY.lowerKey(start) but NavigableMap is
    // available since API 9
    SortedMap<Double, Double> headMap = mXY.headMap(start);
    if (!headMap.isEmpty()) {
      start = headMap.lastKey();
    }

    // this would be simply: end = mXY.higherKey(end) but NavigableMap is
    // available since API 9
    // so we have to do this hack in order to support older versions
    SortedMap<Double, Double> tailMap = mXY.tailMap(stop);
    if (!tailMap.isEmpty()) {
      Iterator<Double> tailIterator = tailMap.keySet().iterator();
      Double next = tailIterator.next();
      if (tailIterator.hasNext()) {
        stop = tailIterator.next();
      } else {
        stop += next;
      }
    }
    return new TreeMap<Double, Double>(mXY.subMap(start, stop));
  }
Exemplo n.º 2
0
 public T get(Object key) {
   if (circle.isEmpty()) {
     return null;
   }
   int hash = hashFunction.hash(key);
   if (!circle.containsKey(hash)) {
     SortedMap<Integer, T> tailMap = circle.tailMap(hash);
     hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
   }
   return circle.get(hash);
 }
Exemplo n.º 3
0
 private OperationsNodeInfo getNearest(byte[] hash) {
   if (circle.isEmpty()) {
     return null;
   }
   if (circle.size() == 1) {
     return circle.get(circle.firstKey());
   }
   SortedMap<byte[], OperationsNodeInfo> tailMap = circle.tailMap(hash);
   hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
   return circle.get(hash);
 }
Exemplo n.º 4
0
  /** MemcachedClient calls this method to handle IO over the connections. */
  @SuppressWarnings("unchecked")
  public void handleIO() throws IOException {
    if (shutDown) {
      throw new IOException("No IO while shut down");
    }

    // Deal with all of the stuff that's been added, but may not be marked
    // writable.
    handleInputQueue();
    getLogger().debug("Done dealing with queue.");

    long delay = 0;
    if (!reconnectQueue.isEmpty()) {
      long now = System.currentTimeMillis();
      long then = reconnectQueue.firstKey();
      delay = Math.max(then - now, 1);
    }
    getLogger().debug("Selecting with delay of %sms", delay);
    assert selectorsMakeSense() : "Selectors don't make sense.";
    int selected = selector.select(delay);
    Set<SelectionKey> selectedKeys = selector.selectedKeys();

    if (selectedKeys.isEmpty() && !shutDown) {
      getLogger().debug("No selectors ready, interrupted: " + Thread.interrupted());
      if (++emptySelects > DOUBLE_CHECK_EMPTY) {
        for (SelectionKey sk : selector.keys()) {
          getLogger().info("%s has %s, interested in %s", sk, sk.readyOps(), sk.interestOps());
          if (sk.readyOps() != 0) {
            getLogger().info("%s has a ready op, handling IO", sk);
            handleIO(sk);
          } else {
            queueReconnect((MemcachedNode) sk.attachment());
          }
        }
        assert emptySelects < EXCESSIVE_EMPTY : "Too many empty selects";
      }
    } else {
      getLogger().debug("Selected %d, selected %d keys", selected, selectedKeys.size());
      emptySelects = 0;
      for (SelectionKey sk : selectedKeys) {
        handleIO(sk);
      } // for each selector
      selectedKeys.clear();
    }

    if (!shutDown && !reconnectQueue.isEmpty()) {
      attemptReconnects();
    }
  }
  @Override
  public void select(
      final String statementName, final Object parameterObject, final ResultHandler handler) {
    if (isSqlAuditorBehaviorEnabled()) {
      getSqlAuditor()
          .audit(
              statementName,
              getSqlByStatementName(statementName, parameterObject),
              parameterObject);
    }
    if (isPartitioningBehaviorEnabled()) {
      SortedMap<String, DataSource> dsMap =
          lookupDataSourcesByRouter(statementName, parameterObject);
      if (dsMap != null && !dsMap.isEmpty()) {
        SqlSessionCallback action =
            new SqlSessionCallback() {
              @Override
              public Object doInSession(SqlSession sqlSession) {
                sqlSession.select(statementName, parameterObject, handler);
                return null;
              }
            };

        if (dsMap.size() == 1) {
          executeWith(dsMap.get(dsMap.firstKey()), action);
        } else {
          executeInConcurrency(action, dsMap);
        }
      }
    }
    super.select(statementName, parameterObject, handler);
  }
  @Override
  public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(name()).field(Fields.TYPE, CONTENT_TYPE);
    if (indexAnalyzer.name().equals(searchAnalyzer.name())) {
      builder.field(Fields.ANALYZER, indexAnalyzer.name());
    } else {
      builder
          .field(Fields.INDEX_ANALYZER.getPreferredName(), indexAnalyzer.name())
          .field(Fields.SEARCH_ANALYZER.getPreferredName(), searchAnalyzer.name());
    }
    builder.field(Fields.PAYLOADS, this.payloads);
    builder.field(Fields.PRESERVE_SEPARATORS.getPreferredName(), this.preserveSeparators);
    builder.field(
        Fields.PRESERVE_POSITION_INCREMENTS.getPreferredName(), this.preservePositionIncrements);
    builder.field(Fields.MAX_INPUT_LENGTH.getPreferredName(), this.maxInputLength);
    multiFields.toXContent(builder, params);

    if (!contextMapping.isEmpty()) {
      builder.startObject(Fields.CONTEXT);
      for (ContextMapping mapping : contextMapping.values()) {
        builder.value(mapping);
      }
      builder.endObject();
    }

    return builder.endObject();
  }
Exemplo n.º 7
0
  private List<ChatMessage> sanitizeMap(final SortedMap<Date, ChatMessage> aMap) {
    if (aMap.isEmpty() || aMap.size() == 1) return Lists.newArrayList(aMap.values());

    final LinkedList<ChatMessage> ret = Lists.newLinkedList(aMap.values());
    final ListIterator<ChatMessage> i = ret.listIterator();
    ChatMessage prevMsg = i.next();
    do {
      ChatMessage msg = i.next();
      if (!msg.getPreviousMessageDate().equals(prevMsg.getDate())) {
        if (msg.getPreviousMessageDate().before(prevMsg.getDate())) {
          msg.setPreviousMessageDate(prevMsg.getDate());
        } else {
          final ChatMessage tmp =
              createLostMessageBetween(
                  msg.getRoom(), prevMsg.getDate(), msg.getPreviousMessageDate());
          aMap.put(tmp.getDate(), tmp);
          i.previous();
          i.add(tmp);
          i.next();
          msg = tmp;
        }
      }
      prevMsg = msg;
    } while (i.hasNext());

    return ret;
  }
  private void collectTimerReports(
      List<DBObject> docs, SortedMap<String, Timer> timers, Date timestamp) {
    if (timers.isEmpty()) return;
    for (Map.Entry<String, Timer> entry : timers.entrySet()) {
      final BasicDBObject report = getBasicDBObject(timestamp, entry.getKey(), "timer");
      final Timer v = entry.getValue();
      final Snapshot s = v.getSnapshot();
      // meter part
      report.put("count", v.getCount());
      report.put("rate-unit", getRateUnit());
      report.put("1-minute-rate", convertRate(v.getOneMinuteRate()));
      report.put("5-minute-rate", convertRate(v.getFiveMinuteRate()));
      report.put("15-minute-rate", convertRate(v.getFifteenMinuteRate()));
      report.put("mean-rate", convertRate(v.getMeanRate()));

      // histogram part
      report.put("duration-unit", getDurationUnit());
      report.put("75-percentile", convertDuration(s.get75thPercentile()));
      report.put("95-percentile", convertDuration(s.get95thPercentile()));
      report.put("98-percentile", convertDuration(s.get98thPercentile()));
      report.put("99-percentile", convertDuration(s.get99thPercentile()));
      report.put("999-percentile", convertDuration(s.get999thPercentile()));
      report.put("max", convertDuration(s.getMax()));
      report.put("min", convertDuration(s.getMin()));
      report.put("mean", convertDuration(s.getMean()));
      report.put("median", convertDuration(s.getMedian()));
      report.put("stddev", convertDuration(s.getStdDev()));
      docs.add(report);
    }
  }
 public void testDescendingSubMapContents2() {
   ConcurrentNavigableMap map = dmap5();
   SortedMap sm = map.subMap(m2, m3);
   assertEquals(1, sm.size());
   assertEquals(m2, sm.firstKey());
   assertEquals(m2, sm.lastKey());
   assertFalse(sm.containsKey(m1));
   assertTrue(sm.containsKey(m2));
   assertFalse(sm.containsKey(m3));
   assertFalse(sm.containsKey(m4));
   assertFalse(sm.containsKey(m5));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(m2));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(m3), null);
   assertEquals(4, map.size());
 }
 public void testSubMapContents2() {
   ConcurrentNavigableMap map = map5();
   SortedMap sm = map.subMap(two, three);
   assertEquals(1, sm.size());
   assertEquals(two, sm.firstKey());
   assertEquals(two, sm.lastKey());
   assertFalse(sm.containsKey(one));
   assertTrue(sm.containsKey(two));
   assertFalse(sm.containsKey(three));
   assertFalse(sm.containsKey(four));
   assertFalse(sm.containsKey(five));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(two));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(three), null);
   assertEquals(4, map.size());
 }
Exemplo n.º 11
0
 private void nastavPatterned() {
   if (blokujEventy) {
     return;
   }
   final RenderSettings.Patterned p = patterned.copy();
   final int index = getSelectedIndex();
   // aby tam vůbec vešel
   if (index >= 0) {
     final String key = keys.get(index);
     if (!geotaggingPatterns.isEmpty()) { // mame data geotaggingu
       p.setPatternNumberCilovy(key);
       if (souradnicovePatterns.containsKey(key)) {
         p.setPatternNumberPredbezny(key);
       }
     } else { // mame jen zakladni data
       p.setPatternNumberPredbezny(key);
       if (p.getPatternNumberCilovy() != null
           && souradnicovePatterns.containsKey(p.getPatternNumberCilovy())) {
         p.setPatternNumberCilovy(key);
       }
     }
   }
   p.setText((String) getSelectedItem());
   setPatterned(p);
 }
Exemplo n.º 12
0
 public List<NamedTestResult> getNamedTestResults() {
   if (namedTestResults.isEmpty()) {
     return Lists.newArrayList();
   } else {
     return convert(namedTestResults.entrySet(), fromMapEntriesToNamedTestResults());
   }
 }
Exemplo n.º 13
0
 /**
  * Returns the largest key in the symbol table less than or equal to <tt>key</tt>.
  *
  * @return the largest key in the symbol table less than or equal to <tt>key</tt>
  * @param key the key
  * @throws NoSuchElementException if the symbol table is empty
  * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>
  */
 public Key floor(Key key) {
   if (key == null) throw new NullPointerException("called floor() with null key");
   // headMap does not include key if present (!)
   if (st.containsKey(key)) return key;
   SortedMap<Key, Value> head = st.headMap(key);
   if (head.isEmpty()) throw new NoSuchElementException();
   return head.lastKey();
 }
Exemplo n.º 14
0
  /** Returns the oldest build in the record. */
  @Exported
  @QuickSilver
  public RunT getFirstBuild() {
    SortedMap<Integer, ? extends RunT> runs = _getRuns();

    if (runs.isEmpty()) return null;
    return runs.get(runs.lastKey());
  }
Exemplo n.º 15
0
  public EntityKnowledge getMainBase() {
    SortedMap<Integer, EntityKnowledge> bases = allies.get(Names.BASE);
    if ((bases == null) || (bases.isEmpty())) {
      return null;
    }
    Integer first = bases.firstKey();

    return bases.get(first);
  }
  private void collectGaugeReports(
      List<DBObject> docs, SortedMap<String, Gauge> gauges, Date timestamp) {
    if (gauges.isEmpty()) return;

    for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
      final BasicDBObject report = getBasicDBObject(timestamp, entry.getKey(), "gauge");
      report.put("value", entry.getValue().getValue());
      docs.add(report);
    }
  }
  /**
   * Build the time-series from the builder.
   *
   * @return a time-series containing the entries from the builder
   */
  public LocalDateDoubleTimeSeries build() {

    if (entries.isEmpty()) {
      return LocalDateDoubleTimeSeries.empty();
    }

    // Depending on how dense the data is, judge which type of time series
    // is the best fit
    return density() > DENSITY_THRESHOLD ? createDenseSeries() : createSparseSeries();
  }
  private void collectCounterReports(
      List<DBObject> docs, SortedMap<String, Counter> counters, Date timestamp) {
    if (counters.isEmpty()) return;

    for (Map.Entry<String, Counter> entry : counters.entrySet()) {
      final BasicDBObject report = getBasicDBObject(timestamp, entry.getKey(), "counter");
      report.put("count", entry.getValue().getCount());
      docs.add(report);
    }
  }
Exemplo n.º 19
0
  private Date maxLastKey(SortedMap<Date, Double> firstSerie, SortedMap<Date, Double> secondSerie)
      throws NotEnoughDataException {

    Date maxDate = null;
    if (secondSerie.isEmpty() && firstSerie.isEmpty()) {
      throw new NotEnoughDataException(
          null, "No prediction data : No prediction period can be infered.", new Exception());
    } else if (secondSerie.isEmpty()) {
      maxDate = firstSerie.lastKey();
    } else if (firstSerie.isEmpty()) {
      maxDate = secondSerie.lastKey();
    } else {
      maxDate =
          (secondSerie.lastKey().after(firstSerie.lastKey()))
              ? secondSerie.lastKey()
              : firstSerie.lastKey();
    }
    return maxDate;
  }
Exemplo n.º 20
0
  /** Return the index of the node in the ring that handles this token */
  int getTokenIndex(BigInteger token) {
    // Find keys strictly less than token
    SortedMap<BigInteger, EndPoint> head = tokenToEndPointMap_.headMap(token);

    // If the last key less than token is the last key of the map total, then
    // we are greater than all keys in the map. Therefore the lowest node in the
    // ring is responsible.
    if (!head.isEmpty() && head.lastKey().equals(tokenToEndPointMap_.lastKey())) {
      return 0;
    }
    // otherwise return the number of elems in the map smaller than token
    return head.size();
  }
 @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);
 }
Exemplo n.º 22
0
  private boolean fetchFromCache(SortedMap<byte[], SimpleQueueEntry> entries, int maxBatchSize) {
    if (entryCache.isEmpty()) {
      return false;
    }

    Iterator<Map.Entry<byte[], SimpleQueueEntry>> iterator = entryCache.entrySet().iterator();
    while (entries.size() < maxBatchSize && iterator.hasNext()) {
      Map.Entry<byte[], SimpleQueueEntry> entry = iterator.next();
      entries.put(entry.getKey(), entry.getValue());
      iterator.remove();
    }
    return true;
  }
Exemplo n.º 23
0
  /** 对Key进行哈希并返回哈希环上对应的节点。 参考了Jedis的Sharded.java */
  public JedisTemplate getShard(String key) {

    if (singleTemplate != null) {
      return singleTemplate;
    }

    SortedMap<Long, JedisTemplate> tail = nodes.tailMap(algo.hash(key));
    // 已到最后,返回第一个点.
    if (tail.isEmpty()) {
      return nodes.get(nodes.firstKey());
    }

    return tail.get(tail.firstKey());
  }
 private void collectMeterReports(
     List<DBObject> docs, SortedMap<String, Meter> meters, Date timestamp) {
   if (meters.isEmpty()) return;
   for (Map.Entry<String, Meter> entry : meters.entrySet()) {
     final BasicDBObject report = getBasicDBObject(timestamp, entry.getKey(), "meter");
     final Meter v = entry.getValue();
     report.put("count", v.getCount());
     report.put("1-minute-rate", v.getOneMinuteRate());
     report.put("5-minute-rate", v.getFiveMinuteRate());
     report.put("15-minute-rate", v.getFifteenMinuteRate());
     report.put("mean-rate", v.getMeanRate());
     docs.add(report);
   }
 }
 /**
  * Find the relevant compression codec for the given file based on its filename suffix.
  *
  * @param file the filename to check
  * @return the codec object
  */
 public CompressionCodec getCodec(Path file) {
   CompressionCodec result = null;
   if (codecs != null) {
     String filename = file.getName();
     String reversedFilename = new StringBuffer(filename).reverse().toString();
     SortedMap<String, CompressionCodec> subMap = codecs.headMap(reversedFilename);
     if (!subMap.isEmpty()) {
       String potentialSuffix = subMap.lastKey();
       if (reversedFilename.startsWith(potentialSuffix)) {
         result = codecs.get(potentialSuffix);
       }
     }
   }
   return result;
 }
  private SortedMap<LocalDate, BigDecimal> accumulateResult(SortedMap<LocalDate, BigDecimal> map) {
    SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
    if (map.isEmpty()) {
      return result;
    }

    BigDecimal accumulatedResult = BigDecimal.ZERO;
    for (LocalDate day : map.keySet()) {
      BigDecimal value = map.get(day);
      accumulatedResult = accumulatedResult.add(value);
      result.put(day, accumulatedResult);
    }

    return result;
  }
  /** Cleanup references to committed transactions that are no longer needed. */
  synchronized void removeUnNeededCommitedTransactions() {
    Integer minStartSeqNumber = getMinStartSequenceNumber();
    if (minStartSeqNumber == null) {
      minStartSeqNumber = Integer.MAX_VALUE; // Remove all
    }

    int numRemoved = 0;
    // Copy list to avoid conc update exception
    for (Entry<Integer, TransactionState> entry :
        new LinkedList<Entry<Integer, TransactionState>>(
            commitedTransactionsBySequenceNumber.entrySet())) {
      if (entry.getKey() >= minStartSeqNumber) {
        break;
      }
      numRemoved =
          numRemoved
              + (commitedTransactionsBySequenceNumber.remove(entry.getKey()) == null ? 0 : 1);
      numRemoved++;
    }

    if (LOG.isDebugEnabled()) {
      StringBuilder debugMessage = new StringBuilder();
      if (numRemoved > 0) {
        debugMessage.append("Removed [").append(numRemoved).append("] commited transactions");

        if (minStartSeqNumber == Integer.MAX_VALUE) {
          debugMessage.append(" with any sequence number.");
        } else {
          debugMessage.append(" with sequence lower than [").append(minStartSeqNumber).append("].");
        }
        if (!commitedTransactionsBySequenceNumber.isEmpty()) {
          debugMessage
              .append(" Still have [")
              .append(commitedTransactionsBySequenceNumber.size())
              .append("] left.");
        } else {
          debugMessage.append(" None left.");
        }
        LOG.debug(debugMessage.toString());
      } else if (commitedTransactionsBySequenceNumber.size() > 0) {
        debugMessage
            .append("Could not remove any transactions, and still have ")
            .append(commitedTransactionsBySequenceNumber.size())
            .append(" left");
        LOG.debug(debugMessage.toString());
      }
    }
  }
Exemplo n.º 28
0
  @Override
  public void process(Node externs, Node root) {
    CollectTweaksResult result = collectTweaks(root);
    applyCompilerDefaultValueOverrides(result.tweakInfos);

    boolean changed = false;

    if (stripTweaks) {
      changed = stripAllCalls(result.tweakInfos);
    } else if (!compilerDefaultValueOverrides.isEmpty()) {
      changed = replaceGetCompilerOverridesCalls(result.getOverridesCalls);
    }
    if (changed) {
      compiler.reportCodeChange();
    }
  }
 static void constructDurationSummary(
     SortedMap<Integer, Long> durationData, JSONObject scenarioStats) {
   JSONObject durationSummary = new JSONObject();
   long runDurationSum = 0;
   for (Long runDuration : durationData.values()) {
     if ((runDuration > 0)) {
       runDurationSum += runDuration;
       continue;
     }
   }
   double scenarioDurationAverage = -1;
   if (!durationData.isEmpty()) {
     scenarioDurationAverage = (double) runDurationSum / durationData.size();
   }
   durationSummary.put("AvgDuration", scenarioDurationAverage);
   scenarioStats.put("AvgScenarioDuration", durationSummary);
 }
Exemplo n.º 30
0
 public void recordAndUpdateNewMessage(final ChatMessage aMsg) {
   final SortedMap<Date, ChatMessage> map = getMapForRoom(aMsg.getRoom());
   synchronized (map) {
     if (!map.isEmpty()) {
       final ChatMessage lastMsg = map.get(map.lastKey());
       while (aMsg.getDate().compareTo(lastMsg.getDate()) <= 0) {
         aMsg.setDate(new Date(1 + aMsg.getDate().getTime()));
       }
       aMsg.setPreviousMessageDate(lastMsg.getDate());
     }
     map.put(aMsg.getDate(), aMsg);
     while (map.size() > MAX_ROOM_HIST) {
       map.remove(map.firstKey());
     }
   }
   SynchroCache.put("ChatCache", m_chatCache);
 }