Search in sources :

Example 1 with ArrayUtils.addAll

use of org.apache.commons.lang3.ArrayUtils.addAll in project cassandra by apache.

the class ForceRepairTest method force.

private void force(boolean includeDifference) throws IOException {
    long nowInMicro = System.currentTimeMillis() * 1000;
    try (Cluster cluster = Cluster.build(3).withConfig(c -> c.set("hinted_handoff_enabled", false).with(Feature.values())).start()) {
        init(cluster);
        cluster.schemaChange(withKeyspace("CREATE TABLE %s.tbl (k INT PRIMARY KEY, v INT)"));
        for (int i = 0; i < 10; i++) cluster.coordinator(1).execute(withKeyspace("INSERT INTO %s.tbl (k,v) VALUES (?, ?) USING TIMESTAMP ?"), ConsistencyLevel.ALL, i, i, nowInMicro++);
        ClusterUtils.stopUnchecked(cluster.get(2));
        // repair should fail because node2 is down
        IInvokableInstance node1 = cluster.get(1);
        for (String[] args : Arrays.asList(new String[] { "--full" }, new String[] { "--full", "--preview" }, // nothing should be in the repaired set, so shouldn't stream
        new String[] { "--full", "--validate" }, // IR Preview
        new String[] { "--preview" }, // nothing should be in the repaired set, so shouldn't stream
        new String[] { "--validate" }, // IR
        new String[0])) {
            if (includeDifference)
                // each loop should have a different timestamp, causing a new difference
                node1.executeInternal(withKeyspace("INSERT INTO %s.tbl (k,v) VALUES (?, ?) USING TIMESTAMP ?"), -1, -1, nowInMicro++);
            try {
                node1.nodetoolResult(ArrayUtils.addAll(new String[] { "repair", KEYSPACE }, args)).asserts().failure();
                node1.nodetoolResult(ArrayUtils.addAll(new String[] { "repair", KEYSPACE, "--force" }, args)).asserts().success();
                assertNoRepairedAt(cluster);
            } catch (Exception | Error e) {
                // tag the error to include which args broke
                e.addSuppressed(new AssertionError("Failure for args: " + Arrays.toString(args)));
                throw e;
            }
        }
        if (includeDifference) {
            SimpleQueryResult expected = QueryResults.builder().row(-1, -1).build();
            for (IInvokableInstance node : Arrays.asList(node1, cluster.get(3))) {
                SimpleQueryResult results = node.executeInternalWithResult(withKeyspace("SELECT * FROM %s.tbl WHERE k=?"), -1);
                expected.reset();
                AssertUtils.assertRows(results, expected);
            }
        }
    }
}
Also used : LongArrayList(com.carrotsearch.hppc.LongArrayList) Arrays(java.util.Arrays) Feature(org.apache.cassandra.distributed.api.Feature) ClusterUtils(org.apache.cassandra.distributed.shared.ClusterUtils) IOException(java.io.IOException) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Test(org.junit.Test) ConsistencyLevel(org.apache.cassandra.distributed.api.ConsistencyLevel) Collectors(java.util.stream.Collectors) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) Schema(org.apache.cassandra.schema.Schema) List(java.util.List) ColumnFamilyStore(org.apache.cassandra.db.ColumnFamilyStore) IInvokableInstance(org.apache.cassandra.distributed.api.IInvokableInstance) TestBaseImpl(org.apache.cassandra.distributed.test.TestBaseImpl) TableMetadata(org.apache.cassandra.schema.TableMetadata) SimpleQueryResult(org.apache.cassandra.distributed.api.SimpleQueryResult) Assertions(org.assertj.core.api.Assertions) Cluster(org.apache.cassandra.distributed.Cluster) QueryResults(org.apache.cassandra.distributed.api.QueryResults) StatsMetadata(org.apache.cassandra.io.sstable.metadata.StatsMetadata) View(org.apache.cassandra.db.lifecycle.View) AssertUtils(org.apache.cassandra.distributed.shared.AssertUtils) IInvokableInstance(org.apache.cassandra.distributed.api.IInvokableInstance) SimpleQueryResult(org.apache.cassandra.distributed.api.SimpleQueryResult) Cluster(org.apache.cassandra.distributed.Cluster) IOException(java.io.IOException)

