Search in sources :

Example 56 with BiConsumer

use of java.util.function.BiConsumer in project mule by mulesoft.

the class MetadataExtensionFunctionalTestCase method getSuccessComponentDynamicMetadata.

private ComponentMetadataDescriptor<T> getSuccessComponentDynamicMetadata(MetadataKey key, BiConsumer<MetadataResult<ComponentMetadataDescriptor<T>>, MetadataKey> assertKeys) {
    MetadataResult<ComponentMetadataDescriptor<T>> componentMetadata = getComponentDynamicMetadata(key);
    String msg = componentMetadata.getFailures().stream().map(f -> "Failure: " + f.getMessage()).collect(joining(", "));
    assertThat(msg, componentMetadata.isSuccess(), is(true));
    assertKeys.accept(componentMetadata, key);
    return componentMetadata.get();
}
Also used : Arrays(java.util.Arrays) DSL_RESOLUTION(org.mule.test.module.extension.metadata.MetadataExtensionFunctionalTestCase.ResolutionType.DSL_RESOLUTION) PERSON(org.mule.test.metadata.extension.MetadataConnection.PERSON) Assert.assertThat(org.junit.Assert.assertThat) MetadataKey(org.mule.runtime.api.metadata.MetadataKey) ExtensionsTestUtils(org.mule.test.module.extension.internal.util.ExtensionsTestUtils) Is.is(org.hamcrest.core.Is.is) ComponentMetadataDescriptor(org.mule.runtime.api.metadata.descriptor.ComponentMetadataDescriptor) ClassTypeLoader(org.mule.metadata.api.ClassTypeLoader) MetadataService(org.mule.runtime.api.metadata.MetadataService) Parameterized(org.junit.runners.Parameterized) NullMetadataKey(org.mule.runtime.extension.api.metadata.NullMetadataKey) ConnectableComponentModel(org.mule.runtime.api.meta.model.ConnectableComponentModel) Collection(java.util.Collection) Set(java.util.Set) SAN_FRANCISCO(org.mule.test.metadata.extension.resolver.TestMultiLevelKeyResolver.SAN_FRANCISCO) Message.of(org.mule.runtime.api.message.Message.of) Collectors.joining(java.util.stream.Collectors.joining) USA(org.mule.test.metadata.extension.resolver.TestMultiLevelKeyResolver.USA) METADATA_SERVICE_KEY(org.mule.runtime.api.metadata.MetadataService.METADATA_SERVICE_KEY) MetadataComponent(org.mule.runtime.api.metadata.resolving.MetadataComponent) TestMetadataResolverUtils.getMetadata(org.mule.test.metadata.extension.resolver.TestMetadataResolverUtils.getMetadata) Type(java.lang.reflect.Type) EXPLICIT_RESOLUTION(org.mule.test.module.extension.metadata.MetadataExtensionFunctionalTestCase.ResolutionType.EXPLICIT_RESOLUTION) OutputModel(org.mule.runtime.api.meta.model.OutputModel) MetadataType(org.mule.metadata.api.model.MetadataType) Matchers.containsString(org.hamcrest.Matchers.containsString) MetadataResult(org.mule.runtime.api.metadata.resolving.MetadataResult) AbstractExtensionFunctionalTestCase(org.mule.test.module.extension.AbstractExtensionFunctionalTestCase) AMERICA(org.mule.test.metadata.extension.resolver.TestMultiLevelKeyResolver.AMERICA) ComponentModel(org.mule.runtime.api.meta.model.ComponentModel) ExtensionsTypeLoaderFactory(org.mule.runtime.extension.api.declaration.type.ExtensionsTypeLoaderFactory) JAVA(org.mule.metadata.api.model.MetadataFormat.JAVA) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) MultilevelMetadataKeyBuilder(org.mule.runtime.module.extension.api.metadata.MultilevelMetadataKeyBuilder) Location(org.mule.runtime.api.component.location.Location) BaseTypeBuilder(org.mule.metadata.api.builder.BaseTypeBuilder) Inject(javax.inject.Inject) RunnerDelegateTo(org.mule.test.runner.RunnerDelegateTo) BiConsumer(java.util.function.BiConsumer) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MetadataKeyBuilder.newKey(org.mule.runtime.api.metadata.MetadataKeyBuilder.newKey) Named(javax.inject.Named) Before(org.junit.Before) Typed(org.mule.runtime.api.meta.Typed) FailureCode(org.mule.runtime.api.metadata.resolving.FailureCode) Matchers.empty(org.hamcrest.Matchers.empty) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) CAR(org.mule.test.metadata.extension.MetadataConnection.CAR) MetadataKeysContainer(org.mule.runtime.api.metadata.MetadataKeysContainer) MetadataFailure(org.mule.runtime.api.metadata.resolving.MetadataFailure) Matchers.containsString(org.hamcrest.Matchers.containsString) ComponentMetadataDescriptor(org.mule.runtime.api.metadata.descriptor.ComponentMetadataDescriptor)

