Java Code Examples for com.google.common.collect.Range#closed()

The following examples show how to use com.google.common.collect.Range#closed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OplinkOpticalPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
private Range<Long> getPowerRange(PortNumber port, String directionKey, String minKey, String maxKey) {
    // TODO
    // Optical protection switch does not support power range configuration, it'll reply error.
    // To prevent replying error log flooding from netconf session when polling all ports information,
    // use general power range of [-60, 60] instead.
    if (handler().get(DeviceService.class).getDevice(data().deviceId()).type()
            == Device.Type.FIBER_SWITCH) {
        return RANGE_GENERAL;
    }
    String reply = netconfGet(handler(), getPowerRangeFilter(port, directionKey));
    HierarchicalConfiguration info = configAt(reply, KEY_PORTS_PORT_PROPERTY);
    if (info == null) {
        return null;
    }
    long minPower = (long) (info.getDouble(minKey) * POWER_MULTIPLIER);
    long maxPower = (long) (info.getDouble(maxKey) * POWER_MULTIPLIER);
    return Range.closed(minPower, maxPower);
}
 
Example 2
Source File: XMLUtils.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public static Range<Double> parseDoubleRange(Element xmlElement, String tagName) {
  NodeList items = xmlElement.getElementsByTagName(tagName);
  if (items.getLength() == 0)
    return null;
  Element tag = (Element) items.item(0);
  items = tag.getElementsByTagName("min");
  if (items.getLength() == 0)
    return null;
  Element min = (Element) items.item(0);
  items = tag.getElementsByTagName("max");
  if (items.getLength() == 0)
    return null;
  Element max = (Element) items.item(0);

  String minText = min.getTextContent();
  String maxText = max.getTextContent();
  Range<Double> r = Range.closed(Double.valueOf(minText), Double.valueOf(maxText));
  return r;
}
 
Example 3
Source File: MemoryGroupByAggregationTest.java    From hop with Apache License 2.0 6 votes vote down vote up
private Iterable<Object[]> getRows() {
  if ( data.isEmpty() ) {
    return ImmutableSet.of();
  }

  Range<Integer> rows = Range.closed( 0, data.rowMap().lastKey() );

  return FluentIterable.from( ContiguousSet.create( rows, DiscreteDomain.integers() ) )
    .transform( Functions.forMap( data.rowMap(), ImmutableMap.<Integer, Optional<Object>>of() ) )
    .transform( new Function<Map<Integer, Optional<Object>>, Object[]>() {
      @Override public Object[] apply( Map<Integer, Optional<Object>> input ) {
        Object[] row = new Object[ rowMeta.size() ];
        for ( Map.Entry<Integer, Optional<Object>> entry : input.entrySet() ) {
          row[ entry.getKey() ] = entry.getValue().orNull();
        }
        return row;
      }
    } );
}
 
Example 4
Source File: QueryCardinalityUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public Range<Long> visitLimit(LimitNode node, Void context)
{
    if (node.isWithTies()) {
        Range<Long> sourceCardinalityRange = node.getSource().accept(this, null);
        long lower = min(node.getCount(), sourceCardinalityRange.lowerEndpoint());
        if (sourceCardinalityRange.hasUpperBound()) {
            return Range.closed(lower, sourceCardinalityRange.upperEndpoint());
        }
        else {
            return Range.atLeast(lower);
        }
    }

    return applyLimit(node.getSource(), node.getCount());
}
 
Example 5
Source File: ModShardingAlgorithmTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertRangeDoShardingWithAllTargets() {
    List<String> availableTargetNames = Lists.newArrayList("t_order_0", "t_order_1", "t_order_2", "t_order_3");
    Range<Long> rangeValue = Range.closed(11L, 14L);
    List<RouteValue> shardingValues = Lists.newArrayList(new RangeRouteValue<>("order_id", "t_order", rangeValue));
    Collection<String> actual = shardingStrategy.doSharding(availableTargetNames, shardingValues, new ConfigurationProperties(new Properties()));
    assertThat(actual.size(), is(4));
}
 
Example 6
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("random")
public Filter parseRandom(Element el) throws InvalidXMLException {
    Node node = new Node(el);
    Range<Double> chance;
    try {
        chance = Range.closedOpen(0d, XMLUtils.parseNumber(node, Double.class));
    } catch(InvalidXMLException e) {
        chance = XMLUtils.parseNumericRange(node, Double.class);
    }

    Range<Double> valid = Range.closed(0d, 1d);
    if (valid.encloses(chance)) {
        return proto.isNoOlderThan(ProtoVersions.EVENT_QUERIES) ? new RandomFilter(chance)
                                                                : new LegacyRandomFilter(chance);
    } else {
        double lower = chance.hasLowerBound() ? chance.lowerEndpoint() : Double.NEGATIVE_INFINITY;
        double upper = chance.hasUpperBound() ? chance.upperEndpoint() : Double.POSITIVE_INFINITY;
        double invalid;
        if(!valid.contains(lower)) {
            invalid = lower;
        } else {
            invalid = upper;
        }

        throw new InvalidXMLException("chance value (" + invalid + ") is not between 0 and 1", el);
    }
}
 