Example 2 with ArrayUtils.addAll

use of org.apache.commons.lang3.ArrayUtils.addAll in project flink by apache.

the class StreamExecGroupWindowAggregate method translateToPlanInternal.

@SuppressWarnings("unchecked")
@Override
protected Transformation<RowData> translateToPlanInternal(PlannerBase planner, ExecNodeConfig config) {
    final boolean isCountWindow;
    if (window instanceof TumblingGroupWindow) {
        isCountWindow = hasRowIntervalType(((TumblingGroupWindow) window).size());
    } else if (window instanceof SlidingGroupWindow) {
        isCountWindow = hasRowIntervalType(((SlidingGroupWindow) window).size());
    } else {
        isCountWindow = false;
    }
    if (isCountWindow && grouping.length > 0 && config.getStateRetentionTime() < 0) {
        LOGGER.warn("No state retention interval configured for a query which accumulates state. " + "Please provide a query configuration with valid retention interval to prevent " + "excessive state size. You may specify a retention time of 0 to not clean up the state.");
    }
    final ExecEdge inputEdge = getInputEdges().get(0);
    final Transformation<RowData> inputTransform = (Transformation<RowData>) inputEdge.translateToPlan(planner);
    final RowType inputRowType = (RowType) inputEdge.getOutputType();
    final int inputTimeFieldIndex;
    if (isRowtimeAttribute(window.timeAttribute())) {
        inputTimeFieldIndex = timeFieldIndex(FlinkTypeFactory.INSTANCE().buildRelNodeRowType(inputRowType), planner.getRelBuilder(), window.timeAttribute());
        if (inputTimeFieldIndex < 0) {
            throw new TableException("Group window must defined on a time attribute, " + "but the time attribute can't be found.\n" + "This should never happen. Please file an issue.");
        }
    } else {
        inputTimeFieldIndex = -1;
    }
    final ZoneId shiftTimeZone = TimeWindowUtil.getShiftTimeZone(window.timeAttribute().getOutputDataType().getLogicalType(), config.getLocalTimeZone());
    final boolean[] aggCallNeedRetractions = new boolean[aggCalls.length];
    Arrays.fill(aggCallNeedRetractions, needRetraction);
    final AggregateInfoList aggInfoList = transformToStreamAggregateInfoList(inputRowType, JavaScalaConversionUtil.toScala(Arrays.asList(aggCalls)), aggCallNeedRetractions, needRetraction, // isStateBackendDataViews
    true, // needDistinctInfo
    true);
    final GeneratedClass<?> aggCodeGenerator = createAggsHandler(aggInfoList, config, planner.getRelBuilder(), inputRowType.getChildren(), shiftTimeZone);
    final LogicalType[] aggResultTypes = extractLogicalTypes(aggInfoList.getActualValueTypes());
    final LogicalType[] windowPropertyTypes = Arrays.stream(namedWindowProperties).map(p -> p.getProperty().getResultType()).toArray(LogicalType[]::new);
    final EqualiserCodeGenerator generator = new EqualiserCodeGenerator(ArrayUtils.addAll(aggResultTypes, windowPropertyTypes));
    final GeneratedRecordEqualiser equaliser = generator.generateRecordEqualiser("WindowValueEqualiser");
    final LogicalType[] aggValueTypes = extractLogicalTypes(aggInfoList.getActualValueTypes());
    final LogicalType[] accTypes = extractLogicalTypes(aggInfoList.getAccTypes());
    final int inputCountIndex = aggInfoList.getIndexOfCountStar();
    final WindowOperator<?, ?> operator = createWindowOperator(config, aggCodeGenerator, equaliser, accTypes, windowPropertyTypes, aggValueTypes, inputRowType.getChildren().toArray(new LogicalType[0]), inputTimeFieldIndex, shiftTimeZone, inputCountIndex);
    final OneInputTransformation<RowData, RowData> transform = ExecNodeUtil.createOneInputTransformation(inputTransform, createTransformationMeta(GROUP_WINDOW_AGGREGATE_TRANSFORMATION, config), operator, InternalTypeInfo.of(getOutputType()), inputTransform.getParallelism());
    // set KeyType and Selector for state
    final RowDataKeySelector selector = KeySelectorUtil.getRowDataSelector(grouping, InternalTypeInfo.of(inputRowType));
    transform.setStateKeySelector(selector);
    transform.setStateKeyType(selector.getProducedType());
    return transform;
}
Also used : AggregateUtil.isProctimeAttribute(org.apache.flink.table.planner.plan.utils.AggregateUtil.isProctimeAttribute) DataType(org.apache.flink.table.types.DataType) Arrays(java.util.Arrays) InputProperty(org.apache.flink.table.planner.plan.nodes.exec.InputProperty) JsonCreator(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator) LoggerFactory(org.slf4j.LoggerFactory) TumblingGroupWindow(org.apache.flink.table.planner.plan.logical.TumblingGroupWindow) FlinkTypeFactory(org.apache.flink.table.planner.calcite.FlinkTypeFactory) AggsHandlerCodeGenerator(org.apache.flink.table.planner.codegen.agg.AggsHandlerCodeGenerator) ExecNode(org.apache.flink.table.planner.plan.nodes.exec.ExecNode) SessionGroupWindow(org.apache.flink.table.planner.plan.logical.SessionGroupWindow) RelBuilder(org.apache.calcite.tools.RelBuilder) KeySelectorUtil(org.apache.flink.table.planner.plan.utils.KeySelectorUtil) Duration(java.time.Duration) AggregateUtil.toDuration(org.apache.flink.table.planner.plan.utils.AggregateUtil.toDuration) Preconditions.checkNotNull(org.apache.flink.util.Preconditions.checkNotNull) CodeGeneratorContext(org.apache.flink.table.planner.codegen.CodeGeneratorContext) SlidingGroupWindow(org.apache.flink.table.planner.plan.logical.SlidingGroupWindow) PlannerBase(org.apache.flink.table.planner.delegation.PlannerBase) GeneratedNamespaceTableAggsHandleFunction(org.apache.flink.table.runtime.generated.GeneratedNamespaceTableAggsHandleFunction) GeneratedNamespaceAggsHandleFunction(org.apache.flink.table.runtime.generated.GeneratedNamespaceAggsHandleFunction) ExecNodeConfig(org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig) RowDataKeySelector(org.apache.flink.table.runtime.keyselector.RowDataKeySelector) AggregateInfoList(org.apache.flink.table.planner.plan.utils.AggregateInfoList) WindowOperatorBuilder(org.apache.flink.table.runtime.operators.window.WindowOperatorBuilder) CountWindow(org.apache.flink.table.runtime.operators.window.CountWindow) JsonProperty(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty) ZoneId(java.time.ZoneId) List(java.util.List) InternalTypeInfo(org.apache.flink.table.runtime.typeutils.InternalTypeInfo) LogicalType(org.apache.flink.table.types.logical.LogicalType) Preconditions.checkArgument(org.apache.flink.util.Preconditions.checkArgument) AggregateUtil.transformToStreamAggregateInfoList(org.apache.flink.table.planner.plan.utils.AggregateUtil.transformToStreamAggregateInfoList) LogicalWindow(org.apache.flink.table.planner.plan.logical.LogicalWindow) TimeWindowUtil(org.apache.flink.table.runtime.util.TimeWindowUtil) WindowEmitStrategy(org.apache.flink.table.planner.plan.utils.WindowEmitStrategy) NamedWindowProperty(org.apache.flink.table.runtime.groupwindow.NamedWindowProperty) GeneratedClass(org.apache.flink.table.runtime.generated.GeneratedClass) AggregateUtil.hasTimeIntervalType(org.apache.flink.table.planner.plan.utils.AggregateUtil.hasTimeIntervalType) LogicalTypeDataTypeConverter(org.apache.flink.table.runtime.types.LogicalTypeDataTypeConverter) WindowOperator(org.apache.flink.table.runtime.operators.window.WindowOperator) AggregateUtil.isRowtimeAttribute(org.apache.flink.table.planner.plan.utils.AggregateUtil.isRowtimeAttribute) ArrayUtils(org.apache.commons.lang3.ArrayUtils) RowType(org.apache.flink.table.types.logical.RowType) ExecNodeUtil(org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil) AggregateUtil.isTableAggregate(org.apache.flink.table.planner.plan.utils.AggregateUtil.isTableAggregate) ReadableConfig(org.apache.flink.configuration.ReadableConfig) FieldReferenceExpression(org.apache.flink.table.expressions.FieldReferenceExpression) FlinkVersion(org.apache.flink.FlinkVersion) TimeWindow(org.apache.flink.table.runtime.operators.window.TimeWindow) ExecNodeContext(org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext) RowData(org.apache.flink.table.data.RowData) Logger(org.slf4j.Logger) ExecNodeMetadata(org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata) TableException(org.apache.flink.table.api.TableException) AggregateUtil.timeFieldIndex(org.apache.flink.table.planner.plan.utils.AggregateUtil.timeFieldIndex) ValueLiteralExpression(org.apache.flink.table.expressions.ValueLiteralExpression) OneInputTransformation(org.apache.flink.streaming.api.transformations.OneInputTransformation) EqualiserCodeGenerator(org.apache.flink.table.planner.codegen.EqualiserCodeGenerator) ExecEdge(org.apache.flink.table.planner.plan.nodes.exec.ExecEdge) AggregateUtil.hasRowIntervalType(org.apache.flink.table.planner.plan.utils.AggregateUtil.hasRowIntervalType) JavaScalaConversionUtil(org.apache.flink.table.planner.utils.JavaScalaConversionUtil) GeneratedRecordEqualiser(org.apache.flink.table.runtime.generated.GeneratedRecordEqualiser) AggregateCall(org.apache.calcite.rel.core.AggregateCall) AggregateUtil.toLong(org.apache.flink.table.planner.plan.utils.AggregateUtil.toLong) Transformation(org.apache.flink.api.dag.Transformation) WindowProperty(org.apache.flink.table.runtime.groupwindow.WindowProperty) Collections(java.util.Collections) OneInputTransformation(org.apache.flink.streaming.api.transformations.OneInputTransformation) Transformation(org.apache.flink.api.dag.Transformation) TableException(org.apache.flink.table.api.TableException) AggregateInfoList(org.apache.flink.table.planner.plan.utils.AggregateInfoList) AggregateUtil.transformToStreamAggregateInfoList(org.apache.flink.table.planner.plan.utils.AggregateUtil.transformToStreamAggregateInfoList) ExecEdge(org.apache.flink.table.planner.plan.nodes.exec.ExecEdge) ZoneId(java.time.ZoneId) RowType(org.apache.flink.table.types.logical.RowType) LogicalType(org.apache.flink.table.types.logical.LogicalType) EqualiserCodeGenerator(org.apache.flink.table.planner.codegen.EqualiserCodeGenerator) GeneratedRecordEqualiser(org.apache.flink.table.runtime.generated.GeneratedRecordEqualiser) RowData(org.apache.flink.table.data.RowData) TumblingGroupWindow(org.apache.flink.table.planner.plan.logical.TumblingGroupWindow) RowDataKeySelector(org.apache.flink.table.runtime.keyselector.RowDataKeySelector) SlidingGroupWindow(org.apache.flink.table.planner.plan.logical.SlidingGroupWindow)

