org.apache.commons.lang3.Range Java Examples

The following examples show how to use org.apache.commons.lang3.Range. 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: LookupTableTransitionTest.java    From synthea with Apache License 2.0 7 votes vote down vote up
@Test
public void keyTestWithAgesMatch() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 20;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertEquals(silver, gold);
  Assert.assertEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertTrue(set.contains(silver));
}
 
Example #2
Source File: BasicOrderedConstraintQuery.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public void fromBinary(final byte[] bytes) {
  final ByteBuffer buf = ByteBuffer.wrap(bytes);
  final int numRanges = VarintUtils.readUnsignedInt(buf);
  ByteArrayUtils.verifyBufferSize(buf, numRanges);
  rangesPerDimension = new Range[numRanges];
  final int indexNameBinaryLength = VarintUtils.readUnsignedInt(buf);
  for (int i = 0; i < rangesPerDimension.length; i++) {
    rangesPerDimension[i] = Range.between(buf.getDouble(), buf.getDouble());
  }
  if (indexNameBinaryLength > 0) {
    final byte[] indexNameBinary = ByteArrayUtils.safeRead(buf, indexNameBinaryLength);
    indexName = StringUtils.stringFromBinary(indexNameBinary);
  } else {
    indexName = null;
  }
}
 
Example #3
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithAgesMatchLow() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 0;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertEquals(silver, gold);
  Assert.assertEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertTrue(set.contains(silver));
}
 
Example #4
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithAgesMatchHigh() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 30;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertEquals(silver, gold);
  Assert.assertEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertTrue(set.contains(silver));
}
 
Example #5
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithAgesNoMatchAge() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 40;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertNotEquals(silver, gold);
  Assert.assertNotEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertFalse(set.contains(silver));
}
 
Example #6
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithAgesNoMatchOther() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 20;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("baz");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertNotEquals(silver, gold);
  Assert.assertNotEquals(gold, silver);
 
  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertFalse(set.contains(silver));
}
 
Example #7
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithoutAgesMatch() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = null;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = null;
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertEquals(silver, gold);
  Assert.assertEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertTrue(set.contains(silver));
}
 
Example #8
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void keyTestWithoutAgesNoMatch() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = null;
  LookupTableKey silver = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("baz");
  Range<Integer> range = null;
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Assert.assertNotEquals(silver, gold);
  Assert.assertNotEquals(gold, silver);

  Set<LookupTableKey> set = new HashSet<LookupTableKey>();
  set.add(gold);
  Assert.assertFalse(set.contains(silver));
}
 
Example #9
Source File: TimeSpan.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public static TimeSpan fromPropertyString(String pString) {
  String[] split = pString.split(",");
  try {
    long start = Long.parseLong(split[0]);
    long end = Long.parseLong(split[1]);
    boolean daily = Boolean.parseBoolean(split[2]);
    int dir = Integer.parseInt(split[3]);
    TimeSpan t = new TimeSpan(Range.between(start, end), daily);
    switch (dir) {
      case 0:
        t.setDirection(DIRECTION.SEND);
        break;
      case 1:
        t.setDirection(DIRECTION.ARRIVE);
        break;
    }
    return t;
  } catch (Exception ignored) {
  }
  return null;
}
 
Example #10
Source File: DSWorkbenchFarmManager.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public Range<Integer> getFarmRange(FARM_CONFIGURATION pConfig) {
    if (pConfig == null) {
        pConfig = FARM_CONFIGURATION.C;
    }
    switch (pConfig) {
        case A:
        return Range.between(UIHelper.parseIntFromField(jMinFarmRuntimeA, 0),
                UIHelper.parseIntFromField(jMaxFarmRuntimeA, 60));
        case B:
        return Range.between(UIHelper.parseIntFromField(jMinFarmRuntimeB, 0),
                UIHelper.parseIntFromField(jMaxFarmRuntimeB, 60));
    case K:
        return Range.between(UIHelper.parseIntFromField(jMinFarmRuntimeK, 0),
                UIHelper.parseIntFromField(jMaxFarmRuntimeK, 60));
        default:
        return Range.between(UIHelper.parseIntFromField(jMinFarmRuntimeC, 0),
                UIHelper.parseIntFromField(jMaxFarmRuntimeC, 60));
    }
}
 