Example 57 with BiConsumer

use of java.util.function.BiConsumer in project robozonky by RoboZonky.

the class DaemonOperationTest method error.

@Test
void error() {
    final Authenticated a = mock(Authenticated.class);
    final BiConsumer<Portfolio, Authenticated> operation = (p, api) -> {
        throw new Error();
    };
    final Consumer<Throwable> shutdown = mock(Consumer.class);
    final DaemonOperation d = new CustomOperation(a, operation, shutdown);
    d.run();
    verify(shutdown).accept(any());
}
Also used : Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) RoboZonkyDaemonFailedEvent(com.github.robozonky.api.notifications.RoboZonkyDaemonFailedEvent) Authenticated(com.github.robozonky.app.authentication.Authenticated) Duration(java.time.Duration) BiConsumer(java.util.function.BiConsumer) Optional(java.util.Optional) Assertions(org.assertj.core.api.Assertions) AbstractZonkyLeveragingTest(com.github.robozonky.app.AbstractZonkyLeveragingTest) Portfolio(com.github.robozonky.app.portfolio.Portfolio) Authenticated(com.github.robozonky.app.authentication.Authenticated) Portfolio(com.github.robozonky.app.portfolio.Portfolio) Test(org.junit.jupiter.api.Test) AbstractZonkyLeveragingTest(com.github.robozonky.app.AbstractZonkyLeveragingTest)

Example 58 with BiConsumer

use of java.util.function.BiConsumer in project narchy by automenta.

the class NAct method actionBipolarFrequencyDifferential.

