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.lightjason.agentspeak.action.builtin.TestCActionCollection.java

/**
 * test clear// www .  j  a  v a  2s .  c  o m
 */
@Test
public final void clear() {
    final List<Integer> l_list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
    final Set<Integer> l_set = IntStream.range(10, 20).boxed().collect(Collectors.toSet());
    final Map<Integer, Integer> l_map = StreamUtils.windowed(IntStream.range(100, 120).boxed(), 2)
            .collect(Collectors.toMap(i -> i.get(0), i -> i.get(1)));

    final Multimap<Integer, Integer> l_multimap = HashMultimap.create();
    IntStream.range(0, 5).forEach(i -> IntStream.range(i, i + 5).forEach(j -> l_map.put(i, j)));

    new CClear().execute(false, IContext.EMPTYPLAN,
            Stream.of(l_list, l_set, l_map, l_multimap).map(CRawTerm::from).collect(Collectors.toList()),
            Collections.emptyList());

    Assert.assertTrue(l_list.isEmpty());
    Assert.assertTrue(l_set.isEmpty());
    Assert.assertTrue(l_map.isEmpty());
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Returns value space for a given BType.
 *
 * @param importsAcceptor imports acceptor
 * @param currentPkgId    current package id
 * @param bType           BType to evaluate
 * @param template        templates to be modified
 * @return {@link String}  modified templates
 *///  w ww .j  a va 2  s .  c  o m
public static String[] getValueSpaceByType(BiConsumer<String, String> importsAcceptor, PackageID currentPkgId,
        BType bType, String[] template) {
    if ((bType.tsymbol == null || bType.tsymbol.name.value.isEmpty()) && bType instanceof BArrayType) {
        BArrayType bArrayType = (BArrayType) bType;
        String[] values = getValueSpaceByTypeSymbol(bArrayType.eType.tsymbol,
                createTemplateArray(template.length));
        IntStream.range(0, template.length).forEach(
                index -> template[index] = template[index].replace(PLACE_HOLDER, "[" + values[index] + "]"));
        return template;
    } else if (bType instanceof BFiniteType) {
        // Check for finite set assignment
        BFiniteType bFiniteType = (BFiniteType) bType;
        Set<BLangExpression> valueSpace = bFiniteType.valueSpace;
        if (!valueSpace.isEmpty()) {
            return getValueSpaceByNode(importsAcceptor, currentPkgId, valueSpace.stream().findFirst().get(),
                    template);
        }
    } else if (bType instanceof BMapType && ((BMapType) bType).constraint != null) {
        // Check for constrained map assignment eg. map<Student>
        BType constraintType = ((BMapType) bType).constraint;
        String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, constraintType,
                createTemplateArray(template.length));
        IntStream.range(0, template.length).forEach(index -> {
            template[index] = template[index].replace(PLACE_HOLDER, "{key: " + values[index] + "}");
        });
        return template;
    } else if (bType instanceof BUnionType) {
        // Check for union assignment int|string
        BUnionType bUnionType = (BUnionType) bType;
        Set<BType> memberTypes = bUnionType.getMemberTypes();
        if (!memberTypes.isEmpty()) {
            return getValueSpaceByType(importsAcceptor, currentPkgId, memberTypes.stream().findFirst().get(),
                    template);
        }
    } else if (bType instanceof BTupleType) {
        // Check for tuple assignment (int, string)
        BTupleType bTupleType = (BTupleType) bType;
        List<BType> tupleTypes = bTupleType.tupleTypes;
        String[][] vSpace = new String[template.length][tupleTypes.size()];
        IntStream.range(0, tupleTypes.size()).forEach(j -> {
            BType type = tupleTypes.get(j);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(i -> vSpace[i][j] = values[i]);
        });
        IntStream.range(0, template.length).forEach(index -> {
            template[index] = template[index].replace(PLACE_HOLDER,
                    "(" + String.join(", ", vSpace[index]) + ")");
        });
        return template;
    } else if (bType instanceof BRecordType) {
        BRecordType bRecordType = (BRecordType) bType;
        List<BField> params = bRecordType.fields;
        String[][] list = new String[template.length][params.size()];
        IntStream.range(0, params.size()).forEach(paramIndex -> {
            BField field = params.get(paramIndex);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, field.type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(valIndex -> {
                list[valIndex][paramIndex] = field.name + ": " + values[valIndex];
            });
        });

        IntStream.range(0, template.length).forEach(index -> {
            String paramsStr = String.join(", ", list[index]);
            String newObjStr = "{" + paramsStr + "}";
            template[index] = template[index].replace(PLACE_HOLDER, newObjStr);
        });
        return template;
    } else if (bType instanceof BObjectType && ((BObjectType) bType).tsymbol instanceof BObjectTypeSymbol) {
        BObjectTypeSymbol bStructSymbol = (BObjectTypeSymbol) ((BObjectType) bType).tsymbol;
        List<BVarSymbol> params = bStructSymbol.initializerFunc.symbol.params;
        String[][] list = new String[template.length][params.size()];
        IntStream.range(0, params.size()).forEach(paramIndex -> {
            BVarSymbol param = params.get(paramIndex);
            String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, param.type,
                    createTemplateArray(template.length));
            IntStream.range(0, values.length).forEach(valIndex -> {
                list[valIndex][paramIndex] = values[valIndex];
            });
        });

        IntStream.range(0, template.length).forEach(index -> {
            String pkgPrefix = CommonUtil.getPackagePrefix(importsAcceptor, currentPkgId, bStructSymbol.pkgID);
            String paramsStr = String.join(", ", list[index]);
            String newObjStr = "new " + pkgPrefix + bStructSymbol.name.getValue() + "(" + paramsStr + ")";
            template[index] = template[index].replace(PLACE_HOLDER, newObjStr);
        });
        return template;
    } else if (bType instanceof BInvokableType) {
        BInvokableType invokableType = (BInvokableType) bType;
        TestFunctionGenerator generator = new TestFunctionGenerator(importsAcceptor, currentPkgId,
                invokableType);
        StringJoiner params = new StringJoiner(", ");
        String[][] valueSpace = generator.getValueSpace();
        String[] typeSpace = generator.getTypeSpace();
        String[] nameSpace = generator.getNamesSpace();
        IntStream.range(0, typeSpace.length - 1).forEach(index -> {
            String type = typeSpace[index];
            String name = nameSpace[index];
            params.add(type + " " + name);
        });
        String returnType = "(" + typeSpace[typeSpace.length - 1] + ")";
        IntStream.range(0, template.length).forEach(index -> {
            String functionStr = "function (" + params.toString() + ") returns " + returnType + "{ "
                    + ((valueSpace != null) ? "return " + valueSpace[index][invokableType.paramTypes.size()]
                            : "")
                    + "; }";
            template[index] = template[index].replace(PLACE_HOLDER, functionStr);
        });
        return template;
    }
    return (bType.tsymbol != null) ? getValueSpaceByTypeSymbol(bType.tsymbol, template)
            : (String[]) Stream.of(template).map(s -> s.replace(PLACE_HOLDER, "()")).toArray();
}

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

