/** * Create a new {@code Random64} instance, where the random numbers are * generated by the given long {@code supplier}. * * @param supplier the random number supplier * @return a new {@code Random64} instance * @throws java.lang.NullPointerException if the given {@code supplier} is * {@code null}. */ public static Random32 of(final IntSupplier supplier) { Objects.requireNonNull(supplier); return new Random32() { private static final long serialVersionUID = 1L; private final Boolean _sentry = Boolean.TRUE; @Override public int nextInt() { return supplier.getAsInt(); } @Override public void setSeed(final long seed) { if (_sentry != null) { throw new UnsupportedOperationException( "The 'setSeed(long)' method is not supported." ); } } }; }
@Test public void canCastClassToKnownInterfaceAndUsePackageName() throws Exception { String classDef = "package com.acme.util;" + "import java.util.function.IntSupplier;" + "public class ZeroSupplier implements IntSupplier {" + "public int getAsInt() { return 0; }" + "}"; Class<?> cls = javacService.compileJavaClass( DefaultClassLoaderContext.INSTANCE, "com.acme.util.ZeroSupplier", classDef ) .orElseThrow( () -> new AssertionError( "Failed to compile class" ) ); IntSupplier instance = ( IntSupplier ) cls.newInstance(); int zero = instance.getAsInt(); assertEquals( 0, zero ); }
/** * General dataset making recipe. * @param fullPath the dataset full path. * @param typeIdSupplier type id supplier lambda. * @param dimensions array with the dimensions of the data. * @param data the data. It must be an array of the appropriate type given the type that is * going to be returned by the {@code typeIdSupplier}. * @return true iff the data-set needed to be created (it did not existed previously). It will * return false if the data-set existed even if it was modified in the process. */ private boolean makeDataset(final String fullPath, final IntSupplier typeIdSupplier, final long[] dimensions, final Object data) { checkCanWrite(); int typeCopyId = -1; try { typeCopyId = typeIdSupplier.getAsInt(); final Pair<String, String> pathAndName = splitPathInParentAndName(fullPath); final String groupPath = pathAndName.getLeft(); final String dataSetName = pathAndName.getRight(); makeGroup(groupPath); final int childType = findOutGroupChildType(groupPath, dataSetName, fullPath); if (childType == HDF5Constants.H5G_UNKNOWN) { createDataset(fullPath, typeCopyId, dimensions); writeDataset(fullPath, typeCopyId, data); return true; } else if (childType == HDF5Constants.H5G_DATASET) { writeDataset(fullPath, typeCopyId, data); return false; } else { throw new HDF5LibException(String.format("problem trying to write dataset %s in file %s: there is a collision with a non-dataset object", fullPath, file)); } } finally { if (typeCopyId != -1) { try { H5.H5Tclose(typeCopyId); } catch (final HDF5Exception ex ){} } } }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullCache() { // given final ConcurrentMap<String, Integer> cache = null; final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = () -> 123; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Provide an empty map instead of NULL."); // then new ConcurrentMapBasedIntSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullKeySupplier() { // given final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = null; final IntSupplier supplier = () -> 123; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Provide a key function, might just be 'MemoizationDefaults.defaultKeySupplier()'."); // then new ConcurrentMapBasedIntSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullValueSupplier() { // given final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = null; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Cannot memoize a NULL Supplier - provide an actual Supplier to fix this."); // then new ConcurrentMapBasedIntSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test public void shouldUseSuppliedKey() { // given final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = () -> 123; // when final ConcurrentMapBasedIntSupplierMemoizer<String> memoizer = new ConcurrentMapBasedIntSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertTrue("Cache is not empty before memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", "key", memoizer.viewCacheForTest().keySet().iterator().next()); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.BOXING) public void shouldTriggerOnce() { // given final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = mock(IntSupplier.class); given(supplier.getAsInt()).willReturn(123); // when final ConcurrentMapBasedIntSupplierMemoizer<String> memoizer = new ConcurrentMapBasedIntSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); // triggers Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); // memoized Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); // memoized Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); // memoized verify(supplier, times(1)).getAsInt(); // real supplier triggered once, all other calls were memoized }
SheetPane() { // define row and column ranges and set up segments final IntSupplier startColumn = () -> 0; final IntSupplier splitColumn = this::getSplitColumn; final IntSupplier endColumn = this::getColumnCount; final IntSupplier startRow = () -> 0; final IntSupplier splitRow = this::getSplitRow; final IntSupplier endRow = this::getRowCount; topLeftQuadrant = new SwingSegmentView(startRow, splitRow, startColumn, splitColumn); topRightQuadrant = new SwingSegmentView(startRow, splitRow, splitColumn, endColumn); bottomLeftQuadrant = new SwingSegmentView(splitRow, endRow, startColumn, splitColumn); bottomRightQuadrant = new SwingSegmentView(splitRow, endRow, splitColumn, endColumn); init(); }
public JfxSheetView() { final GridPane gridPane = new GridPane(); gridPane.setGridLinesVisible(true); // FIXME // define row and column ranges final IntSupplier startColumn = () -> 0; final IntSupplier splitColumn = this::getSplitColumn; final IntSupplier endColumn = this::getColumnCount; final IntSupplier startRow = () -> 0; final IntSupplier splitRow = this::getSplitRow; final IntSupplier endRow = this::getRowCount; leftTopChart = new JfxSegmentView(this, startRow, splitRow, startColumn, splitColumn); rightTopChart = new JfxSegmentView(this, startRow, splitRow, splitColumn, endColumn); leftBottomChart = new JfxSegmentView(this, splitRow, endRow, startColumn, splitColumn); rightBottomChart = new JfxSegmentView(this, splitRow, endRow, splitColumn, endColumn); gridPane.addRow(1, leftTopChart, rightTopChart); gridPane.addRow(2, leftBottomChart, rightBottomChart); getChildren().setAll(gridPane); }
private void shouldReplyToOnNotLeaderWith( final IntSupplier libraryId, final LongSupplier connectCorrelationId, final String... channels) { whenPolled() .then( (inv) -> { library.onNotLeader(libraryId.getAsInt(), connectCorrelationId.getAsLong(), LEADER_CHANNEL); return 1; }) .then(replyWithApplicationHeartbeat()) .then(noReply()); newLibraryPoller(CLUSTER_CHANNELS); library.startConnecting(); pollTwice(); poll(); attemptToConnectTo(channels); verify(connectHandler).onConnect(fixLibrary); }
protected QueryProcessor( MetricMaker metricMaker, SchemaDefinitions<T> schemaDef, IndexConfig indexConfig, IndexCollection<?, T, ? extends Index<?, T>> indexes, IndexRewriter<T> rewriter, String limitField, IntSupplier permittedLimit) { this.metrics = new Metrics(metricMaker); this.schemaDef = schemaDef; this.indexConfig = indexConfig; this.indexes = indexes; this.rewriter = rewriter; this.limitField = limitField; this.permittedLimit = permittedLimit; this.used = new AtomicBoolean(false); }
static <T extends Enum<T> & IntSupplier> Set<T> bitsToSet(int bits, Class<T> tClass) { EnumSet<T> ret = EnumSet.noneOf(tClass); // Internal/Unsafe T[] enums; if (useSharedSecrets) { enums = SharedSecrets.getJavaLangAccess().getEnumConstantsShared(tClass); } else { enums = tClass.getEnumConstants(); } tClass.getEnumConstants(); for (T t : enums) { if ((bits & t.getAsInt()) != 0) { ret.add(t); } } return ret; }
@Test public void rowReadBuilderTest() throws SQLException { final RowReadBuilder lrb = RowReadBuilder.create(); final IntSupplier id = lrb.addInt(sql("id")); final Supplier<String> name = lrb.add(sql("name"), String.class); m.execute(sql("insert into person (id, name) values (1, 'Max')")); m.execute(sql("insert into person (id, name) values (2, 'John')")); final List<List<Object>> rows = m.queryList(sql("select ", lrb.buildColumns(), " from person order by id"), lrb.build()); assertEquals(2, rows.size()); lrb.bindSuppliers(rows.get(0)); assertEquals(1, id.getAsInt()); assertEquals("Max", name.get()); lrb.bindSuppliers(rows.get(1)); assertEquals(2, id.getAsInt()); assertEquals("John", name.get()); }
/** Creates a `Box.Int` from a `IntSupplier` and a `IntConsumer`. */ public static Int from(IntSupplier getter, IntConsumer setter) { return new Int() { @Override public int getAsInt() { return getter.getAsInt(); } @Override public void set(int value) { setter.accept(value); } @Override public String toString() { return "Box.Int.from[" + get() + "]"; } }; }
private void applyColor(GL2 g, IntSupplier func, boolean dot) { float color; if (Globals.floor>=0) { color = ((float)func.getAsInt() - minElevation) / diffElevation; } else if (!dot) { color = ((float)func.getAsInt() - minCaveElevation) / diffCaveElevation; } else { color = ((float)func.getAsInt() - minCaveSize) / diffCaveSize; } if (Float.isNaN(color)) { color = 0.5f; } if (!Properties.colorblind) { g.glColor3f(color, 1-color, 0); } else { g.glColor3f(color, 0, 1-color); } }
private void putTraverseAction(String key, IntSupplier amount) { InputMap im = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); im.put(KeyStroke.getKeyStroke("pressed " + key), key); ActionMap am = getActionMap(); am.put(key, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int newFocus = focusId + amount.getAsInt(); if (newFocus < 0) { getComponent(0).transferFocusBackward(); } else if (newFocus >= getComponentCount()) { getComponent(getComponentCount() - 1).transferFocus(); } else { getComponent(newFocus).requestFocusInWindow(); } } }); }
@Test public void optional_int_orElseGet() { OptionalInt optionalInt = OptionalInt.empty(); assertEquals(10, optionalInt.orElseGet(() -> 10), 0); // or IntSupplier intSupplier = new IntSupplier() { @Override public int getAsInt() { return 10; } }; assertEquals(10, optionalInt.orElseGet(intSupplier), 0); }
private IntSupplier composeAcceptor(final TcpInterfaceAcceptor acceptor) { return () -> { try { return onAcceptable(acceptor.acceptor().accept()); } catch (final Exception ex) { ex.printStackTrace(); // TODO: temporary } return 0; }; }
@Test public void testCheckedIntSupplier() { final CheckedIntSupplier intSupplier = () -> { throw new Exception("int"); }; IntSupplier s1 = Unchecked.intSupplier(intSupplier); IntSupplier s2 = CheckedIntSupplier.unchecked(intSupplier); IntSupplier s3 = Sneaky.intSupplier(intSupplier); IntSupplier s4 = CheckedIntSupplier.sneaky(intSupplier); assertIntSupplier(s1, UncheckedException.class); assertIntSupplier(s2, UncheckedException.class); assertIntSupplier(s3, Exception.class); assertIntSupplier(s4, Exception.class); }
@Test public void lambdaScope() throws Exception { IntSupplier cycle123a = new IntSupplier() { int c = 2; @Override public int getAsInt() { this.c++; return (this.c % 3) + 1; } }; IntSupplier cycle123b = () -> (this.c++ % 3) + 1; assertEquals(cycle123a.getAsInt(), 1); assertEquals(cycle123a.getAsInt(), 2); assertEquals(cycle123a.getAsInt(), 3); assertEquals(cycle123a.getAsInt(), 1); assertEquals(cycle123a.getAsInt(), 2); assertEquals(cycle123a.getAsInt(), 3); assertEquals(cycle123b.getAsInt(), 1); assertEquals(cycle123b.getAsInt(), 2); assertEquals(cycle123b.getAsInt(), 3); assertEquals(cycle123b.getAsInt(), 1); assertEquals(cycle123b.getAsInt(), 2); assertEquals(cycle123b.getAsInt(), 3); assertEquals(this.c, 9); }
@Test public void basicMethodRef() throws Exception { BiFunction<String, Integer, RefDemo> bif1 = RefDemo::new; RefDemo rd1 = bif1.apply("Jon", 10); assertEquals(rd1.name, "Jon"); assertEquals(rd1.age, 10); RefDemo.STATIC_INT = 100; rd1.instanceInt = 200; IntSupplier sup1 = RefDemo::getStaticInt; IntSupplier sup2 = rd1::getInstanceInt; assertEquals(sup1.getAsInt(), 100); assertEquals(sup2.getAsInt(), 200); Function<RefDemo, String> greeting = RefDemo::whoAreYou; assertEquals(greeting.apply(rd1), "My name is Jon, 10 years old."); }
private static Map<Class<?>, Class<?>> createPrimitiveSuppliers() { Map<Class<?>, Class<?>> map = new HashMap<>(); map.put(IntSupplier.class, Integer.TYPE); map.put(LongSupplier.class, Long.TYPE); map.put(BooleanSupplier.class, Boolean.TYPE); map.put(DoubleSupplier.class, Double.TYPE); return Collections.unmodifiableMap(map); }
@Test public void testSupplierPerson() { IntSupplier supplier = () -> { Person manager1 = new Person(Title.MR, "James", "Wilks", 55); return manager1.getAge(); }; assertEquals(55, supplier.getAsInt()); }
/** * This method writes this class ConcurrentTermMap into disk, in a * serialized way, splitting the terms in it into different files, grouped * by their first letter, emptying the map completely. It does not provide a * way to control how much of the map we are writing to disk */ public void save() { if (tmap.getTmap().isEmpty()) { return; } tmap.getTmap().entrySet() .parallelStream() .collect(Collectors.groupingByConcurrent(e -> e.getKey().substring(0, ((IntSupplier) () -> { if (e.getKey().length() > 1) { return splitLevel; } else { return 1; } }).getAsInt()).replace(".", "").toLowerCase())) .entrySet() .forEach(entry -> { if (entry != null) { String fileName = entry.getKey() + ".termMap." + (dm.dirCountContains(entry.getKey())); //remove the entries (from tmap) that we are about to write into disk entry.getValue().parallelStream() .forEach((t) -> tmap.remove(t.getKey())); ConcurrentTermMap map = new ConcurrentTermMap(); entry.getValue().parallelStream() .forEach(e -> map.put(e.getKey(), e.getValue())); dm.write(fileName, map.getTmap()); } }); }
/** * Saves a ConcurrentTermMap to disk (by using the DiskManager) * @param tmap */ private void save(ConcurrentTermMap tmap) { if (tmap.getTmap().isEmpty()) { return; } tmap.getTmap().entrySet() .parallelStream() .collect(Collectors.groupingByConcurrent(e -> e.getKey().substring(0, ((IntSupplier) () -> { if (e.getKey().length() > 1) { return 2; } else { return 1; } }).getAsInt()).replace(".", "").toLowerCase())) .entrySet() .forEach(entry -> { if (entry != null) { String fileName = entry.getKey() + ".termMap.part." + (dm.dirCountContains(entry.getKey())); //remove the entries (from tmap) that we are about to write into disk entry.getValue().parallelStream() .forEach((t) -> tmap.remove(t.getKey())); ConcurrentTermMap map = new ConcurrentTermMap(); entry.getValue().parallelStream() .forEach(e -> map.put(e.getKey(), e.getValue())); dm.write(fileName, map.getTmap()); } }); }
/** * <p>Creates a binding using the passed supplier and list of dependencies.</p> * * <p>Note that this method requires manual implementation of the respective binding logic. For * most cases, however, the static methods provided by this interface do suffice however and * require far less manually programmed logic.</p> */ @Nonnull static IntegerBinding create(@Nonnull IntSupplier supplier, ReadOnlyObservable<?>... observables) { return new AbstractIntegerBinding(new HashSet<>(Arrays.asList(observables))) { @Override protected Integer compute() { return supplier.getAsInt(); } }; }
@Override public IntSupplier setIntSupplier(final int id, final IntSupplier supplier) { if (id >= type.getIntStatCount()) { throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type); } return intSuppliers.put(id, supplier); }
@Test public void invokeIntSuppliersShouldUpdateStats() { IntSupplier supplier1 = mock(IntSupplier.class); when(supplier1.getAsInt()).thenReturn(23); stats.setIntSupplier(4, supplier1); assertEquals(0, stats.invokeSuppliers()); verify(supplier1).getAsInt(); assertEquals(23, stats.getInt(4)); }
@Test public void invokeSuppliersShouldCatchSupplierErrorsAndReturnCount() { IntSupplier supplier1 = mock(IntSupplier.class); when(supplier1.getAsInt()).thenThrow(NullPointerException.class); stats.setIntSupplier(4, supplier1); assertEquals(1, stats.invokeSuppliers()); verify(supplier1).getAsInt(); }
@Test public void badSupplierParamShouldThrowError() { IntSupplier supplier1 = mock(IntSupplier.class); when(supplier1.getAsInt()).thenReturn(23); thrown.expect(IllegalArgumentException.class); stats.setIntSupplier(23, supplier1); }
SetBuilder(Set<T> elements, int defaultVarIndex, IntSupplier nextLocalVar) { this.elements = elements; this.defaultVarIndex = defaultVarIndex; this.nextLocalVar = nextLocalVar; }
@Override public int execute(VirtualFrame frame) { partialEvaluationConstantAndEquals(finalWeakRefInteger.get(), Integer.valueOf(0)); partialEvaluationConstantAndEquals(finalWeakRefNull.get(), null); IntSupplier supplier = finalWeakRef.get(); if (supplier != null) { return supplier.getAsInt(); } else { return 0xdead; } }
@Override public int execute(VirtualFrame frame) { IntSupplier supplier = finalWeakRef.get(); if (supplier == null) { return 0xdead; } else if (supplier == frame.getArguments()[0]) { return supplier.getAsInt(); } else { return -1; } }
private static void solve(Scanner in, PrintWriter out) { final int N = in.nextInt(); int[] array = IntStream.range(0, N).map(i -> in.nextInt()).toArray(); IntStream intStream = Arrays.stream(array); Comparator<? super Map.Entry<Integer, Long>> minByKeyAndMaxByValueComparator = (entry1, entry2) -> { int cmp = Long.compare(entry1.getValue(), entry2.getValue()); if (cmp == 0) { cmp = Integer.compare(entry2.getKey(), entry1.getKey()); } return cmp; }; Optional<Entry<Integer, Long>> maxValue = intStream .boxed() .collect(groupingBy(identity(), counting())) .entrySet() .stream() .max(minByKeyAndMaxByValueComparator); intStream = Arrays.stream(array); IntSupplier intSupplier = () -> maxValue.get().getKey(); IntStream maxIntStream = IntStream.generate(intSupplier).limit(maxValue.get().getValue()); IntStream result = IntStream.concat(intStream.filter(i -> i != maxValue.get().getKey()), maxIntStream); String s = result .mapToObj(Integer::toString) .collect(joining(" ")); out.print(s); out.flush(); }
public BasicMetricsContext( final String stepId, final IoType ioType, final IntSupplier actualConcurrencyGauge, final int driverCount, final int concurrency, final int thresholdConcurrency, final SizeInBytes itemDataSize, final int updateIntervalSec, final boolean stdOutColorFlag, final boolean avgPersistFlag, final boolean sumPersistFlag, final boolean perfDbResultsFileFlag ) { this.stepId = stepId; this.ioType = ioType; this.actualConcurrencyGauge = actualConcurrencyGauge; this.driverCount = driverCount; this.concurrency = concurrency; this.thresholdConcurrency = thresholdConcurrency > 0 ? thresholdConcurrency : Integer.MAX_VALUE; this.itemDataSize = itemDataSize; this.stdOutColorFlag = stdOutColorFlag; this.avgPersistFlag = avgPersistFlag; this.sumPersistFlag = sumPersistFlag; this.perfDbResultsFileFlag = perfDbResultsFileFlag; this.outputPeriodMillis = TimeUnit.SECONDS.toMillis(updateIntervalSec); respLatency = new Histogram(new SlidingWindowReservoir(DEFAULT_RESERVOIR_SIZE)); respLatSnapshot = respLatency.getSnapshot(); respLatencySum = new LongAdder(); reqDuration = new Histogram(new SlidingWindowReservoir(DEFAULT_RESERVOIR_SIZE)); reqDurSnapshot = reqDuration.getSnapshot(); actualConcurrency = new Histogram(new SlidingWindowReservoir(DEFAULT_RESERVOIR_SIZE)); actualConcurrencySnapshot = actualConcurrency.getSnapshot(); reqDurationSum = new LongAdder(); throughputSuccess = new CustomMeter(clock, updateIntervalSec); throughputFail = new CustomMeter(clock, updateIntervalSec); reqBytes = new CustomMeter(clock, updateIntervalSec); ts = System.nanoTime(); }
private synchronized int maybeCompute(IntSupplier supplier) { if (!initialized) { value = requireNonNull(supplier.getAsInt()); initialized = true; } return value; }
/** * Creates a HDF5 type based on a simple copy of a HDF5 type class. * @param classId the class id to copy. * @return never {@code null}. */ private IntSupplier basicTypeCopyIdSupplier(final int classId) { return () -> { try { return checkH5Result(H5.H5Tcopy(classId), () -> ""); } catch (final HDF5LibraryException ex) { throw new HDF5LibException("", ex); } }; }
public static String decode(IntSupplier supplier) { StringBuilder buf = new StringBuilder(); for (;;) { int ch = get(supplier); if (ch >= 0) { buf.append((char)ch); } else { break; } } return buf.toString(); }