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:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java

/**
 * Hammer test. Kick off a lot of metadata updates concurrently with a ledger manager
 * that runs callbacks on random threads, and validate all updates complete eventually,
 * and that the final metadata reflects all the updates.
 *///  w w w  . j a  v a2  s.c om
@Test
public void testHammer() throws Exception {
    try (NonDeterministicMockLedgerManager lm = new NonDeterministicMockLedgerManager()) {
        long ledgerId = 1234L;

        int ensembleSize = 100;
        List<BookieSocketAddress> initialEnsemble = IntStream.range(0, ensembleSize)
                .mapToObj((i) -> address(String.format("0.0.0.%d:3181", i))).collect(Collectors.toList());

        LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(ensembleSize)
                .withDigestType(DigestType.CRC32C).withPassword(new byte[0])
                .newEnsembleEntry(0L, initialEnsemble).build();
        Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get();

        AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata);

        List<BookieSocketAddress> replacementBookies = IntStream.range(0, ensembleSize)
                .mapToObj((i) -> address(String.format("0.0.%d.1:3181", i))).collect(Collectors.toList());

        List<CompletableFuture<Versioned<LedgerMetadata>>> loops = IntStream.range(0, ensembleSize)
                .mapToObj((i) -> new MetadataUpdateLoop(lm, ledgerId, reference::get,
                        (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(initialEnsemble.get(i)),
                        (currentMetadata) -> {
                            List<BookieSocketAddress> ensemble = Lists
                                    .newArrayList(currentMetadata.getEnsembleAt(0L));
                            ensemble.set(i, replacementBookies.get(i));
                            return LedgerMetadataBuilder.from(currentMetadata)
                                    .replaceEnsembleEntry(0L, ensemble).build();
                        }, reference::compareAndSet).run())
                .collect(Collectors.toList());

        loops.forEach((l) -> l.join());

        Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L), replacementBookies);
    }
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Dataset> predict(Dataset inputDataset, Model model, MetaInfo datasetMeta, String taskId) {

    CompletableFuture<Dataset> futureDataset = new CompletableFuture<>();

    Dataset dataset = DatasetFactory.copy(inputDataset);
    Dataset tempWithDependentFeatures = DatasetFactory.copy(dataset,
            new HashSet<>(model.getDependentFeatures()));

    dataset.getDataEntry().parallelStream().forEach(dataEntry -> {
        dataEntry.getValues().keySet().retainAll(model.getIndependentFeatures());
    });/*w w  w .  j a  v a 2 s  . c  om*/
    PredictionRequest predictionRequest = new PredictionRequest();
    predictionRequest.setDataset(dataset);
    predictionRequest.setRawModel(model.getActualModel());
    predictionRequest.setAdditionalInfo(model.getAdditionalInfo());

    final HttpPost request = new HttpPost(model.getAlgorithm().getPredictionService());
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in;
    try {
        in = new PipedInputStream(out);
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
        return futureDataset;
    }
    request.setEntity(new InputStreamEntity(in, ContentType.APPLICATION_JSON));

    Future futureResponse = client.execute(request, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(final HttpResponse response) {
            futureMap.remove(taskId);
            int status = response.getStatusLine().getStatusCode();
            try {
                InputStream responseStream = response.getEntity().getContent();

                switch (status) {
                case 200:
                case 201:
                    try {
                        PredictionResponse predictionResponse = serializer.parse(responseStream,
                                PredictionResponse.class);

                        List<LinkedHashMap<String, Object>> predictions = predictionResponse.getPredictions();
                        if (dataset.getDataEntry().isEmpty()) {
                            DatasetFactory.addEmptyRows(dataset, predictions.size());
                        }
                        List<Feature> features = featureHandler
                                .findBySource("algorithm/" + model.getAlgorithm().getId());
                        IntStream.range(0, dataset.getDataEntry().size())
                                // .parallel()
                                .forEach(i -> {
                                    Map<String, Object> row = predictions.get(i);
                                    DataEntry dataEntry = dataset.getDataEntry().get(i);
                                    if (model.getAlgorithm().getOntologicalClasses().contains("ot:Scaling")
                                            || model.getAlgorithm().getOntologicalClasses()
                                                    .contains("ot:Transformation")) {
                                        dataEntry.getValues().clear();
                                        dataset.getFeatures().clear();
                                    }
                                    row.entrySet().stream().forEach(entry -> {
                                        //                                                    Feature feature = featureHandler.findByTitleAndSource(entry.getKey(), "algorithm/" + model.getAlgorithm().getId());
                                        Feature feature = features.stream()
                                                .filter(f -> f.getMeta().getTitles().contains(entry.getKey()))
                                                .findFirst().orElse(null);
                                        if (feature == null) {
                                            return;
                                        }
                                        dataEntry.getValues().put(baseURI + "feature/" + feature.getId(),
                                                entry.getValue());
                                        FeatureInfo featInfo = new FeatureInfo(
                                                baseURI + "feature/" + feature.getId(),
                                                feature.getMeta().getTitles().stream().findFirst().get());
                                        featInfo.setCategory(Dataset.DescriptorCategory.PREDICTED);
                                        dataset.getFeatures().add(featInfo);
                                    });
                                });
                        dataset.setId(randomStringGenerator.nextString(20));
                        dataset.setTotalRows(dataset.getDataEntry().size());
                        dataset.setMeta(datasetMeta);
                        futureDataset.complete(DatasetFactory.mergeColumns(dataset, tempWithDependentFeatures));
                    } catch (Exception ex) {
                        futureDataset.completeExceptionally(ex);
                    }
                    break;
                case 400:
                    String message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new BadRequestException(message));
                    break;
                case 404:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new NotFoundException(message));
                    break;
                case 500:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                    break;
                default:
                    message = new BufferedReader(new InputStreamReader(responseStream)).lines()
                            .collect(Collectors.joining("\n"));
                    futureDataset.completeExceptionally(new InternalServerErrorException(message));
                }
            } catch (IOException | UnsupportedOperationException ex) {
                futureDataset.completeExceptionally(ex);
            }
        }

        @Override
        public void failed(final Exception ex) {
            futureMap.remove(taskId);
            futureDataset.completeExceptionally(new InternalServerErrorException(ex));
        }

        @Override
        public void cancelled() {
            futureMap.remove(taskId);
            futureDataset.cancel(true);
        }
    });
    serializer.write(predictionRequest, out);
    try {
        out.close();
    } catch (IOException ex) {
        futureDataset.completeExceptionally(ex);
    }
    futureMap.put(taskId, futureResponse);
    return futureDataset;
}

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