default GoalActionAsyncConcept[] actionBipolarFrequencyDifferential(@NotNull Term s, boolean fair, boolean latchPreviousIfUndecided, @NotNull FloatToFloatFunction update) {
    Term pt = // $.p(s, PLUS);
    $.inh(s, PLUS);
    // $.prop(s,PLUS);
    // $.p(s, ZeroProduct);
    // $.p(s,$.the("\"+\""));
    Term nt = // $.p(s, NEG);
    $.inh(s, NEG);
    // $.prop(s, NEG);
    // $.p(ZeroProduct, s);
    // $.p(s,$.the("\"-\""));
    final float[] g = new float[2];
    final float[] c = new float[2];
    final long[] lastUpdate = { ETERNAL };
    final float[] lastX = { 0 };
    // hack
    GoalActionAsyncConcept[] CC = new GoalActionAsyncConcept[2];
    @NotNull BiConsumer<GoalActionAsyncConcept, Truth> u = (action, gg) -> {
        NAR n = nar();
        long now = n.time();
        if (now != lastUpdate[0]) {
            lastUpdate[0] = now;
            // reset
            CC[0] = CC[1] = null;
        }
        // float freqEps = n.freqResolution.floatValue();
        float confMin = n.confMin.floatValue();
        // float eviMin = c2wSafe(confMin);
        float feedbackConf = // fairly shared to sum to default
        w2c(c2w(n.confDefault(BELIEF)) / 2f);
        // n.confDefault(BELIEF);
        // n.confDefault(GOAL);
        // confMin * ...;
        boolean p = action.term().equals(pt);
        int ip = p ? 0 : 1;
        CC[ip] = action;
        g[ip] = gg != null ? // gg.freq()
        gg.expectation() : 0f;
        // 0.5f;
        c[ip] = gg != null ? // gg.evi()
        gg.conf() : 0f;
        // -1..+1
        float x;
        boolean curious;
        if (CC[0] != null && CC[1] != null) /* both ready */
        {
            float cMax = Math.max(c[0], c[1]);
            float cMin = Math.min(c[0], c[1]);
            float coherence = cMin / cMax;
            Random rng = n.random();
            float cur = curiosity().floatValue();
            if (cur > 0 && rng.nextFloat() <= cur) {
                x = (rng.nextFloat() - 0.5f) * 2f;
                // float curiEvi =
                // //c2w(n.confDefault(BELIEF));
                // //eviMin*2;
                // Math.max(c2wSafe(w2cSafe(eviMin)*2), Util.mean(c[0], c[1])); //match desire conf, min=2*minConf
                c[0] = c[1] = feedbackConf;
                coherence = 1f;
                curious = true;
            } else {
                curious = false;
                if (cMax < confMin) {
                    if (latchPreviousIfUndecided) {
                        x = lastX[0];
                    } else {
                        x = 0;
                    }
                } else {
                    // //expectation
                    // float g0 = g[0]-0.5f;
                    // float g1 = g[1]-0.5f;
                    // df = 2f * ((g0) - (g1));
                    // // /Math.max(Math.abs(g0), Math.abs(g1));
                    // frequency -======================
                    // A. subtraction
                    // subtract
                    x = ((g[0] - g[1]));
                    // experimental: lessen by a factor of how equally confident each goal is
                    if (fair) {
                        // fully fair
                        x *= coherence;
                    // x *= Math.sqrt(coherence); //less sharp than linear
                    // semi-fair
                    // df *= 0.5f + 0.5f * (eMin / eMax); //reduction by at most half
                    }
                // df *= 1f - Math.abs(e[0] - e[1]) / eMax;
                // df *= Util.sqr(eMin / eMax); //more cautious
                // df *= Math.min(w2cSafe(e[0]), w2cSafe(e[1])) / w2cSafe(eMax);
                }
            }
            x = Util.clamp(x, -1f, +1f);
            lastX[0] = x;
            // -1..+1
            float y = update.valueOf(x);
            // System.out.println(x + " " + y);
            // w2c(Math.abs(y) * c2w(restConf));
            PreciseTruth Nb, Ng, Pb, Pg;
            if (y == y) {
                // y: (-1..+1)
                float yp, yn;
                if (Math.abs(y) >= n.freqResolution.floatValue()) {
                    yp = 0.5f + y / 2f;
                    yn = 1f - yp;
                } else {
                    yp = yn = 0.5f;
                }
                // float yp = 0.5f + y/2f;
                // float yn = 1f - yp;
                float pbf = yp;
                float nbf = yn;
                Pb = $.t(pbf, feedbackConf);
                Nb = $.t(nbf, feedbackConf);
                // float goalEvi =
                // eviMin;
                // //max(eviMin, max(e[0], e[1]));
                // Pg = curious || e[0] == 0 ? new PreciseTruth(yp, goalEvi, false) : null;
                // Ng = curious || e[1] == 0 ? new PreciseTruth(yn, goalEvi, false) : null;
                // float confBase = confMin*4; //~ alpha, learning rate
                // float fThresh = Float.MIN_NORMAL;
                // float yp = y > +fThresh ? Util.lerp(+y, confBase, feedbackConf) : confBase;
                // float yn = y < -fThresh ? Util.lerp(-y, confBase, feedbackConf) : confBase;
                // Pb = $.t(y > +fThresh ? 1 : 0, y > +fThresh ? yp : feedbackConf - yp);
                // Nb = $.t(y < -fThresh ? 1 : 0, y < -fThresh ? yn : feedbackConf - yn);
                // //Pg = curious || e[0] == 0 ? new PreciseTruth(1, Util.lerp(+y, confMin2, feedbackConf)) : null;
                // Pg = null;
                // //Ng = curious || e[1] == 0 ? new PreciseTruth(1, Util.lerp(-y, confMin2, feedbackConf)) : null;
                // Ng = null;
                // float fThresh = nar().freqResolution.floatValue();
                // int sign = (y > fThresh ? +1 : (y < -fThresh ? -1 : 0));
                // 
                // float feedConf =
                // w2cSafe(c2wSafe(goalConf)/2f); //half/half
                // //goalConf;
                // //Math.max(confMin, goalConf * coherence);
                // switch (sign) {
                // case +1:
                // //Pb = $.t(1f, Util.lerp(+y, confBase, feedbackConf));
                // Pb = $.t(y/2f + 0.5f, feedConf);
                // Nb =
                // //null;
                // $.t(0, feedConf);
                // break;
                // case -1:
                // Pb =
                // //null;
                // $.t(0, feedConf);
                // 
                // Nb = $.t(-y/2f + 0.5f, feedConf);
                // break;
                // case 0:
                // //Pb = Nb = null; //no signal
                // Pb = Nb = $.t(0, feedConf);
                // //Math.max(confMin, feedConf);
                // //w2cSafe(c2wSafe(feedConf)/2f))); //zero
                // break;
                // default:
                // throw new UnsupportedOperationException();
                // }
                Pg = null;
                Ng = null;
            // if (curious) {
            // e[0] = e[1] = 0; //reset to get full evidence override
            // }
            // float g0 = eviMax - e[0];
            // Pg = g0 >= eviMin ? new PreciseTruth(yp, g0, false) : null;
            // float g1 = eviMax - e[1];
            // Ng = g1 >= eviMin ? new PreciseTruth(yn, g1, false) : null;
            } else {
                Pb = Nb = Pg = Ng = null;
            }
            // System.out.println(Pb + "," + Nb + " <- " + g[0] + ";" + c[0] + ", " + g[1] + ';' + c[1]);
            CC[0].feedback(Pb, Pg, n);
            CC[1].feedback(Nb, Ng, n);
        }
    };
    CauseChannel<ITask> cause = nar().newCauseChannel(s);
    GoalActionAsyncConcept p = new GoalActionAsyncConcept(pt, this, cause, u);
    GoalActionAsyncConcept n = new GoalActionAsyncConcept(nt, this, cause, u);
    addAction(p);
    addAction(n);
    nar().believe($.inh(s, SECTe.the(PLUS, NEG)).neg(), Tense.Eternal);
    CC[0] = p;
    CC[1] = n;
    return CC;
}
Also used : Tense(nars.time.Tense) IntConsumer(java.util.function.IntConsumer) Random(java.util.Random) FloatToFloatFunction(org.eclipse.collections.api.block.function.primitive.FloatToFloatFunction) ETERNAL(nars.time.Tense.ETERNAL) IntPredicate(java.util.function.IntPredicate) GoalActionConcept(nars.concept.action.GoalActionConcept) Truth(nars.truth.Truth) ActionConcept(nars.concept.action.ActionConcept) BeliefActionConcept(nars.concept.action.BeliefActionConcept) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) FloatConsumer(jcog.util.FloatConsumer) TruthFunctions.c2w(nars.truth.TruthFunctions.c2w) TruthFunctions.w2c(nars.truth.TruthFunctions.w2c) Term(nars.term.Term) BooleanProcedure(org.eclipse.collections.api.block.procedure.primitive.BooleanProcedure) Util.unitize(jcog.Util.unitize) FloatRange(jcog.math.FloatRange) PreciseTruth(nars.truth.PreciseTruth) SECTe(nars.Op.SECTe) Util(jcog.Util) ITask(nars.task.ITask) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) GoalActionAsyncConcept(nars.concept.action.GoalActionAsyncConcept) BELIEF(nars.Op.BELIEF) CauseChannel(nars.control.CauseChannel) NotNull(org.jetbrains.annotations.NotNull) ITask(nars.task.ITask) Term(nars.term.Term) GoalActionAsyncConcept(nars.concept.action.GoalActionAsyncConcept) NotNull(org.jetbrains.annotations.NotNull) PreciseTruth(nars.truth.PreciseTruth) Random(java.util.Random) Truth(nars.truth.Truth) PreciseTruth(nars.truth.PreciseTruth)