Example #11
Source File: AttackTimePanel.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
/**
 * Get the currently set up send span
 *
 * @return TimeSpan The send span
 */
private TimeSpan getSendSpan() {
    TimeSpan start = null;
    Range<Long> range = Range.between(Math.round(jSendTimeFrame.getMinimumColoredValue()) * DateUtils.MILLIS_PER_HOUR,
            Math.round(jSendTimeFrame.getMaximumColoredValue()) * DateUtils.MILLIS_PER_HOUR);
    if (Objects.equals(range.getMinimum(), range.getMaximum()) && !jExactTimeButton.isSelected()) {
        return null;
    }
    
    if (jAlwaysButton.isSelected()) {
        start = new TimeSpan(range, true);
    } else if (jDayButton.isSelected()) {
        range = Range.between(dateTimeField.getSelectedDate().getTime() + range.getMinimum(),
                dateTimeField.getSelectedDate().getTime() + range.getMaximum());
        start = new TimeSpan(range, false);
    } else if (jExactTimeButton.isSelected()) {
        start = new TimeSpan(dateTimeField.getSelectedDate());
    }
    if (start != null) {
        start.setDirection(TimeSpan.DIRECTION.SEND);
    }

    return start;
}
 
Example #12
Source File: AttackTimePanel.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
/**
 * Get the currently set up arrive span
 *
 * @return TimeSpan The arrive span
 */
private TimeSpan getArriveSpan() {
    TimeSpan arrive = null;
    Range<Long> range = Range.between(Math.round(jSendTimeFrame.getMinimumColoredValue()) * DateUtils.MILLIS_PER_HOUR,
            Math.round(jSendTimeFrame.getMaximumColoredValue()) * DateUtils.MILLIS_PER_HOUR);
    if (Objects.equals(range.getMinimum(), range.getMaximum()) && !jExactTimeButton.isSelected()) {
        return null;
    }
    
    if (jAlwaysButton.isSelected()) {
        arrive = new TimeSpan(range, true);
    } else if (jDayButton.isSelected()) {
        range = Range.between(dateTimeField.getSelectedDate().getTime() + range.getMinimum(),
                dateTimeField.getSelectedDate().getTime() + range.getMaximum());
        arrive = new TimeSpan(range, false);
    } else if (jExactTimeButton.isSelected()) {
        arrive = new TimeSpan(dateTimeField.getSelectedDate());
    }
    if (arrive != null) {
        arrive.setDirection(TimeSpan.DIRECTION.ARRIVE);
    }
    
    return arrive;
}
 
Example #13
Source File: TimeFrame.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
/**
 * Check if a movement with the provided runtime is possible for this
 * AttackFitter
 *
 * @param pRuntime Runtime to check
 * @param pVillage Village for which the runtime is valid
 * @return boolean TRUE=Runtime might be fitted if not all send times are
 * already used
 */
public boolean isMovementPossible(long pRuntime) {
  if (startRanges == null) {
    startRanges = startTimespansToRanges();
  }
  if (arriveRanges == null) {
    arriveRanges = arriveTimespansToRanges();
  }

  for (Range<Long> currentStartRange : startRanges) {
    Range<Long> arriveRangeForStartRange = Range.between(currentStartRange.getMinimum() + pRuntime, currentStartRange.getMaximum() + pRuntime);
    for (Range<Long> currentArriveRange : arriveRanges) {
      if (currentArriveRange.isOverlappedBy(arriveRangeForStartRange)) {
        //movement with 'pRuntime' starting in 'currentStartRange' will arrive withing 'currentArriveRange'
        return true;
      }
    }
  }
  //no overlapping range was found
  return false;
}
 