@Test
public void test() throws InterruptedException, ExecutionException {
    List<CompletableFuture<HRegionLocation>> futures = IntStream.range(0, 256)
            .mapToObj(i -> Bytes.toBytes(String.format("%02x", i)))
            .map(r -> LOCATOR.getRegionLocation(TABLE_NAME, r, RegionLocateType.CURRENT)).collect(toList());
    assertLocs(futures);// w  ww.j  a va 2 s  .co m
    assertTrue(MAX_CONCURRENCY.get() <= MAX_ALLOWED);
}

From source file:kishida.cnn.layers.FullyConnect.java

@Override
public void joinBatch() {
    IntStream.range(0, weight.length).parallel().forEach(ij -> {
        weight[ij] += weightDelta[ij] / parent.getMiniBatch()
                - weight[ij] * parent.getWeightDecay() * parent.getLearningRate();
    });//from  ww w  .ja v  a2s  . c o m
    IntStream.range(0, bias.length).parallel().forEach(i -> {
        bias[i] += biasDelta[i] / parent.getMiniBatch();
    });
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * saving the  Repo Names in the array and calling to Get files content
 *
 * @param rootJsonObject JSON object containing the repositories which are having the current selected commit from the given patch
 * @param commitHash     the current selected commit hash
 * @param gitHubToken    github token for accessing the github REST API
 *//*ww  w  .  j a  v a  2 s .  c o  m*/

public void saveRepoNamesInAnArray(JSONObject rootJsonObject, String commitHash, String gitHubToken) {
    JSONArray jsonArrayOfItems = (JSONArray) rootJsonObject.get(GITHUB_SEARCH_API_ITEMS_KEY_STRING);
    // setting the size of the repoLocationArray
    repoLocation = new String[jsonArrayOfItems.length()];
    //adding the repo name to the array
    IntStream.range(0, jsonArrayOfItems.length()).forEach(i -> {
        JSONObject jsonObject = (JSONObject) jsonArrayOfItems.get(i);
        JSONObject repositoryJsonObject = (JSONObject) jsonObject.get(GITHUB_SEARCH_API_REPOSITORY_KEY_STRING);
        repoLocation[i] = (String) repositoryJsonObject
                .get(GITHUB_SEARCH_API_FULL_NAME_OF_REPOSITORY_KEY_STRING);
    });
    logger.info("Repo names having the given commit are successfully saved in an array");

    SdkGitHubClient sdkGitHubClient = new SdkGitHubClient(gitHubToken);

    //        for running through the repoName Array
    IntStream.range(0, repoLocation.length).filter(i -> StringUtils.contains(repoLocation[i], "wso2/"))
            .forEach(i -> {
                //clearing all the data in the current fileNames and lineRangesChanged arraylists for each repository
                //authorNames.clear();
                fileNames.clear();
                lineRangesChanged.clear();
                patchString.clear();
                Map<String, ArrayList<String>> mapWithFileNamesAndPatch = null;
                try {
                    mapWithFileNamesAndPatch = sdkGitHubClient.getFilesChanged(repoLocation[i], commitHash);
                } catch (CodeQualityMatricesException e) {
                    logger.error(e.getMessage(), e.getCause()); // as exceptions cannot be thrown inside a lambda expression
                    System.exit(2);
                }
                fileNames = mapWithFileNamesAndPatch.get("fileNames");
                patchString = mapWithFileNamesAndPatch.get("patchString");
                saveRelaventEditLineNumbers(fileNames, patchString);
                try {
                    iterateOverFileChanges(repoLocation[i], commitHash, gitHubToken);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e.getCause()); // as exceptions cannot be thrown inside a lambda expression
                    System.exit(3);
                }
            });

    // for printing the author names and commit hashes for a certain commit.
    System.out.println(authorNames);
    System.out.println(commitHashObtainedForPRReview);
}

