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.eclipse.scanning.test.scan.nexus.MandelbrotRemoteTest.java

private void checkNexusFile(IRunnableDevice<ScanModel> scanner, int... sizes)
        throws NexusException, ScanningException, DatasetException {

    final ScanModel mod = ((AbstractRunnableDevice<ScanModel>) scanner).getModel();
    assertEquals(DeviceState.READY, scanner.getDeviceState());

    String filePath = ((AbstractRunnableDevice<ScanModel>) scanner).getModel().getFilePath();
    NexusFile nf = fileFactory.newNexusFile(filePath);
    nf.openToRead();/* ww  w  .j  a  va  2  s .c o m*/

    TreeFile nexusTree = NexusUtils.loadNexusTree(nf);
    NXroot rootNode = (NXroot) nexusTree.getGroupNode();
    NXentry entry = rootNode.getEntry();
    NXinstrument instrument = entry.getInstrument();

    // check that the scan points have been written correctly
    assertSolsticeScanGroup(entry, false, false, sizes);

    LinkedHashMap<String, List<String>> detectorDataFields = new LinkedHashMap<>();
    // axis for additional dimensions of a datafield, e.g. image
    detectorDataFields.put(NXdetector.NX_DATA, Arrays.asList("real", "imaginary"));
    detectorDataFields.put("spectrum", Arrays.asList("spectrum_axis"));
    detectorDataFields.put("value", Collections.emptyList());

    String detectorName = mod.getDetectors().get(0).getName();
    NXdetector detector = instrument.getDetector(detectorName);
    // map of detector data field to name of nxData group where that field is the @signal field
    Map<String, String> expectedDataGroupNames = detectorDataFields.keySet().stream().collect(Collectors
            .toMap(Function.identity(), x -> detectorName + (x.equals(NXdetector.NX_DATA) ? "" : "_" + x)));

    // validate the NXdata generated by the NexusDataBuilder
    Map<String, NXdata> nxDataGroups = entry.getChildren(NXdata.class);
    assertEquals(detectorDataFields.size(), nxDataGroups.size());
    assertTrue(nxDataGroups.keySet().containsAll(expectedDataGroupNames.values()));

    for (String nxDataGroupName : nxDataGroups.keySet()) {
        NXdata nxData = entry.getData(nxDataGroupName);
        String sourceFieldName = nxDataGroupName.equals(detectorName) ? NXdetector.NX_DATA
                : nxDataGroupName.substring(nxDataGroupName.indexOf('_') + 1);
        assertSignal(nxData, sourceFieldName);
        // check the nxData's signal field is a link to the data node of the detector
        DataNode dataNode = detector.getDataNode(sourceFieldName);
        IDataset dataset = dataNode.getDataset().getSlice();
        assertSame(dataNode, nxData.getDataNode(sourceFieldName));

        int[] shape = dataset.getShape();

        for (int i = 0; i < sizes.length; i++)
            assertEquals(sizes[i], shape[i]);

        // Make sure none of the numbers are NaNs. The detector
        // is expected to fill this scan with non-nulls.
        final PositionIterator it = new PositionIterator(shape);
        while (it.hasNext()) {
            int[] next = it.getPos();
            assertFalse(Double.isNaN(dataset.getDouble(next)));
        }

        // Check axes
        final IPosition pos = mod.getPositionIterable().iterator().next();
        final Collection<String> names = pos.getNames();

        // Append _value_demand to each name in list, then add detector axis fields to result
        List<String> expectedAxesNames = Stream.concat(names.stream().map(x -> x + "_value_set"),
                detectorDataFields.get(sourceFieldName).stream()).collect(Collectors.toList());
        assertAxes(nxData, expectedAxesNames.toArray(new String[expectedAxesNames.size()]));

        int[] defaultDimensionMappings = IntStream.range(0, sizes.length).toArray();
        int i = -1;
        for (String positionerName : names) {

            i++;
            NXpositioner positioner = instrument.getPositioner(positionerName);
            assertNotNull(positioner);
            dataNode = positioner.getDataNode("value_set");

            dataset = dataNode.getDataset().getSlice();
            shape = dataset.getShape();
            assertEquals(1, shape.length);
            assertEquals(sizes[i], shape[0]);

            String nxDataFieldName = positionerName + "_value_set";
            assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
            assertIndices(nxData, nxDataFieldName, i);
            assertTarget(nxData, nxDataFieldName, rootNode,
                    "/entry/instrument/" + positionerName + "/value_set");

            // Actual values should be scanD
            dataNode = positioner.getDataNode(NXpositioner.NX_VALUE);
            dataset = dataNode.getDataset().getSlice();
            shape = dataset.getShape();
            assertArrayEquals(sizes, shape);

            nxDataFieldName = positionerName + "_" + NXpositioner.NX_VALUE;
            assertSame(dataNode, nxData.getDataNode(nxDataFieldName));
            assertIndices(nxData, nxDataFieldName, defaultDimensionMappings);
            assertTarget(nxData, nxDataFieldName, rootNode,
                    "/entry/instrument/" + positionerName + "/" + NXpositioner.NX_VALUE);
        }
    }
}

