Example usage for java.util.stream IntStream range

List of usage examples for java.util.stream IntStream range

Introduction

In this page you can find the example usage for java.util.stream IntStream range.

Prototype

public static IntStream range(int startInclusive, int endExclusive) 

Source Link

Document

Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1 .

Usage

From source file:de.fosd.jdime.Main.java

/**
 * Returns a <code>File</code> (possibly <code>f</code>) that does not exist in the parent directory of
 * <code>f</code>. If <code>f</code> exists an increasing number is appended to the name of <code>f</code> until
 * a <code>File</code> is found that does not exist.
 *
 * @param f//  www  . j a v  a 2  s .c o m
 *         the <code>File</code> to find a non existent version of
 * @return a <code>File</code> in the parent directory of <code>f</code> that does not exist
 */
private static File findNonExistent(File f) {

    if (!f.exists()) {
        return f;
    }

    String fullName = f.getName();
    String name;
    String extension;

    int pos = fullName.lastIndexOf('.');

    if (pos != -1) {
        name = fullName.substring(0, pos);
        extension = fullName.substring(pos, fullName.length());
    } else {
        name = fullName;
        extension = "";
    }

    File parent = f.getParentFile();

    Stream<File> files = IntStream.range(0, Integer.MAX_VALUE).mapToObj(v -> {
        String fileName = String.format("%s_%d%s", name, v, extension);
        return new File(parent, fileName);
    });

    File nextFree = files.filter(file -> !file.exists()).findFirst()
            .orElseThrow(() -> new RuntimeException("Can not find a file that does not exist."));

    return nextFree;
}

From source file:delfos.rs.trustbased.WeightedGraph.java

public double[][] asMatrixUnboxed() {

    final List<Node> nodesSorted = nodesSortingForMatrix();

    double[][] matrix = new double[nodesSorted.size()][nodesSorted.size()];

    IntStream.range(0, nodesSorted.size()).parallel().boxed().forEach(indexRow -> {
        Node node1 = nodesSorted.get(indexRow);

        IntStream.range(0, nodesSorted.size()).parallel().boxed().forEach(indexColumn -> {
            Node node2 = nodesSorted.get(indexColumn);
            double value = connectionWeight(node1, node2).orElse(0.0);
            matrix[indexRow][indexColumn] = value;
        });//from   w  w  w.  j av  a 2 s .  c  o  m
    });

    validateWeightMatrix(matrix);
    return matrix;
}

From source file:com.devicehive.service.DeviceNotificationServiceTest.java

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void testFindWithResponse() throws Exception {
    final List<String> guids = IntStream.range(0, 5).mapToObj(i -> UUID.randomUUID().toString())
            .collect(Collectors.toList());
    final Date timestampSt = new Date();
    final Date timestampEnd = new Date();
    final String parameters = "{\"param1\":\"value1\",\"param2\":\"value2\"}";

    final Set<String> guidsForSearch = new HashSet<>(Arrays.asList(guids.get(0), guids.get(2), guids.get(3)));

    // return response for any request
    Map<String, DeviceNotification> notificationMap = guidsForSearch.stream()
            .collect(Collectors.toMap(Function.identity(), guid -> {
                DeviceNotification notification = new DeviceNotification();
                notification.setId(System.nanoTime());
                notification.setDeviceGuid(guid);
                notification.setNotification(RandomStringUtils.randomAlphabetic(10));
                notification.setTimestamp(new Date());
                notification.setParameters(new JsonStringWrapper(parameters));
                return notification;
            }));/*from  www  .  j  a  va2  s .c o  m*/

    when(requestHandler.handle(any(Request.class))).then(invocation -> {
        Request request = invocation.getArgumentAt(0, Request.class);
        String guid = request.getBody().cast(NotificationSearchRequest.class).getGuid();
        return Response.newBuilder()
                .withBody(new NotificationSearchResponse(Collections.singletonList(notificationMap.get(guid))))
                .buildSuccess();
    });

    notificationService.find(guidsForSearch, Collections.emptySet(), timestampSt, timestampEnd)
            .thenAccept(notifications -> {
                assertEquals(3, notifications.size());
                assertEquals(new HashSet<>(notificationMap.values()), new HashSet<>(notifications)); // using HashSet to ignore order
            }).exceptionally(ex -> {
                fail(ex.toString());
                return null;
            }).get(30, TimeUnit.SECONDS);

    verify(requestHandler, times(3)).handle(argument.capture());
}

