List of usage examples for java.util.stream IntStream range
public static IntStream range(int startInclusive, int endExclusive)
From source file:ijfx.service.overlay.io.OverlaySerializer.java
private void savePolytonOverlay(PolygonOverlay overlay, JsonGenerator jg) throws IOException { // {//from w ww . j av a 2 s. c o m jg.writeStartObject(); int numDimension = overlay.numDimensions(); // "ovl_type":"polygon" jg.writeStringField(JsonOverlayToken.OVERLAY_TYPE, JsonOverlayToken.POLYGON_OVERLAY); // "points":[ int vertexCount = overlay.getRegionOfInterest().getVertexCount(); double[] xpoints = IntStream.range(0, vertexCount) .mapToDouble(i -> overlay.getRegionOfInterest().getVertex(i).getDoublePosition(0)).toArray(); double[] ypoints = IntStream.range(0, vertexCount) .mapToDouble(i -> overlay.getRegionOfInterest().getVertex(i).getDoublePosition(1)).toArray(); writeDoubleArray(jg, "xpoints", xpoints); writeDoubleArray(jg, "ypoints", ypoints); // } ColorRGB fcolor = overlay.getFillColor(); ColorRGB lcolor = overlay.getLineColor(); Integer[] fill_color = { fcolor.getRed(), fcolor.getGreen(), fcolor.getBlue() }; Integer[] line_color = { lcolor.getRed(), lcolor.getGreen(), lcolor.getBlue() }; double width = overlay.getLineWidth(); writeNumberArray(jg, JsonOverlayToken.FILL_COLOR, fill_color); writeNumberArray(jg, JsonOverlayToken.LINE_COLOR, line_color); jg.writeFieldName(JsonOverlayToken.LINE_WIDTH); jg.writeNumber(width); jg.writeEndObject(); }
From source file:org.apache.hadoop.hbase.client.TestZKAsyncRegistry.java
@Test public void test() throws InterruptedException, ExecutionException, IOException { assertEquals(TEST_UTIL.getHBaseCluster().getClusterStatus().getClusterId(), REGISTRY.getClusterId().get()); assertEquals(TEST_UTIL.getHBaseCluster().getClusterStatus().getServersSize(), REGISTRY.getCurrentNrHRS().get().intValue()); assertEquals(TEST_UTIL.getHBaseCluster().getMaster().getServerName(), REGISTRY.getMasterAddress().get()); assertEquals(-1, REGISTRY.getMasterInfoPort().get().intValue()); waitUntilAllReplicasHavingRegionLocation(TableName.META_TABLE_NAME); RegionLocations locs = REGISTRY.getMetaRegionLocation().get(); assertEquals(3, locs.getRegionLocations().length); IntStream.range(0, 3).forEach(i -> { HRegionLocation loc = locs.getRegionLocation(i); assertNotNull("Replica " + i + " doesn't have location", loc); assertTrue(loc.getRegionInfo().getTable().equals(TableName.META_TABLE_NAME)); assertEquals(i, loc.getRegionInfo().getReplicaId()); });// w w w . j av a2 s .c om }
From source file:org.shredzone.cilla.view.ResourceView.java
/** * Sets up the internal cache for the resource's etag and content length. * * @param pack/*from w ww. j a va2 s . co m*/ * Resource pack * @param name * Resource name * @return Map key */ private String setup(String pack, String name) throws IOException { String key = pack + '/' + name; if (!(etagMap.containsKey(key) && sizeMap.containsKey(key))) { try (InputStream in = ResourceView.class.getResourceAsStream("/public/" + pack + '/' + name)) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); int counter = 0; byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) >= 0) { md5.update(buffer, 0, length); counter += length; } byte[] digest = md5.digest(); etagMap.put(key, IntStream.range(0, digest.length) .mapToObj(ix -> String.format("%02x", digest[ix] & 0xFF)).collect(joining("", "\"", "\""))); sizeMap.put(key, counter); } catch (NoSuchAlgorithmException ex) { // we expect no exception, since MD5 is a standard digester throw new InternalError(); } } return key; }
From source file:io.mashin.rich.spark.TestJavaRichRDD.java
@Test public void testHttpRDD() { String serverIP = HttpMockConfig.serverIP(); int serverPort = HttpMockConfig.serverPort(); JavaSparkContext sc = sc("testHttpRDD"); HttpMock mock = new HttpMock(); mock.start();// w w w . j a va2 s .c om int numPages = 4; JavaRDD<String> rdd = JavaRichRDD .httpRDD(sc, i -> new HttpGet("http://" + serverIP + ":" + serverPort + "/rdd?page=" + (i + 1)), (i, httpResponse) -> { BufferedReader is = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String s = is.readLine(); is.close(); return Arrays.asList(s.split(",")).iterator(); }, numPages) .cache(); assertEquals(numPages, rdd.getNumPartitions()); assertEquals(numPages * HttpMockConfig.perPage(), rdd.count()); boolean isValid = rdd.mapPartitionsWithIndex((i, iter) -> { List<String> list = StreamSupport .stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false) .collect(Collectors.toList()); return IntStream.range(0, list.size()).mapToObj(j -> HttpMockConfig.isValidElement(list.get(j), i, j)) .iterator(); }, true).reduce(Boolean::logicalAnd); assertTrue(isValid); sc.stop(); mock.stop(); }
From source file:edu.washington.gs.skyline.model.quantification.FoldChangeDataSet.java
public int getControlGroupCount() { return (int) IntStream.range(0, subjectControls.length).filter(this::isSubjectInControlGroup).count(); }
From source file:org.deeplearning4j.examples.tictactoe.TicTacToeData.java
/** * This function called by generatePossibleGames. It is the main function that generates all possible game states. * Refer ReadMe.txt for detailed explanation. *///from w w w.j a v a2s. com private void generateStateBasedOnMoveNumber(int moveNumber, List<INDArray> moveSequenceList, List<String> values) throws Exception { List<INDArray> tempMoveSequenceList = new ArrayList<>(); tempMoveSequenceList.addAll(moveSequenceList); moveSequenceList.clear(); if (moveNumber == 1) { for (int i = 0; i < 9; i++) { INDArray temp2 = Nd4j.zeros(1, 9); temp2.putScalar(new int[] { 0, i }, 1); moveSequenceList.add(temp2); } } else { int lengthOfTempMoveSequenceList = tempMoveSequenceList.size(); for (INDArray moveArraySequence : tempMoveSequenceList) IntStream.range(0, 9).filter(j -> moveArraySequence.getInt(j) == 0).forEach(j -> { INDArray temp1 = Nd4j.zeros(1, 9); Nd4j.copy(moveArraySequence, temp1); temp1.putScalar(new int[] { 0, j }, moveNumber); if (moveNumber > 4) { boolean isOddMoveNumber = (moveNumber % 2) != 0; if (checkWin(temp1, isOddMoveNumber)) { values.addAll(generateGameStatesAndRewardToIt(temp1, isOddMoveNumber ? 0 : 1)); } else { moveSequenceList.add(temp1); } } else { moveSequenceList.add(temp1); } }); } if (moveNumber == 9) { values.addAll( moveSequenceList.stream().flatMap(temp1 -> generateGameStatesAndRewardToIt(temp1, 0).stream()) .collect(Collectors.toList())); } }
From source file:org.gradoop.flink.model.impl.operators.matching.single.cypher.common.pojos.EmbeddingTestUtils.java
/** * Creates a data set of the specified size containing equal embeddings described by the given ids. * * @param env execution environment/*from w ww . j a v a 2 s . c o m*/ * @param size number of embeddings in the generated data set * @param ids ids contained in each embedding * @return data set of embeddings */ public static DataSet<Embedding> createEmbeddings(ExecutionEnvironment env, int size, GradoopId... ids) { List<Embedding> embeddings = new ArrayList<>(size); IntStream.range(0, size).forEach(i -> embeddings.add(createEmbedding(ids))); return env.fromCollection(embeddings); }
From source file:org.hawkular.metrics.core.service.metrics.BaseMetricsITest.java
protected static void assertNumericBucketsEquals(List<NumericBucketPoint> actual, List<NumericBucketPoint> expected) { String msg = String.format("%nExpected:%n%s%nActual:%n%s%n", expected, actual); assertEquals(actual.size(), expected.size(), msg); IntStream.range(0, actual.size()).forEach(i -> { NumericBucketPoint actualPoint = actual.get(i); NumericBucketPoint expectedPoint = expected.get(i); assertNumericBucketEquals(actualPoint, expectedPoint, msg); });//from w ww.jav a 2 s. c o m }
From source file:org.lightjason.examples.pokemon.simulation.agent.pokemon.CDefinition.java
/** * ctor/*from w w w . j a v a2s . c om*/ */ private CDefinition() { Structure l_structure = null; try { // read structure l_structure = (Structure) JAXBContext.newInstance(Structure.class).createUnmarshaller() .unmarshal(CCommon.getResourceURL(CCommon.PACKAGEPATH + "data/character.xml")); } catch (final JAXBException | MalformedURLException | URISyntaxException l_exception) { System.out.println(l_exception); LOGGER.warning(l_exception.toString()); } if (l_structure == null) m_pokemon = Collections.emptyMap(); else { // read attributes final Map<String, CAttribute> l_attribute = Collections.unmodifiableMap(l_structure.getConfiguration() .getAttribute().getItem().stream() .map(i -> new CAttribute(i.getId(), EAccess.valueOf(i.getAgentaccess().trim().toUpperCase()))) .collect(Collectors.toMap(CAttribute::name, i -> i))); // read atacks final Map<String, CAttack> l_attack = Collections.unmodifiableMap(l_structure.getConfiguration() .getAttack().getItem().stream().map(i -> new CAttack(i, l_attribute)) .collect(Collectors.toMap(CAttack::name, i -> i))); // read pokemon character m_pokemon = Collections.unmodifiableMap(l_structure.getCharacter().getPokemon().stream() .collect(Collectors.toMap(i -> i.getId().trim().toLowerCase(), i -> new ImmutablePair<>( i.getExperience(), Collections.unmodifiableList(IntStream.range(0, i.getLevel().size()) .mapToObj(j -> new CLevel(i.getId().trim().toLowerCase(), j, i.getLevel().get(j).getEthnicity().stream().map(Ilevelitem::getId), i.getLevel().get(j).getEthnicity().stream() .map(n -> new ImmutableTriple<Number, Number, Number>( n.getExpected(), n.getMinimum(), n.getMaximum())), i.getLevel().get(j).getMotivation().stream().map(Ilevelitem::getId), i.getLevel().get(j).getMotivation().stream() .map(n -> new ImmutableTriple<Number, Number, Number>( n.getExpected(), n.getMinimum(), n.getMaximum())), i.getLevel().get(j).getAttribute().stream() .map(n -> l_attribute.get(n.getId().trim().toLowerCase())), i.getLevel().get(j).getAttribute().stream() .map(n -> new ImmutableTriple<Number, Number, Number>( n.getExpected(), n.getMinimum(), n.getMaximum())), i.getLevel().get(j).getAttack().stream() .map(n -> l_attack.get(n.getId().trim().toLowerCase())) )).collect(Collectors.toList()))) ))); } }
From source file:com.github.lukaszbudnik.dqueue.QueueClientPerformanceTest.java
@Test public void doItNoFilters() throws ExecutionException, InterruptedException { byte[] data = new byte[2045]; Random r = new Random(); r.nextBytes(data);//w w w. j av a2 s . co m ByteBuffer buffer = ByteBuffer.wrap(data); IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> { UUID startTime = UUIDs.timeBased(); Future<UUID> id = queueClient.publish(new Item(startTime, buffer)); try { id.get(); } catch (Exception e) { fail(e.getMessage()); } }); IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> { Future<Optional<Item>> itemFuture = queueClient.consume(); Optional<Item> item = null; try { item = itemFuture.get(); } catch (Exception e) { fail(e.getMessage()); } assertTrue(item.isPresent()); }); }