From source file:org.jodconverter.cli.Convert.java

private static final Map<String, Object> toMap(final String[] options) {

    if (options == null || options.length == 0 || options.length % 2 != 0) {
        return null;
    }//from ww  w .  ja  va2  s  .  c om

    return IntStream.range(0, options.length).filter(i -> i % 2 == 0).boxed()
            .collect(Collectors.toMap(i -> options[i], i -> {
                final String val = options[i + 1];
                final Boolean bool = BooleanUtils.toBooleanObject(val);
                if (bool != null) {
                    return bool.booleanValue();
                }
                try {
                    return Integer.parseInt(val);
                } catch (NumberFormatException nfe) {
                    return val;
                }
            }));
}

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

private void addDependency(final Builder builder, final String ifPresent, final Object deps) {
    typeMultiplexer(deps).ifObject().then(obj -> {
        builder.schemaDependency(ifPresent, loadChild(obj).build());
    }).ifIs(JSONArray.class).then(propNames -> {
        IntStream.range(0, propNames.length()).mapToObj(i -> propNames.getString(i))
                .forEach(dependency -> builder.propertyDependency(ifPresent, dependency));
    }).requireAny();/*from w ww  .  j ava2s  . c om*/
}

From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java

/**
 * Fill the given VM networks with its network details.
 *//*from  w  ww  .j  ava 2s.  c  o m*/
protected void addNetworkDetails(final Element networkNode, final Collection<VmNetwork> networks) {
    // Private IP (optional)
    addNetworkDetails(networkNode, networks, "private", "privateIpAddress", "privateDnsName");

    // Public IP (optional)
    addNetworkDetails(networkNode, networks, "public", "ipAddress", "dnsName");

    // IPv6 (optional)
    final XPath xPath = xml.xpathFactory.newXPath();
    try {
        final NodeList ipv6 = (NodeList) xPath.evaluate("networkInterfaceSet/item/ipv6AddressesSet",
                networkNode, XPathConstants.NODESET);
        IntStream.range(0, ipv6.getLength()).mapToObj(ipv6::item)
                .forEach(i -> addNetworkDetails((Element) i, networks, "public", "item", "dnsName"));
    } catch (final XPathExpressionException e) {
        log.warn("Unable to evaluate IPv6", e);
    }
}

From source file:org.lightjason.agentspeak.language.CCommon.java

/**
 * calculates the levenshtein distance//ww  w. j a  v a2s  .  c om
 *
 * @param p_first first string
 * @param p_second second string
 * @param p_insertweight inserting weight
 * @param p_replaceweight replace weight
 * @param p_deleteweight delete weight
 * @return distance
 * @see https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
 */