From source file:nu.yona.server.device.service.DeviceService.java

private int findFirstFreeDeviceIndex(User userEntity) {
    Set<Integer> deviceIndexes = userEntity.getDevices().stream().map(UserDevice::getDeviceAnonymized)
            .map(DeviceAnonymized::getDeviceIndex).collect(Collectors.toSet());
    return IntStream.range(0, deviceIndexes.size() + 1).filter(i -> !deviceIndexes.contains(i)).findFirst()
            .orElseThrow(() -> new IllegalStateException("Should always find a nonexisting index"));
}

From source file:com.offbynull.coroutines.instrumenter.ContinuationGenerators.java

public static InsnList entryPointLoader(MethodAttributes attrs) {
    Validate.notNull(attrs);//w  ww  .j a  v a 2  s .  c  o  m

    Variable contArg = attrs.getCoreVariables().getContinuationArgVar();
    Variable methodStateVar = attrs.getCoreVariables().getMethodStateVar();
    Variable storageContainerVar = attrs.getStorageContainerVariables().getContainerVar();

    LockVariables lockVars = attrs.getLockVariables();
    Variable lockStateVar = lockVars.getLockStateVar();

    int numOfContinuationPoints = attrs.getContinuationPoints().size();

    MarkerType markerType = attrs.getSettings().getMarkerType();
    String dbgSig = getLogPrefix(attrs);

    LabelNode startOfMethodLabelNode = new LabelNode();
    return merge(tableSwitch(
            merge(debugMarker(markerType, dbgSig + "Getting state for switch"),
                    call(CONTINUATION_GETMODE_METHOD, loadVar(contArg))),
            merge(debugMarker(markerType, dbgSig + "Unrecognized state"),
                    throwRuntimeException("Unrecognized state")),
            0, merge(debugMarker(markerType, dbgSig + "Case 0 -- Fresh invocation"),
                    // create lockstate if method actually has monitorenter/exit in it (var != null if this were the case)
                    mergeIf(lockStateVar != null,
                            () -> new Object[] { debugMarker(markerType, "Creating monitors container"),
                                    createMonitorContainer(markerType, lockVars), }),
                    debugMarker(markerType, dbgSig + "Jump to start of method point"),
                    jumpTo(startOfMethodLabelNode)),
            merge(debugMarker(markerType, dbgSig + "Case 1 -- Saving state"),
                    throwRuntimeException("Unexpected state (saving not allowed at this point)")),
            merge(debugMarker(markerType, dbgSig + "Case 2 -- Loading state"),
                    debugMarker(markerType, dbgSig + "Loading method state"),
                    call(CONTINUATION_LOADNEXTMETHODSTATE_METHOD, loadVar(contArg)), saveVar(methodStateVar),
                    debugMarker(markerType, dbgSig + "Getting method state data"),
                    call(METHODSTATE_GETDATA_METHOD, loadVar(methodStateVar)), saveVar(storageContainerVar),
                    // get lockstate if method actually has monitorenter/exit in it (var != null if this were the case)
                    mergeIf(lockStateVar != null,
                            () -> new Object[] {
                                    debugMarker(markerType,
                                            dbgSig + "Method has synch points, so loading lockstate as well"),
                                    call(METHODSTATE_GETLOCKSTATE_METHOD, loadVar(methodStateVar)),
                                    saveVar(lockStateVar) }),
                    tableSwitch(
                            merge(debugMarker(markerType, dbgSig + "Getting continuation id for switch"),
                                    call(METHODSTATE_GETCONTINUATIONPOINT_METHOD, loadVar(methodStateVar))),
                            merge(debugMarker(markerType, dbgSig + "Unrecognized continuation id"),
                                    throwRuntimeException("Unrecognized continuation id")),
                            0, IntStream.range(0, numOfContinuationPoints)
                                    .mapToObj(idx -> restoreState(attrs, idx)).toArray((x) -> new InsnList[x]))
            // jump to not required here, switch above either throws exception or jumps to restore point
            )), addLabel(startOfMethodLabelNode), debugMarker(markerType, dbgSig + "Starting method..."));
}