Example 59 with BiConsumer

use of java.util.function.BiConsumer in project LuckPerms by lucko.

the class DebugCommand method execute.

@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, List<String> args, String label) {
    Message.DEBUG_START.send(sender);
    StringBuilder sb = new StringBuilder();
    sb.append("LuckPerms Debug Output\n\n\n");
    BiConsumer<String, JObject> builder = (name, content) -> {
        sb.append("-- ").append(name).append(" --\n");
        sb.append(GSON.toJson(content.toJson()));
        sb.append("\n\n");
    };
    builder.accept("platform.json", getPlatformData(plugin));
    builder.accept("storage.json", getStorageData(plugin));
    builder.accept("context.json", getContextData(plugin));
    builder.accept("players.json", getPlayersData(plugin));
    Pastebin.Paste paste = StandardPastebin.HASTEBIN.postPlain(sb.toString());
    Message.DEBUG_URL.send(sender);
    Component message = TextComponent.builder(paste.url()).color(TextColor.AQUA).clickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, String.valueOf(paste.url()))).hoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to open the debugging data.").color(TextColor.GRAY))).build();
    sender.sendMessage(message);
    return CommandResult.SUCCESS;
}
Also used : LookupSetting(me.lucko.luckperms.api.LookupSetting) PermissionProcessor(me.lucko.luckperms.common.processors.PermissionProcessor) Contexts(me.lucko.luckperms.api.Contexts) MetaStackElement(me.lucko.luckperms.api.metastacking.MetaStackElement) LocaleManager(me.lucko.luckperms.common.locale.LocaleManager) SingleCommand(me.lucko.luckperms.common.command.abstraction.SingleCommand) HoverEvent(net.kyori.text.event.HoverEvent) GsonBuilder(com.google.gson.GsonBuilder) CommandSpec(me.lucko.luckperms.common.locale.command.CommandSpec) TextColor(net.kyori.text.format.TextColor) Gson(com.google.gson.Gson) ClickEvent(net.kyori.text.event.ClickEvent) Map(java.util.Map) Message(me.lucko.luckperms.common.locale.message.Message) BiConsumer(java.util.function.BiConsumer) LuckPermsPlugin(me.lucko.luckperms.common.plugin.LuckPermsPlugin) JObject(me.lucko.luckperms.common.utils.gson.JObject) Pastebin(me.lucko.luckperms.common.web.Pastebin) ProxiedContextCalculator(me.lucko.luckperms.common.contexts.ProxiedContextCalculator) Collection(java.util.Collection) PermissionCache(me.lucko.luckperms.common.caching.type.PermissionCache) Set(java.util.Set) Sender(me.lucko.luckperms.common.sender.Sender) UUID(java.util.UUID) StaticContextCalculator(me.lucko.luckperms.api.context.StaticContextCalculator) ContextSetJsonSerializer(me.lucko.luckperms.common.contexts.ContextSetJsonSerializer) TextComponent(net.kyori.text.TextComponent) JArray(me.lucko.luckperms.common.utils.gson.JArray) Collectors(java.util.stream.Collectors) CommandResult(me.lucko.luckperms.common.command.CommandResult) StandardPastebin(me.lucko.luckperms.common.web.StandardPastebin) MetaContexts(me.lucko.luckperms.api.caching.MetaContexts) MetaCache(me.lucko.luckperms.common.caching.type.MetaCache) CommandPermission(me.lucko.luckperms.common.command.access.CommandPermission) List(java.util.List) Component(net.kyori.text.Component) MetaStackDefinition(me.lucko.luckperms.api.metastacking.MetaStackDefinition) ContextCalculator(me.lucko.luckperms.api.context.ContextCalculator) User(me.lucko.luckperms.common.model.User) Predicates(me.lucko.luckperms.common.utils.Predicates) HoverEvent(net.kyori.text.event.HoverEvent) ClickEvent(net.kyori.text.event.ClickEvent) JObject(me.lucko.luckperms.common.utils.gson.JObject) TextComponent(net.kyori.text.TextComponent) Component(net.kyori.text.Component) Pastebin(me.lucko.luckperms.common.web.Pastebin) StandardPastebin(me.lucko.luckperms.common.web.StandardPastebin)

