List of usage examples for com.google.common.collect Range closedOpen
public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper)
From source file:com.google.googlejavaformat.java.JavaInput.java
/** * Convert from an offset and length flag pair to a token range. * * @param offset the {@code 0}-based offset in characters * @param length the length in characters * @return the {@code 0}-based {@link Range} of tokens * @throws FormatterException/*from www. ja va 2s . com*/ */ Range<Integer> characterRangeToTokenRange(int offset, int length) throws FormatterException { int requiredLength = offset + length; if (requiredLength > text.length()) { throw new FormatterException(String.format( "error: invalid length %d, offset + length (%d) is outside the file", length, requiredLength)); } if (length < 0) { return EMPTY_RANGE; } if (length == 0) { // 0 stands for "format the line under the cursor" length = 1; } ImmutableCollection<Token> enclosed = getPositionTokenMap() .subRangeMap(Range.closedOpen(offset, offset + length)).asMapOfRanges().values(); if (enclosed.isEmpty()) { return EMPTY_RANGE; } return Range.closedOpen(enclosed.iterator().next().getTok().getIndex(), getLast(enclosed).getTok().getIndex() + 1); }
From source file:org.sosy_lab.cpachecker.cfa.ast.c.CInitializers.java
/** * Handle the case when the current subobject that will be initialized next * is an array./*www .j a v a2s.co m*/ * This method only prepares the two stacks by pushing one object on both * of them (for the next element to be initialized, and the iterator for the * remainder of the elements). * @param currentSubobject The struct/union to be initialized * @param startIndex The index of the first element to be initialized * @param arrayType The type of currentSubobject * @param currentSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)} * @param nextSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)} */ private static boolean handleInitializerForArray(final CExpression currentSubobject, final long startIndex, final CArrayType arrayType, final Deque<CExpression> currentSubobjects, final Deque<Iterator<CExpression>> nextSubobjects, final FileLocation loc, final CFAEdge edge, final CDesignator designator) throws UnrecognizedCCodeException { Range<Long> arrayIndices; if (arrayType.getLength() instanceof CIntegerLiteralExpression) { // fixed-size array BigInteger size = ((CIntegerLiteralExpression) arrayType.getLength()).getValue(); if (!BigInteger.valueOf(size.longValue()).equals(size)) { throw new UnrecognizedCCodeException( "Size of type " + arrayType + " is too large to initialize explicitly", edge, designator); } // TODO use DiscreteDomain.bigintegers() when it's available. arrayIndices = Range.closedOpen(startIndex, size.longValue()); } else if (arrayType.getLength() == null) { // variable-length array, this array goes until there are no more initializer values arrayIndices = Range.atLeast(startIndex); } else { throw new UnrecognizedCCodeException( "Cannot initialize arrays with variable modified type like " + arrayType, edge, designator); } if (arrayIndices.isEmpty()) { return false; } final CType elementType = arrayType.getType(); Set<Long> indexSet = ContiguousSet.create(arrayIndices, DiscreteDomain.longs()); Iterator<CExpression> elements = from(indexSet).transform(new Function<Long, CExpression>() { @Override public CExpression apply(Long pInput) { CExpression index = new CIntegerLiteralExpression(loc, CNumericTypes.INT, BigInteger.valueOf(pInput.longValue())); return new CArraySubscriptExpression(loc, elementType, currentSubobject, index); } }).iterator(); CExpression firstElement = elements.next(); currentSubobjects.push(firstElement); nextSubobjects.push(elements); return true; }
From source file:com.github.rinde.rinsim.central.arrays.ArraysSolverValidator.java
/** * Validates the {@link SolutionObject}s that are produced by a * {@link MultiVehicleArraysSolver}. If any of the {@link SolutionObject}s is * infeasible, an {@link IllegalArgumentException} is thrown. * @param sols The {@link SolutionObject}s that are validated. * @param travelTime Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * ./*from w w w . j av a 2 s . c o m*/ * @param releaseDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param dueDates Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param servicePairs Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param serviceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param vehicleTravelTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param inventories Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param remainingServiceTimes Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @param currentDestinations Parameter as specified by * {@link MultiVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], int[][], int[][], int[], int[], SolutionObject[])} * . * @return The solution as is supplied, used for method chaining. */ public static SolutionObject[] validateOutputs(SolutionObject[] sols, int[][] travelTime, int[] releaseDates, int[] dueDates, int[][] servicePairs, int[] serviceTimes, int[][] vehicleTravelTimes, int[][] inventories, int[] remainingServiceTimes, int[] currentDestinations) { final int n = travelTime.length; final ImmutableSet.Builder<Integer> routeSetBuilder = ImmutableSet.builder(); int visitedLocations = 0; for (final SolutionObject sol : sols) { routeSetBuilder.addAll(toSet(sol.route)); visitedLocations += sol.route.length - 2; } final Set<Integer> routeSet = routeSetBuilder.build(); final Set<Integer> locationSet = ContiguousSet.create(Range.closedOpen(0, travelTime.length), DiscreteDomain.integers()); checkArgument(visitedLocations == n - 2, "The number of visits in routes should equal the number of locations, " + "expected: %s, observed: %s.", n - 2, visitedLocations); // checks duplicates and missing locations checkArgument(routeSet.size() == n, "Every location should appear exactly once in one route. Missing " + "location: %s.", Sets.difference(locationSet, routeSet)); // checks for completeness of tour checkArgument(routeSet.equals(locationSet), "Not all locations are serviced, there is probably a non-existing " + "location in the route. Set difference: %s.", Sets.difference(routeSet, locationSet)); final ImmutableMultimap.Builder<Integer, Integer> inventoryBuilder = ImmutableMultimap.builder(); for (int i = 0; i < inventories.length; i++) { inventoryBuilder.put(inventories[i][0], inventories[i][1]); } final Multimap<Integer, Integer> inventoryMap = inventoryBuilder.build(); for (int v = 0; v < sols.length; v++) { final SolutionObject sol = sols[v]; /* * CHECK SERVICE SEQUENCE */ checkArgument(sol.route[0] == 0, "The route should always start with the vehicle start location: 0, " + "actual:%s.", sol.route[0]); checkArgument(sol.route[sol.route.length - 1] == n - 1, "The route should always finish with the depot."); if (currentDestinations[v] != 0) { checkArgument(sol.route[1] == currentDestinations[v], "Vehicle %s has a current destination %s, as such this must be the " + "first point to visit (at index 1). The route: %s.", v, currentDestinations[v], Arrays.toString(sol.route)); } final Set<Integer> locs = ImmutableSet.copyOf(Ints.asList(sol.route)); final Collection<Integer> inventory = inventoryMap.get(v); for (final Integer i : inventory) { checkArgument(locs.contains(i), "Every location in the inventory of a vehicle should occur in its " + "route, route for vehicle %s does not contain location %s.", v, i); } // check service pairs ordering, pickups should be visited before // their corresponding delivery location final Map<Integer, Integer> pairs = newHashMap(); for (int i = 0; i < servicePairs.length; i++) { pairs.put(servicePairs[i][0], servicePairs[i][1]); } final Set<Integer> seen = newHashSet(); final Set<Integer> set = newHashSet(Ints.asList(sol.route)); for (int i = 1; i < sol.route.length - 1; i++) { if (pairs.containsKey(sol.route[i])) { checkArgument(!seen.contains(pairs.get(sol.route[i])), "Pickups should be visited before their corresponding deliveries." + " Location %s should be visited after location %s.", pairs.get(sol.route[i]), sol.route[i]); checkArgument(set.contains(pairs.get(sol.route[i])), "Vehicle %s: this route should contain both the pickup and " + "delivery location, found %s, didn't find %s.", v, sol.route[i], pairs.get(sol.route[i])); } seen.add(sol.route[i]); } /* * CHECK ARRIVAL TIMES */ checkArgument(sol.arrivalTimes.length == sol.route.length, "Number of arrival times should equal number of locations."); checkArgument(sol.arrivalTimes[0] == 0, "The first arrival time should be 0, was %s.", sol.arrivalTimes[0]); // check feasibility final int[] minArrivalTimes = ArraysSolvers.computeArrivalTimes(sol.route, travelTime, remainingServiceTimes[v], vehicleTravelTimes[v], serviceTimes, releaseDates); for (int i = 1; i < sol.route.length; i++) { checkArgument(sol.arrivalTimes[i] >= minArrivalTimes[i], "Vehicle %s, route index %s, arrivalTime (%s) needs to be greater " + "or equal to minArrivalTime (%s).", v, i, sol.arrivalTimes[i], minArrivalTimes[i]); } /* * CHECK OBJECTIVE VALUE */ // sum travel time final int totalTravelTime = ArraysSolvers.computeTotalTravelTime(sol.route, travelTime, vehicleTravelTimes[v]); // sum tardiness final int tardiness = ArraysSolvers.computeRouteTardiness(sol.route, sol.arrivalTimes, serviceTimes, dueDates, remainingServiceTimes[v]); checkArgument(sol.objectiveValue == totalTravelTime + tardiness, "Vehicle %s: incorrect objective value (%s), it should be travel " + "time + tardiness = %s + %s = %s.", v, sol.objectiveValue, totalTravelTime, tardiness, totalTravelTime + tardiness); } return sols; }
From source file:org.apache.bookkeeper.mledger.impl.ManagedCursorImpl.java
@Override public long getNumberOfEntries() { return getNumberOfEntries(Range.closedOpen(readPosition, ledger.getLastPosition().getNext())); }
From source file:com.google.cloud.genomics.cba.GGAnnotateVariants.java
/** * <h1>This function first send a request to Google Genomics to receive all * variant annotations (variantAnnotationSetIds), and after receiving the * information, it creates and return back a ListMultimap that contains all * the overlapped annotations plus their positions. * //from w w w .j av a 2s . com * @param genomics * Genomics * @param request * StreamVariantsRequest * @return annotationMap ListMultimap<Range<Long>, Annotation> */ private ListMultimap<Range<Long>, Annotation> retrieveVariantAnnotations(Genomics genomics, StreamVariantsRequest request) { Stopwatch stopwatch = Stopwatch.createStarted(); ListMultimap<Range<Long>, Annotation> annotationMap = ArrayListMultimap.create(); Iterable<Annotation> annotationIter = Paginator.Annotations .create(genomics, ShardBoundary.Requirement.OVERLAPS) .search(new SearchAnnotationsRequest().setAnnotationSetIds(variantAnnotationSetIds) .setReferenceName(canonicalizeRefName(request.getReferenceName())) .setStart(request.getStart()).setEnd(request.getEnd())); for (Annotation annotation : annotationIter) { long start = 0; if (annotation.getStart() != null) { start = annotation.getStart(); if (annotation.getStart() == 126310) LOG.info("HERE is the annotation: " + annotation.toString() + ") "); } annotationMap.put(Range.closedOpen(start, annotation.getEnd()), annotation); } LOG.info(String.format("read %d variant annotations in %s (%.2f / s)", annotationMap.size(), stopwatch, (double) annotationMap.size() / stopwatch.elapsed(TimeUnit.SECONDS))); return annotationMap; }
From source file:org.eclipse.fx.ui.controls.styledtext.internal.ContentView.java
void updateNodesNow(com.google.common.collect.RangeSet<Integer> rs) { RangeSet<Integer> subRangeSet = rs.subRangeSet(getVisibleLines()) .subRangeSet(Range.closedOpen(Integer.valueOf(0), Integer.valueOf(getNumberOfLines()))); subRangeSet.asRanges().forEach(r -> { ContiguousSet.create(r, DiscreteDomain.integers()).forEach(index -> { getLineLayer().updateNode(index.intValue()); // StyledTextLine m = this.model.get(index); // lineLayer.updateNode(m); });// www .ja v a2 s .c om }); }
From source file:org.eclipse.fx.ui.controls.styledtext.internal.ContentView.java
void releaseNodesNow(com.google.common.collect.RangeSet<Integer> rs) { RangeSet<Integer> subRangeSet = rs .subRangeSet(Range.closedOpen(Integer.valueOf(0), Integer.valueOf(getNumberOfLines()))); subRangeSet.asRanges().forEach(r -> { ContiguousSet.create(r, DiscreteDomain.integers()).forEach(index -> { getLineLayer().releaseNode(index.intValue()); // StyledTextLine m = this.model.get(index); // lineLayer.releaseNode(m); });//from w ww .j a va2s . c o m }); }
From source file:org.apache.bookkeeper.mledger.impl.ManagedCursorImpl.java
protected void internalResetCursor(final PositionImpl newPosition, AsyncCallbacks.ResetCursorCallback resetCursorCallback) { log.info("[{}] Initiate reset position to {} on cursor {}", ledger.getName(), newPosition, name); synchronized (pendingMarkDeleteOps) { if (!RESET_CURSOR_IN_PROGRESS_UPDATER.compareAndSet(this, FALSE, TRUE)) { log.error("[{}] reset requested - position [{}], previous reset in progress - cursor {}", ledger.getName(), newPosition, name); resetCursorCallback.resetFailed(new ManagedLedgerException.ConcurrentFindCursorPositionException( "reset already in progress"), newPosition); }/*from w w w .j a va 2s . com*/ } final AsyncCallbacks.ResetCursorCallback callback = resetCursorCallback; VoidCallback finalCallback = new VoidCallback() { @Override public void operationComplete() { // modify mark delete and read position since we are able to persist new position for cursor lock.writeLock().lock(); try { PositionImpl newMarkDeletePosition = ledger.getPreviousPosition(newPosition); if (markDeletePosition.compareTo(newMarkDeletePosition) >= 0) { messagesConsumedCounter -= getNumberOfEntries( Range.closedOpen(newMarkDeletePosition, markDeletePosition)); } else { messagesConsumedCounter += getNumberOfEntries( Range.closedOpen(markDeletePosition, newMarkDeletePosition)); } markDeletePosition = newMarkDeletePosition; individualDeletedMessages.clear(); PositionImpl oldReadPosition = readPosition; if (oldReadPosition.compareTo(newPosition) >= 0) { log.info("[{}] reset position to {} before current read position {} on cursor {}", ledger.getName(), newPosition, oldReadPosition, name); } else { log.info("[{}] reset position to {} skipping from current read position {} on cursor {}", ledger.getName(), newPosition, oldReadPosition, name); } readPosition = newPosition; } finally { lock.writeLock().unlock(); } synchronized (pendingMarkDeleteOps) { pendingMarkDeleteOps.clear(); if (!RESET_CURSOR_IN_PROGRESS_UPDATER.compareAndSet(ManagedCursorImpl.this, TRUE, FALSE)) { log.error("[{}] expected reset position [{}], but another reset in progress on cursor {}", ledger.getName(), newPosition, name); } } callback.resetComplete(newPosition); } @Override public void operationFailed(ManagedLedgerException exception) { synchronized (pendingMarkDeleteOps) { if (!RESET_CURSOR_IN_PROGRESS_UPDATER.compareAndSet(ManagedCursorImpl.this, TRUE, FALSE)) { log.error("[{}] expected reset position [{}], but another reset in progress on cursor {}", ledger.getName(), newPosition, name); } } callback.resetFailed( new ManagedLedgerException.InvalidCursorPositionException( "unable to persist position for cursor reset " + newPosition.toString()), newPosition); } }; internalAsyncMarkDelete(newPosition, new MarkDeleteCallback() { @Override public void markDeleteComplete(Object ctx) { finalCallback.operationComplete(); } @Override public void markDeleteFailed(ManagedLedgerException exception, Object ctx) { finalCallback.operationFailed(exception); } }, null); }
From source file:edu.mit.streamjit.impl.compiler.Compiler.java
/** * Generates the corework* methods, which contain the steady-state code for * each core. (The buffers are assumed to be already prepared.) *///from w w w. j a v a 2 s. c o m private void generateCoreCode() { List<StreamNode> nodes = new ArrayList<>(ImmutableSet.copyOf(streamNodes.values())); Collections.sort(nodes, new Comparator<StreamNode>() { @Override public int compare(StreamNode o1, StreamNode o2) { return Integer.compare(o1.id, o2.id); } }); //For each core, a list of the nodework-iteration pairs allocated to //that core. List<List<Pair<Method, Range<Integer>>>> allocations = new ArrayList<>(maxNumCores); for (int i = 0; i < maxNumCores; ++i) allocations.add(new ArrayList<Pair<Method, Range<Integer>>>()); for (StreamNode node : nodes) { int iterations = schedule.getExecutions(node); int i = 0; for (int core = 0; core < allocations.size() && i < iterations; ++core) { String name = String.format("node%dcore%diter", node.id, core); IntParameter parameter = config.getParameter(name, IntParameter.class); if (parameter == null || parameter.getValue() == 0) continue; //If the node is stateful, we must put all allocations on the //same core. Arbitrarily pick the first core with an allocation. //If no cores have an allocation, int allocation = node.isStateful() ? iterations : Math.min(parameter.getValue(), iterations - i); allocations.get(core).add(new Pair<>(node.workMethod, Range.closedOpen(i, i + allocation))); i += allocation; } //If we have iterations left over not assigned to a core, //arbitrarily put them on core 0. if (i < iterations) allocations.get(0).add(new Pair<>(node.workMethod, Range.closedOpen(i, iterations))); } //For each core with allocations, make a corework method. for (int core = 0; core < allocations.size(); ++core) { List<Pair<Method, Range<Integer>>> stuff = allocations.get(core); if (stuff.isEmpty()) continue; Method coreCode = new Method("corework" + core, module.types().getMethodType(void.class), EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), blobKlass); BasicBlock previousBlock = new BasicBlock(module, "entry"); coreCode.basicBlocks().add(previousBlock); for (Pair<Method, Range<Integer>> allocation : stuff) { BasicBlock loop = makeCallLoop(allocation.first, allocation.second.lowerEndpoint(), allocation.second.upperEndpoint(), previousBlock, allocation.first.getName()); coreCode.basicBlocks().add(loop); if (previousBlock.getTerminator() == null) previousBlock.instructions().add(new JumpInst(loop)); else ((BranchInst) previousBlock.getTerminator()).setOperand(3, loop); previousBlock = loop; } BasicBlock exit = new BasicBlock(module, "exit"); exit.instructions().add(new ReturnInst(module.types().getVoidType())); coreCode.basicBlocks().add(exit); //We only generate corework for cores with allocations, so we should //always have an allocation above us. assert previousBlock.getTerminator() instanceof BranchInst : previousBlock.getTerminator(); ((BranchInst) previousBlock.getTerminator()).setOperand(3, exit); } }
From source file:edu.mit.streamjit.impl.compiler2.Compiler2.java
private void createInitCode() { ImmutableMap<Actor, ImmutableList<IndexFunction>> indexFxnBackup = adjustOutputIndexFunctions( Storage::initialDataIndices); this.initStorage = createStorage(false, new PeekPokeStorageFactory(InternalArrayConcreteStorage.initFactory(initSchedule))); initReadInstructions.add(new InitDataReadInstruction(initStorage, initialStateDataMap)); ImmutableMap<Storage, ConcreteStorage> internalStorage = createStorage(true, InternalArrayConcreteStorage.initFactory(initSchedule)); IndexFunctionTransformer ift = new IdentityIndexFunctionTransformer(); ImmutableTable.Builder<Actor, Integer, IndexFunctionTransformer> inputTransformers = ImmutableTable .builder(), outputTransformers = ImmutableTable.builder(); for (Actor a : Iterables.filter(actors, WorkerActor.class)) { for (int i = 0; i < a.inputs().size(); ++i) inputTransformers.put(a, i, ift); for (int i = 0; i < a.outputs().size(); ++i) outputTransformers.put(a, i, ift); }/*ww w. ja va 2 s .co m*/ ImmutableMap.Builder<ActorGroup, Integer> unrollFactors = ImmutableMap.builder(); for (ActorGroup g : groups) unrollFactors.put(g, 1); /** * During init, all (nontoken) groups are assigned to the same Core in * topological order (via the ordering on ActorGroups). At the same * time we build the token init schedule information required by the * blob host. */ Core initCore = new Core(CollectionUtils.union(initStorage, internalStorage), (table, wa) -> Combinators.lookupswitch(table), unrollFactors.build(), inputTransformers.build(), outputTransformers.build()); for (ActorGroup g : groups) if (!g.isTokenGroup()) initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g))); else { assert g.actors().size() == 1; TokenActor ta = (TokenActor) g.actors().iterator().next(); assert g.schedule().get(ta) == 1; ConcreteStorage storage = initStorage .get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs())); int executions = initSchedule.get(g); if (ta.isInput()) initReadInstructions.add(makeReadInstruction(ta, storage, executions)); else initWriteInstructions.add(makeWriteInstruction(ta, storage, executions)); } this.initCode = initCore.code(); restoreOutputIndexFunctions(indexFxnBackup); }