@Override public Optional<InputStream> getContent(final IRI identifier, final List<Range<Integer>> ranges) { requireNonNull(ranges, "Byte ranges may not be null"); return getFileFromIdentifier(identifier).map(file -> { try { if (ranges.isEmpty()) { return new FileInputStream(file); } else { final List<InputStream> iss = new ArrayList<>(); for (final Range<Integer> r : ranges) { final InputStream input = new FileInputStream(file); final long skipped = input.skip(r.getMinimum()); LOGGER.debug("Skipped {} bytes", skipped); iss.add(new BoundedInputStream(input, r.getMaximum() - r.getMinimum())); } return new SequenceInputStream(asEnumeration(iss.iterator())); } } catch (final IOException ex) { throw new UncheckedIOException(ex); } }); }
@Override public Optional<InputStream> getContent(final IRI identifier, final List<Range<Integer>> ranges) { requireNonNull(identifier, NON_NULL_IDENTIFIER); requireNonNull(ranges, "Byte ranges may not be null"); final Response res; if (ranges.isEmpty()) { res = httpClient.target(identifier.getIRIString()).request().get(); } else { final StringBuilder builder = new StringBuilder(); ranges.forEach(r -> builder.append(r.getMinimum() + "-" + r.getMaximum())); res = httpClient.target(identifier.getIRIString()).request().header("Range", "bytes=" + builder).get(); } LOGGER.info("HTTP GET request to {} returned status {}", identifier, res.getStatus()); if (res.hasEntity()) { return of(res.getEntity()).map(x -> (InputStream) x); } return empty(); }
@Override public Collection<ItemLootInfo> getItemLootInfo() { Collection<ItemLootInfo> itemLoot = new LinkedList<>(); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_HP_POTION) .chancesOfDropping(1.0f) .itemNumberRange(Range.between(1, 2)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_MP_POTION) .chancesOfDropping(1.0f) .itemNumberRange(Range.between(2, 3)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.BLUE_BERRY) .chancesOfDropping(1.0f) .itemNumberRange(Range.between(2, 3)) .build()); return itemLoot; }
@Override public Collection<ItemLootInfo> getItemLootInfo() { Collection<ItemLootInfo> itemLoot = new LinkedList<>(); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_HP_POTION) .chancesOfDropping(0.5f) .itemNumberRange(Range.between(1, 2)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_MP_POTION) .chancesOfDropping(0.5f) .itemNumberRange(Range.between(2, 3)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.FISH) .chancesOfDropping(1.0f) .itemNumberRange(Range.between(2, 3)) .build()); return itemLoot; }
@Override public Collection<ItemLootInfo> getItemLootInfo() { Collection<ItemLootInfo> itemLoot = new LinkedList<>(); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_HP_POTION) .chancesOfDropping(0.2f) .itemNumberRange(Range.between(1, 2)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.SMALL_MP_POTION) .chancesOfDropping(0.2f) .itemNumberRange(Range.between(1, 2)) .build()); itemLoot.add(new ItemLootInfo.Builder() .itemIdentifier(ItemIdentifiers.FISH) .chancesOfDropping(0.8f) .itemNumberRange(Range.between(2, 3)) .build()); return itemLoot; }
public static void main(String[] args) { PayPeriodCalculator wedThruTue = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); System.out.println("Wednesday through Tuesday"); System.out.println(StringUtils.center("-", 75, '-')); Range<LocalDateTime> calculation = wedThruTue.calculatePayPeriod(new LocalDateTime(2017, 8, 17, 0, 0, 0)); System.out.printf("Aug 17 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); calculation = wedThruTue.calculatePayPeriod(new LocalDateTime(2017, 8, 22, 0, 0, 0)); System.out.printf("Aug 22 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); calculation = wedThruTue.calculatePayPeriod(new LocalDateTime(2017, 7, 4, 0, 0, 0)); System.out.printf("July 4 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); System.out.println("\nSunday through Saturday"); System.out.println(StringUtils.center("-", 75, '-')); PayPeriodCalculator sunThruSat = new PayPeriodCalculator(DayOfWeek.SUNDAY, DayOfWeek.SATURDAY); calculation = sunThruSat.calculatePayPeriod(new LocalDateTime(2017, 8, 17, 0, 0, 0)); System.out.printf("Aug 17 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); calculation = sunThruSat.calculatePayPeriod(new LocalDateTime(2017, 8, 22, 0, 0, 0)); System.out.printf("Aug 22 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); calculation = sunThruSat.calculatePayPeriod(new LocalDateTime(2017, 7, 4, 0, 0, 0)); System.out.printf("July 4 2017 -> %s %s\n", calculation.getMinimum(), calculation.getMaximum()); }
BuiltContainer(final String name, final EntityPlayer player, final List<IInventory> inventories, final Predicate<EntityPlayer> canInteract, final List<Range<Integer>> playerSlotRange, final List<Range<Integer>> tileSlotRange) { this.player = player; this.name = name; this.canInteract = canInteract; this.playerSlotRanges = playerSlotRange; this.tileSlotRanges = tileSlotRange; this.inventories = inventories; this.inventories.forEach(inventory -> inventory.openInventory(player)); }
private Range<Double> getFunctionRange(String functionName) { if (functionName.equals(Spherical.FUNCTION_NAME)) { return Spherical.range; } else if (functionName.equals(Schwefel.FUNCTION_NAME)) { return Schwefel.range; } else if (functionName.equals(Ackley.FUNCTION_NAME)) { return Ackley.range; } else if (functionName.equals(Griewangk.FUNCTION_NAME)) { return Griewangk.range; } else if (functionName.equals(Rastrigin.FUNCTION_NAME)) { return Rastrigin.range; } else if (functionName.equals(Rosenbrock.FUNCTION_NAME)) { return Rosenbrock.range; } else { return null; } }
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) { Assert.assertTrue(assertion.name(), assertion.test(state)); } return state; }
@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); Assert.assertTrue(predicate.test(0L)); Assert.assertTrue(predicate.test(5L)); Assert.assertTrue(predicate.test(30L)); Assert.assertTrue(predicate.test(10L)); Assert.assertFalse(predicate.test(51L)); Assert.assertTrue(predicate.test(15L)); Assert.assertFalse(predicate.test(31L)); Assert.assertTrue(predicate.test(45L)); }
@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()); Assert.assertEquals(1, intervals.size()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(0).getMinimum()); assertEquals(now.getTime() - TimeUnit.MINUTES.toMillis(30), intervals.get(0).getMaximum()); } }
@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()); Assert.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()); } }
@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()); Assert.assertEquals(3, intervals.size()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(3), intervals.get(0).getMinimum()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(3) + TimeUnit.MINUTES.toMillis(30), intervals.get(0).getMaximum()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(1).getMinimum()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2) + TimeUnit.MINUTES.toMillis(30), intervals.get(1).getMaximum()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1), intervals.get(2).getMinimum()); assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(30), intervals.get(2).getMaximum()); }
/** * Constructs a {@link UpnpIgdPortMapper} object. * @param networkBus network bus * @param internalAddress source address (address to communicate with gateway from) * @param controlUrl control URL * @param serverName sever name (may be {@code null}) * @param serviceType service type * @param externalPortRange external port range * @param leaseDurationRange lease duration range * @throws NullPointerException if any argument other than {@code serverName} is {@code null} * @throws IllegalArgumentException if {@code 0L > externalPortRange > 65535L || 0L > leaseDurationRange > 0xFFFFFFFFL}, or if * {@code controlUrl} scheme is not {@code "http"} * */ protected UpnpIgdPortMapper(Bus networkBus, InetAddress internalAddress, URL controlUrl, String serverName, String serviceType, Range<Long> externalPortRange, Range<Long> leaseDurationRange) { Validate.notNull(networkBus); Validate.notNull(internalAddress); Validate.notNull(controlUrl); // Validate.notNull(serverName); // can be null Validate.notNull(serviceType); Validate.notNull(externalPortRange); Validate.notNull(leaseDurationRange); Validate.isTrue(leaseDurationRange.getMinimum() >= 0L); Validate.isTrue(leaseDurationRange.getMaximum() <= 0xFFFFFFFFL); Validate.isTrue(externalPortRange.getMinimum() >= 0L); Validate.isTrue(externalPortRange.getMaximum() <= 0xFFFFL); Validate.isTrue("http".equalsIgnoreCase(controlUrl.getProtocol())); this.networkBus = networkBus; this.internalAddress = internalAddress; this.controlUrl = controlUrl; this.serverName = serverName; this.serviceType = serviceType; this.externalPortRange = externalPortRange; this.leaseDurationRange = leaseDurationRange; }
@Test public void mustProperlyParseFaulyHybrid() throws Exception { byte[] buffer = HYBRID_IP_CONNECTION_AND_IPV6_FIREWALL_CONTROL_WITH_FAULTY_XML.getBytes("US-ASCII"); ServiceDescriptionUpnpIgdResponse resp = new ServiceDescriptionUpnpIgdResponse(buffer); Map<ServiceType, IdentifiedService> services = resp.getIdentifiedServices(); assertEquals(2, services.size()); assertTrue(services.containsKey(ServiceType.OLD_PORT_MAPPER)); assertTrue(services.containsKey(ServiceType.FIREWALL)); IdentifiedService service; service = services.get(ServiceType.OLD_PORT_MAPPER); // these are negative and overlapping in XML, so they should be defaults assertEquals(Range.between(0L, 65535L), service.getExternalPortRange()); assertEquals(Range.between(1L, 604800L), service.getLeaseDurationRange()); service = services.get(ServiceType.FIREWALL); // these are valid assertEquals(Range.between(123L, 500L), service.getExternalPortRange()); assertEquals(Range.between(1L, 11111L), service.getLeaseDurationRange()); }
/** * Find the Lowest Common Ancestor of [from, to] in the tree t * * @param t * @param e * @return null if nothing found */ public static Pair<Tree, Tree> findTree(Tree t, Range<Integer> range) { Tree tnF = null; Tree tnT = null; for (Tree leaf : t.getLeaves()) { OffsetLabel label = (OffsetLabel) leaf.label(); if (range.getMinimum() == label.beginPosition()) { tnF = leaf.parent(t); } if (range.getMaximum() == label.endPosition()) { tnT = leaf.parent(t); } } if (tnF == null || tnT == null) { return null; } return new Pair<Tree, Tree>(tnF, tnT); }
private ContainsTest containmentTest(final double doubleStarts, final double doubleEnds) { ContainsTest containsTest = null; if(start<end){ containsTest = new ContainsTest(){ final Range<Double> range = Range.between(doubleStarts, doubleEnds); @Override public boolean contains(Double dateAsDouble) { return range.contains(dateAsDouble); } }; }else{ containsTest = new ContainsTest(){ final Range<Double> range = Range.between(doubleStarts, doubleEnds); @Override public boolean contains(Double dateAsDouble) { return !range.contains(dateAsDouble); } }; } return containsTest; }
@Test public void testFileContentSegment() { final BinaryService resolver = new FileBasedBinaryService(directory, idService.getSupplier("file:")); final List<Range<Integer>> range = singletonList(between(1, 5)); assertTrue(resolver.getContent(file, range).isPresent()); assertEquals(" tes", resolver.getContent(file, range).map(this::uncheckedToString).get()); }
@Test public void testFileContentSegments() { final BinaryService resolver = new FileBasedBinaryService(directory, idService.getSupplier("file:")); final List<Range<Integer>> ranges = new ArrayList<>(); ranges.add(between(1, 5)); ranges.add(between(8, 10)); assertTrue(resolver.getContent(file, ranges).isPresent()); assertEquals(" tesoc", resolver.getContent(file, ranges).map(this::uncheckedToString).get()); }
@Test public void testFileContentSegmentBeyond() { final BinaryService resolver = new FileBasedBinaryService(directory, idService.getSupplier("file:")); final List<Range<Integer>> range = singletonList(between(1000, 1005)); assertTrue(resolver.getContent(file, range).isPresent()); assertEquals("", resolver.getContent(file, range).map(this::uncheckedToString).get()); }
private static Stream<Link> getTimeMap(final String identifier, final Stream<Range<Instant>> mementos) { return mementos.reduce((acc, x) -> between(acc.getMinimum(), x.getMaximum())) .map(x -> Link.fromUri(identifier + TIMEMAP_PARAM).rel(TIMEMAP).type(APPLICATION_LINK_FORMAT) .param(FROM, ofInstant(x.getMinimum().minusNanos(1L).plusSeconds(1L), UTC).format(RFC_1123_DATE_TIME)) .param(UNTIL, ofInstant(x.getMaximum(), UTC).format(RFC_1123_DATE_TIME)).build()) // TODO use Optional::stream with JDK9 .map(Stream::of).orElseGet(Stream::empty); }
@Test public void testSingleRange() { final ParseValue mock = val(0, 1); final List<Range<Long>> expected = ranges(range(0, 1)); _parseValueProcessor.process(mock); assertEquals(expected, _parseValueProcessor.analysis().ranges()); }
@Test public void testMultiRange() { final ParseValue[] values = new ParseValue[]{val(0, 1), val(1, 1), val(10, 5), val(4, 1), val(8, 2)}; final List<Range<Long>> expected = ranges(range(0, 2), range(4, 5), range(8, 15)); for (final ParseValue value : values) { _parseValueProcessor.process(value); } assertEquals(expected, _parseValueProcessor.analysis().ranges()); }
@Test public void testBigRanges() { final ParseValue[] values = new ParseValue[]{val(0, 1000), val(50, 500), val(10000, 666), val(3000, 7500), val(123456789, 1)}; final List<Range<Long>> expected = ranges(range(0, 1000), range(3000, 10666), range(123456789, 123456790)); for (final ParseValue value : values) { _parseValueProcessor.process(value); } assertEquals(expected, _parseValueProcessor.analysis().ranges()); }
@Test public void testBatchOfIdentical() { final ParseValue[] values = new ParseValue[10000]; for (int i = 0; i < values.length; i++) { values[i] = val(0, 1); } final List<Range<Long>> expected = ranges(range(0, 1)); for (final ParseValue value : values) { _parseValueProcessor.process(value); } assertEquals(expected, _parseValueProcessor.analysis().ranges()); }
public Range<LocalDateTime> calculatePayPeriod(LocalDateTime dateTime) { int todayDayOfWeekNumber = dateTime.getDayOfWeek(); int endingDifference = endingDayOfWeek.getDayNumber() - todayDayOfWeekNumber; int beginningDifference = beginningDayOfWeek.getDayNumber() - todayDayOfWeekNumber; LocalDateTime beginningDateTime = calculateEndingDateTime(dateTime, beginningDifference).toDateTime().withTimeAtStartOfDay().toLocalDateTime(); LocalDateTime endingDateTime = calculateBeginningDateTime(dateTime, endingDifference).toDateTime().withTimeAtStartOfDay().plusHours(23).plusMinutes(59).plusSeconds(59).toLocalDateTime(); return Range.between(beginningDateTime, endingDateTime, LocalDateTime::compareTo); }
@Test public void testWednesdayThroughTuesdayAugust172017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 17, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 16, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 22, 23, 59, 59)); }
@Test public void testWednesdayThroughTuesdayAugust152017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 15, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 9, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 15, 23, 59, 59)); }
@Test public void testWednesdayThroughTuesdayAugust162017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 16, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 16, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 22, 23, 59, 59)); }
@Test public void testWednesdayThroughTuesdayAugust222017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 22, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 16, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 22, 23, 59, 59)); }
@Test public void testWednesdayThroughTuesdayAugust232017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.WEDNESDAY, DayOfWeek.TUESDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 23, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 23, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 29, 23, 59, 59)); }
@Test public void testSundayThroughSaturdayAugust172017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.SUNDAY, DayOfWeek.SATURDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 17, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 13, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 19, 23, 59, 59)); }
@Test public void testSundayThroughSaturdayAugust132017() { PayPeriodCalculator calculator = new PayPeriodCalculator(DayOfWeek.SUNDAY, DayOfWeek.SATURDAY); Range<LocalDateTime> result = calculator.calculatePayPeriod(new LocalDateTime(2017, 8, 13, 0, 0, 0)); assertThat(result.getMinimum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 13, 0, 0, 0)); assertThat(result.getMaximum()).isEqualByComparingTo(new LocalDateTime(2017, 8, 19, 23, 59, 59)); }
/** * Close this builder and add the slot list to the current {@link BuiltContainer} construction. * * @return the parent {@link ContainerBuilder} to resume the "Builder" pattern */ public ContainerBuilder addInventory() { this.parent.tileInventoryRanges.add(Range.between(this.rangeStart, this.parent.slots.size() - 1)); this.parent.inventories.add(this.tile); return this.parent; }