Example 7
Source File: Ms2QualityScoreModel.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double[] calculateQualityScore(FragmentScan fragmentScan) {
  final double[] scores = new double[fragmentScan.ms2ScanNumbers.length];
  Range<Double> mzRange =
      fragmentScan.feature.getMZ() < 75 ? Range.closed(50d, fragmentScan.feature.getMZ())
          : Range.closed(0d, fragmentScan.feature.getMZ() - 20d);
  for (int i = 0; i < scores.length; ++i) {
    double tic = ScanUtils
        .calculateTIC(fragmentScan.origin.getScan(fragmentScan.ms2ScanNumbers[i]), mzRange);
    scores[i] = tic;
  }
  return scores;
}
 
Example 8
Source File: DoubleRangeEditor.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Range<Double> getValue() {
  String minValueS = minTxtField.getText();
  String maxValueS = maxTxtField.getText();
  try {
    double minValue = Double.parseDouble(minValueS);
    double maxValue = Double.parseDouble(maxValueS);
    return Range.closed(minValue, maxValue);
  } catch (NumberFormatException e) {
    return null;
  }
}
 
Example 9
Source File: QueryCardinalityUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
private Range<Long> applyLimit(PlanNode source, long limit)
{
    Range<Long> sourceCardinalityRange = source.accept(this, null);
    if (sourceCardinalityRange.hasUpperBound()) {
        limit = min(sourceCardinalityRange.upperEndpoint(), limit);
    }
    long lower = min(limit, sourceCardinalityRange.lowerEndpoint());
    return Range.closed(lower, limit);
}
 
Example 10
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("kill-streak")
public KillStreakFilter parseKillStreak(Element el) throws InvalidXMLException {
    boolean repeat = XMLUtils.parseBoolean(el.getAttribute("repeat"), false);
    boolean persistent = XMLUtils.parseBoolean(el.getAttribute("persistent"), false);
    Integer count = XMLUtils.parseNumber(el.getAttribute("count"), Integer.class, (Integer) null);
    Integer min = XMLUtils.parseNumber(el.getAttribute("min"), Integer.class, (Integer) null);
    Integer max = XMLUtils.parseNumber(el.getAttribute("max"), Integer.class, (Integer) null);
    Range<Integer> range;

    if(count != null) {
        range = Range.singleton(count);
    } else if(min == null) {
        if(max == null) {
            throw new InvalidXMLException("kill-streak filter must have a count, min, or max", el);
        } else {
            range = Range.atMost(max);
        }
    } else {
        if(max == null) {
            range = Range.atLeast(min);
        } else {
            range = Range.closed(min, max);
        }
    }

    if(repeat && !range.hasUpperBound()) {
        throw new InvalidXMLException("repeating kill-streak filter must have a count or max", el);
    }

    return new KillStreakFilter(range, repeat, persistent);
}
 
Example 11
Source File: SpectraVisualizerWindow.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public void loadIsotopes(IsotopePattern newPattern) {
  // We need to find a normalization factor for the new isotope
  // pattern, to show meaningful intensity range
  double mz = newPattern.getHighestDataPoint().getMZ();
  Range<Double> searchMZRange = Range.closed(mz - 0.5, mz + 0.5);
  ScanDataSet scanDataSet = spectrumPlot.getMainScanDataSet();
  double normalizationFactor = scanDataSet.getHighestIntensity(searchMZRange);

  // If normalization factor is 0, it means there were no data points
  // in given m/z range. In such case we use the max intensity of
  // whole scan as normalization factor.
  if (normalizationFactor == 0) {
    searchMZRange = Range.atLeast(0.0);
    normalizationFactor = scanDataSet.getHighestIntensity(searchMZRange);
  }

  IsotopePattern normalizedPattern =
      IsotopePatternCalculator.normalizeIsotopePattern(newPattern, normalizationFactor);
  Color newColor;
  if (newPattern.getStatus() == IsotopePatternStatus.DETECTED)
    newColor = detectedIsotopesColor;
  else
    newColor = predictedIsotopesColor;
  IsotopesDataSet newDataSet = new IsotopesDataSet(normalizedPattern);
  spectrumPlot.addDataSet(newDataSet, newColor, true);

}
 