Example 60 with BiConsumer

use of java.util.function.BiConsumer in project kontraktor by RuedigerMoeller.

the class GeneratorTest method test.

@Test
public void test() {
    Generator generator = Actors.AsActor(Generator.class);
    try {
        generator.run().await(1000 * 1000l);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }
    try {
        generator.run().await(1 * 1000l);
        Assert.assertTrue(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // test outside actor thread
    BiConsumer<Long, Boolean> outside = (timout, expectTO) -> {
        // +1 == fin signal
        PromiseLatch finished = new PromiseLatch(5 * 5 + 1);
        generator.generate(100, (intarr, err) -> {
            if (!Actor.isErrorOrComplete(err)) {
                System.out.println("-> [" + intarr[0] + "," + intarr[1] + "]");
            }
            finished.countDown();
        });
        try {
            finished.getPromise().await(timout);
            if (expectTO)
                Assert.assertTrue(false);
        } catch (Exception e) {
            e.printStackTrace();
            if (!expectTO)
                Assert.assertTrue(false);
        }
    };
    outside.accept(1000l, true);
    outside.accept(100 * 1000l, false);
}
Also used : Assert(junit.framework.Assert) BiConsumer(java.util.function.BiConsumer) Test(org.junit.Test) org.nustaq.kontraktor(org.nustaq.kontraktor) PromiseLatch(org.nustaq.kontraktor.util.PromiseLatch) PromiseLatch(org.nustaq.kontraktor.util.PromiseLatch) Test(org.junit.Test)

Aggregations

BiConsumer (java.util.function.BiConsumer)255 Test (org.junit.Test)110 List (java.util.List)106 Map (java.util.Map)77 IOException (java.io.IOException)75 Consumer (java.util.function.Consumer)69 ArrayList (java.util.ArrayList)68 HashMap (java.util.HashMap)64 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)50 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Assert (org.junit.Assert)43 Function (java.util.function.Function)41 Optional (java.util.Optional)40 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35