Example #14
Source File: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void extractResultsFromConstructorDeclaration(ConstructorDeclaration cd, CodeAnalysisResult result) {
    // Constructors always have a body.
    int constructorBegin = cd.getBegin().get().line;
    int constructorBodyBegin = cd.getBody().getBegin().get().line;
    int constructorEnd = cd.getEnd().get().line;

    for (int line = constructorBegin; line <= constructorBodyBegin; line++) {
        // constructor signatures are non coverable
        result.nonCoverableCode(line);
    }

    String signature = cd.getDeclarationAsString(false, false, false);
    result.testAccordionMethodDescription(signature, constructorBegin, constructorEnd);

    result.methodSignatures(Range.between(constructorBegin, constructorBodyBegin));
    result.methods(Range.between(constructorBegin, constructorEnd));
}
 
Example #15
Source File: StaticAnalysisTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testClosingBracketIf() {
    String name = "Test";
    String sourceCode = String.join("\n",
            "public class Test {",
            "   public static void main(String[] args) {",
            "       if (2 == 2) {",
            "           System.out.println(\"Hello World\");",
            "       }",
            "   }",
            "}");
    final CodeAnalysisResult result = ClassCodeAnalyser.visitCode(name, sourceCode);
    final Range<Integer> next = result.getClosingBrackets().iterator().next();
    assertEquals(3, next.getMinimum().intValue());
    assertEquals(5, next.getMaximum().intValue());
}
 
Example #16
Source File: StaticAnalysisTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testClosingBracketIfElse() {
    String name = "Test";
    String sourceCode = String.join("\n",
            "public class Test {",
            "   public static void main(String[] args) {",
            "       if (2 == 2) {",
            "           System.out.println(\"Hello World\");",
            "       } ",
            "       else {",
            "           System.out.println(\"World Hello\");",
            "       }",
            "   }",
            "}");
    final CodeAnalysisResult result = ClassCodeAnalyser.visitCode(name, sourceCode);
    final Iterator<Range<Integer>> iterator = result.getClosingBrackets().iterator();
    final Range<Integer> then = iterator.next();
    assertEquals(3, then.getMinimum().intValue());
    assertEquals(5, then.getMaximum().intValue());

    Integer[] expected = {2,5,6,8,9,10};
    assertArrayEquals(expected, result.getNonCoverableCode().toArray());
}
 
Example #17
Source File: WindowLookbackTest.java    From metron with Apache License 2.0 6 votes vote down vote up
public State test(String windowSelector, Date now, Optional<Map<String, Object>> config, Assertions... assertions) {

    List<Range<Long>> windowIntervals = WindowProcessor.process(windowSelector).toIntervals(now.getTime());
    String stellarStatement = "PROFILE_WINDOW('" + windowSelector + "', now"
                            + (config.isPresent()?", config":"")
                            + ")";
    Map<String, Object> variables = new HashMap<>();
    variables.put("now", now.getTime());
    if(config.isPresent()) {
      variables.put("config", config.get());
    }
    StellarProcessor stellar = new StellarProcessor();
    List<ProfilePeriod> periods = (List<ProfilePeriod>)stellar.parse( stellarStatement
                                                                    , new DefaultVariableResolver(k -> variables.get(k),k -> variables.containsKey(k))
                                                                    , resolver
                                                                    , context
                                                                    );
    State state = new State(windowIntervals, periods);
    for(Assertions assertion : assertions) {
      assertTrue(assertion.test(state), assertion.name());
    }
    return state;
  }
 
