@Test public void testAllocationOrderDoesNotOverFillWithMultipleSizesAndWeights() { PreFillQueue allocationOrder = bitmapPreFiller.generateAllocationOrder(new PreFillType[] { new PreFillType.Builder(DEFAULT_BITMAP_WIDTH, DEFAULT_BITMAP_HEIGHT) .setConfig(defaultBitmapConfig).setWeight(4).build(), new PreFillType.Builder(DEFAULT_BITMAP_WIDTH / 2, DEFAULT_BITMAP_HEIGHT) .setConfig(defaultBitmapConfig).build(), new PreFillType.Builder(DEFAULT_BITMAP_WIDTH, DEFAULT_BITMAP_HEIGHT / 3) .setConfig(defaultBitmapConfig).setWeight(3).build() }); int byteSize = 0; while (!allocationOrder.isEmpty()) { PreFillType current = allocationOrder.remove(); byteSize += Util.getBitmapByteSize(current.getWidth(), current.getHeight(), current.getConfig()); } assertThat(byteSize).isIn(Range.atMost(poolSize + cacheSize)); }
@Test public void testAllocationOrderDoesNotOverFillWithMultipleSizes() { PreFillQueue allocationOrder = bitmapPreFiller.generateAllocationOrder( new PreFillType.Builder(DEFAULT_BITMAP_WIDTH, DEFAULT_BITMAP_HEIGHT) .setConfig(defaultBitmapConfig).build(), new PreFillType.Builder(DEFAULT_BITMAP_WIDTH / 2, DEFAULT_BITMAP_HEIGHT) .setConfig(defaultBitmapConfig).build(), new PreFillType.Builder(DEFAULT_BITMAP_WIDTH, DEFAULT_BITMAP_HEIGHT / 2) .setConfig(defaultBitmapConfig).build()); long byteSize = 0; while (!allocationOrder.isEmpty()) { PreFillType current = allocationOrder.remove(); byteSize += Util.getBitmapByteSize(current.getWidth(), current.getHeight(), current.getConfig()); } assertThat(byteSize).isIn(Range.atMost(poolSize + cacheSize)); }
public static FindByRange<DatasetSplitId> getSplitsRange(DatasetConfig datasetConfig) { final String datasetId = datasetConfig.getId().getId(); Range<String> range = getSplitStringRange(datasetConfig); final DatasetSplitId start = new DatasetSplitId(datasetId, range.lowerEndpoint()); final DatasetSplitId end = new DatasetSplitId(datasetId, range.upperEndpoint()); return new FindByRange<DatasetSplitId>() .setStart(start, true) .setEnd(end, false); }
public void add(double value, long numSamples) { checkArgument(numSamples >= 0, "numSamples must be non-negative"); checkDouble(value); // having numSamples = 0 works as expected (does nothing) even if we let it continue, but we // can short-circuit it by returning early. if (numSamples == 0) { return; } Map.Entry<Range<Double>, Long> entry = intervalCounts.getEntry(value); intervalCounts.put(entry.getKey(), entry.getValue() + numSamples); this.count += numSamples; // Update mean and sumOfSquaredDeviation using Welford's method // See Knuth, "The Art of Computer Programming", Vol. 2, page 232, 3rd edition double delta = value - mean; mean += delta * numSamples / count; sumOfSquaredDeviation += delta * (value - mean) * numSamples; }
@Test public void testAdd_positiveThenNegativeValue() { distribution.add(2.0); distribution.add(-2.0); assertThat(distribution.count()).isEqualTo(2); assertThat(distribution.mean()).isWithin(0.0).of(0.0); assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(8.0); assertThat(distribution.intervalCounts()) .isEqualTo( ImmutableRangeMap.<Double, Long>builder() .put(Range.lessThan(3.0), 2L) .put(Range.closedOpen(3.0, 5.0), 0L) .put(Range.atLeast(5.0), 0L) .build()); }
/** * Builds a mapping of block locations to file byte range */ private ImmutableRangeMap<Long,BlockLocation> buildBlockMap(FileStatus status) throws IOException { final Timer.Context context = metrics.timer(BLOCK_MAP_BUILDER_TIMER).time(); BlockLocation[] blocks; ImmutableRangeMap<Long,BlockLocation> blockMap; blocks = fs.getFileBlockLocations(status, 0 , status.getLen()); ImmutableRangeMap.Builder<Long, BlockLocation> blockMapBuilder = new ImmutableRangeMap.Builder<>(); for (BlockLocation block : blocks) { long start = block.getOffset(); long end = start + block.getLength(); Range<Long> range = Range.closedOpen(start, end); blockMapBuilder = blockMapBuilder.put(range, block); } blockMap = blockMapBuilder.build(); blockMapMap.put(status.getPath(), blockMap); context.stop(); return blockMap; }
@Test public void intRange() throws Exception { Entropy e = new MutableEntropy(SEED); Range<Integer> range = Range.closedOpen(-5, 5); Multiset<Integer> distribution = HashMultiset.create(); // Choose 1k values and check that they are in the range for(int i = 0; i < 10000; i++) { final int value = e.randomInt(range); assertContains(range, value); distribution.add(value); e.advance(); } // Assert that each of the 10 values was chosen ~1000 times Ranges.forEach(range, value -> { assertEquals(1000D, distribution.count(value), 50D); }); }
private QuoteFilter(Map<Symbol, ImmutableRangeSet<Integer>> docIdToBannedRegions) { this.docIdToBannedRegions = ImmutableMap.copyOf(docIdToBannedRegions); for (RangeSet<Integer> rs : docIdToBannedRegions.values()) { for (final Range<Integer> r : rs.asRanges()) { checkArgument(r.hasLowerBound()); checkArgument(r.hasUpperBound()); checkArgument(r.lowerEndpoint() >= 0); } } // these ensure we can serialize safely for (Symbol sym : docIdToBannedRegions.keySet()) { final String s = sym.toString(); checkArgument(!s.isEmpty(), "Document IDs may not be empty"); checkArgument(!CharMatcher.WHITESPACE.matchesAnyOf(s), "Document IDs may not contain whitespace: %s", s); } }
public void saveTo(ByteSink sink) throws IOException { final PrintWriter out = new PrintWriter(sink.asCharSink(Charsets.UTF_8).openBufferedStream()); out.println(docIdToBannedRegions.size()); for (final Map.Entry<Symbol, ImmutableRangeSet<Integer>> entry : docIdToBannedRegions .entrySet()) { out.println(entry.getKey()); final List<String> parts = Lists.newArrayList(); for (final Range<Integer> r : entry.getValue().asRanges()) { // we know by construction these ranges are bounded above and below parts.add(String.format("%d-%d", r.lowerEndpoint(), r.upperEndpoint())); } out.println(StringUtils.SpaceJoiner.join(parts)); } out.close(); }
@Test public void testQuotedRegionComputation() throws IOException { final Map<String, ImmutableRangeSet<Integer>> testCases = ImmutableMap.of( "Foo <quote>bar <quote>baz</quote> <quote>meep</quote></quote> blah <quote>another</quote>", ImmutableRangeSet.<Integer>builder().add(Range.closed(4, 60)).add(Range.closed(67, 88)) .build(), "<quote>lalala</quote>", ImmutableRangeSet.of(Range.closed(0, 20)), "No quotes!", ImmutableRangeSet.<Integer>of()); for (final Map.Entry<String, ImmutableRangeSet<Integer>> entry : testCases.entrySet()) { final Symbol docid = Symbol.from("dummy"); final QuoteFilter reference = QuoteFilter.createFromBannedRegions(ImmutableMap.of(docid, entry.getValue())); final QuoteFilter computed = QuoteFilter.createFromOriginalText(ImmutableMap.of(docid, CharSource.wrap(entry.getKey()))); assertEquals(reference, computed); } }
@Test public void testTableWithTransitiveInds(DataAccessObject dataAccessObject) throws AlgorithmExecutionException { // GIVEN Attribute attributeA = new Attribute(new ColumnIdentifier(TABLE_NAME, "a"), Range.closed(1, 3), INTEGER); Attribute attributeB = new Attribute(new ColumnIdentifier(TABLE_NAME, "b"), Range.closed(3, 4), INTEGER); Attribute attributeC = new Attribute(new ColumnIdentifier(TABLE_NAME, "c"), Range.closed(1, 3), INTEGER); Attribute attributeD = new Attribute(new ColumnIdentifier(TABLE_NAME, "d"), Range.closed(1, 4), INTEGER); ImmutableList<Attribute> attributes = ImmutableList.of(attributeA, attributeB, attributeC, attributeD); TableInfo tableInfo = new TableInfo(TABLE_NAME, attributes); InclusionDependency indAC = toInd(attributeA.getColumnIdentifier(), attributeC.getColumnIdentifier()); InclusionDependency indAD = toInd(attributeA.getColumnIdentifier(), attributeD.getColumnIdentifier()); InclusionDependency indCA = toInd(attributeC.getColumnIdentifier(), attributeA.getColumnIdentifier()); InclusionDependency indCD = toInd(attributeC.getColumnIdentifier(), attributeD.getColumnIdentifier()); InclusionDependency indBD = toInd(attributeB.getColumnIdentifier(), attributeD.getColumnIdentifier()); ImmutableSet<InclusionDependency> validInds = ImmutableSet.of(indAC, indAD, indCA, indCD, indBD); when(dataAccessObject.isValidUIND(any(InclusionDependency.class))) .thenAnswer(invocation -> validInds.contains(invocation.<InclusionDependency>getArgument(0))); // WHEN when(dataAccessObject.getTableInfo(TABLE_NAME)).thenReturn(tableInfo); bellBrockhausen.execute(); // THEN assertThat(resultReceiver.getReceivedResults()).containsExactlyInAnyOrder(toArray(validInds)); }
private void refillRetentions() { result.ranges.clear(); int counter = 0; final int valuesMaxIndex = ageRetentionMap.values().size() - 1; final List<Map.Entry<Integer, Integer>> entryList = ageRetentionMap.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toList()); for (Map.Entry<Integer, Integer> retention : entryList) { final Integer age = retention.getKey(); final Integer precision = retention.getValue(); final boolean isLast = (counter == valuesMaxIndex); if (!isLast) { final Integer nextAge = entryList.get(counter + 1).getKey(); result.ranges.put(Range.closedOpen(age, nextAge), precision); } else { result.ranges.put(Range.atLeast(age), precision); } counter++; } }
public boolean matches(DrillFileSystem fs, FileStatus status) throws IOException{ if (ranges.isEmpty()) { return false; } final Range<Long> fileRange = Range.closedOpen( 0L, status.getLen()); try (FSDataInputStream is = fs.open(status.getPath())) { for(RangeMagics rMagic : ranges) { Range<Long> r = rMagic.range; if (!fileRange.encloses(r)) { continue; } int len = (int) (r.upperEndpoint() - r.lowerEndpoint()); byte[] bytes = new byte[len]; is.readFully(r.lowerEndpoint(), bytes); for (byte[] magic : rMagic.magics) { if (Arrays.equals(magic, bytes)) { return true; } } } } return false; }
public List<T> parseChildList(Element parent, Range<Integer> count) throws InvalidXMLException { final List<T> list = parseChildren(parent).collect(Collectors.toList()); if(count.contains(list.size())) return list; final Optional<Integer> min = Ranges.minimum(count), max = Ranges.maximum(count); if(!max.isPresent()) { throw new InvalidXMLException("Expected " + min.get() + " or more child elements", parent); } else if(!min.isPresent()) { throw new InvalidXMLException("Expected no more than " + max.get() + " child elements", parent); } else if(min.equals(max)) { throw new InvalidXMLException("Expected exactly " + min.get() + " child elements", parent); } else { throw new InvalidXMLException("Expected between " + min.get() + " and " + max.get() + " child elements", parent); } }
public void testNewProxy_goodMethodWithNotEnoughTime() throws Exception { SampleImpl target = new SampleImpl(9999); Sample proxy = service.newProxy(target, Sample.class, NOT_ENOUGH_MS, MILLISECONDS); Stopwatch stopwatch = Stopwatch.createStarted(); try { proxy.sleepThenReturnInput("x"); fail("no exception thrown"); } catch (UncheckedTimeoutException expected) { } assertThat(stopwatch.elapsed(MILLISECONDS)).isIn(Range.closed(NOT_ENOUGH_MS, DELAY_MS * 2)); // Is it still computing away anyway? assertThat(target.finished).isFalse(); MILLISECONDS.sleep(ENOUGH_MS); assertThat(target.finished).isFalse(); }
@Override protected void configure() { final TypeLiteral<Range<T>> rangeType = Ranges.typeOf(type); final TypeLiteral<RangeParser<T>> rangeParserType = new ResolvableType<RangeParser<T>>(){}.with(typeArg); final TypeLiteral<RangeProperty<T>> rangePropertyType = new ResolvableType<RangeProperty<T>>(){}.with(typeArg); bindPrimitiveParser(rangeType).to(rangeParserType); // NodeParser<Range<T>> -> RangeParser<T> bind(rangeParserType); // RangeParser<T> install(new PropertyManifest<>(rangeType, rangePropertyType)); }
@Nonnull private static ABIVersion selectVersion(final ConnectClientRequest message) { final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion()); for (ABIVersion v : SUPPORTED_ABIVERSIONS) { if (clientRange.contains(v)) { return v; } } throw new IllegalArgumentException(String.format( "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS, clientRange)); }
@Test public void testDefaultMemoryCacheSizeIsLimitedByMemoryClass() { final int memoryClassBytes = Math.round(harness.getScreenSize() * harness.memoryCacheScreens * harness.sizeMultiplier); Shadows.shadowOf(harness.activityManager).setMemoryClass(memoryClassBytes / (1024 * 1024)); float memoryCacheSize = harness.getCalculator().getMemoryCacheSize(); assertThat(memoryCacheSize) .isIn(Range.atMost(memoryClassBytes * harness.sizeMultiplier)); }
public int deleteSplitOrphans() { final List<SplitRange> ranges = new ArrayList<>(); int itemsDeleted = 0; for(Map.Entry<byte[], NameSpaceContainer> entry : namespace.find()) { NameSpaceContainer container = entry.getValue(); if(container.getType() == Type.DATASET && container.getDataset().getReadDefinition() != null && container.getDataset().getReadDefinition().getSplitVersion() != null) { ranges.add(new SplitRange(DatasetSplitId.getSplitStringRange(container.getDataset()))); } } for(Map.Entry<DatasetSplitId, DatasetSplit> e : splitsStore.find()) { String id = e.getKey().getSplitIdentifier(); final int item = Collections.binarySearch(ranges, new SplitRange(Range.singleton(id))); // we should never find a match since we're searching for a split key. Preconditions.checkArgument(item < 0); final int insertionPoint = (-item) - 1; final int consideredRange = insertionPoint - 1; // since a normal match would come directly after the start range, we need to check the range directly above the insertion point. if(consideredRange < 0 || ranges.get(consideredRange).range.contains(id)) { splitsStore.delete(e.getKey()); itemsDeleted++; } } return itemsDeleted; }
MaterialData chooseShuffledMaterial() { ImmutableRangeMap.Builder<Double, MaterialData> weightsBuilder = ImmutableRangeMap.builder(); double sum = 0d; for(MaterialData material : shuffleableMaterialDeficit.materials()) { double weight = shuffleableMaterialDeficit.get(material); if(weight > 0) { weightsBuilder.put(Range.closedOpen(sum, sum + weight), material); sum += weight; } } RangeMap<Double, MaterialData> weights = weightsBuilder.build(); return weights.get(match.getRandom().nextDouble() * sum); }
Collection<BaseComponent> format() { final ImmutableList.Builder<BaseComponent> lines = ImmutableList.builder(); lines.add(new TranslatableComponent( "matchQuota.matchCounts", new Component(String.valueOf(matchesPlayed), ChatColor.AQUA), new Component(String.valueOf(quota.maximum()), ChatColor.AQUA) )); if(matchesRemaining() == 0) { lines.add(new TranslatableComponent( "matchQuota.nextMatch", new Component(PeriodFormats.briefNaturalApproximate(now, earliestJoinTime), ChatColor.AQUA) )); } if(!quota.premium()) { Range<Integer> premiumRange = getConfig().getPremiumMaximum(); if(premiumRange != null) { if(premiumRange.upperEndpoint() == Integer.MAX_VALUE) { lines.add(Links.shopPlug("shop.plug.rankedMatches.unlimited")); } else { BaseComponent premiumLimit = new Component(String.valueOf(premiumRange.upperEndpoint()), ChatColor.AQUA); if(premiumRange.upperEndpoint().equals(premiumRange.lowerEndpoint())) { lines.add(Links.shopPlug("shop.plug.rankedMatches.uniform", premiumLimit)); } else { lines.add(Links.shopPlug("shop.plug.rankedMatches.upto", premiumLimit)); } } } } return lines.build(); }
@Test public void testCumulativePoolAndMemoryCacheSizeAreLimitedByMemoryClass() { final int memoryClassBytes = Math.round( harness.getScreenSize() * (harness.bitmapPoolScreens + harness.memoryCacheScreens) * harness.sizeMultiplier); Shadows.shadowOf(harness.activityManager).setMemoryClass(memoryClassBytes / (1024 * 1024)); int memoryCacheSize = harness.getCalculator().getMemoryCacheSize(); int bitmapPoolSize = harness.getCalculator().getBitmapPoolSize(); assertThat((float) memoryCacheSize + bitmapPoolSize) .isIn(Range.atMost(memoryClassBytes * harness.sizeMultiplier)); }
@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); } }
@MethodParser("countdown") public Filter parseCountdownFilter(Element el) throws InvalidXMLException { final Duration duration = XMLUtils.parseDuration(el, "duration").required(); if(Comparables.greaterThan(duration, Duration.ZERO)) { return new MonostableFilter(duration, filterParser.parseReferenceOrChild(el), messageTemplates.property(el, "message") .placeholders(Range.closed(0, 1)) .optional()); } else { return new StaticFilter(Filter.QueryResponse.DENY); } }
@Test public void testAdd_oneValue() { distribution.add(5.0); assertThat(distribution.count()).isEqualTo(1); assertThat(distribution.mean()).isWithin(0.0).of(5.0); assertThat(distribution.sumOfSquaredDeviation()).isWithin(0.0).of(0); assertThat(distribution.intervalCounts()) .isEqualTo( ImmutableRangeMap.<Double, Long>builder() .put(Range.lessThan(3.0), 0L) .put(Range.closedOpen(3.0, 5.0), 0L) .put(Range.atLeast(5.0), 1L) .build()); }
@Test public void testAdd_noFiniteIntervals_edgeValue_returnsOverflowInterval() throws Exception { MutableDistribution distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(2.0))); distribution.add(2.0); assertThat(distribution.intervalCounts()) .isEqualTo( ImmutableRangeMap.<Double, Long>builder() .put(Range.lessThan(2.0), 0L) .put(Range.atLeast(2.0), 1L) .build()); }
@Override public EncodedDiscreteResources read(Kryo kryo, Input input, Class<EncodedDiscreteResources> cls) { @SuppressWarnings("unchecked") List<ClosedOpenRange> ranges = kryo.readObject(input, ArrayList.class); DiscreteResourceCodec codec = (DiscreteResourceCodec) kryo.readClassAndObject(input); RangeSet<Integer> rangeSet = TreeRangeSet.create(); ranges.stream() .map(x -> Range.closedOpen(x.lowerBound(), x.upperBound())) .forEach(rangeSet::add); return new EncodedDiscreteResources(rangeSet, codec); }
@Test public void testAdd_oneFiniteInterval_inBoundsValue_returnsInBoundsInterval() throws Exception { MutableDistribution distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0))); distribution.add(3.0); assertThat(distribution.intervalCounts()) .isEqualTo( ImmutableRangeMap.<Double, Long>builder() .put(Range.lessThan(1.0), 0L) .put(Range.closedOpen(1.0, 5.0), 1L) .put(Range.atLeast(5.0), 0L) .build()); }
@Override Range<Integer> computeRange() { Range<Integer> docRange = EMPTY_RANGE; for (Doc doc : docs) { docRange = union(docRange, doc.range()); } return docRange; }
@Test public void testAdd_oneFiniteInterval_secondEdgeValue_returnsOverflowInterval() throws Exception { MutableDistribution distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(1.0, 5.0))); distribution.add(5.0); assertThat(distribution.intervalCounts()) .isEqualTo( ImmutableRangeMap.<Double, Long>builder() .put(Range.lessThan(1.0), 0L) .put(Range.closedOpen(1.0, 5.0), 0L) .put(Range.atLeast(5.0), 1L) .build()); }
private void fillDefinedMappingRanges() { RangeMapping range = new RangeMapping(0, ""); Map<Integer, String> cssProgressToStyleMapping = cssMappingParser.getCssProgressToStyleMapping(); for (int percent = 0; percent <= 100; ++percent) { if (cssProgressToStyleMapping.containsKey(percent)) { progressToStyleName.addValueForRange(Range.closedOpen(range.getRangeStart(), percent), range.getRangeStyleName()); range = new RangeMapping(percent, cssProgressToStyleMapping.get(percent)); } } progressToStyleName.addValueForRange(Range.closed(range.getRangeStart(), 100), range.getRangeStyleName()); }
@Override public void setPlayerLimits(Range<Integer> limits) { if(!playerLimits.equals(limits)) { checkArgument(limits.lowerBoundType() == BoundType.CLOSED); checkArgument(limits.upperBoundType() == BoundType.CLOSED); playerLimits = limits; callEvent(new MatchResizeEvent(this)); } }
public boolean matches(FileSystemWrapper fs, FileStatus status) throws IOException{ if (ranges.isEmpty() || status.isDirectory()) { return false; } // walk all the way down in the symlinks until a hard entry is reached FileStatus current = status; while (current.isSymlink()) { current = fs.getFileStatus(status.getSymlink()); } // if hard entry is not a file nor can it be a symlink then it is not readable simply deny matching. if (!current.isFile()) { return false; } final Range<Long> fileRange = Range.closedOpen( 0L, status.getLen()); try (FSDataInputStream is = fs.open(status.getPath())) { for(RangeMagics rMagic : ranges) { Range<Long> r = rMagic.range; if (!fileRange.encloses(r)) { continue; } int len = (int) (r.upperEndpoint() - r.lowerEndpoint()); byte[] bytes = new byte[len]; is.readFully(r.lowerEndpoint(), bytes); for (byte[] magic : rMagic.magics) { if (Arrays.equals(magic, bytes)) { return true; } } } } return false; }
private ProgressAsset buildProgressAsset(Map<Integer, List<ShowImageDTO>> resolvedConfig, int index) { ProgressAsset progressAsset = new ProgressAsset(index); int lowerBound = Integer.MIN_VALUE; ShowImageDTO imageDTO = new ShowImageDTO("", new Size(0, 0)); for (Entry<Integer, List<ShowImageDTO>> element : resolvedConfig.entrySet()) { Range<Integer> range = Range.closedOpen(lowerBound, element.getKey()); progressAsset.add(range, imageDTO); lowerBound = element.getKey(); imageDTO = getElementAtIndex(element.getValue(), index); } Range<Integer> lastRange = Range.atLeast(lowerBound); progressAsset.add(lastRange, imageDTO); return progressAsset; }
private ArrayList<Branch2> getLeavesInfoForM5P(M5P model){ ArrayList<Branch2> retval = new ArrayList<Branch2>(); ArrayList<RuleNode> leafNodes = new ArrayList<RuleNode>(); model.getM5RootNode().returnLeaves(new ArrayList[]{leafNodes}); for(RuleNode leaf : leafNodes){ Branch2 branch = new Branch2(); ArrayList<PreConstructedLinearModel> lmodel = new ArrayList<PreConstructedLinearModel>(); lmodel.add(leaf.getModel()); branch.setLinearModels(lmodel); Map<Attribute,Range<Double>> rangeMap = branch.getRangeMap(); RuleNode parent = leaf, child; while(parent.parentNode()!=null){ child = parent; parent = parent.parentNode(); Attribute att = this.labeledInstances.attribute(parent.splitAtt()); Range<Double> previous = null; if(parent.leftNode()==child) previous = rangeMap.put(att,Range.atMost(parent.splitVal())); else previous = rangeMap.put(att, Range.greaterThan(parent.splitVal())); //the attribute is visited previously if(previous!=null){ previous = rangeMap.get(att).intersection(previous); rangeMap.put(att, previous); } } retval.add(branch); } return retval; }
/** * Generates {@code Replacement}s rewriting {@code source} to {@code replacement}, under the * assumption that they differ in whitespace alone. */ private static List<Replacement> toReplacements(String source, String replacement) { if (!NOT_WHITESPACE.retainFrom(source).equals(NOT_WHITESPACE.retainFrom(replacement))) { throw new IllegalArgumentException( "source = \"" + source + "\", replacement = \"" + replacement + "\""); } /* * In the past we seemed to have problems touching non-whitespace text in the formatter, even * just replacing some code with itself. Retrospective attempts to reproduce this have failed, * but this may be an issue for future changes. */ List<Replacement> replacements = new ArrayList<>(); int i = NOT_WHITESPACE.indexIn(source); int j = NOT_WHITESPACE.indexIn(replacement); if (i != 0 || j != 0) { replacements.add(Replacement.create(Range.closedOpen(0, i), replacement.substring(0, j))); } while (i != -1 && j != -1) { int i2 = NOT_WHITESPACE.indexIn(source, i + 1); int j2 = NOT_WHITESPACE.indexIn(replacement, j + 1); if (i2 == -1 || j2 == -1) { break; } if ((i2 - i) != (j2 - j) || !source.substring(i + 1, i2).equals(replacement.substring(j + 1, j2))) { replacements.add( Replacement.create(Range.closedOpen(i + 1, i2), replacement.substring(j + 1, j2))); } i = i2; j = j2; } return replacements; }
public Integer getCenterPosition(int size, int parentAbsoluteCoord, Axis coord) { // viewport Rectangle viewport = viewportHelper.getViewport(); Range<Integer> viewportRange = rangeCreator.getRangeForAxis(viewport, coord); // container Rectangle playerRect = sizeHelper.getPlayerContainerRectangle(); Range<Integer> containerRange = rangeCreator.getRangeForAxis(playerRect, coord); // compute int value = findCenterPosition(size, containerRange, viewportRange); return value - parentAbsoluteCoord; }
public static Range toRange(Coprocessor.KeyRange range) { if (range == null || (range.getStart().isEmpty() && range.getEnd().isEmpty())) { return Range.all(); } if (range.getStart().isEmpty()) { return Range.lessThan(Comparables.wrap(range.getEnd())); } if (range.getEnd().isEmpty()) { return Range.atLeast(Comparables.wrap(range.getStart())); } return Range.closedOpen(Comparables.wrap(range.getStart()), Comparables.wrap(range.getEnd())); }
private static Range<Integer> findComment(String text, int offset) { int start = text.indexOf("/*", offset); int end = text.indexOf("*/", start); if (start == -1 || end == -1) { return null; } return Range.closed(start, end + 2); }