protected final Map<Node, Integer> makeIndex(List<Node> nodes) {
    return IntStream.range(0, nodes.size()).boxed()
            .collect(Collectors.toMap(indexNode -> nodes.get(indexNode), indexNode -> indexNode));
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionCollectionList.java

/**
 * test zip action/*from  w  w w. j a  va  2s  .c o  m*/
 */
@Test
public final void zip() {
    final List<ITerm> l_return = new ArrayList<>();

    new CZip().execute(false, IContext.EMPTYPLAN,
            IntStream.range(0, 6).boxed().map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 1);
    Assert.assertEquals(l_return.get(0).<List<?>>raw().size(), 3);

    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(0).getKey(), 0);
    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(0).getValue(), 3);

    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(1).getKey(), 1);
    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(1).getValue(), 4);

    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(2).getKey(), 2);
    Assert.assertEquals(l_return.get(0).<List<AbstractMap.SimpleEntry<?, ?>>>raw().get(2).getValue(), 5);

    new CZip().execute(true, IContext.EMPTYPLAN,
            Stream.of(1, 2).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 2);
    Assert.assertEquals(l_return.get(1).<List<?>>raw().getClass(),
            Collections.synchronizedList(Collections.emptyList()).getClass());

}

From source file:org.apache.sysml.runtime.matrix.data.LibMatrixNative.java

private static FloatBuffer toFloatBuffer(double[] input, ThreadLocal<FloatBuffer> buff, boolean copy) {
    //maintain thread-local buffer (resized on demand)
    FloatBuffer ret = buff.get();
    if (ret == null || ret.capacity() < input.length) {
        ret = ByteBuffer.allocateDirect(4 * input.length).order(ByteOrder.nativeOrder()).asFloatBuffer();
        buff.set(ret);/*from  w  w w  . jav  a 2 s  .co  m*/
    }
    //copy to direct byte buffer
    final FloatBuffer ret2 = ret;
    if (copy) {
        IntStream.range(0, input.length).parallel().forEach(i -> ret2.put(i, (float) input[i]));
    }
    return ret2;
}

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