Example #18
Source File: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void extractResultsFromMethodDeclaration(MethodDeclaration md, CodeAnalysisResult result) {
    // Note that md.getEnd().get().line returns the last line of the method, not of the signature
    if (!md.getBody().isPresent()) {
        return;
    }
    BlockStmt body = md.getBody().get();

    // Since a signature might span over different lines we need to get to its body and take its beginning
    // Also note that interfaces have no body ! So this might fail !
    int methodBegin = md.getBegin().get().line;
    int methodBodyBegin = body.getBegin().get().line;
    int methodEnd = md.getEnd().get().line;
    for (int line = methodBegin; line <= methodBodyBegin; line++) {
        // method signatures are non coverable
        result.nonCoverableCode(line);
    }

    String signature = md.getDeclarationAsString(false, false, false);
    signature = signature.substring(signature.indexOf(' ') + 1); // Remove return type

    result.methodSignatures(Range.between(methodBegin, methodBodyBegin));
    result.methods(Range.between(methodBegin, methodEnd));
    result.testAccordionMethodDescription(signature, methodBegin, methodEnd);
}
 
Example #19
Source File: IntervalPredicateTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithOverlap() {
  List<Range<Long>> intervals = new ArrayList<Range<Long>>() {{
    add(Range.between(0L, 10L));
    add(Range.between(5L, 30L));
    add(Range.between(40L, 50L));
  }};
  IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
  assertTrue(predicate.test(0L));
  assertTrue(predicate.test(5L));
  assertTrue(predicate.test(30L));
  assertTrue(predicate.test(10L));
  assertFalse(predicate.test(51L));
  assertTrue(predicate.test(15L));
  assertFalse(predicate.test(31L));
  assertTrue(predicate.test(45L));
}
 
Example #20
Source File: WindowProcessorTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testDenseWindow() {
  for (String text : new String[] {
          "from 2 hours ago to 30 minutes ago"
          ,"starting from 2 hours until 30 minutes"
          ,"starting from 2 hours ago until 30 minutes ago"
          ,"starting from 30 minutes ago until 2 hours ago"
          ,"from 30 minutes ago to 2 hours ago "
  }) {
    Window w = WindowProcessor.process(text);
  /*
  A dense window starting 2 hour ago and continuing until 30 minutes ago
   */
    Date now = new Date();
    List<Range<Long>> intervals = w.toIntervals(now.getTime());
    assertEquals(1, intervals.size());
    assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(0).getMinimum());
    assertTimeEquals(now.getTime() - TimeUnit.MINUTES.toMillis(30), intervals.get(0).getMaximum());
  }
}
 
Example #21
Source File: ParallelAsync.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
static Completable forEachAsync(Range<Integer> range, int partition, Action1<Integer> func) {

        int partitionSize = (range.getMaximum() - range.getMinimum()) / partition;
        List<Completable> task = new ArrayList<>();
        int startRange = range.getMinimum();
        for (int i = 0; i < partition; i++) {
            Range<Integer> integerRange = Range.between(startRange, startRange + partitionSize);
            task.add(Completable.defer(() -> {
                for(int j = integerRange.getMinimum(); j < integerRange.getMaximum();j++) {
                    func.call(j);
                }
                return Completable.complete();
            }));
            startRange = startRange + partitionSize ;
        }
        return Completable.mergeDelayError(task);
    }
 
Example #22
Source File: WindowProcessorTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testSparse() {
  for(String text : new String[] {
    "30 minute window every 1 hour from 2 hours ago to 30 minutes ago",
    "30 minute window every 1 hour starting from 2 hours ago to 30 minutes ago",
    "30 minute window every 1 hour starting from 2 hours ago until 30 minutes ago",
    "30 minute window for every 1 hour starting from 2 hours ago until 30 minutes ago",
  })
  {
    Window w = WindowProcessor.process(text);
  /*
  A window size of 30 minutes
  Starting 2 hour ago and continuing until 30 minutes ago
  window 1: ( now - 2 hour, now - 2 hour + 30 minutes)
  window 2: (now - 1 hour, now - 1 hour + 30 minutes)
   */
    Date now = new Date();
    List<Range<Long>> intervals = w.toIntervals(now.getTime());
    assertEquals(2, intervals.size());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(0).getMinimum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2) + TimeUnit.MINUTES.toMillis(30), intervals.get(0).getMaximum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1), intervals.get(1).getMinimum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(30), intervals.get(1).getMaximum());
  }
}
 
