use of org.apache.commons.lang3.Range in project Solar by ArekkuusuJerii.
the class TileDilaton method pushExtension.
public void pushExtension(boolean powered) {
if (!world.isRemote && !(!isActiveLazy() && !powered)) {
ProfilerHelper.flagSection("[Dilaton] Redstone signal received");
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(getPos());
EnumFacing facing = getFacingLazy();
int range = powered ? getRedstonePower() + 1 : 16;
int pointer = 0;
if (isActiveLazy()) {
ProfilerHelper.flagSection("[Dilaton] Locate nearest extension");
boolean found = false;
for (; pointer < range; pointer++) {
if (!isPosValid(pos.move(facing)) || pointer >= range)
return;
IBlockState state = world.getBlockState(pos);
if (state.getBlock() == ModBlocks.DILATON_EXTENSION) {
world.setBlockToAir(pos);
found = true;
break;
}
}
if (!found)
return;
if (!powered)
pointer = 0;
}
ProfilerHelper.begin("[Dilaton] Gathering pushed blocks");
if (!powered)
facing = facing.getOpposite();
List<Triple<IBlockState, NBTTagCompound, BlockPos>> pushed = Lists.newArrayList();
List<BlockPos> removed = Lists.newArrayList();
loop: for (; pointer < range; pointer++) {
if (pos.move(facing).equals(getPos()) || !isPosValid(pos))
break;
IBlockState next = world.getBlockState(pos);
if (next.getBlock() == Blocks.AIR)
continue;
float hardness = next.getBlockHardness(world, pos);
if (hardness > 2000F || hardness < 0F)
break;
EnumPushReaction reaction;
if (next.getMaterial() == Material.WATER)
reaction = EnumPushReaction.IGNORE;
else
reaction = next.getMobilityFlag();
switch(reaction) {
case PUSH_ONLY:
case NORMAL:
if (pushed.add(getStateTile(next, pos.toImmutable())) && pushed.size() > 15)
break loop;
else
++range;
continue loop;
case DESTROY:
removed.add(pos.toImmutable());
continue loop;
case BLOCK:
break loop;
case IGNORE:
}
}
ProfilerHelper.interrupt("[Dilaton] Relocating pushed blocks");
Set<BlockPos> deleted = Sets.newHashSet();
if (pushed.size() <= 15) {
pos.move(facing.getOpposite());
}
for (int i = 0, size = pushed.size(); i < size; i++) {
if (isPosReplaceable(pos)) {
for (int index = pushed.size() - 1; index >= 0; index--) {
Triple<IBlockState, NBTTagCompound, BlockPos> triplet = pushed.get(index);
if (setStateTile(triplet.getLeft(), triplet.getMiddle(), pos.toImmutable()))
removed.add(pos.toImmutable());
BlockPos oldPos = triplet.getRight();
if (deleted.add(oldPos))
deleted.removeIf(a -> a.equals(pos));
pos.move(facing.getOpposite());
}
deleted.forEach(delete -> {
if (world.getTileEntity(delete) != null)
world.removeTileEntity(delete);
world.setBlockToAir(delete);
});
break;
} else if (!pushed.isEmpty())
pushed.remove(pushed.size() - 1);
pos.move(facing.getOpposite());
}
ProfilerHelper.flagSection("[Dilaton] Block drops");
removed.forEach(p -> {
IBlockState state = world.getBlockState(p);
float chance = state.getBlock() instanceof BlockSnow ? -1.0F : 1.0F;
state.getBlock().dropBlockAsItemWithChance(world, p, state, chance, 0);
world.setBlockToAir(p);
});
ProfilerHelper.end();
ProfilerHelper.flagSection("[Dilaton] Place extension");
if (pos.equals(getPos().offset(facing.getOpposite()))) {
if (isActiveLazy())
world.setBlockState(getPos(), world.getBlockState(getPos()).withProperty(State.ACTIVE, false));
} else if (!pos.equals(getPos())) {
if (!isActiveLazy())
world.setBlockState(getPos(), world.getBlockState(getPos()).withProperty(State.ACTIVE, true));
IBlockState extension = ModBlocks.DILATON_EXTENSION.getDefaultState().withProperty(BlockDirectional.FACING, facing);
world.setBlockState(pos, extension);
}
}
}
use of org.apache.commons.lang3.Range in project incubator-gobblin by apache.
the class GoogleWebmasterDataFetcherImpl method getPages.
/**
* Get all pages in an async mode.
*/
private Collection<String> getPages(String startDate, String endDate, List<Dimension> dimensions, ApiDimensionFilter countryFilter, Queue<Pair<String, FilterOperator>> toProcess, int rowLimit) throws IOException {
String country = GoogleWebmasterFilter.countryFilterToString(countryFilter);
ConcurrentLinkedDeque<String> allPages = new ConcurrentLinkedDeque<>();
int r = 0;
while (r <= GET_PAGES_RETRIES) {
++r;
log.info(String.format("Get pages at round %d with size %d.", r, toProcess.size()));
ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound = new ConcurrentLinkedDeque<>();
ExecutorService es = Executors.newFixedThreadPool(10, ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName())));
while (!toProcess.isEmpty()) {
submitJob(toProcess.poll(), countryFilter, startDate, endDate, dimensions, es, allPages, nextRound, rowLimit);
}
// wait for jobs to finish and start next round if necessary.
try {
es.shutdown();
boolean terminated = es.awaitTermination(5, TimeUnit.MINUTES);
if (!terminated) {
es.shutdownNow();
log.warn(String.format("Timed out while getting all pages for country-%s at round %d. Next round now has size %d.", country, r, nextRound.size()));
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (nextRound.isEmpty()) {
break;
}
toProcess = nextRound;
}
if (r == GET_PAGES_RETRIES) {
throw new RuntimeException(String.format("Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.", GET_PAGES_RETRIES, startDate, endDate, country));
}
return allPages;
}
use of org.apache.commons.lang3.Range in project drbookings by DrBookings.
the class StatsViewController method updateUI.
private void updateUI(final BookingsByOrigin<BookingEntry> bookings, final Range<LocalDate> dateRange) {
if (logger.isDebugEnabled()) {
logger.debug("Statistics for\n" + BookingEntries.toBookings(bookings.getAllBookings()).stream().map(i -> i.toString()).collect(Collectors.joining("\n")));
}
final float allAllNigths = BookingEntries.countNights(bookings, false);
final NavigableSet<LocalDate> allDates = bookings.getAllBookings(true).stream().map(b -> b.getDate()).collect(Collectors.toCollection(TreeSet::new));
long monthCount = TemporalQueries.countOccurrences(allDates, SettingsManager.getInstance().getFixCostsPaymentDay());
if (logger.isDebugEnabled()) {
logger.debug("Month count: " + monthCount);
}
if (monthCount < 1) {
monthCount = 1;
if (logger.isDebugEnabled()) {
logger.debug("Month count (corrected): " + monthCount);
}
}
final float additionalCosts = SettingsManager.getInstance().getAdditionalCosts() * monthCount;
final float numberOfRooms = SettingsManager.getInstance().getNumberOfRooms();
final float totalAdditionalCosts = additionalCosts * numberOfRooms;
if (logger.isDebugEnabled()) {
logger.debug("Fix costs total: " + totalAdditionalCosts);
}
for (final Entry<BookingOrigin, Collection<BookingEntry>> e : bookings.getMap().entrySet()) {
final Collection<? extends BookingEntry> bookingsFilteredByPaymentDate = e.getValue().stream().filter(new PaymentDateFilter(dateRange)).collect(Collectors.toList());
final Collection<? extends BookingEntry> bookingsFilteredByCleaningDate = e.getValue().stream().filter(new CleaningDateFilter(dateRange)).collect(Collectors.toList());
final int numberOfAllBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()), false);
final int numberOfPayedBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()), false);
final int numberOfAllNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(e.getValue()), false);
final int numberOfPayedNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(bookingsFilteredByPaymentDate), false);
final float percentage;
if (StringUtils.isBlank(e.getKey().getName())) {
percentage = 0;
} else {
percentage = numberOfAllNights / allAllNigths * 100f;
}
if (logger.isDebugEnabled()) {
logger.debug(e.getKey() + " percentage of all nights: " + percentage);
}
final double relativeFixCosts = totalAdditionalCosts * percentage / 100;
if (logger.isDebugEnabled()) {
logger.debug(e.getKey() + " relative fix costs " + relativeFixCosts);
}
if (logger.isDebugEnabled()) {
logger.debug(e.getKey() + " number of bookings (all/payed): " + numberOfAllBookings + "/" + numberOfPayedBookings);
}
if (logger.isDebugEnabled()) {
logger.debug(e.getKey() + ": Number of nights (all/payed): " + numberOfAllNights + "/" + numberOfPayedNights);
}
if (logger.isDebugEnabled()) {
Set<Guest> set = e.getValue().stream().map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(LinkedHashSet::new));
List<Guest> list = e.getValue().stream().filter(b -> !b.isCheckOut()).map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
StringBuilder sb = new StringBuilder(e.getKey() + " guest and nights (all):");
int cnt = 1;
int cnt2 = 0;
for (final Guest guest : set) {
final int cnt3 = Collections.frequency(list, guest);
sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
cnt2 += cnt3;
}
sb.append(String.format("%n%24s%4d", "Total", cnt2));
logger.debug(sb.toString());
set = bookingsFilteredByPaymentDate.stream().map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(LinkedHashSet::new));
list = bookingsFilteredByPaymentDate.stream().filter(b -> !b.isCheckOut()).map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
sb = new StringBuilder(e.getKey() + " guest and nights (payed):");
cnt = 1;
cnt2 = 0;
for (final Guest guest : set) {
final int cnt3 = Collections.frequency(list, guest);
sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
cnt2 += cnt3;
}
sb.append(String.format("%n%24s%4d", "Total", cnt2));
logger.debug(sb.toString());
}
final StatisticsTableBean b = StatisticsTableBean.build(e.getKey().getName(), bookingsFilteredByPaymentDate);
StatisticsTableBean.applyCleaningStuff(b, bookingsFilteredByCleaningDate);
b.setFixCosts((float) relativeFixCosts);
b.setNightsPercent(percentage);
b.setNumberOfPayedNights(numberOfPayedNights);
b.setNumberOfAllNights(numberOfAllNights);
b.setNumberOfPayedBookings(numberOfPayedBookings);
b.setNumberOfAllBookings(numberOfAllBookings);
data.add(b);
}
// add a total row
final float relativeFixCosts = totalAdditionalCosts;
final StatisticsTableBean b = StatisticsTableBean.buildSum(data);
b.setFixCosts(relativeFixCosts);
b.setNightsPercent(100);
data.add(b);
}
use of org.apache.commons.lang3.Range in project incubator-pulsar by apache.
the class NamespaceBundleFactory method splitBundles.
/**
* Fetches {@link NamespaceBundles} from cache for a given namespace. finds target bundle, split into numBundles and
* returns new {@link NamespaceBundles} with newly split bundles into it.
*
* @param targetBundle
* {@link NamespaceBundle} needs to be split
* @param numBundles
* split into numBundles
* @return List of split {@link NamespaceBundle} and {@link NamespaceBundles} that contains final bundles including
* split bundles for a given namespace
*/
public Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles(NamespaceBundle targetBundle, int numBundles) {
checkArgument(canSplitBundle(targetBundle), "%s bundle can't be split further", targetBundle);
checkNotNull(targetBundle, "can't split null bundle");
checkNotNull(targetBundle.getNamespaceObject(), "namespace must be present");
NamespaceName nsname = targetBundle.getNamespaceObject();
NamespaceBundles sourceBundle = bundlesCache.synchronous().get(nsname);
final int lastIndex = sourceBundle.partitions.length - 1;
final long[] partitions = new long[sourceBundle.partitions.length + (numBundles - 1)];
int pos = 0;
int splitPartition = -1;
final Range<Long> range = targetBundle.getKeyRange();
for (int i = 0; i < lastIndex; i++) {
if (sourceBundle.partitions[i] == range.lowerEndpoint() && (range.upperEndpoint() == sourceBundle.partitions[i + 1])) {
splitPartition = i;
Long maxVal = sourceBundle.partitions[i + 1];
Long minVal = sourceBundle.partitions[i];
Long segSize = (maxVal - minVal) / numBundles;
partitions[pos++] = minVal;
Long curPartition = minVal + segSize;
for (int j = 0; j < numBundles - 1; j++) {
partitions[pos++] = curPartition;
curPartition += segSize;
}
} else {
partitions[pos++] = sourceBundle.partitions[i];
}
}
partitions[pos] = sourceBundle.partitions[lastIndex];
if (splitPartition != -1) {
// keep version of sourceBundle
NamespaceBundles splittedNsBundles = new NamespaceBundles(nsname, partitions, this, sourceBundle.getVersion());
List<NamespaceBundle> splittedBundles = splittedNsBundles.getBundles().subList(splitPartition, (splitPartition + numBundles));
return new ImmutablePair<NamespaceBundles, List<NamespaceBundle>>(splittedNsBundles, splittedBundles);
}
return null;
}
use of org.apache.commons.lang3.Range in project sqlg by pietermartin.
the class SchemaTableTree method constructOuterOrderByClause.
private static String constructOuterOrderByClause(SqlgGraph sqlgGraph, List<LinkedList<SchemaTableTree>> subQueryLinkedLists) {
String result = "";
int countOuter = 1;
// last table list with order as last step wins
int winningOrder = 0;
for (LinkedList<SchemaTableTree> subQueryLinkedList : subQueryLinkedLists) {
if (!subQueryLinkedList.isEmpty()) {
SchemaTableTree schemaTableTree = subQueryLinkedList.peekLast();
if (!schemaTableTree.getDbComparators().isEmpty()) {
winningOrder = countOuter;
}
}
countOuter++;
}
countOuter = 1;
// construct the order by clause for the comparators
MutableBoolean mutableOrderBy = new MutableBoolean(false);
for (LinkedList<SchemaTableTree> subQueryLinkedList : subQueryLinkedLists) {
if (!subQueryLinkedList.isEmpty()) {
SchemaTableTree schemaTableTree = subQueryLinkedList.peekLast();
if (countOuter == winningOrder) {
result += schemaTableTree.toOrderByClause(sqlgGraph, mutableOrderBy, countOuter);
}
// support range without order
result += schemaTableTree.toRangeClause(sqlgGraph, mutableOrderBy);
}
countOuter++;
}
return result;
}
Aggregations