@Test
public void should_lock_user_if_max_login_attempts_reached() throws Exception {
    UserVO newUser = new UserVO();
    newUser.setLogin(RandomStringUtils.randomAlphabetic(10));
    newUser.setStatus(UserStatus.ACTIVE);
    UserVO user = userService.createUser(newUser, "123");
    assertThat(user, notNullValue());//w ww  .  java  2  s. c  om
    assertThat(user.getId(), notNullValue());
    assertThat(user.getLogin(), notNullValue());
    assertThat(user.getPasswordHash(), notNullValue());
    assertThat(user.getPasswordSalt(), notNullValue());
    assertThat(user.getStatus(), equalTo(UserStatus.ACTIVE));

    configurationService.save(Constants.MAX_LOGIN_ATTEMPTS, 5);

    IntStream.range(1, 5).forEach(attempt -> {
        try {
            userService.authenticate(user.getLogin(), "wrong_password");
            fail("should throw login exception");
        } catch (ActionNotAllowedException e) {
            assertThat(e.getMessage(), equalTo(String.format(Messages.INCORRECT_CREDENTIALS, user.getLogin())));
        }
        UserVO updatedUser = userDao.find(user.getId());
        assertThat(updatedUser, notNullValue());
        assertThat(updatedUser.getLoginAttempts(), equalTo(attempt));
        assertThat(updatedUser.getStatus(), equalTo(UserStatus.ACTIVE));
        assertThat(updatedUser.getLastLogin(), nullValue());
    });

    try {
        userService.authenticate(user.getLogin(), "wrong_password");
        fail("should throw login exception");
    } catch (ActionNotAllowedException e) {
        assertThat(e.getMessage(), equalTo(String.format(Messages.INCORRECT_CREDENTIALS, user.getLogin())));
    }
    UserVO updatedUser = userDao.find(user.getId());
    assertThat(updatedUser, notNullValue());
    assertThat(updatedUser.getLoginAttempts(), equalTo(0));
    assertThat(updatedUser.getStatus(), equalTo(UserStatus.LOCKED_OUT));
    assertThat(updatedUser.getLastLogin(), nullValue());
}

From source file:org.apache.storm.messaging.netty.NettyTest.java

private void doTestBatch(Map<String, Object> stormConf) throws Exception {
    int numMessages = 100_000;
    LOG.info("Should send and receive many messages (testing with " + numMessages + " messages)");
    ArrayList<TaskMessage> responses = new ArrayList<>();
    AtomicInteger received = new AtomicInteger();
    IContext context = TransportFactory.makeContext(stormConf);
    try {/*w w  w .  ja v a2  s  .  co m*/
        try (IConnection server = context.bind(null, 0);
                IConnection client = context.connect(null, "localhost", server.getPort(), remoteBpStatus)) {
            server.registerRecv(mkConnectionCallback((message) -> {
                responses.add(message);
                received.incrementAndGet();
            }));
            waitUntilReady(client, server);

            IntStream.range(1, numMessages)
                    .forEach(i -> send(client, taskId, String.valueOf(i).getBytes(StandardCharsets.UTF_8)));

            Testing.whileTimeout(Testing.TEST_TIMEOUT_MS, () -> responses.size() < numMessages - 1, () -> {
                LOG.info("{} of {} received", responses.size(), numMessages - 1);
                sleep().run();
            });
            IntStream.range(1, numMessages).forEach(i -> {
                assertThat(new String(responses.get(i - 1).message(), StandardCharsets.UTF_8),
                        is(String.valueOf(i)));
            });
        }
    } finally {
        context.term();
    }
}

From source file:org.everit.json.schema.loader.SchemaLoader.java

private EnumSchema.Builder buildEnumSchema() {
    Set<Object> possibleValues = new HashSet<>();
    JSONArray arr = schemaJson.getJSONArray("enum");
    IntStream.range(0, arr.length()).mapToObj(arr::get).forEach(possibleValues::add);
    return EnumSchema.builder().possibleValues(possibleValues);
}

From source file:org.kie.workbench.common.forms.migration.tool.pipelines.basic.AbstractFormDefinitionGeneratorTest.java