Example #23
Source File: FeatureAttributeDimensionField.java    From geowave with Apache License 2.0 6 votes vote down vote up
public FeatureAttributeDimensionField(
    final AttributeDescriptor attributeDescriptor,
    final Range<Double> range) {
  super(
      range == null ? null
          : new BasicDimensionDefinition(range.getMinimum(), range.getMaximum()));
  writer =
      new FeatureAttributeWriterWrapper(
          (FieldWriter) FieldUtils.getDefaultWriterForClass(
              attributeDescriptor.getType().getBinding()));
  reader =
      new FeatureAttributeReaderWrapper(
          (FieldReader) FieldUtils.getDefaultReaderForClass(
              attributeDescriptor.getType().getBinding()));
  attributeName = attributeDescriptor.getLocalName();
}
 
Example #24
Source File: WindowProcessorTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeatTilNow() {
  Window w = WindowProcessor.process("30 minute window every 1 hour from 3 hours ago");
  /*
  A window size of 30 minutes
  Starting 3 hours ago and continuing until now
  window 1: ( now - 3 hour, now - 3 hour + 30 minutes)
  window 2: ( now - 2 hour, now - 2 hour + 30 minutes)
  window 3: ( now - 1 hour, now - 1 hour + 30 minutes)
   */
  Date now = new Date();
  List<Range<Long>> intervals = w.toIntervals(now.getTime());
  assertEquals(3, intervals.size());

  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(3), intervals.get(0).getMinimum());
  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(3) + TimeUnit.MINUTES.toMillis(30), intervals.get(0).getMaximum());

  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(1).getMinimum());
  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(2) + TimeUnit.MINUTES.toMillis(30), intervals.get(1).getMaximum());

  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(1), intervals.get(2).getMinimum());
  assertTimeEquals(now.getTime() - TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(30), intervals.get(2).getMaximum());
}
 
Example #25
Source File: Transition.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Create a symbolic lookup key for a given row that contains lookup values.
 * @param attributes Table attribute values.
 * @param range If the table contains an age column, range contains the age range
 *     information for this key.
 */
public LookupTableKey(List<String> attributes, Range<Integer> range, Range<Long> timeRange) {
  this.attributes = attributes;
  this.age = null;
  this.ageRange = range;
  this.time = null;
  this.timeRange = timeRange;
}
 
Example #26
Source File: IntervalPredicateTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void testTrivialCase() {
  List<Range<Long>> intervals = new ArrayList<Range<Long>>() {{
    add(Range.between(0L, 10L));
  }};
  IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
  assertTrue(predicate.test(0L));
  assertTrue(predicate.test(5L));
  assertTrue(predicate.test(10L));
  assertFalse(predicate.test(51L));
  assertFalse(predicate.test(15L));
}
 
Example #27
Source File: IntervalPredicateTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicTest() {
  List<Range<Long>> intervals = new ArrayList<Range<Long>>() {{
    add(Range.between(0L, 10L));
    add(Range.between(20L, 30L));
    add(Range.between(40L, 50L));
  }};
  IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
  assertTrue(predicate.test(0L));
  assertTrue(predicate.test(10L));
  assertTrue(predicate.test(5L));
  assertFalse(predicate.test(51L));
  assertFalse(predicate.test(15L));
}
 
Example #28
Source File: Window.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the set of sorted (oldest to newest) window intervals relative to the passed timestamp
 * given inclusion and exclusion predicates.
 *
 * @param now
 * @return intervals returns a set of sorted (oldest to newest) window intervals relative to the
 * passed timestamp given inclusion and exclusion predicates.
 */