Example 3 with ArrayUtils.addAll

use of org.apache.commons.lang3.ArrayUtils.addAll in project PixelmonPlaceholders by happyzleaf.

the class ParserUtility method parsePokedexInfo.

public static Object parsePokedexInfo(EnumPokemon pokemon, String[] values) throws NoValueException {
    if (values.length == 1) {
        return pokemon.name;
    }
    BaseStats stats = DatabaseStats.getBaseStats(pokemon.name).orElse(null);
    if (stats == null) {
        throw new RuntimeException("Could not find BaseStats for pokémon " + pokemon.name + ".");
    }
    switch(values[1]) {
        case "name":
            return pokemon.name;
        case "catchrate":
            return stats.catchRate;
        case "nationalid":
            return stats.nationalPokedexNumber;
        case "rarity":
            if (values.length == 3) {
                int rarity;
                switch(values[2]) {
                    case "day":
                        rarity = stats.rarity.day;
                        break;
                    case "night":
                        rarity = stats.rarity.night;
                        break;
                    case "dawndusk":
                        rarity = stats.rarity.dawndusk;
                        break;
                    default:
                        throw new NoValueException();
                }
                return rarity <= 0 ? EnumPokemon.legendaries.contains(pokemon.name) ? 0 : 1 : rarity;
            }
            break;
        case "postevolutions":
            /*
				 * "postevolutions" does not work how you might think.
				 * The post evolution of Bulbasaur is only Ivysaur, while the post evolutions of Eevee are all the eevolutions.
				 * The problem is that even if i'd like to add Venusaur to the post evolutions of Bulbasaur, after Ivysaur,
				 * i can't know it programmatically without doing any kind of human sacrifice,
				 * and i wound't know if i'd have to add them (the evolutions of an evolution) only if the post evolutions is one or so,
				 * cause, even if i'm sure that Umbreon does not have a post evolution,
				 * i'm putting a big limit to the OOP which should work regardless of the poke.
				 *
				 * Yeah, i'm sure no one will understand what i've wrote, but don't worry, i'm the choosen, i'm gonna fix it myself and you won't even notice.
				 */
            return asReadableList(values, 2, Arrays.stream(stats.evolutions).map(evolution -> evolution.to.name).toArray());
        case "preevolutions":
            return asReadableList(values, 2, stats.preEvolutions);
        case // Evolutions in order since 1.3.0
        "evolutions":
            // WHAT AM I DOING
            return asReadableList(values, 2, ArrayUtils.addAll(ArrayUtils.add(ArrayUtils.addAll(new Object[] {}, stats.preEvolutions), pokemon.name), Arrays.stream(stats.evolutions).map(evolution -> evolution.to.name).toArray()));
        case "ability":
            if (values.length == 3) {
                String value1 = values[2];
                int ability = value1.equals("1") ? 0 : value1.equals("2") ? 1 : value1.equalsIgnoreCase("h") ? 2 : -1;
                if (ability != -1) {
                    String result = stats.abilities[ability];
                    return result == null ? PPConfig.noneText : result;
                }
            }
            break;
        case "abilities":
            return asReadableList(values, 2, stats.abilities);
        // Since 1.2.0
        case "biomes":
            return asReadableList(values, 2, Arrays.stream(stats.biomeIDs).map(id -> Biome.getBiome(id).getBiomeName()).toArray());
        case "spawnlocations":
            return asReadableList(values, 2, stats.spawnLocations);
        case // 1.2.2
        "doesevolve":
            return stats.evolutions.length != 0;
        case // 1.2.2
        "evolutionscount":
            return stats.evolutions.length;
        case // Modified in 1.2.2
        "evolution":
            if (values.length >= 3) {
                int evolution;
                try {
                    evolution = Integer.parseInt(values[2]) - 1;
                } catch (NumberFormatException e) {
                    throw new NoValueException();
                }
                if (stats.evolutions.length <= 0) {
                    throw new NoValueException();
                }
                if (stats.evolutions.length <= evolution) {
                    return "Does not evolve.";
                } else {
                    Evolution evol = stats.evolutions[evolution];
                    if (values.length < 4) {
                        return stats.evolutions[evolution].to.name;
                    } else {
                        // Drastically changed since 1.3.0
                        String choice = values[3];
                        if (choice.equals("list")) {
                            // TODO write better
                            List<String> conditions = new ArrayList<>();
                            for (Map.Entry<String, EvoParser> entry : evoParsers.entrySet()) {
                                for (EvoCondition cond : evol.conditions) {
                                    if (cond.getClass().equals(entry.getValue().clazz)) {
                                        conditions.add(entry.getKey());
                                    }
                                }
                            }
                            if (!conditions.contains("level") && evol instanceof LevelingEvolution) {
                                conditions.add("level");
                            }
                            return asReadableList(values, 4, conditions.toArray());
                        } else {
                            try {
                                EvoParser parser = evoParsers.get(values[3]);
                                if (parser == null)
                                    throw new NoValueException();
                                EvoCondition cond = null;
                                for (EvoCondition c : evol.conditions) {
                                    if (c.getClass().equals(parser.clazz)) {
                                        cond = c;
                                    }
                                }
                                if (cond == null) {
                                    if (values[3].equals("level") && evol instanceof LevelingEvolution) {
                                        return ((LevelingEvolution) evol).level;
                                    }
                                    throw new NoValueException();
                                }
                                try {
                                    // noinspection unchecked
                                    return parser.parse(cond, values, 4);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            } catch (NoValueException e) {
                                return PPConfig.evolutionNotAvailableText;
                            }
                        }
                    }
                }
            }
            break;
        case "type":
            return asReadableList(values, 2, stats.getTypeList().toArray());
        case "basestats":
            if (values.length >= 3) {
                switch(values[2]) {
                    case "hp":
                        return stats.hp;
                    case "atk":
                        return stats.attack;
                    case "def":
                        return stats.defence;
                    case "spa":
                        return stats.spAtt;
                    case "spd":
                        return stats.spDef;
                    case "spe":
                        return stats.speed;
                    case "yield":
                        if (values.length >= 4) {
                            EVsStore yield = stats.evGain;
                            switch(values[3]) {
                                case "hp":
                                    return yield.HP;
                                case "atk":
                                    return yield.Attack;
                                case "def":
                                    return yield.Defence;
                                case "spa":
                                    return yield.SpecialAttack;
                                case "spd":
                                    return yield.SpecialDefence;
                                case "spe":
                                    return yield.Speed;
                            }
                        }
                        break;
                    case "yields":
                        EVsStore yield = stats.evGain;
                        return yield.HP + yield.Attack + yield.Defence + yield.SpecialAttack + yield.SpecialDefence + yield.Speed;
                }
            }
            break;
        case "drops":
            if (values.length >= 3) {
                PokemonDropInformation drops = pokemonDrops.get(pokemon);
                if (drops == null) {
                    return PPConfig.noneText;
                } else {
                    try {
                        switch(values[2]) {
                            case "main":
                                return getItemStackInfo((ItemStack) mainDrop.get(drops));
                            case "rare":
                                return getItemStackInfo((ItemStack) rareDrop.get(drops));
                            case "optional1":
                                return getItemStackInfo((ItemStack) optDrop1.get(drops));
                            case "optional2":
                                return getItemStackInfo((ItemStack) optDrop2.get(drops));
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            break;
        case "egggroups":
            return asReadableList(values, 2, stats.eggGroups);
        case // Since 1.2.3
        "texturelocation":
            return "pixelmon:sprites/pokemon/" + String.format("%03d", stats.nationalPokedexNumber);
        case // Since 1.3.0
        "move":
            if (values.length >= 3) {
                try {
                    List<Attack> attacks = DatabaseMoves.getAllAttacks(stats.nationalPokedexNumber);
                    int attack = Integer.parseInt(values[2]) - 1;
                    if (attack >= 0 && attack < attacks.size()) {
                        return attacks.get(attack);
                    } else {
                        return PPConfig.moveNotAvailableText;
                    }
                } catch (NumberFormatException ignored) {
                }
            }
            break;
        case "moves":
            return asReadableList(values, 2, DatabaseMoves.getAllAttacks(stats.nationalPokedexNumber).stream().map(attack -> attack.baseAttack.getLocalizedName()).toArray());
    }
    throw new NoValueException();
}
Also used : java.util(java.util) ArrayUtils(org.apache.commons.lang3.ArrayUtils) NoValueException(me.rojo8399.placeholderapi.NoValueException) com.pixelmonmod.pixelmon.entities.pixelmon.stats(com.pixelmonmod.pixelmon.entities.pixelmon.stats) PPConfig(com.github.happyzleaf.pixelmonplaceholders.PPConfig) ItemStack(net.minecraft.item.ItemStack) DatabaseMoves(com.pixelmonmod.pixelmon.database.DatabaseMoves) Attack(com.pixelmonmod.pixelmon.battles.attacks.Attack) WeatherType(com.pixelmonmod.pixelmon.api.world.WeatherType) PokemonDropInformation(com.pixelmonmod.pixelmon.entities.npcs.registry.PokemonDropInformation) Nullable(javax.annotation.Nullable) DatabaseStats(com.pixelmonmod.pixelmon.database.DatabaseStats) LevelingEvolution(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.types.LevelingEvolution) World(net.minecraft.world.World) DecimalFormat(java.text.DecimalFormat) EnumPokemon(com.pixelmonmod.pixelmon.enums.EnumPokemon) EnumType(com.pixelmonmod.pixelmon.enums.EnumType) Evolution(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.Evolution) Field(java.lang.reflect.Field) EntityPixelmon(com.pixelmonmod.pixelmon.entities.pixelmon.EntityPixelmon) PlayerStorage(com.pixelmonmod.pixelmon.storage.PlayerStorage) DropItemRegistry(com.pixelmonmod.pixelmon.entities.npcs.registry.DropItemRegistry) Player(org.spongepowered.api.entity.living.player.Player) com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.conditions(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.conditions) Biome(net.minecraft.world.biome.Biome) LevelingEvolution(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.types.LevelingEvolution) PokemonDropInformation(com.pixelmonmod.pixelmon.entities.npcs.registry.PokemonDropInformation) Attack(com.pixelmonmod.pixelmon.battles.attacks.Attack) NoValueException(me.rojo8399.placeholderapi.NoValueException) LevelingEvolution(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.types.LevelingEvolution) Evolution(com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.Evolution)

Example 4 with ArrayUtils.addAll

use of org.apache.commons.lang3.ArrayUtils.addAll in project narchy by automenta.

the class Taskify method test.

/**
 * note: the return value here shouldnt matter so just return true anyway
 */
@Override
public boolean test(Derivation d) {
    Truth tru = d.concTruth;
    if (tru != null) {
        float finalEvi = tru.evi() * d.concEviFactor;
        if (d.eviMin > finalEvi) {
            d.use(Param.TTL_EVI_INSUFFICIENT);
            return true;
        }
        tru = tru.withEvi(finalEvi);
    }
    Term x0 = d.derivedTerm.get();
    Term x = d.anon.get(x0).normalize();
    long[] occ = d.concOcc;
    byte punc = d.concPunc;
    assert (punc != 0) : "no punctuation assigned";
    DerivedTask t = (DerivedTask) Task.tryTask(x, punc, tru, (C, tr) -> {
        int dither = d.ditherTime;
        long start = Tense.dither(occ[0], dither);
        long end = Tense.dither(occ[1], dither);
        assert (end >= start) : "task has reversed occurrence: " + start + ".." + end;
        return Param.DEBUG ? new DebugDerivedTask(C, punc, tr, start, end, d) : new DerivedTask(C, punc, tr, start, end, d);
    });
    if (t == null) {
        d.nar.emotion.deriveFailTaskify.increment();
        return spam(d, Param.TTL_DERIVE_TASK_FAIL);
    }
    if (same(t, d._task, d.freqRes) || (d._belief != null && same(t, d._belief, d.freqRes))) {
        d.nar.emotion.deriveFailParentDuplicate.increment();
        return spam(d, Param.TTL_DERIVE_TASK_SAME);
    }
    if (d.single)
        t.setCyclic(true);
    float priority = d.deriver.prioritize.pri(t, d);
    if (priority != priority) {
        d.nar.emotion.deriveFailPrioritize.increment();
        return spam(d, Param.TTL_DERIVE_TASK_PRIORITIZE);
    }
    t.priSet(priority);
    t.cause = ArrayUtils.addAll(d.parentCause, channel.id);
    if (d.add(t) != t) {
        d.nar.emotion.deriveFailDerivationDuplicate.increment();
        spam(d, Param.TTL_DERIVE_TASK_REPEAT);
    } else {
        if (Param.DEBUG)
            t.log(channel.ruleString);
        d.use(Param.TTL_DERIVE_TASK_SUCCESS);
    }
    return true;
}
Also used : DebugDerivedTask(nars.task.DebugDerivedTask) Tense(nars.time.Tense) Logger(org.slf4j.Logger) DerivedTask(nars.task.DerivedTask) FILTER_SIMILAR_DERIVATIONS(nars.Param.FILTER_SIMILAR_DERIVATIONS) LoggerFactory(org.slf4j.LoggerFactory) ArrayUtils(org.apache.commons.lang3.ArrayUtils) BOOL(nars.Op.BOOL) nars.$(nars.$) Util(jcog.Util) NALTask(nars.task.NALTask) Param(nars.Param) AbstractPred(nars.term.pred.AbstractPred) Task(nars.Task) Truth(nars.truth.Truth) VAR_PATTERN(nars.Op.VAR_PATTERN) Term(nars.term.Term) Term(nars.term.Term) DebugDerivedTask(nars.task.DebugDerivedTask) DerivedTask(nars.task.DerivedTask) DebugDerivedTask(nars.task.DebugDerivedTask) Truth(nars.truth.Truth)

Example 5 with ArrayUtils.addAll

use of org.apache.commons.lang3.ArrayUtils.addAll in project gridss by PapenfussLab.

the class KmerEvidence method create.

public static KmerEvidence create(int k, SingleReadEvidence sre) {
    if (!sre.isBreakendExact()) {
        throw new NotImplementedException("reassembly of XNX placeholder contigs");
    }
    byte[] aseq = sre.getAnchorSequence();
    byte[] beseq = sre.getBreakendSequence();
    byte[] aqual = sre.getAnchorQuality();
    byte[] bequal = sre.getBreakendQuality();
    byte[] seq;
    byte[] qual;
    BreakendSummary bs = sre.getBreakendSummary();
    int positionOffset;
    int firstAnchoredBase;
    int anchoredBases = aseq.length;
    if (bs.direction == BreakendDirection.Forward) {
        seq = ArrayUtils.addAll(aseq, beseq);
        qual = ArrayUtils.addAll(aqual, bequal);
        positionOffset = -(aseq.length - 1);
        firstAnchoredBase = 0;
    } else {
        seq = ArrayUtils.addAll(beseq, aseq);
        qual = ArrayUtils.addAll(bequal, aqual);
        firstAnchoredBase = beseq.length;
        positionOffset = -beseq.length;
    }
    if (k > seq.length) {
        return null;
    }
    return new KmerEvidence(sre, bs.start + positionOffset, bs.end + positionOffset, k, firstAnchoredBase, firstAnchoredBase + anchoredBases - (k - 1), seq, qual, false, false, sre.getBreakendQual());
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) BreakendSummary(au.edu.wehi.idsv.BreakendSummary)

Aggregations

ArrayUtils (org.apache.commons.lang3.ArrayUtils)6 Arrays (java.util.Arrays)3 List (java.util.List)3 IOException (java.io.IOException)2 Collections (java.util.Collections)2 Collectors (java.util.stream.Collectors)2 BreakendSummary (au.edu.wehi.idsv.BreakendSummary)1 LongArrayList (com.carrotsearch.hppc.LongArrayList)1 PPConfig (com.github.happyzleaf.pixelmonplaceholders.PPConfig)1 WeatherType (com.pixelmonmod.pixelmon.api.world.WeatherType)1 Attack (com.pixelmonmod.pixelmon.battles.attacks.Attack)1 DatabaseMoves (com.pixelmonmod.pixelmon.database.DatabaseMoves)1 DatabaseStats (com.pixelmonmod.pixelmon.database.DatabaseStats)1 DropItemRegistry (com.pixelmonmod.pixelmon.entities.npcs.registry.DropItemRegistry)1 PokemonDropInformation (com.pixelmonmod.pixelmon.entities.npcs.registry.PokemonDropInformation)1 EntityPixelmon (com.pixelmonmod.pixelmon.entities.pixelmon.EntityPixelmon)1 com.pixelmonmod.pixelmon.entities.pixelmon.stats (com.pixelmonmod.pixelmon.entities.pixelmon.stats)1 Evolution (com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.Evolution)1 com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.conditions (com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.conditions)1 LevelingEvolution (com.pixelmonmod.pixelmon.entities.pixelmon.stats.evolution.types.LevelingEvolution)1