/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullCache() { // given final ConcurrentMap<String, Double> cache = null; final Supplier<String> keySupplier = () -> "key"; final DoubleSupplier supplier = () -> 123.456D; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Provide an empty map instead of NULL."); // then new ConcurrentMapBasedDoubleSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullKeySupplier() { // given final ConcurrentMap<String, Double> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = null; final DoubleSupplier supplier = () -> 123.456D; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Provide a key function, might just be 'MemoizationDefaults.defaultKeySupplier()'."); // then new ConcurrentMapBasedDoubleSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test @SuppressWarnings(CompilerWarnings.UNUSED) public void shouldRequireNonNullValueSupplier() { // given final ConcurrentMap<String, Double> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final DoubleSupplier supplier = null; // when thrown.expect(NullPointerException.class); thrown.expectMessage("Cannot memoize a NULL Supplier - provide an actual Supplier to fix this."); // then new ConcurrentMapBasedDoubleSupplierMemoizer<>(cache, keySupplier, supplier); }
/** * */ @Test public void shouldUseSuppliedKey() { // given final ConcurrentMap<String, Double> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final DoubleSupplier supplier = () -> 123.456D; // when final ConcurrentMapBasedDoubleSupplierMemoizer<String> memoizer = new ConcurrentMapBasedDoubleSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertTrue("Cache is not empty before memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoized value does not match expectations", 123.456D, memoizer.getAsDouble(), 0.0D); 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, Double> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final DoubleSupplier supplier = mock(DoubleSupplier.class); given(supplier.getAsDouble()).willReturn(123.456D); // when final ConcurrentMapBasedDoubleSupplierMemoizer<String> memoizer = new ConcurrentMapBasedDoubleSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertEquals("Memoized value does not match expectations", 123.456D, memoizer.getAsDouble(), 0.0D); // triggers Assert.assertEquals("Memoized value does not match expectations", 123.456D, memoizer.getAsDouble(), 0.0D); // memoized Assert.assertEquals("Memoized value does not match expectations", 123.456D, memoizer.getAsDouble(), 0.0D); // memoized Assert.assertEquals("Memoized value does not match expectations", 123.456D, memoizer.getAsDouble(), 0.0D); // memoized verify(supplier, times(1)).getAsDouble(); // real supplier triggered once, all other calls were memoized }
/** * Creates a new view configuration * * @param viewportSupplier A supplier that supplies the viewport, * as 4 float elements, [x, y, width, height] * @param aspectRatioSupplier An optional supplier for the aspect ratio. * If this is <code>null</code>, then the aspect ratio of the * camera will be used * @param externalViewMatrixSupplier The optional external supplier of * a view matrix. * @param externalProjectionMatrixSupplier The optional external supplier * of a projection matrix. */ ViewConfiguration( Supplier<float[]> viewportSupplier, DoubleSupplier aspectRatioSupplier, Supplier<float[]> externalViewMatrixSupplier, Supplier<float[]> externalProjectionMatrixSupplier) { this.viewportSupplier = Objects.requireNonNull( viewportSupplier, "The viewportSupplier may not be null"); this.currentCameraModelSupplier = new SettableSupplier<CameraModel>(); this.aspectRatioSupplier = aspectRatioSupplier; this.viewMatrixSupplier = createViewMatrixSupplier(externalViewMatrixSupplier); this.projectionMatrixSupplier = createProjectionMatrixSupplier(externalProjectionMatrixSupplier); }
/** * Create a gyroscope for the given functions that returns the angular displacement and velocity. * * @param angleSupplier the function that returns the angle; may not be null * @param rateSupplier the function that returns the angular acceleration; may not be null * @return the angle sensor */ public static Gyroscope create(DoubleSupplier angleSupplier, DoubleSupplier rateSupplier) { return new Gyroscope() { private volatile double zero = 0; @Override public double getAngle() { return angleSupplier.getAsDouble() - zero; } @Override public Gyroscope zero() { zero = angleSupplier.getAsDouble(); return this; } @Override public double getRate() { return rateSupplier.getAsDouble(); } }; }
/** * Create a distance sensor for the given function that returns the distance. * * @param distanceSupplier the function that returns the distance; may not be null * @return the angle sensor */ public static DistanceSensor create(DoubleSupplier distanceSupplier) { return new DistanceSensor() { private double zero = 0; @Override public double getDistanceInInches() { return distanceSupplier.getAsDouble() - zero; } @Override public DistanceSensor zero() { zero = distanceSupplier.getAsDouble(); return this; } }; }
/** * Create an angle sensor around the given function that returns the angle. * * @param angleSupplier the function that returns the angle; may not be null * @return the angle sensor */ public static AngleSensor create(DoubleSupplier angleSupplier) { return new AngleSensor() { private volatile double zero = 0; @Override public double getAngle() { return angleSupplier.getAsDouble() - zero; } @Override public AngleSensor zero() { zero = angleSupplier.getAsDouble(); return this; } }; }
/** * Create a angle sensor for the given function that returns the angle. * * @param angleSupplier the function that returns the angle; may not be null * @return the angle sensor */ public static Compass create(DoubleSupplier angleSupplier) { return new Compass() { private volatile double zero = 0; @Override public double getAngle() { return angleSupplier.getAsDouble() - zero; } @Override public Compass zero() { zero = angleSupplier.getAsDouble(); return this; } }; }
/** * Create a new PowerPanel from functions that supply the current for each channel, total current, voltage, and temperature. * * @param currentForChannel the function that returns the current for a given channel; may not be null * @param totalCurrent the function that returns total current; may not be null * @param voltage the function that returns voltage; may not be null * @param temperature the function that returns temperature; may not be null * @return the power panel; never null * @see Hardware#powerPanel() */ public static PowerPanel create(IntToDoubleFunction currentForChannel, DoubleSupplier totalCurrent, DoubleSupplier voltage, DoubleSupplier temperature) { return new PowerPanel() { @Override public CurrentSensor getCurrentSensor(int channel) { return () -> currentForChannel.applyAsDouble(channel); } @Override public CurrentSensor getTotalCurrentSensor() { return totalCurrent::getAsDouble; } @Override public VoltageSensor getVoltageSensor() { return voltage::getAsDouble; } @Override public TemperatureSensor getTemperatureSensor() { return voltage::getAsDouble; } }; }
/** Creates a `Box.Dbl` from a `DoubleSupplier` and a `DoubleConsumer`. */ public static Dbl from(DoubleSupplier getter, DoubleConsumer setter) { return new Dbl() { @Override public double getAsDouble() { return getter.getAsDouble(); } @Override public void set(double value) { setter.accept(value); } @Override public String toString() { return "Box.Dbl.from[" + get() + "]"; } }; }
@Test public void optional_double_orElseGet() { OptionalDouble optionalDouble = OptionalDouble.empty(); assertEquals(10, optionalDouble.orElseGet(() -> 10), 0); // or DoubleSupplier doubleSupplier = new DoubleSupplier() { @Override public double getAsDouble() { return 10; } }; assertEquals(10, optionalDouble.orElseGet(doubleSupplier), 0); }
@Test public void testCheckedDoubleSupplier() { final CheckedDoubleSupplier doubleSupplier = () -> { throw new Exception("double"); }; DoubleSupplier s1 = Unchecked.doubleSupplier(doubleSupplier); DoubleSupplier s2 = CheckedDoubleSupplier.unchecked(doubleSupplier); DoubleSupplier s3 = Sneaky.doubleSupplier(doubleSupplier); DoubleSupplier s4 = CheckedDoubleSupplier.sneaky(doubleSupplier); assertDoubleSupplier(s1, UncheckedException.class); assertDoubleSupplier(s2, UncheckedException.class); assertDoubleSupplier(s3, Exception.class); assertDoubleSupplier(s4, Exception.class); }
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); }
/** * <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 DoubleBinding create(@Nonnull DoubleSupplier supplier, ReadOnlyObservable<?>... observables) { return new AbstractDoubleBinding(new HashSet<>(Arrays.asList(observables))) { @Override protected Double compute() { return supplier.getAsDouble(); } }; }
/** * Core of a reimplementation of {@link #nextGaussian()} whose locking is overridable and doesn't * happen when a value is already stored. * @param nextDouble shall return a random number between 0 and 1, like {@link #nextDouble()}, * but shall not debit the entropy count. * @return a random number that is normally distributed with mean 0 and standard deviation 1. */ @SuppressWarnings("LocalVariableHidesMemberVariable") protected double internalNextGaussian( final DoubleSupplier nextDouble) { // See Knuth, ACP, Section 3.4.1 Algorithm C. final double firstTryOut = Double.longBitsToDouble(nextNextGaussian.getAndSet(NAN_LONG_BITS)); if (Double.isNaN(firstTryOut)) { lockForNextGaussian(); try { // Another output may have become available while we waited for the lock final double secondTryOut = Double.longBitsToDouble(nextNextGaussian.getAndSet(NAN_LONG_BITS)); if (!Double.isNaN(secondTryOut)) { return secondTryOut; } double s; double v1; double v2; do { v1 = (2 * nextDouble.getAsDouble()) - 1; // between -1 and 1 v2 = (2 * nextDouble.getAsDouble()) - 1; // between -1 and 1 s = (v1 * v1) + (v2 * v2); } while ((s >= 1) || (s == 0)); final double multiplier = StrictMath.sqrt((-2 * StrictMath.log(s)) / s); nextNextGaussian.set(Double.doubleToRawLongBits(v2 * multiplier)); return v1 * multiplier; } finally { unlockForNextGaussian(); } } else { return firstTryOut; } }
public ColorGradientSprite(Entity e, Color start, Color end, DoubleSupplier variable) { this(e, () -> { float val = (float) variable.getAsDouble(); if(val > 1) val = 1; else if(val < 0) val = 0; return new Color( (1 - val) * start.getRed() / 255 + val * end.getRed() / 255, (1 - val) * start.getGreen() / 255 + val * end.getGreen() / 255, (1 - val) * start.getBlue() / 255 + val * end.getBlue() / 255); }); }
@Override public DoubleSupplier setDoubleSupplier(final int id, final DoubleSupplier supplier) { if (id >= type.getDoubleStatCount()) { throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type); } return doubleSuppliers.put(id, supplier); }
@Test public void invokeDoubleSuppliersShouldUpdateStats() { DoubleSupplier supplier1 = mock(DoubleSupplier.class); when(supplier1.getAsDouble()).thenReturn(23.3); stats.setDoubleSupplier(4, supplier1); assertEquals(0, stats.invokeSuppliers()); verify(supplier1).getAsDouble(); assertEquals(23.3, stats.getDouble(4), 0.1f); }
@Override public DoubleSupplier measurementFor(Measure measure) { if (!MEASURES.contains(measure)) { throw new IllegalArgumentException("invalid measure: " + measure.name()); } return () -> digitalOutput.get() ? 1.0 : 0.0; }
@Override public DoubleSupplier measurementFor(Measure measure) { if (!MEASURES.contains(measure)) { throw new IllegalArgumentException("invalid measure: " + measure.name()); } switch (measure) { case POSITION: return servo::getPosition; case ANGLE: return servo::getAngle; default: throw new AssertionError(measure); } }
@Override public DoubleSupplier measurementFor(Measure measure) { if (!MEASURES.contains(measure)) { throw new IllegalArgumentException("invalid measure: " + measure.name()); } return () -> digitalInput.get() ? 1.0 : 0.0; }
public void measurementsToJson(BufferedSink sink) throws IOException { long ts = System.currentTimeMillis(); JsonWriter writer = JsonWriter.of(sink); writer.beginObject(); writer.name("timestamp").value(ts); writer.name("data"); writer.beginArray(); for (DoubleSupplier m : measurements) { writer.value(m.getAsDouble()); } writer.endArray(); writer.endObject(); }
@Override public DoubleSupplier measurementFor(Measure measure) { if (!MEASURES.contains(measure)) { throw new IllegalArgumentException("invalid measure: " + measure.name()); } switch (measure) { case ANGLE: return gyro::getAngle; case GYRO_YAW: return gyro::getYaw; default: throw new AssertionError(measure); } }
private Gauge(final String name, final String help, final String[] labelNames, final Map<List<String>, DoubleSupplier> valueSuppliers) { super(name, help, labelNames); this.valueSuppliers = valueSuppliers; }
@Override ChildMetricRepo<DoubleSupplier> createChildMetricRepo() { if (valueSuppliers.size() == 1 && getLabelNames().isEmpty()) { final DoubleSupplier supplier = valueSuppliers.values().iterator().next(); return new UnlabeledChildRepo<>(new MetricData<>(supplier)); } else { final ChildMetricRepo<DoubleSupplier> result = new LabeledChildrenRepo<>(labelValues -> new MetricData<>( valueSuppliers.get(labelValues), labelValues)); valueSuppliers.keySet().forEach(result::metricForLabels); return result; } }
/** * @see Gauge for more information on what value suppliers are and how they relate to label values */ public GaugeValueSuppliersBuilder withValueSupplier(final DoubleSupplier valueSupplier, final String... labelValues) { validateValueSupplier(valueSupplier); validateValueSupplierLabels(labelNames.length, labelValues); valueSuppliers.put(Arrays.asList(labelValues), valueSupplier); return this; }
/** * Randomly mirrors each plane of the grid to the other side of the centroid. * Also mirrors the directions of the lines. */ public void randomReflection() { final DoubleSupplier randomSign = () -> rng.nextBoolean() ? -1.0 : 1.0; xySign = randomSign.getAsDouble(); xzSign = randomSign.getAsDouble(); yzSign = randomSign.getAsDouble(); }
private synchronized double maybeCompute(DoubleSupplier supplier) { if (!initialized) { value = requireNonNull(supplier.getAsDouble()); initialized = true; } return value; }
private void tileFactorize(LazyEnergyCapProvider lecp) { if (broken) return; final ICapabilityProvider cp = lecp.getObject(); if (cp == null || !(cp instanceof TileEntity)) return; final TileEntity te = (TileEntity) cp; final IEnergyTile et = EnergyNet.instance.getTile(te.getWorld(), te.getPos()); final IEnergySource esrc = et instanceof IEnergySource ? (IEnergySource) et : null; final IEnergySink esnk = et instanceof IEnergySink ? (IEnergySink) et : null; DoubleSupplier cfunc = et instanceof BasicSource ? ((BasicSource) et)::getCapacity : et instanceof BasicSink ? ((BasicSink) et)::getCapacity : null; DoubleSupplier efunc = et instanceof BasicSource ? ((BasicSource) et)::getEnergyStored : et instanceof BasicSink ? ((BasicSink) et)::getEnergyStored : null; if (IC2_TEB.isInstance(cp)) { Object o = null; try { o = COMPONENT.invoke(cp, IC2_ENERGY); } catch (Exception e) { MCFluxReport.sendException(e, "[IC2] FluxCompat factorize"); } cfunc = doubleFunc(CAPACITY, o); efunc = doubleFunc(ENERGY, o); } final EUDelegate eud = new EUDelegate(cfunc, efunc, esnk, esrc); final EnergyTile[] es = new EnergyTile[7]; for (int i = 0; i < U.FANCY_FACING.length; i++) { EnumFacing f = U.FANCY_FACING[i]; es[i] = new EnergyTile(eud, f); } lecp.update(es, new int[0], null, true); CloudUtils.reportEnergy(cp.getClass(), et.getClass(), "ic2"); }
private static DoubleSupplier doubleFunc(Method m, Object o) { return () -> { try { return (double) m.invoke(o); } catch (Exception e) { e.printStackTrace(); } return 0; }; }
/** * */ @Test public void shouldMemoizeDoubleSupplierWithKeyFunction() { // given final DoubleSupplier supplier = () -> 123.456D; final Supplier<String> keySupplier = defaultKeySupplier(); // when final DoubleSupplier memoize = CaffeineMemoize.doubleSupplier(supplier, keySupplier); // then Assert.assertNotNull("Memoized DoubleSupplier is NULL", memoize); }
/** * */ @Test public void shouldMemoizeDoubleSupplier() { // given final DoubleSupplier supplier = () -> 123.456D; // when final DoubleSupplier memoize = CaffeineMemoize.doubleSupplier(supplier); // then Assert.assertNotNull("Memoized DoubleSupplier is NULL", memoize); }
/** * */ @Test public void shouldMemoizeDoubleSupplierWithLambda() { // given // when final DoubleSupplier memoize = CaffeineMemoize.doubleSupplier(() -> 123.456D); // then Assert.assertNotNull("Memoized DoubleSupplier is NULL", memoize); }
GuavaCacheBasedDoubleSupplierMemoizer( final Cache<KEY, Double> cache, final Supplier<KEY> keySupplier, final DoubleSupplier supplier) { super(cache); this.keySupplier = keySupplier; this.supplier = supplier; }
/** * */ @Test public void shouldMemoizeDoubleSupplierWithKeySupplier() { // given final DoubleSupplier supplier = () -> 123.456D; final Supplier<String> keySupplier = () -> "key"; // when final DoubleSupplier memoize = GuavaMemoize.doubleSupplier(supplier, keySupplier); // then Assert.assertNotNull("Memoized DoubleSupplier is NULL", memoize); }
/** * */ @Test public void shouldAcceptLoadingCacheAndKeySupplier() { // given final DoubleSupplier supplier = () -> 123.456D; final Supplier<String> keySupplier = () -> "key"; final Cache<String, Double> cache = CacheBuilder.newBuilder().build(); // when final GuavaCacheBasedDoubleSupplierMemoizer<String> memoizer = new GuavaCacheBasedDoubleSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertNotNull(memoizer); }
/** * */ @Test public void shouldReturnSuppliedValue() { // given final DoubleSupplier supplier = () -> 123.456D; final Supplier<String> keySupplier = () -> "key"; final Cache<String, Double> cache = CacheBuilder.newBuilder().build(); // when final GuavaCacheBasedDoubleSupplierMemoizer<String> memoizer = new GuavaCacheBasedDoubleSupplierMemoizer<>( cache, keySupplier, supplier); // then Assert.assertEquals(123.456D, memoizer.getAsDouble(), 0.0D); }