public List<Range<Long>> toIntervals(long now) {
  List<Range<Long>> intervals = new ArrayList<>();
  long startMillis = getStartMillis(now);
  long endMillis = getEndMillis(now);
  Iterable<Predicate<Long>> includes = getIncludes(now);
  Iterable<Predicate<Long>> excludes = getExcludes(now);
  //if we don't have a skip distance, then we just skip past everything to make the window dense
  long skipDistance = getSkipDistance().orElse(Long.MAX_VALUE);
  //if we don't have a window width, then we want the window to be completely dense.
  Optional<Long> binWidthOpt = getBinWidth();
  long binWidth = binWidthOpt.isPresent()?binWidthOpt.get():endMillis-startMillis;

  for(long left = startMillis;left >= 0 && left + binWidth <= endMillis;left += skipDistance) {
    Range<Long> interval = Range.between(left, left + binWidth);
    boolean include = includes.iterator().hasNext()?false:true;
    for(Predicate<Long> inclusionPredicate : includes) {
      include |= inclusionPredicate.test(left);
    }
    if(include) {
      for(Predicate<Long> exclusionPredicate : excludes) {
        include &= !exclusionPredicate.test(left);
      }
    }
    if(include) {
      intervals.add(interval);
    }
  }
  return intervals;
}
 
Example #29
Source File: IntervalPredicate.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if x is in the set of intervals in O(log*n) time.
 * @param x
 * @return true if in the set of intervals and false otherwise.
 */
@Override
public boolean test(T x) {
  long ts = timestampTransformer.apply(x);
  int pos = Collections.binarySearch(intervals, Range.is(ts), INTERVAL_COMPARATOR);
  if(pos < 0) {
    pos = -pos - 1;
  }

  Optional<Range<Long>> right = pos >= 0 && pos < intervals.size()?Optional.of(intervals.get(pos)):Optional.empty();
  Optional<Range<Long>> left = pos - 1 >= 0 && pos - 1 < intervals.size()?Optional.of(intervals.get(pos - 1)):Optional.empty();
  return (right.isPresent()?containsInclusive(right.get(),ts):false) || (left.isPresent()?containsInclusive(left.get(),ts):false);
}
 
Example #30
Source File: LookupTableTransitionTest.java    From synthea with Apache License 2.0 5 votes vote down vote up
@Test
public void keyTestCorrectMatch() {
  DirectTransition test = new DirectTransition("test");

  List<String> attributes = new ArrayList<String>();
  attributes.add("foo");
  attributes.add("bar");
  Integer age = 20;
  LookupTableKey yellow = test.new LookupTableKey(attributes, age, null);
  age = 50;
  LookupTableKey grey = test.new LookupTableKey(attributes, age, null);

  List<String> others = new ArrayList<String>();
  others.add("foo");
  others.add("bar");
  Range<Integer> range = Range.between(0, 30);
  LookupTableKey gold = test.new LookupTableKey(others, range, null);

  Range<Integer> anotherRange = Range.between(31, 60);
  LookupTableKey platinum = test.new LookupTableKey(others, anotherRange, null);

  Assert.assertEquals(yellow, gold);
  Assert.assertEquals(gold, yellow);
  Assert.assertEquals(grey, platinum);
  Assert.assertEquals(platinum, grey);

  Assert.assertNotEquals(grey, gold);
  Assert.assertNotEquals(yellow, platinum);
  Assert.assertNotEquals(gold, platinum);
  Assert.assertNotEquals(yellow, grey);

  Map<LookupTableKey, String> map = new HashMap<LookupTableKey, String>();
  map.put(gold, "gold");
  map.put(platinum, "platinum");
  Assert.assertTrue(map.containsKey(yellow));
  Assert.assertEquals(map.get(yellow), "gold");
  Assert.assertTrue(map.containsKey(grey));
  Assert.assertEquals(map.get(grey), "platinum");
}