From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
    for (int value = 0; value < 10;) {
        Double numberOfExecution = Math.pow(10, value);
        CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();

        Long startTime = System.nanoTime();
        IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
            SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(codeToExecute, kernel,
                    new Message(new Header(message.type(), message.getHeader().getSession())), 0);
            if (!showResult) {
                simpleEvaluationObject.noResult();
            }//from  w  w w  .jav  a2 s.co m

            kernel.executeCode(codeToExecute, simpleEvaluationObject);
            if (numberOfExecution.intValue() - 1 == indexOfExecution) {
                if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
                    keepLooking.complete(false);
                } else {
                    keepLooking.complete(true);
                }
            }
        });

        try {
            if (keepLooking.get()) {
                value++;
            } else {
                return numberOfExecution.intValue();
            }
        } catch (ExecutionException | InterruptedException e) {
            throw new IllegalStateException("Cannot create best number of execution.");
        }
    }

    throw new IllegalStateException("Cannot create best number of execution.");
}

From source file:com.yahoo.bullet.storm.JoinBoltTest.java

private static byte[] getGroupDataWithCount(String countField, int count) {
    GroupData groupData = new GroupData(
            new HashSet<>(singletonList(new GroupOperation(COUNT, null, countField))));
    IntStream.range(0, count).forEach(i -> groupData.consume(RecordBox.get().getRecord()));
    return SerializerDeserializer.toBytes(groupData);
}

From source file:com.simiacryptus.mindseye.lang.Tensor.java

/**
 * From rgb tensor.// ww w.  ja  va  2s. com
 *
 * @param img the img
 * @return the tensor
 */
@Nonnull
public static Tensor fromRGB(@Nonnull final BufferedImage img) {
    final int width = img.getWidth();
    final int height = img.getHeight();
    @Nonnull
    final Tensor a = new Tensor(width, height, 3);
    IntStream.range(0, width).parallel().forEach(x -> {
        @Nonnull
        final int[] coords = { 0, 0, 0 };
        IntStream.range(0, height).forEach(y -> {
            coords[0] = x;
            coords[1] = y;
            coords[2] = 0;
            a.set(coords, img.getRGB(x, y) & 0xFF);
            coords[2] = 1;
            a.set(coords, img.getRGB(x, y) >> 8 & 0xFF);
            coords[2] = 2;
            a.set(coords, img.getRGB(x, y) >> 16 & 0x0FF);
        });
    });
    return a;
}

From source file:com.vsthost.rnd.DMatrixUtilsTest.java

/**
 * Multiple test for random ZMBD test.
 */
public void testMultipleZmbdRandom() {
    IntStream.range(0, 1000).forEach(e -> this.testZmbdRandom());
}

From source file:org.gradoop.flink.model.impl.operators.matching.single.cypher.common.pojos.EmbeddingMetaDataTest.java

@Test
public void testGetVertexVariables() throws Exception {
    EmbeddingMetaData metaData = new EmbeddingMetaData();
    List<String> inputVariables = Arrays.asList("a", "b", "c", "d");
    IntStream.range(0, inputVariables.size()).forEach(i -> metaData.setEntryColumn(inputVariables.get(i),
            i % 2 == 0 ? EntryType.VERTEX : EntryType.EDGE, i));

    List<String> expectedVariables = inputVariables.stream().filter(var -> inputVariables.indexOf(var) % 2 == 0)
            .collect(Collectors.toList());

    assertThat(metaData.getVertexVariables(), is(expectedVariables));
}