项目:GitHub
文件:BitmapPreFillerTest.java
@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));
}
项目:GitHub
文件:BitmapPreFillerTest.java
@Test
public void testAllocationorderDoesNotOverFillWithMultipleSizes() {
PreFillQueue allocationorder = bitmapPreFiller.generateallocationorder(
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.getConfig());
}
assertthat(byteSize).isIn(Range.atMost(poolSize + cacheSize));
}
项目:dremio-oss
文件:DatasetSplitId.java
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());
}
项目:dremio-oss
文件:BlockMapBuilder.java
/**
* 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,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;
}
项目:ProjectAres
文件:EntropyTest.java
@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);
});
}
项目:tac-kbp-eal
文件:QuoteFilter.java
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);
}
}
项目:tac-kbp-eal
文件:QuoteFilter.java
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();
}
项目:tac-kbp-eal
文件:TestQuoteFilter.java
@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"),INTEGER);
Attribute attributeD = new Attribute(new ColumnIdentifier(TABLE_NAME,"d"),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));
}
项目:graphouse
文件:MetricRetention.java
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++;
}
}
项目:QDrill
文件:BasicFormatMatcher.java
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;
}
项目:ProjectAres
文件:FeatureParser.java
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);
}
}
项目:guava-mock
文件:SimpleTimeLimiterTest.java
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();
}
项目:ProjectAres
文件:RangeParserManifest.java
@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));
}
项目:hashsdn-controller
文件:Shard.java
@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));
}
项目:dremio-oss
文件:NamespaceServiceImpl.java
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;
}
项目:ProjectAres
文件:Renewable.java
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);
}
项目:ProjectAres
文件:QuotaMatchModule.java
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,0L)
.put(Range.closedOpen(3.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());
}
项目:athena
文件:EncodedResourcesSerializer.java
@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,1L)
.put(Range.atLeast(5.0),0L)
.build());
}
项目:javaide
文件:Doc.java
@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,1L)
.build());
}
项目:empiria.player
文件:InfoModuleProgressMapping.java
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());
}
项目:ProjectAres
文件:MatchImpl.java
@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));
}
}
项目:dremio-oss
文件:BasicFormatMatcher.java
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,bytes)) {
return true;
}
}
}
}
return false;
}
项目:empiria.player
文件:ProgressAssetProvider.java
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;
}
项目:bestconf
文件:COMT2.java
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;
}
项目:javaide
文件:SnippetFormatter.java
/**
* 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;
}
项目:empiria.player
文件:CenterPositionFinder.java
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;
}
项目:tikv-client-lib-java
文件:KeyRangeUtils.java
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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。