Example 12
Source File: PeakListTablePopupMenu.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a peak's RT range.
 *
 * @param peak the peak.
 * @return The peak's RT range.
 */
private static Range<Double> getPeakRTRange(final Feature peak) {

  final Range<Double> range = peak.getRawDataPointsRTRange();
  final double rtLen = range.upperEndpoint() - range.lowerEndpoint();
  return Range.closed(Math.max(0.0, range.lowerEndpoint() - rtLen),
      range.upperEndpoint() + rtLen);
}
 
Example 13
Source File: IntervalShardingAlgorithmTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertRangeDoShardingByMonth() {
    Range<String> rangeValue = Range.closed("2019-10-15 10:59:08", "2020-04-08 10:59:08");
    List<RouteValue> shardingValues = Collections.singletonList(new RangeRouteValue<>("create_time", "t_order", rangeValue));
    Collection<String> actual = shardingStrategyByMonth.doSharding(availableTablesForMonthStrategy, shardingValues, new ConfigurationProperties(new Properties()));
    assertThat(actual.size(), is(7));
}
 
Example 14
Source File: AutoIntervalShardingAlgorithmTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertRangeDoShardingWithAllRange() {
    List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3", "t_order_4");
    Range<String> rangeValue = Range.closed("2019-01-01 00:00:00", "2020-01-01 00:00:15");
    List<RouteValue> shardingValues = Collections.singletonList(new RangeRouteValue<>("create_time", "t_order", rangeValue));
    Collection<String> actual = shardingStrategy.doSharding(availableTargetNames, shardingValues, new ConfigurationProperties(new Properties()));
    assertThat(actual.size(), is(5));
}
 
Example 15
Source File: TestTopStateHandoffMetrics.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "succeededNonGraceful")
public void testTopStateSuccessfulYetNonGracefulHandoff(TestCaseConfig cfg) {
  // localhost_0 crashed at 15000
  // localhost_1 slave -> master started 20000, ended 22000, top state handoff = 7000
  preSetup();
  final String downInstance = "localhost_0";
  final Long lastOfflineTime = 15000L;
  Range<Long> expectedDuration = Range.closed(7000L, 7000L);
  runStageAndVerify(
      cfg.initialCurrentStates, cfg.currentStateWithMissingTopState, cfg.finalCurrentState,
      new MissingStatesDataCacheInject() {
        @Override
        public void doInject(ResourceControllerDataProvider cache) {
          accessor.removeProperty(accessor.keyBuilder().liveInstance(downInstance));
          Map<String, LiveInstance> liMap = new HashMap<>(cache.getLiveInstances());
          liMap.remove("localhost_0");
          cache.setLiveInstances(new ArrayList<>(liMap.values()));
          cache.getInstanceOfflineTimeMap().put("localhost_0", lastOfflineTime);
          cache.notifyDataChange(HelixConstants.ChangeType.LIVE_INSTANCE);
        }
      }, 1, 0,
      DURATION_ZERO, // graceful handoff duration should be 0
      expectedDuration, // we should have an record for non-graceful handoff
      expectedDuration, // max handoff should be same as non-graceful handoff
      DURATION_ZERO // we don't record user latency for non-graceful transition
  );
}
 
Example 16
Source File: WCAHistoLimits.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
private static Range<Float> range(String id, HistoDbAttr attr, HistoDbStats stats) {
    HistoDbAttributeId pAttrId = new HistoDbNetworkAttributeId(id, HistoDbAttr.P);
    float minP = stats.getValue(HistoDbStatsType.MIN, pAttrId, AmplConstants.INVALID_FLOAT_VALUE);
    float maxP = stats.getValue(HistoDbStatsType.MAX, pAttrId, AmplConstants.INVALID_FLOAT_VALUE);
    return Range.closed(minP, maxP);
}
 
Example 17
Source File: OptionParserTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void parseLongRange_spanningZero() {
  final String input = "-11..22";
  final Range<Long> expected = Range.closed(-11L, 22L);
  assertThat(OptionParser.parseLongRange(input)).isEqualTo(expected);
}
 
Example 18
Source File: CommitLogBucket.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private static Range<Integer> getBucketIdRange() {
  return Range.closed(1, getCommitLogBucketCount());
}
 
Example 19
Source File: Rectangle.java    From mapper with Apache License 2.0 4 votes vote down vote up
public Range<Integer> xRange() {
  return Range.closed(origin.x, origin.x + dimension.x);
}
 
Example 20
Source File: Rectangle.java    From mapper with Apache License 2.0 4 votes vote down vote up
public Range<Integer> yRange() {
  return Range.closed(origin.y, origin.y + dimension.y);
}