public static double levenshtein(final String p_first, final String p_second, final double p_insertweight,
        final double p_replaceweight, final double p_deleteweight) {
    // the array of distances
    double[] l_cost = IntStream.range(0, p_first.length() + 1).mapToDouble(i -> i).toArray();
    double[] l_newcost = new double[l_cost.length];

    for (int j = 1; j < p_second.length() + 1; j++) {
        l_newcost[0] = j;

        // calculate cost of operation for all characters
        for (int i = 1; i < l_cost.length; i++)
            l_newcost[i] = min(
                    l_cost[i - 1] + (p_first.charAt(i - 1) == p_second.charAt(j - 1) ? 0 : p_replaceweight),
                    l_newcost[i - 1] + p_deleteweight, l_cost[i] + p_insertweight);

        final double[] l_swap = l_cost;
        l_cost = l_newcost;
        l_newcost = l_swap;
    }

    return l_cost[p_first.length()];
}

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

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

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

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

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

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

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

    LayoutTemplate formLayout = newForm.getLayoutTemplate();

    assertNotNull(formLayout);//  w  w w  .  ja  v  a  2  s. co  m

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

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

        switch (index) {
        case 0:
            checkFieldDefinition(fieldDefinition, USER_LOGIN, "login", "login", TextBoxFieldDefinition.class,
                    newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        case 1:
            checkFieldDefinition(fieldDefinition, USER_PASSWORD, "password", "password",
                    TextBoxFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
            break;
        }

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

        assertNotNull(fieldRow);

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

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

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

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

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

From source file:org.apache.sysml.runtime.instructions.spark.SpoofSPInstruction.java

private static boolean[] determineBroadcastInputs(SparkExecutionContext sec, CPOperand[] inputs) {
    boolean[] ret = new boolean[inputs.length];
    double localBudget = OptimizerUtils.getLocalMemBudget() - CacheableData.getBroadcastSize(); //account for other broadcasts
    double bcBudget = SparkExecutionContext.getBroadcastMemoryBudget();

    //decided for each matrix input if it fits into remaining memory
    //budget; the major input, i.e., inputs[0] is always an RDD
    for (int i = 0; i < inputs.length; i++)
        if (inputs[i].getDataType().isMatrix()) {
            MatrixCharacteristics mc = sec.getMatrixCharacteristics(inputs[i].getName());
            double sizeL = OptimizerUtils.estimateSizeExactSparsity(mc);
            double sizeP = OptimizerUtils.estimatePartitionedSizeExactSparsity(mc);
            //account for partitioning and local/remote budgets
            ret[i] = localBudget > (sizeL + sizeP) && bcBudget > sizeP;
            localBudget -= ret[i] ? sizeP : 0; //in local block manager
            bcBudget -= ret[i] ? sizeP : 0; //in remote block managers
        }/*ww w. j ava2  s  .c  o m*/

    //ensure there is at least one RDD input, with awareness for scalars
    if (!IntStream.range(0, ret.length).anyMatch(i -> inputs[i].isMatrix() && !ret[i]))
        ret[0] = false;

    return ret;
}

From source file:org.apache.hadoop.hbase.client.TestAsyncNonMetaRegionLocator.java

@Test
public void testConcurrentLocate() throws IOException, InterruptedException, ExecutionException {
    createMultiRegionTable();/*from  ww  w . java2s. c om*/
    byte[][] startKeys = getStartKeys();
    byte[][] endKeys = getEndKeys();
    ServerName[] serverNames = getLocations(startKeys);
    for (int i = 0; i < 100; i++) {
        LOCATOR.clearCache(TABLE_NAME);
        List<CompletableFuture<HRegionLocation>> futures = IntStream.range(0, 1000)
                .mapToObj(n -> String.format("%03d", n)).map(s -> Bytes.toBytes(s))
                .map(r -> LOCATOR.getRegionLocation(TABLE_NAME, r, RegionLocateType.CURRENT)).collect(toList());
        for (int j = 0; j < 1000; j++) {
            int index = Math.min(8, j / 111);
            assertLocEquals(startKeys[index], endKeys[index], serverNames[index], futures.get(j).get());
        }
    }
}

From source file:com.uber.hoodie.common.util.TestCompactionUtils.java

private HoodieCompactionPlan createCompactionPlan(String instantId, int numFileIds) {
    List<HoodieCompactionOperation> ops = IntStream.range(0, numFileIds).boxed().map(idx -> {
        try {//from   ww w.j  a  va2  s. com
            String fileId = HoodieTestUtils.createNewDataFile(basePath, DEFAULT_PARTITION_PATHS[0], instantId);
            HoodieTestUtils.createNewLogFile(metaClient.getFs(), basePath, DEFAULT_PARTITION_PATHS[0],
                    instantId, fileId, Optional.of(1));
            HoodieTestUtils.createNewLogFile(metaClient.getFs(), basePath, DEFAULT_PARTITION_PATHS[0],
                    instantId, fileId, Optional.of(2));
            FileSlice slice = new FileSlice(instantId, fileId);
            slice.setDataFile(new TestHoodieDataFile(
                    HoodieTestUtils.createDataFile(basePath, DEFAULT_PARTITION_PATHS[0], instantId, fileId)));
            String logFilePath1 = HoodieTestUtils.getLogFilePath(basePath, DEFAULT_PARTITION_PATHS[0],
                    instantId, fileId, Optional.of(1));
            String logFilePath2 = HoodieTestUtils.getLogFilePath(basePath, DEFAULT_PARTITION_PATHS[0],
                    instantId, fileId, Optional.of(2));
            slice.addLogFile(new HoodieLogFile(new Path(logFilePath1)));
            slice.addLogFile(new HoodieLogFile(new Path(logFilePath2)));
            return CompactionUtils.buildFromFileSlice(DEFAULT_PARTITION_PATHS[0], slice, Optional.empty());
        } catch (IOException e) {
            throw new HoodieIOException(e.getMessage(), e);
        }
    }).collect(Collectors.toList());
    return new HoodieCompactionPlan(ops.isEmpty() ? null : ops, new HashMap<>());
}

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

@Test
public void should_increase_login_attempts_if_user_failed_to_login() throws Exception {
    UserVO newUser = new UserVO();
    newUser.setLogin(RandomStringUtils.randomAlphabetic(10));
    newUser.setStatus(UserStatus.ACTIVE);
    UserVO user = userService.createUser(newUser, "123");
    assertThat(user, notNullValue());//from  ww  w .  j a v  a 2  s .  co m
    assertThat(user.getId(), notNullValue());
    assertThat(user.getLogin(), notNullValue());
    assertThat(user.getPasswordHash(), notNullValue());
    assertThat(user.getPasswordSalt(), notNullValue());
    assertThat(user.getStatus(), equalTo(UserStatus.ACTIVE));

    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());
    });
}