protected void verifyLineForm(FormMigrationSummary summary) {
    Form originalForm = summary.getOriginalForm().get();

    Assertions.assertThat(originalForm.getFormFields()).isNotEmpty().hasSize(4);

    FormDefinition newForm = summary.getNewForm().get();

    Assertions.assertThat(newForm.getFields()).isNotEmpty().hasSize(4);

    Assertions.assertThat(newForm.getModel()).isNotNull().hasFieldOrPropertyWithValue("className", LINE_MODEL)
            .isInstanceOf(DataObjectFormModel.class);

    IntStream indexStream = IntStream.range(0, newForm.getFields().size());

    LayoutTemplate formLayout = newForm.getLayoutTemplate();

    assertNotNull(formLayout);//from  w  w  w . j  av a  2s . c o  m

    Assertions.assertThat(formLayout.getRows()).isNotEmpty().hasSize(1);

    LayoutRow fieldRow = formLayout.getRows().get(0);

    indexStream.forEach(index -> {
        FieldDefinition fieldDefinition = newForm.getFields().get(index);

        switch (index) {
        case 0:
            checkFieldDefinition(fieldDefinition, LINE_PRODUCT, "product", "product",
                    TextBoxFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        case 1:
            checkFieldDefinition(fieldDefinition, LINE_PRICE, "price", "price", DecimalBoxFieldDefinition.class,
                    newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        case 2:
            checkFieldDefinition(fieldDefinition, LINE_QUANTITY, "quantity", "quantity",
                    IntegerBoxFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        case 3:
            checkFieldDefinition(fieldDefinition, LINE_TOTAL, "total", "total", DecimalBoxFieldDefinition.class,
                    newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        }

        assertNotNull(fieldRow);

        Assertions.assertThat(fieldRow.getLayoutColumns()).isNotEmpty().hasSize(4);

        LayoutColumn fieldColumn = fieldRow.getLayoutColumns().get(index);

        assertNotNull(fieldColumn);
        assertEquals("3", fieldColumn.getSpan());

        Assertions.assertThat(fieldColumn.getLayoutComponents()).isNotEmpty().hasSize(1);

        checkLayoutFormField(fieldColumn.getLayoutComponents().get(0), fieldDefinition, newForm);
    });
}

From source file:org.broadinstitute.gatk.tools.walkers.cancer.m2.TumorPowerCalculator.java

private double calculatePower(final int numReads, final double alleleFraction) throws MathException {
    if (numReads == 0)
        return 0;

    // TODO: add the factor of 1/3
    final double probAltRead = alleleFraction * (1 - errorProbability)
            + (1 / 3) * (1 - alleleFraction) * errorProbability;
    final BinomialDistribution binom = new BinomialDistributionImpl(numReads, probAltRead);
    final double[] binomialProbabilities = IntStream.range(0, numReads + 1).mapToDouble(binom::probability)
            .toArray();//from  ww  w. ja v a2 s.  c  o  m

    // find the smallest number of ALT reads k such that tumorLOD(k) > tumorLODThreshold
    final OptionalInt smallestKAboveLogThreshold = IntStream.range(0, numReads + 1)
            .filter(k -> calculateTumorLod(numReads, k) > tumorLODThreshold).findFirst();

    if (!smallestKAboveLogThreshold.isPresent()) {
        return 0;
    }

    if (smallestKAboveLogThreshold.getAsInt() <= 0) {
        throw new IllegalStateException(
                "smallest k that meets the tumor LOD threshold is less than or equal to 0");
    }

    double power = Arrays
            .stream(binomialProbabilities, smallestKAboveLogThreshold.getAsInt(), binomialProbabilities.length)
            .sum();

    // here we correct for the fact that the exact lod threshold is likely somewhere between
    // the k and k-1 bin, so we prorate the power from that bin
    if (enableSmoothing) {
        final double tumorLODAtK = calculateTumorLod(numReads, smallestKAboveLogThreshold.getAsInt());
        final double tumorLODAtKMinusOne = calculateTumorLod(numReads,
                smallestKAboveLogThreshold.getAsInt() - 1);
        final double weight = 1
                - (tumorLODThreshold - tumorLODAtKMinusOne) / (tumorLODAtK - tumorLODAtKMinusOne);
        power += weight * binomialProbabilities[smallestKAboveLogThreshold.getAsInt() - 1];
    }

    return (power);
}