From source file:edu.cmu.lti.oaqa.baseqa.providers.ml.classifiers.LibSvmProvider.java

@Override
public void train(List<Map<String, Double>> X, List<String> Y, boolean crossValidation)
        throws AnalysisEngineProcessException {
    // create feature to id map
    fid2feat = ClassifierProvider.createFeatureIdKeyMap(X);
    // create label to id map
    lid2label = ClassifierProvider.createLabelIdKeyMap(Y);
    label2lid = lid2label.inverse();// w  ww .j a  v  a  2s  . c  o  m
    try {
        ClassifierProvider.saveIdKeyMap(fid2feat, featIndexFile);
        ClassifierProvider.saveIdKeyMap(lid2label, labelIndexFile);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // create libsvm data structure and train
    svm_problem prob = new svm_problem();
    assert X.size() == Y.size();
    int dataCount = X.size();
    int featCount = fid2feat.size();
    LOG.info("Training for {} instances, {} features, {} labels.", dataCount, featCount, lid2label.size());
    prob.l = dataCount;
    prob.x = X.stream().map(x -> IntStream.range(1, featCount + 1).mapToObj(j -> {
        svm_node node = new svm_node();
        node.index = j;
        node.value = x.getOrDefault(fid2feat.get(j), 0.0);
        return node;
    }).toArray(svm_node[]::new)).toArray(svm_node[][]::new);
    prob.y = Y.stream().mapToDouble(label2lid::get).toArray();
    model = svm.svm_train(prob, param);
    try {
        svm.svm_save_model(modelFile.getAbsolutePath(), model);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    double[] target = new double[prob.l];
    if (crossValidation) {
        svm.svm_cross_validation(prob, param, 10, target);
    }
}

From source file:org.lightjason.agentspeak.common.CPath.java

@Override
public final synchronized boolean endsWith(final IPath p_path) {
    return p_path.size() <= this.size() && IntStream.range(0, p_path.size()).boxed().parallel()
            .allMatch(i -> this.get(i - p_path.size()).equals(p_path.get(i)));
}

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

/**
 * test clear action without keys/*  ww w  . j  a  va  2s  .  com*/
 */
@Test
public final void clearwithoutkeys() {
    Assume.assumeNotNull(m_context);

    IntStream.range(0, 100).mapToObj(i -> RandomStringUtils.random(25))
            .forEach(i -> m_context.agent().storage().put(i, RandomStringUtils.random(5)));

    Assert.assertEquals(m_context.agent().storage().size(), 100);

    new CClear().execute(false, m_context, Collections.emptyList(), Collections.emptyList());

    Assert.assertTrue(m_context.agent().storage().isEmpty());
}

From source file:org.shredzone.commons.view.manager.ViewPattern.java

/**
 * Resolves a requested URL path. For each placeholder in the view pattern, the
 * placeholder name and its value in the URL path is returned in a map.
 *
 * @param path/*from w ww. j  a v  a2s  .  c  om*/
 *            the requested URL to be resolved
 * @return Map containing the placeholder names and its values
 */
public Map<String, String> resolve(String path) {
    Matcher m = regEx.matcher(path);
    if (!m.matches()) {
        return null;
    }

    if (m.groupCount() != parameter.size()) {
        throw new IllegalStateException(
                "regex group count " + m.groupCount() + " does not match parameter count " + parameter.size());
    }

    // TODO: only use decode when #encode() was used
    return IntStream.range(0, parameter.size()).collect(HashMap::new,
            (map, ix) -> map.put(parameter.get(ix), PathUtils.decode(m.group(ix + 1))), Map::putAll);
}

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

/**
 * data provider generator for aggregation-value tests
 * @return data/*from w w  w . j  a  v a 2s  . c o  m*/
 */
@DataProvider
public static Object[] aggregationvaluegenerate() {
    final Random l_random = new Random();

    return aggregationvaluetestcase(

            IntStream.range(0, 100).boxed().map(i -> l_random.nextGaussian()),

            Stream.of(CAverage.class, CSum.class, CMin.class, CMax.class),

            (i) -> i.mapToDouble(Number::doubleValue).average().getAsDouble(),
            (i) -> i.mapToDouble(Number::doubleValue).sum(),
            (i) -> i.mapToDouble(Number::doubleValue).min().getAsDouble(),
            (i) -> i.mapToDouble(Number::doubleValue).max().getAsDouble()

    ).toArray();
}