file_id
int64 1
180k
| content
stringlengths 13
357k
| repo
stringlengths 6
109
| path
stringlengths 6
1.15k
|
---|---|---|---|
179,692 | // Targeted by JavaCPP version 1.5.10: DO NOT EDIT THIS FILE
package org.bytedeco.gsl;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.gsl.global.gsl.*;
@Properties(inherit = org.bytedeco.gsl.presets.gsl.class)
public class gsl_monte_vegas_state extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public gsl_monte_vegas_state() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public gsl_monte_vegas_state(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public gsl_monte_vegas_state(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public gsl_monte_vegas_state position(long position) {
return (gsl_monte_vegas_state)super.position(position);
}
@Override public gsl_monte_vegas_state getPointer(long i) {
return new gsl_monte_vegas_state((Pointer)this).offsetAddress(i);
}
/* grid */
public native @Cast("size_t") long dim(); public native gsl_monte_vegas_state dim(long setter);
public native @Cast("size_t") long bins_max(); public native gsl_monte_vegas_state bins_max(long setter);
public native @Cast("unsigned int") int bins(); public native gsl_monte_vegas_state bins(int setter);
public native @Cast("unsigned int") int boxes(); public native gsl_monte_vegas_state boxes(int setter); /* these are both counted along the axes */
public native DoublePointer xi(); public native gsl_monte_vegas_state xi(DoublePointer setter);
public native DoublePointer xin(); public native gsl_monte_vegas_state xin(DoublePointer setter);
public native DoublePointer delx(); public native gsl_monte_vegas_state delx(DoublePointer setter);
public native DoublePointer weight(); public native gsl_monte_vegas_state weight(DoublePointer setter);
public native double vol(); public native gsl_monte_vegas_state vol(double setter);
public native DoublePointer x(); public native gsl_monte_vegas_state x(DoublePointer setter);
public native IntPointer bin(); public native gsl_monte_vegas_state bin(IntPointer setter);
public native IntPointer box(); public native gsl_monte_vegas_state box(IntPointer setter);
/* distribution */
public native DoublePointer d(); public native gsl_monte_vegas_state d(DoublePointer setter);
/* control variables */
public native double alpha(); public native gsl_monte_vegas_state alpha(double setter);
public native int mode(); public native gsl_monte_vegas_state mode(int setter);
public native int verbose(); public native gsl_monte_vegas_state verbose(int setter);
public native @Cast("unsigned int") int iterations(); public native gsl_monte_vegas_state iterations(int setter);
public native int stage(); public native gsl_monte_vegas_state stage(int setter);
/* scratch variables preserved between calls to vegas1/2/3 */
public native double jac(); public native gsl_monte_vegas_state jac(double setter);
public native double wtd_int_sum(); public native gsl_monte_vegas_state wtd_int_sum(double setter);
public native double sum_wgts(); public native gsl_monte_vegas_state sum_wgts(double setter);
public native double chi_sum(); public native gsl_monte_vegas_state chi_sum(double setter);
public native double chisq(); public native gsl_monte_vegas_state chisq(double setter);
public native double result(); public native gsl_monte_vegas_state result(double setter);
public native double sigma(); public native gsl_monte_vegas_state sigma(double setter);
public native @Cast("unsigned int") int it_start(); public native gsl_monte_vegas_state it_start(int setter);
public native @Cast("unsigned int") int it_num(); public native gsl_monte_vegas_state it_num(int setter);
public native @Cast("unsigned int") int samples(); public native gsl_monte_vegas_state samples(int setter);
public native @Cast("unsigned int") int calls_per_box(); public native gsl_monte_vegas_state calls_per_box(int setter);
public native FILE ostream(); public native gsl_monte_vegas_state ostream(FILE setter);
}
| bytedeco/javacpp-presets | gsl/src/gen/java/org/bytedeco/gsl/gsl_monte_vegas_state.java |
179,693 | /**
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.concurrency.limits.limit;
import com.netflix.concurrency.limits.MetricIds;
import com.netflix.concurrency.limits.MetricRegistry;
import com.netflix.concurrency.limits.MetricRegistry.SampleListener;
import com.netflix.concurrency.limits.internal.EmptyMetricRegistry;
import com.netflix.concurrency.limits.internal.Preconditions;
import com.netflix.concurrency.limits.limit.functions.Log10RootFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* Limiter based on TCP Vegas where the limit increases by alpha if the queue_use is small ({@literal <} alpha)
* and decreases by alpha if the queue_use is large ({@literal >} beta).
*
* Queue size is calculated using the formula,
* queue_use = limit − BWE×RTTnoLoad = limit × (1 − RTTnoLoad/RTTactual)
*
* For traditional TCP Vegas alpha is typically 2-3 and beta is typically 4-6. To allow for better growth and
* stability at higher limits we set alpha=Max(3, 10% of the current limit) and beta=Max(6, 20% of the current limit)
*/
public class VegasLimit extends AbstractLimit {
private static final Logger LOG = LoggerFactory.getLogger(VegasLimit.class);
private static final Function<Integer, Integer> LOG10 = Log10RootFunction.create(0);
public static class Builder {
private int initialLimit = 20;
private int maxConcurrency = 1000;
private MetricRegistry registry = EmptyMetricRegistry.INSTANCE;
private double smoothing = 1.0;
private Function<Integer, Integer> alphaFunc = (limit) -> 3 * LOG10.apply(limit.intValue());
private Function<Integer, Integer> betaFunc = (limit) -> 6 * LOG10.apply(limit.intValue());
private Function<Integer, Integer> thresholdFunc = (limit) -> LOG10.apply(limit.intValue());
private Function<Double, Double> increaseFunc = (limit) -> limit + LOG10.apply(limit.intValue());
private Function<Double, Double> decreaseFunc = (limit) -> limit - LOG10.apply(limit.intValue());
private int probeMultiplier = 30;
private Builder() {
}
/**
* The limiter will probe for a new noload RTT every probeMultiplier * current limit
* iterations. Default value is 30.
* @param probeMultiplier
* @return Chainable builder
*/
public Builder probeMultiplier(int probeMultiplier) {
this.probeMultiplier = probeMultiplier;
return this;
}
public Builder alpha(int alpha) {
this.alphaFunc = (ignore) -> alpha;
return this;
}
public Builder threshold(Function<Integer, Integer> threshold) {
this.thresholdFunc = threshold;
return this;
}
public Builder alpha(Function<Integer, Integer> alpha) {
this.alphaFunc = alpha;
return this;
}
public Builder beta(int beta) {
this.betaFunc = (ignore) -> beta;
return this;
}
public Builder beta(Function<Integer, Integer> beta) {
this.betaFunc = beta;
return this;
}
public Builder increase(Function<Double, Double> increase) {
this.increaseFunc = increase;
return this;
}
public Builder decrease(Function<Double, Double> decrease) {
this.decreaseFunc = decrease;
return this;
}
public Builder smoothing(double smoothing) {
this.smoothing = smoothing;
return this;
}
public Builder initialLimit(int initialLimit) {
this.initialLimit = initialLimit;
return this;
}
@Deprecated
public Builder tolerance(double tolerance) {
return this;
}
public Builder maxConcurrency(int maxConcurrency) {
this.maxConcurrency = maxConcurrency;
return this;
}
@Deprecated
public Builder backoffRatio(double ratio) {
return this;
}
public Builder metricRegistry(MetricRegistry registry) {
this.registry = registry;
return this;
}
public VegasLimit build() {
if (initialLimit > maxConcurrency) {
LOG.warn("Initial limit {} exceeded maximum limit {}", initialLimit, maxConcurrency);
}
return new VegasLimit(this);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static VegasLimit newDefault() {
return newBuilder().build();
}
/**
* Estimated concurrency limit based on our algorithm
*/
private volatile double estimatedLimit;
private volatile long rtt_noload = 0;
/**
* Maximum allowed limit providing an upper bound failsafe
*/
private final int maxLimit;
private final double smoothing;
private final Function<Integer, Integer> alphaFunc;
private final Function<Integer, Integer> betaFunc;
private final Function<Integer, Integer> thresholdFunc;
private final Function<Double, Double> increaseFunc;
private final Function<Double, Double> decreaseFunc;
private final SampleListener rttSampleListener;
private final int probeMultiplier;
private int probeCount = 0;
private double probeJitter;
private VegasLimit(Builder builder) {
super(builder.initialLimit);
this.estimatedLimit = builder.initialLimit;
this.maxLimit = builder.maxConcurrency;
this.alphaFunc = builder.alphaFunc;
this.betaFunc = builder.betaFunc;
this.increaseFunc = builder.increaseFunc;
this.decreaseFunc = builder.decreaseFunc;
this.thresholdFunc = builder.thresholdFunc;
this.smoothing = builder.smoothing;
this.probeMultiplier = builder.probeMultiplier;
resetProbeJitter();
this.rttSampleListener = builder.registry.distribution(MetricIds.MIN_RTT_NAME);
}
private void resetProbeJitter() {
probeJitter = ThreadLocalRandom.current().nextDouble(0.5, 1);
}
private boolean shouldProbe() {
return probeJitter * probeMultiplier * estimatedLimit <= probeCount;
}
@Override
protected int _update(long startTime, long rtt, int inflight, boolean didDrop) {
Preconditions.checkArgument(rtt > 0, "rtt must be >0 but got " + rtt);
probeCount++;
if (shouldProbe()) {
LOG.debug("Probe MinRTT {}", TimeUnit.NANOSECONDS.toMicros(rtt) / 1000.0);
resetProbeJitter();
probeCount = 0;
rtt_noload = rtt;
return (int)estimatedLimit;
}
if (rtt_noload == 0 || rtt < rtt_noload) {
LOG.debug("New MinRTT {}", TimeUnit.NANOSECONDS.toMicros(rtt) / 1000.0);
rtt_noload = rtt;
return (int)estimatedLimit;
}
rttSampleListener.addSample(rtt_noload);
return updateEstimatedLimit(rtt, inflight, didDrop);
}
private int updateEstimatedLimit(long rtt, int inflight, boolean didDrop) {
final int queueSize = (int) Math.ceil(estimatedLimit * (1 - (double)rtt_noload / rtt));
double newLimit;
// Treat any drop (i.e timeout) as needing to reduce the limit
if (didDrop) {
newLimit = decreaseFunc.apply(estimatedLimit);
// Prevent upward drift if not close to the limit
} else if (inflight * 2 < estimatedLimit) {
return (int)estimatedLimit;
} else {
int alpha = alphaFunc.apply((int)estimatedLimit);
int beta = betaFunc.apply((int)estimatedLimit);
int threshold = this.thresholdFunc.apply((int)estimatedLimit);
// Aggressive increase when no queuing
if (queueSize <= threshold) {
newLimit = estimatedLimit + beta;
// Increase the limit if queue is still manageable
} else if (queueSize < alpha) {
newLimit = increaseFunc.apply(estimatedLimit);
// Detecting latency so decrease
} else if (queueSize > beta) {
newLimit = decreaseFunc.apply(estimatedLimit);
// We're within he sweet spot so nothing to do
} else {
return (int)estimatedLimit;
}
}
newLimit = Math.max(1, Math.min(maxLimit, newLimit));
newLimit = (1 - smoothing) * estimatedLimit + smoothing * newLimit;
if ((int)newLimit != (int)estimatedLimit && LOG.isDebugEnabled()) {
LOG.debug("New limit={} minRtt={} ms winRtt={} ms queueSize={}",
(int)newLimit,
TimeUnit.NANOSECONDS.toMicros(rtt_noload) / 1000.0,
TimeUnit.NANOSECONDS.toMicros(rtt) / 1000.0,
queueSize);
}
estimatedLimit = newLimit;
return (int)estimatedLimit;
}
@Override
public String toString() {
return "VegasLimit [limit=" + getLimit() +
", rtt_noload=" + TimeUnit.NANOSECONDS.toMicros(rtt_noload) / 1000.0 +
" ms]";
}
}
| Netflix/concurrency-limits | concurrency-limits-core/src/main/java/com/netflix/concurrency/limits/limit/VegasLimit.java |
179,694 | package magic.ai;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import magic.model.MagicGame;
import magic.model.MagicGameLog;
import magic.model.MagicPlayer;
import magic.model.event.MagicEvent;
public class VegasAI extends MagicAI {
private static final long SEC_TO_NANO=1000000000L;
private final boolean CHEAT;
VegasAI(final boolean cheat) {
CHEAT = cheat;
}
private void log(final String message) {
MagicGameLog.log(message);
}
@Override
public Object[] findNextEventChoiceResults(final MagicGame sourceGame,final MagicPlayer scorePlayer) {
final long startTime = System.currentTimeMillis();
final MagicGame choiceGame=new MagicGame(sourceGame,scorePlayer);
if (!CHEAT) {
choiceGame.hideHiddenCards();
}
final MagicEvent event=choiceGame.getNextEvent();
final List<Object[]> choiceResultsList=event.getArtificialChoiceResults(choiceGame);
// No choices
final int size=choiceResultsList.size();
if (size==0) {
throw new RuntimeException("No choice results");
}
// Single choice
if (size==1) {
return sourceGame.map(choiceResultsList.get(0));
}
// Multiple choices
final ExecutorService executor = Executors.newFixedThreadPool(getMaxThreads());
final List<VegasScore> scores= new ArrayList<>();
final int artificialLevel = scorePlayer.getAiProfile().getAiLevel();
final int rounds = (size + getMaxThreads() - 1) / getMaxThreads();
final long slice = artificialLevel * SEC_TO_NANO / rounds;
for (final Object[] choiceResults : choiceResultsList) {
final VegasScore score=new VegasScore(choiceResults);
scores.add(score);
executor.execute(new VegasWorker(
CHEAT,
choiceGame,
score,
slice
));
}
executor.shutdown();
try { //await termination
executor.awaitTermination(artificialLevel + 1,TimeUnit.SECONDS);
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
} finally {
// force termination of workers
executor.shutdownNow();
}
// Return best choice
VegasScore bestScore=scores.get(0);
for (final VegasScore score : scores) {
if (score.getScore() > bestScore.getScore()) {
bestScore = score;
}
}
// Logging.
final long timeTaken = System.currentTimeMillis() - startTime;
log("VEGAS" +
" cheat=" + CHEAT +
" index=" + scorePlayer.getIndex() +
" life=" + scorePlayer.getLife() +
" phase=" + sourceGame.getPhase().getType() +
" slice=" + (slice/1000000) +
" time=" + timeTaken
);
for (final VegasScore score : scores) {
log((score == bestScore ? "* " : " ") + score);
}
return sourceGame.map(bestScore.getChoiceResults());
}
}
| magarena/magarena | src/magic/ai/VegasAI.java |
179,695 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Camunda License 1.0. You may not use this file
* except in compliance with the Camunda License 1.0.
*/
package io.camunda.zeebe.broker.system.configuration.backpressure;
import com.netflix.concurrency.limits.Limit;
import com.netflix.concurrency.limits.limit.FixedLimit;
import com.netflix.concurrency.limits.limit.Gradient2Limit;
import com.netflix.concurrency.limits.limit.GradientLimit;
import com.netflix.concurrency.limits.limit.VegasLimit;
import com.netflix.concurrency.limits.limit.WindowedLimit;
import io.camunda.zeebe.broker.system.configuration.ConfigurationEntry;
import io.camunda.zeebe.broker.transport.backpressure.StabilizingAIMDLimit;
import java.util.concurrent.TimeUnit;
public final class LimitCfg implements ConfigurationEntry {
private boolean enabled = true;
private boolean useWindowed = true;
private LimitAlgorithm algorithm = LimitAlgorithm.AIMD;
private final AIMDCfg aimd = new AIMDCfg();
private final FixedCfg fixed = new FixedCfg();
private final VegasCfg vegas = new VegasCfg();
private final GradientCfg gradient = new GradientCfg();
private final Gradient2Cfg gradient2 = new Gradient2Cfg();
private final LegacyVegasCfg legacyVegas = new LegacyVegasCfg();
public boolean isEnabled() {
return enabled;
}
public LimitCfg setEnabled(final boolean enabled) {
this.enabled = enabled;
return this;
}
public boolean useWindowed() {
return useWindowed;
}
public void setUseWindowed(final boolean useWindowed) {
this.useWindowed = useWindowed;
}
public LimitAlgorithm getAlgorithm() {
return algorithm;
}
public void setAlgorithm(final String algorithm) {
this.algorithm = LimitAlgorithm.valueOf(algorithm.toUpperCase());
}
public void setAlgorithm(LimitAlgorithm algorithm) {
this.algorithm = algorithm;
}
public AIMDCfg getAimd() {
return aimd;
}
public FixedCfg getFixed() {
return fixed;
}
public VegasCfg getVegas() {
return vegas;
}
public GradientCfg getGradient() {
return gradient;
}
public Gradient2Cfg getGradient2() {
return gradient2;
}
public LegacyVegasCfg getLegacyVegas() {
return legacyVegas;
}
@Override
public String toString() {
return "LimitCfg{"
+ "enabled="
+ enabled
+ ", useWindowed="
+ useWindowed
+ ", algorithm='"
+ algorithm
+ '\''
+ ", aimd="
+ aimd
+ ", fixed="
+ fixed
+ ", vegas="
+ vegas
+ ", gradient="
+ gradient
+ ", gradient2="
+ gradient2
+ ", legacyVegas="
+ legacyVegas
+ '}';
}
/**
* @return null if disabled, (windowed) limit otherwise.
*/
public Limit buildLimit() {
if (!enabled) {
return null;
}
final var baseLimit =
switch (getAlgorithm()) {
case AIMD -> getAIMD(getAimd());
case FIXED -> FixedLimit.of(getFixed().getLimit());
case GRADIENT -> getGradientLimit(getGradient());
case GRADIENT2 -> getGradient2Limit(getGradient2());
case VEGAS -> getVegasLimit(getVegas());
case LEGACY_VEGAS -> getLegacyVegasLimit(getLegacyVegas());
};
if (useWindowed) {
return WindowedLimit.newBuilder().build(baseLimit);
} else {
return baseLimit;
}
}
private static VegasLimit getLegacyVegasLimit(final LegacyVegasCfg legacyVegas) {
return VegasLimit.newBuilder()
.alpha(limit -> Math.max(3, (int) (limit * legacyVegas.alphaLimit())))
.beta(limit -> Math.max(6, (int) (limit * legacyVegas.betaLimit())))
.initialLimit(legacyVegas.initialLimit())
.maxConcurrency(legacyVegas.getMaxConcurrency())
// per default Vegas uses log10
.increase(limit -> limit + Math.log(limit))
.decrease(limit -> limit - Math.log(limit))
.build();
}
private static VegasLimit getVegasLimit(final VegasCfg vegasCfg) {
return VegasLimit.newBuilder()
.alpha(vegasCfg.getAlpha())
.beta(vegasCfg.getBeta())
.initialLimit(vegasCfg.getInitialLimit())
.build();
}
private static Gradient2Limit getGradient2Limit(final Gradient2Cfg gradient2Cfg) {
return Gradient2Limit.newBuilder()
.rttTolerance(gradient2Cfg.getRttTolerance())
.initialLimit(gradient2Cfg.getInitialLimit())
.minLimit(gradient2Cfg.getMinLimit())
.longWindow(gradient2Cfg.getLongWindow())
.build();
}
private static GradientLimit getGradientLimit(final GradientCfg gradientCfg) {
return GradientLimit.newBuilder()
.minLimit(gradientCfg.getMinLimit())
.initialLimit(gradientCfg.getInitialLimit())
.rttTolerance(gradientCfg.getRttTolerance())
.build();
}
private static StabilizingAIMDLimit getAIMD(final AIMDCfg aimdCfg) {
return StabilizingAIMDLimit.newBuilder()
.initialLimit(aimdCfg.getInitialLimit())
.minLimit(aimdCfg.getMinLimit())
.maxLimit(aimdCfg.getMaxLimit())
.expectedRTT(aimdCfg.getRequestTimeout().toMillis(), TimeUnit.MILLISECONDS)
.backoffRatio(aimdCfg.getBackoffRatio())
.build();
}
public enum LimitAlgorithm {
VEGAS,
GRADIENT,
GRADIENT2,
FIXED,
AIMD,
LEGACY_VEGAS,
}
}
| camunda/zeebe | zeebe/broker/src/main/java/io/camunda/zeebe/broker/system/configuration/backpressure/LimitCfg.java |
179,696 | package constants.id;
import java.util.stream.IntStream;
public class ItemId {
// Misc
public static final int PENDANT_OF_THE_SPIRIT = 1122017;
public static final int HEART_SHAPED_CHOCOLATE = 5110000;
public static final int HAPPY_BIRTHDAY = 2022153;
public static final int FISHING_CHAIR = 3011000;
public static final int MINI_GAME_BASE = 4080000;
public static final int MATCH_CARDS = 4080100;
public static final int MAGICAL_MITTEN = 1472063;
public static final int RPS_CERTIFICATE_BASE = 4031332;
public static final int GOLDEN_MAPLE_LEAF = 4000313;
public static final int PERFECT_PITCH = 4310000;
public static final int MAGIC_ROCK = 4006000;
public static final int GOLDEN_CHICKEN_EFFECT = 4290000;
public static final int BUMMER_EFFECT = 4290001;
public static final int ARPQ_SHIELD = 2022269;
public static final int ROARING_TIGER_MESSENGER = 5390006;
public static boolean isExpIncrease(int itemId) {
return itemId >= 2022450 && itemId <= 2022452;
}
public static boolean isRateCoupon(int itemId) {
int itemType = itemId / 1000;
return itemType == 5211 || itemType == 5360;
}
public static boolean isMonsterCard(int itemId) {
int itemType = itemId / 10000;
return itemType == 238;
}
public static boolean isPyramidBuff(int itemId) {
return (itemId >= 2022585 && itemId <= 2022588) || (itemId >= 2022616 && itemId <= 2022617);
}
public static boolean isDojoBuff(int itemId) {
return itemId >= 2022359 && itemId <= 2022421;
}
// Potion
public static final int WHITE_POTION = 2000002;
public static final int BLUE_POTION = 2000003;
public static final int ORANGE_POTION = 2000001;
public static final int MANA_ELIXIR = 2000006;
// HP/MP recovery
public static final int SORCERERS_POTION = 2022337;
public static final int RUSSELLONS_PILLS = 2022198;
// Environment
public static final int RED_BEAN_PORRIDGE = 2022001;
public static final int SOFT_WHITE_BUN = 2022186;
public static final int AIR_BUBBLE = 2022040;
// Chair
public static final int RELAXER = 3010000;
private static final int CHAIR_MIN = RELAXER;
private static final int CHAIR_MAX = FISHING_CHAIR;
public static boolean isChair(int itemId) {
return itemId >= CHAIR_MIN && itemId <= CHAIR_MAX;
// alt: return itemId / 10000 == 301;
}
// Throwing star
public static final int SUBI_THROWING_STARS = 2070000;
public static final int HWABI_THROWING_STARS = 2070007;
public static final int BALANCED_FURY = 2070018;
public static final int CRYSTAL_ILBI_THROWING_STARS = 2070016;
private static final int THROWING_STAR_MIN = SUBI_THROWING_STARS;
private static final int THROWING_STAR_MAX = 2070016;
public static final int DEVIL_RAIN_THROWING_STAR = 2070014;
public static int[] allThrowingStarIds() {
return IntStream.range(THROWING_STAR_MIN, THROWING_STAR_MAX + 1).toArray();
}
// Bullet
public static final int BULLET = 2330000;
private static final int BULLET_MIN = BULLET;
private static final int BULLET_MAX = 2330005;
public static final int BLAZE_CAPSULE = 2331000;
public static final int GLAZE_CAPSULE = 2332000;
public static int[] allBulletIds() {
return IntStream.range(BULLET_MIN, BULLET_MAX + 1).toArray();
}
// Starter
public static final int BEGINNERS_GUIDE = 4161001;
public static final int LEGENDS_GUIDE = 4161048;
public static final int NOBLESSE_GUIDE = 4161047;
// Warrior
public static final int RED_HWARANG_SHIRT = 1040021;
public static final int BLACK_MARTIAL_ARTS_PANTS = 1060016;
public static final int MITHRIL_BATTLE_GRIEVES = 1072039;
public static final int GLADIUS = 1302008;
public static final int MITHRIL_POLE_ARM = 1442001;
public static final int MITHRIL_MAUL = 1422001;
public static final int FIREMANS_AXE = 1312005;
public static final int DARK_ENGRIT = 1051010;
// Bowman
public static final int GREEN_HUNTERS_ARMOR = 1040067;
public static final int GREEN_HUNTRESS_ARMOR = 1041054;
public static final int GREEN_HUNTERS_PANTS = 1060056;
public static final int GREEN_HUNTRESS_PANTS = 1061050;
public static final int GREEN_HUNTER_BOOTS = 1072081;
public static final int RYDEN = 1452005;
public static final int MOUNTAIN_CROSSBOW = 1462000;
// Magician
public static final int BLUE_WIZARD_ROBE = 1050003;
public static final int PURPLE_FAIRY_TOP = 1041041;
public static final int PURPLE_FAIRY_SKIRT = 1061034;
public static final int RED_MAGICSHOES = 1072075;
public static final int MITHRIL_WAND = 1372003;
public static final int CIRCLE_WINDED_STAFF = 1382017;
// Thief
public static final int DARK_BROWN_STEALER = 1040057;
public static final int RED_STEAL = 1041047;
public static final int DARK_BROWN_STEALER_PANTS = 1060043;
public static final int RED_STEAL_PANTS = 1061043;
public static final int BRONZE_CHAIN_BOOTS = 1072032;
public static final int STEEL_GUARDS = 1472008;
public static final int REEF_CLAW = 1332012;
// Pirate
public static final int BROWN_PAULIE_BOOTS = 1072294;
public static final int PRIME_HANDS = 1482004;
public static final int COLD_MIND = 1492004;
public static final int BROWN_POLLARD = 1052107;
// Three snails
public static final int SNAIL_SHELL = 4000019;
public static final int BLUE_SNAIL_SHELL = 4000000;
public static final int RED_SNAIL_SHELL = 4000016;
// Special scroll
public static final int COLD_PROTECTION_SCROLl = 2041058;
public static final int SPIKES_SCROLL = 2040727;
public static final int VEGAS_SPELL_10 = 5610000;
public static final int VEGAS_SPELL_60 = 5610001;
public static final int CHAOS_SCROll_60 = 2049100;
public static final int LIAR_TREE_SAP = 2049101;
public static final int MAPLE_SYRUP = 2049102;
public static final int WHITE_SCROLL = 2340000;
public static final int CLEAN_SLATE_1 = 2049000;
public static final int CLEAN_SLATE_3 = 2049001;
public static final int CLEAN_SLATE_5 = 2049002;
public static final int CLEAN_SLATE_20 = 2049003;
public static final int RING_STR_100_SCROLL = 2041100;
public static final int DRAGON_STONE_SCROLL = 2041200;
public static final int BELT_STR_100_SCROLL = 2041300;
// Cure debuff
public static final int ALL_CURE_POTION = 2050004;
public static final int EYEDROP = 2050001;
public static final int TONIC = 2050002;
public static final int HOLY_WATER = 2050003;
public static final int ANTI_BANISH_SCROLL = 2030100;
private static final int DOJO_PARTY_ALL_CURE = 2022433;
private static final int CARNIVAL_PARTY_ALL_CURE = 2022163;
public static final int WHITE_ELIXIR = 2022544;
public static boolean isPartyAllCure(int itemId) {
return itemId == DOJO_PARTY_ALL_CURE || itemId == CARNIVAL_PARTY_ALL_CURE;
}
// Special effect
public static final int PHARAOHS_BLESSING_1 = 2022585;
public static final int PHARAOHS_BLESSING_2 = 2022586;
public static final int PHARAOHS_BLESSING_3 = 2022587;
public static final int PHARAOHS_BLESSING_4 = 2022588;
// Evolve pet
public static final int DRAGON_PET = 5000028;
public static final int ROBO_PET = 5000047;
// Pet equip
public static final int MESO_MAGNET = 1812000;
public static final int ITEM_POUCH = 1812001;
public static final int ITEM_IGNORE = 1812007;
public static boolean isPet(int itemId) {
return itemId / 1000 == 5000;
}
// Expirable pet
public static final int PET_SNAIL = 5000054;
// Permanent pet
private static final int PERMA_PINK_BEAN = 5000060;
private static final int PERMA_KINO = 5000100;
private static final int PERMA_WHITE_TIGER = 5000101;
private static final int PERMA_MINI_YETI = 5000102;
public static int[] getPermaPets() {
return new int[]{PERMA_PINK_BEAN, PERMA_KINO, PERMA_WHITE_TIGER, PERMA_MINI_YETI};
}
// Maker
public static final int BASIC_MONSTER_CRYSTAL_1 = 4260000;
public static final int BASIC_MONSTER_CRYSTAL_2 = 4260001;
public static final int BASIC_MONSTER_CRYSTAL_3 = 4260002;
public static final int INTERMEDIATE_MONSTER_CRYSTAL_1 = 4260003;
public static final int INTERMEDIATE_MONSTER_CRYSTAL_2 = 4260004;
public static final int INTERMEDIATE_MONSTER_CRYSTAL_3 = 4260005;
public static final int ADVANCED_MONSTER_CRYSTAL_1 = 4260006;
public static final int ADVANCED_MONSTER_CRYSTAL_2 = 4260007;
public static final int ADVANCED_MONSTER_CRYSTAL_3 = 4260008;
// NPC weather (PQ)
public static final int NPC_WEATHER_GROWLIE = 5120016; // Henesys PQ
// Safety charm
public static final int SAFETY_CHARM = 5130000;
public static final int EASTER_BASKET = 4031283;
public static final int EASTER_CHARM = 4140903;
// Engagement box
public static final int ENGAGEMENT_BOX_MOONSTONE = 2240000;
public static final int ENGAGEMENT_BOX_STAR = 2240001;
public static final int ENGAGEMENT_BOX_GOLDEN = 2240002;
public static final int ENGAGEMENT_BOX_SILVER = 2240003;
public static final int EMPTY_ENGAGEMENT_BOX_MOONSTONE = 4031357;
public static final int ENGAGEMENT_RING_MOONSTONE = 4031358;
public static final int EMPTY_ENGAGEMENT_BOX_STAR = 4031359;
public static final int ENGAGEMENT_RING_STAR = 4031360;
public static final int EMPTY_ENGAGEMENT_BOX_GOLDEN = 4031361;
public static final int ENGAGEMENT_RING_GOLDEN = 4031362;
public static final int EMPTY_ENGAGEMENT_BOX_SILVER = 4031363;
public static final int ENGAGEMENT_RING_SILVER = 4031364;
public static boolean isWeddingToken(int itemId) {
return itemId >= ItemId.EMPTY_ENGAGEMENT_BOX_MOONSTONE && itemId <= ItemId.ENGAGEMENT_RING_SILVER;
}
// Wedding etc
public static final int PARENTS_BLESSING = 4031373;
public static final int OFFICIATORS_PERMISSION = 4031374;
public static final int ONYX_CHEST_FOR_COUPLE = 4031424;
// Wedding ticket
public static final int NORMAL_WEDDING_TICKET_CATHEDRAL = 5251000;
public static final int NORMAL_WEDDING_TICKET_CHAPEL = 5251001;
public static final int PREMIUM_WEDDING_TICKET_CHAPEL = 5251002;
public static final int PREMIUM_WEDDING_TICKET_CATHEDRAL = 5251003;
// Wedding reservation
public static final int PREMIUM_CATHEDRAL_RESERVATION_RECEIPT = 4031375;
public static final int PREMIUM_CHAPEL_RESERVATION_RECEIPT = 4031376;
public static final int NORMAL_CATHEDRAL_RESERVATION_RECEIPT = 4031480;
public static final int NORMAL_CHAPEL_RESERVATION_RECEIPT = 4031481;
// Wedding invite
public static final int INVITATION_CHAPEL = 4031377;
public static final int INVITATION_CATHEDRAL = 4031395;
public static final int RECEIVED_INVITATION_CHAPEL = 4031406;
public static final int RECEIVED_INVITATION_CATHEDRAL = 4031407;
public static final int CARAT_RING_BASE = 1112300; // Unsure about math on this and the following one
public static final int CARAT_RING_BOX_BASE = 2240004;
private static final int CARAT_RING_BOX_MAX = 2240015;
public static final int ENGAGEMENT_BOX_MIN = ENGAGEMENT_BOX_MOONSTONE;
public static final int ENGAGEMENT_BOX_MAX = CARAT_RING_BOX_MAX;
// Wedding ring
public static final int WEDDING_RING_MOONSTONE = 1112803;
public static final int WEDDING_RING_STAR = 1112806;
public static final int WEDDING_RING_GOLDEN = 1112807;
public static final int WEDDING_RING_SILVER = 1112809;
public static boolean isWeddingRing(int itemId) {
return itemId == WEDDING_RING_MOONSTONE || itemId == WEDDING_RING_STAR ||
itemId == WEDDING_RING_GOLDEN || itemId == WEDDING_RING_SILVER;
}
// Priority buff
public static final int ROSE_SCENT = 2022631;
public static final int FREESIA_SCENT = 2022632;
public static final int LAVENDER_SCENT = 2022633;
// Cash shop
public static final int WHEEL_OF_FORTUNE = 5510000;
public static final int CASH_SHOP_SURPRISE = 5222000;
public static final int EXP_COUPON_2X_4H = 5211048;
public static final int DROP_COUPON_2X_4H = 5360042;
public static final int EXP_COUPON_3X_2H = 5211060;
public static final int QUICK_DELIVERY_TICKET = 5330000;
public static final int CHALKBOARD_1 = 5370000;
public static final int CHALKBOARD_2 = 5370001;
public static final int REMOTE_GACHAPON_TICKET = 5451000;
public static final int AP_RESET = 5050000;
public static final int NAME_CHANGE = 5400000;
public static final int WORLD_TRANSFER = 5401000;
public static final int MAPLE_LIFE_B = 5432000;
public static final int VICIOUS_HAMMER = 5570000;
public static final int NX_CARD_100 = 4031865;
public static final int NX_CARD_250 = 4031866;
public static boolean isNxCard(int itemId) {
return itemId == NX_CARD_100 || itemId == NX_CARD_250;
}
// Face expression
private static final int FACE_EXPRESSION_MIN = 5160000;
private static final int FACE_EXPRESSION_MAX = 5160014;
public static boolean isFaceExpression(int itemId) {
return itemId >= FACE_EXPRESSION_MIN && itemId <= FACE_EXPRESSION_MAX;
}
// New Year card
public static final int NEW_YEARS_CARD = 2160101;
public static final int NEW_YEARS_CARD_SEND = 4300000;
public static final int NEW_YEARS_CARD_RECEIVED = 4301000;
// Popular owl items
private static final int WORK_GLOVES = 1082002;
private static final int STEELY_THROWING_KNIVES = 2070005;
private static final int ILBI_THROWING_STARS = 2070006;
private static final int OWL_BALL_MASK = 1022047;
private static final int PINK_ADVENTURER_CAPE = 1102041;
private static final int CLAW_30_SCROLL = 2044705;
private static final int HELMET_60_ACC_SCROLL = 2040017;
private static final int MAPLE_SHIELD = 1092030;
private static final int GLOVES_ATT_60_SCROLL = 2040804;
public static int[] getOwlItems() {
return new int[]{WORK_GLOVES, STEELY_THROWING_KNIVES, ILBI_THROWING_STARS, OWL_BALL_MASK, PINK_ADVENTURER_CAPE,
CLAW_30_SCROLL, WHITE_SCROLL, HELMET_60_ACC_SCROLL, MAPLE_SHIELD, GLOVES_ATT_60_SCROLL};
}
// Henesys PQ
public static final int GREEN_PRIMROSE_SEED = 4001095;
public static final int PURPLE_PRIMROSE_SEED = 4001096;
public static final int PINK_PRIMROSE_SEED = 4001097;
public static final int BROWN_PRIMROSE_SEED = 4001098;
public static final int YELLOW_PRIMROSE_SEED = 4001099;
public static final int BLUE_PRIMROSE_SEED = 4001100;
public static final int MOON_BUNNYS_RICE_CAKE = 4001101;
// Catch mobs items
public static final int PHEROMONE_PERFUME = 2270000;
public static final int POUCH = 2270001;
public static final int GHOST_SACK = 4031830;
public static final int ARPQ_ELEMENT_ROCK = 2270002;
public static final int ARPQ_SPIRIT_JEWEL = 4031868;
public static final int MAGIC_CANE = 2270003;
public static final int TAMED_RUDOLPH = 4031887;
public static final int TRANSPARENT_MARBLE_1 = 2270005;
public static final int MONSTER_MARBLE_1 = 2109001;
public static final int TRANSPARENT_MARBLE_2 = 2270006;
public static final int MONSTER_MARBLE_2 = 2109002;
public static final int TRANSPARENT_MARBLE_3 = 2270007;
public static final int MONSTER_MARBLE_3 = 2109003;
public static final int EPQ_PURIFICATION_MARBLE = 2270004;
public static final int EPQ_MONSTER_MARBLE = 4001169;
public static final int FISH_NET = 2270008;
public static final int FISH_NET_WITH_A_CATCH = 2022323;
// Mount
public static final int BATTLESHIP = 1932000;
// Explorer mount
public static final int HOG = 1902000;
private static final int SILVER_MANE = 1902001;
private static final int RED_DRACO = 1902002;
private static final int EXPLORER_SADDLE = 1912000;
public static boolean isExplorerMount(int itemId) {
return itemId >= HOG && itemId <= RED_DRACO || itemId == EXPLORER_SADDLE;
}
// Cygnus mount
private static final int MIMIANA = 1902005;
private static final int MIMIO = 1902006;
private static final int SHINJOU = 1902007;
private static final int CYGNUS_SADDLE = 1912005;
public static boolean isCygnusMount(int itemId) {
return itemId >= MIMIANA && itemId <= SHINJOU || itemId == CYGNUS_SADDLE;
}
// Dev equips
public static final int GREEN_HEADBAND = 1002067;
public static final int TIMELESS_NIBLEHEIM = 1402046;
public static final int BLUE_KORBEN = 1082140;
public static final int MITHRIL_PLATINE_PANTS = 1060091;
public static final int BLUE_CARZEN_BOOTS = 1072154;
public static final int MITHRIL_PLATINE = 1040103;
}
| P0nk/Cosmic | src/main/java/constants/id/ItemId.java |
179,697 | // Targeted by JavaCPP version 1.5.10: DO NOT EDIT THIS FILE
package org.bytedeco.gsl;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.gsl.global.gsl.*;
@Properties(inherit = org.bytedeco.gsl.presets.gsl.class)
public class gsl_monte_vegas_params extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public gsl_monte_vegas_params() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public gsl_monte_vegas_params(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public gsl_monte_vegas_params(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public gsl_monte_vegas_params position(long position) {
return (gsl_monte_vegas_params)super.position(position);
}
@Override public gsl_monte_vegas_params getPointer(long i) {
return new gsl_monte_vegas_params((Pointer)this).offsetAddress(i);
}
public native double alpha(); public native gsl_monte_vegas_params alpha(double setter);
public native @Cast("size_t") long iterations(); public native gsl_monte_vegas_params iterations(long setter);
public native int stage(); public native gsl_monte_vegas_params stage(int setter);
public native int mode(); public native gsl_monte_vegas_params mode(int setter);
public native int verbose(); public native gsl_monte_vegas_params verbose(int setter);
public native FILE ostream(); public native gsl_monte_vegas_params ostream(FILE setter);
}
| bytedeco/javacpp-presets | gsl/src/gen/java/org/bytedeco/gsl/gsl_monte_vegas_params.java |
179,698 | package chapter5.section3;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 24/02/18.
*/
public class Exercise12 {
public class RabinKarpLasVegas extends RabinKarp {
RabinKarpLasVegas(String pattern) {
super(pattern, false);
}
@Override
protected boolean check(String text, int textIndex) {
for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
if (pattern.charAt(patternIndex) != text.charAt(textIndex + patternIndex)) {
return false;
}
}
return true;
}
}
public static void main(String[] args) {
Exercise12 exercise12 = new Exercise12();
String text = "abacadabrabracabracadabrabrabracad";
String pattern1 = "abracadabra";
RabinKarpLasVegas rabinKarpLasVegas1 = exercise12.new RabinKarpLasVegas(pattern1);
int index1 = rabinKarpLasVegas1.search(text);
StdOut.println("Index 1: " + index1 + " Expected: 14");
String pattern2 = "rab";
RabinKarpLasVegas rabinKarpLasVegas2 = exercise12.new RabinKarpLasVegas(pattern2);
int index2 = rabinKarpLasVegas2.search(text);
StdOut.println("Index 2: " + index2 + " Expected: 8");
String pattern3 = "bcara";
RabinKarpLasVegas rabinKarpLasVegas3 = exercise12.new RabinKarpLasVegas(pattern3);
int index3 = rabinKarpLasVegas3.search(text);
StdOut.println("Index 3: " + index3 + " Expected: 34");
String pattern4 = "rabrabracad";
RabinKarpLasVegas rabinKarpLasVegas4 = exercise12.new RabinKarpLasVegas(pattern4);
int index4 = rabinKarpLasVegas4.search(text);
StdOut.println("Index 4: " + index4 + " Expected: 23");
String pattern5 = "abacad";
RabinKarpLasVegas rabinKarpLasVegas5 = exercise12.new RabinKarpLasVegas(pattern5);
int index5 = rabinKarpLasVegas5.search(text);
StdOut.println("Index 5: " + index5 + " Expected: 0");
}
}
| reneargento/algorithms-sedgewick-wayne | src/chapter5/section3/Exercise12.java |
179,699 | package com.baeldung.jsonjava;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;
public class CDLDemo {
public static void main(String[] args) {
System.out.println("8.1. Producing JSONArray Directly from Comma Delimited Text: ");
jsonArrayFromCDT();
System.out.println("\n8.2. Producing Comma Delimited Text from JSONArray: ");
cDTfromJSONArray();
System.out.println("\n8.3.1. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
System.out.println("\n8.3.2. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
}
public static void jsonArrayFromCDT() {
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
System.out.println(ja);
}
public static void cDTfromJSONArray() {
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
System.out.println(cdt);
}
public static void jaOfJOFromCDT() {
String string =
"name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
System.out.println(result.toString());
}
public static void jaOfJOFromCDT2() {
JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");
String string =
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
System.out.println(result.toString());
}
}
| eugenp/tutorials | json-modules/json/src/main/java/com/baeldung/jsonjava/CDLDemo.java |
179,700 |
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Random;
import org.chicago.cases.AbstractOptionsCase;
import org.chicago.cases.AbstractOptionsCase.OptionsCase;
import org.chicago.cases.options.OptionSignals.ForecastMessage;
import org.chicago.cases.options.OptionSignals.RiskMessage;
import org.chicago.cases.options.OptionSignals.VolUpdate;
import org.chicago.cases.options.OrderInfo;
import org.chicago.cases.options.OrderInfo.OrderSide;
import org.chicago.cases.options.Optionsutil;
import com.optionscity.freeway.api.IDB;
import com.optionscity.freeway.api.IJobSetup;
import com.optionscity.freeway.api.InstrumentDetails;
/*
* This is a barebones sample of a OptionCase implementation. This sample is "working", however.
* This means that you can launch Freeway, upload this job, and run it against the provided sample data.
*
* Your team will need to provide your own implementation of this case.
*/
public class MIT2Options extends AbstractOptionsCase implements OptionsCase {
private IDB myDatabase;
int factor;
private List<String> knownSymbols = new ArrayList<String>();
//Option prices and greeks
private HashMap<String, Double[]> prices = new HashMap<String, Double[]>();
private HashMap<String, Double> deltas = new HashMap<String, Double>();
private HashMap<String, Double> gammas = new HashMap<String, Double>();
private HashMap<String, Double> vegas = new HashMap<String, Double>();
private HashMap<String, Double> ratios = new HashMap<String, Double>();
//current time
private double tick = 100.0;
//pricing
private double rate = 0.01;
//vol
private double vol = 0.0;
//current positions
private double portfolioVega = 0;
private double portfolioGamma = 0;
private double portfolioDelta = 0;
//limits
private double minDelta = 0;
private double maxDelta = 0;
private double minGamma = 0;
private double maxGamma = 0;
private double minVega = 0;
private double maxVega = 0;
//forecast
private double forecastDelta = 0;
private double forecastGamma = 0;
private double forecastVega = 0;
//order queue
ArrayList<OrderInfo> orders = new ArrayList<OrderInfo>();
//random number generator
private Random randomGenerator = new Random();
//initialization flag
private boolean initialized = false;
public void addVariables(IJobSetup setup) {
setup.addVariable("someFactor", "factor used to adjust something", "int", "2");
}
public void initializeAlgo(IDB database) {
// Databases can be used to store data between rounds
myDatabase = database;
// helper method for accessing declared variables
factor = getIntVar("someFactor");
}
public void newBidAsk(String idSymbol, double bid, double ask) {
if (knownSymbols.contains(idSymbol) == false) {
knownSymbols.add(idSymbol);
}
prices.put(idSymbol, new Double[] {bid, ask});
//log("I received a new bid of " + bid + ", and ask of " + ask + ", for " + idSymbol);
/*
if (prices.keySet().contains("MIT2~RAND-E")) {
log("The bid of the underlier is currently" + Double.toString((prices.get("MIT2~RAND-E")[0])));
log("The ask of the underlier is currently" + Double.toString(prices.get("MIT2~RAND-E")[1]));
}*/
}
public void orderFilled(int volume, double fillPrice) {
log("My order was filled with qty of " + volume + " at a price of " + fillPrice);
}
public void newRiskMessage(RiskMessage msg) {
minDelta = msg.minDelta;
maxDelta = msg.maxDelta;
minVega = msg.minVega;
maxVega = msg.maxVega;
minGamma = msg.minGamma;
maxGamma = msg.maxGamma;
if (knownSymbols.size() > 10) {
this.optimizePortfolio();
}
}
public void newForecastMessage(ForecastMessage msg) {
log("I received a forecast message!");
forecastDelta = msg.delta;
forecastVega = msg.vega;
forecastGamma = msg.gamma;
}
public void newVolUpdate(VolUpdate msg) {
vol = msg.impliedVol;
tick -= 1.0;
if (knownSymbols.size() > 10) {
initialized = true;
//log("WENT TRUE");
}
if (initialized == true) {
this.updateOptionGreeks();
this.optimizePortfolio();
}
//log("Updated volatility forecast");
}
public void penaltyFill(String idSymbol, double price, int quantity) {
log("Penalty called...oh no!");
}
public OrderInfo[] placeOrders() {
log("Placing orders");
OrderInfo[] liveOrders = new OrderInfo[orders.size()];
log(String.valueOf(orders.size()));
for (int i = 0; i < orders.size(); i++) {
liveOrders[i] = orders.get(i);
}
orders.clear();
return liveOrders;
}
public void orderFilled(String idSymbol, double price, int quantity) {
if (idSymbol.equals("MIT2~RAND-E")) {
portfolioDelta += quantity;
log("DELTA: " + String.valueOf(portfolioDelta));
}
else {
//update portfolio greeks based on new position
InstrumentDetails details = instruments().getInstrumentDetails(idSymbol);
double spot = (prices.get("MIT2~RAND-E")[0] + prices.get("MIT2~RAND-E")[1])/2.0;
portfolioDelta += quantity * Optionsutil.calculateDelta(spot, details.strikePrice, tick/365.0, rate, vol);
portfolioVega += quantity * Optionsutil.calculateVega(spot, details.strikePrice, tick/365.0, rate, vol);
portfolioGamma += quantity * Optionsutil.calculateGamma(spot, details.strikePrice, tick/365.0, rate, vol);
//hedge
this.hedge();
if (!idSymbol.equals("MIT2~RAND-E")) {
//log("My order for " + idSymbol + " got filled at " + price + " with quantity of " + quantity);
}
//log("DELTA: " + String.valueOf(portfolioDelta) + " | VEGA: " + String.valueOf(portfolioVega) + " | GAMMA: " + String.valueOf(portfolioGamma));
//log("FORECAST_DELTA: " + String.valueOf(forecastDelta) + " | FORECAST_VEGA: " + String.valueOf(forecastVega) + " | FORECAST_GAMMA: " + String.valueOf(forecastGamma));
}
}
public void updateOptionGreeks() {
for (int i=0; i < knownSymbols.size(); i++) {
if (!knownSymbols.get(i).equals("MIT2~RAND-E")) {
InstrumentDetails details = instruments().getInstrumentDetails(knownSymbols.get(i));
double spot = (prices.get("MIT2~RAND-E")[0] + prices.get("MIT2~RAND-E")[1])/2.0;
double gamma = Optionsutil.calculateGamma(spot, details.strikePrice, tick/365.0, rate, vol);
double vega = Optionsutil.calculateVega(spot, details.strikePrice, tick/365.0, rate, vol);
double normalizedGamma = gamma/(maxGamma-minGamma);
double normalizedVega = vega/(maxVega-minVega);
deltas.put(knownSymbols.get(i), Optionsutil.calculateDelta(spot, details.strikePrice, tick/365.0, rate, vol));
gammas.put(knownSymbols.get(i), gamma);
vegas.put(knownSymbols.get(i), vega);
ratios.put(knownSymbols.get(i), normalizedGamma/normalizedVega);
}
}
}
public void optimizePortfolio() {
log("OPTIMIZING");
//get all option names
ArrayList<String> optionNames = new ArrayList<String>();
for (int i=0; i < knownSymbols.size(); i++) {
if (!knownSymbols.get(i).equals("MIT2~RAND-E")) {
optionNames.add(knownSymbols.get(i));
}
}
this.hedge();
//put vega and gamma within limits
if (portfolioVega > minVega && portfolioVega < maxVega) {
double maxRatio = 0.0;
int maxIndex = 0;
//find max ratio
for (int i=0; i< optionNames.size(); i++) {
double ratio = ratios.get(optionNames.get(i));
if (ratio > maxRatio) {
maxRatio = ratio;
maxIndex = i;
}
}
String bestRatioOption = optionNames.get(maxIndex);
if (portfolioGamma > maxGamma) {
double gammaDifference = portfolioGamma - (maxGamma*0.99999);
double optionGamma = gammas.get(bestRatioOption);
orders.add(new OrderInfo(bestRatioOption, OrderSide.SELL, 0.00001, (int)Math.ceil(gammaDifference/optionGamma)));
}
else if (portfolioGamma < minGamma) {
double gammaDifference = (minGamma*1.00001) - portfolioGamma;
double optionGamma = gammas.get(bestRatioOption);
orders.add(new OrderInfo(bestRatioOption, OrderSide.BUY, 10000.0, (int)Math.ceil(gammaDifference/optionGamma)));
}
}
else if (portfolioGamma > minGamma && portfolioGamma < maxGamma) {
double minRatio = 0.0;
int minIndex = 0;
//find min ratio
for (int i=0; i< optionNames.size(); i++) {
double ratio = ratios.get(optionNames.get(i));
if (ratio < minRatio) {
minRatio = ratio;
minIndex = i;
}
}
String bestRatioOption = optionNames.get(minIndex);
if (portfolioVega > maxVega) {
double vegaDifference = portfolioVega - (maxVega*0.99999);
double optionVega = vegas.get(bestRatioOption);
orders.add(new OrderInfo(bestRatioOption, OrderSide.SELL, 0.0001, (int)Math.ceil(vegaDifference/optionVega)));
}
else if (portfolioVega < minVega) {
double vegaDifference = (minVega*1.00001) - portfolioVega;
double optionVega = vegas.get(bestRatioOption);
orders.add(new OrderInfo(bestRatioOption, OrderSide.BUY, 10000.0, (int)Math.ceil(vegaDifference/optionVega)));
}
}
else if (portfolioGamma > maxGamma && portfolioVega > maxVega) {
double normalizedGammaOvershoot = (portfolioGamma - maxGamma)/(maxGamma-minGamma);
double normalizedVegaOvershoot = (portfolioVega - maxVega)/(maxVega-minVega);
double overshootGammaVegaRatio = normalizedGammaOvershoot/normalizedVegaOvershoot;
double bestRatioDiff = 1000000000;
int bestIndex = 0;
//find best ratio
for (int i=0; i< optionNames.size(); i++) {
double ratio = ratios.get(optionNames.get(i));
if (Math.abs((ratio - overshootGammaVegaRatio)) < bestRatioDiff) {
bestRatioDiff = ratio - overshootGammaVegaRatio;
bestIndex = i;
}
}
String bestRatioOption = optionNames.get(bestIndex);
double vegaDifference = portfolioVega - (maxVega*0.9999);
double optionVega = vegas.get(bestRatioOption);
double gammaDifference = portfolioGamma - (maxGamma*0.9999);
double optionGamma = vegas.get(bestRatioOption);
double numVegaOptions = Math.ceil(vegaDifference/optionVega);
double numGammaOptions = Math.ceil(gammaDifference/optionGamma);
orders.add(new OrderInfo(bestRatioOption, OrderSide.SELL, 0.0001, (int)Math.max(numVegaOptions, numGammaOptions)));
}
else if (portfolioGamma < minGamma && portfolioVega < minVega) {
double normalizedGammaOvershoot = (minGamma - portfolioGamma)/(maxGamma-minGamma);
double normalizedVegaOvershoot = (minVega - portfolioVega)/(maxVega-minVega);
double overshootGammaVegaRatio = normalizedGammaOvershoot/normalizedVegaOvershoot;
double bestRatioDiff = 1000000000;
int bestIndex = 0;
//find best ratio
for (int i=0; i< optionNames.size(); i++) {
double ratio = ratios.get(optionNames.get(i));
if (Math.abs((ratio - overshootGammaVegaRatio)) < bestRatioDiff) {
bestRatioDiff = ratio - overshootGammaVegaRatio;
bestIndex = i;
}
}
String bestRatioOption = optionNames.get(bestIndex);
double vegaDifference = (minVega*1.00001) - portfolioVega;
double optionVega = vegas.get(bestRatioOption);
double gammaDifference = (minGamma*1.000001) - portfolioGamma;
double optionGamma = vegas.get(bestRatioOption);
double numVegaOptions = Math.ceil(vegaDifference/optionVega);
double numGammaOptions = Math.ceil(gammaDifference/optionGamma);
orders.add(new OrderInfo(bestRatioOption, OrderSide.BUY, 100000.0, (int)Math.max(numVegaOptions, numGammaOptions)));
}
//theoretical greeks
double theoGamma = portfolioGamma;
double theoVega = portfolioVega;
if (portfolioGamma > forecastGamma || portfolioVega > forecastVega) {
double desiredGamma = Math.max(minGamma, forecastGamma);
double desiredVega = Math.max(minVega, forecastVega);
double cost = this.costFunction(theoGamma, theoVega, desiredGamma, desiredVega);
double oldcost = cost;
while (cost <= oldcost) {
//log("OVER GREEKS");
//log("OLDCOST: " + String.valueOf(oldcost) + "| NEWCOST: " + String.valueOf(cost));
int randomIndex = randomGenerator.nextInt(optionNames.size());
String randomOption = optionNames.get(randomIndex);
double optionGamma = gammas.get(randomOption);
double optionVega = vegas.get(randomOption);
theoGamma -= optionGamma;
theoVega -= optionVega;
oldcost = cost;
cost = this.costFunction(theoGamma, theoVega, desiredGamma, desiredVega);
orders.add(new OrderInfo(randomOption, OrderSide.SELL, 0.00001, 1));
}
} else if (portfolioGamma < forecastGamma || portfolioVega < forecastVega) {
double desiredGamma = Math.min(maxGamma, forecastGamma);
double desiredVega = Math.max(maxVega, forecastVega);
double cost = this.costFunction(theoGamma, theoVega, desiredGamma, desiredVega);
double oldcost = cost;
while (cost <= oldcost) {
//log("UNDER GREEKS");
//log("OLDCOST: " + String.valueOf(oldcost) + "| NEWCOST: " + String.valueOf(cost));
int randomIndex = randomGenerator.nextInt(optionNames.size());
String randomOption = optionNames.get(randomIndex);
double optionGamma = gammas.get(randomOption);
double optionVega = vegas.get(randomOption);
theoGamma += optionGamma;
theoVega += optionVega;
oldcost = cost;
cost = this.costFunction(theoGamma, theoVega, desiredGamma, desiredVega);
orders.add(new OrderInfo(randomOption, OrderSide.BUY, 10000.0, 1));
}
}
}
public double costFunction(double gamma, double vega, double desiredGamma, double desiredVega) {
return (Math.pow((gamma - desiredGamma), 2) + Math.pow((vega - desiredVega), 2));
}
public void hedge() {
if (portfolioDelta > maxDelta) {
double difference = Math.abs(portfolioDelta - 0.0);
int amount = (int)Math.round(difference);
if (amount != 0) {
orders.add(new OrderInfo("MIT2~RAND-E", OrderSide.SELL, 0.0001, (int)Math.round(difference)));
}
}
else if (portfolioDelta < minDelta) {
double difference = Math.abs(portfolioDelta);
int amount = (int)Math.round(difference);
if (amount != 0) {
orders.add(new OrderInfo("MIT2~RAND-E", OrderSide.BUY, 10000.0, (int)Math.round(difference)));
}
}
}
public OptionsCase getOptionCaseImplementation() {
return this;
}
}
| rnyang/MidwestTradingCompetition | cases/MIT2Options.java |
179,702 | package de.catma.ui.client.ui.visualization.vega;
import java.util.List;
import com.vaadin.shared.communication.ServerRpc;
import de.catma.ui.client.ui.visualization.vega.shared.SelectedQueryResultRow;
public interface VegaServerRpc extends ServerRpc {
public void onUserSelection(List<SelectedQueryResultRow> selection);
}
| forTEXT/catma | src/main/java/de/catma/ui/client/ui/visualization/vega/VegaServerRpc.java |
179,703 | /* Copyright 2009-2015 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package org.um.feri.ears.operators;
import org.um.feri.ears.problems.NumberSolution;
import org.um.feri.ears.problems.moo.ParetoSolution;
import org.um.feri.ears.util.comparator.ObjectiveComparator;
import org.um.feri.ears.util.random.RNG;
public class VEGASelection<N extends Number> {
private final ObjectiveComparator<N> comparator;
/**
* The tournament size. This is the number of solutions sampled from which
* the tournament winner is selected.
*/
private int size;
/**
* Constructs a binary tournament selection operator using the specified
* dominance comparator.
*
* @param comparator the comparator used to determine the tournament winner
*/
public VEGASelection(ObjectiveComparator<N> comparator) {
this(2, comparator);
}
/**
* Constructs a tournament selection operator of the specified size and
* using the specified dominance comparator.
*
* @param size the tournament size
* @param comparator the comparator used to determine the tournament winner
*/
public VEGASelection(int size, ObjectiveComparator<N> comparator) {
this.size = size;
this.comparator = comparator;
}
/**
* Performs deterministic tournament selection with the specified
* population, returning the tournament winner. If more than one solution is
* a winner, one of the winners is returned with equal probability.
*
* @param coralReef the population from which candidate solutions are
* selected
* @return the winner of tournament selection
*/
public NumberSolution<N> execute(Object object) {
ParetoSolution<N> population = (ParetoSolution<N>) object;
NumberSolution<N> winner = population.get(RNG.nextInt(population.size()));
for (int i = 1; i < size; i++) {
NumberSolution<N> candidate = population
.get(RNG.nextInt(population.size()));
int flag = comparator.compare(winner, candidate);
if (flag > 0) {
winner = candidate;
}
}
return winner;
}
}
| UM-LPM/EARS | src/org/um/feri/ears/operators/VEGASelection.java |
179,704 | /* Copyright 2009-2024 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package org.moeaframework.algorithm;
import org.moeaframework.core.Initialization;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.PRNG;
import org.moeaframework.core.Population;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Selection;
import org.moeaframework.core.Settings;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Variation;
import org.moeaframework.core.comparator.ObjectiveComparator;
import org.moeaframework.core.configuration.Property;
import org.moeaframework.core.initialization.RandomInitialization;
import org.moeaframework.core.selection.TournamentSelection;
import org.moeaframework.core.spi.OperatorFactory;
/**
* Implementation of the Vector Evaluated Genetic Algorithm (VEGA). VEGA should be avoided in practice, since many
* modern algorithms outperform it and exhibit better convergence properties, but is included due to its historical
* significance. VEGA is considered the earliest MOEA. It supports {@code M} objectives during the selection phase by
* selecting {@code M} different subgroups, each selected based on the i-th objective value, for {@code i=1,...,M}.
* <p>
* There is one small algorithmic difference between this implementation and [1]. In [1], applying the genetic
* operators fills the entire population. However, since custom variation operators can be specified, it is possible
* that the population will not be filled completely. As a result, this implementation will continue selecting parents
* until the population is full.
* <p>
* References:
* <ol>
* <li>Schaffer, D. (1985). Multiple Objective Optimization with Vector Evaluated Genetic Algorithms. Proceedings
* of the 1st International Conference on Genetic Algorithms, pp. 93-100.
* </ol>
*/
public class VEGA extends AbstractEvolutionaryAlgorithm {
/**
* The selection operator.
*/
private final Selection selection;
/**
* Constructs a new VEGA instance with default settings.
*
* @param problem the problem
*/
public VEGA(Problem problem) {
this(problem,
Settings.DEFAULT_POPULATION_SIZE,
new Population(),
null,
new RandomInitialization(problem),
OperatorFactory.getInstance().getVariation(problem));
}
/**
* Constructs a new VEGA instance.
*
* @param problem the problem
* @param initialPopulationSize the initial population size
* @param population the population
* @param archive the external archive; or {@code null} if no external archive is used
* @param initialization the initialization operator
* @param variation the variation operator
*/
public VEGA(Problem problem, int initialPopulationSize, Population population, NondominatedPopulation archive,
Initialization initialization, Variation variation) {
super(problem, initialPopulationSize, population, archive, initialization, variation);
selection = new VEGASelection();
}
@Override
@Property("operator")
public void setVariation(Variation variation) {
super.setVariation(variation);
}
@Override
@Property("populationSize")
public void setInitialPopulationSize(int initialPopulationSize) {
super.setInitialPopulationSize(initialPopulationSize);
}
@Override
protected void iterate() {
Population population = getPopulation();
Variation variation = getVariation();
int populationSize = population.size();
// select the parents from the M different subgroups
Solution[] parents = selection.select(populationSize, population);
// shuffle the parents
PRNG.shuffle(parents);
// loop until the next generation is filled
int index = 0;
boolean filled = false;
population.clear();
while (!filled) {
Solution[] offspring = variation.evolve(select(parents, index, variation.getArity()));
for (int i = 0; i < offspring.length; i++) {
population.add(offspring[i]);
if (population.size() >= populationSize) {
filled = true;
break;
}
}
index += variation.getArity() % populationSize;
}
// evaluate the offspring
evaluateAll(population);
}
/**
* Returns the subset of parents for the next variation operator.
*
* @param parents all parents
* @param index the starting index
* @param size the size of the subset
* @return the subset of parents
*/
private Solution[] select(Solution[] parents, int index, int size) {
Solution[] result = new Solution[size];
for (int i = 0; i < size; i++) {
result[i] = parents[(index+i) % parents.length];
}
return result;
}
/**
* VEGA selection operator that selects parents based on only one of the objectives.
*/
private class VEGASelection implements Selection {
private Selection[] selectors;
public VEGASelection() {
super();
selectors = new Selection[problem.getNumberOfObjectives()];
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
selectors[i] = new TournamentSelection(new ObjectiveComparator(i));
}
}
@Override
public Solution[] select(int arity, Population population) {
Solution[] result = new Solution[arity];
for (int i = 0; i < arity; i++) {
Selection selector = selectors[i % problem.getNumberOfObjectives()];
result[i] = selector.select(1, population)[0];
}
return result;
}
}
}
| MOEAFramework/MOEAFramework | src/org/moeaframework/algorithm/VEGA.java |
179,705 | package micdoodle8.mods.galacticraft.core.tile;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import micdoodle8.mods.galacticraft.api.transmission.NetworkType;
import micdoodle8.mods.galacticraft.api.transmission.tile.IOxygenReceiver;
import micdoodle8.mods.galacticraft.api.transmission.tile.IOxygenStorage;
import micdoodle8.mods.galacticraft.api.vector.BlockVec3;
import micdoodle8.mods.galacticraft.core.GCFluids;
import micdoodle8.mods.galacticraft.core.energy.EnergyConfigHandler;
import micdoodle8.mods.galacticraft.core.energy.EnergyUtil;
import micdoodle8.mods.galacticraft.core.energy.tile.TileBaseElectricBlock;
import micdoodle8.mods.galacticraft.core.fluid.FluidNetwork;
import micdoodle8.mods.galacticraft.core.fluid.NetworkHelper;
import micdoodle8.mods.galacticraft.core.util.CompatibilityManager;
import micdoodle8.mods.galacticraft.core.wrappers.FluidHandlerWrapper;
import micdoodle8.mods.galacticraft.core.wrappers.IFluidHandlerWrapper;
import micdoodle8.mods.miccore.Annotations;
import micdoodle8.mods.miccore.Annotations.NetworkedField;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.relauncher.Side;
import java.util.EnumSet;
public abstract class TileEntityOxygen extends TileBaseElectricBlock implements IOxygenReceiver, IOxygenStorage, IFluidHandlerWrapper
{
public int oxygenPerTick;
@NetworkedField(targetSide = Side.CLIENT)
public FluidTankGC tank;
public float lastStoredOxygen;
public static int timeSinceOxygenRequest;
public TileEntityOxygen(String tileName, int maxOxygen, int oxygenPerTick)
{
super(tileName);
this.tank = new FluidTankGC(maxOxygen, this);
this.oxygenPerTick = oxygenPerTick;
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)
return true;
if (EnergyUtil.checkMekGasHandler(capability))
return true;
return super.hasCapability(capability, facing);
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)
{
return (T) new FluidHandlerWrapper(this, facing);
}
if (EnergyUtil.checkMekGasHandler(capability))
{
return (T) this;
}
return super.getCapability(capability, facing);
}
public int getScaledOxygenLevel(int scale)
{
return (int) Math.floor(this.getOxygenStored() * scale / (this.getMaxOxygenStored() - this.oxygenPerTick));
}
public abstract boolean shouldUseOxygen();
public int getCappedScaledOxygenLevel(int scale)
{
return (int) Math.max(Math.min(Math.floor((double) this.tank.getFluidAmount() / (double) this.tank.getCapacity() * scale), scale), 0);
}
@Override
public void update()
{
super.update();
if (!this.world.isRemote)
{
if (TileEntityOxygen.timeSinceOxygenRequest > 0)
{
TileEntityOxygen.timeSinceOxygenRequest--;
}
if (this.shouldUseOxygen())
{
if (this.tank.getFluid() != null)
{
FluidStack fluid = this.tank.getFluid().copy();
fluid.amount = Math.max(fluid.amount - this.oxygenPerTick, 0);
this.tank.setFluid(fluid);
}
}
}
this.lastStoredOxygen = this.tank.getFluidAmount();
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
if (nbt.hasKey("storedOxygen"))
{
this.tank.setFluid(new FluidStack(GCFluids.fluidOxygenGas, nbt.getInteger("storedOxygen")));
}
else if (nbt.hasKey("storedOxygenF"))
{
int oxygen = (int) nbt.getFloat("storedOxygenF");
oxygen = Math.min(this.tank.getCapacity(), oxygen);
this.tank.setFluid(new FluidStack(GCFluids.fluidOxygenGas, oxygen));
}
else
{
this.tank.readFromNBT(nbt);
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
this.tank.writeToNBT(nbt);
return nbt;
}
@Override
public NBTTagCompound getUpdateTag()
{
return this.writeToNBT(new NBTTagCompound());
}
@Override
public void setOxygenStored(int oxygen)
{
this.tank.setFluid(new FluidStack(GCFluids.fluidOxygenGas, (int) Math.max(Math.min(oxygen, this.getMaxOxygenStored()), 0)));
}
@Override
public int getOxygenStored()
{
return this.tank.getFluidAmount();
}
@Override
public int getMaxOxygenStored()
{
return this.tank.getCapacity();
}
public EnumSet<EnumFacing> getOxygenInputDirections()
{
return EnumSet.allOf(EnumFacing.class);
}
public EnumSet<EnumFacing> getOxygenOutputDirections()
{
return EnumSet.noneOf(EnumFacing.class);
}
@Override
public boolean canConnect(EnumFacing direction, NetworkType type)
{
if (direction == null)
{
return false;
}
if (type == NetworkType.FLUID)
{
return this.getOxygenInputDirections().contains(direction) || this.getOxygenOutputDirections().contains(direction);
}
if (type == NetworkType.POWER)
// return this.nodeAvailable(new EnergySourceAdjacent(direction));
{
return super.canConnect(direction, type);
}
return false;
}
@Override
public int receiveOxygen(EnumFacing from, int receive, boolean doReceive)
{
if (this.getOxygenInputDirections().contains(from))
{
if (!doReceive)
{
return this.getOxygenRequest(from);
}
return this.receiveOxygen(receive, doReceive);
}
return 0;
}
public int receiveOxygen(int receive, boolean doReceive)
{
if (receive > 0)
{
int prevOxygenStored = this.getOxygenStored();
int newStoredOxygen = Math.min(prevOxygenStored + receive, this.getMaxOxygenStored());
if (doReceive)
{
TileEntityOxygen.timeSinceOxygenRequest = 20;
this.setOxygenStored(newStoredOxygen);
}
return Math.max(newStoredOxygen - prevOxygenStored, 0);
}
return 0;
}
@Override
public int provideOxygen(EnumFacing from, int request, boolean doProvide)
{
if (this.getOxygenOutputDirections().contains(from))
{
return this.drawOxygen(request, doProvide);
}
return 0;
}
public int drawOxygen(int request, boolean doProvide)
{
if (request > 0)
{
int requestedOxygen = Math.min(request, this.getOxygenStored());
if (doProvide)
{
this.setOxygenStored(this.getOxygenStored() - requestedOxygen);
}
return requestedOxygen;
}
return 0;
}
public void produceOxygen()
{
if (!this.world.isRemote)
{
for (EnumFacing direction : this.getOxygenOutputDirections())
{
if (direction != null)
{
this.produceOxygen(direction);
}
}
}
}
public boolean produceOxygen(EnumFacing outputDirection)
{
int provide = this.getOxygenProvide(outputDirection);
if (provide > 0)
{
TileEntity outputTile = new BlockVec3(this).getTileEntityOnSide(this.world, outputDirection);
FluidNetwork outputNetwork = NetworkHelper.getFluidNetworkFromTile(outputTile, outputDirection);
if (outputNetwork != null)
{
int gasRequested = outputNetwork.getRequest();
if (gasRequested > 0)
{
int usedGas = outputNetwork.emitToBuffer(new FluidStack(GCFluids.fluidOxygenGas, Math.min(gasRequested, provide)), true);
this.drawOxygen(usedGas, true);
return true;
}
}
else if (outputTile instanceof IOxygenReceiver)
{
float requestedOxygen = ((IOxygenReceiver) outputTile).getOxygenRequest(outputDirection.getOpposite());
if (requestedOxygen > 0)
{
int acceptedOxygen = ((IOxygenReceiver) outputTile).receiveOxygen(outputDirection.getOpposite(), provide, true);
this.drawOxygen(acceptedOxygen, true);
return true;
}
}
// else if (EnergyConfigHandler.isMekanismLoaded())
// {
// //TODO Oxygen item handling - internal tank (IGasItem)
// //int acceptedOxygen = GasTransmission.addGas(itemStack, type, amount);
// //this.drawOxygen(acceptedOxygen, true);
//
// if (outputTile instanceof IGasHandler && ((IGasHandler) outputTile).canReceiveGas(outputDirection.getOpposite(), (Gas) EnergyConfigHandler.gasOxygen))
// {
// GasStack toSend = new GasStack((Gas) EnergyConfigHandler.gasOxygen, (int) Math.floor(provide));
// int acceptedOxygen = 0;
// try {
// acceptedOxygen = ((IGasHandler) outputTile).receiveGas(outputDirection.getOpposite(), toSend);
// } catch (Exception e) { }
// this.drawOxygen(acceptedOxygen, true);
// return true;
// }
// }
}
return false;
}
@Override
public int getOxygenRequest(EnumFacing direction)
{
if (this.shouldPullOxygen())
{
return Math.min(this.oxygenPerTick * 2, this.getMaxOxygenStored() - this.getOxygenStored());
}
else
{
return 0;
}
}
@Override
public boolean shouldPullOxygen()
{
return this.getOxygenStored() < this.getMaxOxygenStored();
}
/**
* Make sure this does not exceed the oxygen stored.
* This should return 0 if no oxygen is stored.
* Implementing tiles must respect this or you will generate infinite oxygen.
*/
@Override
public int getOxygenProvide(EnumFacing direction)
{
return 0;
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public int receiveGas(EnumFacing side, GasStack stack, boolean doTransfer)
{
if (!stack.getGas().getName().equals("oxygen"))
{
return 0;
}
return (int) Math.floor(this.receiveOxygen(stack.amount, doTransfer));
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public int receiveGas(EnumFacing side, GasStack stack)
{
return this.receiveGas(side, stack, true);
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public GasStack drawGas(EnumFacing side, int amount, boolean doTransfer)
{
return new GasStack((Gas) EnergyConfigHandler.gasOxygen, (int) Math.floor(this.drawOxygen(amount, doTransfer)));
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public GasStack drawGas(EnumFacing side, int amount)
{
return this.drawGas(side, amount, true);
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public boolean canReceiveGas(EnumFacing side, Gas type)
{
return type.getName().equals("oxygen") && this.getOxygenInputDirections().contains(side);
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.IGasHandler", modID = CompatibilityManager.modidMekanism)
public boolean canDrawGas(EnumFacing side, Gas type)
{
return type.getName().equals("oxygen") && this.getOxygenOutputDirections().contains(side);
}
@Annotations.RuntimeInterface(clazz = "mekanism.api.gas.ITubeConnection", modID = CompatibilityManager.modidMekanism)
public boolean canTubeConnect(EnumFacing side)
{
return this.canConnect(side, NetworkType.FLUID);
}
@Override
public int fill(EnumFacing from, FluidStack resource, boolean doFill)
{
if (this.getOxygenInputDirections().contains(from) && resource != null)
{
if (!doFill)
{
return this.getOxygenRequest(from);
}
return this.receiveOxygen(resource.amount, doFill);
}
return 0;
}
@Override
public FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain)
{
return resource == null ? null : drain(from, resource.amount, doDrain);
}
@Override
public FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain)
{
if (this.getOxygenOutputDirections().contains(from))
{
return new FluidStack(GCFluids.fluidOxygenGas, this.drawOxygen(maxDrain, doDrain));
}
return null;
}
@Override
public boolean canFill(EnumFacing from, Fluid fluid)
{
return this.getOxygenInputDirections().contains(from) && (fluid == null || fluid.getName().equals("oxygen"));
}
@Override
public boolean canDrain(EnumFacing from, Fluid fluid)
{
return this.getOxygenOutputDirections().contains(from) && (fluid == null || fluid.getName().equals("oxygen"));
}
@Override
public FluidTankInfo[] getTankInfo(EnumFacing from)
{
if (canConnect(from, NetworkType.FLUID))
{
return new FluidTankInfo[] { this.tank.getInfo() };
}
return new FluidTankInfo[] {};
}
}
| micdoodle8/Galacticraft | src/main/java/micdoodle8/mods/galacticraft/core/tile/TileEntityOxygen.java |
179,706 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hwpf.model.types;
import org.apache.poi.hwpf.model.Colorref;
import org.apache.poi.hwpf.model.Hyphenation;
import org.apache.poi.hwpf.usermodel.BorderCode;
import org.apache.poi.hwpf.usermodel.DateAndTime;
import org.apache.poi.hwpf.usermodel.ShadingDescriptor;
import org.apache.poi.util.BitField;
import org.apache.poi.util.Internal;
/**
* Character Properties.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* remove the record in src/records/definitions.
* @author S. Ryan Ackley
*/
@Internal
public abstract class CHPAbstractType
{
protected int field_1_grpfChp;
/**/private static BitField fBold = new BitField(0x00000001);
/**/private static BitField fItalic = new BitField(0x00000002);
/**/private static BitField fRMarkDel = new BitField(0x00000004);
/**/private static BitField fOutline = new BitField(0x00000008);
/**/private static BitField fFldVanish = new BitField(0x00000010);
/**/private static BitField fSmallCaps = new BitField(0x00000020);
/**/private static BitField fCaps = new BitField(0x00000040);
/**/private static BitField fVanish = new BitField(0x00000080);
/**/private static BitField fRMark = new BitField(0x00000100);
/**/private static BitField fSpec = new BitField(0x00000200);
/**/private static BitField fStrike = new BitField(0x00000400);
/**/private static BitField fObj = new BitField(0x00000800);
/**/private static BitField fShadow = new BitField(0x00001000);
/**/private static BitField fLowerCase = new BitField(0x00002000);
/**/private static BitField fData = new BitField(0x00004000);
/**/private static BitField fOle2 = new BitField(0x00008000);
/**/private static BitField fEmboss = new BitField(0x00010000);
/**/private static BitField fImprint = new BitField(0x00020000);
/**/private static BitField fDStrike = new BitField(0x00040000);
/**/private static BitField fUsePgsuSettings = new BitField(0x00080000);
/**/private static BitField fBoldBi = new BitField(0x00100000);
/**/private static BitField fComplexScripts = new BitField(0x00200000);
/**/private static BitField fItalicBi = new BitField(0x00400000);
/**/private static BitField fBiDi = new BitField(0x00800000);
protected int field_2_hps;
protected int field_3_ftcAscii;
protected int field_4_ftcFE;
protected int field_5_ftcOther;
protected int field_6_ftcBi;
protected int field_7_dxaSpace;
protected Colorref field_8_cv;
protected byte field_9_ico;
protected int field_10_pctCharWidth;
protected int field_11_lidDefault;
protected int field_12_lidFE;
protected byte field_13_kcd;
/**/protected final static byte KCD_NON = 0;
/**/protected final static byte KCD_DOT = 1;
/**/protected final static byte KCD_COMMA = 2;
/**/protected final static byte KCD_CIRCLE = 3;
/**/protected final static byte KCD_UNDER_DOT = 4;
protected boolean field_14_fUndetermine;
protected byte field_15_iss;
/**/protected final static byte ISS_NONE = 0;
/**/protected final static byte ISS_SUPERSCRIPTED = 1;
/**/protected final static byte ISS_SUBSCRIPTED = 2;
protected boolean field_16_fSpecSymbol;
protected byte field_17_idct;
protected byte field_18_idctHint;
protected byte field_19_kul;
/**/protected final static byte KUL_NONE = 0;
/**/protected final static byte KUL_SINGLE = 1;
/**/protected final static byte KUL_BY_WORD = 2;
/**/protected final static byte KUL_DOUBLE = 3;
/**/protected final static byte KUL_DOTTED = 4;
/**/protected final static byte KUL_HIDDEN = 5;
/**/protected final static byte KUL_THICK = 6;
/**/protected final static byte KUL_DASH = 7;
/**/protected final static byte KUL_DOT = 8;
/**/protected final static byte KUL_DOT_DASH = 9;
/**/protected final static byte KUL_DOT_DOT_DASH = 10;
/**/protected final static byte KUL_WAVE = 11;
/**/protected final static byte KUL_DOTTED_HEAVY = 20;
/**/protected final static byte KUL_DASHED_HEAVY = 23;
/**/protected final static byte KUL_DOT_DASH_HEAVY = 25;
/**/protected final static byte KUL_DOT_DOT_DASH_HEAVY = 26;
/**/protected final static byte KUL_WAVE_HEAVY = 27;
/**/protected final static byte KUL_DASH_LONG = 39;
/**/protected final static byte KUL_WAVE_DOUBLE = 43;
/**/protected final static byte KUL_DASH_LONG_HEAVY = 55;
protected Hyphenation field_20_hresi;
protected int field_21_hpsKern;
protected short field_22_hpsPos;
protected ShadingDescriptor field_23_shd;
protected BorderCode field_24_brc;
protected int field_25_ibstRMark;
protected byte field_26_sfxtText;
/**/protected final static byte SFXTTEXT_NO = 0;
/**/protected final static byte SFXTTEXT_LAS_VEGAS_LIGHTS = 1;
/**/protected final static byte SFXTTEXT_BACKGROUND_BLINK = 2;
/**/protected final static byte SFXTTEXT_SPARKLE_TEXT = 3;
/**/protected final static byte SFXTTEXT_MARCHING_ANTS = 4;
/**/protected final static byte SFXTTEXT_MARCHING_RED_ANTS = 5;
/**/protected final static byte SFXTTEXT_SHIMMER = 6;
protected boolean field_27_fDblBdr;
protected boolean field_28_fBorderWS;
protected short field_29_ufel;
/**/private static BitField itypFELayout = new BitField(0x00ff);
/**/private static BitField fTNY = new BitField(0x0100);
/**/private static BitField fWarichu = new BitField(0x0200);
/**/private static BitField fKumimoji = new BitField(0x0400);
/**/private static BitField fRuby = new BitField(0x0800);
/**/private static BitField fLSFitText = new BitField(0x1000);
/**/private static BitField spare = new BitField(0xe000);
protected byte field_30_copt;
/**/private static BitField iWarichuBracket = new BitField(0x07);
/**/private static BitField fWarichuNoOpenBracket = new BitField(0x08);
/**/private static BitField fTNYCompress = new BitField(0x10);
/**/private static BitField fTNYFetchTxm = new BitField(0x20);
/**/private static BitField fCellFitText = new BitField(0x40);
/**/private static BitField unused = new BitField(0x80);
protected int field_31_hpsAsci;
protected int field_32_hpsFE;
protected int field_33_hpsBi;
protected int field_34_ftcSym;
protected int field_35_xchSym;
protected int field_36_fcPic;
protected int field_37_fcObj;
protected int field_38_lTagObj;
protected int field_39_fcData;
protected Hyphenation field_40_hresiOld;
protected int field_41_ibstRMarkDel;
protected DateAndTime field_42_dttmRMark;
protected DateAndTime field_43_dttmRMarkDel;
protected int field_44_istd;
protected int field_45_idslRMReason;
protected int field_46_idslReasonDel;
protected int field_47_cpg;
protected short field_48_Highlight;
/**/private static BitField icoHighlight = new BitField(0x001f);
/**/private static BitField fHighlight = new BitField(0x0020);
protected short field_49_CharsetFlags;
/**/private static BitField fChsDiff = new BitField(0x0001);
/**/private static BitField fMacChs = new BitField(0x0020);
protected short field_50_chse;
protected boolean field_51_fPropRMark;
protected int field_52_ibstPropRMark;
protected DateAndTime field_53_dttmPropRMark;
protected boolean field_54_fConflictOrig;
protected boolean field_55_fConflictOtherDel;
protected int field_56_wConflict;
protected int field_57_IbstConflict;
protected DateAndTime field_58_dttmConflict;
protected boolean field_59_fDispFldRMark;
protected int field_60_ibstDispFldRMark;
protected DateAndTime field_61_dttmDispFldRMark;
protected byte[] field_62_xstDispFldRMark;
protected int field_63_fcObjp;
protected byte field_64_lbrCRJ;
/**/protected final static byte LBRCRJ_NONE = 0;
/**/protected final static byte LBRCRJ_LEFT = 1;
/**/protected final static byte LBRCRJ_RIGHT = 2;
/**/protected final static byte LBRCRJ_BOTH = 3;
protected boolean field_65_fSpecVanish;
protected boolean field_66_fHasOldProps;
protected boolean field_67_fSdtVanish;
protected int field_68_wCharScale;
protected CHPAbstractType()
{
this.field_2_hps = 20;
this.field_8_cv = new Colorref();
this.field_11_lidDefault = 0x0400;
this.field_12_lidFE = 0x0400;
this.field_20_hresi = new Hyphenation();
this.field_23_shd = new ShadingDescriptor();
this.field_24_brc = new BorderCode();
this.field_36_fcPic = -1;
this.field_40_hresiOld = new Hyphenation();
this.field_42_dttmRMark = new DateAndTime();
this.field_43_dttmRMarkDel = new DateAndTime();
this.field_44_istd = 10;
this.field_53_dttmPropRMark = new DateAndTime();
this.field_58_dttmConflict = new DateAndTime();
this.field_61_dttmDispFldRMark = new DateAndTime();
this.field_62_xstDispFldRMark = new byte[0];
this.field_68_wCharScale = 100;
}
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("[CHP]\n");
builder.append(" .grpfChp = ");
builder.append(" (").append(getGrpfChp()).append(" )\n");
builder.append(" .fBold = ").append(isFBold()).append('\n');
builder.append(" .fItalic = ").append(isFItalic()).append('\n');
builder.append(" .fRMarkDel = ").append(isFRMarkDel()).append('\n');
builder.append(" .fOutline = ").append(isFOutline()).append('\n');
builder.append(" .fFldVanish = ").append(isFFldVanish()).append('\n');
builder.append(" .fSmallCaps = ").append(isFSmallCaps()).append('\n');
builder.append(" .fCaps = ").append(isFCaps()).append('\n');
builder.append(" .fVanish = ").append(isFVanish()).append('\n');
builder.append(" .fRMark = ").append(isFRMark()).append('\n');
builder.append(" .fSpec = ").append(isFSpec()).append('\n');
builder.append(" .fStrike = ").append(isFStrike()).append('\n');
builder.append(" .fObj = ").append(isFObj()).append('\n');
builder.append(" .fShadow = ").append(isFShadow()).append('\n');
builder.append(" .fLowerCase = ").append(isFLowerCase()).append('\n');
builder.append(" .fData = ").append(isFData()).append('\n');
builder.append(" .fOle2 = ").append(isFOle2()).append('\n');
builder.append(" .fEmboss = ").append(isFEmboss()).append('\n');
builder.append(" .fImprint = ").append(isFImprint()).append('\n');
builder.append(" .fDStrike = ").append(isFDStrike()).append('\n');
builder.append(" .fUsePgsuSettings = ").append(isFUsePgsuSettings()).append('\n');
builder.append(" .fBoldBi = ").append(isFBoldBi()).append('\n');
builder.append(" .fComplexScripts = ").append(isFComplexScripts()).append('\n');
builder.append(" .fItalicBi = ").append(isFItalicBi()).append('\n');
builder.append(" .fBiDi = ").append(isFBiDi()).append('\n');
builder.append(" .hps = ");
builder.append(" (").append(getHps()).append(" )\n");
builder.append(" .ftcAscii = ");
builder.append(" (").append(getFtcAscii()).append(" )\n");
builder.append(" .ftcFE = ");
builder.append(" (").append(getFtcFE()).append(" )\n");
builder.append(" .ftcOther = ");
builder.append(" (").append(getFtcOther()).append(" )\n");
builder.append(" .ftcBi = ");
builder.append(" (").append(getFtcBi()).append(" )\n");
builder.append(" .dxaSpace = ");
builder.append(" (").append(getDxaSpace()).append(" )\n");
builder.append(" .cv = ");
builder.append(" (").append(getCv()).append(" )\n");
builder.append(" .ico = ");
builder.append(" (").append(getIco()).append(" )\n");
builder.append(" .pctCharWidth = ");
builder.append(" (").append(getPctCharWidth()).append(" )\n");
builder.append(" .lidDefault = ");
builder.append(" (").append(getLidDefault()).append(" )\n");
builder.append(" .lidFE = ");
builder.append(" (").append(getLidFE()).append(" )\n");
builder.append(" .kcd = ");
builder.append(" (").append(getKcd()).append(" )\n");
builder.append(" .fUndetermine = ");
builder.append(" (").append(getFUndetermine()).append(" )\n");
builder.append(" .iss = ");
builder.append(" (").append(getIss()).append(" )\n");
builder.append(" .fSpecSymbol = ");
builder.append(" (").append(getFSpecSymbol()).append(" )\n");
builder.append(" .idct = ");
builder.append(" (").append(getIdct()).append(" )\n");
builder.append(" .idctHint = ");
builder.append(" (").append(getIdctHint()).append(" )\n");
builder.append(" .kul = ");
builder.append(" (").append(getKul()).append(" )\n");
builder.append(" .hresi = ");
builder.append(" (").append(getHresi()).append(" )\n");
builder.append(" .hpsKern = ");
builder.append(" (").append(getHpsKern()).append(" )\n");
builder.append(" .hpsPos = ");
builder.append(" (").append(getHpsPos()).append(" )\n");
builder.append(" .shd = ");
builder.append(" (").append(getShd()).append(" )\n");
builder.append(" .brc = ");
builder.append(" (").append(getBrc()).append(" )\n");
builder.append(" .ibstRMark = ");
builder.append(" (").append(getIbstRMark()).append(" )\n");
builder.append(" .sfxtText = ");
builder.append(" (").append(getSfxtText()).append(" )\n");
builder.append(" .fDblBdr = ");
builder.append(" (").append(getFDblBdr()).append(" )\n");
builder.append(" .fBorderWS = ");
builder.append(" (").append(getFBorderWS()).append(" )\n");
builder.append(" .ufel = ");
builder.append(" (").append(getUfel()).append(" )\n");
builder.append(" .itypFELayout = ").append(getItypFELayout()).append('\n');
builder.append(" .fTNY = ").append(isFTNY()).append('\n');
builder.append(" .fWarichu = ").append(isFWarichu()).append('\n');
builder.append(" .fKumimoji = ").append(isFKumimoji()).append('\n');
builder.append(" .fRuby = ").append(isFRuby()).append('\n');
builder.append(" .fLSFitText = ").append(isFLSFitText()).append('\n');
builder.append(" .spare = ").append(getSpare()).append('\n');
builder.append(" .copt = ");
builder.append(" (").append(getCopt()).append(" )\n");
builder.append(" .iWarichuBracket = ").append(getIWarichuBracket()).append('\n');
builder.append(" .fWarichuNoOpenBracket = ").append(isFWarichuNoOpenBracket()).append('\n');
builder.append(" .fTNYCompress = ").append(isFTNYCompress()).append('\n');
builder.append(" .fTNYFetchTxm = ").append(isFTNYFetchTxm()).append('\n');
builder.append(" .fCellFitText = ").append(isFCellFitText()).append('\n');
builder.append(" .unused = ").append(isUnused()).append('\n');
builder.append(" .hpsAsci = ");
builder.append(" (").append(getHpsAsci()).append(" )\n");
builder.append(" .hpsFE = ");
builder.append(" (").append(getHpsFE()).append(" )\n");
builder.append(" .hpsBi = ");
builder.append(" (").append(getHpsBi()).append(" )\n");
builder.append(" .ftcSym = ");
builder.append(" (").append(getFtcSym()).append(" )\n");
builder.append(" .xchSym = ");
builder.append(" (").append(getXchSym()).append(" )\n");
builder.append(" .fcPic = ");
builder.append(" (").append(getFcPic()).append(" )\n");
builder.append(" .fcObj = ");
builder.append(" (").append(getFcObj()).append(" )\n");
builder.append(" .lTagObj = ");
builder.append(" (").append(getLTagObj()).append(" )\n");
builder.append(" .fcData = ");
builder.append(" (").append(getFcData()).append(" )\n");
builder.append(" .hresiOld = ");
builder.append(" (").append(getHresiOld()).append(" )\n");
builder.append(" .ibstRMarkDel = ");
builder.append(" (").append(getIbstRMarkDel()).append(" )\n");
builder.append(" .dttmRMark = ");
builder.append(" (").append(getDttmRMark()).append(" )\n");
builder.append(" .dttmRMarkDel = ");
builder.append(" (").append(getDttmRMarkDel()).append(" )\n");
builder.append(" .istd = ");
builder.append(" (").append(getIstd()).append(" )\n");
builder.append(" .idslRMReason = ");
builder.append(" (").append(getIdslRMReason()).append(" )\n");
builder.append(" .idslReasonDel = ");
builder.append(" (").append(getIdslReasonDel()).append(" )\n");
builder.append(" .cpg = ");
builder.append(" (").append(getCpg()).append(" )\n");
builder.append(" .Highlight = ");
builder.append(" (").append(getHighlight()).append(" )\n");
builder.append(" .icoHighlight = ").append(getIcoHighlight()).append('\n');
builder.append(" .fHighlight = ").append(isFHighlight()).append('\n');
builder.append(" .CharsetFlags = ");
builder.append(" (").append(getCharsetFlags()).append(" )\n");
builder.append(" .fChsDiff = ").append(isFChsDiff()).append('\n');
builder.append(" .fMacChs = ").append(isFMacChs()).append('\n');
builder.append(" .chse = ");
builder.append(" (").append(getChse()).append(" )\n");
builder.append(" .fPropRMark = ");
builder.append(" (").append(getFPropRMark()).append(" )\n");
builder.append(" .ibstPropRMark = ");
builder.append(" (").append(getIbstPropRMark()).append(" )\n");
builder.append(" .dttmPropRMark = ");
builder.append(" (").append(getDttmPropRMark()).append(" )\n");
builder.append(" .fConflictOrig = ");
builder.append(" (").append(getFConflictOrig()).append(" )\n");
builder.append(" .fConflictOtherDel = ");
builder.append(" (").append(getFConflictOtherDel()).append(" )\n");
builder.append(" .wConflict = ");
builder.append(" (").append(getWConflict()).append(" )\n");
builder.append(" .IbstConflict = ");
builder.append(" (").append(getIbstConflict()).append(" )\n");
builder.append(" .dttmConflict = ");
builder.append(" (").append(getDttmConflict()).append(" )\n");
builder.append(" .fDispFldRMark = ");
builder.append(" (").append(getFDispFldRMark()).append(" )\n");
builder.append(" .ibstDispFldRMark = ");
builder.append(" (").append(getIbstDispFldRMark()).append(" )\n");
builder.append(" .dttmDispFldRMark = ");
builder.append(" (").append(getDttmDispFldRMark()).append(" )\n");
builder.append(" .xstDispFldRMark = ");
builder.append(" (").append(getXstDispFldRMark()).append(" )\n");
builder.append(" .fcObjp = ");
builder.append(" (").append(getFcObjp()).append(" )\n");
builder.append(" .lbrCRJ = ");
builder.append(" (").append(getLbrCRJ()).append(" )\n");
builder.append(" .fSpecVanish = ");
builder.append(" (").append(getFSpecVanish()).append(" )\n");
builder.append(" .fHasOldProps = ");
builder.append(" (").append(getFHasOldProps()).append(" )\n");
builder.append(" .fSdtVanish = ");
builder.append(" (").append(getFSdtVanish()).append(" )\n");
builder.append(" .wCharScale = ");
builder.append(" (").append(getWCharScale()).append(" )\n");
builder.append("[/CHP]\n");
return builder.toString();
}
/**
* Collection of the 32 flags.
*/
@Internal
public int getGrpfChp()
{
return field_1_grpfChp;
}
/**
* Collection of the 32 flags.
*/
@Internal
public void setGrpfChp( int field_1_grpfChp )
{
this.field_1_grpfChp = field_1_grpfChp;
}
/**
* Font size in half points.
*/
@Internal
public int getHps()
{
return field_2_hps;
}
/**
* Font size in half points.
*/
@Internal
public void setHps( int field_2_hps )
{
this.field_2_hps = field_2_hps;
}
/**
* Font for ASCII text.
*/
@Internal
public int getFtcAscii()
{
return field_3_ftcAscii;
}
/**
* Font for ASCII text.
*/
@Internal
public void setFtcAscii( int field_3_ftcAscii )
{
this.field_3_ftcAscii = field_3_ftcAscii;
}
/**
* Font for East Asian text.
*/
@Internal
public int getFtcFE()
{
return field_4_ftcFE;
}
/**
* Font for East Asian text.
*/
@Internal
public void setFtcFE( int field_4_ftcFE )
{
this.field_4_ftcFE = field_4_ftcFE;
}
/**
* Font for non-East Asian text.
*/
@Internal
public int getFtcOther()
{
return field_5_ftcOther;
}
/**
* Font for non-East Asian text.
*/
@Internal
public void setFtcOther( int field_5_ftcOther )
{
this.field_5_ftcOther = field_5_ftcOther;
}
/**
* Font for Complex Scripts text.
*/
@Internal
public int getFtcBi()
{
return field_6_ftcBi;
}
/**
* Font for Complex Scripts text.
*/
@Internal
public void setFtcBi( int field_6_ftcBi )
{
this.field_6_ftcBi = field_6_ftcBi;
}
/**
* Space following each character in the run expressed in twip units..
*/
@Internal
public int getDxaSpace()
{
return field_7_dxaSpace;
}
/**
* Space following each character in the run expressed in twip units..
*/
@Internal
public void setDxaSpace( int field_7_dxaSpace )
{
this.field_7_dxaSpace = field_7_dxaSpace;
}
/**
* 24-bit color.
*/
@Internal
public Colorref getCv()
{
return field_8_cv;
}
/**
* 24-bit color.
*/
@Internal
public void setCv( Colorref field_8_cv )
{
this.field_8_cv = field_8_cv;
}
/**
* Color of text for Word 97.
*/
@Internal
public byte getIco()
{
return field_9_ico;
}
/**
* Color of text for Word 97.
*/
@Internal
public void setIco( byte field_9_ico )
{
this.field_9_ico = field_9_ico;
}
/**
* Character scale.
*/
@Internal
public int getPctCharWidth()
{
return field_10_pctCharWidth;
}
/**
* Character scale.
*/
@Internal
public void setPctCharWidth( int field_10_pctCharWidth )
{
this.field_10_pctCharWidth = field_10_pctCharWidth;
}
/**
* Get the lidDefault field for the CHP record.
*/
@Internal
public int getLidDefault()
{
return field_11_lidDefault;
}
/**
* Set the lidDefault field for the CHP record.
*/
@Internal
public void setLidDefault( int field_11_lidDefault )
{
this.field_11_lidDefault = field_11_lidDefault;
}
/**
* Get the lidFE field for the CHP record.
*/
@Internal
public int getLidFE()
{
return field_12_lidFE;
}
/**
* Set the lidFE field for the CHP record.
*/
@Internal
public void setLidFE( int field_12_lidFE )
{
this.field_12_lidFE = field_12_lidFE;
}
/**
* Emphasis mark.
*
* @return One of
* <li>{@link #KCD_NON}
* <li>{@link #KCD_DOT}
* <li>{@link #KCD_COMMA}
* <li>{@link #KCD_CIRCLE}
* <li>{@link #KCD_UNDER_DOT}
*/
@Internal
public byte getKcd()
{
return field_13_kcd;
}
/**
* Emphasis mark.
*
* @param field_13_kcd
* One of
* <li>{@link #KCD_NON}
* <li>{@link #KCD_DOT}
* <li>{@link #KCD_COMMA}
* <li>{@link #KCD_CIRCLE}
* <li>{@link #KCD_UNDER_DOT}
*/
@Internal
public void setKcd( byte field_13_kcd )
{
this.field_13_kcd = field_13_kcd;
}
/**
* Character is undetermined.
*/
@Internal
public boolean getFUndetermine()
{
return field_14_fUndetermine;
}
/**
* Character is undetermined.
*/
@Internal
public void setFUndetermine( boolean field_14_fUndetermine )
{
this.field_14_fUndetermine = field_14_fUndetermine;
}
/**
* Superscript/subscript indices.
*
* @return One of
* <li>{@link #ISS_NONE}
* <li>{@link #ISS_SUPERSCRIPTED}
* <li>{@link #ISS_SUBSCRIPTED}
*/
@Internal
public byte getIss()
{
return field_15_iss;
}
/**
* Superscript/subscript indices.
*
* @param field_15_iss
* One of
* <li>{@link #ISS_NONE}
* <li>{@link #ISS_SUPERSCRIPTED}
* <li>{@link #ISS_SUBSCRIPTED}
*/
@Internal
public void setIss( byte field_15_iss )
{
this.field_15_iss = field_15_iss;
}
/**
* Used by Word internally.
*/
@Internal
public boolean getFSpecSymbol()
{
return field_16_fSpecSymbol;
}
/**
* Used by Word internally.
*/
@Internal
public void setFSpecSymbol( boolean field_16_fSpecSymbol )
{
this.field_16_fSpecSymbol = field_16_fSpecSymbol;
}
/**
* Not stored in file.
*/
@Internal
public byte getIdct()
{
return field_17_idct;
}
/**
* Not stored in file.
*/
@Internal
public void setIdct( byte field_17_idct )
{
this.field_17_idct = field_17_idct;
}
/**
* Identifier of Character type.
*/
@Internal
public byte getIdctHint()
{
return field_18_idctHint;
}
/**
* Identifier of Character type.
*/
@Internal
public void setIdctHint( byte field_18_idctHint )
{
this.field_18_idctHint = field_18_idctHint;
}
/**
* Underline code.
*
* @return One of
* <li>{@link #KUL_NONE}
* <li>{@link #KUL_SINGLE}
* <li>{@link #KUL_BY_WORD}
* <li>{@link #KUL_DOUBLE}
* <li>{@link #KUL_DOTTED}
* <li>{@link #KUL_HIDDEN}
* <li>{@link #KUL_THICK}
* <li>{@link #KUL_DASH}
* <li>{@link #KUL_DOT}
* <li>{@link #KUL_DOT_DASH}
* <li>{@link #KUL_DOT_DOT_DASH}
* <li>{@link #KUL_WAVE}
* <li>{@link #KUL_DOTTED_HEAVY}
* <li>{@link #KUL_DASHED_HEAVY}
* <li>{@link #KUL_DOT_DASH_HEAVY}
* <li>{@link #KUL_DOT_DOT_DASH_HEAVY}
* <li>{@link #KUL_WAVE_HEAVY}
* <li>{@link #KUL_DASH_LONG}
* <li>{@link #KUL_WAVE_DOUBLE}
* <li>{@link #KUL_DASH_LONG_HEAVY}
*/
@Internal
public byte getKul()
{
return field_19_kul;
}
/**
* Underline code.
*
* @param field_19_kul
* One of
* <li>{@link #KUL_NONE}
* <li>{@link #KUL_SINGLE}
* <li>{@link #KUL_BY_WORD}
* <li>{@link #KUL_DOUBLE}
* <li>{@link #KUL_DOTTED}
* <li>{@link #KUL_HIDDEN}
* <li>{@link #KUL_THICK}
* <li>{@link #KUL_DASH}
* <li>{@link #KUL_DOT}
* <li>{@link #KUL_DOT_DASH}
* <li>{@link #KUL_DOT_DOT_DASH}
* <li>{@link #KUL_WAVE}
* <li>{@link #KUL_DOTTED_HEAVY}
* <li>{@link #KUL_DASHED_HEAVY}
* <li>{@link #KUL_DOT_DASH_HEAVY}
* <li>{@link #KUL_DOT_DOT_DASH_HEAVY}
* <li>{@link #KUL_WAVE_HEAVY}
* <li>{@link #KUL_DASH_LONG}
* <li>{@link #KUL_WAVE_DOUBLE}
* <li>{@link #KUL_DASH_LONG_HEAVY}
*/
@Internal
public void setKul( byte field_19_kul )
{
this.field_19_kul = field_19_kul;
}
/**
* Get the hresi field for the CHP record.
*/
@Internal
public Hyphenation getHresi()
{
return field_20_hresi;
}
/**
* Set the hresi field for the CHP record.
*/
@Internal
public void setHresi( Hyphenation field_20_hresi )
{
this.field_20_hresi = field_20_hresi;
}
/**
* Kerning distance for characters in run recorded in half points.
*/
@Internal
public int getHpsKern()
{
return field_21_hpsKern;
}
/**
* Kerning distance for characters in run recorded in half points.
*/
@Internal
public void setHpsKern( int field_21_hpsKern )
{
this.field_21_hpsKern = field_21_hpsKern;
}
/**
* Reserved (actually used as vertical offset(?) value).
*/
@Internal
public short getHpsPos()
{
return field_22_hpsPos;
}
/**
* Reserved (actually used as vertical offset(?) value).
*/
@Internal
public void setHpsPos( short field_22_hpsPos )
{
this.field_22_hpsPos = field_22_hpsPos;
}
/**
* Shading.
*/
@Internal
public ShadingDescriptor getShd()
{
return field_23_shd;
}
/**
* Shading.
*/
@Internal
public void setShd( ShadingDescriptor field_23_shd )
{
this.field_23_shd = field_23_shd;
}
/**
* Border.
*/
@Internal
public BorderCode getBrc()
{
return field_24_brc;
}
/**
* Border.
*/
@Internal
public void setBrc( BorderCode field_24_brc )
{
this.field_24_brc = field_24_brc;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when text in run was newly typed when revision marking was enabled.
*/
@Internal
public int getIbstRMark()
{
return field_25_ibstRMark;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when text in run was newly typed when revision marking was enabled.
*/
@Internal
public void setIbstRMark( int field_25_ibstRMark )
{
this.field_25_ibstRMark = field_25_ibstRMark;
}
/**
* Text animation.
*
* @return One of
* <li>{@link #SFXTTEXT_NO}
* <li>{@link #SFXTTEXT_LAS_VEGAS_LIGHTS}
* <li>{@link #SFXTTEXT_BACKGROUND_BLINK}
* <li>{@link #SFXTTEXT_SPARKLE_TEXT}
* <li>{@link #SFXTTEXT_MARCHING_ANTS}
* <li>{@link #SFXTTEXT_MARCHING_RED_ANTS}
* <li>{@link #SFXTTEXT_SHIMMER}
*/
@Internal
public byte getSfxtText()
{
return field_26_sfxtText;
}
/**
* Text animation.
*
* @param field_26_sfxtText
* One of
* <li>{@link #SFXTTEXT_NO}
* <li>{@link #SFXTTEXT_LAS_VEGAS_LIGHTS}
* <li>{@link #SFXTTEXT_BACKGROUND_BLINK}
* <li>{@link #SFXTTEXT_SPARKLE_TEXT}
* <li>{@link #SFXTTEXT_MARCHING_ANTS}
* <li>{@link #SFXTTEXT_MARCHING_RED_ANTS}
* <li>{@link #SFXTTEXT_SHIMMER}
*/
@Internal
public void setSfxtText( byte field_26_sfxtText )
{
this.field_26_sfxtText = field_26_sfxtText;
}
/**
* Used internally by Word.
*/
@Internal
public boolean getFDblBdr()
{
return field_27_fDblBdr;
}
/**
* Used internally by Word.
*/
@Internal
public void setFDblBdr( boolean field_27_fDblBdr )
{
this.field_27_fDblBdr = field_27_fDblBdr;
}
/**
* Used internally by Word.
*/
@Internal
public boolean getFBorderWS()
{
return field_28_fBorderWS;
}
/**
* Used internally by Word.
*/
@Internal
public void setFBorderWS( boolean field_28_fBorderWS )
{
this.field_28_fBorderWS = field_28_fBorderWS;
}
/**
* Collection properties represented by itypFELayout and copt (East Asian layout properties).
*/
@Internal
public short getUfel()
{
return field_29_ufel;
}
/**
* Collection properties represented by itypFELayout and copt (East Asian layout properties).
*/
@Internal
public void setUfel( short field_29_ufel )
{
this.field_29_ufel = field_29_ufel;
}
/**
* Collection of the 5 flags.
*/
@Internal
public byte getCopt()
{
return field_30_copt;
}
/**
* Collection of the 5 flags.
*/
@Internal
public void setCopt( byte field_30_copt )
{
this.field_30_copt = field_30_copt;
}
/**
* Font size for ASCII font.
*/
@Internal
public int getHpsAsci()
{
return field_31_hpsAsci;
}
/**
* Font size for ASCII font.
*/
@Internal
public void setHpsAsci( int field_31_hpsAsci )
{
this.field_31_hpsAsci = field_31_hpsAsci;
}
/**
* Font size for East Asian text.
*/
@Internal
public int getHpsFE()
{
return field_32_hpsFE;
}
/**
* Font size for East Asian text.
*/
@Internal
public void setHpsFE( int field_32_hpsFE )
{
this.field_32_hpsFE = field_32_hpsFE;
}
/**
* Font size for Complex Scripts text.
*/
@Internal
public int getHpsBi()
{
return field_33_hpsBi;
}
/**
* Font size for Complex Scripts text.
*/
@Internal
public void setHpsBi( int field_33_hpsBi )
{
this.field_33_hpsBi = field_33_hpsBi;
}
/**
* an index into the rgffn structure. When chp.fSpec is 1 and the character recorded for the run in the document stream is chSymbol (0x28), chp.ftcSym identifies the font code of the symbol font that will be used to display the symbol character recorded in chp.xchSym..
*/
@Internal
public int getFtcSym()
{
return field_34_ftcSym;
}
/**
* an index into the rgffn structure. When chp.fSpec is 1 and the character recorded for the run in the document stream is chSymbol (0x28), chp.ftcSym identifies the font code of the symbol font that will be used to display the symbol character recorded in chp.xchSym..
*/
@Internal
public void setFtcSym( int field_34_ftcSym )
{
this.field_34_ftcSym = field_34_ftcSym;
}
/**
* When chp.fSpec==1 and the character recorded for the run in the document stream is chSymbol (0x28), the character stored chp.xchSym will be displayed using the font specified in chp.ftcSym..
*/
@Internal
public int getXchSym()
{
return field_35_xchSym;
}
/**
* When chp.fSpec==1 and the character recorded for the run in the document stream is chSymbol (0x28), the character stored chp.xchSym will be displayed using the font specified in chp.ftcSym..
*/
@Internal
public void setXchSym( int field_35_xchSym )
{
this.field_35_xchSym = field_35_xchSym;
}
/**
* Offset in data stream pointing to beginning of a picture when character is a picture character (character is 0x01 and chp.fSpec is 1)..
*/
@Internal
public int getFcPic()
{
return field_36_fcPic;
}
/**
* Offset in data stream pointing to beginning of a picture when character is a picture character (character is 0x01 and chp.fSpec is 1)..
*/
@Internal
public void setFcPic( int field_36_fcPic )
{
this.field_36_fcPic = field_36_fcPic;
}
/**
* Offset in data stream pointing to beginning of a picture when character is an OLE1 object character (character is 0x20 and chp.fSpec is 1, chp.fOle2 is 0)..
*/
@Internal
public int getFcObj()
{
return field_37_fcObj;
}
/**
* Offset in data stream pointing to beginning of a picture when character is an OLE1 object character (character is 0x20 and chp.fSpec is 1, chp.fOle2 is 0)..
*/
@Internal
public void setFcObj( int field_37_fcObj )
{
this.field_37_fcObj = field_37_fcObj;
}
/**
* An object ID for an OLE object, only set if chp.fSpec and chp.fOle2 are both true, and chp.fObj..
*/
@Internal
public int getLTagObj()
{
return field_38_lTagObj;
}
/**
* An object ID for an OLE object, only set if chp.fSpec and chp.fOle2 are both true, and chp.fObj..
*/
@Internal
public void setLTagObj( int field_38_lTagObj )
{
this.field_38_lTagObj = field_38_lTagObj;
}
/**
* Points to location of picture data, only if chp.fSpec is true..
*/
@Internal
public int getFcData()
{
return field_39_fcData;
}
/**
* Points to location of picture data, only if chp.fSpec is true..
*/
@Internal
public void setFcData( int field_39_fcData )
{
this.field_39_fcData = field_39_fcData;
}
/**
* Get the hresiOld field for the CHP record.
*/
@Internal
public Hyphenation getHresiOld()
{
return field_40_hresiOld;
}
/**
* Set the hresiOld field for the CHP record.
*/
@Internal
public void setHresiOld( Hyphenation field_40_hresiOld )
{
this.field_40_hresiOld = field_40_hresiOld;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when text in run was deleted when revision marking was enabled..
*/
@Internal
public int getIbstRMarkDel()
{
return field_41_ibstRMarkDel;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when text in run was deleted when revision marking was enabled..
*/
@Internal
public void setIbstRMarkDel( int field_41_ibstRMarkDel )
{
this.field_41_ibstRMarkDel = field_41_ibstRMarkDel;
}
/**
* Date/time at which this run of text was entered/modified by the author (Only recorded when revision marking is on.).
*/
@Internal
public DateAndTime getDttmRMark()
{
return field_42_dttmRMark;
}
/**
* Date/time at which this run of text was entered/modified by the author (Only recorded when revision marking is on.).
*/
@Internal
public void setDttmRMark( DateAndTime field_42_dttmRMark )
{
this.field_42_dttmRMark = field_42_dttmRMark;
}
/**
* Date/time at which this run of text was deleted by the author (Only recorded when revision marking is on.).
*/
@Internal
public DateAndTime getDttmRMarkDel()
{
return field_43_dttmRMarkDel;
}
/**
* Date/time at which this run of text was deleted by the author (Only recorded when revision marking is on.).
*/
@Internal
public void setDttmRMarkDel( DateAndTime field_43_dttmRMarkDel )
{
this.field_43_dttmRMarkDel = field_43_dttmRMarkDel;
}
/**
* Index to character style descriptor in the stylesheet that tags this run of text. When istd is istdNormalChar (10 decimal), characters in run are not affected by a character style. If chp.istd contains any other value, chpx of the specified character style are applied to CHP for this run before any other exceptional properties are applied..
*/
@Internal
public int getIstd()
{
return field_44_istd;
}
/**
* Index to character style descriptor in the stylesheet that tags this run of text. When istd is istdNormalChar (10 decimal), characters in run are not affected by a character style. If chp.istd contains any other value, chpx of the specified character style are applied to CHP for this run before any other exceptional properties are applied..
*/
@Internal
public void setIstd( int field_44_istd )
{
this.field_44_istd = field_44_istd;
}
/**
* An index to strings displayed as reasons for actions taken by Word's AutoFormat code.
*/
@Internal
public int getIdslRMReason()
{
return field_45_idslRMReason;
}
/**
* An index to strings displayed as reasons for actions taken by Word's AutoFormat code.
*/
@Internal
public void setIdslRMReason( int field_45_idslRMReason )
{
this.field_45_idslRMReason = field_45_idslRMReason;
}
/**
* An index to strings displayed as reasons for actions taken by Word's AutoFormat code.
*/
@Internal
public int getIdslReasonDel()
{
return field_46_idslReasonDel;
}
/**
* An index to strings displayed as reasons for actions taken by Word's AutoFormat code.
*/
@Internal
public void setIdslReasonDel( int field_46_idslReasonDel )
{
this.field_46_idslReasonDel = field_46_idslReasonDel;
}
/**
* Code page of run in pre-Unicode files.
*/
@Internal
public int getCpg()
{
return field_47_cpg;
}
/**
* Code page of run in pre-Unicode files.
*/
@Internal
public void setCpg( int field_47_cpg )
{
this.field_47_cpg = field_47_cpg;
}
/**
* Get the Highlight field for the CHP record.
*/
@Internal
public short getHighlight()
{
return field_48_Highlight;
}
/**
* Set the Highlight field for the CHP record.
*/
@Internal
public void setHighlight( short field_48_Highlight )
{
this.field_48_Highlight = field_48_Highlight;
}
/**
* Get the CharsetFlags field for the CHP record.
*/
@Internal
public short getCharsetFlags()
{
return field_49_CharsetFlags;
}
/**
* Set the CharsetFlags field for the CHP record.
*/
@Internal
public void setCharsetFlags( short field_49_CharsetFlags )
{
this.field_49_CharsetFlags = field_49_CharsetFlags;
}
/**
* Get the chse field for the CHP record.
*/
@Internal
public short getChse()
{
return field_50_chse;
}
/**
* Set the chse field for the CHP record.
*/
@Internal
public void setChse( short field_50_chse )
{
this.field_50_chse = field_50_chse;
}
/**
* properties have been changed with revision marking on.
*/
@Internal
public boolean getFPropRMark()
{
return field_51_fPropRMark;
}
/**
* properties have been changed with revision marking on.
*/
@Internal
public void setFPropRMark( boolean field_51_fPropRMark )
{
this.field_51_fPropRMark = field_51_fPropRMark;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when properties have been changed when revision marking was enabled..
*/
@Internal
public int getIbstPropRMark()
{
return field_52_ibstPropRMark;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when properties have been changed when revision marking was enabled..
*/
@Internal
public void setIbstPropRMark( int field_52_ibstPropRMark )
{
this.field_52_ibstPropRMark = field_52_ibstPropRMark;
}
/**
* Date/time at which properties of this were changed for this run of text by the author. (Only recorded when revision marking is on.).
*/
@Internal
public DateAndTime getDttmPropRMark()
{
return field_53_dttmPropRMark;
}
/**
* Date/time at which properties of this were changed for this run of text by the author. (Only recorded when revision marking is on.).
*/
@Internal
public void setDttmPropRMark( DateAndTime field_53_dttmPropRMark )
{
this.field_53_dttmPropRMark = field_53_dttmPropRMark;
}
/**
* When chp.wConflict!=0, this is TRUE when text is part of the original version of text. When FALSE, text is alternative introduced by reconciliation operation..
*/
@Internal
public boolean getFConflictOrig()
{
return field_54_fConflictOrig;
}
/**
* When chp.wConflict!=0, this is TRUE when text is part of the original version of text. When FALSE, text is alternative introduced by reconciliation operation..
*/
@Internal
public void setFConflictOrig( boolean field_54_fConflictOrig )
{
this.field_54_fConflictOrig = field_54_fConflictOrig;
}
/**
* When fConflictOtherDel==fTrue, the other side of a reconciliation conflict causes this text to be deleted.
*/
@Internal
public boolean getFConflictOtherDel()
{
return field_55_fConflictOtherDel;
}
/**
* When fConflictOtherDel==fTrue, the other side of a reconciliation conflict causes this text to be deleted.
*/
@Internal
public void setFConflictOtherDel( boolean field_55_fConflictOtherDel )
{
this.field_55_fConflictOtherDel = field_55_fConflictOtherDel;
}
/**
* When != 0, index number that identifies all text participating in a particular conflict incident.
*/
@Internal
public int getWConflict()
{
return field_56_wConflict;
}
/**
* When != 0, index number that identifies all text participating in a particular conflict incident.
*/
@Internal
public void setWConflict( int field_56_wConflict )
{
this.field_56_wConflict = field_56_wConflict;
}
/**
* Who made this change for this side of the conflict..
*/
@Internal
public int getIbstConflict()
{
return field_57_IbstConflict;
}
/**
* Who made this change for this side of the conflict..
*/
@Internal
public void setIbstConflict( int field_57_IbstConflict )
{
this.field_57_IbstConflict = field_57_IbstConflict;
}
/**
* When the change was made.
*/
@Internal
public DateAndTime getDttmConflict()
{
return field_58_dttmConflict;
}
/**
* When the change was made.
*/
@Internal
public void setDttmConflict( DateAndTime field_58_dttmConflict )
{
this.field_58_dttmConflict = field_58_dttmConflict;
}
/**
* the number for a ListNum field is being tracked in xstDispFldRMark. If that number is different from the current value, the number has changed. Only valid for ListNum fields..
*/
@Internal
public boolean getFDispFldRMark()
{
return field_59_fDispFldRMark;
}
/**
* the number for a ListNum field is being tracked in xstDispFldRMark. If that number is different from the current value, the number has changed. Only valid for ListNum fields..
*/
@Internal
public void setFDispFldRMark( boolean field_59_fDispFldRMark )
{
this.field_59_fDispFldRMark = field_59_fDispFldRMark;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when ListNum field numbering has been changed when revision marking was enabled..
*/
@Internal
public int getIbstDispFldRMark()
{
return field_60_ibstDispFldRMark;
}
/**
* Index to author IDs stored in hsttbfRMark. Used when ListNum field numbering has been changed when revision marking was enabled..
*/
@Internal
public void setIbstDispFldRMark( int field_60_ibstDispFldRMark )
{
this.field_60_ibstDispFldRMark = field_60_ibstDispFldRMark;
}
/**
* The date for the ListNum field number change.
*/
@Internal
public DateAndTime getDttmDispFldRMark()
{
return field_61_dttmDispFldRMark;
}
/**
* The date for the ListNum field number change.
*/
@Internal
public void setDttmDispFldRMark( DateAndTime field_61_dttmDispFldRMark )
{
this.field_61_dttmDispFldRMark = field_61_dttmDispFldRMark;
}
/**
* The string value of the ListNum field when revision mark tracking began.
*/
@Internal
public byte[] getXstDispFldRMark()
{
return field_62_xstDispFldRMark;
}
/**
* The string value of the ListNum field when revision mark tracking began.
*/
@Internal
public void setXstDispFldRMark( byte[] field_62_xstDispFldRMark )
{
this.field_62_xstDispFldRMark = field_62_xstDispFldRMark;
}
/**
* Offset in the data stream indicating the location of OLE object data.
*/
@Internal
public int getFcObjp()
{
return field_63_fcObjp;
}
/**
* Offset in the data stream indicating the location of OLE object data.
*/
@Internal
public void setFcObjp( int field_63_fcObjp )
{
this.field_63_fcObjp = field_63_fcObjp;
}
/**
* Line BReak code for xchCRJ.
*
* @return One of
* <li>{@link #LBRCRJ_NONE}
* <li>{@link #LBRCRJ_LEFT}
* <li>{@link #LBRCRJ_RIGHT}
* <li>{@link #LBRCRJ_BOTH}
*/
@Internal
public byte getLbrCRJ()
{
return field_64_lbrCRJ;
}
/**
* Line BReak code for xchCRJ.
*
* @param field_64_lbrCRJ
* One of
* <li>{@link #LBRCRJ_NONE}
* <li>{@link #LBRCRJ_LEFT}
* <li>{@link #LBRCRJ_RIGHT}
* <li>{@link #LBRCRJ_BOTH}
*/
@Internal
public void setLbrCRJ( byte field_64_lbrCRJ )
{
this.field_64_lbrCRJ = field_64_lbrCRJ;
}
/**
* Special hidden for leading emphasis (always hidden).
*/
@Internal
public boolean getFSpecVanish()
{
return field_65_fSpecVanish;
}
/**
* Special hidden for leading emphasis (always hidden).
*/
@Internal
public void setFSpecVanish( boolean field_65_fSpecVanish )
{
this.field_65_fSpecVanish = field_65_fSpecVanish;
}
/**
* Used for character property revision marking. The chp at the time fHasOldProps is set to 1, the is the old chp..
*/
@Internal
public boolean getFHasOldProps()
{
return field_66_fHasOldProps;
}
/**
* Used for character property revision marking. The chp at the time fHasOldProps is set to 1, the is the old chp..
*/
@Internal
public void setFHasOldProps( boolean field_66_fHasOldProps )
{
this.field_66_fHasOldProps = field_66_fHasOldProps;
}
/**
* Mark the character as hidden..
*/
@Internal
public boolean getFSdtVanish()
{
return field_67_fSdtVanish;
}
/**
* Mark the character as hidden..
*/
@Internal
public void setFSdtVanish( boolean field_67_fSdtVanish )
{
this.field_67_fSdtVanish = field_67_fSdtVanish;
}
/**
* Get the wCharScale field for the CHP record.
*/
@Internal
public int getWCharScale()
{
return field_68_wCharScale;
}
/**
* Set the wCharScale field for the CHP record.
*/
@Internal
public void setWCharScale( int field_68_wCharScale )
{
this.field_68_wCharScale = field_68_wCharScale;
}
/**
* Sets the fBold field value.
* Text is bold
*/
@Internal
public void setFBold( boolean value )
{
field_1_grpfChp = (int)fBold.setBoolean(field_1_grpfChp, value);
}
/**
* Text is bold
* @return the fBold field value.
*/
@Internal
public boolean isFBold()
{
return fBold.isSet(field_1_grpfChp);
}
/**
* Sets the fItalic field value.
* Italic
*/
@Internal
public void setFItalic( boolean value )
{
field_1_grpfChp = (int)fItalic.setBoolean(field_1_grpfChp, value);
}
/**
* Italic
* @return the fItalic field value.
*/
@Internal
public boolean isFItalic()
{
return fItalic.isSet(field_1_grpfChp);
}
/**
* Sets the fRMarkDel field value.
* has been deleted and will be displayed with strikethrough when revision marked text is to be displayed
*/
@Internal
public void setFRMarkDel( boolean value )
{
field_1_grpfChp = (int)fRMarkDel.setBoolean(field_1_grpfChp, value);
}
/**
* has been deleted and will be displayed with strikethrough when revision marked text is to be displayed
* @return the fRMarkDel field value.
*/
@Internal
public boolean isFRMarkDel()
{
return fRMarkDel.isSet(field_1_grpfChp);
}
/**
* Sets the fOutline field value.
* Outlined
*/
@Internal
public void setFOutline( boolean value )
{
field_1_grpfChp = (int)fOutline.setBoolean(field_1_grpfChp, value);
}
/**
* Outlined
* @return the fOutline field value.
*/
@Internal
public boolean isFOutline()
{
return fOutline.isSet(field_1_grpfChp);
}
/**
* Sets the fFldVanish field value.
* Used internally by Word
*/
@Internal
public void setFFldVanish( boolean value )
{
field_1_grpfChp = (int)fFldVanish.setBoolean(field_1_grpfChp, value);
}
/**
* Used internally by Word
* @return the fFldVanish field value.
*/
@Internal
public boolean isFFldVanish()
{
return fFldVanish.isSet(field_1_grpfChp);
}
/**
* Sets the fSmallCaps field value.
* Displayed with small caps
*/
@Internal
public void setFSmallCaps( boolean value )
{
field_1_grpfChp = (int)fSmallCaps.setBoolean(field_1_grpfChp, value);
}
/**
* Displayed with small caps
* @return the fSmallCaps field value.
*/
@Internal
public boolean isFSmallCaps()
{
return fSmallCaps.isSet(field_1_grpfChp);
}
/**
* Sets the fCaps field value.
* Displayed with caps
*/
@Internal
public void setFCaps( boolean value )
{
field_1_grpfChp = (int)fCaps.setBoolean(field_1_grpfChp, value);
}
/**
* Displayed with caps
* @return the fCaps field value.
*/
@Internal
public boolean isFCaps()
{
return fCaps.isSet(field_1_grpfChp);
}
/**
* Sets the fVanish field value.
* text has hidden format, and is not displayed unless fPagHidden is set in the DOP
*/
@Internal
public void setFVanish( boolean value )
{
field_1_grpfChp = (int)fVanish.setBoolean(field_1_grpfChp, value);
}
/**
* text has hidden format, and is not displayed unless fPagHidden is set in the DOP
* @return the fVanish field value.
*/
@Internal
public boolean isFVanish()
{
return fVanish.isSet(field_1_grpfChp);
}
/**
* Sets the fRMark field value.
* text is newly typed since the last time revision marks have been accepted and will be displayed with an underline when revision marked text is to be displayed
*/
@Internal
public void setFRMark( boolean value )
{
field_1_grpfChp = (int)fRMark.setBoolean(field_1_grpfChp, value);
}
/**
* text is newly typed since the last time revision marks have been accepted and will be displayed with an underline when revision marked text is to be displayed
* @return the fRMark field value.
*/
@Internal
public boolean isFRMark()
{
return fRMark.isSet(field_1_grpfChp);
}
/**
* Sets the fSpec field value.
* Character is a Word special character
*/
@Internal
public void setFSpec( boolean value )
{
field_1_grpfChp = (int)fSpec.setBoolean(field_1_grpfChp, value);
}
/**
* Character is a Word special character
* @return the fSpec field value.
*/
@Internal
public boolean isFSpec()
{
return fSpec.isSet(field_1_grpfChp);
}
/**
* Sets the fStrike field value.
* Displayed with strikethrough
*/
@Internal
public void setFStrike( boolean value )
{
field_1_grpfChp = (int)fStrike.setBoolean(field_1_grpfChp, value);
}
/**
* Displayed with strikethrough
* @return the fStrike field value.
*/
@Internal
public boolean isFStrike()
{
return fStrike.isSet(field_1_grpfChp);
}
/**
* Sets the fObj field value.
* Embedded objec
*/
@Internal
public void setFObj( boolean value )
{
field_1_grpfChp = (int)fObj.setBoolean(field_1_grpfChp, value);
}
/**
* Embedded objec
* @return the fObj field value.
*/
@Internal
public boolean isFObj()
{
return fObj.isSet(field_1_grpfChp);
}
/**
* Sets the fShadow field value.
* Character is drawn with a shadow
*/
@Internal
public void setFShadow( boolean value )
{
field_1_grpfChp = (int)fShadow.setBoolean(field_1_grpfChp, value);
}
/**
* Character is drawn with a shadow
* @return the fShadow field value.
*/
@Internal
public boolean isFShadow()
{
return fShadow.isSet(field_1_grpfChp);
}
/**
* Sets the fLowerCase field value.
* Character is displayed in lower case. This field may be set to 1 only when chp.fSmallCaps is 1.
*/
@Internal
public void setFLowerCase( boolean value )
{
field_1_grpfChp = (int)fLowerCase.setBoolean(field_1_grpfChp, value);
}
/**
* Character is displayed in lower case. This field may be set to 1 only when chp.fSmallCaps is 1.
* @return the fLowerCase field value.
*/
@Internal
public boolean isFLowerCase()
{
return fLowerCase.isSet(field_1_grpfChp);
}
/**
* Sets the fData field value.
* chp.fcPic points to an FFDATA, the data structure binary data used by Word to describe a form field. The bit chp.fData may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01)
*/
@Internal
public void setFData( boolean value )
{
field_1_grpfChp = (int)fData.setBoolean(field_1_grpfChp, value);
}
/**
* chp.fcPic points to an FFDATA, the data structure binary data used by Word to describe a form field. The bit chp.fData may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01)
* @return the fData field value.
*/
@Internal
public boolean isFData()
{
return fData.isSet(field_1_grpfChp);
}
/**
* Sets the fOle2 field value.
* chp.lTagObj specifies a particular object in the object stream that specifies the particular OLE object in the stream that should be displayed when the chPicture fSpec character that is tagged with the fOle2 is encountered. The bit chp.fOle2 may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01).
*/
@Internal
public void setFOle2( boolean value )
{
field_1_grpfChp = (int)fOle2.setBoolean(field_1_grpfChp, value);
}
/**
* chp.lTagObj specifies a particular object in the object stream that specifies the particular OLE object in the stream that should be displayed when the chPicture fSpec character that is tagged with the fOle2 is encountered. The bit chp.fOle2 may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01).
* @return the fOle2 field value.
*/
@Internal
public boolean isFOle2()
{
return fOle2.isSet(field_1_grpfChp);
}
/**
* Sets the fEmboss field value.
* Text is embossed
*/
@Internal
public void setFEmboss( boolean value )
{
field_1_grpfChp = (int)fEmboss.setBoolean(field_1_grpfChp, value);
}
/**
* Text is embossed
* @return the fEmboss field value.
*/
@Internal
public boolean isFEmboss()
{
return fEmboss.isSet(field_1_grpfChp);
}
/**
* Sets the fImprint field value.
* Text is engraved
*/
@Internal
public void setFImprint( boolean value )
{
field_1_grpfChp = (int)fImprint.setBoolean(field_1_grpfChp, value);
}
/**
* Text is engraved
* @return the fImprint field value.
*/
@Internal
public boolean isFImprint()
{
return fImprint.isSet(field_1_grpfChp);
}
/**
* Sets the fDStrike field value.
* Displayed with double strikethrough
*/
@Internal
public void setFDStrike( boolean value )
{
field_1_grpfChp = (int)fDStrike.setBoolean(field_1_grpfChp, value);
}
/**
* Displayed with double strikethrough
* @return the fDStrike field value.
*/
@Internal
public boolean isFDStrike()
{
return fDStrike.isSet(field_1_grpfChp);
}
/**
* Sets the fUsePgsuSettings field value.
* Used internally by Word
*/
@Internal
public void setFUsePgsuSettings( boolean value )
{
field_1_grpfChp = (int)fUsePgsuSettings.setBoolean(field_1_grpfChp, value);
}
/**
* Used internally by Word
* @return the fUsePgsuSettings field value.
*/
@Internal
public boolean isFUsePgsuSettings()
{
return fUsePgsuSettings.isSet(field_1_grpfChp);
}
/**
* Sets the fBoldBi field value.
* Complex Scripts text is bold
*/
@Internal
public void setFBoldBi( boolean value )
{
field_1_grpfChp = (int)fBoldBi.setBoolean(field_1_grpfChp, value);
}
/**
* Complex Scripts text is bold
* @return the fBoldBi field value.
*/
@Internal
public boolean isFBoldBi()
{
return fBoldBi.isSet(field_1_grpfChp);
}
/**
* Sets the fComplexScripts field value.
* Complex Scripts text that requires special processing to display and process
*/
@Internal
public void setFComplexScripts( boolean value )
{
field_1_grpfChp = (int)fComplexScripts.setBoolean(field_1_grpfChp, value);
}
/**
* Complex Scripts text that requires special processing to display and process
* @return the fComplexScripts field value.
*/
@Internal
public boolean isFComplexScripts()
{
return fComplexScripts.isSet(field_1_grpfChp);
}
/**
* Sets the fItalicBi field value.
* Complex Scripts text is italics
*/
@Internal
public void setFItalicBi( boolean value )
{
field_1_grpfChp = (int)fItalicBi.setBoolean(field_1_grpfChp, value);
}
/**
* Complex Scripts text is italics
* @return the fItalicBi field value.
*/
@Internal
public boolean isFItalicBi()
{
return fItalicBi.isSet(field_1_grpfChp);
}
/**
* Sets the fBiDi field value.
* Complex Scripts right-to-left text that requires special processing to display and process (character reordering; contextual shaping; display of combining characters and diacritics; specialized justification rules; cursor positioning)
*/
@Internal
public void setFBiDi( boolean value )
{
field_1_grpfChp = (int)fBiDi.setBoolean(field_1_grpfChp, value);
}
/**
* Complex Scripts right-to-left text that requires special processing to display and process (character reordering; contextual shaping; display of combining characters and diacritics; specialized justification rules; cursor positioning)
* @return the fBiDi field value.
*/
@Internal
public boolean isFBiDi()
{
return fBiDi.isSet(field_1_grpfChp);
}
/**
* Sets the itypFELayout field value.
*
*/
@Internal
public void setItypFELayout( short value )
{
field_29_ufel = (short)itypFELayout.setValue(field_29_ufel, value);
}
/**
*
* @return the itypFELayout field value.
*/
@Internal
public short getItypFELayout()
{
return ( short )itypFELayout.getValue(field_29_ufel);
}
/**
* Sets the fTNY field value.
* Tatenakayoko: Horizontal-in-vertical (range of text in a direction perpendicular to the text flow) is used
*/
@Internal
public void setFTNY( boolean value )
{
field_29_ufel = (short)fTNY.setBoolean(field_29_ufel, value);
}
/**
* Tatenakayoko: Horizontal-in-vertical (range of text in a direction perpendicular to the text flow) is used
* @return the fTNY field value.
*/
@Internal
public boolean isFTNY()
{
return fTNY.isSet(field_29_ufel);
}
/**
* Sets the fWarichu field value.
* Two lines in one (text in the group is displayed as two half-height lines within a line)
*/
@Internal
public void setFWarichu( boolean value )
{
field_29_ufel = (short)fWarichu.setBoolean(field_29_ufel, value);
}
/**
* Two lines in one (text in the group is displayed as two half-height lines within a line)
* @return the fWarichu field value.
*/
@Internal
public boolean isFWarichu()
{
return fWarichu.isSet(field_29_ufel);
}
/**
* Sets the fKumimoji field value.
* combine characters
*/
@Internal
public void setFKumimoji( boolean value )
{
field_29_ufel = (short)fKumimoji.setBoolean(field_29_ufel, value);
}
/**
* combine characters
* @return the fKumimoji field value.
*/
@Internal
public boolean isFKumimoji()
{
return fKumimoji.isSet(field_29_ufel);
}
/**
* Sets the fRuby field value.
* Phonetic guide
*/
@Internal
public void setFRuby( boolean value )
{
field_29_ufel = (short)fRuby.setBoolean(field_29_ufel, value);
}
/**
* Phonetic guide
* @return the fRuby field value.
*/
@Internal
public boolean isFRuby()
{
return fRuby.isSet(field_29_ufel);
}
/**
* Sets the fLSFitText field value.
* fit text
*/
@Internal
public void setFLSFitText( boolean value )
{
field_29_ufel = (short)fLSFitText.setBoolean(field_29_ufel, value);
}
/**
* fit text
* @return the fLSFitText field value.
*/
@Internal
public boolean isFLSFitText()
{
return fLSFitText.isSet(field_29_ufel);
}
/**
* Sets the spare field value.
* Unused
*/
@Internal
public void setSpare( byte value )
{
field_29_ufel = (short)spare.setValue(field_29_ufel, value);
}
/**
* Unused
* @return the spare field value.
*/
@Internal
public byte getSpare()
{
return ( byte )spare.getValue(field_29_ufel);
}
/**
* Sets the iWarichuBracket field value.
* Bracket character for two-lines-in-one
*/
@Internal
public void setIWarichuBracket( byte value )
{
field_30_copt = (byte)iWarichuBracket.setValue(field_30_copt, value);
}
/**
* Bracket character for two-lines-in-one
* @return the iWarichuBracket field value.
*/
@Internal
public byte getIWarichuBracket()
{
return ( byte )iWarichuBracket.getValue(field_30_copt);
}
/**
* Sets the fWarichuNoOpenBracket field value.
* Two-lines-in-one uses no open
*/
@Internal
public void setFWarichuNoOpenBracket( boolean value )
{
field_30_copt = (byte)fWarichuNoOpenBracket.setBoolean(field_30_copt, value);
}
/**
* Two-lines-in-one uses no open
* @return the fWarichuNoOpenBracket field value.
*/
@Internal
public boolean isFWarichuNoOpenBracket()
{
return fWarichuNoOpenBracket.isSet(field_30_copt);
}
/**
* Sets the fTNYCompress field value.
* fit text in line
*/
@Internal
public void setFTNYCompress( boolean value )
{
field_30_copt = (byte)fTNYCompress.setBoolean(field_30_copt, value);
}
/**
* fit text in line
* @return the fTNYCompress field value.
*/
@Internal
public boolean isFTNYCompress()
{
return fTNYCompress.isSet(field_30_copt);
}
/**
* Sets the fTNYFetchTxm field value.
* fetch text metrics
*/
@Internal
public void setFTNYFetchTxm( boolean value )
{
field_30_copt = (byte)fTNYFetchTxm.setBoolean(field_30_copt, value);
}
/**
* fetch text metrics
* @return the fTNYFetchTxm field value.
*/
@Internal
public boolean isFTNYFetchTxm()
{
return fTNYFetchTxm.isSet(field_30_copt);
}
/**
* Sets the fCellFitText field value.
* Fit text in cell
*/
@Internal
public void setFCellFitText( boolean value )
{
field_30_copt = (byte)fCellFitText.setBoolean(field_30_copt, value);
}
/**
* Fit text in cell
* @return the fCellFitText field value.
*/
@Internal
public boolean isFCellFitText()
{
return fCellFitText.isSet(field_30_copt);
}
/**
* Sets the unused field value.
* Not used
*/
@Internal
public void setUnused( boolean value )
{
field_30_copt = (byte)unused.setBoolean(field_30_copt, value);
}
/**
* Not used
* @return the unused field value.
*/
@Internal
public boolean isUnused()
{
return unused.isSet(field_30_copt);
}
/**
* Sets the icoHighlight field value.
* Highlight color (see chp.ico)
*/
@Internal
public void setIcoHighlight( byte value )
{
field_48_Highlight = (short)icoHighlight.setValue(field_48_Highlight, value);
}
/**
* Highlight color (see chp.ico)
* @return the icoHighlight field value.
*/
@Internal
public byte getIcoHighlight()
{
return ( byte )icoHighlight.getValue(field_48_Highlight);
}
/**
* Sets the fHighlight field value.
* When 1, characters are highlighted with color specified by chp.icoHighlight
*/
@Internal
public void setFHighlight( boolean value )
{
field_48_Highlight = (short)fHighlight.setBoolean(field_48_Highlight, value);
}
/**
* When 1, characters are highlighted with color specified by chp.icoHighlight
* @return the fHighlight field value.
*/
@Internal
public boolean isFHighlight()
{
return fHighlight.isSet(field_48_Highlight);
}
/**
* Sets the fChsDiff field value.
* Pre-Unicode files, char's char set different from FIB char set
*/
@Internal
public void setFChsDiff( boolean value )
{
field_49_CharsetFlags = (short)fChsDiff.setBoolean(field_49_CharsetFlags, value);
}
/**
* Pre-Unicode files, char's char set different from FIB char set
* @return the fChsDiff field value.
*/
@Internal
public boolean isFChsDiff()
{
return fChsDiff.isSet(field_49_CharsetFlags);
}
/**
* Sets the fMacChs field value.
* fTrue if char's are Macintosh char set
*/
@Internal
public void setFMacChs( boolean value )
{
field_49_CharsetFlags = (short)fMacChs.setBoolean(field_49_CharsetFlags, value);
}
/**
* fTrue if char's are Macintosh char set
* @return the fMacChs field value.
*/
@Internal
public boolean isFMacChs()
{
return fMacChs.isSet(field_49_CharsetFlags);
}
} // END OF CLASS
| qhm123/POI-Android | ppt/scratchpad/src/org/apache/poi/hwpf/model/types/CHPAbstractType.java |
179,707 | /*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.chainimport;
import static java.util.concurrent.TimeUnit.SECONDS;
import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.core.BlockImporter;
import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator;
import org.hyperledger.besu.ethereum.mainnet.BlockImportResult;
import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec;
import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
import org.hyperledger.besu.ethereum.util.RawBlockIterator;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.base.MoreObjects;
import com.google.common.base.Stopwatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Tool for importing rlp-encoded block data from files. */
public class RlpBlockImporter implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(RlpBlockImporter.class);
private final Semaphore blockBacklog = new Semaphore(2);
private final ExecutorService validationExecutor = Executors.newCachedThreadPool();
private final ExecutorService importExecutor = Executors.newSingleThreadExecutor();
private long cumulativeGas;
private long segmentGas;
private final Stopwatch cumulativeTimer = Stopwatch.createUnstarted();
private final Stopwatch segmentTimer = Stopwatch.createUnstarted();
private static final long SEGMENT_SIZE = 1000;
/** Default Constructor. */
public RlpBlockImporter() {}
/**
* Imports blocks that are stored as concatenated RLP sections in the given file into Besu's block
* storage.
*
* @param blocks Path to the file containing the blocks
* @param besuController the BesuController that defines blockchain behavior
* @param skipPowValidation Skip proof of work validation (correct mix hash and difficulty)
* @return the import result
* @throws IOException On Failure
*/
public RlpBlockImporter.ImportResult importBlockchain(
final Path blocks, final BesuController besuController, final boolean skipPowValidation)
throws IOException {
return importBlockchain(blocks, besuController, skipPowValidation, 0L, Long.MAX_VALUE);
}
/**
* Import blockchain.
*
* @param blocks the blocks
* @param besuController the besu controller
* @param skipPowValidation the skip pow validation
* @param startBlock the start block
* @param endBlock the end block
* @return the rlp block importer - import result
* @throws IOException the io exception
*/
public RlpBlockImporter.ImportResult importBlockchain(
final Path blocks,
final BesuController besuController,
final boolean skipPowValidation,
final long startBlock,
final long endBlock)
throws IOException {
final ProtocolSchedule protocolSchedule = besuController.getProtocolSchedule();
final ProtocolContext context = besuController.getProtocolContext();
final MutableBlockchain blockchain = context.getBlockchain();
int count = 0;
final BlockHeaderFunctions blockHeaderFunctions =
ScheduleBasedBlockHeaderFunctions.create(protocolSchedule);
try (final RawBlockIterator iterator = new RawBlockIterator(blocks, blockHeaderFunctions)) {
BlockHeader previousHeader = null;
CompletableFuture<Void> previousBlockFuture = null;
final AtomicReference<Throwable> threadedException = new AtomicReference<>();
while (iterator.hasNext()) {
final Block block = iterator.next();
final BlockHeader header = block.getHeader();
final long blockNumber = header.getNumber();
if (blockNumber == BlockHeader.GENESIS_BLOCK_NUMBER
|| blockNumber < startBlock
|| blockNumber >= endBlock) {
continue;
}
if (blockchain.contains(header.getHash())) {
continue;
}
if (previousHeader == null) {
previousHeader = lookupPreviousHeader(blockchain, header);
}
final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(header);
final BlockHeader lastHeader = previousHeader;
final CompletableFuture<Void> validationFuture =
CompletableFuture.runAsync(
() -> validateBlock(protocolSpec, context, lastHeader, header, skipPowValidation),
validationExecutor);
final CompletableFuture<Void> extractingFuture =
CompletableFuture.runAsync(() -> extractSignatures(block));
final CompletableFuture<Void> calculationFutures;
if (previousBlockFuture == null) {
calculationFutures = extractingFuture;
} else {
calculationFutures = CompletableFuture.allOf(extractingFuture, previousBlockFuture);
}
try {
do {
final Throwable t = (Exception) threadedException.get();
if (t != null) {
throw new RuntimeException("Error importing block " + header.getNumber(), t);
}
} while (!blockBacklog.tryAcquire(1, SECONDS));
} catch (final InterruptedException e) {
LOG.error("Interrupted adding to backlog.", e);
break;
}
previousBlockFuture =
validationFuture.runAfterBothAsync(
calculationFutures,
() ->
evaluateBlock(
context,
block,
header,
protocolSchedule.getByBlockHeader(header),
skipPowValidation),
importExecutor);
previousBlockFuture.exceptionally(
exception -> {
threadedException.set(exception);
return null;
});
++count;
previousHeader = header;
}
if (previousBlockFuture != null) {
previousBlockFuture.join();
}
logProgress(blockchain.getChainHeadBlockNumber());
return new RlpBlockImporter.ImportResult(
blockchain.getChainHead().getTotalDifficulty(), count);
}
}
private void extractSignatures(final Block block) {
final List<CompletableFuture<Void>> futures =
new ArrayList<>(block.getBody().getTransactions().size());
for (final Transaction tx : block.getBody().getTransactions()) {
futures.add(CompletableFuture.runAsync(tx::getSender, validationExecutor));
}
for (final CompletableFuture<Void> future : futures) {
future.join();
}
}
private void validateBlock(
final ProtocolSpec protocolSpec,
final ProtocolContext context,
final BlockHeader previousHeader,
final BlockHeader header,
final boolean skipPowValidation) {
final BlockHeaderValidator blockHeaderValidator = protocolSpec.getBlockHeaderValidator();
final boolean validHeader =
blockHeaderValidator.validateHeader(
header,
previousHeader,
context,
skipPowValidation
? HeaderValidationMode.LIGHT_DETACHED_ONLY
: HeaderValidationMode.DETACHED_ONLY);
if (!validHeader) {
throw new IllegalStateException("Invalid header at block number " + header.getNumber() + ".");
}
}
private void evaluateBlock(
final ProtocolContext context,
final Block block,
final BlockHeader header,
final ProtocolSpec protocolSpec,
final boolean skipPowValidation) {
try {
cumulativeTimer.start();
segmentTimer.start();
final BlockImporter blockImporter = protocolSpec.getBlockImporter();
final BlockImportResult blockImported =
blockImporter.importBlock(
context,
block,
skipPowValidation
? HeaderValidationMode.LIGHT_SKIP_DETACHED
: HeaderValidationMode.SKIP_DETACHED,
skipPowValidation ? HeaderValidationMode.LIGHT : HeaderValidationMode.FULL);
if (!blockImported.isImported()) {
throw new IllegalStateException(
"Invalid block at block number " + header.getNumber() + ".");
}
} finally {
blockBacklog.release();
cumulativeTimer.stop();
segmentTimer.stop();
final long thisGas = block.getHeader().getGasUsed();
cumulativeGas += thisGas;
segmentGas += thisGas;
if (header.getNumber() % SEGMENT_SIZE == 0) {
logProgress(header.getNumber());
}
}
}
private void logProgress(final long blockNum) {
final long elapseMicros = segmentTimer.elapsed(TimeUnit.MICROSECONDS);
//noinspection PlaceholderCountMatchesArgumentCount
LOG.info(
"Import at block {} / {} gas {} micros / Mgps {} segment {} cumulative",
blockNum,
segmentGas,
elapseMicros,
segmentGas / (double) elapseMicros,
cumulativeGas / (double) cumulativeTimer.elapsed(TimeUnit.MICROSECONDS));
segmentGas = 0;
segmentTimer.reset();
}
private BlockHeader lookupPreviousHeader(
final MutableBlockchain blockchain, final BlockHeader header) {
return blockchain
.getBlockHeader(header.getParentHash())
.orElseThrow(
() ->
new IllegalStateException(
String.format(
"Block %s does not connect to the existing chain. Current chain head %s",
header.getNumber(), blockchain.getChainHeadBlockNumber())));
}
@Override
public void close() {
validationExecutor.shutdownNow();
try {
//noinspection ResultOfMethodCallIgnored
validationExecutor.awaitTermination(5, SECONDS);
} catch (final Exception e) {
LOG.error("Error shutting down validatorExecutor.", e);
}
importExecutor.shutdownNow();
try {
//noinspection ResultOfMethodCallIgnored
importExecutor.awaitTermination(5, SECONDS);
} catch (final Exception e) {
LOG.error("Error shutting down importExecutor", e);
}
}
/** The Import result. */
public static final class ImportResult {
/** The difficulty. */
public final Difficulty td;
/** The Count. */
final int count;
/**
* Instantiates a new Import result.
*
* @param td the td
* @param count the count
*/
ImportResult(final Difficulty td, final int count) {
this.td = td;
this.count = count;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("td", td).add("count", count).toString();
}
}
}
| hyperledger/besu | besu/src/main/java/org/hyperledger/besu/chainimport/RlpBlockImporter.java |
179,708 | package nc.tile.internal.fluid;
import mekanism.api.gas.*;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fluids.*;
import net.minecraftforge.fluids.capability.*;
import net.minecraftforge.fml.common.Optional;
import javax.annotation.Nullable;
@Optional.InterfaceList({@Optional.Interface(iface = "mekanism.api.gas.ITubeConnection", modid = "mekanism"), @Optional.Interface(iface = "mekanism.api.gas.IGasHandler", modid = "mekanism")})
public class TankVoid implements IFluidTank, IFluidHandler, ITubeConnection, IGasHandler {
public TankVoid() {}
@Override
public IFluidTankProperties[] getTankProperties() {
return new IFluidTankProperties[] {new TankVoidProperties(this)};
}
private static class TankVoidProperties implements IFluidTankProperties {
protected final TankVoid tank;
public TankVoidProperties(TankVoid tank) {
this.tank = tank;
}
@Override
public @Nullable FluidStack getContents() {
return tank.getFluid();
}
@Override
public int getCapacity() {
return tank.getCapacity();
}
@Override
public boolean canFill() {
return true;
}
@Override
public boolean canDrain() {
return false;
}
@Override
public boolean canFillFluidType(FluidStack fluidStack) {
return true;
}
@Override
public boolean canDrainFluidType(FluidStack fluidStack) {
return false;
}
}
@Override
public @Nullable FluidStack drain(FluidStack resource, boolean doDrain) {
return null;
}
@Override
public @Nullable FluidStack getFluid() {
return null;
}
@Override
public int getFluidAmount() {
return 0;
}
@Override
public int getCapacity() {
return Integer.MAX_VALUE;
}
@Override
public FluidTankInfo getInfo() {
return new FluidTankInfo(this);
}
@Override
public int fill(FluidStack resource, boolean doFill) {
return resource == null ? 0 : resource.amount;
}
@Override
public @Nullable FluidStack drain(int maxDrain, boolean doDrain) {
return null;
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canDrawGas(EnumFacing side, Gas gas) {
return false;
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canReceiveGas(EnumFacing side, Gas gas) {
return true;
}
@Override
@Optional.Method(modid = "mekanism")
public GasStack drawGas(EnumFacing side, int var2, boolean doTransfer) {
return null;
}
@Override
@Optional.Method(modid = "mekanism")
public int receiveGas(EnumFacing side, GasStack stack, boolean doTransfer) {
return stack == null ? 0 : stack.amount;
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canTubeConnect(EnumFacing side) {
return true;
}
}
| tomdodd4598/NuclearCraft | src/main/java/nc/tile/internal/fluid/TankVoid.java |
179,709 | package mekanism.api.gas;
import net.minecraft.item.ItemStack;
/**
* Implement this in your item class if it can store or transfer certain gasses.
* @author AidanBrady
*
*/
public interface IGasItem
{
/**
* Gets the rate of transfer this item can handle.
* @return
*/
public int getRate(ItemStack itemstack);
/**
* Adds a defined amount of a certain gas to an item.
* @param itemstack - the itemstack to add gas to
* @param type - the type of gas to add
* @param amount - the amount of gas to add
* @return the gas that was accepted by the item
*/
public int addGas(ItemStack itemstack, GasStack stack);
/**
* Removes the defined amount of a certain gas from the item.
* @param itemstack - the itemstack to remove gas from
* @param type - the type of gas to remove
* @param amount - the amount of gas to remove
* @return the gas that was removed by the item
*/
public GasStack removeGas(ItemStack itemstack, int amount);
/**
* Whether or not this storage tank be given a specific gas.
* @param itemstack - the itemstack to check
* @param type - the type of gas the tank can possibly receive
* @return if the item be charged
*/
public boolean canReceiveGas(ItemStack itemstack, Gas type);
/**
* Whether or not this item can give a gas receiver a certain type of gas.
* @param itemstack - the itemstack to check
* @param type - the type of gas the tank can provide
* @return if the item can provide gas
*/
public boolean canProvideGas(ItemStack itemstack, Gas type);
/**
* Get the gas of a declared type.
* @param type - type of gas
* @param data - ItemStack parameter if necessary
* @return gas stored
*/
public GasStack getGas(ItemStack itemstack);
/**
* Set the gas of a declared type to a new amount;
* @param type - type of gas
* @param data - ItemStack parameter if necessary
* @param amount - amount to store
*/
public void setGas(ItemStack itemstack, GasStack stack);
/**
* Gets the maximum amount of gas this tile entity can store.
* @param type - type of gas
* @param data - ItemStack parameter if necessary
* @return maximum gas
*/
public int getMaxGas(ItemStack itemstack);
/**
* Returns whether or not this item contains metadata-specific subtypes instead of using metadata for damage display.
* @return if the item contains metadata-specific subtypes
*/
public boolean isMetadataSpecific(ItemStack itemstack);
}
| microsoft/vsminecraft | minecraftpkg/MekanismModSample/src/main/java/mekanism/api/gas/IGasItem.java |
179,710 | package magic.ai;
public class VegasScore {
private final Object[] choiceResults;
private long totalScore;
private int count;
VegasScore(final Object[] choiceResults) {
this.choiceResults=choiceResults;
}
void incrementScore(final int score) {
totalScore+=score;
count++;
}
Object[] getChoiceResults() {
return choiceResults;
}
@Override
public String toString() {
final StringBuilder buffer=new StringBuilder();
buffer.append("[").append(getScore()).append('/').append(count).append("]");
if (choiceResults!=null) {
buffer.append(" (");
boolean first=true;
for (final Object choiceResult : choiceResults) {
if (first) {
first=false;
} else {
buffer.append(',');
}
buffer.append(choiceResult);
}
buffer.append(')');
}
return buffer.toString();
}
int getScore() {
return count>0?(int)(totalScore/count):ArtificialScoringSystem.LOSE_GAME_SCORE;
}
}
| xcorail/magarena | src/magic/ai/VegasScore.java |
179,711 | package magic.ai;
import magic.model.MagicGame;
import magic.model.event.MagicEvent;
public class VegasWorker implements Runnable {
private static final int MAIN_PHASES=6;
private final MagicGame sourceGame;
private final VegasScore score;
private final Object[] choiceResults;
private final long slice;
private final boolean CHEAT;
VegasWorker(final boolean cheat, final MagicGame sourceGame, final VegasScore score,final long slice) {
this.CHEAT = cheat;
this.sourceGame=sourceGame;
this.score=score;
this.choiceResults=score.getChoiceResults();
this.slice=slice;
}
/** Play game until number of main phases are completed or until the game is finished. */
private void runGame(final MagicGame game) {
while (game.advanceToNextEventWithChoice()) {
final MagicEvent event = game.getNextEvent();
final Object[] result = event.getSimulationChoiceResult(game);
game.executeNextEvent(result);
}
}
@Override
public void run() {
final long endTime = System.nanoTime() + slice;
while (System.nanoTime() < endTime) {
final MagicGame game = new MagicGame(sourceGame, sourceGame.getScorePlayer());
if (!CHEAT) {
game.showRandomizedHiddenCards();
}
game.setMainPhases(MAIN_PHASES);
game.executeNextEvent(game.map(choiceResults));
runGame(game);
score.incrementScore(game.getScore());
}
}
}
| xcorail/magarena | src/magic/ai/VegasWorker.java |
179,712 |
package org.drip.simm.parameters;
import java.util.HashMap;
import java.util.Map;
import org.drip.measure.gaussian.NormalQuadrature;
import org.drip.numerical.common.NumberUtil;
import org.drip.simm.credit.CRNQSystemics20;
import org.drip.simm.credit.CRNQSystemics21;
import org.drip.simm.credit.CRNQSystemics24;
import org.drip.simm.credit.CRQSystemics20;
import org.drip.simm.credit.CRQSystemics21;
import org.drip.simm.credit.CRQSystemics24;
import org.drip.simm.credit.CRThresholdContainer20;
import org.drip.simm.credit.CRThresholdContainer21;
import org.drip.simm.credit.CRThresholdContainer24;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2022 Lakshmi Krishnamurthy
* Copyright (C) 2021 Lakshmi Krishnamurthy
* Copyright (C) 2020 Lakshmi Krishnamurthy
* Copyright (C) 2019 Lakshmi Krishnamurthy
* Copyright (C) 2018 Lakshmi Krishnamurthy
*
* This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
* asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
* analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
* equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
* numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
* graph builder/navigator, and computational support.
*
* https://lakshmidrip.github.io/DROP/
*
* DROP is composed of three modules:
*
* - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
* - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
* - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
*
* DROP Product Core implements libraries for the following:
* - Fixed Income Analytics
* - Loan Analytics
* - Transaction Cost Analytics
*
* DROP Portfolio Core implements libraries for the following:
* - Asset Allocation Analytics
* - Asset Liability Management Analytics
* - Capital Estimation Analytics
* - Exposure Analytics
* - Margin Analytics
* - XVA Analytics
*
* DROP Computational Core implements libraries for the following:
* - Algorithm Support
* - Computation Support
* - Function Analysis
* - Graph Algorithm
* - Model Validation
* - Numerical Analysis
* - Numerical Optimizer
* - Spline Builder
* - Statistical Learning
*
* Documentation for DROP is Spread Over:
*
* - Main => https://lakshmidrip.github.io/DROP/
* - Wiki => https://github.com/lakshmiDRIP/DROP/wiki
* - GitHub => https://github.com/lakshmiDRIP/DROP
* - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
* - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html
* - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
* - Release Versions => https://lakshmidrip.github.io/DROP/version.html
* - Community Credits => https://lakshmidrip.github.io/DROP/credits.html
* - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <i>BucketVegaSettingsCR</i> holds the Vega Risk Weights, Concentration Thresholds, and Cross-Tenor
* Correlations for each Credit Curve and its Tenor. The References are:
*
* <br><br>
* <ul>
* <li>
* Andersen, L. B. G., M. Pykhtin, and A. Sokol (2017): Credit Exposure in the Presence of Initial
* Margin https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2806156 <b>eSSRN</b>
* </li>
* <li>
* Albanese, C., S. Caenazzo, and O. Frankel (2017): Regression Sensitivities for Initial Margin
* Calculations https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2763488 <b>eSSRN</b>
* </li>
* <li>
* Anfuso, F., D. Aziz, P. Giltinan, and K. Loukopoulus (2017): A Sound Modeling and Back-testing
* Framework for Forecasting Initial Margin Requirements
* https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2716279 <b>eSSRN</b>
* </li>
* <li>
* Caspers, P., P. Giltinan, R. Lichters, and N. Nowaczyk (2017): Forecasting Initial Margin
* Requirements - A Model Evaluation https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2911167
* <b>eSSRN</b>
* </li>
* <li>
* International Swaps and Derivatives Association (2021): SIMM v2.4 Methodology
* https://www.isda.org/a/CeggE/ISDA-SIMM-v2.4-PUBLIC.pdf
* </li>
* </ul>
*
* <br><br>
* <ul>
* <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/PortfolioCore.md">Portfolio Core Module</a></li>
* <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/MarginAnalyticsLibrary.md">Initial and Variation Margin Analytics</a></li>
* <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/simm/README.md">Initial Margin Analytics based on ISDA SIMM and its Variants</a></li>
* <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/simm/parameters/README.md">ISDA SIMM Risk Factor Parameters</a></li>
* </ul>
* <br><br>
*
* @author Lakshmi Krishnamurthy
*/
public class BucketVegaSettingsCR
extends BucketSensitivitySettingsCR
{
private double _vegaScaler = Double.NaN;
private double _historicalVolatilityRatio = Double.NaN;
private Map<String, Double> _tenorDeltaRiskWeight = null;
/**
* Retrieve the ISDA 2.0 Credit Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.0 Credit Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRQ_20 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRQ_DELTA_20 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRQSystemics20.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer20.QualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Retrieve the ISDA 2.0 Credit Non-Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.0 Credit Non-Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRNQ_20 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRNQ_DELTA_20 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRNQSystemics20.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer20.NonQualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Retrieve the ISDA 2.1 Credit Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.1 Credit Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRQ_21 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRQ_DELTA_21 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRQSystemics21.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer21.QualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Retrieve the ISDA 2.1 Credit Non-Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.1 Credit Non-Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRNQ_21 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRNQ_DELTA_21 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRNQSystemics21.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer21.NonQualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Retrieve the ISDA 2.4 Credit Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.4 Credit Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRQ_24 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRQ_DELTA_24 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRQSystemics24.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer24.QualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Retrieve the ISDA 2.4 Credit Non-Qualifying Bucket Vega Settings
*
* @param bucketNumber The Bucket Number
*
* @return The ISDA 2.4 Credit Non-Qualifying Bucket Vega Settings
*/
public static BucketVegaSettingsCR ISDA_CRNQ_24 (
final int bucketNumber)
{
BucketSensitivitySettingsCR bucketSensitivitySettingsCR =
BucketSensitivitySettingsCR.ISDA_CRNQ_DELTA_24 (
bucketNumber
);
try
{
return null == bucketSensitivitySettingsCR ? null : new BucketVegaSettingsCR (
TenorRiskWeightMap (
CRNQSystemics24.VEGA_RISK_WEIGHT
),
bucketSensitivitySettingsCR.intraFamilyCrossTenorCorrelation(),
bucketSensitivitySettingsCR.extraFamilyCrossTenorCorrelation(),
CRThresholdContainer24.NonQualifyingThreshold (
bucketNumber
).vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsCR.tenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* BucketVegaSettingsCR Constructor
*
* @param tenorVegaRiskWeight The Tenor Vega Risk Weight Map
* @param sameIssuerSeniorityCorrelation Same Issuer/Seniority Correlation
* @param differentIssuerSeniorityCorrelation Different Issuer/Seniority Correlation
* @param concentrationThreshold The Concentration Threshold
* @param vegaScaler The Vega Scaler
* @param historicalVolatilityRatio The Historical Volatility Ratio
* @param tenorDeltaRiskWeight The Credit Tenor Delta Risk Weight
*
* @throws Exception Thrown if the Inputs are Invalid
*/
public BucketVegaSettingsCR (
final Map<String, Double> tenorVegaRiskWeight,
final double sameIssuerSeniorityCorrelation,
final double differentIssuerSeniorityCorrelation,
final double concentrationThreshold,
final double vegaScaler,
final double historicalVolatilityRatio,
final Map<String, Double> tenorDeltaRiskWeight)
throws Exception
{
super (
tenorVegaRiskWeight,
sameIssuerSeniorityCorrelation,
differentIssuerSeniorityCorrelation,
concentrationThreshold
);
if (!NumberUtil.IsValid (
_vegaScaler = vegaScaler
) ||
!NumberUtil.IsValid (
_historicalVolatilityRatio = historicalVolatilityRatio
) ||
null == (_tenorDeltaRiskWeight = tenorDeltaRiskWeight)
)
{
throw new Exception (
"BucketVegaSettingsIR Constructor => Invalid Inputs"
);
}
}
/**
* Retrieve the Vega Scaler
*
* @return The Vega Scaler
*/
public double vegaScaler()
{
return _vegaScaler;
}
/**
* Retrieve the Historical Volatility Ratio
*
* @return The Historical Volatility Ratio
*/
public double historicalVolatilityRatio()
{
return _historicalVolatilityRatio;
}
/**
* Retrieve the Tenor Delta Risk Weight
*
* @return The Tenor Delta Risk Weight
*/
public Map<String, Double> tenorDeltaRiskWeight()
{
return _tenorDeltaRiskWeight;
}
/**
* Retrieve the Tenor Vega Risk Weight
*
* @return The Tenor Vega Risk Weight
*/
public Map<String, Double> tenorVegaRiskWeight()
{
return super.tenorRiskWeight();
}
@Override public Map<String, Double> tenorRiskWeight()
{
Map<String, Double> tenorVegaRiskWeight = tenorVegaRiskWeight();
Map<String, Double> tenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> tenorVegaRiskWeightEntry : tenorVegaRiskWeight.entrySet())
{
String tenor = tenorVegaRiskWeightEntry.getKey();
if (!tenorVegaRiskWeight.containsKey (
tenor
))
{
return null;
}
tenorRiskWeight.put (
tenor,
tenorVegaRiskWeightEntry.getValue() * _tenorDeltaRiskWeight.get (
tenor
) * _vegaScaler * _historicalVolatilityRatio
);
}
return tenorRiskWeight;
}
}
| lakshmiDRIP/DROP | src/main/java/org/drip/simm/parameters/BucketVegaSettingsCR.java |
179,713 |
package org.drip.simm.parameters;
import java.util.HashMap;
import java.util.Map;
import org.drip.measure.gaussian.NormalQuadrature;
import org.drip.numerical.common.NumberUtil;
import org.drip.simm.rates.IRSettingsContainer20;
import org.drip.simm.rates.IRSettingsContainer21;
import org.drip.simm.rates.IRSettingsContainer24;
import org.drip.simm.rates.IRSystemics;
import org.drip.simm.rates.IRSystemics20;
import org.drip.simm.rates.IRSystemics21;
import org.drip.simm.rates.IRSystemics24;
import org.drip.simm.rates.IRThreshold;
import org.drip.simm.rates.IRThresholdContainer20;
import org.drip.simm.rates.IRThresholdContainer21;
import org.drip.simm.rates.IRThresholdContainer24;
import org.drip.simm.rates.IRWeight;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2022 Lakshmi Krishnamurthy
* Copyright (C) 2021 Lakshmi Krishnamurthy
* Copyright (C) 2020 Lakshmi Krishnamurthy
* Copyright (C) 2019 Lakshmi Krishnamurthy
* Copyright (C) 2018 Lakshmi Krishnamurthy
*
* This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
* asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
* analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
* equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
* numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
* graph builder/navigator, and computational support.
*
* https://lakshmidrip.github.io/DROP/
*
* DROP is composed of three modules:
*
* - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
* - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
* - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
*
* DROP Product Core implements libraries for the following:
* - Fixed Income Analytics
* - Loan Analytics
* - Transaction Cost Analytics
*
* DROP Portfolio Core implements libraries for the following:
* - Asset Allocation Analytics
* - Asset Liability Management Analytics
* - Capital Estimation Analytics
* - Exposure Analytics
* - Margin Analytics
* - XVA Analytics
*
* DROP Computational Core implements libraries for the following:
* - Algorithm Support
* - Computation Support
* - Function Analysis
* - Graph Algorithm
* - Model Validation
* - Numerical Analysis
* - Numerical Optimizer
* - Spline Builder
* - Statistical Learning
*
* Documentation for DROP is Spread Over:
*
* - Main => https://lakshmidrip.github.io/DROP/
* - Wiki => https://github.com/lakshmiDRIP/DROP/wiki
* - GitHub => https://github.com/lakshmiDRIP/DROP
* - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
* - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html
* - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
* - Release Versions => https://lakshmidrip.github.io/DROP/version.html
* - Community Credits => https://lakshmidrip.github.io/DROP/credits.html
* - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <i>BucketVegaSettingsIR</i> holds the Vega Risk Weights, Concentration Thresholds, and
* Cross-Tenor/Cross-Curve Correlations for each Currency Curve and its Tenor. The References are:
*
* <br><br>
* <ul>
* <li>
* Andersen, L. B. G., M. Pykhtin, and A. Sokol (2017): Credit Exposure in the Presence of Initial
* Margin https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2806156 <b>eSSRN</b>
* </li>
* <li>
* Albanese, C., S. Caenazzo, and O. Frankel (2017): Regression Sensitivities for Initial Margin
* Calculations https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2763488 <b>eSSRN</b>
* </li>
* <li>
* Anfuso, F., D. Aziz, P. Giltinan, and K. Loukopoulus (2017): A Sound Modeling and Back-testing
* Framework for Forecasting Initial Margin Requirements
* https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2716279 <b>eSSRN</b>
* </li>
* <li>
* Caspers, P., P. Giltinan, R. Lichters, and N. Nowaczyk (2017): Forecasting Initial Margin
* Requirements - A Model Evaluation https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2911167
* <b>eSSRN</b>
* </li>
* <li>
* International Swaps and Derivatives Association (2021): SIMM v2.4 Methodology
* https://www.isda.org/a/CeggE/ISDA-SIMM-v2.4-PUBLIC.pdf
* </li>
* </ul>
*
* <br><br>
* <ul>
* <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/PortfolioCore.md">Portfolio Core Module</a></li>
* <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/MarginAnalyticsLibrary.md">Initial and Variation Margin Analytics</a></li>
* <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/simm/README.md">Initial Margin Analytics based on ISDA SIMM and its Variants</a></li>
* <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/simm/parameters/README.md">ISDA SIMM Risk Factor Parameters</a></li>
* </ul>
* <br><br>
*
* @author Lakshmi Krishnamurthy
*/
public class BucketVegaSettingsIR
extends BucketSensitivitySettingsIR
{
private double _vegaScaler = Double.NaN;
private double _historicalVolatilityRatio = Double.NaN;
private Map<String, Double> _oisTenorDeltaRiskWeight = null;
private Map<String, Double> _primeTenorDeltaRiskWeight = null;
private Map<String, Double> _libor1MTenorDeltaRiskWeight = null;
private Map<String, Double> _libor3MTenorDeltaRiskWeight = null;
private Map<String, Double> _libor6MTenorDeltaRiskWeight = null;
private Map<String, Double> _libor12MTenorDeltaRiskWeight = null;
private Map<String, Double> _municipalTenorDeltaRiskWeight = null;
/**
* Construct the ISDA 2.0 Standard IR Vega Sensitivity Settings for the Currency
*
* @param currency Currency
*
* @return The ISDA 2.0 Standard IR Vega Sensitivity Settings for the Currency
*/
public static BucketVegaSettingsIR ISDA_20 (
final String currency)
{
IRThreshold irThreshold = IRThresholdContainer20.Threshold (
currency
);
IRWeight oisRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_OIS
);
IRWeight libor1MRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_1M
);
IRWeight libor3MRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_3M
);
IRWeight libor6MRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_6M
);
IRWeight libor12MRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_12M
);
IRWeight primeRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_PRIME
);
IRWeight municipalRiskWeight = IRSettingsContainer20.RiskWeight (
currency,
IRSystemics.SUB_CURVE_MUNICIPAL
);
BucketSensitivitySettingsIR bucketSensitivitySettingsIR = BucketSensitivitySettingsIR.ISDA_DELTA_20 (
currency
);
try
{
return null == irThreshold ||
null == libor1MRiskWeight ||
null == libor1MRiskWeight ||
null == libor3MRiskWeight ||
null == libor6MRiskWeight ||
null == libor12MRiskWeight ||
null == primeRiskWeight ||
null == municipalRiskWeight ||
null == bucketSensitivitySettingsIR ? null : new BucketVegaSettingsIR (
oisRiskWeight.tenorVega(),
libor1MRiskWeight.tenorVega(),
libor3MRiskWeight.tenorVega(),
libor6MRiskWeight.tenorVega(),
libor12MRiskWeight.tenorVega(),
primeRiskWeight.tenorVega(),
municipalRiskWeight.tenorVega(),
IRSettingsContainer20.SingleCurveTenorCorrelation(),
IRSystemics20.SINGLE_CURRENCY_CROSS_CURVE_CORRELATION,
irThreshold.deltaVega().vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsIR.oisTenorRiskWeight(),
bucketSensitivitySettingsIR.libor1MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor3MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor6MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor12MTenorRiskWeight(),
bucketSensitivitySettingsIR.primeTenorRiskWeight(),
bucketSensitivitySettingsIR.municipalTenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Construct the ISDA 2.1 Standard IR Vega Sensitivity Settings for the Currency
*
* @param currency Currency
*
* @return The ISDA 2.1 Standard IR Vega Sensitivity Settings for the Currency
*/
public static BucketVegaSettingsIR ISDA_21 (
final String currency)
{
IRThreshold irThreshold = IRThresholdContainer21.Threshold (
currency
);
IRWeight oisRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_OIS
);
IRWeight libor1MRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_1M
);
IRWeight libor3MRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_3M
);
IRWeight libor6MRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_6M
);
IRWeight libor12MRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_12M
);
IRWeight primeRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_PRIME
);
IRWeight municipalRiskWeight = IRSettingsContainer21.RiskWeight (
currency,
IRSystemics.SUB_CURVE_MUNICIPAL
);
BucketSensitivitySettingsIR bucketSensitivitySettingsIR = BucketSensitivitySettingsIR.ISDA_DELTA_21 (
currency
);
try
{
return null == irThreshold ||
null == libor1MRiskWeight ||
null == libor1MRiskWeight ||
null == libor3MRiskWeight ||
null == libor6MRiskWeight ||
null == libor12MRiskWeight ||
null == primeRiskWeight ||
null == municipalRiskWeight ||
null == bucketSensitivitySettingsIR ? null : new BucketVegaSettingsIR (
oisRiskWeight.tenorVega(),
libor1MRiskWeight.tenorVega(),
libor3MRiskWeight.tenorVega(),
libor6MRiskWeight.tenorVega(),
libor12MRiskWeight.tenorVega(),
primeRiskWeight.tenorVega(),
municipalRiskWeight.tenorVega(),
IRSettingsContainer21.SingleCurveTenorCorrelation(),
IRSystemics21.SINGLE_CURRENCY_CROSS_CURVE_CORRELATION,
irThreshold.deltaVega().vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsIR.oisTenorRiskWeight(),
bucketSensitivitySettingsIR.libor1MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor3MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor6MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor12MTenorRiskWeight(),
bucketSensitivitySettingsIR.primeTenorRiskWeight(),
bucketSensitivitySettingsIR.municipalTenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* Construct the ISDA 2.4 Standard IR Vega Sensitivity Settings for the Currency
*
* @param currency Currency
*
* @return The ISDA 2.4 Standard IR Vega Sensitivity Settings for the Currency
*/
public static BucketVegaSettingsIR ISDA_24 (
final String currency)
{
IRThreshold irThreshold = IRThresholdContainer24.Threshold (
currency
);
IRWeight oisRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_OIS
);
IRWeight libor1MRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_1M
);
IRWeight libor3MRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_3M
);
IRWeight libor6MRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_6M
);
IRWeight libor12MRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_LIBOR_12M
);
IRWeight primeRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_PRIME
);
IRWeight municipalRiskWeight = IRSettingsContainer24.RiskWeight (
currency,
IRSystemics.SUB_CURVE_MUNICIPAL
);
BucketSensitivitySettingsIR bucketSensitivitySettingsIR = BucketSensitivitySettingsIR.ISDA_DELTA_24 (
currency
);
try
{
return null == irThreshold ||
null == libor1MRiskWeight ||
null == libor1MRiskWeight ||
null == libor3MRiskWeight ||
null == libor6MRiskWeight ||
null == libor12MRiskWeight ||
null == primeRiskWeight ||
null == municipalRiskWeight ||
null == bucketSensitivitySettingsIR ? null : new BucketVegaSettingsIR (
oisRiskWeight.tenorVega(),
libor1MRiskWeight.tenorVega(),
libor3MRiskWeight.tenorVega(),
libor6MRiskWeight.tenorVega(),
libor12MRiskWeight.tenorVega(),
primeRiskWeight.tenorVega(),
municipalRiskWeight.tenorVega(),
IRSettingsContainer24.SingleCurveTenorCorrelation(),
IRSystemics24.SINGLE_CURRENCY_CROSS_CURVE_CORRELATION,
irThreshold.deltaVega().vega(),
Math.sqrt (
365. / 14.
) / NormalQuadrature.InverseCDF (
0.99
),
1.,
bucketSensitivitySettingsIR.oisTenorRiskWeight(),
bucketSensitivitySettingsIR.libor1MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor3MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor6MTenorRiskWeight(),
bucketSensitivitySettingsIR.libor12MTenorRiskWeight(),
bucketSensitivitySettingsIR.primeTenorRiskWeight(),
bucketSensitivitySettingsIR.municipalTenorRiskWeight()
);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* BucketVegaSettingsIR Constructor
*
* @param oisTenorVegaRiskWeight The OIS Tenor Vega Risk Weight
* @param libor1MTenorVegaRiskWeight The LIBOR 1M Tenor Vega Risk Weight
* @param libor3MTenorVegaRiskWeight The LIBOR 3M Tenor Vega Risk Weight
* @param libor6MTenorVegaRiskWeight The LIBOR 6M Tenor Vega Risk Weight
* @param libor12MTenorVegaRiskWeight The LIBOR 12M Tenor Vega Risk Weight
* @param primeTenorVegaRiskWeight The PRIME Tenor Vega Risk Weight
* @param municipalTenorVegaRiskWeight The MUNICIPAL Tenor Vega Risk Weight
* @param crossTenorCorrelation Single Curve Cross-Tenor Correlation
* @param crossCurveCorrelation Cross Curve Correlation
* @param concentrationThreshold The Concentration Threshold
* @param vegaScaler The Vega Scaler
* @param historicalVolatilityRatio The Historical Volatility Ratio
* @param oisTenorDeltaRiskWeight The OIS Tenor Delta Risk Weight
* @param libor1MTenorDeltaRiskWeight The LIBOR 1M Tenor Delta Risk Weight
* @param libor3MTenorDeltaRiskWeight The LIBOR 3M Tenor Delta Risk Weight
* @param libor6MTenorDeltaRiskWeight The LIBOR 6M Tenor Delta Risk Weight
* @param libor12MTenorDeltaRiskWeight The LIBOR 12M Tenor Delta Risk Weight
* @param primeTenorDeltaRiskWeight The PRIME Tenor Delta Risk Weight
* @param municipalTenorDeltaRiskWeight The MUNICIPAL Tenor Delta Risk Weight
*
* @throws Exception Thrown if the Inputs are Invalid
*/
public BucketVegaSettingsIR (
final Map<String, Double> oisTenorVegaRiskWeight,
final Map<String, Double> libor1MTenorVegaRiskWeight,
final Map<String, Double> libor3MTenorVegaRiskWeight,
final Map<String, Double> libor6MTenorVegaRiskWeight,
final Map<String, Double> libor12MTenorVegaRiskWeight,
final Map<String, Double> primeTenorVegaRiskWeight,
final Map<String, Double> municipalTenorVegaRiskWeight,
final org.drip.measure.stochastic.LabelCorrelation crossTenorCorrelation,
final double crossCurveCorrelation,
final double concentrationThreshold,
final double vegaScaler,
final double historicalVolatilityRatio,
final Map<String, Double> oisTenorDeltaRiskWeight,
final Map<String, Double> libor1MTenorDeltaRiskWeight,
final Map<String, Double> libor3MTenorDeltaRiskWeight,
final Map<String, Double> libor6MTenorDeltaRiskWeight,
final Map<String, Double> libor12MTenorDeltaRiskWeight,
final Map<String, Double> primeTenorDeltaRiskWeight,
final Map<String, Double> municipalTenorDeltaRiskWeight)
throws Exception
{
super (
oisTenorVegaRiskWeight,
libor1MTenorVegaRiskWeight,
libor3MTenorVegaRiskWeight,
libor6MTenorVegaRiskWeight,
libor12MTenorVegaRiskWeight,
primeTenorVegaRiskWeight,
municipalTenorVegaRiskWeight,
crossTenorCorrelation,
crossCurveCorrelation,
concentrationThreshold
);
if (!NumberUtil.IsValid (
_vegaScaler = vegaScaler
) ||
!NumberUtil.IsValid (
_historicalVolatilityRatio = historicalVolatilityRatio
) ||
null == (_oisTenorDeltaRiskWeight = oisTenorDeltaRiskWeight) ||
null == (_libor1MTenorDeltaRiskWeight = libor1MTenorDeltaRiskWeight) ||
null == (_libor3MTenorDeltaRiskWeight = libor3MTenorDeltaRiskWeight) ||
null == (_libor6MTenorDeltaRiskWeight = libor6MTenorDeltaRiskWeight) ||
null == (_libor12MTenorDeltaRiskWeight = libor12MTenorDeltaRiskWeight) ||
null == (_primeTenorDeltaRiskWeight = primeTenorDeltaRiskWeight) ||
null == (_municipalTenorDeltaRiskWeight = municipalTenorDeltaRiskWeight))
{
throw new Exception (
"BucketVegaSettingsIR Constructor => Invalid Inputs"
);
}
}
/**
* Retrieve the Vega Scaler
*
* @return The Vega Scaler
*/
public double vegaScaler()
{
return _vegaScaler;
}
/**
* Retrieve the Historical Volatility Ratio
*
* @return The Historical Volatility Ratio
*/
public double historicalVolatilityRatio()
{
return _historicalVolatilityRatio;
}
/**
* Retrieve the OIS Tenor Delta Risk Weight
*
* @return The OIS Tenor Delta Risk Weight
*/
public Map<String, Double> oisTenorDeltaRiskWeight()
{
return _oisTenorDeltaRiskWeight;
}
/**
* Retrieve the OIS Tenor Vega Risk Weight
*
* @return The OIS Tenor Vega Risk Weight
*/
public Map<String, Double> oisTenorVegaRiskWeight()
{
return super.oisTenorRiskWeight();
}
/**
* Retrieve the LIBOR 1M Tenor Delta Risk Weight
*
* @return The LIBOR 1M Tenor Delta Risk Weight
*/
public Map<String, Double> libor1MTenorDeltaRiskWeight()
{
return _libor1MTenorDeltaRiskWeight;
}
/**
* Retrieve the LIBOR1M Tenor Vega Risk Weight
*
* @return The LIBOR1M Tenor Vega Risk Weight
*/
public Map<String, Double> libor1MTenorVegaRiskWeight()
{
return super.libor1MTenorRiskWeight();
}
/**
* Retrieve the LIBOR 3M Tenor Delta Risk Weight
*
* @return The LIBOR 3M Tenor Delta Risk Weight
*/
public Map<String, Double> libor3MTenorDeltaRiskWeight()
{
return _libor3MTenorDeltaRiskWeight;
}
/**
* Retrieve the LIBOR3M Tenor Vega Risk Weight
*
* @return The LIBOR3M Tenor Vega Risk Weight
*/
public Map<String, Double> libor3MTenorVegaRiskWeight()
{
return super.libor3MTenorRiskWeight();
}
/**
* Retrieve the LIBOR 6M Tenor Delta Risk Weight
*
* @return The LIBOR 6M Tenor Delta Risk Weight
*/
public Map<String, Double> libor6MTenorDeltaRiskWeight()
{
return _libor6MTenorDeltaRiskWeight;
}
/**
* Retrieve the LIBOR6M Tenor Vega Risk Weight
*
* @return The LIBOR6M Tenor Vega Risk Weight
*/
public Map<String, Double> libor6MTenorVegaRiskWeight()
{
return super.libor6MTenorRiskWeight();
}
/**
* Retrieve the LIBOR 12M Tenor Delta Risk Weight
*
* @return The LIBOR 12M Tenor Delta Risk Weight
*/
public Map<String, Double> libor12MTenorDeltaRiskWeight()
{
return _libor12MTenorDeltaRiskWeight;
}
/**
* Retrieve the LIBOR 12M Tenor Vega Risk Weight
*
* @return The LIBOR 12M Tenor Vega Risk Weight
*/
public Map<String, Double> libor12MTenorVegaRiskWeight()
{
return super.libor12MTenorRiskWeight();
}
/**
* Retrieve the PRIME Tenor Delta Risk Weight
*
* @return The PRIME Tenor Delta Risk Weight
*/
public Map<String, Double> primeTenorDeltaRiskWeight()
{
return _primeTenorDeltaRiskWeight;
}
/**
* Retrieve the PRIME Tenor Vega Risk Weight
*
* @return The PRIME Tenor Vega Risk Weight
*/
public Map<String, Double> primeTenorVegaRiskWeight()
{
return super.primeTenorRiskWeight();
}
/**
* Retrieve the MUNICIPAL Tenor Delta Risk Weight
*
* @return The MUNICIPAL Tenor Delta Risk Weight
*/
public Map<String, Double> municipalTenorDeltaRiskWeight()
{
return _municipalTenorDeltaRiskWeight;
}
/**
* Retrieve the MUNICIPAL Tenor Vega Risk Weight
*
* @return The MUNICIPAL Tenor Vega Risk Weight
*/
public Map<String, Double> municipalTenorVegaRiskWeight()
{
return super.municipalTenorRiskWeight();
}
@Override public Map<String, Double> oisTenorRiskWeight()
{
Map<String, Double> oisTenorVegaRiskWeight = oisTenorVegaRiskWeight();
Map<String, Double> oisTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> oisTenorVegaRiskWeightEntry : oisTenorVegaRiskWeight.entrySet())
{
String tenor = oisTenorVegaRiskWeightEntry.getKey();
if (!_oisTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
oisTenorRiskWeight.put (
tenor,
oisTenorVegaRiskWeightEntry.getValue() * _oisTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler * _historicalVolatilityRatio
);
}
return oisTenorRiskWeight;
}
@Override public Map<String, Double> libor1MTenorRiskWeight()
{
Map<String, Double> libor1MTenorVegaRiskWeight = libor1MTenorVegaRiskWeight();
Map<String, Double> libor1MTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> libor1MTenorVegaRiskWeightEntry :
libor1MTenorVegaRiskWeight.entrySet()
)
{
String tenor = libor1MTenorVegaRiskWeightEntry.getKey();
if (!_libor1MTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
libor1MTenorRiskWeight.put (
tenor,
libor1MTenorVegaRiskWeightEntry.getValue() * _libor1MTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler * _historicalVolatilityRatio
);
}
return libor1MTenorRiskWeight;
}
@Override public Map<String, Double> libor3MTenorRiskWeight()
{
Map<String, Double> libor3MTenorVegaRiskWeight = libor3MTenorVegaRiskWeight();
Map<String, Double> libor3MTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> libor3MTenorVegaRiskWeightEntry :
libor3MTenorVegaRiskWeight.entrySet())
{
String tenor = libor3MTenorVegaRiskWeightEntry.getKey();
if (!_libor3MTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
libor3MTenorRiskWeight.put (
tenor,
libor3MTenorVegaRiskWeightEntry.getValue() * _libor3MTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler * _historicalVolatilityRatio
);
}
return libor3MTenorRiskWeight;
}
@Override public Map<String, Double> libor6MTenorRiskWeight()
{
Map<String, Double> libor6MTenorVegaRiskWeight = libor6MTenorVegaRiskWeight();
Map<String, Double> libor6MTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> libor6MTenorVegaRiskWeightEntry :
libor6MTenorVegaRiskWeight.entrySet())
{
String tenor = libor6MTenorVegaRiskWeightEntry.getKey();
if (!_libor6MTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
libor6MTenorRiskWeight.put (
tenor,
libor6MTenorVegaRiskWeightEntry.getValue() * _libor6MTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler *_historicalVolatilityRatio
);
}
return libor6MTenorRiskWeight;
}
@Override public Map<String, Double> libor12MTenorRiskWeight()
{
Map<String, Double> libor12MTenorVegaRiskWeight = libor12MTenorVegaRiskWeight();
Map<String, Double> libor12MTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> libor12MTenorVegaRiskWeightEntry :
libor12MTenorVegaRiskWeight.entrySet()
)
{
String tenor = libor12MTenorVegaRiskWeightEntry.getKey();
if (!_libor12MTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
libor12MTenorRiskWeight.put (
tenor,
libor12MTenorVegaRiskWeightEntry.getValue() * _libor12MTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler *_historicalVolatilityRatio
);
}
return libor12MTenorRiskWeight;
}
@Override public Map<String, Double> primeTenorRiskWeight()
{
Map<String, Double> primeTenorVegaRiskWeight = primeTenorVegaRiskWeight();
Map<String, Double> primeTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> primeTenorVegaRiskWeightEntry : primeTenorVegaRiskWeight.entrySet())
{
String tenor = primeTenorVegaRiskWeightEntry.getKey();
if (!_primeTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
primeTenorRiskWeight.put (
tenor,
primeTenorVegaRiskWeightEntry.getValue() * _primeTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler *_historicalVolatilityRatio
);
}
return primeTenorRiskWeight;
}
@Override public Map<String, Double> municipalTenorRiskWeight()
{
Map<String, Double> municipalTenorVegaRiskWeight = super.municipalTenorRiskWeight();
Map<String, Double> municipalTenorRiskWeight = new HashMap<String, Double>();
for (Map.Entry<String, Double> municipalTenorVegaRiskWeightEntry :
municipalTenorVegaRiskWeight.entrySet()
)
{
String tenor = municipalTenorVegaRiskWeightEntry.getKey();
if (!_municipalTenorDeltaRiskWeight.containsKey (
tenor
))
{
return null;
}
municipalTenorRiskWeight.put (
tenor,
municipalTenorVegaRiskWeightEntry.getValue() * _municipalTenorDeltaRiskWeight.get (
tenor
) * _vegaScaler *_historicalVolatilityRatio
);
}
return municipalTenorRiskWeight;
}
}
| lakshmiDRIP/DROP | src/main/java/org/drip/simm/parameters/BucketVegaSettingsIR.java |
179,714 | package jnibwapi;
import java.util.ArrayList;
import java.util.List;
import jnibwapi.Position.PosType;
import jnibwapi.types.PlayerType;
import jnibwapi.types.RaceType;
import jnibwapi.types.RaceType.RaceTypes;
import jnibwapi.types.TechType;
import jnibwapi.types.TechType.TechTypes;
import jnibwapi.types.UpgradeType;
import jnibwapi.types.UpgradeType.UpgradeTypes;
/**
* Represents a StarCraft player.
*
* For a description of fields see: http://code.google.com/p/bwapi/wiki/Player
*/
public class Player {
public static final int numAttributes = 11;
private final int ID;
private final int raceID;
private final int typeID;
private final int startLocationX;
private final int startLocationY;
private final boolean self;
private final boolean ally;
private final boolean enemy;
private final boolean neutral;
private final boolean observer;
private final int color;
private final String name;
private int minerals;
private int gas;
private int supplyUsed;
private int supplyTotal;
private int cumulativeMinerals;
private int cumulativeGas;
private int unitScore;
private int killScore;
private int buildingScore;
private int razingScore;
private final boolean[] researching;
private final boolean[] researched;
private final boolean[] upgrading;
private final int[] upgradeLevel;
public Player(int[] data, int index, String name) {
ID = data[index++];
raceID = data[index++];
typeID = data[index++];
startLocationX = data[index++];
startLocationY = data[index++];
self = (data[index++] == 1);
ally = (data[index++] == 1);
enemy = (data[index++] == 1);
neutral = (data[index++] == 1);
observer = (data[index++] == 1);
color = data[index++];
this.name = name;
// Initialise technology records
int highestIDTechType = 0;
for (TechType t : TechTypes.getAllTechTypes()) {
highestIDTechType = Math.max(highestIDTechType, t.getID());
}
researching = new boolean[highestIDTechType + 1];
researched = new boolean[highestIDTechType + 1];
int highestIDUpgradeType = 0;
for (UpgradeType ut : UpgradeTypes.getAllUpgradeTypes()) {
highestIDUpgradeType = Math.max(highestIDUpgradeType, ut.getID());
}
upgrading = new boolean[highestIDUpgradeType + 1];
upgradeLevel = new int[highestIDUpgradeType + 1];
}
public void update(int[] data) {
int index = 0;
minerals = data[index++];
gas = data[index++];
supplyUsed = data[index++];
supplyTotal = data[index++];
cumulativeMinerals = data[index++];
cumulativeGas = data[index++];
unitScore = data[index++];
killScore = data[index++];
buildingScore = data[index++];
razingScore = data[index++];
}
public void updateResearch(int[] techData, int[] upgradeData) {
for (int i = 0; i < techData.length; i += 3) {
int techTypeID = techData[i];
researched[techTypeID] = (techData[i + 1] == 1);
researching[techTypeID] = (techData[i + 2] == 1);
}
for (int i = 0; i < upgradeData.length; i += 3) {
int upgradeTypeID = upgradeData[i];
upgradeLevel[upgradeTypeID] = upgradeData[i + 1];
upgrading[upgradeTypeID] = (upgradeData[i + 2] == 1);
}
}
public int getID() {
return ID;
}
@Deprecated
public int getRaceID() {
return raceID;
}
public RaceType getRace() {
return RaceTypes.getRaceType(raceID);
}
public PlayerType getTypeID() {
return PlayerType.getPlayerType(typeID);
}
/**
* Returns the starting tile position of the Player. Note: the position may be equal to
* Positions.Invalid / Positions.None / Positions.Unknown.
*/
public Position getStartLocation() {
return new Position(startLocationX, startLocationY, PosType.BUILD);
}
public boolean isSelf() {
return self;
}
public boolean isAlly() {
return ally;
}
public boolean isEnemy() {
return enemy;
}
public boolean isNeutral() {
return neutral;
}
public boolean isObserver() {
return observer;
}
public int getColor() {
return color;
}
public String getName() {
return name;
}
public List<Unit> getUnits() {
List<Unit> units = new ArrayList<>();
for (Unit u : JNIBWAPI.getInstance().getAllUnits()) {
if (u.getPlayer() == this) {
units.add(u);
}
}
return units;
}
public int getMinerals() {
return minerals;
}
public int getGas() {
return gas;
}
public int getSupplyUsed() {
return supplyUsed;
}
public int getSupplyTotal() {
return supplyTotal;
}
public int getCumulativeMinerals() {
return cumulativeMinerals;
}
public int getCumulativeGas() {
return cumulativeGas;
}
public int getUnitScore() {
return unitScore;
}
public int getKillScore() {
return killScore;
}
public int getBuildingScore() {
return buildingScore;
}
public int getRazingScore() {
return razingScore;
}
public boolean isResearched(TechType tech) {
return researched[tech.getID()];
}
@Deprecated
public boolean isResearched(int techID) {
return (techID >= 0 && techID < researched.length) ? researched[techID] : false;
}
public boolean isResearching(TechType tech) {
return researching[tech.getID()];
}
@Deprecated
public boolean isResearching(int techID) {
return (techID >= 0 && techID < researching.length) ? researching[techID] : false;
}
public int getUpgradeLevel(UpgradeType upgrade) {
return upgradeLevel[upgrade.getID()];
}
@Deprecated
public int getUpgradeLevel(int upgradeID) {
return (upgradeID >= 0 && upgradeID < upgradeLevel.length) ?
upgradeLevel[upgradeID] : 0;
}
public boolean isUpgrading(UpgradeType upgrade) {
return upgrading[upgrade.getID()];
}
@Deprecated
public boolean isUpgrading(int upgradeID) {
return (upgradeID >= 0 && upgradeID < upgrading.length) ? upgrading[upgradeID] : false;
}
@Override
public int hashCode() {
return ID;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Player other = (Player) obj;
if (ID != other.ID)
return false;
return true;
}
}
| JNIBWAPI/JNIBWAPI | src/java/jnibwapi/Player.java |
179,715 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.infn.mw.voms.aa.impl;
import it.infn.mw.voms.aa.VOMSRequestContext;
public interface AttributeResolver {
public void resolveFQANs(VOMSRequestContext requestContext);
public void resolveGAs(VOMSRequestContext requestContext);
}
| indigo-iam/iam | iam-voms-aa/src/main/java/it/infn/mw/voms/aa/impl/AttributeResolver.java |
179,716 | /*
* This file is part of RskJ
* Copyright (C) 2017 RSK Labs Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.rpc.dto;
import org.ethereum.core.Block;
import org.ethereum.core.SignatureCache;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.db.TransactionInfo;
import org.ethereum.rpc.LogFilterElement;
import org.ethereum.vm.LogInfo;
import co.rsk.core.RskAddress;
import co.rsk.util.HexUtils;
/**
* Created by Ruben on 5/1/2016.
*/
public class TransactionReceiptDTO {
private static final String TRANSACTION_TYPE = "0x0";
private String transactionHash; // hash of the transaction.
private String transactionIndex; // integer of the transactions index position in the block.
private String blockHash; // hash of the block where this transaction was in.
private String blockNumber; // block number where this transaction was in.
private String cumulativeGasUsed; // The total amount of gas used when this transaction was executed in the block.
private String gasUsed; // The amount of gas used by this specific transaction alone.
private String contractAddress; // The contract address created, if the transaction was a contract creation, otherwise null .
private LogFilterElement[] logs; // Array of log objects, which this transaction generated.
private String from; // address of the sender.
private String to; // address of the receiver. null when it's a contract creation transaction.
private String status; // either 1 (success) or 0 (failure)
private String logsBloom; // Bloom filter for light clients to quickly retrieve related logs.
private String type = TRANSACTION_TYPE; // is a positive unsigned 8-bit number that represents the type of the transaction.
public TransactionReceiptDTO(Block block, TransactionInfo txInfo, SignatureCache signatureCache) {
TransactionReceipt receipt = txInfo.getReceipt();
status = HexUtils.toQuantityJsonHex(txInfo.getReceipt().getStatus());
blockHash = HexUtils.toUnformattedJsonHex(txInfo.getBlockHash());
blockNumber = HexUtils.toQuantityJsonHex(block.getNumber());
RskAddress contractAddress = receipt.getTransaction().getContractAddress();
if (contractAddress != null) {
this.contractAddress = contractAddress.toJsonString();
}
cumulativeGasUsed = HexUtils.toQuantityJsonHex(receipt.getCumulativeGas());
from = receipt.getTransaction().getSender(signatureCache).toJsonString();
gasUsed = HexUtils.toQuantityJsonHex(receipt.getGasUsed());
logs = new LogFilterElement[receipt.getLogInfoList().size()];
for (int i = 0; i < logs.length; i++) {
LogInfo logInfo = receipt.getLogInfoList().get(i);
logs[i] = new LogFilterElement(logInfo, block, txInfo.getIndex(),
txInfo.getReceipt().getTransaction(), i);
}
to = receipt.getTransaction().getReceiveAddress().toJsonString();
transactionHash = receipt.getTransaction().getHash().toJsonString();
transactionIndex = HexUtils.toQuantityJsonHex(txInfo.getIndex());
logsBloom = HexUtils.toUnformattedJsonHex(txInfo.getReceipt().getBloomFilter().getData());
}
public String getTransactionHash() {
return transactionHash;
}
public String getTransactionIndex() {
return transactionIndex;
}
public String getBlockHash() {
return blockHash;
}
public String getBlockNumber() {
return blockNumber;
}
public String getCumulativeGasUsed() {
return cumulativeGasUsed;
}
public String getGasUsed() {
return gasUsed;
}
public String getContractAddress() {
return contractAddress;
}
public LogFilterElement[] getLogs() {
return logs.clone();
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
public String getStatus() {
return status;
}
public String getLogsBloom() {
return logsBloom;
}
public String getType() {
return type;
}
} | rsksmart/rskj | rskj-core/src/main/java/org/ethereum/rpc/dto/TransactionReceiptDTO.java |
179,717 | /*
* Copyright 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.daemon;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static io.flutter.testing.JsonTesting.curly;
import static org.junit.Assert.assertEquals;
/**
* Verifies that we can read events sent using the Flutter daemon protocol.
*/
public class DaemonEventTest {
private List<String> log;
private DaemonEvent.Listener listener;
@Before
public void setUp() {
log = new ArrayList<>();
listener = new DaemonEvent.Listener() {
// daemon domain
@Override
public void onDaemonLogMessage(DaemonEvent.DaemonLogMessage event) {
logEvent(event, event.level, event.message, event.stackTrace);
}
@Override
public void onDaemonShowMessage(DaemonEvent.DaemonShowMessage event) {
logEvent(event, event.level, event.title, event.message);
}
// app domain
@Override
public void onAppStarting(DaemonEvent.AppStarting event) {
logEvent(event, event.appId, event.deviceId, event.directory, event.launchMode);
}
@Override
public void onAppDebugPort(DaemonEvent.AppDebugPort event) {
logEvent(event, event.appId, event.wsUri, event.baseUri);
}
@Override
public void onAppStarted(DaemonEvent.AppStarted event) {
logEvent(event, event.appId);
}
@Override
public void onAppLog(DaemonEvent.AppLog event) {
logEvent(event, event.appId, event.log, event.error);
}
@Override
public void onAppProgressStarting(DaemonEvent.AppProgress event) {
logEvent(event, "starting", event.appId, event.id, event.getType(), event.message);
}
@Override
public void onAppProgressFinished(DaemonEvent.AppProgress event) {
logEvent(event, "finished", event.appId, event.id, event.getType(), event.message);
}
@Override
public void onAppStopped(DaemonEvent.AppStopped event) {
if (event.error != null) {
logEvent(event, event.appId, event.error);
}
else {
logEvent(event, event.appId);
}
}
// device domain
@Override
public void onDeviceAdded(DaemonEvent.DeviceAdded event) {
logEvent(event, event.id, event.name, event.platform, event.category);
}
@Override
public void onDeviceRemoved(DaemonEvent.DeviceRemoved event) {
logEvent(event, event.id, event.name, event.platform);
}
};
}
@Test
public void shouldIgnoreUnknownEvent() {
send("unknown.message", curly());
checkLog();
}
// daemon domain
@Test
public void canReceiveLogMessage() {
send("daemon.logMessage", curly("level:\"spam\"", "message:\"Make money fast\"", "stackTrace:\"Las Vegas\""));
checkLog("DaemonLogMessage: spam, Make money fast, Las Vegas");
}
@Test
public void canReceiveShowMessage() {
send("daemon.showMessage", curly("level:\"info\"", "title:\"Spam\"", "message:\"Make money fast\""));
checkLog("DaemonShowMessage: info, Spam, Make money fast");
}
// app domain
@Test
public void canReceiveAppStarting() {
send("app.start", curly("appId:42", "deviceId:456", "directory:somedir", "launchMode:run"));
checkLog("AppStarting: 42, 456, somedir, run");
}
@Test
public void canReceiveDebugPort() {
// The port parameter is deprecated; should ignore it.
send("app.debugPort", curly("appId:42", "port:456", "wsUri:\"example.com\"", "baseUri:\"belongto:us\""));
checkLog("AppDebugPort: 42, example.com, belongto:us");
}
@Test
public void canReceiveAppStarted() {
send("app.started", curly("appId:42"));
checkLog("AppStarted: 42");
}
@Test
public void canReceiveAppLog() {
send("app.log", curly("appId:42", "log:\"Oh no!\"", "error:true"));
checkLog("AppLog: 42, Oh no!, true");
}
@Test
public void canReceiveProgressStarting() {
send("app.progress", curly("appId:42", "id:opaque", "progressId:very.hot", "message:\"Please wait\""));
checkLog("AppProgress: starting, 42, opaque, very.hot, Please wait");
}
@Test
public void canReceiveProgressFinished() {
send("app.progress", curly("appId:42", "id:opaque", "progressId:very.hot", "message:\"All done!\"", "finished:true"));
checkLog("AppProgress: finished, 42, opaque, very.hot, All done!");
}
@Test
public void canReceiveAppStopped() {
send("app.stop", curly("appId:42"));
checkLog("AppStopped: 42");
}
@Test
public void canReceiveAppStoppedWithError() {
send("app.stop", curly("appId:42", "error:\"foobar\""));
checkLog("AppStopped: 42, foobar");
}
// device domain
@Test
public void canReceiveDeviceAdded() {
send("device.added", curly("id:9000", "name:\"Banana Jr\"", "platform:\"feet\"", "category:\"mobile\""));
checkLog("DeviceAdded: 9000, Banana Jr, feet, mobile");
}
@Test
public void canReceiveDeviceRemoved() {
send("device.removed", curly("id:9000", "name:\"Banana Jr\"", "platform:\"feet\""));
checkLog("DeviceRemoved: 9000, Banana Jr, feet");
}
private void send(String eventName, String params) {
DaemonEvent.dispatch(
GSON.fromJson(curly("event:\"" + eventName + "\"", "params:" + params),
JsonObject.class), listener);
}
private void logEvent(DaemonEvent event, Object... items) {
log.add(event.getClass().getSimpleName() + ": " + Joiner.on(", ").join(items));
}
private void checkLog(String... expectedEntries) {
assertEquals("log entries are different", Arrays.asList(expectedEntries), log);
log.clear();
}
private static final Gson GSON = new Gson();
}
| flutter/flutter-intellij | flutter-idea/testSrc/unit/io/flutter/run/daemon/DaemonEventTest.java |
179,718 | package eisbot.proxy.model;
import eisbot.proxy.JNIBWAPI;
/**
* Represents a StarCraft player.
*
* For a description of fields see: http://code.google.com/p/bwapi/wiki/Player
*/
public class Player {
public static final int numAttributes = 8;
private int ID;
private int raceID;
private int typeID;
private boolean self;
private boolean ally;
private boolean enemy;
private boolean neutral;
private int color;
private int minerals;
private int gas;
private int supplyUsed;
private int supplyTotal;
private int cumulativeMinerals;
private int cumulativeGas;
private int unitScore;
private int killScore;
private int buildingScore;
private int razingScore;
private boolean[] researching = new boolean[47];
private boolean[] researched = new boolean[47];
private boolean[] upgrading = new boolean[63];
private int[] upgradeLevel = new int[63];
public Player(int[] data, int index) {
ID = data[index++];
raceID = data[index++];
typeID = data[index++];
self = (data[index++] == 1);
ally = (data[index++] == 1);
enemy = (data[index++] == 1);
neutral = (data[index++] == 1);
color = data[index++];
}
public void update(int[] data) {
int index = 0;
minerals = data[index++];
gas = data[index++];
supplyUsed = data[index++];
supplyTotal = data[index++];
cumulativeMinerals = data[index++];
cumulativeGas = data[index++];
unitScore = data[index++];
killScore = data[index++];
buildingScore = data[index++];
razingScore = data[index++];
}
public void updateResearch(JNIBWAPI bwapi, int[] researchData, int[] upgradeData) {
for (int i=0; i<researchData.length; i+=2) {
researched[i/2] = (researchData[i] == 1);
researching[i/2] = (researchData[i + 1] == 1);
}
for (int i=0; i<upgradeData.length; i+=2) {
upgradeLevel[i/2] = upgradeData[i];
upgrading[i/2] = (upgradeData[i + 1] == 1);
}
}
public int getID() {
return ID;
}
public int getRaceID() {
return raceID;
}
public int getTypeID() {
return typeID;
}
public boolean isSelf() {
return self;
}
public boolean isAlly() {
return ally;
}
public boolean isEnemy() {
return enemy;
}
public boolean isNeutral() {
return neutral;
}
public int getColor() {
return color;
}
public int getMinerals() {
return minerals;
}
public int getGas() {
return gas;
}
public int getSupplyUsed() {
return supplyUsed;
}
public int getSupplyTotal() {
return supplyTotal;
}
public int getCumulativeMinerals() {
return cumulativeMinerals;
}
public int getCumulativeGas() {
return cumulativeGas;
}
public int getUnitScore() {
return unitScore;
}
public int getKillScore() {
return killScore;
}
public int getBuildingScore() {
return buildingScore;
}
public int getRazingScore() {
return razingScore;
}
public boolean[] getResearchCompleted() {
return researched;
}
public boolean[] getResearchInProgress() {
return researching;
}
public int[] getUpgradeLevels() {
return upgradeLevel;
}
public boolean[] getUpgradesInProgress() {
return upgrading;
}
public boolean hasResearched(int techID) {
return (researched != null && techID < researched.length) ? researched[techID] : false;
}
public boolean isResearching(int techID) {
return (researching != null && techID < researching.length) ? researching[techID] : false;
}
public int upgradeLevel(int upgradeID) {
return (upgradeLevel != null && upgradeID < upgradeLevel.length) ? upgradeLevel[upgradeID] : 0;
}
public boolean isUpgrading(int upgradeID) {
return (upgrading != null && upgradeID < upgrading.length) ? upgrading[upgradeID] : false;
}
}
| bgweber/eisbot | src/eisbot/proxy/model/Player.java |
179,719 | package com.drew.metadata.wav;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Directory;
import java.util.HashMap;
/**
* Holds basic metadata from Wav files including some ID3 tags
*
* @author Payton Garland
*/
public class WavDirectory extends Directory
{
public static final int TAG_FORMAT = 1;
public static final int TAG_CHANNELS = 2;
public static final int TAG_SAMPLES_PER_SEC = 3;
public static final int TAG_BYTES_PER_SEC = 4;
public static final int TAG_BLOCK_ALIGNMENT = 5;
public static final int TAG_BITS_PER_SAMPLE = 6;
public static final int TAG_ARTIST = 7;
public static final int TAG_TITLE = 8;
public static final int TAG_PRODUCT = 9;
public static final int TAG_TRACK_NUMBER = 10;
public static final int TAG_DATE_CREATED = 11;
public static final int TAG_GENRE = 12;
public static final int TAG_COMMENTS = 13;
public static final int TAG_COPYRIGHT = 14;
public static final int TAG_SOFTWARE = 15;
public static final int TAG_DURATION = 16;
public static final String CHUNK_FORMAT = "fmt ";
public static final String CHUNK_DATA = "data";
public static final String LIST_INFO = "INFO";
public static final String FORMAT = "WAVE";
@NotNull
private static final HashMap<Integer, String> _tagNameMap = new HashMap<Integer, String>();
@NotNull
transient static final HashMap<String, Integer> _tagIntegerMap = new HashMap<String, Integer>();
@NotNull
transient static final HashMap<Integer, String> _audioEncodingMap = new HashMap<Integer, String>();
static {
_tagIntegerMap.put("IART", TAG_ARTIST);
_tagIntegerMap.put("INAM", TAG_TITLE);
_tagIntegerMap.put("IPRD", TAG_PRODUCT);
_tagIntegerMap.put("ITRK", TAG_TRACK_NUMBER);
_tagIntegerMap.put("ICRD", TAG_DATE_CREATED);
_tagIntegerMap.put("IGNR", TAG_GENRE);
_tagIntegerMap.put("ICMT", TAG_COMMENTS);
_tagIntegerMap.put("ICOP", TAG_COPYRIGHT);
_tagIntegerMap.put("ISFT", TAG_SOFTWARE);
_tagNameMap.put(TAG_FORMAT, "Format");
_tagNameMap.put(TAG_CHANNELS, "Channels");
_tagNameMap.put(TAG_SAMPLES_PER_SEC, "Samples Per Second");
_tagNameMap.put(TAG_BYTES_PER_SEC, "Bytes Per Second");
_tagNameMap.put(TAG_BLOCK_ALIGNMENT, "Block Alignment");
_tagNameMap.put(TAG_BITS_PER_SAMPLE, "Bits Per Sample");
_tagNameMap.put(TAG_ARTIST, "Artist");
_tagNameMap.put(TAG_TITLE, "Title");
_tagNameMap.put(TAG_PRODUCT, "Product");
_tagNameMap.put(TAG_TRACK_NUMBER, "Track Number");
_tagNameMap.put(TAG_DATE_CREATED, "Date Created");
_tagNameMap.put(TAG_GENRE, "Genre");
_tagNameMap.put(TAG_COMMENTS, "Comments");
_tagNameMap.put(TAG_COPYRIGHT, "Copyright");
_tagNameMap.put(TAG_SOFTWARE, "Software");
_tagNameMap.put(TAG_DURATION, "Duration");
// Audio encoding tags from http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/RIFF.html#AudioEncoding
_audioEncodingMap.put(0x1, "Microsoft PCM");
_audioEncodingMap.put(0x2, "Microsoft ADPCM");
_audioEncodingMap.put(0x3, "Microsoft IEEE float");
_audioEncodingMap.put(0x4, "Compaq VSELP");
_audioEncodingMap.put(0x5, "IBM CVSD");
_audioEncodingMap.put(0x6, "Microsoft a-Law");
_audioEncodingMap.put(0x7, "Microsoft u-Law");
_audioEncodingMap.put(0x8, "Microsoft DTS");
_audioEncodingMap.put(0x9, "DRM");
_audioEncodingMap.put(0xa, "WMA 9 Speech");
_audioEncodingMap.put(0xb, "Microsoft Windows Media RT Voice");
_audioEncodingMap.put(0x10, "OKI-ADPCM");
_audioEncodingMap.put(0x11, "Intel IMA/DVI-ADPCM");
_audioEncodingMap.put(0x12, "Videologic Mediaspace ADPCM");
_audioEncodingMap.put(0x13, "Sierra ADPCM");
_audioEncodingMap.put(0x14, "Antex G.723 ADPCM");
_audioEncodingMap.put(0x15, "DSP Solutions DIGISTD");
_audioEncodingMap.put(0x16, "DSP Solutions DIGIFIX");
_audioEncodingMap.put(0x17, "Dialoic OKI ADPCM");
_audioEncodingMap.put(0x18, "Media Vision ADPCM");
_audioEncodingMap.put(0x19, "HP CU");
_audioEncodingMap.put(0x1a, "HP Dynamic Voice");
_audioEncodingMap.put(0x20, "Yamaha ADPCM");
_audioEncodingMap.put(0x21, "SONARC Speech Compression");
_audioEncodingMap.put(0x22, "DSP Group True Speech");
_audioEncodingMap.put(0x23, "Echo Speech Corp.");
_audioEncodingMap.put(0x24, "Virtual Music Audiofile AF36");
_audioEncodingMap.put(0x25, "Audio Processing Tech.");
_audioEncodingMap.put(0x26, "Virtual Music Audiofile AF10");
_audioEncodingMap.put(0x27, "Aculab Prosody 1612");
_audioEncodingMap.put(0x28, "Merging Tech. LRC");
_audioEncodingMap.put(0x30, "Dolby AC2");
_audioEncodingMap.put(0x31, "Microsoft GSM610");
_audioEncodingMap.put(0x32, "MSN Audio");
_audioEncodingMap.put(0x33, "Antex ADPCME");
_audioEncodingMap.put(0x34, "Control Resources VQLPC");
_audioEncodingMap.put(0x35, "DSP Solutions DIGIREAL");
_audioEncodingMap.put(0x36, "DSP Solutions DIGIADPCM");
_audioEncodingMap.put(0x37, "Control Resources CR10");
_audioEncodingMap.put(0x38, "Natural MicroSystems VBX ADPCM");
_audioEncodingMap.put(0x39, "Crystal Semiconductor IMA ADPCM");
_audioEncodingMap.put(0x3a, "Echo Speech ECHOSC3");
_audioEncodingMap.put(0x3b, "Rockwell ADPCM");
_audioEncodingMap.put(0x3c, "Rockwell DIGITALK");
_audioEncodingMap.put(0x3d, "Xebec Multimedia");
_audioEncodingMap.put(0x40, "Antex G.721 ADPCM");
_audioEncodingMap.put(0x41, "Antex G.728 CELP");
_audioEncodingMap.put(0x42, "Microsoft MSG723");
_audioEncodingMap.put(0x43, "IBM AVC ADPCM");
_audioEncodingMap.put(0x45, "ITU-T G.726");
_audioEncodingMap.put(0x50, "Microsoft MPEG");
_audioEncodingMap.put(0x51, "RT23 or PAC");
_audioEncodingMap.put(0x52, "InSoft RT24");
_audioEncodingMap.put(0x53, "InSoft PAC");
_audioEncodingMap.put(0x55, "MP3");
_audioEncodingMap.put(0x59, "Cirrus");
_audioEncodingMap.put(0x60, "Cirrus Logic");
_audioEncodingMap.put(0x61, "ESS Tech. PCM");
_audioEncodingMap.put(0x62, "Voxware Inc.");
_audioEncodingMap.put(0x63, "Canopus ATRAC");
_audioEncodingMap.put(0x64, "APICOM G.726 ADPCM");
_audioEncodingMap.put(0x65, "APICOM G.722 ADPCM");
_audioEncodingMap.put(0x66, "Microsoft DSAT");
_audioEncodingMap.put(0x67, "Micorsoft DSAT DISPLAY");
_audioEncodingMap.put(0x69, "Voxware Byte Aligned");
_audioEncodingMap.put(0x70, "Voxware AC8");
_audioEncodingMap.put(0x71, "Voxware AC10");
_audioEncodingMap.put(0x72, "Voxware AC16");
_audioEncodingMap.put(0x73, "Voxware AC20");
_audioEncodingMap.put(0x74, "Voxware MetaVoice");
_audioEncodingMap.put(0x75, "Voxware MetaSound");
_audioEncodingMap.put(0x76, "Voxware RT29HW");
_audioEncodingMap.put(0x77, "Voxware VR12");
_audioEncodingMap.put(0x78, "Voxware VR18");
_audioEncodingMap.put(0x79, "Voxware TQ40");
_audioEncodingMap.put(0x7a, "Voxware SC3");
_audioEncodingMap.put(0x7b, "Voxware SC3");
_audioEncodingMap.put(0x80, "Soundsoft");
_audioEncodingMap.put(0x81, "Voxware TQ60");
_audioEncodingMap.put(0x82, "Microsoft MSRT24");
_audioEncodingMap.put(0x83, "AT&T G.729A");
_audioEncodingMap.put(0x84, "Motion Pixels MVI MV12");
_audioEncodingMap.put(0x85, "DataFusion G.726");
_audioEncodingMap.put(0x86, "DataFusion GSM610");
_audioEncodingMap.put(0x88, "Iterated Systems Audio");
_audioEncodingMap.put(0x89, "Onlive");
_audioEncodingMap.put(0x8a, "Multitude, Inc. FT SX20");
_audioEncodingMap.put(0x8b, "Infocom ITS A/S G.721 ADPCM");
_audioEncodingMap.put(0x8c, "Convedia G729");
_audioEncodingMap.put(0x8d, "Not specified congruency, Inc.");
_audioEncodingMap.put(0x91, "Siemens SBC24");
_audioEncodingMap.put(0x92, "Sonic Foundry Dolby AC3 APDIF");
_audioEncodingMap.put(0x93, "MediaSonic G.723");
_audioEncodingMap.put(0x94, "Aculab Prosody 8kbps");
_audioEncodingMap.put(0x97, "ZyXEL ADPCM");
_audioEncodingMap.put(0x98, "Philips LPCBB");
_audioEncodingMap.put(0x99, "Studer Professional Audio Packed");
_audioEncodingMap.put(0xa0, "Malden PhonyTalk");
_audioEncodingMap.put(0xa1, "Racal Recorder GSM");
_audioEncodingMap.put(0xa2, "Racal Recorder G720.a");
_audioEncodingMap.put(0xa3, "Racal G723.1");
_audioEncodingMap.put(0xa4, "Racal Tetra ACELP");
_audioEncodingMap.put(0xb0, "NEC AAC NEC Corporation");
_audioEncodingMap.put(0xff, "AAC");
_audioEncodingMap.put(0x100, "Rhetorex ADPCM");
_audioEncodingMap.put(0x101, "IBM u-Law");
_audioEncodingMap.put(0x102, "IBM a-Law");
_audioEncodingMap.put(0x103, "IBM ADPCM");
_audioEncodingMap.put(0x111, "Vivo G.723");
_audioEncodingMap.put(0x112, "Vivo Siren");
_audioEncodingMap.put(0x120, "Philips Speech Processing CELP");
_audioEncodingMap.put(0x121, "Philips Speech Processing GRUNDIG");
_audioEncodingMap.put(0x123, "Digital G.723");
_audioEncodingMap.put(0x125, "Sanyo LD ADPCM");
_audioEncodingMap.put(0x130, "Sipro Lab ACEPLNET");
_audioEncodingMap.put(0x131, "Sipro Lab ACELP4800");
_audioEncodingMap.put(0x132, "Sipro Lab ACELP8V3");
_audioEncodingMap.put(0x133, "Sipro Lab G.729");
_audioEncodingMap.put(0x134, "Sipro Lab G.729A");
_audioEncodingMap.put(0x135, "Sipro Lab Kelvin");
_audioEncodingMap.put(0x136, "VoiceAge AMR");
_audioEncodingMap.put(0x140, "Dictaphone G.726 ADPCM");
_audioEncodingMap.put(0x150, "Qualcomm PureVoice");
_audioEncodingMap.put(0x151, "Qualcomm HalfRate");
_audioEncodingMap.put(0x155, "Ring Zero Systems TUBGSM");
_audioEncodingMap.put(0x160, "Microsoft Audio1");
_audioEncodingMap.put(0x161, "Windows Media Audio V2 V7 V8 V9 / DivX audio (WMA) / Alex AC3 Audio");
_audioEncodingMap.put(0x162, "Windows Media Audio Professional V9");
_audioEncodingMap.put(0x163, "Windows Media Audio Lossless V9");
_audioEncodingMap.put(0x164, "WMA Pro over S/PDIF");
_audioEncodingMap.put(0x170, "UNISYS NAP ADPCM");
_audioEncodingMap.put(0x171, "UNISYS NAP ULAW");
_audioEncodingMap.put(0x172, "UNISYS NAP ALAW");
_audioEncodingMap.put(0x173, "UNISYS NAP 16K");
_audioEncodingMap.put(0x174, "MM SYCOM ACM SYC008 SyCom Technologies");
_audioEncodingMap.put(0x175, "MM SYCOM ACM SYC701 G726L SyCom Technologies");
_audioEncodingMap.put(0x176, "MM SYCOM ACM SYC701 CELP54 SyCom Technologies");
_audioEncodingMap.put(0x177, "MM SYCOM ACM SYC701 CELP68 SyCom Technologies");
_audioEncodingMap.put(0x178, "Knowledge Adventure ADPCM");
_audioEncodingMap.put(0x180, "Fraunhofer IIS MPEG2AAC");
_audioEncodingMap.put(0x190, "Digital Theater Systems DTS DS");
_audioEncodingMap.put(0x200, "Creative Labs ADPCM");
_audioEncodingMap.put(0x202, "Creative Labs FASTSPEECH8");
_audioEncodingMap.put(0x203, "Creative Labs FASTSPEECH10");
_audioEncodingMap.put(0x210, "UHER ADPCM");
_audioEncodingMap.put(0x215, "Ulead DV ACM");
_audioEncodingMap.put(0x216, "Ulead DV ACM");
_audioEncodingMap.put(0x220, "Quarterdeck Corp.");
_audioEncodingMap.put(0x230, "I-Link VC");
_audioEncodingMap.put(0x240, "Aureal Semiconductor Raw Sport");
_audioEncodingMap.put(0x241, "ESST AC3");
_audioEncodingMap.put(0x250, "Interactive Products HSX");
_audioEncodingMap.put(0x251, "Interactive Products RPELP");
_audioEncodingMap.put(0x260, "Consistent CS2");
_audioEncodingMap.put(0x270, "Sony SCX");
_audioEncodingMap.put(0x271, "Sony SCY");
_audioEncodingMap.put(0x272, "Sony ATRAC3");
_audioEncodingMap.put(0x273, "Sony SPC");
_audioEncodingMap.put(0x280, "TELUM Telum Inc.");
_audioEncodingMap.put(0x281, "TELUMIA Telum Inc.");
_audioEncodingMap.put(0x285, "Norcom Voice Systems ADPCM");
_audioEncodingMap.put(0x300, "Fujitsu FM TOWNS SND");
_audioEncodingMap.put(0x301, "Fujitsu (not specified)");
_audioEncodingMap.put(0x302, "Fujitsu (not specified)");
_audioEncodingMap.put(0x303, "Fujitsu (not specified)");
_audioEncodingMap.put(0x304, "Fujitsu (not specified)");
_audioEncodingMap.put(0x305, "Fujitsu (not specified)");
_audioEncodingMap.put(0x306, "Fujitsu (not specified)");
_audioEncodingMap.put(0x307, "Fujitsu (not specified)");
_audioEncodingMap.put(0x308, "Fujitsu (not specified)");
_audioEncodingMap.put(0x350, "Micronas Semiconductors, Inc. Development");
_audioEncodingMap.put(0x351, "Micronas Semiconductors, Inc. CELP833");
_audioEncodingMap.put(0x400, "Brooktree Digital");
_audioEncodingMap.put(0x401, "Intel Music Coder (IMC)");
_audioEncodingMap.put(0x402, "Ligos Indeo Audio");
_audioEncodingMap.put(0x450, "QDesign Music");
_audioEncodingMap.put(0x500, "On2 VP7 On2 Technologies");
_audioEncodingMap.put(0x501, "On2 VP6 On2 Technologies");
_audioEncodingMap.put(0x680, "AT&T VME VMPCM");
_audioEncodingMap.put(0x681, "AT&T TCP");
_audioEncodingMap.put(0x700, "YMPEG Alpha (dummy for MPEG-2 compressor)");
_audioEncodingMap.put(0x8ae, "ClearJump LiteWave (lossless)");
_audioEncodingMap.put(0x1000, "Olivetti GSM");
_audioEncodingMap.put(0x1001, "Olivetti ADPCM");
_audioEncodingMap.put(0x1002, "Olivetti CELP");
_audioEncodingMap.put(0x1003, "Olivetti SBC");
_audioEncodingMap.put(0x1004, "Olivetti OPR");
_audioEncodingMap.put(0x1100, "Lernout & Hauspie");
_audioEncodingMap.put(0x1101, "Lernout & Hauspie CELP codec");
_audioEncodingMap.put(0x1102, "Lernout & Hauspie SBC codec");
_audioEncodingMap.put(0x1103, "Lernout & Hauspie SBC codec");
_audioEncodingMap.put(0x1104, "Lernout & Hauspie SBC codec");
_audioEncodingMap.put(0x1400, "Norris Comm. Inc.");
_audioEncodingMap.put(0x1401, "ISIAudio");
_audioEncodingMap.put(0x1500, "AT&T Soundspace Music Compression");
_audioEncodingMap.put(0x181c, "VoxWare RT24 speech codec");
_audioEncodingMap.put(0x181e, "Lucent elemedia AX24000P Music codec");
_audioEncodingMap.put(0x1971, "Sonic Foundry LOSSLESS");
_audioEncodingMap.put(0x1979, "Innings Telecom Inc. ADPCM");
_audioEncodingMap.put(0x1c07, "Lucent SX8300P speech codec");
_audioEncodingMap.put(0x1c0c, "Lucent SX5363S G.723 compliant codec");
_audioEncodingMap.put(0x1f03, "CUseeMe DigiTalk (ex-Rocwell)");
_audioEncodingMap.put(0x1fc4, "NCT Soft ALF2CD ACM");
_audioEncodingMap.put(0x2000, "FAST Multimedia DVM");
_audioEncodingMap.put(0x2001, "Dolby DTS (Digital Theater System)");
_audioEncodingMap.put(0x2002, "RealAudio 1 / 2 14.4");
_audioEncodingMap.put(0x2003, "RealAudio 1 / 2 28.8");
_audioEncodingMap.put(0x2004, "RealAudio G2 / 8 Cook (low bitrate)");
_audioEncodingMap.put(0x2005, "RealAudio 3 / 4 / 5 Music (DNET)");
_audioEncodingMap.put(0x2006, "RealAudio 10 AAC (RAAC)");
_audioEncodingMap.put(0x2007, "RealAudio 10 AAC+ (RACP)");
_audioEncodingMap.put(0x2500, "Reserved range to 0x2600 Microsoft");
_audioEncodingMap.put(0x3313, "makeAVIS (ffvfw fake AVI sound from AviSynth scripts)");
_audioEncodingMap.put(0x4143, "Divio MPEG-4 AAC audio");
_audioEncodingMap.put(0x4201, "Nokia adaptive multirate");
_audioEncodingMap.put(0x4243, "Divio G726 Divio, Inc.");
_audioEncodingMap.put(0x434c, "LEAD Speech");
_audioEncodingMap.put(0x564c, "LEAD Vorbis");
_audioEncodingMap.put(0x5756, "WavPack Audio");
_audioEncodingMap.put(0x674f, "Ogg Vorbis (mode 1)");
_audioEncodingMap.put(0x6750, "Ogg Vorbis (mode 2)");
_audioEncodingMap.put(0x6751, "Ogg Vorbis (mode 3)");
_audioEncodingMap.put(0x676f, "Ogg Vorbis (mode 1+)");
_audioEncodingMap.put(0x6770, "Ogg Vorbis (mode 2+)");
_audioEncodingMap.put(0x6771, "Ogg Vorbis (mode 3+)");
_audioEncodingMap.put(0x7000, "3COM NBX 3Com Corporation");
_audioEncodingMap.put(0x706d, "FAAD AAC");
_audioEncodingMap.put(0x7a21, "GSM-AMR (CBR, no SID)");
_audioEncodingMap.put(0x7a22, "GSM-AMR (VBR, including SID)");
_audioEncodingMap.put(0xa100, "Comverse Infosys Ltd. G723 1");
_audioEncodingMap.put(0xa101, "Comverse Infosys Ltd. AVQSBC");
_audioEncodingMap.put(0xa102, "Comverse Infosys Ltd. OLDSBC");
_audioEncodingMap.put(0xa103, "Symbol Technologies G729A");
_audioEncodingMap.put(0xa104, "VoiceAge AMR WB VoiceAge Corporation");
_audioEncodingMap.put(0xa105, "Ingenient Technologies Inc. G726");
_audioEncodingMap.put(0xa106, "ISO/MPEG-4 advanced audio Coding");
_audioEncodingMap.put(0xa107, "Encore Software Ltd G726");
_audioEncodingMap.put(0xa109, "Speex ACM Codec xiph.org");
_audioEncodingMap.put(0xdfac, "DebugMode SonicFoundry Vegas FrameServer ACM Codec");
_audioEncodingMap.put(0xe708, "Unknown -");
_audioEncodingMap.put(0xf1ac, "Free Lossless Audio Codec FLAC");
_audioEncodingMap.put(0xfffe, "Extensible");
_audioEncodingMap.put(0xffff, "Development");
}
public WavDirectory()
{
this.setDescriptor(new WavDescriptor(this));
}
@NotNull
@Override
public String getName()
{
return "WAV";
}
@NotNull
@Override
protected HashMap<Integer, String> getTagNameMap()
{
return _tagNameMap;
}
}
| drewnoakes/metadata-extractor | Source/com/drew/metadata/wav/WavDirectory.java |
179,720 | package edu.stanford.nlp.sempre.interactive;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.google.common.collect.Sets;
import edu.stanford.nlp.sempre.*;
import fig.exec.Execution;
import org.testng.util.Strings;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import fig.basic.IOUtils;
import fig.basic.LogInfo;
import fig.basic.Option;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
/**
* Vega-specific code that loads the schema, colors, and generate paths and type maps
* @author sidaw
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class VegaResources {
public static class Options {
@Option(gloss = "File containing the vega schema") String vegaSchema;
@Option(gloss = "Path elements to exclude") Set<String> excludedPaths;
@Option(gloss = "Paths in the context that are not considered for removals") Set<String> excludedContextPaths;
@Option(gloss = "File containing all the colors") String colorFile;
@Option(gloss = "File containing initial plot templates") String initialTemplates;
@Option(gloss = "Path to a log of queries") String examplesPath;
@Option(gloss = "verbosity") int verbose = 0;
}
public static Options opts = new Options();
private final String savePath = Execution.getFile("vega");
public static VegaLitePathMatcher allPathsMatcher;
private static List<List<String>> filteredPaths;
private static List<JsonSchema> descendants;
public static JsonSchema vegaSchema;
private static Map<String, Set<String>> enumValueToTypes;
private static Map<String, Set<List<String>>> enumValueToPaths;
private static Set<String> colorSet;
private static List<Example> examples;
public static final Set<String> CHANNELS = Sets.newHashSet("x", "y", "color", "opacity", "shape", "size", "row", "column");
public static final Set<String> MARKS = Sets.newHashSet("area", "bar", "circle", "line", "point", "rect", "rule", "square", "text", "tick");
public static final Set<String> AGGREGATES = Sets.newHashSet("max", "mean", "min", "median", "sum");
static class InitialTemplate {
@JsonProperty("mark") public String mark;
@JsonProperty("encoding") public Map<String, String> encoding;
}
private static List<InitialTemplate> initialTemplates;
public VegaResources() {
try {
if (!Strings.isNullOrEmpty(opts.vegaSchema)) {
LogInfo.begin_track("Loading schemas from %s", opts.vegaSchema);
vegaSchema = JsonSchema.fromFile(new File(opts.vegaSchema));
LogInfo.end_track();
}
List<JsonSchema> allDescendants = vegaSchema.descendants();
descendants = allDescendants.stream().filter(s -> s.node().has("type")).collect(Collectors.toList());
LogInfo.logs("Got %d descendants, %d typed", allDescendants.size(), descendants.size());
filteredPaths = allSimplePaths(descendants);
LogInfo.logs("Got %d distinct simple path not containing %s", filteredPaths.size(), opts.excludedPaths);
allPathsMatcher = new VegaLitePathMatcher(filteredPaths);
Json.prettyWriteValueHard(new File(savePath+".simplePaths.json"), filteredPaths);
// a serialization of the action space
int totalValues = 0;
List<Object> pathsToValues = new ArrayList<>();
for (List<String> simplePath: filteredPaths) {
List<JsonSchema> schemas = vegaSchema.schemas(simplePath);
Map<String, Object> pathToSummary = new HashMap<>();
pathToSummary.put("path", simplePath);
ArrayList<String> types = new ArrayList<>();
pathToSummary.put("types", types);
List<JsonNode> values = getValues(simplePath, null, false).stream().map(jv -> jv.getJsonNode()).collect(Collectors.toList());
pathToSummary.put("values", values);
totalValues += values.size();
for (JsonSchema schema: schemas) {
for (String type: schema.types()) {
types.add(type);
}
}
pathsToValues.add(pathToSummary);
}
LogInfo.logs("Action space contains %d values", totalValues);
Json.prettyWriteValueHard(new File(savePath+".actions.json"), pathsToValues);
if (!Strings.isNullOrEmpty(opts.colorFile)) {
colorSet = Json.readMapHard(String.join("\n", IOUtils.readLines(opts.colorFile))).keySet();
LogInfo.logs("loaded %d colors from %s", colorSet.size(), opts.colorFile);
}
if (!Strings.isNullOrEmpty(opts.initialTemplates)) {
initialTemplates = new ArrayList<>();
for (JsonNode node : Json.readValueHard(String.join("\n", IOUtils.readLines(opts.initialTemplates)), JsonNode.class)) {
initialTemplates.add(Json.getMapper().treeToValue(node, InitialTemplate.class));
}
LogInfo.logs("Read %d initial templates", initialTemplates.size());
}
if (!Strings.isNullOrEmpty(opts.examplesPath)) {
Stream<String> stream = Files.lines(Paths.get(opts.examplesPath));
List<Example> loaded = stream.map(q -> Json.readMapHard(q)).filter(q -> ((List<?>)q.get("q")).get(0).equals("accept"))
.map(q -> {
Map<String, Object> jsonObj = ((List<Map<String, Object>>) q.get("q")).get(1);
String queryId = q.containsKey("queryId")? (String) q.get("queryId"): (String) q.get("sessionId") + q.get("time") + q.get("count");
return new Example(
queryId,
(String) jsonObj.get("utterance"),
new VegaJsonContextValue(jsonObj.get("context")),
null,
new JsonValue(jsonObj.get("targetValue")),
null);
}).collect(Collectors.toList());
examples = Collections.unmodifiableList(loaded);
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
private List<List<String>> allSimplePaths(List<JsonSchema> descendents) {
LinkedHashSet<List<String>> simplePaths = descendents.stream()
.map(s -> s.simplePath()).collect(Collectors.toCollection(LinkedHashSet::new));
LogInfo.logs("Got %d distinct simple paths", simplePaths.size());
return simplePaths.stream().filter(p -> !p.isEmpty() && p.stream().allMatch(s -> !opts.excludedPaths.contains(s)))
.collect(Collectors.toList());
}
private static boolean checkType(List<String> path, JsonValue value) {
JsonSchema jsonSchema = VegaResources.vegaSchema;
List<JsonSchema> pathSchemas = jsonSchema.schemas(path);
String stringValue = value.getJsonNode().asText();
for (JsonSchema schema : pathSchemas) {
String valueType = value.getSchemaType();
List<String> schemaTypes = schema.types();
if (opts.verbose > 1)
System.out.println(String.format("checkType: path: %s | simplePath: %s | types: %s | valueType: %s", path, schema.simplePath(), schemaTypes, valueType));
for (String schemaType : schemaTypes) {
List<String> simplePath = schema.simplePath();
String last = simplePath.get(simplePath.size() - 1);
if (schemaType.equals("string") && (last.endsWith("color") || last.endsWith("Color")
|| last.equals("fill")
|| last.equals("stroke") || last.equals("background"))) {
return valueType.equals("color");
}
if (schemaType.equals("string") && last.equals("field")) {
return valueType.equals("field");
}
if (schemaType.equals("string") && schema.isEnum()) {
return schema.enums().contains(stringValue);
}
if (valueType.equals(schemaType)) {
return true;
}
if (schemaType.equals(JsonSchema.NOTYPE))
throw new RuntimeException("JsonFn: schema has no type: " + schema);
}
}
return false;
}
private static void addValues(List<JsonValue> values, String[] valueArray, String type) {
for (String pick: valueArray) {
values.add(new JsonValue(pick).withSchemaType(type));
}
}
public static List<JsonValue> getValues(List<String> path, JsonValue value, boolean sample) {
if (value != null) {
if (checkType(path, value)) {
return Lists.newArrayList(value);
} else {
return Lists.newArrayList();
}
}
Set<JsonValue> values = new HashSet<>();
List<JsonSchema> schemas = vegaSchema.schemas(path);
String[] colors = {"red", "blue", "green"};
for (JsonSchema schema : schemas) {
for (String type : schema.types()) {
List<JsonValue> schemaValues = new ArrayList<>();
if (opts.verbose > 0)
LogInfo.logs("getValues %s %s", type, path.toString());
List<String> simplePath = schema.simplePath();
String lastFull = simplePath.size() == 0? "$" : simplePath.get(simplePath.size() - 1);
String last = lastFull.toLowerCase();
if (type.equals(JsonSchema.NOTYPE)) {
continue;
}
if (schema.isEnum()) {
schemaValues.addAll(schema.enums().stream().map(s -> new JsonValue(s).withSchemaType("enum"))
.collect(Collectors.toList()));
} else if (type.equals("string")) {
if (last.endsWith("color")
|| last.equals("fill")
|| last.equals("stroke") || last.equals("background")) {
addValues(schemaValues, colors, "string");
} else if (last.equals("field")) {
// values.add(new JsonValue("fieldName").withSchemaType("string"));
} else if (last.endsWith("font")) {
addValues(schemaValues, new String[]{"times", "monaco", "cursive"}, "string");
} else if (last.equals("value")) {
String channel = simplePath.get(simplePath.size() - 2);
if (channel.equals("color") || channel.equals("fill")) {
addValues(schemaValues, colors, "string");
} else if (channel.equals("shape") || channel.equals("fill")) {
addValues(schemaValues, new String[]{"square", "cross", "diamond", "triangle-up", "triangle-down", "circle"}, "string");
}
} else {
schemaValues.add(new JsonValue("XYZ").withSchemaType(type));
}
} else if (type.equals("boolean")) {
schemaValues.add(new JsonValue(true).withSchemaType("boolean"));
schemaValues.add(new JsonValue(false).withSchemaType("boolean"));
} else if (type.equals("number")) {
double max = schema.node().has("maximum") ? schema.node().get("maximum").asInt() : 100;
double min = schema.node().has("minimum") ? schema.node().get("minimum").asInt() : 0;
if (last.endsWith("opacity")) {
max = 1;
min = 0;
} else if (lastFull.endsWith("Width")) {
min = 0.5;
max = 10;
}
double numberValue = ThreadLocalRandom.current().nextDouble(min, max);
numberValue = new BigDecimal(Double.toString(numberValue)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
JsonNode fixed = DoubleNode.valueOf(numberValue);
schemaValues.add(new JsonValue(fixed).withSchemaType("number"));
} else if (type.equals("null")) {
schemaValues.add(new JsonValue(NullNode.getInstance()).withSchemaType("null"));
}
if (schemaValues.size() == 0)
continue;
if (sample)
values.add(schemaValues.get(ThreadLocalRandom.current().nextInt(schemaValues.size())));
else
values.addAll(schemaValues);
}
}
return Lists.newArrayList(values);
}
public static Set<String> getEnumTypes(String value) {
if (enumValueToTypes.containsKey(value)) return enumValueToTypes.get(value);
return null;
}
public static void addExample(Example ex) {
examples.add(ex);
}
public static Example getExample() {
int index = ThreadLocalRandom.current().nextInt(examples.size());
return examples.get(index);
}
public static Set<String> getColorSet() {
return colorSet;
}
public static List<InitialTemplate> getInitialTemplates() {
return initialTemplates;
}
}
| stanfordnlp/sempre-plot | src/edu/stanford/nlp/sempre/interactive/VegaResources.java |
179,721 | package com.hbm.inventory.fluid.types;
import com.hbm.render.util.EnumSymbol;
public class RadioactiveGas extends RadioactiveFluid {
public RadioactiveGas(String name, int color, int p, int f, int r, EnumSymbol symbol) {
super(name, color, p, f, r, symbol);
this.addTraits(FluidTrait.GASEOUS);
}
}
| 7pheonix/Hbm-s-Nuclear-Tech-GIT | src/main/java/com/hbm/inventory/fluid/types/RadioactiveGas.java |
179,722 | package org.ethereum.vmtrace;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.OpCode;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.spongycastle.util.encoders.Hex;
import java.nio.ByteBuffer;
import java.util.*;
/**
* Data to for one program step to save.
*
* {
* 'op': 'CODECOPY'
* 'storage': {},
* 'gas': '99376',
* 'pc': '9',
* 'memory': '',
* 'stack': ['15', '15', '14', '0'],
* }
*
* www.etherj.com
*
* @author: Roman Mandeleil
* Created on: 28/10/2014 23:39
*/
public class Op {
byte op;
int pc;
DataWord gas;
Map<String, String> storage;
byte[] memory;
List<String> stack;
public void setOp(byte op) {
this.op = op;
}
public void setPc(int pc) {
this.pc = pc;
}
public void saveGas(DataWord gas) {
this.gas = gas;
}
public void saveStorageMap(Map<DataWord, DataWord> storage) {
this.storage = new HashMap<>();
List<DataWord> keys = new ArrayList<>(storage.keySet());
Collections.sort(keys);
for (DataWord key : keys) {
DataWord value = storage.get(key);
this.storage.put(Hex.toHexString(key.getNoLeadZeroesData()),
Hex.toHexString(value.getNoLeadZeroesData()));
}
}
public void saveMemory(ByteBuffer memory){
if (memory != null)
this.memory = Arrays.copyOf(memory.array(), memory.array().length);
}
public void saveStack(Stack<DataWord> stack) {
this.stack = new ArrayList<>();
for(DataWord element : stack){
this.stack.add(0, Hex.toHexString(element.getNoLeadZeroesData()));
}
}
public String toString(){
Map<Object, Object> jsonData = new LinkedHashMap<>();
jsonData.put("op", OpCode.code(op).name());
jsonData.put("pc", Long.toString(pc));
jsonData.put("gas", gas.value().toString());
jsonData.put("stack", stack);
jsonData.put("memory", memory == null ? "" : Hex.toHexString(memory));
jsonData.put("storage", new JSONObject(storage) );
return JSONValue.toJSONString(jsonData);
}
}
| ethereumj/ethereumj | ethereumj-core/src/main/java/org/ethereum/vmtrace/Op.java |
179,723 | package eisbot.proxy.model;
public class PlayerScore {
public static final int numAttributes = 11;
private int ID;
private int completedUnits;
private int deadUnits;
private int killedUnits;
private int cumulativeMinerals;
private int cumulativeGas;
private int unitScore;
private int killScore;
private int buildingScore;
private int razingScore;
private int customScore;
public PlayerScore(int[] data, int index) {
ID = data[index++];
completedUnits = data[index++];
deadUnits = data[index++];
killedUnits = data[index++];
cumulativeMinerals = data[index++];
cumulativeGas = data[index++];
unitScore = data[index++];
killScore = data[index++];
buildingScore = data[index++];
razingScore = data[index++];
customScore = data[index++];
}
public int getID() {
return ID;
}
public int getCompletedUnits() {
return completedUnits;
}
public int getDeadUnits() {
return deadUnits;
}
public int getKilledUnits() {
return killedUnits;
}
public int getCumulativeMinerals() {
return cumulativeMinerals;
}
public int getCumulativeGas() {
return cumulativeGas;
}
public int getUnitScore() {
return unitScore;
}
public int getKillScore() {
return killScore;
}
public int getBuildingScore() {
return buildingScore;
}
public int getRazingScore() {
return razingScore;
}
public int getCustomScore() {
return customScore;
}
}
| bgweber/eisbot | src/eisbot/proxy/model/PlayerScore.java |
179,726 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.testdomain.model.valuetypes;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.lang.Nullable;
import org.apache.causeway.applib.annotation.Action;
import org.apache.causeway.applib.annotation.Collection;
import org.apache.causeway.applib.annotation.DomainObject;
import org.apache.causeway.applib.annotation.Editing;
import org.apache.causeway.applib.annotation.Nature;
import org.apache.causeway.applib.annotation.Parameter;
import org.apache.causeway.applib.annotation.Programmatic;
import org.apache.causeway.applib.annotation.Property;
import org.apache.causeway.applib.annotation.ValueSemantics;
import org.apache.causeway.applib.exceptions.recoverable.TextEntryParseException;
import org.apache.causeway.applib.graph.tree.TreeAdapter;
import org.apache.causeway.applib.graph.tree.TreeNode;
import org.apache.causeway.applib.graph.tree.TreePath;
import org.apache.causeway.applib.graph.tree.TreeState;
import org.apache.causeway.applib.services.appfeat.ApplicationFeatureId;
import org.apache.causeway.applib.services.bookmark.Bookmark;
import org.apache.causeway.applib.services.wrapper.WrapperFactory;
import org.apache.causeway.applib.value.Blob;
import org.apache.causeway.applib.value.Clob;
import org.apache.causeway.applib.value.LocalResourcePath;
import org.apache.causeway.applib.value.Markup;
import org.apache.causeway.applib.value.NamedWithMimeType.CommonMimeType;
import org.apache.causeway.applib.value.Password;
import org.apache.causeway.applib.value.semantics.ValueSemanticsAbstract;
import org.apache.causeway.commons.collections.Can;
import org.apache.causeway.commons.internal.base._Temporals;
import org.apache.causeway.commons.io.TextUtils;
import org.apache.causeway.core.metamodel.valuesemantics.ApplicationFeatureIdValueSemantics;
import org.apache.causeway.core.metamodel.valuesemantics.MarkupValueSemantics;
import org.apache.causeway.extensions.fullcalendar.applib.value.CalendarEvent;
import org.apache.causeway.extensions.fullcalendar.applib.value.CalendarEventSemantics;
import org.apache.causeway.schema.chg.v2.ChangesDto;
import org.apache.causeway.schema.cmd.v2.CommandDto;
import org.apache.causeway.schema.common.v2.OidDto;
import org.apache.causeway.schema.ixn.v2.InteractionDto;
import org.apache.causeway.valuetypes.vega.applib.value.Vega;
import org.apache.causeway.valuetypes.vega.metamodel.semantics.VegaValueSemantics;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.Singular;
import lombok.SneakyThrows;
import lombok.val;
public abstract class ValueTypeExample<T> {
@Property(editing = Editing.ENABLED)
public abstract T getValue();
public abstract void setValue(T value);
@Programmatic
public abstract T getUpdateValue();
@Action
public final void updateValue(@Parameter @Nullable final T value) {
setValue(value);
}
@Action
public abstract T sampleAction(@Parameter @Nullable final T value);
@Programmatic
public final T invokeSampleActionUsingWrapper(final WrapperFactory wrapper, final @Nullable T value) {
return wrapper.wrap(this).sampleAction(value);
}
/**
* Name of the value-type plus suffix if any, as extracted from the implementing example name.
*/
@Programmatic
public final String getName() {
val nameSuffix = extractSuffix(getClass().getSimpleName())
.map(s->"_" + s)
.orElse("");
val name = String.format("%s%s", getValueType().getName(), nameSuffix);
return name;
}
@Autowired(required = false) List<ValueSemanticsAbstract<T>> semanticsList;
@Programmatic
public Can<T> getParserRoundtripExamples() {
return Can.ofCollection(semanticsList)
.getFirst()
.map(semantics->semantics.getExamples())
.orElseGet(()->Can.of(getValue(), getUpdateValue()));
}
@Collection
public List<T> getValues() {
return List.of(getValue(), getUpdateValue());
}
@SuppressWarnings("unchecked")
@Programmatic
public final Class<T> getValueType() {
return (Class<T>) getValue().getClass();
}
// -- PARSING
@lombok.Value @Builder
public static class ParseExpectation<T> {
final T value;
@Singular
final List<String> inputSamples;
final String expectedOutput;
final Class<? extends Throwable> expectedThrows;
}
public Can<ParseExpectation<T>> getParseExpectations() {
System.err.printf("skipping parsing test for %s%n", getName());
return Can.empty();
}
// -- RENDERING
@lombok.Value @Builder
public static class RenderExpectation<T> {
final T value;
final String title;
final String html;
}
public Can<RenderExpectation<T>> getRenderExpectations() {
System.err.printf("skipping rendering test for %s%n", getName());
return Can.empty();
}
// -- HELPER
private static Optional<String> extractSuffix(final String name) {
if(!name.contains("_")) {
return Optional.empty();
}
return Optional.of(TextUtils.cutter(name)
.keepBefore("_")
.getValue());
}
// -- EXAMPLES - BASIC
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBoolean")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBoolean
extends ValueTypeExample<Boolean> {
@Property @Getter @Setter
private Boolean value = Boolean.TRUE;
@Getter
private Boolean updateValue = Boolean.FALSE;
@Action @Override
public Boolean sampleAction(@Parameter @Nullable final Boolean value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleCharacter")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleCharacter
extends ValueTypeExample<Character> {
@Property @Getter @Setter
private Character value = 'a';
@Getter
private Character updateValue = 'b';
@Action @Override
public Character sampleAction(@Parameter @Nullable final Character value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleString")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleString
extends ValueTypeExample<String> {
@Property @Getter @Setter
private String value = "aString";
@Getter
private String updateValue = "anotherString";
@Action @Override
public String sampleAction(@Parameter @Nullable final String value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExamplePassword")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExamplePassword
extends ValueTypeExample<Password> {
@Property @Getter @Setter
private Password value = Password.of("aPassword");
@Getter
private Password updateValue = Password.of("anotherPassword");
@Action @Override
public Password sampleAction(@Parameter @Nullable final Password value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBufferedImage")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBufferedImage
extends ValueTypeExample<BufferedImage> {
@Property @Getter @Setter
private BufferedImage value = new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB);
@Getter
private BufferedImage updateValue = new BufferedImage(8, 8, BufferedImage.TYPE_INT_RGB);
@Action @Override
public BufferedImage sampleAction(@Parameter @Nullable final BufferedImage value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBlob")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBlob
extends ValueTypeExample<Blob> {
@Property @Getter @Setter
private Blob value = Blob.of("aBlob", CommonMimeType.BIN, new byte[] {1, 2, 3});
@Getter
private Blob updateValue = Blob.of("anotherBlob", CommonMimeType.BIN, new byte[] {3, 4});
@Action @Override
public Blob sampleAction(@Parameter @Nullable final Blob value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleClob")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleClob
extends ValueTypeExample<Clob> {
@Property @Getter @Setter
private Clob value = Clob.of("aClob", CommonMimeType.TXT, "abc");
@Getter
private Clob updateValue = Clob.of("anotherClob", CommonMimeType.TXT, "ef");
@Action @Override
public Clob sampleAction(@Parameter @Nullable final Clob value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLocalResourcePath")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLocalResourcePath
extends ValueTypeExample<LocalResourcePath> {
@Property @Getter @Setter
private LocalResourcePath value = new LocalResourcePath("img/a");
@Getter
private LocalResourcePath updateValue = new LocalResourcePath("img/b");
@Action @Override
public LocalResourcePath sampleAction(@Parameter @Nullable final LocalResourcePath value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleUrl")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleUrl
extends ValueTypeExample<URL> {
@Property @Getter @Setter
private URL value = url("https://a.b.c");
@Getter
private URL updateValue = url("https://b.c.d");
@SneakyThrows
private static URL url(final String url) {
return new URL(url);
}
@Action @Override
public URL sampleAction(@Parameter @Nullable final URL value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleMarkup")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleMarkup
extends ValueTypeExample<Markup> {
private MarkupValueSemantics markupSemantics = new MarkupValueSemantics();
@Property @Getter @Setter
private Markup value = markupSemantics.getExamples().getElseFail(0);
@Getter
private Markup updateValue = markupSemantics.getExamples().getElseFail(1);
@Override
public Can<ParseExpectation<Markup>> getParseExpectations() {
val htmlSample = "<a href=\"https://www.apache.org\" rel=\"nofollow\">link</a>";
return Can.of(
ParseExpectation.<Markup>builder()
.value(new Markup(htmlSample))
.inputSample(htmlSample)
.expectedOutput(htmlSample)
.build()
);
}
@Action @Override
public Markup sampleAction(@Parameter @Nullable final Markup value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleVega")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleVega
extends ValueTypeExample<Vega> {
private VegaValueSemantics vegaSemantics = new VegaValueSemantics();
@Property @Getter @Setter
private Vega value = vegaSemantics.getExamples().getElseFail(0);
@Getter
private Vega updateValue = vegaSemantics.getExamples().getElseFail(1);
@Action @Override
public Vega sampleAction(@Parameter @Nullable final Vega value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleUuid")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleUuid
extends ValueTypeExample<UUID> {
@Property @Getter @Setter
private UUID value = UUID.randomUUID();
@Getter
private UUID updateValue = UUID.randomUUID();
@Action @Override
public UUID sampleAction(@Parameter @Nullable final UUID value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLocale")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLocale
extends ValueTypeExample<Locale> {
@Property @Getter @Setter
private Locale value = Locale.US;
@Getter
private Locale updateValue = Locale.GERMAN;
@Action @Override
public Locale sampleAction(@Parameter @Nullable final Locale value) { return value; }
}
// -- EXAMPLES - NUMBERS
@Named("causeway.testdomain.valuetypes.ValueTypeExampleByte")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleByte
extends ValueTypeExample<Byte> {
@Property @Getter @Setter
private Byte value = -63;
@Getter
private Byte updateValue = 0;
@Action @Override
public Byte sampleAction(@Parameter @Nullable final Byte value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleShort")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleShort
extends ValueTypeExample<Short> {
@Property @Getter @Setter
private Short value = -63;
@Getter
private Short updateValue = 0;
@Action @Override
public Short sampleAction(@Parameter @Nullable final Short value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleInteger")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleInteger
extends ValueTypeExample<Integer> {
@Property @Getter @Setter
private Integer value = -63;
@Getter
private Integer updateValue = 0;
@Action @Override
public Integer sampleAction(@Parameter @Nullable final Integer value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLong")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLong
extends ValueTypeExample<Long> {
@Property @Getter @Setter
private Long value = -63L;
@Getter
private Long updateValue = 0L;
@Action @Override
public Long sampleAction(@Parameter @Nullable final Long value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleFloat")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleFloat
extends ValueTypeExample<Float> {
@Property @Getter @Setter
private Float value = -63.1f;
@Getter
private Float updateValue = 0.f;
//FIXME does not handle example Float.MIN_VALUE well
@Deprecated // remove override once fixed
@Override public Can<Float> getParserRoundtripExamples() {
return Can.of(value, updateValue);
}
@Action @Override
public Float sampleAction(@Parameter @Nullable final Float value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleDouble")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleDouble
extends ValueTypeExample<Double> {
@Property @Getter @Setter
private Double value = -63.1;
@Getter
private Double updateValue = 0.;
//FIXME does not handle example Double.MIN_VALUE well
@Deprecated // remove override once fixed
@Override public Can<Double> getParserRoundtripExamples() {
return Can.of(value, updateValue);
}
@Action @Override
public Double sampleAction(@Parameter @Nullable final Double value) { return value; }
}
// -- BIG INTEGER
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBigInteger")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBigInteger
extends ValueTypeExample<BigInteger> {
@Property @Getter @Setter
private BigInteger value = BigInteger.valueOf(-63L);
@Getter
private BigInteger updateValue = BigInteger.ZERO;
@Action @Override
public BigInteger sampleAction(@Parameter @Nullable final BigInteger value) { return value; }
}
// -- BIG DECIMAL
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBigDecimal_default")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBigDecimal_default
extends ValueTypeExample<BigDecimal> {
@Property @Getter @Setter
private BigDecimal value = new BigDecimal("-63.123456");
@Getter
private BigDecimal updateValue = BigDecimal.ZERO;
@Action @Override
public BigDecimal sampleAction(@Parameter @Nullable final BigDecimal value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBigDecimal_fixedFractionalDigits")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBigDecimal_fixedFractionalDigits
extends ValueTypeExample<BigDecimal> {
@Property @ValueSemantics(minFractionalDigits = 2, maxFractionalDigits = 2)
@Getter @Setter
private BigDecimal value = new BigDecimal("-63.12");
@Getter
private BigDecimal updateValue = BigDecimal.ZERO;
// with this example maxFractionalDigits = 2 must not be exceeded
@Override public Can<BigDecimal> getParserRoundtripExamples() {
return Can.of(value, updateValue, new BigDecimal("0.1"));
}
@Override
public Can<ParseExpectation<BigDecimal>> getParseExpectations() {
return Can.of(
ParseExpectation.<BigDecimal>builder()
.value(new BigDecimal("123"))
.inputSample("123")
.inputSample("123.0")
.inputSample("123.00")
.expectedOutput("123.00")
.build(),
ParseExpectation.<BigDecimal>builder()
.value(new BigDecimal("123.45"))
.inputSample("123.45")
.expectedOutput("123.45")
.build(),
ParseExpectation.<BigDecimal>builder()
.value(new BigDecimal("123.45"))
.inputSample("123.456")
//org.apache.causeway.applib.exceptions.recoverable.TextEntryParseException:
// No more than 2 digits can be entered after the decimal separator, got 3 in '123.456'.
.expectedThrows(TextEntryParseException.class)
.build()
);
}
@Override
public Can<RenderExpectation<BigDecimal>> getRenderExpectations() {
return Can.of(
RenderExpectation.<BigDecimal>builder()
.value(new BigDecimal("123")).title("123.00").html("123.00").build(),
RenderExpectation.<BigDecimal>builder()
.value(new BigDecimal("0")).title("0.00").html("0.00").build(),
RenderExpectation.<BigDecimal>builder()
.value(new BigDecimal("123.456")).title("123.46").html("123.46").build()
);
}
@Action @Override
public BigDecimal sampleAction(@Parameter @Nullable final BigDecimal value) { return value; }
}
// -- EXAMPLES - TEMPORAL - LEGACY
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJavaUtilDate")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJavaUtilDate
extends ValueTypeExample<java.util.Date> {
@Property @Getter @Setter
private java.util.Date value = new java.util.Date();
@Getter
private java.util.Date updateValue = new java.util.Date(0L);
@Action @Override
public java.util.Date sampleAction(@Parameter @Nullable final java.util.Date value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJavaSqlDate")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJavaSqlDate
extends ValueTypeExample<java.sql.Date> {
@Property @Getter @Setter
private java.sql.Date value = new java.sql.Date(new java.util.Date().getTime());
@Getter
private java.sql.Date updateValue = new java.sql.Date(0L);
@Action @Override
public java.sql.Date sampleAction(@Parameter @Nullable final java.sql.Date value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJavaSqlTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJavaSqlTime
extends ValueTypeExample<java.sql.Time> {
@Property @Getter @Setter
private java.sql.Time value = new java.sql.Time(new java.util.Date().getTime());
@Getter
private java.sql.Time updateValue = new java.sql.Time(0L);
@Action @Override
public java.sql.Time sampleAction(@Parameter @Nullable final java.sql.Time value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleTimestamp")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleTimestamp
extends ValueTypeExample<Timestamp> {
@Property @Getter @Setter
private Timestamp value = new Timestamp(new java.util.Date().getTime());
@Getter
private Timestamp updateValue = new Timestamp(0L);
@Action @Override
public Timestamp sampleAction(@Parameter @Nullable final Timestamp value) { return value; }
}
// -- EXAMPLES - TEMPORAL - JAVA TIME
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLocalDate")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLocalDate
extends ValueTypeExample<LocalDate> {
@Property @Getter @Setter
private LocalDate value = _Temporals.sampleLocalDate().getElseFail(0);
@Getter
private LocalDate updateValue = getValue().plusDays(2);
@Action @Override
public LocalDate sampleAction(@Parameter @Nullable final LocalDate value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLocalDateTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLocalDateTime
extends ValueTypeExample<LocalDateTime> {
@Property @Getter @Setter
private LocalDateTime value = _Temporals.sampleLocalDateTime().getElseFail(0);
@Getter
private LocalDateTime updateValue = getValue().plusDays(2).plusSeconds(15);
@Action @Override
public LocalDateTime sampleAction(@Parameter @Nullable final LocalDateTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleLocalTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleLocalTime
extends ValueTypeExample<LocalTime> {
@Property @Getter @Setter
private LocalTime value = _Temporals.sampleLocalTime().getElseFail(0);
@Getter
private LocalTime updateValue = getValue().plusSeconds(15);
@Action @Override
public LocalTime sampleAction(@Parameter @Nullable final LocalTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleOffsetDateTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleOffsetDateTime
extends ValueTypeExample<OffsetDateTime> {
@Property @Getter @Setter
private OffsetDateTime value = _Temporals.sampleOffsetDateTime().getElseFail(0);
@Getter
private OffsetDateTime updateValue = getValue().plusDays(2).plusSeconds(15);
@Action @Override
public OffsetDateTime sampleAction(@Parameter @Nullable final OffsetDateTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleOffsetTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleOffsetTime
extends ValueTypeExample<OffsetTime> {
@Property @Getter @Setter
private OffsetTime value = _Temporals.sampleOffsetTime().getElseFail(0);
@Getter
private OffsetTime updateValue = OffsetTime.now().plusSeconds(15);
@Action @Override
public OffsetTime sampleAction(@Parameter @Nullable final OffsetTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleZonedDateTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleZonedDateTime
extends ValueTypeExample<ZonedDateTime> {
@Property @Getter @Setter
private ZonedDateTime value = _Temporals.sampleZonedDateTime().getElseFail(0);
@Getter
private ZonedDateTime updateValue = getValue().plusDays(2).plusSeconds(15);
@Action @Override
public ZonedDateTime sampleAction(@Parameter @Nullable final ZonedDateTime value) { return value; }
}
// -- EXAMPLES - TEMPORAL - JODA TIME
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJodaDateTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJodaDateTime
extends ValueTypeExample<org.joda.time.DateTime> {
@Property @Getter @Setter
private org.joda.time.DateTime value = org.joda.time.DateTime.now();
@Getter
private org.joda.time.DateTime updateValue = org.joda.time.DateTime.now().plusDays(2).plusSeconds(15);
@Action @Override
public org.joda.time.DateTime sampleAction(@Parameter @Nullable final org.joda.time.DateTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJodaLocalDateTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJodaLocalDateTime
extends ValueTypeExample<org.joda.time.LocalDateTime> {
@Property @Getter @Setter
private org.joda.time.LocalDateTime value = org.joda.time.LocalDateTime.now();
@Getter
private org.joda.time.LocalDateTime updateValue = org.joda.time.LocalDateTime.now().plusDays(2).plusSeconds(15);
@Action @Override
public org.joda.time.LocalDateTime sampleAction(@Parameter @Nullable final org.joda.time.LocalDateTime value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJodaLocalDate")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJodaLocalDate
extends ValueTypeExample<org.joda.time.LocalDate> {
@Property @Getter @Setter
private org.joda.time.LocalDate value = org.joda.time.LocalDate.now();
@Getter
private org.joda.time.LocalDate updateValue = org.joda.time.LocalDate.now().plusDays(2);
@Action @Override
public org.joda.time.LocalDate sampleAction(@Parameter @Nullable final org.joda.time.LocalDate value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleJodaLocalTime")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleJodaLocalTime
extends ValueTypeExample<org.joda.time.LocalTime> {
@Property @Getter @Setter
private org.joda.time.LocalTime value = org.joda.time.LocalTime.now();
@Getter
private org.joda.time.LocalTime updateValue = org.joda.time.LocalTime.now().plusSeconds(15);
@Action @Override
public org.joda.time.LocalTime sampleAction(@Parameter @Nullable final org.joda.time.LocalTime value) { return value; }
}
// -- EXAMPLES - META MODEL
@Named("causeway.testdomain.valuetypes.ValueTypeExampleApplicationFeatureId")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleApplicationFeatureId
extends ValueTypeExample<ApplicationFeatureId> {
@Property @Getter @Setter
private ApplicationFeatureId value = new ApplicationFeatureIdValueSemantics().getExamples().getElseFail(0);
@Getter
private ApplicationFeatureId updateValue = new ApplicationFeatureIdValueSemantics().getExamples().getElseFail(1);
@Action @Override
public ApplicationFeatureId sampleAction(@Parameter @Nullable final ApplicationFeatureId value) { return value; }
}
// -- EXAMPLES - DATA STRUCTURE
@Named("causeway.testdomain.valuetypes.ValueTypeExampleTreePath")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleTreePath
extends ValueTypeExample<TreePath> {
@Property @Getter @Setter
private TreePath value = TreePath.root();
@Getter
private TreePath updateValue = TreePath.of(0, 1, 2, 3, 4);
@Action @Override
public TreePath sampleAction(@Parameter @Nullable final TreePath value) { return value; }
}
//TODO TreeNode
// @DomainObject(
// @Named("causeway.testdomain.valuetypes.ValueTypeExampleTreeNode",
// nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleTreeNode
extends ValueTypeExample<TreeNode<String>> {
@Property @Getter @Setter
private TreeNode<String> value = TreeNode.root(
"root", new TreeAdapterString(), TreeState.rootCollapsed());
@Getter
private TreeNode<String> updateValue = TreeNode.root(
"anotherRoot", new TreeAdapterString(), TreeState.rootCollapsed());
private static class TreeAdapterString implements TreeAdapter<String> {
@Override public Stream<String> childrenOf(final String value) {
return Stream.empty(); }
}
@Action @Override
public TreeNode<String> sampleAction(@Parameter @Nullable final TreeNode<String> value) { return value; }
}
// -- EXAMPLES - ENUM
public static enum ExampleEnum {
HALLO, WORLD
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleEnum")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleEnum
extends ValueTypeExample<ExampleEnum> {
@Property @Getter @Setter
private ExampleEnum value = ExampleEnum.HALLO;
@Getter
private ExampleEnum updateValue = ExampleEnum.WORLD;
@Action @Override
public ExampleEnum sampleAction(@Parameter @Nullable final ExampleEnum value) { return value; }
}
// -- EXAMPLES - COMPOSITES
@Named("causeway.testdomain.valuetypes.ValueTypeExampleCalendarEvent")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleCalendarEvent
extends ValueTypeExample<CalendarEvent> {
@Property @Getter @Setter
private CalendarEvent value = new CalendarEventSemantics().getExamples().getElseFail(0);
@Getter
private CalendarEvent updateValue = new CalendarEventSemantics().getExamples().getElseFail(1);
@Action @Override
public CalendarEvent sampleAction(@Parameter @Nullable final CalendarEvent value) { return value; }
}
// -- EXAMPLES - DATA STRUCTURE
// -- EXAMPLES - OTHER
@Named("causeway.testdomain.valuetypes.ValueTypeExampleBookmark")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleBookmark
extends ValueTypeExample<Bookmark> {
@Property @Getter @Setter
private Bookmark value = Bookmark.parseElseFail("a:b");
@Getter
private Bookmark updateValue = Bookmark.parseElseFail("c:d");
@Action @Override
public Bookmark sampleAction(@Parameter @Nullable final Bookmark value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleOidDto")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleOidDto
extends ValueTypeExample<OidDto> {
@Property @Getter @Setter
private OidDto value = Bookmark.parseElseFail("a:b").toOidDto();
@Getter
private OidDto updateValue = Bookmark.parseElseFail("c:d").toOidDto();
@Action @Override
public OidDto sampleAction(@Parameter @Nullable final OidDto value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleChangesDto")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleChangesDto
extends ValueTypeExample<ChangesDto> {
@Property @Getter @Setter
private ChangesDto value = new ChangesDto();
@Getter
private ChangesDto updateValue = new ChangesDto();
@Action @Override
public ChangesDto sampleAction(@Parameter @Nullable final ChangesDto value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleCommandDto")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleCommandDto
extends ValueTypeExample<CommandDto> {
@Property @Getter @Setter
private CommandDto value = new CommandDto();
@Getter
private CommandDto updateValue = new CommandDto();
@Action @Override
public CommandDto sampleAction(@Parameter @Nullable final CommandDto value) { return value; }
}
@Named("causeway.testdomain.valuetypes.ValueTypeExampleInteractionDto")
@DomainObject(
nature = Nature.BEAN) @Scope("prototype")
public static class ValueTypeExampleInteractionDto
extends ValueTypeExample<InteractionDto> {
@Property @Getter @Setter
private InteractionDto value = new InteractionDto();
@Getter
private InteractionDto updateValue = new InteractionDto();
@Action @Override
public InteractionDto sampleAction(@Parameter @Nullable final InteractionDto value) { return value; }
}
}
| apache/causeway | regressiontests/base/src/main/java/org/apache/causeway/testdomain/model/valuetypes/ValueTypeExample.java |
179,727 | /*
* Copyright 2015, 2016 Ether.Camp Inc. (US)
* This file is part of Ethereum Harmony.
*
* Ethereum Harmony is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Ethereum Harmony is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Ethereum Harmony. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ethercamp.harmony.jsonrpc;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Value;
import lombok.experimental.NonFinal;
import org.ethereum.core.Block;
import org.ethereum.core.TransactionInfo;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.vm.LogInfo;
import static com.ethercamp.harmony.jsonrpc.TypeConverter.toJsonHex;
/**
* Created by Ruben on 5/1/2016.
*/
@Value
@NonFinal
public class TransactionReceiptDTO {
public String transactionHash; // hash of the transaction.
public String transactionIndex; // integer of the transactions index position in the block.
public String blockHash; // hash of the block where this transaction was in.
public String blockNumber; // block number where this transaction was in.
public String from; // 20 Bytes - address of the sender.
public String to; // 20 Bytes - address of the receiver. null when its a contract creation transaction.
public String cumulativeGasUsed; // The total amount of gas used when this transaction was executed in the block.
public String gasUsed; // The amount of gas used by this specific transaction alone.
public String contractAddress; // The contract address created, if the transaction was a contract creation, otherwise null .
public JsonRpc.LogFilterElement[] logs; // Array of log objects, which this transaction generated.
public String logsBloom; // 256 Bytes - Bloom filter for light clients to quickly retrieve related logs.
@JsonInclude(JsonInclude.Include.NON_NULL)
public String root; // 32 bytes of post-transaction stateroot (pre Byzantium)
@JsonInclude(JsonInclude.Include.NON_NULL)
public String status; // either 1 (success) or 0 (failure) (post Byzantium)
public TransactionReceiptDTO(Block block, TransactionInfo txInfo){
TransactionReceipt receipt = txInfo.getReceipt();
transactionHash = toJsonHex(receipt.getTransaction().getHash());
transactionIndex = toJsonHex(new Integer(txInfo.getIndex()).longValue());
cumulativeGasUsed = toJsonHex(receipt.getCumulativeGas());
gasUsed = toJsonHex(receipt.getGasUsed());
contractAddress = toJsonHex(receipt.getTransaction().getContractAddress());
from = toJsonHex(receipt.getTransaction().getSender());
to = toJsonHex(receipt.getTransaction().getReceiveAddress());
logs = new JsonRpc.LogFilterElement[receipt.getLogInfoList().size()];
if (block != null) {
blockNumber = toJsonHex(block.getNumber());
blockHash = toJsonHex(txInfo.getBlockHash());
} else {
blockNumber = null;
blockHash = null;
}
for (int i = 0; i < logs.length; i++) {
LogInfo logInfo = receipt.getLogInfoList().get(i);
logs[i] = new JsonRpc.LogFilterElement(logInfo, block, txInfo.getIndex(),
txInfo.getReceipt().getTransaction(), i);
}
logsBloom = toJsonHex(receipt.getBloomFilter().getData());
if (receipt.hasTxStatus()) { // post Byzantium
root = null;
status = receipt.isTxStatusOK() ? "0x1" : "0x0";
} else { // pre Byzantium
root = toJsonHex(receipt.getPostTxState());
status = null;
}
}
}
| ether-camp/ethereum-harmony | src/main/java/com/ethercamp/harmony/jsonrpc/TransactionReceiptDTO.java |
179,728 | /*
* This file is part of USC
* Copyright (C) 2016 - 2018 USC developer team.
* (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import org.ethereum.vm.LogInfo;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.apache.commons.lang3.ArrayUtils.nullToEmpty;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
/**
* The transaction receipt is a tuple of three items
* comprising the transaction, together with the post-transaction state,
* and the cumulative gas used in the block containing the transaction receipt
* as of immediately after the transaction has happened,
*/
public class TransactionReceipt {
private Transaction transaction;
protected static final byte[] FAILED_STATUS = EMPTY_BYTE_ARRAY;
protected static final byte[] SUCCESS_STATUS = new byte[]{0x01};
private byte[] postTxState = EMPTY_BYTE_ARRAY;
private byte[] cumulativeGas = EMPTY_BYTE_ARRAY;
private byte[] gasUsed = EMPTY_BYTE_ARRAY;
private byte[] status = EMPTY_BYTE_ARRAY;
private Bloom bloomFilter = new Bloom();
private List<LogInfo> logInfoList = new ArrayList<>();
/* Tx Receipt in encoded form */
private byte[] rlpEncoded;
public TransactionReceipt() {
}
public TransactionReceipt(byte[] rlp) {
ArrayList<RLPElement> params = RLP.decode2(rlp);
RLPList receipt = (RLPList) params.get(0);
RLPItem postTxStateRLP = (RLPItem) receipt.get(0);
RLPItem cumulativeGasRLP = (RLPItem) receipt.get(1);
RLPItem bloomRLP = (RLPItem) receipt.get(2);
RLPList logs = (RLPList) receipt.get(3);
RLPItem gasUsedRLP = (RLPItem) receipt.get(4);
postTxState = nullToEmpty(postTxStateRLP.getRLPData());
cumulativeGas = cumulativeGasRLP.getRLPData() == null ? EMPTY_BYTE_ARRAY : cumulativeGasRLP.getRLPData();
bloomFilter = new Bloom(bloomRLP.getRLPData());
gasUsed = gasUsedRLP.getRLPData() == null ? EMPTY_BYTE_ARRAY : gasUsedRLP.getRLPData();
if (receipt.size() > 5 ) {
byte[] transactionStatus = nullToEmpty(receipt.get(5).getRLPData());
this.status = transactionStatus;
}
for (RLPElement log : logs) {
LogInfo logInfo = new LogInfo(log.getRLPData());
logInfoList.add(logInfo);
}
rlpEncoded = rlp;
}
public TransactionReceipt(byte[] postTxState, byte[] cumulativeGas, byte[] gasUsed,
Bloom bloomFilter, List<LogInfo> logInfoList, byte[] status) {
this.postTxState = postTxState;
this.cumulativeGas = cumulativeGas;
this.gasUsed = gasUsed;
this.bloomFilter = bloomFilter;
this.logInfoList = logInfoList;
if (Arrays.equals(status, FAILED_STATUS) || Arrays.equals(status, SUCCESS_STATUS)) {
this.status = status;
}
}
public byte[] getPostTxState() {
return postTxState;
}
public byte[] getCumulativeGas() {
return cumulativeGas;
}
// TODO: return gas used for this transaction instead of cumulative gas
public byte[] getGasUsed() {
return gasUsed;
}
public long getCumulativeGasLong() {
return new BigInteger(1, cumulativeGas).longValue();
}
public Bloom getBloomFilter() {
return bloomFilter;
}
public List<LogInfo> getLogInfoList() {
return logInfoList;
}
/* [postTxState, cumulativeGas, bloomFilter, logInfoList] */
public byte[] getEncoded() {
if (rlpEncoded != null) {
return rlpEncoded;
}
byte[] postTxStateRLP = RLP.encodeElement(this.postTxState);
byte[] cumulativeGasRLP = RLP.encodeElement(this.cumulativeGas);
byte[] gasUsedRLP = RLP.encodeElement(this.gasUsed);
byte[] bloomRLP = RLP.encodeElement(this.bloomFilter.data);
byte[] statusRLP = RLP.encodeElement(this.status);
final byte[] logInfoListRLP;
if (logInfoList != null) {
byte[][] logInfoListE = new byte[logInfoList.size()][];
int i = 0;
for (LogInfo logInfo : logInfoList) {
logInfoListE[i] = logInfo.getEncoded();
++i;
}
logInfoListRLP = RLP.encodeList(logInfoListE);
} else {
logInfoListRLP = RLP.encodeList();
}
rlpEncoded = RLP.encodeList(postTxStateRLP, cumulativeGasRLP, bloomRLP, logInfoListRLP, gasUsedRLP, statusRLP);
return rlpEncoded;
}
public void setStatus(byte[] status) {
if (Arrays.equals(status, FAILED_STATUS)){
this.status = FAILED_STATUS;
} else if (Arrays.equals(status, SUCCESS_STATUS)){
this.status = SUCCESS_STATUS;
}
}
public boolean isSuccessful() {
return Arrays.equals(this.status, SUCCESS_STATUS);
}
public void setTxStatus(boolean success) {
this.postTxState = success ? new byte[]{1} : new byte[0];
rlpEncoded = null;
}
public boolean hasTxStatus() {
return postTxState != null && postTxState.length <= 1;
}
public boolean isTxStatusOK() {
return postTxState != null && postTxState.length == 1 && postTxState[0] == 1;
}
public void setPostTxState(byte[] postTxState) {
this.postTxState = postTxState;
}
public void setCumulativeGas(long cumulativeGas) {
this.cumulativeGas = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(cumulativeGas));
}
public void setGasUsed(long gasUsed) {
this.gasUsed = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(gasUsed));
}
public void setCumulativeGas(byte[] cumulativeGas) {
this.cumulativeGas = cumulativeGas;
}
public void setGasUsed(byte[] gasUsed) {
this.gasUsed = gasUsed;
}
public void setLogInfoList(List<LogInfo> logInfoList) {
if (logInfoList == null) {
return;
}
this.rlpEncoded = null;
this.logInfoList = logInfoList;
for (LogInfo loginfo : logInfoList) {
bloomFilter.or(loginfo.getBloom());
}
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public Transaction getTransaction() {
return transaction;
}
@Override
public String toString() {
// todo: fix that
return "TransactionReceipt[" +
"\n , " + (hasTxStatus() ? ("txStatus=" + (isSuccessful()? "OK" : "FAILED"))
: ("postTxState=" + Hex.toHexString(postTxState))) +
"\n , cumulativeGas=" + Hex.toHexString(cumulativeGas) +
"\n , bloom=" + bloomFilter.toString() +
"\n , logs=" + logInfoList +
']';
}
public byte[] getStatus() {
return this.status;
}
}
| UlordChain/Ulord-Sidechain | uscj-core/src/main/java/org/ethereum/core/TransactionReceipt.java |
179,729 | /*******************************************************************************
* HellFirePvP / Modular Machinery 2019
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/ModularMachinery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.modularmachinery.common.util;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nullable;
/**
* This class is part of the Modular Machinery Mod
* The complete source code for this mod can be found on github.
* Class: HybridGasTank
* Created by HellFirePvP
* Date: 26.08.2017 / 19:03
*/
public class HybridGasTank extends HybridTank implements IGasHandler {
@Nullable
protected GasStack gas;
public HybridGasTank(int capacity) {
super(capacity);
}
@Override
public void setFluid(@Nullable FluidStack fluid) {
super.setFluid(fluid);
if(getFluid() != null) {
setGas(null);
}
}
@Override
public int fillInternal(FluidStack resource, boolean doFill) {
if(getGas() != null && getGas().amount > 0) {
return 0;
}
return super.fillInternal(resource, doFill);
}
@Nullable
@Override
public FluidStack drainInternal(int maxDrain, boolean doDrain) {
if(getGas() != null && getGas().amount > 0) {
return null;
}
return super.drainInternal(maxDrain, doDrain);
}
@Nullable
@Override
public FluidStack drainInternal(FluidStack resource, boolean doDrain) {
if(getGas() != null && getGas().amount > 0) {
return null;
}
return super.drainInternal(resource, doDrain);
}
public void setGas(@Nullable GasStack stack) {
if(stack != null) {
this.gas = stack.copy();
setFluid(null);
} else {
this.gas = null;
}
}
@Nullable
public GasStack getGas() {
return this.gas;
}
@Override
public int receiveGas(EnumFacing side, GasStack stack, boolean doTransfer) {
if (stack == null || stack.amount <= 0) {
return 0;
}
if (fluid != null && fluid.amount > 0) {
return 0; //We don't collide with the internal fluids
}
if (!doTransfer) {
if (getGas() == null) {
return Math.min(capacity, stack.amount);
}
if (!getGas().isGasEqual(stack)) {
return 0;
}
return Math.min(capacity - getGas().amount, stack.amount);
}
if (getGas() == null) {
setGas(new GasStack(stack.getGas(), Math.min(capacity, stack.amount)));
onContentsChanged();
return getGas().amount;
}
if (!getGas().isGasEqual(stack)) {
return 0;
}
int filled = capacity - getGas().amount;
if (getGas().amount < filled) {
getGas().amount += stack.amount;
filled = stack.amount;
} else {
getGas().amount = capacity;
}
onContentsChanged();
return filled;
}
@Override
public GasStack drawGas(EnumFacing side, int amount, boolean doTransfer) {
if (getGas() == null || amount <= 0) {
return null;
}
if (getFluid() != null && getFluid().amount > 0) {
return null; //We don't collide with the internal fluids
}
int drained = amount;
if (getGas().amount < drained) {
drained = getGas().amount;
}
GasStack stack = new GasStack(getGas().getGas(), drained);
if (doTransfer) {
getGas().amount -= drained;
if (getGas().amount <= 0) {
setGas(null);
}
onContentsChanged();
}
return stack;
}
@Override
public boolean canReceiveGas(EnumFacing side, Gas type) {
return super.canFill();
}
@Override
public boolean canDrawGas(EnumFacing side, Gas type) {
return super.canDrain();
}
public void readGasFromNBT(NBTTagCompound nbt) {
NBTTagCompound subGas = nbt.getCompoundTag("gasTag");
if (subGas.getSize() > 0) {
if (!subGas.hasKey("Empty")) {
setGas(GasStack.readFromNBT(subGas));
} else {
setGas(null);
}
} else {
setGas(null);
}
}
public void writeGasToNBT(NBTTagCompound nbt) {
NBTTagCompound subGas = new NBTTagCompound();
if (gas != null) {
gas.write(subGas);
} else {
subGas.setString("Empty", "");
}
nbt.setTag("gasTag", subGas);
}
}
| HellFirePvP/ModularMachinery | src/main/java/hellfirepvp/modularmachinery/common/util/HybridGasTank.java |
179,730 | package com.sap.mentors.lemonaid.entities;
import java.util.Calendar;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import com.sap.mentors.lemonaid.annotations.SAP;
import com.sap.mentors.lemonaid.odata.authorization.ODataAuthorization;
import com.sap.mentors.lemonaid.repository.MentorRepository;
import com.sap.mentors.lemonaid.utils.types.Point;
@Entity
@Table(name="mentors")
public class Mentor {
static MentorRepository mentorRepository;
@Id
@SAP(fieldGroup="Key") private String id;
@SAP(fieldGroup="BasicInfo") private String fullName;
@SAP(fieldGroup="BasicInfo") private String photoUrl;
@SAP(fieldGroup="BasicInfo") @JoinColumn(name="statusId") @ManyToOne private MentorStatus statusId;
@SAP(fieldGroup="BasicInfo") @Temporal(TemporalType.DATE) private Calendar mentorSince;
@SAP(fieldGroup="BasicInfo") private String jobTitle;
@SAP(fieldGroup="BasicInfo") @Column(nullable = true ) private Boolean jobTitlePublic = false;
@SAP(fieldGroup="BasicInfo") private String company;
@SAP(fieldGroup="BasicInfo") @Column(nullable = true ) private Boolean companyPublic = false;
@SAP(fieldGroup="BasicInfo") @JoinColumn(name="relationshipToSapId") @ManyToOne private RelationshipToSap relationshipToSapId;
@SAP(fieldGroup="BasicInfo") @Column(length = 5000) private String bio;
@SAP(fieldGroup="BasicInfo") private String email1;
@SAP(fieldGroup="BasicInfo") @Column(nullable = true ) private Boolean email1Public = false;
@SAP(fieldGroup="BasicInfo") private String email2;
@SAP(fieldGroup="BasicInfo") @Column(nullable = true ) private Boolean email2Public = false;
@SAP(fieldGroup="BasicInfo") @JoinColumn(name="Language1Id") @ManyToOne private Language language1Id;
@SAP(fieldGroup="BasicInfo") @JoinColumn(name="Language2Id") @ManyToOne private Language language2Id;
@SAP(fieldGroup="BasicInfo") @JoinColumn(name="Language3Id") @ManyToOne private Language language3Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="lineOfBusiness1Id") @ManyToOne private LineOfBusiness lineOfBusiness1Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="lineOfBusiness2Id") @ManyToOne private LineOfBusiness lineOfBusiness2Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="lineOfBusiness3Id") @ManyToOne private LineOfBusiness lineOfBusiness3Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="industry1Id") @ManyToOne private Industry industry1Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="industry2Id") @ManyToOne private Industry industry2Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="industry3Id") @ManyToOne private Industry industry3Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise1Id") @ManyToOne private SapSoftwareSolution sapExpertise1Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise1LevelId") @ManyToOne private ExpertiseLevel sapExpertise1LevelId;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise2Id") @ManyToOne private SapSoftwareSolution sapExpertise2Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise2LevelId") @ManyToOne private ExpertiseLevel sapExpertise2LevelId;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise3Id") @ManyToOne private SapSoftwareSolution sapExpertise3Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="sapExpertise3LevelId") @ManyToOne private ExpertiseLevel sapExpertise3LevelId;
@SAP(fieldGroup="Expertise") @Column(nullable = true ) private Boolean softSkillsPublic = false;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill1Id") @ManyToOne private SoftSkill softSkill1Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill2Id") @ManyToOne private SoftSkill softSkill2Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill3Id") @ManyToOne private SoftSkill softSkill3Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill4Id") @ManyToOne private SoftSkill softSkill4Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill5Id") @ManyToOne private SoftSkill softSkill5Id;
@SAP(fieldGroup="Expertise") @JoinColumn(name="softSkill6Id") @ManyToOne private SoftSkill softSkill6Id;
@SAP(fieldGroup="Address") private String address1;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean address1Public = true;
@SAP(fieldGroup="Address") private String address2;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean address2Public = true;
@SAP(fieldGroup="Address") private String city;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean cityPublic = true;
@SAP(fieldGroup="Address") private String state;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean statePublic = true;
@SAP(fieldGroup="Address") private String zip;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean zipPublic = true;
@SAP(fieldGroup="Address") @JoinColumn(name="countryId") @ManyToOne() private Country countryId;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean countryPublic = true;
@SAP(fieldGroup="Address") private String phone;
@SAP(fieldGroup="Address") @Column(nullable = true ) private Boolean phonePublic = true;
@SAP(fieldGroup="Address") private Double latitude;
@SAP(fieldGroup="Address") private Double longitude;
@SAP(fieldGroup="Address") private Double publicLatitude;
@SAP(fieldGroup="Address") private Double publicLongitude;
@SAP(fieldGroup="Address") @JoinColumn(name="regionId") @ManyToOne private Region regionId;
@SAP(fieldGroup="Shirt") private String shirtNumber;
@SAP(fieldGroup="Shirt") private String shirtText;
@SAP(fieldGroup="Shirt") @JoinColumn(name="shirtSizeId") @ManyToOne private Size shirtSizeId;
@SAP(fieldGroup="Shirt") @JoinColumn(name="shirtMFId") @ManyToOne private Gender shirtMFId;
@SAP(fieldGroup="SocialMedia") private String scnUrl;
@SAP(fieldGroup="SocialMedia") private String twitterId;
@SAP(fieldGroup="SocialMedia") private String linkedInUrl;
@SAP(fieldGroup="SocialMedia") private String xingUrl;
@SAP(fieldGroup="SocialMedia") private String facebookUrl;
@SAP(fieldGroup="SocialMedia") private String slackId;
@SAP(fieldGroup="MentorManagement") private boolean interestInMentorCommunicationStrategy;
@SAP(fieldGroup="MentorManagement") private boolean interestInMentorManagementModel;
@SAP(fieldGroup="MentorManagement") private boolean interestInMentorMix;
@SAP(fieldGroup="MentorManagement") private boolean interestInOtherIdeas;
@SAP(fieldGroup="MentorManagement") private int hoursAvailable;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topicLeadRegionId") @ManyToOne private Region topicLeadRegionId;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topic1Id") @ManyToOne private Topic topic1Id;
@SAP(fieldGroup="TopicLead") private String topic1Executive;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topic2Id") @ManyToOne private Topic topic2Id;
@SAP(fieldGroup="TopicLead") private String topic2Executive;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topic3Id") @ManyToOne private Topic topic3Id;
@SAP(fieldGroup="TopicLead") private String topic3Executive;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topic4Id") @ManyToOne private Topic topic4Id;
@SAP(fieldGroup="TopicLead") private String topic4Executive;
@SAP(fieldGroup="TopicLead") private boolean topicLeadInterest;
@SAP(fieldGroup="TopicLead") @JoinColumn(name="topicInterestId") @ManyToOne private Topic topicInterestId;
@SAP(fieldGroup="JamBand") private boolean jambandMusician;
@SAP(fieldGroup="JamBand") private boolean jambandLasVegas;
@SAP(fieldGroup="JamBand") private boolean jambandBarcelona;
@SAP(fieldGroup="JamBand") private String jambandInstrument;
@Transient private boolean mayEdit;
private boolean publicProfile;
@OneToMany(cascade = CascadeType.ALL, mappedBy="mentorId")
private List<Attachment> attachments;
@Column(nullable = true ) private Boolean attachmentsPublic= true;
@Temporal(TemporalType.TIMESTAMP) private Calendar createdAt;
private String createdBy;
@SAP(fieldGroup="MentorManagement") @Temporal(TemporalType.TIMESTAMP) private Calendar updatedAt;
@SAP(fieldGroup="MentorManagement") private String updatedBy;
public Mentor() {}
public Mentor(
String id, String fullName, MentorStatus status,
String jobTitle, String company, RelationshipToSap relationshipToSap,
LineOfBusiness lineOfBusiness1Id, LineOfBusiness lineOfBusiness2Id, LineOfBusiness lineOfBusiness3Id,
Industry industry1Id, Industry industry2Id, Industry industry3Id,
SapSoftwareSolution sapExpertise1Id, ExpertiseLevel sapExpertise1LevelId, SapSoftwareSolution sapExpertise2Id, ExpertiseLevel sapExpertise2LevelId, SapSoftwareSolution sapExpertise3Id, ExpertiseLevel sapExpertise3LevelId,
SoftSkill softSkill1Id, SoftSkill softSkill2Id, SoftSkill softSkill3Id, SoftSkill softSkill4Id, SoftSkill softSkill5Id, SoftSkill softSkill6Id,
String bio,
String email1, String email2,
String address, String city, String state, String zip, Country countryId, String phone,
Double latitude, Double longitude, Double publicLatitude, Double publicLongitude,
Region regionId,
String shirtNumber, String shirtText, Size shirtSizeId, Gender shirtMFId,
String scnUrl, String twitterId, String linkedInUrl, String xingUrl, String facebookUrl, String slackId,
boolean interestInMentorCommunicationStrategy, boolean interestInMentorManagementModel, boolean interestInMentorMix, boolean interestInOtherIdeas, int hoursAvailable,
Region topicLeadRegionId, Topic topic1Id, String topic1Executive, Topic topic2Id, String topic2Executive, Topic topic3Id, String topic3Executive, Topic topic4Id, String topic4Executive, boolean topicLeadInterest, Topic topicInterestId,
boolean jambandMusician, boolean jambandLasVegas, boolean jambandBarcelona, String jambandInstrument,
boolean publicProfile, Boolean jobTitlePublic, Boolean companyPublic, Boolean address1Public, Boolean address2Public, Boolean cityPublic, Boolean statePublic, Boolean zipPublic, Boolean countryPublic,Boolean phonePublic, Boolean email1Public,
Boolean email2Public, Boolean attachmentsPublic, Boolean softSkillsPublic )
{
this.id = id;
this.fullName = fullName;
this.statusId = status;
this.jobTitle = jobTitle;
this.jobTitlePublic = jobTitlePublic;
this.company = company;
this.companyPublic = companyPublic;
this.relationshipToSapId = relationshipToSap;
this.lineOfBusiness1Id = lineOfBusiness1Id;
this.lineOfBusiness2Id = lineOfBusiness2Id;
this.lineOfBusiness3Id = lineOfBusiness3Id;
this.industry1Id = industry1Id;
this.industry2Id = industry2Id;
this.industry3Id = industry3Id;
this.sapExpertise1Id = sapExpertise1Id;
this.sapExpertise1LevelId = sapExpertise1LevelId;
this.sapExpertise2Id = sapExpertise2Id;
this.sapExpertise2LevelId = sapExpertise2LevelId;
this.sapExpertise3Id = sapExpertise3Id;
this.sapExpertise3LevelId = sapExpertise3LevelId;
this.softSkill1Id = softSkill1Id;
this.softSkill2Id = softSkill2Id;
this.softSkill3Id = softSkill3Id;
this.softSkill4Id = softSkill4Id;
this.softSkill5Id = softSkill5Id;
this.softSkill6Id = softSkill6Id;
this.bio = bio;
this.email1 = email1;
this.email1Public = email1Public;
this.email2 = email2;
this.email2Public = email2Public;
this.address1 = address;
this.address1Public = address1Public;
this.address2Public = address2Public;
this.city = city;
this.cityPublic = cityPublic;
this.state = state;
this.statePublic = statePublic;
this.zip = zip;
this.zipPublic = zipPublic;
this.countryId = countryId;
this.countryPublic = countryPublic;
this.phone = phone;
this.phonePublic = phonePublic;
this.latitude = latitude;
this.longitude = longitude;
this.publicLatitude = publicLatitude;
this.publicLongitude = publicLongitude;
this.regionId = regionId;
this.shirtNumber = shirtNumber;
this.shirtText = shirtText;
this.shirtSizeId = shirtSizeId;
this.shirtMFId = shirtMFId;
this.scnUrl = scnUrl;
this.twitterId = twitterId;
this.linkedInUrl = linkedInUrl;
this.xingUrl = xingUrl;
this.facebookUrl = facebookUrl;
this.slackId = slackId;
this.interestInMentorCommunicationStrategy = interestInMentorCommunicationStrategy;
this.interestInMentorManagementModel = interestInMentorManagementModel;
this.interestInMentorMix = interestInMentorMix;
this.interestInOtherIdeas = interestInOtherIdeas;
this.hoursAvailable = hoursAvailable;
this.topicLeadRegionId = topicLeadRegionId;
this.topic1Id = topic1Id;
this.topic1Executive = topic1Executive;
this.topic2Id = topic2Id;
this.topic2Executive = topic2Executive;
this.topic3Id = topic3Id;
this.topic3Executive = topic3Executive;
this.topic4Id = topic4Id;
this.topic4Executive = topic4Executive;
this.topicLeadInterest = topicLeadInterest;
this.topicInterestId = topicInterestId;
this.jambandMusician = jambandMusician;
this.jambandLasVegas = jambandLasVegas;
this.jambandBarcelona = jambandBarcelona;
this.jambandInstrument = jambandInstrument;
this.publicProfile = publicProfile;
this.attachmentsPublic = attachmentsPublic;
this.softSkillsPublic = softSkillsPublic;
}
@Override
public String toString() {
return String.format(
"Mentor[id=%d, fullName='%s']",
id, fullName);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public MentorStatus getStatusId() {
return statusId;
}
public void setStatusId(MentorStatus statusId) {
this.statusId = statusId;
}
public Calendar getMentorSince() {
return mentorSince;
}
public void setMentorSince(Calendar mentorSince) {
this.mentorSince = mentorSince;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public RelationshipToSap getRelationshipToSapId() {
return relationshipToSapId;
}
public void setRelationshipToSapId(RelationshipToSap relationshipToSapId) {
this.relationshipToSapId = relationshipToSapId;
}
public LineOfBusiness getLineOfBusiness1Id() {
return lineOfBusiness1Id;
}
public void setLineOfBusiness1Id(LineOfBusiness lineOfBusiness1Id) {
this.lineOfBusiness1Id = lineOfBusiness1Id;
}
public LineOfBusiness getLineOfBusiness2Id() {
return lineOfBusiness2Id;
}
public void setLineOfBusiness2Id(LineOfBusiness lineOfBusiness2Id) {
this.lineOfBusiness2Id = lineOfBusiness2Id;
}
public LineOfBusiness getLineOfBusiness3Id() {
return lineOfBusiness3Id;
}
public void setLineOfBusiness3Id(LineOfBusiness lineOfBusiness3Id) {
this.lineOfBusiness3Id = lineOfBusiness3Id;
}
public Industry getIndustry1Id() {
return industry1Id;
}
public void setIndustry1Id(Industry industry1Id) {
this.industry1Id = industry1Id;
}
public Industry getIndustry2Id() {
return industry2Id;
}
public void setIndustry2Id(Industry industry2Id) {
this.industry2Id = industry2Id;
}
public Industry getIndustry3Id() {
return industry3Id;
}
public void setIndustry3Id(Industry industry3Id) {
this.industry3Id = industry3Id;
}
public SapSoftwareSolution getSapExpertise1Id() {
return sapExpertise1Id;
}
public void setSapExpertise1Id(SapSoftwareSolution sapExpertise1Id) {
this.sapExpertise1Id = sapExpertise1Id;
}
public ExpertiseLevel getSapExpertise1LevelId() {
return sapExpertise1LevelId;
}
public void setSapExpertise1LevelId(ExpertiseLevel sapExpertise1LevelId) {
this.sapExpertise1LevelId = sapExpertise1LevelId;
}
public SapSoftwareSolution getSapExpertise2Id() {
return sapExpertise2Id;
}
public void setSapExpertise2Id(SapSoftwareSolution sapExpertise2Id) {
this.sapExpertise2Id = sapExpertise2Id;
}
public ExpertiseLevel getSapExpertise2LevelId() {
return sapExpertise2LevelId;
}
public void setSapExpertise2LevelId(ExpertiseLevel sapExpertise2LevelId) {
this.sapExpertise2LevelId = sapExpertise2LevelId;
}
public SapSoftwareSolution getSapExpertise3Id() {
return sapExpertise3Id;
}
public void setSapExpertise3Id(SapSoftwareSolution sapExpertise3Id) {
this.sapExpertise3Id = sapExpertise3Id;
}
public ExpertiseLevel getSapExpertise3LevelId() {
return sapExpertise3LevelId;
}
public void setSapExpertise3LevelId(ExpertiseLevel sapExpertise3LevelId) {
this.sapExpertise3LevelId = sapExpertise3LevelId;
}
public SoftSkill getSoftSkill1Id() {
return softSkill1Id;
}
public void setSoftSkill1Id(SoftSkill softSkill1Id) {
this.softSkill1Id = softSkill1Id;
}
public SoftSkill getSoftSkill2Id() {
return softSkill2Id;
}
public void setSoftSkill2Id(SoftSkill softSkill2Id) {
this.softSkill2Id = softSkill2Id;
}
public SoftSkill getSoftSkill3Id() {
return softSkill3Id;
}
public void setSoftSkill3Id(SoftSkill softSkill3Id) {
this.softSkill3Id = softSkill3Id;
}
public SoftSkill getSoftSkill4Id() {
return softSkill4Id;
}
public void setSoftSkill4Id(SoftSkill softSkill4Id) {
this.softSkill4Id = softSkill4Id;
}
public SoftSkill getSoftSkill5Id() {
return softSkill5Id;
}
public void setSoftSkill5Id(SoftSkill softSkill5Id) {
this.softSkill5Id = softSkill5Id;
}
public SoftSkill getSoftSkill6Id() {
return softSkill6Id;
}
public void setSoftSkill6Id(SoftSkill softSkill6Id) {
this.softSkill6Id = softSkill6Id;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getEmail1() {
return email1;
}
public void setEmail1(String email1) {
this.email1 = email1;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public Language getLanguage1Id() {
return language1Id;
}
public void setLanguage1Id(Language language1Id) {
this.language1Id = language1Id;
}
public Language getLanguage2Id() {
return language2Id;
}
public void setLanguage2Id(Language language2Id) {
this.language2Id = language2Id;
}
public Language getLanguage3Id() {
return language3Id;
}
public void setLanguage3Id(Language language3Id) {
this.language3Id = language3Id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getPublicLatitude() {
return publicLatitude;
}
public void setPublicLatitude(Double publicLatitude) {
this.publicLatitude = publicLatitude;
}
public Double getPublicLongitude() {
return publicLongitude;
}
public void setPublicLongitude(Double publicLongitude) {
this.publicLongitude = publicLongitude;
}
public Region getRegionId() {
return regionId;
}
public void setRegionId(Region regionId) {
this.regionId = regionId;
}
public String getShirtNumber() {
return shirtNumber;
}
public void setShirtNumber(String shirtNumber) {
this.shirtNumber = shirtNumber;
}
public String getShirtText() {
return shirtText;
}
public void setShirtText(String shirtText) {
this.shirtText = shirtText;
}
public Size getShirtSizeId() {
return shirtSizeId;
}
public void setShirtSizeId(Size shirtSizeId) {
this.shirtSizeId = shirtSizeId;
}
public Gender getShirtMFId() {
return shirtMFId;
}
public void setShirtMFId(Gender shirtMFId) {
this.shirtMFId = shirtMFId;
}
public String getScnUrl() {
return scnUrl;
}
public void setScnUrl(String scnUrl) {
this.scnUrl = scnUrl;
}
public String getTwitterId() {
return twitterId;
}
public void setTwitterId(String twitterId) {
this.twitterId = twitterId;
}
public String getLinkedInUrl() {
return linkedInUrl;
}
public void setLinkedInUrl(String linkedInUrl) {
this.linkedInUrl = linkedInUrl;
}
public String getXingUrl() {
return xingUrl;
}
public void setXingUrl(String xingUrl) {
this.xingUrl = xingUrl;
}
public String getFacebookUrl() {
return facebookUrl;
}
public void setFacebookUrl(String facebookUrl) {
this.facebookUrl = facebookUrl;
}
public String getSlackId() {
return slackId;
}
public void setSlackId(String slackId) {
this.slackId = slackId;
}
public boolean isInterestInMentorCommunicationStrategy() {
return interestInMentorCommunicationStrategy;
}
public void setInterestInMentorCommunicationStrategy(boolean interestInMentorCommunicationStrategy) {
this.interestInMentorCommunicationStrategy = interestInMentorCommunicationStrategy;
}
public boolean isInterestInMentorManagementModel() {
return interestInMentorManagementModel;
}
public void setInterestInMentorManagementModel(boolean interestInMentorManagementModel) {
this.interestInMentorManagementModel = interestInMentorManagementModel;
}
public boolean isInterestInMentorMix() {
return interestInMentorMix;
}
public void setInterestInMentorMix(boolean interestInMentorMix) {
this.interestInMentorMix = interestInMentorMix;
}
public boolean isInterestInOtherIdeas() {
return interestInOtherIdeas;
}
public void setInterestInOtherIdeas(boolean interestInOtherIdeas) {
this.interestInOtherIdeas = interestInOtherIdeas;
}
public int getHoursAvailable() {
return hoursAvailable;
}
public void setHoursAvailable(int hoursAvailable) {
this.hoursAvailable = hoursAvailable;
}
public Region getTopicLeadRegionId() {
return topicLeadRegionId;
}
public void setTopicLeadRegionId(Region topicLeadRegionId) {
this.topicLeadRegionId = topicLeadRegionId;
}
public Topic getTopic1Id() {
return topic1Id;
}
public void setTopic1Id(Topic topic1Id) {
this.topic1Id = topic1Id;
}
public String getTopic1Executive() {
return topic1Executive;
}
public void setTopic1Executive(String topic1Executive) {
this.topic1Executive = topic1Executive;
}
public Topic getTopic2Id() {
return topic2Id;
}
public void setTopic2Id(Topic topic2Id) {
this.topic2Id = topic2Id;
}
public String getTopic2Executive() {
return topic2Executive;
}
public void setTopic2Executive(String topic2Executive) {
this.topic2Executive = topic2Executive;
}
public Topic getTopic3Id() {
return topic3Id;
}
public void setTopic3Id(Topic topic3Id) {
this.topic3Id = topic3Id;
}
public String getTopic3Executive() {
return topic3Executive;
}
public void setTopic3Executive(String topic3Executive) {
this.topic3Executive = topic3Executive;
}
public Topic getTopic4Id() {
return topic4Id;
}
public void setTopic4Id(Topic topic4Id) {
this.topic4Id = topic4Id;
}
public String getTopic4Executive() {
return topic4Executive;
}
public void setTopic4Executive(String topic4Executive) {
this.topic4Executive = topic4Executive;
}
public boolean isTopicLeadInterest() {
return topicLeadInterest;
}
public void setTopicLeadInterest(boolean topicLeadInterest) {
this.topicLeadInterest = topicLeadInterest;
}
public Topic getTopicInterestId() {
return topicInterestId;
}
public void setTopicInterestId(Topic topicInterestId) {
this.topicInterestId = topicInterestId;
}
public boolean isJambandMusician() {
return jambandMusician;
}
public void setJambandMusician(boolean jambandMusician) {
this.jambandMusician = jambandMusician;
}
public boolean isJambandLasVegas() {
return jambandLasVegas;
}
public void setJambandLasVegas(boolean jambandLasVegas) {
this.jambandLasVegas = jambandLasVegas;
}
public boolean isJambandBarcelona() {
return jambandBarcelona;
}
public void setJambandBarcelona(boolean jambandBarcelona) {
this.jambandBarcelona = jambandBarcelona;
}
public String getJambandInstrument() {
return jambandInstrument;
}
public void setJambandInstrument(String jambandInstrument) {
this.jambandInstrument = jambandInstrument;
}
public boolean isPublicProfile() {
return publicProfile;
}
public void setPublicProfile(boolean publicProfile) {
this.publicProfile = publicProfile;
}
public boolean isMayEdit() {
return mayEdit;
}
public void setMayEdit(boolean mayEdit) {
this.mayEdit = mayEdit;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public void setLocation(Point location) {
if (location == null) {
this.latitude = null;
this.longitude = null;
} else {
this.latitude = location.getLatitude();
this.longitude = location.getLongitude();
}
}
public void setPublicLocation(Point location) {
if (location == null) {
this.publicLatitude = null;
this.publicLongitude = null;
} else {
this.publicLatitude = location.getLatitude();
this.publicLongitude = location.getLongitude();
}
}
public Calendar getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Calendar createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Calendar getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Calendar updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public boolean getJobTitlePublic(){
if(jobTitlePublic == null){
jobTitlePublic = false;
}
return jobTitlePublic;
}
public void setJobTitlePublic(Boolean jobTitlePublic){
this.jobTitlePublic = jobTitlePublic;
}
public boolean getCompanyPublic(){
if(companyPublic == null){
companyPublic = false;
}
return companyPublic;
}
public void setCompanyPublic(Boolean companyPublic){
this.companyPublic = companyPublic;
}
public Boolean getAddress1Public(){
if(address1Public == null){
address1Public = false;
}
return address1Public;
}
public void setAddress1Public(Boolean address1Public){
this.address1Public = address1Public;
}
public Boolean getAddress2Public(){
if(address2Public == null){
address2Public = false;
}
return address2Public;
}
public void setAddress2Public(Boolean address2Public){
this.address2Public = address2Public;
}
public Boolean getCityPublic(){
if(cityPublic == null){
cityPublic = false;
}
return cityPublic;
}
public void setCityPublic(Boolean cityPublic){
this.cityPublic = cityPublic;
}
public Boolean getStatePublic(){
if(statePublic == null){
statePublic = false;
}
return statePublic;
}
public void setStatePublic(Boolean statePublic){
this.statePublic = statePublic;
}
public Boolean getZipPublic(){
if(zipPublic == null){
zipPublic = false;
}
return zipPublic;
}
public void setZipPublic(Boolean zipPublic){
this.zipPublic = zipPublic;
}
public Boolean getCountryPublic(){
if(countryPublic == null){
countryPublic = false;
}
return countryPublic;
}
public void setCountryPublic(Boolean countryPublic){
this.countryPublic = countryPublic;
}
public Boolean getPhonePublic(){
if(phonePublic == null){
phonePublic = false;
}
return phonePublic;
}
public void setPhonePublic(Boolean phonePublic){
this.phonePublic = phonePublic;
}
public Boolean getEmail1Public(){
if(email1Public == null){
email1Public = false;
}
return email1Public;
}
public void setEmail1Public(Boolean email1Public){
this.email1Public = email1Public;
}
public Boolean getEmail2Public(){
if(email2Public == null){
email2Public = false;
}
return email2Public;
}
public void setEmail2Public(Boolean email2Public){
this.email2Public = email2Public;
}
public Boolean getAttachmentsPublic(){
if(attachmentsPublic == null){
attachmentsPublic = false;
}
return attachmentsPublic;
}
public void setAttachmentsPublic(Boolean attachmentsPublic){
this.attachmentsPublic = attachmentsPublic;
}
public Boolean getSoftSkillsPublic(){
if(softSkillsPublic == null){
softSkillsPublic = false;
}
return softSkillsPublic;
}
public void setSoftSkillsPublic(Boolean softSkillsPublic){
this.softSkillsPublic = softSkillsPublic;
}
@PrePersist
private void persist() {
String userName = (String) ODataAuthorization.getThreadLocalData().get().get("UserName");
this.createdAt = Calendar.getInstance();
this.updatedAt = Calendar.getInstance();
if (userName == null) {
this.createdBy = "SYSTEM";
this.updatedBy = "SYSTEM";
} else {
this.createdBy = userName;
this.updatedBy = userName;
}
}
@PreUpdate
private void update() {
String userName = null;
try {
userName = (String) ODataAuthorization.getThreadLocalData().get().get("UserName");
} catch (RuntimeException e) {};
if (userName != null) {
this.updatedAt = Calendar.getInstance();
this.updatedBy = userName;
}
}
}
| sapmentors/lemonaid | src/main/java/com/sap/mentors/lemonaid/entities/Mentor.java |
179,731 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.infn.mw.voms.aa.impl;
import static java.util.Comparator.comparing;
import java.util.Set;
import org.italiangrid.voms.ac.impl.VOMSGenericAttributeImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.infn.mw.iam.persistence.model.IamAccount;
import it.infn.mw.iam.persistence.model.IamAccountGroupMembership;
import it.infn.mw.iam.persistence.model.IamAttribute;
import it.infn.mw.iam.persistence.model.IamGroup;
import it.infn.mw.iam.persistence.model.IamLabel;
import it.infn.mw.voms.aa.VOMSErrorMessage;
import it.infn.mw.voms.aa.VOMSRequestContext;
import it.infn.mw.voms.aa.VOMSResponse.Outcome;
import it.infn.mw.voms.api.VOMSFqan;
import it.infn.mw.voms.properties.VomsProperties;
public class IamVOMSAttributeResolver implements AttributeResolver {
public static final Logger LOG = LoggerFactory.getLogger(IamVOMSAttributeResolver.class);
private final IamLabel vomsRoleLabel;
private final FQANEncoding fqanEncoding;
public IamVOMSAttributeResolver(VomsProperties properties, FQANEncoding fqanEncoding) {
vomsRoleLabel = IamLabel.builder().name(properties.getAa().getOptionalGroupLabel()).build();
this.fqanEncoding = fqanEncoding;
}
protected boolean iamGroupIsVomsGroup(VOMSRequestContext context, IamGroup g) {
final String voName = context.getVOName();
final boolean nameMatches = g.getName().equals(voName) || g.getName().startsWith(voName + "/");
return nameMatches && !g.getLabels().contains(vomsRoleLabel);
}
protected void noSuchUserError(VOMSRequestContext context) {
VOMSErrorMessage m = VOMSErrorMessage.noSuchUser(context.getRequest().getHolderSubject(),
context.getRequest().getHolderIssuer());
context.getResponse().setOutcome(Outcome.FAILURE);
context.getResponse().getErrorMessages().add(m);
context.setHandled(true);
}
protected void noSuchAttributeError(VOMSRequestContext context, VOMSFqan fqan) {
VOMSErrorMessage m = VOMSErrorMessage.noSuchAttribute(fqan.getFqan());
context.getResponse().setOutcome(Outcome.FAILURE);
context.getResponse().getErrorMessages().add(m);
context.setHandled(true);
}
protected boolean iamGroupIsVomsRole(IamGroup g) {
return g.getLabels().contains(vomsRoleLabel);
}
protected boolean groupMatchesFqan(IamGroup g, VOMSFqan fqan) {
final String name = fqan.asIamGroupName();
final boolean nameMatches = name.equals(g.getName());
if (fqan.isRoleFqan()) {
return nameMatches && g.getLabels().contains(vomsRoleLabel);
} else {
return nameMatches;
}
}
protected void issueRequestedFqan(VOMSRequestContext context, VOMSFqan fqan) {
if (context.getIamAccount()
.getGroups()
.stream()
.map(IamAccountGroupMembership::getGroup)
.anyMatch(g -> groupMatchesFqan(g, fqan))) {
LOG.debug("Issuing fqan: {}", fqan.getFqan());
context.getResponse().getIssuedFQANs().add(fqanEncoding.encodeFQAN(fqan.getFqan()));
} else {
noSuchAttributeError(context, fqan);
}
}
protected void issueCompulsoryGroupFqan(VOMSRequestContext context, IamGroup g) {
final String fqan = "/" + g.getName();
if (context.getResponse().getIssuedFQANs().add(fqanEncoding.encodeFQAN(fqan))) {
LOG.debug("Issued compulsory fqan: {}", fqan);
}
}
protected boolean requestAccountIsMemberOfGroup(VOMSRequestContext context, String groupName) {
IamAccount account = context.getIamAccount();
return account.getGroups().stream().anyMatch(g -> g.getGroup().getName().equals(groupName));
}
protected void resolveRequestedFQANs(VOMSRequestContext requestContext) {
requestContext.getRequest()
.getRequestedFQANs()
.forEach(f -> issueRequestedFqan(requestContext, f));
}
protected void resolveCompulsoryFQANs(VOMSRequestContext requestContext) {
requestContext.getIamAccount()
.getGroups()
.stream()
.sorted(comparing(gm -> gm.getGroup().getName()))
.filter(g -> iamGroupIsVomsGroup(requestContext, g.getGroup()))
.forEach(g -> issueCompulsoryGroupFqan(requestContext, g.getGroup()));
if (requestContext.getResponse().getIssuedFQANs().isEmpty()) {
noSuchUserError(requestContext);
}
}
@Override
public void resolveFQANs(VOMSRequestContext requestContext) {
requestContext.getRequest()
.getRequestedFQANs()
.forEach(f -> issueRequestedFqan(requestContext, f));
resolveCompulsoryFQANs(requestContext);
}
@Override
public void resolveGAs(VOMSRequestContext requestContext) {
Set<IamAttribute> attrs = requestContext.getIamAccount().getAttributes();
for (IamAttribute a : attrs) {
VOMSGenericAttributeImpl attr = new VOMSGenericAttributeImpl();
attr.setName(a.getName());
attr.setValue(a.getValue());
attr.setContext(requestContext.getVOName());
LOG.debug("Issuing generic attribute: {}", attr);
requestContext.getResponse().getIssuedGAs().add(attr);
}
}
}
| indigo-iam/iam | iam-voms-aa/src/main/java/it/infn/mw/voms/aa/impl/IamVOMSAttributeResolver.java |
179,732 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.blobs;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Corrosion;
import com.shatteredpixel.shatteredpixeldungeon.effects.BlobEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.watabou.utils.Bundle;
public class CorrosiveGas extends Blob {
//FIXME should have strength per-cell
private int strength = 0;
//used in specific cases where the source of the corrosion is important for death logic
private Class source;
@Override
protected void evolve() {
super.evolve();
if (volume == 0){
strength = 0;
source = null;
} else {
Char ch;
int cell;
for (int i = area.left; i < area.right; i++){
for (int j = area.top; j < area.bottom; j++){
cell = i + j*Dungeon.level.width();
if (cur[cell] > 0 && (ch = Actor.findChar( cell )) != null) {
if (!ch.isImmune(this.getClass()))
Buff.affect(ch, Corrosion.class).set(2f, strength, source);
}
}
}
}
}
public CorrosiveGas setStrength(int str){
return setStrength(str, null);
}
public CorrosiveGas setStrength(int str, Class source){
if (str > strength) {
strength = str;
this.source = source;
}
return this;
}
private static final String STRENGTH = "strength";
private static final String SOURCE = "source";
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
strength = bundle.getInt( STRENGTH );
source = bundle.getClass( SOURCE );
}
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put( STRENGTH, strength );
bundle.put( SOURCE, source );
}
@Override
public void use( BlobEmitter emitter ) {
super.use( emitter );
emitter.pour( Speck.factory(Speck.CORROSION), 0.4f );
}
@Override
public String tileDesc() {
return Messages.get(this, "desc");
}
}
| ifritdiezel/is-seedfinder | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/blobs/CorrosiveGas.java |
179,733 | /*
* Encog(tm) Core v3.4 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2017 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.mathutil.randomize;
import java.io.Serializable;
import java.util.Random;
import org.encog.EncogError;
import org.encog.util.EngineArray;
/**
* Generate random choices unevenly. This class is used to select random
* choices from a list, with a probability weight places on each item
* in the list.
*
* This is often called a Roulette Wheel in Machine Learning texts. How it differs from
* a Roulette Wheel that you might find in Las Vegas or Monte Carlo is that the
* areas that can be selected are not of uniform size. However, you can be sure
* that one will be picked.
*
* http://en.wikipedia.org/wiki/Fitness_proportionate_selection
*/
public class RandomChoice implements Serializable {
/**
* The probabilities of each item in the list.
*/
final private double[] probabilities;
/**
* Construct a list of probabilities.
* @param theProbabilities The probability of each item in the list.
*/
public RandomChoice(double[] theProbabilities) {
this.probabilities = EngineArray.arrayCopy(theProbabilities);
double total = 0;
for (int i = 0; i < probabilities.length; i++) {
total += probabilities[i];
}
if (total == 0.0) {
double prob = 1.0 / probabilities.length;
for (int i = 0; i < probabilities.length; i++) {
probabilities[i] = prob;
}
} else {
double total2 = 0;
double factor = 1.0 / total;
for (int i = 0; i < probabilities.length; i++) {
probabilities[i] = probabilities[i] * factor;
total2 += probabilities[i];
}
if (Math.abs(1.0 - total2) > 0.02) {
double prob = 1.0 / probabilities.length;
for (int i = 0; i < probabilities.length; i++) {
probabilities[i] = prob;
}
}
}
}
/**
* Generate a random choice, based on the probabilities provided to the constructor.
* @param theGenerator The random number generator.
* @return The random choice.
*/
public int generate(Random theGenerator) {
double r = theGenerator.nextDouble();
double sum = 0.0;
for (int i = 0; i < probabilities.length; i++) {
sum += probabilities[i];
if (r < sum) {
return i;
}
}
for (int i = 0; i < probabilities.length; i++) {
if (probabilities[i] != 0.0) {
return i;
}
}
throw new EncogError("Invalid probabilities.");
}
/**
* Generate a random choice, but skip one of the choices.
* @param theGenerator The random number generator.
* @param skip The choice to skip.
* @return The random choice.
*/
public int generate(Random theGenerator, int skip) {
double totalProb = 1.0 - probabilities[skip];
double throwValue = theGenerator.nextDouble() * totalProb;
double accumulator = 0.0;
for (int i = 0; i < skip; i++) {
accumulator += probabilities[i];
if (accumulator > throwValue) {
return i;
}
}
for (int i = skip + 1; i < probabilities.length; i++) {
accumulator += probabilities[i];
if (accumulator > throwValue) {
return i;
}
}
for (int i = 0; i < skip; i++) {
if (probabilities[i] != 0.0) {
return i;
}
}
for (int i = skip + 1; i < probabilities.length; i++) {
if (probabilities[i] != 0.0) {
return i;
}
}
return -1;
}
}
| jeffheaton/encog-java-core | src/main/java/org/encog/mathutil/randomize/RandomChoice.java |
179,734 | /*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2024, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.search.restart;
/**
* A Luby cutoff strategy.
* <p>
* Based on:
* <br/>
* "Optimal Speedup of Las Vegas Algorithms",
* M. Luby, A. Sinclair, D. Zuckerman,
* IPL: Information Processing Letters, 1993, 47, 173-180.
* <br/>
* <p>
* Example, with <i>s</i>=1:
* 1, 1, 2, 1, 1, 2, 4, 1, 1, 2, 1, 1, 2, 4, 8, 1, 1, 2, ...
*
* @author Charles Prud'homme, Arnaud Malapert, Hadrien Cambazard
* @since 13/05/11
*/
public final class LubyCutoff extends AbstractCutoff {
/**
* Current cutoff, starts at 1 and will be multiplied by {@link #scaleFactor}
* anytime {@link #getNextCutoff()} is called.
*/
private int un = 1;
/**
* Current limit, which set {@link #un} to 1 when reached.
*/
private int vn = 1;
/**
* A Luby cutoff strategy.
*
* @param s scale factor
*/
@SuppressWarnings("WeakerAccess")
public LubyCutoff(long s) {
super(s);
}
/**
* From SAT 2012: computing Luby values the way presented by Donald Knuth
* in his invited talk at the SAT 2012 conference.
* </br>
* Credits: sat4j.
*/
@Override
public long getNextCutoff() {
final long cutoff = scaleFactor * this.vn * grower.getAsInt();
if ((this.un & -this.un) == this.vn) {
this.un = this.un + 1;
this.vn = 1;
} else {
this.vn = this.vn << 1;
}
return cutoff;
}
@Override
public void reset() {
un = vn = 1;
}
@Override
public String toString() {
return "LUBY(s=" + scaleFactor + ",log2)";
}
}
| chocoteam/choco-solver | solver/src/main/java/org/chocosolver/solver/search/restart/LubyCutoff.java |
179,738 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liskovsoft.smartyoutubetv2.tv.ui.mod.clickable;
import androidx.annotation.RestrictTo;
import java.util.regex.Pattern;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;
/**
* Commonly used regular expression patterns.
*/
public final class PatternsCompat {
/**
* Regular expression to match all IANA top-level domains.
*
* List accurate as of 2015/11/24. List taken from:
* http://data.iana.org/TLD/tlds-alpha-by-domain.txt
* This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
*/
static final String IANA_TOP_LEVEL_DOMAINS =
"(?:"
+ "(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active"
+ "|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam"
+ "|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates"
+ "|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])"
+ "|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva"
+ "|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black"
+ "|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique"
+ "|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business"
+ "|buzz|bzh|b[abdefghijmnorstvwyz])"
+ "|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards"
+ "|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo"
+ "|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco"
+ "|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach"
+ "|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos"
+ "|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses"
+ "|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])"
+ "|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta"
+ "|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount"
+ "|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])"
+ "|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises"
+ "|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed"
+ "|express|e[cegrstu])"
+ "|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film"
+ "|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth"
+ "|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi"
+ "|f[ijkmor])"
+ "|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving"
+ "|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger"
+ "|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])"
+ "|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings"
+ "|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai"
+ "|h[kmnrtu])"
+ "|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute"
+ "|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])"
+ "|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])"
+ "|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])"
+ "|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc"
+ "|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live"
+ "|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])"
+ "|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba"
+ "|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda"
+ "|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar"
+ "|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])"
+ "|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk"
+ "|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])"
+ "|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka"
+ "|otsuka|ovh|om)"
+ "|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography"
+ "|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing"
+ "|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property"
+ "|protection|pub|p[aefghklmnrstwy])"
+ "|(?:qpon|quebec|qa)"
+ "|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals"
+ "|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks"
+ "|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])"
+ "|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo"
+ "|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security"
+ "|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski"
+ "|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting"
+ "|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies"
+ "|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])"
+ "|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica"
+ "|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools"
+ "|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])"
+ "|(?:ubs|university|uno|uol|u[agksyz])"
+ "|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin"
+ "|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])"
+ "|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill"
+ "|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])"
+ "|(?:\u03b5\u03bb|\u0431\u0435\u043b|\u0434\u0435\u0442\u0438|\u043a\u043e\u043c|\u043c\u043a\u0434"
+ "|\u043c\u043e\u043d|\u043c\u043e\u0441\u043a\u0432\u0430|\u043e\u043d\u043b\u0430\u0439\u043d"
+ "|\u043e\u0440\u0433|\u0440\u0443\u0441|\u0440\u0444|\u0441\u0430\u0439\u0442|\u0441\u0440\u0431"
+ "|\u0443\u043a\u0440|\u049b\u0430\u0437|\u0570\u0561\u0575|\u05e7\u05d5\u05dd|\u0627\u0631\u0627\u0645\u0643\u0648"
+ "|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629"
+ "|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0627\u06cc\u0631\u0627\u0646"
+ "|\u0628\u0627\u0632\u0627\u0631|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633"
+ "|\u0633\u0648\u062f\u0627\u0646|\u0633\u0648\u0631\u064a\u0629|\u0634\u0628\u0643\u0629"
+ "|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0641\u0644\u0633\u0637\u064a\u0646"
+ "|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0645\u0644\u064a\u0633\u064a\u0627"
+ "|\u0645\u0648\u0642\u0639|\u0915\u0949\u092e|\u0928\u0947\u091f|\u092d\u093e\u0930\u0924"
+ "|\u0938\u0902\u0917\u0920\u0928|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4"
+ "|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd"
+ "|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e04\u0e2d\u0e21|\u0e44\u0e17\u0e22"
+ "|\u10d2\u10d4|\u307f\u3093\u306a|\u30b0\u30fc\u30b0\u30eb|\u30b3\u30e0|\u4e16\u754c"
+ "|\u4e2d\u4fe1|\u4e2d\u56fd|\u4e2d\u570b|\u4e2d\u6587\u7f51|\u4f01\u4e1a|\u4f5b\u5c71"
+ "|\u4fe1\u606f|\u5065\u5eb7|\u516b\u5366|\u516c\u53f8|\u516c\u76ca|\u53f0\u6e7e|\u53f0\u7063"
+ "|\u5546\u57ce|\u5546\u5e97|\u5546\u6807|\u5728\u7ebf|\u5927\u62ff|\u5a31\u4e50|\u5de5\u884c"
+ "|\u5e7f\u4e1c|\u6148\u5584|\u6211\u7231\u4f60|\u624b\u673a|\u653f\u52a1|\u653f\u5e9c"
+ "|\u65b0\u52a0\u5761|\u65b0\u95fb|\u65f6\u5c1a|\u673a\u6784|\u6de1\u9a6c\u9521|\u6e38\u620f"
+ "|\u70b9\u770b|\u79fb\u52a8|\u7ec4\u7ec7\u673a\u6784|\u7f51\u5740|\u7f51\u5e97|\u7f51\u7edc"
+ "|\u8c37\u6b4c|\u96c6\u56e2|\u98de\u5229\u6d66|\u9910\u5385|\u9999\u6e2f|\ub2f7\ub137"
+ "|\ub2f7\ucef4|\uc0bc\uc131|\ud55c\uad6d|xbox"
+ "|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g"
+ "|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim"
+ "|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks"
+ "|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a"
+ "|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd"
+ "|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h"
+ "|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s"
+ "|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c"
+ "|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i"
+ "|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d"
+ "|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt"
+ "|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e"
+ "|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab"
+ "|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema"
+ "|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh"
+ "|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c"
+ "|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb"
+ "|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a"
+ "|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o"
+ "|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)"
+ "|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])"
+ "|(?:zara|zip|zone|zuerich|z[amw]))";
public static final Pattern IP_ADDRESS
= Pattern.compile(
"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
+ "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
+ "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
+ "|[1-9][0-9]|[0-9]))");
/**
* Valid UCS characters defined in RFC 3987. Excludes space characters.
*/
private static final String UCS_CHAR = "[" +
"\u00A0-\uD7FF" +
"\uF900-\uFDCF" +
"\uFDF0-\uFFEF" +
"\uD800\uDC00-\uD83F\uDFFD" +
"\uD840\uDC00-\uD87F\uDFFD" +
"\uD880\uDC00-\uD8BF\uDFFD" +
"\uD8C0\uDC00-\uD8FF\uDFFD" +
"\uD900\uDC00-\uD93F\uDFFD" +
"\uD940\uDC00-\uD97F\uDFFD" +
"\uD980\uDC00-\uD9BF\uDFFD" +
"\uD9C0\uDC00-\uD9FF\uDFFD" +
"\uDA00\uDC00-\uDA3F\uDFFD" +
"\uDA40\uDC00-\uDA7F\uDFFD" +
"\uDA80\uDC00-\uDABF\uDFFD" +
"\uDAC0\uDC00-\uDAFF\uDFFD" +
"\uDB00\uDC00-\uDB3F\uDFFD" +
"\uDB44\uDC00-\uDB7F\uDFFD" +
"&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]";
/**
* Valid characters for IRI label defined in RFC 3987.
*/
private static final String LABEL_CHAR = "a-zA-Z0-9" + UCS_CHAR;
/**
* Valid characters for IRI TLD defined in RFC 3987.
*/
private static final String TLD_CHAR = "a-zA-Z" + UCS_CHAR;
/**
* RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.
*/
private static final String IRI_LABEL =
"[" + LABEL_CHAR + "](?:[" + LABEL_CHAR + "_\\-]{0,61}[" + LABEL_CHAR + "]){0,1}";
/**
* RFC 3492 references RFC 1034 and limits Punycode algorithm output to 63 characters.
*/
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String TLD = "(" + PUNYCODE_TLD + "|" + "[" + TLD_CHAR + "]{2,63}" +")";
private static final String HOST_NAME = "(" + IRI_LABEL + "\\.)+" + TLD;
public static final Pattern DOMAIN_NAME
= Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");
private static final String PROTOCOL = "(?i:http|https|rtsp)://";
/* A word boundary or end of input. This is to stop foo.sure from matching as foo.su */
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
+ "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
+ "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[" + LABEL_CHAR
+ ";/\\?:@&=#~" // plus optional query params
+ "\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
/**
* Regular expression pattern to match most part of RFC 3987
* Internationalized URLs, aka IRIs.
*/
public static final Pattern WEB_URL = Pattern.compile("("
+ "("
+ "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")?"
+ "(?:" + DOMAIN_NAME + ")"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")");
/**
* Regular expression that matches known TLDs and punycode TLDs
*/
private static final String STRICT_TLD = "(?:" +
IANA_TOP_LEVEL_DOMAINS + "|" + PUNYCODE_TLD + ")";
/**
* Regular expression that matches host names using {@link #STRICT_TLD}
*/
private static final String STRICT_HOST_NAME = "(?:(?:" + IRI_LABEL + "\\.)+"
+ STRICT_TLD + ")";
/**
* Regular expression that matches domain names using either {@link #STRICT_HOST_NAME} or
* {@link #IP_ADDRESS}
*/
private static final Pattern STRICT_DOMAIN_NAME
= Pattern.compile("(?:" + STRICT_HOST_NAME + "|" + IP_ADDRESS + ")");
/**
* Regular expression that matches domain names without a TLD
*/
private static final String RELAXED_DOMAIN_NAME =
"(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" +"?)+" + "|" + IP_ADDRESS + ")";
/**
* Regular expression to match strings that do not start with a supported protocol. The TLDs
* are expected to be one of the known TLDs.
*/
private static final String WEB_URL_WITHOUT_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?<!:\\/\\/)"
+ "("
+ "(?:" + STRICT_DOMAIN_NAME + ")"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
/**
* Regular expression to match strings that start with a supported protocol. Rules for domain
* names and TLDs are more relaxed. TLDs are optional.
*/
private static final String WEB_URL_WITH_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?:"
+ "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")"
+ "(?:" + RELAXED_DOMAIN_NAME + ")?"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
/**
* Regular expression pattern to match IRIs. If a string starts with http(s):// the expression
* tries to match the URL structure with a relaxed rule for TLDs. If the string does not start
* with http(s):// the TLDs are expected to be one of the known TLDs.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP_PREFIX)
public static final Pattern AUTOLINK_WEB_URL = Pattern.compile(
"(" + WEB_URL_WITH_PROTOCOL + "|" + WEB_URL_WITHOUT_PROTOCOL + ")");
/**
* Regular expression for valid email characters. Does not include some of the valid characters
* defined in RFC5321: #&~!^`{}/=$*?|
*/
private static final String EMAIL_CHAR = LABEL_CHAR + "\\+\\-_%'";
/**
* Regular expression for local part of an email address. RFC5321 section 4.5.3.1.1 limits
* the local part to be at most 64 octets.
*/
private static final String EMAIL_ADDRESS_LOCAL_PART =
"[" + EMAIL_CHAR + "]" + "(?:[" + EMAIL_CHAR + "\\.]{0,62}[" + EMAIL_CHAR + "])?";
/**
* Regular expression for the domain part of an email address. RFC5321 section 4.5.3.1.2 limits
* the domain to be at most 255 octets.
*/
private static final String EMAIL_ADDRESS_DOMAIN =
"(?=.{1,255}(?:\\s|$|^))" + HOST_NAME;
/**
* Regular expression pattern to match email addresses. It excludes double quoted local parts
* and the special characters #&~!^`{}/=$*?| that are included in RFC5321.
* @hide
*/
@RestrictTo(LIBRARY_GROUP_PREFIX)
public static final Pattern AUTOLINK_EMAIL_ADDRESS = Pattern.compile("(" + WORD_BOUNDARY +
"(?:" + EMAIL_ADDRESS_LOCAL_PART + "@" + EMAIL_ADDRESS_DOMAIN + ")" +
WORD_BOUNDARY + ")"
);
private static final String TIME_CODE_PART = "(?:\\d+\\:\\d+)(?:\\:\\d+)?";
public static final Pattern AUTOLINK_TIME_CODE = Pattern.compile("(" + WORD_BOUNDARY +
"(?:" + TIME_CODE_PART + ")" +
WORD_BOUNDARY + ")"
);
public static final Pattern EMAIL_ADDRESS
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
/**
* Do not create this static utility class.
*/
private PatternsCompat() {}
}
| yuliskov/SmartTube | smarttubetv/src/main/java/com/liskovsoft/smartyoutubetv2/tv/ui/mod/clickable/PatternsCompat.java |
179,739 | /*******************************************************************************
* HellFirePvP / Modular Machinery 2019
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/ModularMachinery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.modularmachinery.common.tiles.base;
import hellfirepvp.modularmachinery.common.base.Mods;
import hellfirepvp.modularmachinery.common.block.prop.FluidHatchSize;
import hellfirepvp.modularmachinery.common.machine.IOType;
import hellfirepvp.modularmachinery.common.machine.MachineComponent;
import hellfirepvp.modularmachinery.common.util.HybridGasTank;
import hellfirepvp.modularmachinery.common.util.HybridTank;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import mekanism.api.gas.ITubeConnection;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.common.Optional;
import javax.annotation.Nullable;
/**
* This class is part of the Modular Machinery Mod
* The complete source code for this mod can be found on github.
* Class: TileFluidTank
* Created by HellFirePvP
* Date: 07.07.2017 / 17:51
*/
@Optional.InterfaceList({
@Optional.Interface(modid = "mekanism", iface = "mekanism.api.gas.IGasHandler"),
@Optional.Interface(modid = "mekanism", iface = "mekanism.api.gas.ITubeConnection")
})
public abstract class TileFluidTank extends TileColorableMachineComponent implements MachineComponentTile, IGasHandler, ITubeConnection {
private HybridTank tank;
private IOType ioType;
private FluidHatchSize hatchSize;
public TileFluidTank() {}
public TileFluidTank(FluidHatchSize size, IOType type) {
this.tank = size.buildTank(this, type == IOType.INPUT, type == IOType.OUTPUT);
this.hatchSize = size;
this.ioType = type;
}
public HybridTank getTank() {
return tank;
}
@Override
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) {
if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
return true;
}
if(Mods.MEKANISM.isPresent()) {
if(checkMekanismGasCapabilitiesPresence(capability, facing)) {
return true;
}
}
return super.hasCapability(capability, facing);
}
@Nullable
@Override
public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) {
if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) {
return (T) tank;
}
if(Mods.MEKANISM.isPresent()) {
if(checkMekanismGasCapabilities(capability, facing)) {
return (T) this;
}
}
return super.getCapability(capability, facing);
}
@Optional.Method(modid = "mekanism")
private boolean checkMekanismGasCapabilitiesPresence(Capability<?> capability, @Nullable EnumFacing facing) {
return checkMekanismGasCapabilities(capability, facing);
}
@Optional.Method(modid = "mekanism")
private boolean checkMekanismGasCapabilities(Capability<?> capability, @Nullable EnumFacing facing) {
String gasType = IGasHandler.class.getName().intern();
String tubeConnectionName = ITubeConnection.class.getName().intern();
return capability != null && (capability.getName().equals(gasType) || capability.getName().equals(tubeConnectionName));
}
@Override
public void readCustomNBT(NBTTagCompound compound) {
super.readCustomNBT(compound);
this.ioType = compound.getBoolean("input") ? IOType.INPUT : IOType.OUTPUT;
this.hatchSize = FluidHatchSize.values()[MathHelper.clamp(compound.getInteger("size"), 0, FluidHatchSize.values().length - 1)];
HybridTank newTank = hatchSize.buildTank(this, ioType == IOType.INPUT, ioType == IOType.OUTPUT);
NBTTagCompound tankTag = compound.getCompoundTag("tank");
newTank.readFromNBT(tankTag);
this.tank = newTank;
if(Mods.MEKANISM.isPresent()) {
this.readMekGasData(tankTag);
}
}
@Override
public void writeCustomNBT(NBTTagCompound compound) {
super.writeCustomNBT(compound);
compound.setBoolean("input", ioType == IOType.INPUT);
compound.setInteger("size", this.hatchSize.ordinal());
NBTTagCompound tankTag = new NBTTagCompound();
this.tank.writeToNBT(tankTag);
if(Mods.MEKANISM.isPresent()) {
this.writeMekGasData(tankTag);
}
compound.setTag("tank", tankTag);
}
@Nullable
@Override
public MachineComponent provideComponent() {
return new MachineComponent.FluidHatch(ioType) {
@Override
public HybridTank getContainerProvider() {
return TileFluidTank.this.tank;
}
};
}
//Mek things
@Override
@Optional.Method(modid = "mekanism")
public boolean canTubeConnect(EnumFacing side) {
return true;
}
@Optional.Method(modid = "mekanism")
private void writeMekGasData(NBTTagCompound compound) {
if(this.tank instanceof HybridGasTank) {
((HybridGasTank) this.tank).writeGasToNBT(compound);
}
}
@Optional.Method(modid = "mekanism")
private void readMekGasData(NBTTagCompound compound) {
if(this.tank instanceof HybridGasTank) {
((HybridGasTank) this.tank).readGasFromNBT(compound);
}
}
@Override
@Optional.Method(modid = "mekanism")
public int receiveGas(EnumFacing side, GasStack stack, boolean doTransfer) {
if(this.tank instanceof HybridGasTank) {
return ((HybridGasTank) this.tank).receiveGas(side, stack, doTransfer);
}
return 0;
}
@Override
@Optional.Method(modid = "mekanism")
public GasStack drawGas(EnumFacing side, int amount, boolean doTransfer) {
if(this.tank instanceof HybridGasTank) {
return ((HybridGasTank) this.tank).drawGas(side, amount, doTransfer);
}
return null;
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canReceiveGas(EnumFacing side, Gas type) {
return this.tank instanceof HybridGasTank && ((HybridGasTank) this.tank).canReceiveGas(side, type);
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canDrawGas(EnumFacing side, Gas type) {
return this.tank instanceof HybridGasTank && ((HybridGasTank) this.tank).canDrawGas(side, type);
}
}
| HellFirePvP/ModularMachinery | src/main/java/hellfirepvp/modularmachinery/common/tiles/base/TileFluidTank.java |
179,742 | /*
* ====================================================================
* Project: openCRX/Core, http://www.opencrx.org/
* Description: TextPart
* Owner: the original authors.
* ====================================================================
*
* This software is published under the BSD license
* as listed below.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the openCRX team nor the names of the contributors
* to openCRX may be used to endorse or promote products derived
* from this software without specific prior written permission
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* ------------------
*
* This product includes software developed by the Apache Software
* Foundation (http://www.apache.org/).
*
* This product includes software developed by contributors to
* openMDX (http://www.openmdx.org/)
*/
package org.opencrx.kernel.utils.rtf;
import java.awt.Font;
public class TextPart
implements Text {
public TextPart(String text) {
rawrtf = false;
bold = false;
italic = false;
underline = false;
capitals = false;
outline = false;
shadow = false;
animtext = 0;
fontsize = 0;
content = text;
}
protected TextPart(String rawtext, boolean raw) {
rawrtf = false;
bold = false;
italic = false;
underline = false;
capitals = false;
outline = false;
shadow = false;
animtext = 0;
fontsize = 0;
if(raw) {
content = rawtext;
rawrtf = true;
}
else {
content = rawtext;
}
}
public TextPart(int format, String text) {
this(text);
if((format & 1) == 1)
this.setBold(true);
if((format & 2) == 2)
this.setItalic(true);
if((format & 4) == 4)
this.setUnderline(true);
if((format & 8) == 8)
this.setCapitals(true);
if((format & 0x10) == 16)
this.setOutline(true);
if((format & 0x20) == 32)
this.setShadow(true);
}
public TextPart(int format, int fontsize, Font font, String text) {
this(format, text);
this.fontsize = fontsize;
}
public void setItalic(boolean value) {
italic = value;
}
public boolean isItalic() {
return italic;
}
public void setBold(boolean value) {
bold = value;
}
public boolean isBold() {
return bold;
}
public void setUnderline(boolean value) {
underline = value;
}
public boolean isUnderline() {
return underline;
}
public void setCapitals(boolean value) {
capitals = value;
}
public boolean isCapitals() {
return capitals;
}
public void setOutline(boolean value) {
outline = value;
}
public boolean isOutline() {
return outline;
}
public void setShadow(boolean value) {
shadow = value;
}
public boolean isShadow() {
return shadow;
}
public void setAnimtext(int animtext) {
this.animtext = animtext;
}
public int getFontsize() {
return fontsize;
}
public void setFontsize(int size) {
fontsize = size;
}
public int getAnimtext() {
return animtext;
}
public void setContent(String value) {
content = value;
}
public String getRtfContent() {
String format = (bold ? "\\b" : "") + (italic ? "\\i" : "") + (underline ? "\\ul" : "") + (capitals ? "\\caps" : "") + (outline ? "\\outl" : "") + (shadow ? "\\shad" : "") + (animtext <= 0 ? "" : "\\animtext" + animtext) + (fontsize <= 0 ? "" : "\\fs" + fontsize * 2);
return "{" + (format.length() <= 0 ? "" : format + " ") + (rawrtf ? content : RtfUtil.getRTFString(content)) + "}";
}
public static final int FORMAT_NORMAL = 0;
public static final int FORMAT_BOLD = 1;
public static final int FORMAT_ITALIC = 2;
public static final int FORMAT_UNDERLINE = 4;
public static final int FORMAT_CAPITALS = 8;
public static final int FORMAT_OUTLINE = 16;
public static final int FORMAT_SHADOW = 32;
public static final int ANIMTEXT_NO = 0;
public static final int ANIMTEXT_LASVEGAS_LIGHTS = 1;
public static final int ANIMTEXT_BLINKING_BACKGROUND = 2;
public static final int ANIMTEXT_SPARKLE_TEXT = 3;
public static final int ANIMTEXT_MARCHING_BLACK_ANTS = 4;
public static final int ANIMTEXT_MARCHING_RED_ANTS = 5;
public static final int ANIMTEXT_SHIMMER = 6;
public static final char SIGN_TAB = 9;
public static final TextPart TABULATOR = new TextPart("\\tab", true);
public static final TextPart NEWLINE = new TextPart("\\line", true);
public static final TextPart SIGN_HARDSPACE = new TextPart("\\~", true);
public static final TextPart SIGN_NON_REQUIRED_HYPHEN = new TextPart("\\-", true);
public static final TextPart SIGN_NO_BREAKING_HYPHEN = new TextPart("\\_", true);
private boolean rawrtf;
private String content;
private boolean bold;
private boolean italic;
private boolean underline;
private boolean capitals;
private boolean outline;
private boolean shadow;
private int animtext;
private int fontsize;
}
| opencrx/opencrx | core/src/main/java/org/opencrx/kernel/utils/rtf/TextPart.java |
179,743 | package mekanism.common.item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import mekanism.api.EnumColor;
import mekanism.api.MekanismConfig.general;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasRegistry;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasItem;
import mekanism.client.render.ModelCustomArmor;
import mekanism.client.render.ModelCustomArmor.ArmorModel;
import mekanism.common.Mekanism;
import mekanism.common.util.LangUtils;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.EnumHelper;
import java.util.List;
public class ItemScubaTank extends ItemArmor implements IGasItem
{
public int TRANSFER_RATE = 16;
public ItemScubaTank()
{
super(EnumHelper.addArmorMaterial("SCUBATANK", 0, new int[] {0, 0, 0, 0}, 0), 0, 1);
setCreativeTab(Mekanism.tabMekanism);
}
@Override
public void addInformation(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag)
{
GasStack gasStack = getGas(itemstack);
if(gasStack == null)
{
list.add(LangUtils.localize("tooltip.noGas") + ".");
}
else {
list.add(LangUtils.localize("tooltip.stored") + " " + gasStack.getGas().getLocalizedName() + ": " + gasStack.amount);
}
list.add(EnumColor.GREY + LangUtils.localize("tooltip.flowing") + ": " + (getFlowing(itemstack) ? EnumColor.DARK_GREEN : EnumColor.DARK_RED) + getFlowingStr(itemstack));
}
@Override
public boolean showDurabilityBar(ItemStack stack)
{
return true;
}
@Override
public double getDurabilityForDisplay(ItemStack stack)
{
return 1D-((getGas(stack) != null ? (double)getGas(stack).amount : 0D)/(double)getMaxGas(stack));
}
@Override
public boolean isValidArmor(ItemStack stack, int armorType, Entity entity)
{
return armorType == 1;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type)
{
return "mekanism:render/NullArmor.png";
}
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot)
{
ModelCustomArmor model = ModelCustomArmor.INSTANCE;
model.modelType = ArmorModel.SCUBATANK;
return model;
}
public void useGas(ItemStack itemstack)
{
setGas(itemstack, new GasStack(getGas(itemstack).getGas(), getGas(itemstack).amount-1));
}
public GasStack useGas(ItemStack itemstack, int amount)
{
if(getGas(itemstack) == null)
{
return null;
}
Gas type = getGas(itemstack).getGas();
int gasToUse = Math.min(getStored(itemstack), Math.min(getRate(itemstack), amount));
setGas(itemstack, new GasStack(type, getStored(itemstack)-gasToUse));
return new GasStack(type, gasToUse);
}
@Override
public int getMaxGas(ItemStack itemstack)
{
return general.maxScubaGas;
}
@Override
public int getRate(ItemStack itemstack)
{
return TRANSFER_RATE;
}
@Override
public int addGas(ItemStack itemstack, GasStack stack)
{
if(getGas(itemstack) != null && getGas(itemstack).getGas() != stack.getGas())
{
return 0;
}
if(stack.getGas() != GasRegistry.getGas("oxygen"))
{
return 0;
}
int toUse = Math.min(getMaxGas(itemstack)-getStored(itemstack), Math.min(getRate(itemstack), stack.amount));
setGas(itemstack, new GasStack(stack.getGas(), getStored(itemstack)+toUse));
return toUse;
}
@Override
public GasStack removeGas(ItemStack itemstack, int amount)
{
return null;
}
public int getStored(ItemStack itemstack)
{
return getGas(itemstack) != null ? getGas(itemstack).amount : 0;
}
public void toggleFlowing(ItemStack stack)
{
setFlowing(stack, !getFlowing(stack));
}
public boolean getFlowing(ItemStack stack)
{
if(stack.stackTagCompound == null)
{
return false;
}
return stack.stackTagCompound.getBoolean("flowing");
}
public String getFlowingStr(ItemStack stack)
{
boolean flowing = getFlowing(stack);
return LangUtils.localize("tooltip." + (flowing ? "yes" : "no"));
}
public void setFlowing(ItemStack stack, boolean flowing)
{
if(stack.stackTagCompound == null)
{
stack.setTagCompound(new NBTTagCompound());
}
stack.stackTagCompound.setBoolean("flowing", flowing);
}
@Override
public boolean canReceiveGas(ItemStack itemstack, Gas type)
{
return type == GasRegistry.getGas("oxygen");
}
@Override
public boolean canProvideGas(ItemStack itemstack, Gas type)
{
return false;
}
@Override
public GasStack getGas(ItemStack itemstack)
{
if(itemstack.stackTagCompound == null)
{
return null;
}
return GasStack.readFromNBT(itemstack.stackTagCompound.getCompoundTag("stored"));
}
@Override
public void setGas(ItemStack itemstack, GasStack stack)
{
if(itemstack.stackTagCompound == null)
{
itemstack.setTagCompound(new NBTTagCompound());
}
if(stack == null || stack.amount == 0)
{
itemstack.stackTagCompound.removeTag("stored");
}
else {
int amount = Math.max(0, Math.min(stack.amount, getMaxGas(itemstack)));
GasStack gasStack = new GasStack(stack.getGas(), amount);
itemstack.stackTagCompound.setTag("stored", gasStack.write(new NBTTagCompound()));
}
}
public ItemStack getEmptyItem()
{
ItemStack empty = new ItemStack(this);
setGas(empty, null);
return empty;
}
@Override
public void getSubItems(Item item, CreativeTabs tabs, List list)
{
ItemStack empty = new ItemStack(this);
setGas(empty, null);
list.add(empty);
ItemStack filled = new ItemStack(this);
setGas(filled, new GasStack(GasRegistry.getGas("oxygen"), ((IGasItem)filled.getItem()).getMaxGas(filled)));
list.add(filled);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister register) {}
}
| Thorfusion/Mekanism-Community-Edition | src/main/java/mekanism/common/item/ItemScubaTank.java |
179,744 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package commons.validator.routines;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Locale;
/**
* <p><b>Domain name</b> validation routines.</p>
*
* <p>
* This validator provides methods for validating Internet domain names
* and top-level domains.
* </p>
*
* <p>Domain names are evaluated according
* to the standards <a href="http://www.ietf.org/rfc/rfc1034.txt">RFC1034</a>,
* section 3, and <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC1123</a>,
* section 2.1. No accommodation is provided for the specialized needs of
* other applications; if the domain name has been URL-encoded, for example,
* validation will fail even though the equivalent plaintext version of the
* same name would have passed.
* </p>
*
* <p>
* Validation is also provided for top-level domains (TLDs) as defined and
* maintained by the Internet Assigned Numbers Authority (IANA):
* </p>
*
* <ul>
* <li>{@link #isValidInfrastructureTld} - validates infrastructure TLDs
* (<code>.arpa</code>, etc.)</li>
* <li>{@link #isValidGenericTld} - validates generic TLDs
* (<code>.com, .org</code>, etc.)</li>
* <li>{@link #isValidCountryCodeTld} - validates country code TLDs
* (<code>.us, .uk, .cn</code>, etc.)</li>
* </ul>
*
* <p>
* (<b>NOTE</b>: This class does not provide IP address lookup for domain names or
* methods to ensure that a given domain name matches a specific IP; see
* {@link java.net.InetAddress} for that functionality.)
* </p>
*
* @version $Revision$
* @since Validator 1.4
*/
public class DomainValidator implements Serializable {
private static final long serialVersionUID = -4407125112880174009L;
// Regular expression strings for hostnames (derived from RFC2396 and RFC 1123)
// RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
// Max 63 characters
private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]{0,61}\\p{Alnum})?";
// RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum
// Max 63 characters
private static final String TOP_LABEL_REGEX = "\\p{Alpha}(?>[\\p{Alnum}-]{0,61}\\p{Alnum})?";
// RFC2396 hostname = *( domainlabel "." ) toplabel [ "." ]
// Note that the regex currently requires both a domain label and a top level label, whereas
// the RFC does not. This is because the regex is used to detect if a TLD is present.
// If the match fails, input is checked against DOMAIN_LABEL_REGEX (hostnameRegex)
// RFC1123 sec 2.1 allows hostnames to start with a digit
private static final String DOMAIN_NAME_REGEX =
"^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")\\.?$";
private final boolean allowLocal;
/**
* Singleton instance of this validator, which
* doesn't consider local addresses as valid.
*/
private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator(false);
/**
* Singleton instance of this validator, which does
* consider local addresses valid.
*/
private static final DomainValidator DOMAIN_VALIDATOR_WITH_LOCAL = new DomainValidator(true);
/**
* RegexValidator for matching domains.
*/
private final RegexValidator domainRegex =
new RegexValidator(DOMAIN_NAME_REGEX);
/**
* RegexValidator for matching a local hostname
*/
// RFC1123 sec 2.1 allows hostnames to start with a digit
private final RegexValidator hostnameRegex =
new RegexValidator(DOMAIN_LABEL_REGEX);
/**
* Returns the singleton instance of this validator. It
* will not consider local addresses as valid.
* @return the singleton instance of this validator
*/
public static DomainValidator getInstance() {
return DOMAIN_VALIDATOR;
}
/**
* Returns the singleton instance of this validator,
* with local validation as required.
* @param allowLocal Should local addresses be considered valid?
* @return the singleton instance of this validator
*/
public static DomainValidator getInstance(boolean allowLocal) {
if(allowLocal) {
return DOMAIN_VALIDATOR_WITH_LOCAL;
}
return DOMAIN_VALIDATOR;
}
/** Private constructor. */
private DomainValidator(boolean allowLocal) {
this.allowLocal = allowLocal;
}
/**
* Returns true if the specified <code>String</code> parses
* as a valid domain name with a recognized top-level domain.
* The parsing is case-insensitive.
* @param domain the parameter to check for domain name syntax
* @return true if the parameter is a valid domain name
*/
public boolean isValid(String domain) {
if (domain == null) {
return false;
}
domain = unicodeToASCII(domain);
// hosts must be equally reachable via punycode and Unicode;
// Unicode is never shorter than punycode, so check punycode
// if domain did not convert, then it will be caught by ASCII
// checks in the regexes below
if (domain.length() > 253) {
return false;
}
String[] groups = domainRegex.match(domain);
if (groups != null && groups.length > 0) {
return isValidTld(groups[0]);
}
return allowLocal && hostnameRegex.isValid(domain);
}
// package protected for unit test access
// must agree with isValid() above
final boolean isValidDomainSyntax(String domain) {
if (domain == null) {
return false;
}
domain = unicodeToASCII(domain);
// hosts must be equally reachable via punycode and Unicode;
// Unicode is never shorter than punycode, so check punycode
// if domain did not convert, then it will be caught by ASCII
// checks in the regexes below
if (domain.length() > 253) {
return false;
}
String[] groups = domainRegex.match(domain);
return (groups != null && groups.length > 0)
|| hostnameRegex.isValid(domain);
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined top-level domain. Leading dots are ignored if present.
* The search is case-insensitive.
* @param tld the parameter to check for TLD status, not null
* @return true if the parameter is a TLD
*/
public boolean isValidTld(String tld) {
tld = unicodeToASCII(tld);
if(allowLocal && isValidLocalTld(tld)) {
return true;
}
return isValidInfrastructureTld(tld)
|| isValidGenericTld(tld)
|| isValidCountryCodeTld(tld);
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined infrastructure top-level domain. Leading dots are
* ignored if present. The search is case-insensitive.
* @param iTld the parameter to check for infrastructure TLD status, not null
* @return true if the parameter is an infrastructure TLD
*/
public boolean isValidInfrastructureTld(String iTld) {
iTld = unicodeToASCII(iTld);
return Arrays.binarySearch(INFRASTRUCTURE_TLDS, (chompLeadingDot(iTld.toLowerCase(Locale.ENGLISH)))) >= 0;
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined generic top-level domain. Leading dots are ignored
* if present. The search is case-insensitive.
* @param gTld the parameter to check for generic TLD status, not null
* @return true if the parameter is a generic TLD
*/
public boolean isValidGenericTld(String gTld) {
gTld = unicodeToASCII(gTld);
return Arrays.binarySearch(GENERIC_TLDS, chompLeadingDot(gTld.toLowerCase(Locale.ENGLISH))) >= 0;
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined country code top-level domain. Leading dots are
* ignored if present. The search is case-insensitive.
* @param ccTld the parameter to check for country code TLD status, not null
* @return true if the parameter is a country code TLD
*/
public boolean isValidCountryCodeTld(String ccTld) {
ccTld = unicodeToASCII(ccTld);
return Arrays.binarySearch(COUNTRY_CODE_TLDS, chompLeadingDot(ccTld.toLowerCase(Locale.ENGLISH))) >= 0;
}
/**
* Returns true if the specified <code>String</code> matches any
* widely used "local" domains (localhost or localdomain). Leading dots are
* ignored if present. The search is case-insensitive.
* @param lTld the parameter to check for local TLD status, not null
* @return true if the parameter is an local TLD
*/
public boolean isValidLocalTld(String lTld) {
lTld = unicodeToASCII(lTld);
return Arrays.binarySearch(LOCAL_TLDS, chompLeadingDot(lTld.toLowerCase(Locale.ENGLISH))) >= 0;
}
private String chompLeadingDot(String str) {
if (str.startsWith(".")) {
return str.substring(1);
}
return str;
}
// ---------------------------------------------
// ----- TLDs defined by IANA
// ----- Authoritative and comprehensive list at:
// ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt
// Note that the above list is in UPPER case.
// The code currently converts strings to lower case (as per the tables below)
// IANA also provide an HTML list at http://www.iana.org/domains/root/db
// Note that this contains several country code entries which are NOT in
// the text file. These all have the "Not assigned" in the "Sponsoring Organisation" column
// For example (as of 2015-01-02):
// .bl country-code Not assigned
// .um country-code Not assigned
// WARNING: this array MUST be sorted, others it cannot be searched reliably using binary search
private static final String[] INFRASTRUCTURE_TLDS = new String[] {
"arpa", // internet infrastructure
};
// WARNING: this array MUST be sorted, others it cannot be searched reliably using binary search
private static final String[] GENERIC_TLDS = new String[] {
"abogado",
"academy",
"accountants",
"active",
"actor",
"adult",
"aero",
"agency",
"airforce",
"allfinanz",
"alsace",
"amsterdam",
"android",
"aquarelle",
"archi",
"army",
"arpa",
"asia",
"associates",
"attorney",
"auction",
"audio",
"autos",
"axa",
"band",
"bar",
"bargains",
"bayern",
"beer",
"berlin",
"best",
"bid",
"bike",
"bio",
"biz",
"black",
"blackfriday",
"bloomberg",
"blue",
"bmw",
"bnpparibas",
"boo",
"boutique",
"brussels",
"budapest",
"build",
"builders",
"business",
"buzz",
"bzh",
"cab",
"cal",
"camera",
"camp",
"cancerresearch",
"capetown",
"capital",
"caravan",
"cards",
"care",
"career",
"careers",
"cartier",
"casa",
"cash",
"cat",
"catering",
"center",
"ceo",
"cern",
"channel",
"cheap",
"christmas",
"chrome",
"church",
"citic",
"city",
"claims",
"cleaning",
"click",
"clinic",
"clothing",
"club",
"coach",
"codes",
"coffee",
"college",
"cologne",
"com",
"community",
"company",
"computer",
"condos",
"construction",
"consulting",
"contractors",
"cooking",
"cool",
"coop",
"country",
"credit",
"creditcard",
"cricket",
"crs",
"cruises",
"cuisinella",
"cymru",
"dad",
"dance",
"dating",
"day",
"deals",
"degree",
"delivery",
"democrat",
"dental",
"dentist",
"desi",
"design",
"dev",
"diamonds",
"diet",
"digital",
"direct",
"directory",
"discount",
"dnp",
"docs",
"domains",
"doosan",
"durban",
"dvag",
"eat",
"edu",
"education",
"email",
"emerck",
"energy",
"engineer",
"engineering",
"enterprises",
"equipment",
"esq",
"estate",
"eurovision",
"eus",
"events",
"everbank",
"exchange",
"expert",
"exposed",
"fail",
"farm",
"fashion",
"feedback",
"finance",
"financial",
"firmdale",
"fish",
"fishing",
"fitness",
"flights",
"florist",
"flowers",
"flsmidth",
"fly",
"foo",
"forsale",
"foundation",
"frl",
"frogans",
"fund",
"furniture",
"futbol",
"gal",
"gallery",
"garden",
"gbiz",
"gent",
"ggee",
"gift",
"gifts",
"gives",
"glass",
"gle",
"global",
"globo",
"gmail",
"gmo",
"gmx",
"google",
"gop",
"gov",
"graphics",
"gratis",
"green",
"gripe",
"guide",
"guitars",
"guru",
"hamburg",
"haus",
"healthcare",
"help",
"here",
"hiphop",
"hiv",
"holdings",
"holiday",
"homes",
"horse",
"host",
"hosting",
"house",
"how",
"ibm",
"immo",
"immobilien",
"industries",
"info",
"ing",
"ink",
"institute",
"insure",
"int",
"international",
"investments",
"irish",
"iwc",
"jetzt",
"jobs",
"joburg",
"juegos",
"kaufen",
"kim",
"kitchen",
"kiwi",
"koeln",
"krd",
"kred",
"lacaixa",
"land",
"latrobe",
"lawyer",
"lds",
"lease",
"legal",
"lgbt",
"lidl",
"life",
"lighting",
"limited",
"limo",
"link",
"loans",
"london",
"lotto",
"ltda",
"luxe",
"luxury",
"madrid",
"maison",
"management",
"mango",
"market",
"marketing",
"media",
"meet",
"melbourne",
"meme",
"memorial",
"menu",
"miami",
"mil",
"mini",
"mobi",
"moda",
"moe",
"monash",
"money",
"mormon",
"mortgage",
"moscow",
"motorcycles",
"mov",
"museum",
"nagoya",
"name",
"navy",
"net",
"network",
"neustar",
"new",
"nexus",
"ngo",
"nhk",
"ninja",
"nra",
"nrw",
"nyc",
"okinawa",
"ong",
"onl",
"ooo",
"org",
"organic",
"osaka",
"otsuka",
"ovh",
"paris",
"partners",
"parts",
"party",
"pharmacy",
"photo",
"photography",
"photos",
"physio",
"pics",
"pictures",
"pink",
"pizza",
"place",
"plumbing",
"pohl",
"poker",
"porn",
"post",
"praxi",
"press",
"pro",
"prod",
"productions",
"prof",
"properties",
"property",
"pub",
"qpon",
"quebec",
"realtor",
"recipes",
"red",
"rehab",
"reise",
"reisen",
"reit",
"ren",
"rentals",
"repair",
"report",
"republican",
"rest",
"restaurant",
"reviews",
"rich",
"rio",
"rip",
"rocks",
"rodeo",
"rsvp",
"ruhr",
"ryukyu",
"saarland",
"sale",
"samsung",
"sarl",
"sca",
"scb",
"schmidt",
"schule",
"schwarz",
"science",
"scot",
"services",
"sew",
"sexy",
"shiksha",
"shoes",
"shriram",
"singles",
"sky",
"social",
"software",
"sohu",
"solar",
"solutions",
"soy",
"space",
"spiegel",
"supplies",
"supply",
"support",
"surf",
"surgery",
"suzuki",
"sydney",
"systems",
"taipei",
"tatar",
"tattoo",
"tax",
"technology",
"tel",
"tienda",
"tips",
"tires",
"tirol",
"today",
"tokyo",
"tools",
"top",
"town",
"toys",
"trade",
"training",
"travel",
"trust",
"tui",
"university",
"uno",
"uol",
"vacations",
"vegas",
"ventures",
"versicherung",
"vet",
"viajes",
"video",
"villas",
"vision",
"vlaanderen",
"vodka",
"vote",
"voting",
"voto",
"voyage",
"wales",
"wang",
"watch",
"webcam",
"website",
"wed",
"wedding",
"whoswho",
"wien",
"wiki",
"williamhill",
"wme",
"work",
"works",
"world",
"wtc",
"wtf",
"xn--1qqw23a", // 佛山 Guangzhou YU Wei Information Technology Co., Ltd.
"xn--3bst00m", // 集团 Eagle Horizon Limited
"xn--3ds443g", // 在线 TLD REGISTRY LIMITED
"xn--45q11c", // 八卦 Zodiac Scorpio Limited
"xn--4gbrim", // موقع Suhub Electronic Establishment
"xn--55qw42g", // 公益 China Organizational Name Administration Center
"xn--55qx5d", // 公司 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center)
"xn--6frz82g", // 移动 Afilias Limited
"xn--6qq986b3xl", // 我爱你 Tycoon Treasure Limited
"xn--80adxhks", // москва Foundation for Assistance for Internet Technologies and Infrastructure Development (FAITID)
"xn--80asehdb", // онлайн CORE Association
"xn--80aswg", // сайт CORE Association
"xn--c1avg", // орг Public Interest Registry
"xn--cg4bki", // 삼성 SAMSUNG SDS CO., LTD
"xn--czr694b", // 商标 HU YI GLOBAL INFORMATION RESOURCES(HOLDING) COMPANY.HONGKONG LIMITED
"xn--czrs0t", // 商店 Wild Island, LLC
"xn--czru2d", // 商城 Zodiac Aquarius Limited
"xn--d1acj3b", // дети The Foundation for Network Initiatives “The Smart Internet”
"xn--fiq228c5hs", // 中文网 TLD REGISTRY LIMITED
"xn--fiq64b", // 中信 CITIC Group Corporation
"xn--flw351e", // 谷歌 Charleston Road Registry Inc.
"xn--hxt814e", // 网店 Zodiac Libra Limited
"xn--i1b6b1a6a2e", // संगठन Public Interest Registry
"xn--io0a7i", // 网络 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center)
"xn--kput3i", // 手机 Beijing RITT-Net Technology Development Co., Ltd
"xn--mgbab2bd", // بازار CORE Association
"xn--ngbc5azd", // شبكة International Domain Registry Pty. Ltd.
"xn--nqv7f", // 机构 Public Interest Registry
"xn--nqv7fs00ema", // 组织机构 Public Interest Registry
"xn--p1acf", // рус Rusnames Limited
"xn--q9jyb4c", // みんな Charleston Road Registry Inc.
"xn--qcka1pmc", // グーグル Charleston Road Registry Inc.
"xn--rhqv96g", // 世界 Stable Tone Limited
"xn--ses554g", // 网址 HU YI GLOBAL INFORMATION RESOURCES (HOLDING) COMPANY. HONGKONG LIMITED
"xn--unup4y", // 游戏 Spring Fields, LLC
"xn--vermgensberater-ctb", // vermögensberater Deutsche Vermögensberatung Aktiengesellschaft DVAG
"xn--vermgensberatung-pwb", // vermögensberatung Deutsche Vermögensberatung Aktiengesellschaft DVAG
"xn--vhquv", // 企业 Dash McCook, LLC
"xn--xhq521b", // 广东 Guangzhou YU Wei Information Technology Co., Ltd.
"xn--zfr164b", // 政务 China Organizational Name Administration Center
"xxx",
"xyz",
"yachts",
"yandex",
"yoga",
"yokohama",
"youtube",
"zip",
"zone",
"zuerich",
};
// WARNING: this array MUST be sorted, others it cannot be searched reliably using binary search
private static final String[] COUNTRY_CODE_TLDS = new String[] {
"ac", // Ascension Island
"ad", // Andorra
"ae", // United Arab Emirates
"af", // Afghanistan
"ag", // Antigua and Barbuda
"ai", // Anguilla
"al", // Albania
"am", // Armenia
"an", // Netherlands Antilles
"ao", // Angola
"aq", // Antarctica
"ar", // Argentina
"as", // American Samoa
"at", // Austria
"au", // Australia (includes Ashmore and Cartier Islands and Coral Sea Islands)
"aw", // Aruba
"ax", // Åland
"az", // Azerbaijan
"ba", // Bosnia and Herzegovina
"bb", // Barbados
"bd", // Bangladesh
"be", // Belgium
"bf", // Burkina Faso
"bg", // Bulgaria
"bh", // Bahrain
"bi", // Burundi
"bj", // Benin
"bm", // Bermuda
"bn", // Brunei Darussalam
"bo", // Bolivia
"br", // Brazil
"bs", // Bahamas
"bt", // Bhutan
"bv", // Bouvet Island
"bw", // Botswana
"by", // Belarus
"bz", // Belize
"ca", // Canada
"cc", // Cocos (Keeling) Islands
"cd", // Democratic Republic of the Congo (formerly Zaire)
"cf", // Central African Republic
"cg", // Republic of the Congo
"ch", // Switzerland
"ci", // Côte d'Ivoire
"ck", // Cook Islands
"cl", // Chile
"cm", // Cameroon
"cn", // China, mainland
"co", // Colombia
"cr", // Costa Rica
"cu", // Cuba
"cv", // Cape Verde
"cw", // Curaçao
"cx", // Christmas Island
"cy", // Cyprus
"cz", // Czech Republic
"de", // Germany
"dj", // Djibouti
"dk", // Denmark
"dm", // Dominica
"do", // Dominican Republic
"dz", // Algeria
"ec", // Ecuador
"ee", // Estonia
"eg", // Egypt
"er", // Eritrea
"es", // Spain
"et", // Ethiopia
"eu", // European Union
"fi", // Finland
"fj", // Fiji
"fk", // Falkland Islands
"fm", // Federated States of Micronesia
"fo", // Faroe Islands
"fr", // France
"ga", // Gabon
"gb", // Great Britain (United Kingdom)
"gd", // Grenada
"ge", // Georgia
"gf", // French Guiana
"gg", // Guernsey
"gh", // Ghana
"gi", // Gibraltar
"gl", // Greenland
"gm", // The Gambia
"gn", // Guinea
"gp", // Guadeloupe
"gq", // Equatorial Guinea
"gr", // Greece
"gs", // South Georgia and the South Sandwich Islands
"gt", // Guatemala
"gu", // Guam
"gw", // Guinea-Bissau
"gy", // Guyana
"hk", // Hong Kong
"hm", // Heard Island and McDonald Islands
"hn", // Honduras
"hr", // Croatia (Hrvatska)
"ht", // Haiti
"hu", // Hungary
"id", // Indonesia
"ie", // Ireland (Éire)
"il", // Israel
"im", // Isle of Man
"in", // India
"io", // British Indian Ocean Territory
"iq", // Iraq
"ir", // Iran
"is", // Iceland
"it", // Italy
"je", // Jersey
"jm", // Jamaica
"jo", // Jordan
"jp", // Japan
"ke", // Kenya
"kg", // Kyrgyzstan
"kh", // Cambodia (Khmer)
"ki", // Kiribati
"km", // Comoros
"kn", // Saint Kitts and Nevis
"kp", // North Korea
"kr", // South Korea
"kw", // Kuwait
"ky", // Cayman Islands
"kz", // Kazakhstan
"la", // Laos (currently being marketed as the official domain for Los Angeles)
"lb", // Lebanon
"lc", // Saint Lucia
"li", // Liechtenstein
"lk", // Sri Lanka
"lr", // Liberia
"ls", // Lesotho
"lt", // Lithuania
"lu", // Luxembourg
"lv", // Latvia
"ly", // Libya
"ma", // Morocco
"mc", // Monaco
"md", // Moldova
"me", // Montenegro
"mg", // Madagascar
"mh", // Marshall Islands
"mk", // Republic of Macedonia
"ml", // Mali
"mm", // Myanmar
"mn", // Mongolia
"mo", // Macau
"mp", // Northern Mariana Islands
"mq", // Martinique
"mr", // Mauritania
"ms", // Montserrat
"mt", // Malta
"mu", // Mauritius
"mv", // Maldives
"mw", // Malawi
"mx", // Mexico
"my", // Malaysia
"mz", // Mozambique
"na", // Namibia
"nc", // New Caledonia
"ne", // Niger
"nf", // Norfolk Island
"ng", // Nigeria
"ni", // Nicaragua
"nl", // Netherlands
"no", // Norway
"np", // Nepal
"nr", // Nauru
"nu", // Niue
"nz", // New Zealand
"om", // Oman
"pa", // Panama
"pe", // Peru
"pf", // French Polynesia With Clipperton Island
"pg", // Papua New Guinea
"ph", // Philippines
"pk", // Pakistan
"pl", // Poland
"pm", // Saint-Pierre and Miquelon
"pn", // Pitcairn Islands
"pr", // Puerto Rico
"ps", // Palestinian territories (PA-controlled West Bank and Gaza Strip)
"pt", // Portugal
"pw", // Palau
"py", // Paraguay
"qa", // Qatar
"re", // Réunion
"ro", // Romania
"rs", // Serbia
"ru", // Russia
"rw", // Rwanda
"sa", // Saudi Arabia
"sb", // Solomon Islands
"sc", // Seychelles
"sd", // Sudan
"se", // Sweden
"sg", // Singapore
"sh", // Saint Helena
"si", // Slovenia
"sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian dependencies; see .no)
"sk", // Slovakia
"sl", // Sierra Leone
"sm", // San Marino
"sn", // Senegal
"so", // Somalia
"sr", // Suriname
"st", // São Tomé and Príncipe
"su", // Soviet Union (deprecated)
"sv", // El Salvador
"sx", // Sint Maarten
"sy", // Syria
"sz", // Swaziland
"tc", // Turks and Caicos Islands
"td", // Chad
"tf", // French Southern and Antarctic Lands
"tg", // Togo
"th", // Thailand
"tj", // Tajikistan
"tk", // Tokelau
"tl", // East Timor (deprecated old code)
"tm", // Turkmenistan
"tn", // Tunisia
"to", // Tonga
"tp", // East Timor
"tr", // Turkey
"tt", // Trinidad and Tobago
"tv", // Tuvalu
"tw", // Taiwan, Republic of China
"tz", // Tanzania
"ua", // Ukraine
"ug", // Uganda
"uk", // United Kingdom
"us", // United States of America
"uy", // Uruguay
"uz", // Uzbekistan
"va", // Vatican City State
"vc", // Saint Vincent and the Grenadines
"ve", // Venezuela
"vg", // British Virgin Islands
"vi", // U.S. Virgin Islands
"vn", // Vietnam
"vu", // Vanuatu
"wf", // Wallis and Futuna
"ws", // Samoa (formerly Western Samoa)
"xn--3e0b707e", // 한국 KISA (Korea Internet & Security Agency)
"xn--45brj9c", // ভারত National Internet Exchange of India
"xn--80ao21a", // қаз Association of IT Companies of Kazakhstan
"xn--90a3ac", // срб Serbian National Internet Domain Registry (RNIDS)
"xn--clchc0ea0b2g2a9gcd", // சிங்கப்பூர் Singapore Network Information Centre (SGNIC) Pte Ltd
"xn--d1alf", // мкд Macedonian Academic Research Network Skopje
"xn--fiqs8s", // 中国 China Internet Network Information Center
"xn--fiqz9s", // 中國 China Internet Network Information Center
"xn--fpcrj9c3d", // భారత్ National Internet Exchange of India
"xn--fzc2c9e2c", // ලංකා LK Domain Registry
"xn--gecrj9c", // ભારત National Internet Exchange of India
"xn--h2brj9c", // भारत National Internet Exchange of India
"xn--j1amh", // укр Ukrainian Network Information Centre (UANIC), Inc.
"xn--j6w193g", // 香港 Hong Kong Internet Registration Corporation Ltd.
"xn--kprw13d", // 台湾 Taiwan Network Information Center (TWNIC)
"xn--kpry57d", // 台灣 Taiwan Network Information Center (TWNIC)
"xn--l1acc", // мон Datacom Co.,Ltd
"xn--lgbbat1ad8j", // الجزائر CERIST
"xn--mgb9awbf", // عمان Telecommunications Regulatory Authority (TRA)
"xn--mgba3a4f16a", // ایران Institute for Research in Fundamental Sciences (IPM)
"xn--mgbaam7a8h", // امارات Telecommunications Regulatory Authority (TRA)
"xn--mgbayh7gpa", // الاردن National Information Technology Center (NITC)
"xn--mgbbh1a71e", // بھارت National Internet Exchange of India
"xn--mgbc0a9azcg", // المغرب Agence Nationale de Réglementation des Télécommunications (ANRT)
"xn--mgberp4a5d4ar", // السعودية Communications and Information Technology Commission
"xn--mgbx4cd0ab", // مليسيا MYNIC Berhad
"xn--node", // გე Information Technologies Development Center (ITDC)
"xn--o3cw4h", // ไทย Thai Network Information Center Foundation
"xn--ogbpf8fl", // سورية National Agency for Network Services (NANS)
"xn--p1ai", // рф Coordination Center for TLD RU
"xn--pgbs0dh", // تونس Agence Tunisienne d'Internet
"xn--s9brj9c", // ਭਾਰਤ National Internet Exchange of India
"xn--wgbh1c", // مصر National Telecommunication Regulatory Authority - NTRA
"xn--wgbl6a", // قطر Communications Regulatory Authority
"xn--xkc2al3hye2a", // இலங்கை LK Domain Registry
"xn--xkc2dl3a5ee0h", // இந்தியா National Internet Exchange of India
"xn--yfro4i67o", // 新加坡 Singapore Network Information Centre (SGNIC) Pte Ltd
"xn--ygbi2ammx", // فلسطين Ministry of Telecom & Information Technology (MTIT)
"ye", // Yemen
"yt", // Mayotte
"za", // South Africa
"zm", // Zambia
"zw", // Zimbabwe
};
// WARNING: this array MUST be sorted, others it cannot be searched reliably using binary search
private static final String[] LOCAL_TLDS = new String[] {
"localdomain", // Also widely used as localhost.localdomain
"localhost", // RFC2606 defined
};
/**
* Converts potentially Unicode input to punycode.
* If conversion fails, returns the original input.
*
* @param input the string to convert, not null
* @return converted input, or original input if conversion fails
*/
// Needed by UrlValidator
static String unicodeToASCII(String input) {
try {
return /* java.net.IDN. */ toASCII(input);
} catch (IllegalArgumentException e) { // input is not valid
return input;
}
}
// ================= Code needed for Java 1.4 and 1.5 compatibility ===============
private static class IDNHolder {
private static Method getMethod() {
try {
Class clazz = Class.forName("java.net.IDN", false, DomainValidator.class.getClassLoader());
return clazz.getDeclaredMethod("toASCII", new Class[]{String.class});
} catch (Exception e) {
return null;
}
}
private static final Method JAVA_NET_IDN_TO_ASCII = getMethod();
}
/*
* Helper method to invoke java.net.IDN.toAscii(String).
* Allows code to be compiled with Java 1.4 and 1.5
* @throws IllegalArgumentException if the input string doesn't conform to RFC 3490 specification
*/
private static final String toASCII(String line) throws IllegalArgumentException {
// java.net.IDN.toASCII(line); // Java 1.6+
// implementation for Java 1.4 and 1.5
// effectively this is done by IDN.toASCII but we want to skip the entire call
if (isOnlyASCII(line)) {
return line;
}
Method m = IDNHolder.JAVA_NET_IDN_TO_ASCII;
if (m == null) { // avoid NPE
return line;
}
try {
return (String) m.invoke(null, new String[]{line.toLowerCase(Locale.ENGLISH)});
} catch (IllegalAccessException e) {
throw new RuntimeException(e); // Should not happen
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof IllegalArgumentException) { // this is expected from toASCII method
throw (IllegalArgumentException) t;
}
throw new RuntimeException(e); // Should not happen
}
}
/*
* Check if input contains only ASCII
* Treats null as all ASCII
*/
private static boolean isOnlyASCII(String input) {
if (input == null) {
return true;
}
for(int i=0; i < input.length(); i++) {
if (input.charAt(i) > 0x7F) {
return false;
}
}
return true;
}
}
| ragunathjawahar/android-saripaar | saripaar/src/main/java/commons/validator/routines/DomainValidator.java |
179,745 | /*
* Write a method called stripHtmlTags that accepts a Scanner representing
* an input file containing an HTML web page as its parameter, then reads
* that file and prints the file's text with all HTML tags removed. A tag
* is any text between the characters < and > . For example, consider the
* following text:
* <html>
* <head>
* <title>My web page</title>
* </head>
* <body>
* <p>There are many pictures of my cat here,
* as well as my <b>very cool</b> blog page,
* stuff about my trip to Vegas.</p>
*
* Here's my cat now:<img src="cat.jpg">
* </body>
* </html>
*
* If the file contained these lines, your program should output the following text:
*
* My web page
*
*
* There are many pictures of my cat here,
* as well as my very cool blog page,
* which contains awesome
* stuff about my trip to Vegas.
*
* Here's my cat now:
*
* You may assume that the file is a well-formed HTML document and that there
* are no < or > characters inside tags.
*/
public static void stripHtmlTags(Scanner input) {
while (input.hasNextLine()) {
String line = input.nextLine();
while (line.contains("<") || line.contains(">")) {
int index1 = line.indexOf("<");
int index2 = line.indexOf(">");
if (index1 == 0) {
line = line.substring(index2 + 1);
} else {
line = line.substring(0, index1) + line.substring(index2 + 1);
}
}
System.out.println(line);
}
}
| Creede15/practice-it | chapter-6/stripHtmlTags.java |
179,747 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.valuetypes.vega.ui.wkt.components;
import java.util.Optional;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.model.IModel;
import org.apache.causeway.applib.value.semantics.Renderer.SyntaxHighlighter;
import org.apache.causeway.commons.internal.base._Casts;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.object.MmUnwrapUtils;
import org.apache.causeway.valuetypes.vega.applib.value.Vega;
import org.apache.causeway.valuetypes.vega.ui.wkt.components.js.VegaEmbedJsReference;
import org.apache.causeway.valuetypes.vega.ui.wkt.components.js.VegaJsReference;
import org.apache.causeway.valuetypes.vega.ui.wkt.components.js.VegaLiteJsReference;
import org.apache.causeway.viewer.wicket.ui.components.scalars.markup.MarkupComponent;
import lombok.val;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class VegaComponentWkt extends MarkupComponent {
private static final long serialVersionUID = 1L;
public VegaComponentWkt(final String id, final IModel<?> model){
super(id, model,
org.apache.causeway.viewer.wicket.ui.components.scalars.markup.MarkupComponent.Options.builder()
.syntaxHighlighter(SyntaxHighlighter.NONE)
.build());
}
@Override
public void renderHead(final IHeaderResponse response) {
super.renderHead(response);
vegaSchema()
.ifPresent(vegaSchema->{
if(vegaSchema.isVega()) {
response.render(VegaJsReference.asHeaderItem());
}
else
if(vegaSchema.isVegaLite()) {
response.render(VegaJsReference.asHeaderItem());
response.render(VegaLiteJsReference.asHeaderItem());
response.render(VegaEmbedJsReference.asHeaderItem());
}
});
}
// -- HELPER
private Optional<Vega.Schema> vegaSchema() {
val modelObject = getDefaultModelObject();
if(modelObject==null) {
return Optional.empty();
}
if(!(modelObject instanceof ManagedObject)) {
log.error("framework bug: unexpected type {}", modelObject.getClass().getName());
return Optional.empty();
}
return _Casts.castTo(Vega.class, MmUnwrapUtils.single((ManagedObject)modelObject))
.map(Vega::getSchema);
}
}
| apache/causeway | valuetypes/vega/ui/wicket/src/main/java/org/apache/causeway/valuetypes/vega/ui/wkt/components/VegaComponentWkt.java |
179,748 | package mekanism.common.integration.crafttweaker;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
import mekanism.api.chemical.ChemicalBuilder;
import mekanism.api.chemical.ChemicalStack;
import mekanism.api.gear.ICustomModule;
import mekanism.api.providers.IChemicalProvider;
import mekanism.api.providers.IModuleDataProvider;
import mekanism.api.providers.IRobitSkinProvider;
import mekanism.common.Mekanism;
/**
* Registers some "unused" and non instantiatable classes to ZenCode so that they can be resolved when ZenCode is resolving generics even if they don't need to be used on
* the ZenCode side and are just there to make the Java side easier to manage.
*/
public class DummyCrTNatives {
private DummyCrTNatives() {
}
private static final String DUMMY = "NativeDummy";
@ZenRegister
@NativeTypeRegistration(value = ChemicalStack.class, zenCodeName = CrTConstants.CLASS_CHEMICAL_STACK + DUMMY)
public static class CrTNativeChemicalStack {
private CrTNativeChemicalStack() {
}
}
@ZenRegister(loaders = CrTConstants.CONTENT_LOADER)
@NativeTypeRegistration(value = ChemicalBuilder.class, zenCodeName = CrTConstants.CLASS_BUILDER_CHEMICAL + DUMMY)
public static class CrTNativeChemicalBuilder {
private CrTNativeChemicalBuilder() {
}
}
@ZenRegister
@NativeTypeRegistration(value = ICustomModule.class, zenCodeName = CrTConstants.CLASS_CUSTOM_MODULE + DUMMY)
public static class CrTNativeCustomModule {
private CrTNativeCustomModule() {
}
}
@ZenRegister
@NativeTypeRegistration(value = IModuleDataProvider.class, zenCodeName = CrTConstants.CLASS_MODULE_DATA_PROVIDER + DUMMY)
public static class CrTNativeModuleDataProvider {
private CrTNativeModuleDataProvider() {
}
}
//TODO - 1.18: Remove the below dummies once https://github.com/ZenCodeLang/ZenCode/issues/97 is resolved
@ZenRegister
@NativeTypeRegistration(value = IChemicalProvider.class, zenCodeName = "mods." + Mekanism.MODID + ".api.provider.ChemicalProvider" + DUMMY)
public static class CrTNativeChemicalProvider {
private CrTNativeChemicalProvider() {
}
}
@ZenRegister
@NativeTypeRegistration(value = IRobitSkinProvider.class, zenCodeName = "mods." + Mekanism.MODID + ".api.provider.RobitSkinProvider" + DUMMY)
public static class CrTNativeRobitSkinProvider {
private CrTNativeRobitSkinProvider() {
}
}
} | mekanism/Mekanism | src/main/java/mekanism/common/integration/crafttweaker/DummyCrTNatives.java |
179,749 | /*******************************************************************************
* Copyright (c) 2015 David Lamparter, Daniel Marbach
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package ch.unil.genescore.vegas;
public interface WeightedChisquareAlgorithm {
int getIfault();
double probQsupx(double q);
}
| Bonder-MJ/systemsgenetics | Downstreamer/src/main/java/ch/unil/genescore/vegas/WeightedChisquareAlgorithm.java |
179,750 | package main;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import etc.Constants;
import etc.DPSPanel;
import damage.Damage;
import damage.SurfaceDamage;
import etc.UIBuilder;
import mods.Mod;
import mods.ModManagerPanel;
import ttk.TTKManagerPanel;
import ttk.TTKTarget;
import weapons.ArcGunPanel;
import weapons.PistolPanel;
import weapons.RiflePanel;
import weapons.ShotgunPanel;
import weapons.MeleePanel;
import weapons.WeaponManagerPanel;
import weapons.WeaponPanel;
import options.ColorOptionsPanel;
import Maximizer.Maximizer;
import Stances.Stance.Combo;
import Stances.Stance.Hit;
import Stances.StanceManagerPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
/**
* ____________________________________________________________ GLOBAL VARIABLES
* ____________________________________________________________
*/
/** JFrames **/
protected static JFrame mainFrame = new JFrame();
protected static JFrame modManagerFrame = new JFrame();
protected static JFrame targetManagerFrame = new JFrame();
public static JFrame weaponManagerFrame = new JFrame();
protected static JFrame colorOptionsFrame = new JFrame();
public static JFrame stanceManagerFrame = new JFrame();
/** JButtons **/
protected static JButton calculateButton = new JButton("Calculate");
protected static JButton clearOutputButton = new JButton("Clear Output");
protected static JButton maximizeButton = new JButton("Maximize");
protected static JButton stopButton = new JButton("Cancel Calculation");
protected static JButton quickTargetButton = new JButton("Add");
protected static JButton removeTargetButton = new JButton("Remove");
protected static JLabel TTKIterationsLabel = new JLabel("TTK Iterations:");
protected static JTextField TTKIterationsField = new JTextField(4);
public static JTextField targetLevelField = new JTextField(4);
protected static JLabel targetLevelLabel = new JLabel("Level");
protected static JLabel loadingLabel = new JLabel("CALCULATING");
/** JTextAreas **/
public static JTextArea output = new JTextArea();
protected static DefaultListModel enemyListModel = new DefaultListModel();
protected static JList enemyList = new JList(enemyListModel);
/** JTabbedPanes **/
protected static JTabbedPane weaponPane = new JTabbedPane();
/** JScrollPanes **/
protected static JScrollPane outputScroll = new JScrollPane(output);
/** JPanels **/
protected static JPanel mainPanel = new JPanel();
protected static JPanel secondaryPanel = new JPanel();
protected static JPanel deepsPanel = new JPanel();
protected static JPanel topPanel = new JPanel();
protected static JPanel bottomPanel = new JPanel();
protected static JPanel loadingScreen = (JPanel) mainFrame.getGlassPane();
protected static RiflePanel riflePanel;
protected static ShotgunPanel shotgunPanel;
protected static PistolPanel pistolPanel;
protected static ArcGunPanel arcGunPanel;
public static MeleePanel meleePanel;
protected static ModManagerPanel theModManager = null;
protected static TTKManagerPanel theTTKManager = null;
protected static WeaponManagerPanel theWeaponManager = null;
protected static ColorOptionsPanel theColorPanel = null;
protected static StanceManagerPanel theStanceManager = null;
protected static DPSPanel DPSPanel = new DPSPanel();
/** JMenuBar **/
protected static JMenuBar mainMenuBar = new JMenuBar();
/** JMenuItems **/
protected static JMenu fileMenu = new JMenu("File");
protected static JMenuItem modMenu = new JMenuItem("Mod Manager");
protected static JMenuItem TTKMenu = new JMenuItem("Target Manager");
protected static JMenuItem weaponMenu = new JMenuItem("Weapon Manager");
protected static JMenuItem stanceMenu = new JMenuItem("Stance Manager");
protected static JMenuItem saveItem = new JMenuItem("Save");
protected static JMenuItem loadItem = new JMenuItem("Load");
protected static JMenuItem colorOptionsItem = new JMenuItem("Color Options");
/** JFileChoosers **/
protected static JFileChooser chooser = new JFileChooser();
/** Misc UI Components **/
protected static MainActionListener action = new MainActionListener();
protected static MainChangeListener change = new MainChangeListener();
protected static MainWindowListener window = new MainWindowListener();
protected static Boolean modManagerInit = false;
protected static Boolean targetManagerInit = false;
protected static Boolean weaponManagerInit = false;
protected static Boolean colorOptionsInit = false;
protected static Boolean stanceManagerInit = false;
protected static JLabel targetGroupLabel = new JLabel("Group:");
public static JComboBox targetGroupBox = new JComboBox();
protected static JLabel corrosiveProjectionLabel = new JLabel("CPs:");
protected static JLabel shieldDisruptionLabel = new JLabel("SDs:");
protected static JComboBox corrosiveProjectionBox = new JComboBox();
protected static JComboBox shieldDisruptionBox = new JComboBox();
protected static JCheckBox headShots = new JCheckBox("Headshots");
public static JCheckBox smartMax = new JCheckBox("SmartMax");
/** Data **/
/** Selected WeaponPanel **/
public static WeaponPanel selectedWeapon = null;
/** The Maximizer **/
public static Maximizer theMaximizer = new Maximizer();
public static JProgressBar progressBar;
/** Mod Vectors **/
protected static Vector<Mod> activeMods = new Vector<Mod>();
protected static Vector<Integer> modRanks = new Vector<Integer>();
public static Vector<TTKTarget> groupTargets;
/** Base Values **/
protected static boolean useComplexTTK = true;
public static int complexTTKIterations = 10000;
// public static int complexTTKCompletions = 0;
public static String longestTTKName = "";
public static int maxTTKTime = 6000000;
public static String weaponName = "";
public static String weaponMode = "";
protected static String damageType = "";
protected static String damage2Type = "";
protected static String explosiveDamage1Type = "";
protected static String explosiveDamage2Type = "";
protected static double chargeTime = 0.0;
public static double fireRate = 0.0;
protected static double reloadTime = 0.0;
public static double critChance = 0.0;
protected static double critMult = 0.0;
public static double projectileCount = 0.0;
protected static double firstShotDamageMult = 1.0;
protected static double lastShotDamageMult = 1.0;
public static double statusChance = 0.0;
protected static double statusDuration = 1.0;
protected static double damageMult = 1.0;
protected static double deadAimMult = 1.0;
protected static double flatDamageBonus = 0.0;
protected static int mag = 0;
public static int combo = 0;
public static double startingCombo = 0;
public static int burstCount = 0;
public static double drain = 1;
public static int shatteringImpact = 0;
public static String forcedProc = "";
public static String forcedProcEX = "";
/** Calculated Values **/
public static int finalMag = 0;
protected static int finalAmmo = 0;
protected static double finalIterationTime = 0.0;
protected static double finalIterationsPerMinute = 0.0;
protected static double averageCritMult = 0.0;
public static double finalCritChance = 0.0;
public static double finalComboCrit = 0.0;
public static double finalCritMult = 0.0;
public static double finalFireRate = 0.0;
public static double finalReloadTime = 0.0;
public static double finalProjectileCount = 0.0;
public static double finalFirstShotDamageMult = 1.0;
public static double finalLastShotDamageMult = 1.0;
public static double finalStatusChance = 0.0;
public static double finalStatusDuration = 1.0;
public static double finalDamageMult = 1.0;
public static double finalDeadAimMult = 1.0;
protected static double finalFlatDamageBonus = 0.0;
public static double finalCorpusMult = 1.0;
public static double finalGrineerMult = 1.0;
public static double finalInfestedMult = 1.0;
public static double finalCorruptedMult = 1.0;
public static double averageProjectileCount = 1;
public static double averageStatusChance = 0;
/** Damage/DPS Values **/
// Misc Values
protected static double procsPerSecond = 0.0;
protected static double burstProcsPerSecond = 0.0;
protected static double slashStacks = 0;
protected static double fireStacks = 0;
protected static double toxinStacks = 0;
protected static double gasStacks = 0;
protected static double electricStacks = 0;
protected static double burstSlashStacks = 0;
protected static double burstFireStacks = 0;
protected static double burstToxinStacks = 0;
protected static double burstGasStacks = 0;
protected static double burstElectricStacks = 0;
protected static double explosiveSlashStacks = 0;
protected static double explosiveBurstSlashStacks = 0;
protected static double explosiveToxinStacks = 0;
protected static double explosiveBurstToxinStacks = 0;
protected static double explosiveGasStacks = 0;
protected static double explosiveBurstGasStacks = 0;
protected static double explosiveElectricStacks = 0;
protected static double explosiveBurstElectricStacks = 0;
protected static double explosiveFireStacks = 0;
protected static double explosiveBurstFireStacks = 0;
public static Damage raw = new Damage();
public static Damage impact = new Damage();
public static Damage puncture = new Damage();
public static Damage slash = new Damage();
public static Damage fire = new Damage();
public static Damage ice = new Damage();
public static Damage electric = new Damage();
public static Damage toxin = new Damage();
public static Damage blast = new Damage();
public static Damage magnetic = new Damage();
public static Damage gas = new Damage();
public static Damage radiation = new Damage();
public static Damage corrosive = new Damage();
public static Damage viral = new Damage();
public static Damage explosiveRaw = new Damage();
public static Damage explosiveImpact = new Damage();
public static Damage explosivePuncture = new Damage();
public static Damage explosiveSlash = new Damage();
public static Damage explosiveFire = new Damage();
public static Damage explosiveIce = new Damage();
public static Damage explosiveElectric = new Damage();
public static Damage explosiveToxin = new Damage();
public static Damage explosiveBlast = new Damage();
public static Damage explosiveMagnetic = new Damage();
public static Damage explosiveGas = new Damage();
public static Damage explosiveRadiation = new Damage();
public static Damage explosiveCorrosive = new Damage();
public static Damage explosiveViral = new Damage();
public static SurfaceDamage corpus = new SurfaceDamage();
public static SurfaceDamage grineer = new SurfaceDamage();
public static SurfaceDamage infested = new SurfaceDamage();
public static SurfaceDamage corrupted = new SurfaceDamage();
public static SurfaceDamage cloneFlesh = new SurfaceDamage();
public static SurfaceDamage ferrite = new SurfaceDamage();
public static SurfaceDamage alloy = new SurfaceDamage();
public static SurfaceDamage mechanical = new SurfaceDamage();
public static SurfaceDamage corpusFlesh = new SurfaceDamage();
public static SurfaceDamage shield = new SurfaceDamage();
public static SurfaceDamage protoShield = new SurfaceDamage();
public static SurfaceDamage robotic = new SurfaceDamage();
public static SurfaceDamage infestedFlesh = new SurfaceDamage();
public static SurfaceDamage fossilized = new SurfaceDamage();
public static SurfaceDamage sinew = new SurfaceDamage();
// Bunch of unsorted variables
public static double impactProcRate;
public static double punctureProcRate;
public static double slashProcRate;
public static double fireProcRate;
public static double iceProcRate;
public static double toxinProcRate;
public static double electricProcRate;
public static double corrosiveProcRate;
public static double gasProcRate;
public static double viralProcRate;
public static double blastProcRate;
public static double radiationProcRate;
public static double magneticProcRate;
public static double explosiveImpactProcRate;
public static double explosivePunctureProcRate;
public static double explosiveSlashProcRate;
public static double explosiveFireProcRate;
public static double explosiveIceProcRate;
public static double explosiveToxinProcRate;
public static double explosiveElectricProcRate;
public static double explosiveCorrosiveProcRate;
public static double explosiveGasProcRate;
public static double explosiveViralProcRate;
public static double explosiveBlastProcRate;
public static double explosiveRadiationProcRate;
public static double explosiveMagneticProcRate;
public static double globalToxin;
public static double globalFire;
public static double globalElectric;
public static double globalIce;
public static double fireRateModPower;
public static double hunterMunitions;
public static double impactslash;
public static double vigilante;
public static double comboCrit;
public static double comboStatus;
public static double conditionOverload;
public static boolean headShot = false;
public static double bleedDoTDPS;
public static double electricDoTDPS;
public static double poisonDoTDPS;
public static double heatDoTDPS;
public static double cloudDoTDPS;
public static double electricProcDPS;
public static double burstBleedDoTDPS;
public static double burstPoisonDoTDPS;
public static double burstHeatDoTDPS;
public static double burstCloudDoTDPS;
public static double burstElectricProcDPS;
public static double burstelectricProcDPS;
public static boolean updateOutput;
public static boolean stop = false;
public static boolean setup = true;
public static boolean maxxing = false;
public static boolean quickGroup = false;
public static double headShotBonus;
public static double headShotMult;
public static Combo stanceCombo;
public static double avgHit;
public static double avgDelay;
static double forcedSlashProcs = 0;
static double forcedImpactProcs = 0;
static double forcedPunctureProcs = 0;
static double forcedKnockdownProcs = 0;
static double COMult = 0;
static double viralMult = 0;
/**
* ____________________________________________________________ METHODS
* ____________________________________________________________
*/
/**
* Main Method
*
* @param args
*/
public static void main(String[] args) {
UIBuilder.UIInit();
riflePanel = new RiflePanel();
shotgunPanel = new ShotgunPanel();
pistolPanel = new PistolPanel();
arcGunPanel = new ArcGunPanel();
meleePanel = new MeleePanel();
theModManager = new ModManagerPanel(riflePanel, shotgunPanel, pistolPanel, meleePanel, arcGunPanel);
theTTKManager = new TTKManagerPanel();
theStanceManager = new StanceManagerPanel();
theWeaponManager = new WeaponManagerPanel(riflePanel, shotgunPanel, pistolPanel, meleePanel, arcGunPanel);
theColorPanel = new ColorOptionsPanel();
buildUI();
mainFrame.setVisible(true);
setup = false;
updateTargetList();
repack();
}
/**
* Builds the frame UI
*/
public static void buildUI() {
UIBuilder.panelInit(mainPanel);
UIBuilder.panelInit(secondaryPanel);
UIBuilder.panelInit(deepsPanel);
UIBuilder.panelInit(topPanel);
UIBuilder.panelInit(bottomPanel);
UIBuilder.panelInit(riflePanel);
UIBuilder.panelInit(shotgunPanel);
UIBuilder.panelInit(pistolPanel);
UIBuilder.panelInit(meleePanel);
UIBuilder.panelInit(arcGunPanel);
UIBuilder.buttonInit(calculateButton);
UIBuilder.buttonInit(maximizeButton);
UIBuilder.buttonInit(stopButton);
UIBuilder.buttonInit(quickTargetButton);
UIBuilder.buttonInit(removeTargetButton);
UIBuilder.labelInit(TTKIterationsLabel);
UIBuilder.labelInit(targetLevelLabel);
UIBuilder.labelInit(loadingLabel);
UIBuilder.numberFieldInit(TTKIterationsField);
UIBuilder.numberFieldInit(targetLevelField);
UIBuilder.buttonInit(clearOutputButton);
UIBuilder.textAreaInit(output);
UIBuilder.scrollPaneInit(outputScroll);
UIBuilder.tabbedPaneInit(weaponPane);
UIBuilder.menuBarInit(mainMenuBar);
UIBuilder.menuInit(fileMenu);
UIBuilder.menuItemInit(modMenu);
UIBuilder.menuItemInit(TTKMenu);
UIBuilder.menuItemInit(weaponMenu);
UIBuilder.menuItemInit(stanceMenu);
UIBuilder.menuItemInit(saveItem);
UIBuilder.menuItemInit(loadItem);
UIBuilder.menuItemInit(colorOptionsItem);
UIBuilder.fileChooserInit(chooser);
UIBuilder.checkBoxInit(headShots);
UIBuilder.checkBoxInit(smartMax);
UIBuilder.labelInit(corrosiveProjectionLabel);
UIBuilder.labelInit(shieldDisruptionLabel);
UIBuilder.labelInit(targetGroupLabel);
UIBuilder.comboBoxInit(corrosiveProjectionBox);
UIBuilder.comboBoxInit(shieldDisruptionBox);
UIBuilder.comboBoxInit(targetGroupBox);
UIBuilder.listInit(enemyList);
enemyList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
enemyList.setLayoutOrientation(JList.VERTICAL_WRAP);
enemyList.setVisibleRowCount(-1);
corrosiveProjectionBox.setPrototypeDisplayValue("XX");
shieldDisruptionBox.setPrototypeDisplayValue("XX");
targetGroupBox.setPrototypeDisplayValue("XX");
for (int i = 0; i < 10; i++) {
targetGroupBox.addItem("" + i);
}
for (int i = 0; i < 5; i++) {
corrosiveProjectionBox.addItem("" + i);
}
for (int i = 0; i < 5; i++) {
shieldDisruptionBox.addItem("" + i);
}
try {
File currentDirectory = new File(".");
chooser.setCurrentDirectory(currentDirectory);
} catch (Exception ex) {
ex.printStackTrace();
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
calculateButton.addActionListener(action);
maximizeButton.addActionListener(action);
stopButton.addActionListener(action);
quickTargetButton.addActionListener(action);
removeTargetButton.addActionListener(action);
clearOutputButton.addActionListener(action);
saveItem.addActionListener(action);
loadItem.addActionListener(action);
modMenu.addActionListener(action);
TTKMenu.addActionListener(action);
weaponMenu.addActionListener(action);
stanceMenu.addActionListener(action);
colorOptionsItem.addActionListener(action);
headShots.addActionListener(action);
targetGroupBox.addActionListener(action);
weaponPane.addChangeListener(change);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
secondaryPanel.setLayout(new BoxLayout(secondaryPanel, BoxLayout.X_AXIS));
deepsPanel.setLayout(new BoxLayout(deepsPanel, BoxLayout.Y_AXIS));
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
weaponPane.add(riflePanel, Constants.RIFLE);
weaponPane.add(shotgunPanel, Constants.SHOTGUN);
weaponPane.add(pistolPanel, Constants.PISTOL);
weaponPane.add(meleePanel, Constants.MELEE);
weaponPane.add(arcGunPanel, Constants.ARCHGUN);
JPanel targetButtonPanel = new JPanel();
UIBuilder.panelInit(targetButtonPanel);
targetButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
targetButtonPanel.add(targetGroupLabel);
targetButtonPanel.add(targetGroupBox);
targetButtonPanel.add(targetLevelLabel);
targetButtonPanel.add(targetLevelField);
targetButtonPanel.add(quickTargetButton);
targetButtonPanel.add(removeTargetButton);
JPanel buttonPanel = new JPanel();
UIBuilder.panelInit(buttonPanel);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(corrosiveProjectionLabel);
buttonPanel.add(corrosiveProjectionBox);
buttonPanel.add(shieldDisruptionLabel);
buttonPanel.add(shieldDisruptionBox);
buttonPanel.add(headShots);
buttonPanel.add(TTKIterationsLabel);
buttonPanel.add(TTKIterationsField);
buttonPanel.add(calculateButton);
buttonPanel.add(maximizeButton);
buttonPanel.add(clearOutputButton);
buttonPanel.add(smartMax);
headShots.setToolTipText("Calcualtes TTK as if you are getting only headshots. Not related to effects triggered by headshots.");
corrosiveProjectionLabel.setToolTipText("Number of Corrosive Projection auras active.");
corrosiveProjectionBox.setToolTipText("Number of Corrosive Projection auras active.");
shieldDisruptionLabel.setToolTipText("Number of Shield Disruption auras active.");
shieldDisruptionBox.setToolTipText("Number of Shield Disruption auras active.");
targetGroupLabel.setToolTipText("Target group to run calculations against.");
targetGroupBox.setToolTipText("Target group to run calculations against.");
TTKIterationsField.setToolTipText("Set the number of TTK simulation iterations. 10000 by defautl, 1000 for lightweight TTK.");
TTKIterationsLabel.setToolTipText("Set the number of TTK simulation iterations. 10000 by defautl, 1000 for lightweight TTK.");
maximizeButton.setToolTipText("Test every combination of mods in empty mod slots for the best builds. Will take time to complete");
targetLevelLabel.setToolTipText("Override the default level");
targetLevelField.setToolTipText("Override the default level");
quickTargetButton.setToolTipText("Add targets to the current group");
removeTargetButton.setToolTipText("Remove selected target from the current group");
smartMax.setToolTipText("Allows the maximizer to skip bad builds. Disable if you want complete results");
JPanel bottomRightPanel = new JPanel();
UIBuilder.panelInit(bottomRightPanel);
bottomRightPanel.setLayout(new BoxLayout(bottomRightPanel, BoxLayout.Y_AXIS));
bottomRightPanel.add(outputScroll);
bottomRightPanel.add(buttonPanel);
JPanel bottomLeftPanel = new JPanel();
JPanel bottomLeftFillPanel = new JPanel();
bottomLeftFillPanel.setLayout(new GridBagLayout());
UIBuilder.panelInit(bottomLeftPanel);
bottomLeftPanel.setLayout(new BoxLayout(bottomLeftPanel, BoxLayout.Y_AXIS));
bottomLeftFillPanel.add(enemyList, gbc);
bottomLeftPanel.add(bottomLeftFillPanel);
bottomLeftPanel.add(targetButtonPanel, gbc);
UIBuilder.panelInit(bottomLeftFillPanel);
outputScroll.getViewport().setPreferredSize(new Dimension(850, 250));
bottomLeftFillPanel.setPreferredSize(new Dimension(300, 250));
buttonPanel.setSize(new Dimension(200, 30));
targetLevelField.setPreferredSize(new Dimension(0, 24));
TTKIterationsField.setPreferredSize(new Dimension(0, 24));
topPanel.add(weaponPane);
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
mainPanel.add(topPanel);
mainPanel.add(bottomPanel);
mainPanel.setAlignmentY(Component.TOP_ALIGNMENT);
DPSPanel.setAlignmentY(Component.TOP_ALIGNMENT);
secondaryPanel.add(mainPanel);
secondaryPanel.add(DPSPanel);
fileMenu.add(colorOptionsItem);
fileMenu.add(saveItem);
fileMenu.add(loadItem);
mainMenuBar.add(fileMenu);
mainMenuBar.add(modMenu);
mainMenuBar.add(TTKMenu);
mainMenuBar.add(weaponMenu);
mainMenuBar.add(stanceMenu);
mainFrame.setJMenuBar(mainMenuBar);
mainFrame.add(secondaryPanel);
mainFrame.pack();
mainFrame.addWindowListener(window);
mainFrame.setTitle(Constants.APP_TITLE + " " + Constants.APP_VERSION);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
smartMax.setSelected(false);
// Loading screen
progressBar = new JProgressBar(0, 100);
progressBar.setBackground(Color.BLACK);
progressBar.setForeground(Color.GREEN);
loadingLabel.setFont(new Font("Verdana", Font.PLAIN, 100));
loadingScreen.setLayout(new GridBagLayout());
JPanel loadingStats = new JPanel();
JPanel loadingBackground = new JPanel();
loadingBackground.setBackground(new Color(0, 0, 0, 180));
loadingStats.setOpaque(false);
loadingBackground.setLayout(new GridBagLayout());
loadingStats.setLayout(new BoxLayout(loadingStats, BoxLayout.Y_AXIS));
loadingStats.add(loadingLabel);
loadingStats.add(progressBar);
JPanel stopPanel = new JPanel();
stopPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
stopPanel.add(stopButton);
stopPanel.setOpaque(false);
loadingStats.add(stopPanel);
loadingStats.setBackground(new Color(0, 0, 0, 0));
loadingBackground.add(loadingStats);
loadingScreen.add(loadingBackground, gbc);
loadingScreen.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.consume();
}
@Override
public void mousePressed(MouseEvent e) {
e.consume();
}
});
TTKIterationsField.setText("10000");
UIBuilder.createTitledLineBorder(DPSPanel.stats, "CALCULATED STATS");
UIBuilder.createTitledLineBorder(DPSPanel.status, "STATUS BREAKDOWN");
UIBuilder.createTitledLineBorder(bottomLeftFillPanel, "TARGETS");
}
/**
* Calculates and Displays the DPS
*/
public static void calculateDPS() {
// Clear all the previous values
clearValues();
// Get the Selected Weapon Type and Active Mods
selectedWeapon = (WeaponPanel) weaponPane.getSelectedComponent();
// selectedWeapon.parseActiveMods();
// Get the base values from the selected weapon
getBaseValues();
// Calculate the final values based on weapon parameters and Active Mods
calculateFinals();
// Calculate miscellaneous values
calculateMiscValues();
// Calculate damage per shot
calculateDamagePerShot();
// Calculate the damage per magazine
calculateDamagePerIteration();
// Calculate the damage per minute
calculateDamagePerMinute();
// Calculate the damage per second
calculateDamagePerSecond();
// Calculate the burst damage per second
calculateBurstDamagePerSecond();
// Calculate Time To Kill Values
String iters = TTKIterationsField.getText();
if (iters == null) {
iters = "10000";
}
complexTTKIterations = Integer.parseInt(iters);
if (useComplexTTK && raw.perSecond > 100) {
int targetGroup = Integer.parseInt((String) targetGroupBox.getSelectedItem());
groupTargets = new Vector<TTKTarget>();
for (TTKTarget target : theTTKManager.targets) {
if (target.groups.contains(targetGroup)) {
groupTargets.add(target);
}
}
// complexTTKCompletions = 0;
for (TTKTarget target : groupTargets) {
target.runAdvancedTTK();
String name = target.name + "[" + target.currentLevel + "]";
if (name.length() > longestTTKName.length()) {
longestTTKName = name;
}
}
}
// Print the data to the text area and render the graph
if (updateOutput) {
updateOutput();
}
}
public static void updateTargetList() {
enemyListModel.clear();
int targetGroup = Integer.parseInt((String) targetGroupBox.getSelectedItem());
groupTargets = new Vector<TTKTarget>();
for (TTKTarget target : theTTKManager.targets) {
if (target.groups.contains(targetGroup)) {
enemyListModel.addElement(target.name);
}
}
repack();
}
/**
* Clears all values
*/
public static void clearValues() {
selectedWeapon = null;
activeMods = new Vector<Mod>();
modRanks = new Vector<Integer>();
weaponName = "";
weaponMode = "";
damageType = "";
damage2Type = "";
explosiveDamage1Type = "";
explosiveDamage2Type = "";
chargeTime = 0.0;
drain = 0;
raw.clear();
impact.clear();
puncture.clear();
slash.clear();
fire.clear();
ice.clear();
electric.clear();
toxin.clear();
blast.clear();
magnetic.clear();
gas.clear();
radiation.clear();
corrosive.clear();
viral.clear();
explosiveRaw.clear();
explosiveImpact.clear();
explosivePuncture.clear();
explosiveSlash.clear();
explosiveFire.clear();
explosiveIce.clear();
explosiveElectric.clear();
explosiveToxin.clear();
explosiveBlast.clear();
explosiveMagnetic.clear();
explosiveGas.clear();
explosiveRadiation.clear();
explosiveCorrosive.clear();
explosiveViral.clear();
corpus.clear();
grineer.clear();
infested.clear();
corrupted.clear();
cloneFlesh.clear();
ferrite.clear();
alloy.clear();
mechanical.clear();
corpusFlesh.clear();
shield.clear();
protoShield.clear();
robotic.clear();
infestedFlesh.clear();
fossilized.clear();
sinew.clear();
fireRate = 0.0;
reloadTime = 0.0;
critChance = 0.0;
critMult = 0.0;
projectileCount = 0.0;
firstShotDamageMult = 1.0;
lastShotDamageMult = 1.0;
statusChance = 0.0;
statusDuration = 1.0;
damageMult = 1.0;
deadAimMult = 1.0;
flatDamageBonus = 0.0;
mag = 0;
combo = 0;
startingCombo = 1;
burstCount = 0;
finalMag = 0;
finalAmmo = 0;
finalIterationTime = 0.0;
finalIterationsPerMinute = 0.0;
averageCritMult = 0;
finalCritChance = 0.0;
finalCritMult = 0.0;
finalFireRate = 0.0;
finalReloadTime = 0.0;
finalProjectileCount = 0.0;
finalFirstShotDamageMult = 1.0;
finalLastShotDamageMult = 1.0;
finalStatusChance = 0.0;
finalStatusDuration = 0.0;
finalDamageMult = 1.0;
finalDeadAimMult = 1.0;
finalFlatDamageBonus = 0.0;
finalCorpusMult = 1.0;
finalGrineerMult = 1.0;
finalInfestedMult = 1.0;
finalCorruptedMult = 1.0;
procsPerSecond = 0.0;
burstProcsPerSecond = 0.0;
slashStacks = 0;
fireStacks = 0;
toxinStacks = 0;
gasStacks = 0;
burstSlashStacks = 0;
burstFireStacks = 0;
burstToxinStacks = 0;
burstGasStacks = 0;
// complexTTKCompletions = 0;
globalFire = 0;
globalToxin = 0;
globalElectric = 0;
globalIce = 0;
hunterMunitions = 0;
impactslash = 0;
vigilante = 0;
comboCrit = 0;
comboStatus = 0;
conditionOverload = 0;
groupTargets = null;
headShotBonus = 1;
headShotMult = 1;
stanceCombo = null;
avgHit = 1;
avgDelay = 1;
shatteringImpact = 0;
explosiveSlashProcRate = 0;
explosiveFireProcRate = 0;
explosiveToxinProcRate = 0;
explosiveGasProcRate = 0;
explosiveElectricProcRate = 0;
explosiveImpactProcRate = 0;
explosivePunctureProcRate = 0;
explosiveIceProcRate = 0;
explosiveCorrosiveProcRate = 0;
explosiveViralProcRate = 0;
explosiveBlastProcRate = 0;
explosiveRadiationProcRate = 0;
explosiveMagneticProcRate = 0;
forcedSlashProcs = 0;
forcedImpactProcs = 0;
forcedPunctureProcs = 0;
forcedKnockdownProcs = 0;
COMult = 0;
finalComboCrit = 0.0;
averageStatusChance = 0;
viralMult = 1;
forcedProc = "";
forcedProcEX = "";
}
/**
* Gets the base values from the selected weapon
*/
protected static void getBaseValues() {
// Base Values
weaponName = selectedWeapon.getName();
weaponMode = selectedWeapon.getWeaponMode();
damageType = selectedWeapon.getDamageType();
chargeTime = selectedWeapon.getChargeTime();
fireRate = selectedWeapon.getFireRate();
reloadTime = selectedWeapon.getReloadTime();
critChance = selectedWeapon.getCritChance();
critMult = selectedWeapon.getCritMultiplier();
projectileCount = selectedWeapon.getProjectiles();
firstShotDamageMult = 1;
lastShotDamageMult = 1;
statusChance = selectedWeapon.getStatusChance();
mag = selectedWeapon.getMagSize();
if (selectedWeapon.weaponType.equals(Constants.MELEE)) {
stanceCombo = selectedWeapon.getStanceCombo();
combo = 5;
} else {
combo = selectedWeapon.getCombo();
}
startingCombo = selectedWeapon.getStartingCombo();
burstCount = selectedWeapon.getBurstCount();
drain = selectedWeapon.getDrain();
impact.base = selectedWeapon.getImpactDamage();
puncture.base = selectedWeapon.getPunctureDamage();
slash.base = selectedWeapon.getSlashDamage();
explosiveImpact.base = selectedWeapon.getExplosiveImpactDamage();
explosivePuncture.base = selectedWeapon.getExplosivePunctureDamage();
explosiveSlash.base = selectedWeapon.getExplosiveSlashDamage();
damage2Type = selectedWeapon.getDamage2Type();
explosiveDamage1Type = selectedWeapon.getExplosiveDamage1Type();
explosiveDamage2Type = selectedWeapon.getExplosiveDamage2Type();
forcedProc = selectedWeapon.getForcedProcType();
forcedProcEX = selectedWeapon.getForcedProcEXType();
switch (damageType) {
case Constants.FIRE_WEAPON_DAMAGE:
fire.base = selectedWeapon.getBaseDamage();
break;
case Constants.ICE_WEAPON_DAMAGE:
ice.base = selectedWeapon.getBaseDamage();
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
electric.base = selectedWeapon.getBaseDamage();
break;
case Constants.TOXIN_WEAPON_DAMAGE:
toxin.base = selectedWeapon.getBaseDamage();
break;
case Constants.BLAST_WEAPON_DAMAGE:
blast.base = selectedWeapon.getBaseDamage();
break;
case Constants.MAGNETIC_WEAPON_DAMAGE:
magnetic.base = selectedWeapon.getBaseDamage();
break;
case Constants.GAS_WEAPON_DAMAGE:
gas.base = selectedWeapon.getBaseDamage();
break;
case Constants.RADIATION_WEAPON_DAMAGE:
radiation.base = selectedWeapon.getBaseDamage();
break;
case Constants.CORROSIVE_WEAPON_DAMAGE:
corrosive.base = selectedWeapon.getBaseDamage();
break;
case Constants.VIRAL_WEAPON_DAMAGE:
viral.base = selectedWeapon.getBaseDamage();
break;
}
switch (damage2Type) {
case Constants.FIRE_WEAPON_DAMAGE:
fire.base = selectedWeapon.getBaseDamage2();
break;
case Constants.ICE_WEAPON_DAMAGE:
ice.base = selectedWeapon.getBaseDamage2();
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
electric.base = selectedWeapon.getBaseDamage2();
break;
case Constants.TOXIN_WEAPON_DAMAGE:
toxin.base = selectedWeapon.getBaseDamage2();
break;
case Constants.BLAST_WEAPON_DAMAGE:
blast.base = selectedWeapon.getBaseDamage2();
break;
case Constants.MAGNETIC_WEAPON_DAMAGE:
magnetic.base = selectedWeapon.getBaseDamage2();
break;
case Constants.GAS_WEAPON_DAMAGE:
gas.base = selectedWeapon.getBaseDamage2();
break;
case Constants.RADIATION_WEAPON_DAMAGE:
radiation.base = selectedWeapon.getBaseDamage2();
break;
case Constants.CORROSIVE_WEAPON_DAMAGE:
corrosive.base = selectedWeapon.getBaseDamage2();
break;
case Constants.VIRAL_WEAPON_DAMAGE:
viral.base = selectedWeapon.getBaseDamage2();
break;
}
switch (explosiveDamage1Type) {
case Constants.FIRE_WEAPON_DAMAGE:
explosiveFire.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.ICE_WEAPON_DAMAGE:
explosiveIce.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
explosiveElectric.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.TOXIN_WEAPON_DAMAGE:
explosiveToxin.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.BLAST_WEAPON_DAMAGE:
explosiveBlast.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.MAGNETIC_WEAPON_DAMAGE:
explosiveMagnetic.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.GAS_WEAPON_DAMAGE:
explosiveGas.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.RADIATION_WEAPON_DAMAGE:
explosiveRadiation.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.CORROSIVE_WEAPON_DAMAGE:
explosiveCorrosive.base = selectedWeapon.getExplosiveBaseDamage();
break;
case Constants.VIRAL_WEAPON_DAMAGE:
explosiveViral.base = selectedWeapon.getExplosiveBaseDamage();
break;
}
switch (explosiveDamage2Type) {
case Constants.FIRE_WEAPON_DAMAGE:
explosiveFire.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.ICE_WEAPON_DAMAGE:
explosiveIce.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
explosiveElectric.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.TOXIN_WEAPON_DAMAGE:
explosiveToxin.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.BLAST_WEAPON_DAMAGE:
explosiveBlast.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.MAGNETIC_WEAPON_DAMAGE:
explosiveMagnetic.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.GAS_WEAPON_DAMAGE:
explosiveGas.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.RADIATION_WEAPON_DAMAGE:
explosiveRadiation.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.CORROSIVE_WEAPON_DAMAGE:
explosiveCorrosive.base = selectedWeapon.getExplosiveBaseDamage2();
break;
case Constants.VIRAL_WEAPON_DAMAGE:
explosiveViral.base = selectedWeapon.getExplosiveBaseDamage2();
break;
}
raw.base = impact.base + puncture.base + slash.base + fire.base + ice.base + electric.base + toxin.base + blast.base + magnetic.base + gas.base + radiation.base + corrosive.base + viral.base;
explosiveRaw.base = explosiveImpact.base + explosivePuncture.base + explosiveSlash.base + explosiveFire.base + explosiveIce.base + explosiveElectric.base + explosiveToxin.base + explosiveBlast.base + explosiveMagnetic.base + explosiveGas.base + explosiveRadiation.base + explosiveCorrosive.base + explosiveViral.base;
// Factor for multiple projectiles per shot
if (projectileCount > 1.0) {
raw.base /= projectileCount;
impact.base /= projectileCount;
puncture.base /= projectileCount;
slash.base /= projectileCount;
fire.base /= projectileCount;
ice.base /= projectileCount;
electric.base /= projectileCount;
toxin.base /= projectileCount;
blast.base /= projectileCount;
magnetic.base /= projectileCount;
gas.base /= projectileCount;
radiation.base /= projectileCount;
corrosive.base /= projectileCount;
viral.base /= projectileCount;
explosiveRaw.base /= projectileCount;
explosiveImpact.base /= projectileCount;
explosivePuncture.base /= projectileCount;
explosiveSlash.base /= projectileCount;
explosiveFire.base /= projectileCount;
explosiveIce.base /= projectileCount;
explosiveElectric.base /= projectileCount;
explosiveToxin.base /= projectileCount;
explosiveBlast.base /= projectileCount;
explosiveMagnetic.base /= projectileCount;
explosiveGas.base /= projectileCount;
explosiveRadiation.base /= projectileCount;
explosiveCorrosive.base /= projectileCount;
explosiveViral.base /= projectileCount;
}
// Mod Vectors
if (maxxing) {
activeMods = theMaximizer.simulatedMods;
modRanks = theMaximizer.simulatedRanks;
} else {
activeMods = selectedWeapon.getActiveMods();
modRanks = selectedWeapon.getActiveModRanks();
}
}
/**
* Calculates the final modded values
*/
protected static void calculateFinals() {
// Initialize mod vectors
Vector<Double> magMods = new Vector<Double>();
Vector<Double> critChanceMods = new Vector<Double>();
Vector<Double> addCritChanceMods = new Vector<Double>();
Vector<Double> critMultMods = new Vector<Double>();
Vector<Double> fireRateMods = new Vector<Double>();
Vector<Double> multiplicativeFireRateMods = new Vector<Double>();
Vector<Double> reloadTimeMods = new Vector<Double>();
Vector<Double> damageMultMods = new Vector<Double>();
Vector<Double> impactDamageMods = new Vector<Double>();
Vector<Double> punctureDamageMods = new Vector<Double>();
Vector<Double> slashDamageMods = new Vector<Double>();
Vector<Double> fireDamageMods = new Vector<Double>();
Vector<Double> iceDamageMods = new Vector<Double>();
Vector<Double> electricDamageMods = new Vector<Double>();
Vector<Double> toxinDamageMods = new Vector<Double>();
Vector<Double> blastDamageMods = new Vector<Double>();
Vector<Double> magneticDamageMods = new Vector<Double>();
Vector<Double> gasDamageMods = new Vector<Double>();
Vector<Double> radiationDamageMods = new Vector<Double>();
Vector<Double> corrosiveDamageMods = new Vector<Double>();
Vector<Double> viralDamageMods = new Vector<Double>();
Vector<Double> explosiveFireDamageMods = new Vector<Double>();
Vector<Double> explosiveIceDamageMods = new Vector<Double>();
Vector<Double> explosiveElectricDamageMods = new Vector<Double>();
Vector<Double> explosiveToxinDamageMods = new Vector<Double>();
Vector<Double> explosiveBlastDamageMods = new Vector<Double>();
Vector<Double> explosiveMagneticDamageMods = new Vector<Double>();
Vector<Double> explosiveGasDamageMods = new Vector<Double>();
Vector<Double> explosiveRadiationDamageMods = new Vector<Double>();
Vector<Double> explosiveCorrosiveDamageMods = new Vector<Double>();
Vector<Double> explosiveViralDamageMods = new Vector<Double>();
Vector<Double> projectileCountMods = new Vector<Double>();
Vector<Double> firstShotDamageMods = new Vector<Double>();
Vector<Double> lastShotDamageMods = new Vector<Double>();
Vector<Double> statusChanceMods = new Vector<Double>();
Vector<Double> statusDurationMods = new Vector<Double>();
Vector<Double> corpusMods = new Vector<Double>();
Vector<Double> grineerMods = new Vector<Double>();
Vector<Double> infestedMods = new Vector<Double>();
Vector<Double> corruptedMods = new Vector<Double>();
Vector<Double> flatDamageMods = new Vector<Double>();
Vector<Double> deadAimMods = new Vector<Double>();
Vector<Double> flatStatusMods = new Vector<Double>();
Vector<Double> flatMagMods = new Vector<Double>();
Vector<String> elements = new Vector<String>(); // Ordered element vector
Vector<String> elements2 = new Vector<String>(); // Ordered element vector for the explosion
// Populate mod vectors
for (int i = 0; i < activeMods.size(); i++) {
Mod tempMod = activeMods.get(i);
if (tempMod != null) {
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_MAG_CAP)) {
magMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_MAG_CAP))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_CRIT_CHANCE)) {
critChanceMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_CRIT_CHANCE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_CRIT_MULTIPLIER)) {
critMultMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_CRIT_MULTIPLIER))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FIRE_RATE)) {
fireRateMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FIRE_RATE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_MULTI_RATE)) {
multiplicativeFireRateMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_MULTI_RATE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_RELOAD_SPEED)) {
reloadTimeMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_RELOAD_SPEED))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_DAMAGE_BONUS)) {
damageMultMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_DAMAGE_BONUS))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_MULTISHOT)) {
projectileCountMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_MULTISHOT))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FIRST_SHOT_DAMAGE)) {
firstShotDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FIRST_SHOT_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_LAST_SHOT_DAMAGE)) {
lastShotDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_LAST_SHOT_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_STATUS_CHANCE)) {
statusChanceMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_STATUS_CHANCE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_STATUS_DURATION)) {
statusDurationMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_STATUS_DURATION))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_CORPUS_DAMAGE)) {
corpusMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_CORPUS_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_GRINEER_DAMAGE)) {
grineerMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_GRINEER_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_CORRUPTED_DAMAGE)) {
corruptedMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_CORRUPTED_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_INFESTED_DAMAGE)) {
infestedMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_INFESTED_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FLAT_DAMAGE)) {
flatDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FLAT_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FLAT_STATUS)) {
flatStatusMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FLAT_STATUS))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FLAT_MAG)) {
flatMagMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FLAT_MAG))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_DEAD_AIM)) {
deadAimMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_DEAD_AIM))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_MUNITIONS)) {
hunterMunitions = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_MUNITIONS)) * (1.0 + modRanks.get(i));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_IMPACTSLASH)) {
impactslash = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_IMPACTSLASH)) * (1.0 + modRanks.get(i));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_IMPACT_DAMAGE)) {
impactDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_IMPACT_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_PUNCTURE_DAMAGE)) {
punctureDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_PUNCTURE_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_SLASH_DAMAGE)) {
slashDamageMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_SLASH_DAMAGE))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_LIGHTNING_DAMAGE)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_LIGHTNING_DAMAGE)) * (1.0 + modRanks.get(i));
globalElectric += modPower;
if (!elements.contains("Electric"))
elements.add("Electric");
if (!elements2.contains("Electric"))
elements2.add("Electric");
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_FIRE_DAMAGE)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_FIRE_DAMAGE)) * (1.0 + modRanks.get(i));
globalFire += modPower;
if (!elements.contains("Fire"))
elements.add("Fire");
if (!elements2.contains("Fire"))
elements2.add("Fire");
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_TOXIN_DAMAGE)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_TOXIN_DAMAGE)) * (1.0 + modRanks.get(i));
globalToxin += modPower;
if (!elements.contains("Toxin"))
elements.add("Toxin");
if (!elements2.contains("Toxin"))
elements2.add("Toxin");
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_ICE_DAMAGE)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_ICE_DAMAGE)) * (1.0 + modRanks.get(i));
globalIce += modPower;
if (!elements.contains("Ice"))
elements.add("Ice");
if (!elements2.contains("Ice"))
elements2.add("Ice");
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_VIGILANTE)) {
vigilante += 1;
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_COMBO_CRIT)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_COMBO_CRIT)) * (1.0 + modRanks.get(i));
comboCrit += modPower;
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_COMBO_STATUS)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_COMBO_STATUS)) * (1.0 + modRanks.get(i));
comboStatus += modPower;
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_CONDITION_OVERLOAD)) {
double modPower = tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_CONDITION_OVERLOAD)) * (1.0 + modRanks.get(i));
conditionOverload += modPower;
}
if (tempMod.effectTypes.contains(Constants.HEADSHOT_BONUS)) {
headShotBonus += ((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.HEADSHOT_BONUS))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_ADDITIVE_CC)) {
addCritChanceMods.add((tempMod.effectStrengths.get(tempMod.effectTypes.indexOf(Constants.MOD_TYPE_ADDITIVE_CC))) * (1.0 + modRanks.get(i)));
}
if (tempMod.effectTypes.contains(Constants.MOD_TYPE_SHATTERING_IMPACT)) {
shatteringImpact += (1.0 + modRanks.get(i));
}
}
}
// Mutalist Quanta: get bubble counts
int mQ1 = 0;
int mQ2 = 0;
int mQ3 = 0;
try {
mQ1 = Integer.parseInt(selectedWeapon.mQ1Field.getText());
} catch (Exception e) {
}
try {
mQ2 = Integer.parseInt(selectedWeapon.mQ2Field.getText());
} catch (Exception e) {
}
try {
mQ3 = Integer.parseInt(selectedWeapon.mQ3Field.getText());
} catch (Exception e) {
}
// Mutalist Quanta: If innate heat, the innate element combines before
// M.Quanta's added electric
if (damageType.equals("Fire")) {
if (!elements.contains(damageType) && selectedWeapon.getBaseDamage() > 0)
elements.add(damageType);
}
if (damage2Type.equals("Fire")) {
if (!elements.contains(damage2Type) && selectedWeapon.getBaseDamage2() > 0)
elements.add(damage2Type);
}
if (explosiveDamage1Type.equals("Fire")) {
if (!elements2.contains(explosiveDamage1Type) && selectedWeapon.getExplosiveBaseDamage() > 0)
elements2.add(explosiveDamage1Type);
}
if (explosiveDamage2Type.equals("Fire")) {
if (!elements2.contains(explosiveDamage2Type) && selectedWeapon.getExplosiveBaseDamage2() > 0)
elements2.add(explosiveDamage2Type);
}
// Mutalist Quanta: If NOT hitscan, add element to be combined
if ((mQ1 > 0 || mQ2 > 0 || mQ3 > 0) && !selectedWeapon.mQCombineElement.isSelected()) {
globalElectric += mQ1;
globalElectric += mQ2 * 3.65;
globalElectric += mQ3 * 5;
if (!elements.contains("Electric")) {
elements.add("Electric");
}
if (!elements2.contains("Electric")) {
elements2.add("Electric");
}
}
if (!damageType.equals("Fire")) {
if (!elements.contains(damageType) && selectedWeapon.getBaseDamage() > 0)
if (damageType.equals("Ice") || damageType.equals("Toxin") || damageType.equals("Electric")) {
elements.add(damageType);
}
}
if (!damage2Type.equals("Fire")) {
if (!elements.contains(damage2Type) && selectedWeapon.getBaseDamage2() > 0)
if (damage2Type.equals("Ice") || damage2Type.equals("Toxin") || damage2Type.equals("Electric")) {
elements.add(damage2Type);
}
}
if (!explosiveDamage1Type.equals("Fire")) {
if (!elements2.contains(explosiveDamage1Type) && selectedWeapon.getExplosiveBaseDamage() > 0)
if (explosiveDamage1Type.equals("Ice") || explosiveDamage1Type.equals("Toxin") || explosiveDamage1Type.equals("Electric")) {
elements2.add(explosiveDamage1Type);
}
}
if (!explosiveDamage2Type.equals("Fire")) {
if (!elements2.contains(explosiveDamage2Type) && selectedWeapon.getExplosiveBaseDamage2() > 0)
if (explosiveDamage2Type.equals("Ice") || explosiveDamage2Type.equals("Toxin") || explosiveDamage2Type.equals("Electric")) {
elements2.add(explosiveDamage2Type);
}
}
// Combine elements
for (int i = 0; i < elements.size() - 1; i++) {
String element1 = elements.get(i);
String element2 = elements.get(i + 1);
if ((element1.equals("Fire") || element1.equals("Ice") || element1.equals("Toxin") || element1.equals("Electric")) && (element2.equals("Fire") || element2.equals("Ice") || element2.equals("Toxin") || element2.equals("Electric"))) {
if ((element1.equals("Fire") && element2.equals("Ice")) || (element1.equals("Ice") && element2.equals("Fire"))) {
elements.add("Blast");
blastDamageMods.add(globalFire + globalIce);
if (damageType.equals("Fire") || damageType.equals("Ice") || damage2Type.equals("Fire") || damage2Type.equals("Ice")) {
blastDamageMods.add(fire.base / raw.base);
blastDamageMods.add(ice.base / raw.base);
fire.base = 0.0;
ice.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Electric"))) {
elements.add("Corrosive");
corrosiveDamageMods.add(globalElectric + globalToxin);
if (damageType.equals("Electric") || damageType.equals("Toxin") || damage2Type.equals("Electric") || damage2Type.equals("Toxin")) {
corrosiveDamageMods.add(electric.base / raw.base);
corrosiveDamageMods.add(toxin.base / raw.base);
electric.base = 0.0;
toxin.base = 0.0;
}
} else if ((element1.equals("Fire") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Fire"))) {
elements.add("Gas");
gasDamageMods.add(globalFire + globalToxin);
if (damageType.equals("Fire") || damageType.equals("Toxin") || damage2Type.equals("Fire") || damage2Type.equals("Toxin")) {
gasDamageMods.add(fire.base / raw.base);
gasDamageMods.add(toxin.base / raw.base);
fire.base = 0.0;
toxin.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Ice")) || (element1.equals("Ice") && element2.equals("Electric"))) {
elements.add("Magnetic");
magneticDamageMods.add(globalElectric + globalIce);
if (damageType.equals("Electric") || damageType.equals("Ice") || damage2Type.equals("Electric") || damage2Type.equals("Ice")) {
magneticDamageMods.add(electric.base / raw.base);
magneticDamageMods.add(ice.base / raw.base);
electric.base = 0.0;
ice.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Fire")) || (element1.equals("Fire") && element2.equals("Electric"))) {
elements.add("Radiation");
radiationDamageMods.add(globalFire + globalElectric);
if (damageType.equals("Fire") || damageType.equals("Electric") || damage2Type.equals("Fire") || damage2Type.equals("Electric")) {
radiationDamageMods.add(fire.base / raw.base);
radiationDamageMods.add(electric.base / raw.base);
fire.base = 0.0;
electric.base = 0.0;
}
} else if ((element1.equals("Ice") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Ice"))) {
elements.add("Viral");
viralDamageMods.add(globalToxin + globalIce);
if (damageType.equals("Toxin") || damageType.equals("Ice") || damage2Type.equals("Toxin") || damage2Type.equals("Ice")) {
viralDamageMods.add(toxin.base / raw.base);
viralDamageMods.add(ice.base / raw.base);
toxin.base = 0.0;
ice.base = 0.0;
}
}
elements.remove(i);
elements.remove(i);
i -= 1;
}
}
// Mutalist Quanta: If hitscan, add electric damage
if ((mQ1 > 0 || mQ2 > 0 || mQ3 > 0) && selectedWeapon.mQCombineElement.isSelected()) {
globalElectric += mQ1;
globalElectric += mQ2 * 3.65;
globalElectric += mQ3 * 5;
if (!elements.contains("Electric")) {
elements.add("Electric");
}
if (!elements2.contains("Electric")) {
elements2.add("Electric");
}
}
// Uncombined elements
if (elements.contains("Fire")) {
fireDamageMods.add(globalFire);
}
if (elements.contains("Electric")) {
electricDamageMods.add(globalElectric);
}
if (elements.contains("Toxin")) {
toxinDamageMods.add(globalToxin);
}
if (elements.contains("Ice")) {
iceDamageMods.add(globalIce);
}
// Mutalist Quanta note: Only projectile weapons cause explosions, so we know it
// will combine (already added correctly from previous step).
// Combine elements for the explosion
for (int i = 0; i < elements2.size() - 1; i++) {
String element1 = elements2.get(i);
String element2 = elements2.get(i + 1);
if ((element1.equals("Fire") || element1.equals("Ice") || element1.equals("Toxin") || element1.equals("Electric")) && (element2.equals("Fire") || element2.equals("Ice") || element2.equals("Toxin") || element2.equals("Electric"))) {
if ((element1.equals("Fire") && element2.equals("Ice")) || (element1.equals("Ice") && element2.equals("Fire"))) {
elements2.add("Blast");
explosiveBlastDamageMods.add(globalFire + globalIce);
if (explosiveDamage1Type.equals("Fire") || explosiveDamage1Type.equals("Ice") || explosiveDamage2Type.equals("Fire") || explosiveDamage2Type.equals("Ice")) {
explosiveBlastDamageMods.add(explosiveFire.base / explosiveRaw.base);
explosiveBlastDamageMods.add(explosiveIce.base / explosiveRaw.base);
explosiveFire.base = 0.0;
explosiveIce.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Electric"))) {
elements2.add("Corrosive");
explosiveCorrosiveDamageMods.add(globalElectric + globalToxin);
if (explosiveDamage1Type.equals("Electric") || explosiveDamage1Type.equals("Toxin") || explosiveDamage2Type.equals("Electric") || explosiveDamage2Type.equals("Toxin")) {
explosiveCorrosiveDamageMods.add(explosiveElectric.base / explosiveRaw.base);
explosiveCorrosiveDamageMods.add(explosiveToxin.base / explosiveRaw.base);
explosiveElectric.base = 0.0;
explosiveToxin.base = 0.0;
}
} else if ((element1.equals("Fire") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Fire"))) {
elements2.add("Gas");
explosiveGasDamageMods.add(globalFire + globalToxin);
if (explosiveDamage1Type.equals("Fire") || explosiveDamage1Type.equals("Toxin") || explosiveDamage2Type.equals("Fire") || explosiveDamage2Type.equals("Toxin")) {
explosiveGasDamageMods.add(explosiveFire.base / explosiveRaw.base);
explosiveGasDamageMods.add(explosiveToxin.base / explosiveRaw.base);
explosiveFire.base = 0.0;
explosiveToxin.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Ice")) || (element1.equals("Ice") && element2.equals("Electric"))) {
elements2.add("Magnetic");
explosiveMagneticDamageMods.add(globalElectric + globalIce);
if (explosiveDamage1Type.equals("Electric") || explosiveDamage1Type.equals("Ice") || explosiveDamage2Type.equals("Electric") || explosiveDamage2Type.equals("Ice")) {
explosiveMagneticDamageMods.add(explosiveElectric.base / explosiveRaw.base);
explosiveMagneticDamageMods.add(explosiveIce.base / explosiveRaw.base);
explosiveElectric.base = 0.0;
explosiveIce.base = 0.0;
}
} else if ((element1.equals("Electric") && element2.equals("Fire")) || (element1.equals("Fire") && element2.equals("Electric"))) {
elements2.add("Radiation");
explosiveRadiationDamageMods.add(globalFire + globalElectric);
if (explosiveDamage1Type.equals("Fire") || explosiveDamage1Type.equals("Electric") || explosiveDamage2Type.equals("Fire") || explosiveDamage2Type.equals("Electric")) {
explosiveRadiationDamageMods.add(explosiveElectric.base / explosiveRaw.base);
explosiveRadiationDamageMods.add(explosiveFire.base / explosiveRaw.base);
explosiveFire.base = 0.0;
explosiveElectric.base = 0.0;
}
} else if ((element1.equals("Ice") && element2.equals("Toxin")) || (element1.equals("Toxin") && element2.equals("Ice"))) {
elements2.add("Viral");
explosiveViralDamageMods.add(globalToxin + globalIce);
if (explosiveDamage1Type.equals("Toxin") || explosiveDamage1Type.equals("Ice") || explosiveDamage2Type.equals("Toxin") || explosiveDamage2Type.equals("Ice")) {
explosiveViralDamageMods.add(explosiveToxin.base / explosiveRaw.base);
explosiveViralDamageMods.add(explosiveIce.base / explosiveRaw.base);
explosiveToxin.base = 0.0;
explosiveIce.base = 0.0;
}
}
elements2.remove(i);
elements2.remove(i);
i -= 1;
}
}
// Uncombined elements2 for the explosion
if (elements2.contains("Fire")) {
explosiveFireDamageMods.add(globalFire);
}
if (elements2.contains("Electric")) {
explosiveElectricDamageMods.add(globalElectric);
}
if (elements2.contains("Toxin")) {
explosiveToxinDamageMods.add(globalToxin);
}
if (elements2.contains("Ice")) {
explosiveIceDamageMods.add(globalIce);
}
// Scope effects
if (weaponMode.equals(Constants.LANKA) || weaponMode.equals(Constants.SNIPER)) {
if (selectedWeapon.getScopeEffect() == Constants.ADDITIVE_CRIT_CHANCE) {
addCritChanceMods.add(selectedWeapon.getScopeStrength());
}
if (selectedWeapon.getScopeEffect() == Constants.ADDITIVE_CRIT_DAMAGE) {
critMultMods.add(selectedWeapon.getScopeStrength());
}
if (selectedWeapon.getScopeEffect() == Constants.HEADSHOT_BONUS) {
headShotBonus += selectedWeapon.getScopeStrength();
}
}
headShotBonus += selectedWeapon.getAddHS();
// Mutalist Quanta: crit stuff
if (mQ1 > 0 || mQ2 > 0 || mQ3 > 0) {
addCritChanceMods.add(0.25 * (mQ1 + mQ2 + mQ3));
}
// Calculate finals
double tempMag = mag;
for (int i = 0; i < magMods.size(); i++) {
tempMag += mag * magMods.get(i);
}
finalMag = (int) Math.round(tempMag);
for (int i = 0; i < flatMagMods.size(); i++) {
finalMag += flatMagMods.get(i);
}
finalMag = Math.max(1, finalMag);
finalCritChance = critChance;
for (int i = 0; i < critChanceMods.size(); i++) {
finalCritChance += critChance * critChanceMods.get(i);
}
for (int i = 0; i < addCritChanceMods.size(); i++) {
finalCritChance += addCritChanceMods.get(i);
}
finalCritChance += selectedWeapon.getAddCC();
finalCritChance = Math.max(0, finalCritChance);
finalCritMult = critMult;
for (int i = 0; i < critMultMods.size(); i++) {
finalCritMult += critMult * critMultMods.get(i);
}
finalCritMult += selectedWeapon.getAddCD();
if (mQ1 > 0 || mQ2 > 0 || mQ3 > 0) { // Mutalist Quanta
finalCritMult *= 1.25;
}
finalCritMult = Math.max(0, finalCritMult);
finalFlatDamageBonus = flatDamageBonus;
for (int i = 0; i < flatDamageMods.size(); i++) {
finalFlatDamageBonus += flatDamageMods.get(i);
}
finalDeadAimMult = deadAimMult;
for (int i = 0; i < deadAimMods.size(); i++) {
finalDeadAimMult += deadAimMult * deadAimMods.get(i);
}
finalDamageMult = damageMult;
for (int i = 0; i < damageMultMods.size(); i++) {
finalDamageMult += damageMult * damageMultMods.get(i);
}
finalDamageMult += damageMult * selectedWeapon.getAddDam();
finalDamageMult = Math.max(0, finalDamageMult);
// Mutalist Quanta: damage stuff
if (mQ1 > 0 || mQ2 > 0 || mQ3 > 0) {
finalDamageMult *= Math.pow(0.66, mQ1 + mQ2 + mQ3);
}
startingCombo = Math.max(1, startingCombo);
finalFireRate = fireRate;
fireRateModPower = 0;
for (int i = 0; i < fireRateMods.size(); i++) {
fireRateModPower += fireRateMods.get(i);
}
if (weaponMode.equals(Constants.AUTOBOW) || weaponMode.equals(Constants.SEMIBOW) || weaponMode.equals(Constants.CHARGEBOW)) {
fireRateModPower *= 2;
}
if (weaponMode.equals(Constants.CHARGE) || weaponMode.equals(Constants.LANKA) || weaponMode.equals(Constants.CHARGEBOW)) {
double finalChargeTime = chargeTime / (1 + fireRateModPower + selectedWeapon.getAddFR());
if (fireRate > 0) {
finalFireRate = 1 / ((1 / (fireRate * (1 + fireRateModPower))) + finalChargeTime);
} else {
finalFireRate = 1 / finalChargeTime;
}
} else {
finalFireRate += fireRate * fireRateModPower;
finalFireRate += fireRate * selectedWeapon.getAddFR();
}
if (weaponMode.equals(Constants.SEMI_AUTO) || weaponMode.equals(Constants.SNIPER) || weaponMode.equals(Constants.SEMIBOW)) {
if (finalFireRate > 10.0) {
finalFireRate = 10.0;
}
}
for (int i = 0; i < multiplicativeFireRateMods.size(); i++) { // Berserker only at this time
finalFireRate *= (1 + multiplicativeFireRateMods.get(i));
}
finalFireRate = Math.max(0, finalFireRate);
if (finalFireRate < 2.5 || ((weaponMode.equals(Constants.AUTOBOW) || weaponMode.equals(Constants.SEMIBOW) || weaponMode.equals(Constants.CHARGEBOW)) && fireRateModPower < 2.5)) {
impactslash *= 2;
}
finalReloadTime = reloadTime;
double reloadSpeedMult = 1.0;
for (int i = 0; i < reloadTimeMods.size(); i++) {
reloadSpeedMult += reloadTimeMods.get(i);
}
finalReloadTime /= reloadSpeedMult;
finalProjectileCount = projectileCount;
for (int i = 0; i < projectileCountMods.size(); i++) {
finalProjectileCount += projectileCount * projectileCountMods.get(i);
}
finalProjectileCount = Math.max(0, finalProjectileCount);
finalFirstShotDamageMult = firstShotDamageMult;
for (int i = 0; i < firstShotDamageMods.size(); i++) {
finalFirstShotDamageMult += firstShotDamageMult * firstShotDamageMods.get(i);
}
finalLastShotDamageMult = lastShotDamageMult;
for (int i = 0; i < lastShotDamageMods.size(); i++) {
finalLastShotDamageMult += lastShotDamageMult * lastShotDamageMods.get(i);
}
finalStatusChance = statusChance;
for (int i = 0; i < statusChanceMods.size(); i++) {
finalStatusChance += statusChance * statusChanceMods.get(i);
}
for (int i = 0; i < flatStatusMods.size(); i++) {
double localStatus = flatStatusMods.get(i);
finalStatusChance += localStatus;
}
finalStatusChance += selectedWeapon.getAddSC();
averageStatusChance = finalStatusChance;
finalStatusDuration = statusDuration;
for (int i = 0; i < statusDurationMods.size(); i++) {
finalStatusDuration += statusDuration * statusDurationMods.get(i);
}
finalStatusDuration = Math.max(0, finalStatusDuration);
impact.finalBase = impact.base;
explosiveImpact.finalBase = explosiveImpact.base;
for (int i = 0; i < impactDamageMods.size(); i++) {
impact.finalBase += impact.base * impactDamageMods.get(i);
explosiveImpact.finalBase += explosiveImpact.base * impactDamageMods.get(i);
}
impact.finalBase = Math.max(0, impact.finalBase);
explosiveImpact.finalBase = Math.max(0, explosiveImpact.finalBase);
puncture.finalBase = puncture.base;
explosivePuncture.finalBase = explosivePuncture.base;
for (int i = 0; i < punctureDamageMods.size(); i++) {
puncture.finalBase += puncture.base * punctureDamageMods.get(i);
explosivePuncture.finalBase += explosivePuncture.base * punctureDamageMods.get(i);
}
puncture.finalBase = Math.max(0, puncture.finalBase);
explosivePuncture.finalBase = Math.max(0, explosivePuncture.finalBase);
slash.finalBase = slash.base;
explosiveSlash.finalBase = explosiveSlash.base;
for (int i = 0; i < slashDamageMods.size(); i++) {
slash.finalBase += slash.base * slashDamageMods.get(i);
explosiveSlash.finalBase += explosiveSlash.base * slashDamageMods.get(i);
}
slash.finalBase = Math.max(0, slash.finalBase);
explosiveSlash.finalBase = Math.max(0, explosiveSlash.finalBase);
fire.finalBase = fire.base;
for (int i = 0; i < fireDamageMods.size(); i++) {
fire.finalBase += raw.base * fireDamageMods.get(i);
}
explosiveFire.finalBase = explosiveFire.base;
for (int i = 0; i < explosiveFireDamageMods.size(); i++) {
explosiveFire.finalBase += explosiveRaw.base * explosiveFireDamageMods.get(i);
}
ice.finalBase = ice.base;
for (int i = 0; i < iceDamageMods.size(); i++) {
ice.finalBase += raw.base * iceDamageMods.get(i);
}
explosiveIce.finalBase = explosiveIce.base;
for (int i = 0; i < explosiveIceDamageMods.size(); i++) {
explosiveIce.finalBase += explosiveRaw.base * explosiveIceDamageMods.get(i);
}
electric.finalBase = electric.base;
for (int i = 0; i < electricDamageMods.size(); i++) {
electric.finalBase += raw.base * electricDamageMods.get(i);
}
explosiveElectric.finalBase = explosiveElectric.base;
for (int i = 0; i < explosiveElectricDamageMods.size(); i++) {
explosiveElectric.finalBase += explosiveRaw.base * explosiveElectricDamageMods.get(i);
}
toxin.finalBase = toxin.base;
for (int i = 0; i < toxinDamageMods.size(); i++) {
toxin.finalBase += raw.base * toxinDamageMods.get(i);
}
explosiveToxin.finalBase = explosiveToxin.base;
for (int i = 0; i < explosiveToxinDamageMods.size(); i++) {
explosiveToxin.finalBase += explosiveRaw.base * explosiveToxinDamageMods.get(i);
}
blast.finalBase = blast.base;
for (int i = 0; i < blastDamageMods.size(); i++) {
blast.finalBase += raw.base * blastDamageMods.get(i);
}
explosiveBlast.finalBase = explosiveBlast.base;
for (int i = 0; i < explosiveBlastDamageMods.size(); i++) {
explosiveBlast.finalBase += explosiveRaw.base * explosiveBlastDamageMods.get(i);
}
magnetic.finalBase = magnetic.base;
for (int i = 0; i < magneticDamageMods.size(); i++) {
magnetic.finalBase += raw.base * magneticDamageMods.get(i);
}
explosiveMagnetic.finalBase = explosiveMagnetic.base;
for (int i = 0; i < explosiveMagneticDamageMods.size(); i++) {
explosiveMagnetic.finalBase += explosiveRaw.base * explosiveMagneticDamageMods.get(i);
}
gas.finalBase = gas.base;
for (int i = 0; i < gasDamageMods.size(); i++) {
gas.finalBase += raw.base * gasDamageMods.get(i);
}
explosiveGas.finalBase = explosiveGas.base;
for (int i = 0; i < explosiveGasDamageMods.size(); i++) {
explosiveGas.finalBase += explosiveRaw.base * explosiveGasDamageMods.get(i);
}
radiation.finalBase = radiation.base;
for (int i = 0; i < radiationDamageMods.size(); i++) {
radiation.finalBase += raw.base * radiationDamageMods.get(i);
}
explosiveRadiation.finalBase = explosiveRadiation.base;
for (int i = 0; i < explosiveRadiationDamageMods.size(); i++) {
explosiveRadiation.finalBase += explosiveRaw.base * explosiveRadiationDamageMods.get(i);
}
corrosive.finalBase = corrosive.base;
for (int i = 0; i < corrosiveDamageMods.size(); i++) {
corrosive.finalBase += raw.base * corrosiveDamageMods.get(i);
}
explosiveCorrosive.finalBase = explosiveCorrosive.base;
for (int i = 0; i < explosiveCorrosiveDamageMods.size(); i++) {
explosiveCorrosive.finalBase += explosiveRaw.base * explosiveCorrosiveDamageMods.get(i);
}
viral.finalBase = viral.base;
for (int i = 0; i < viralDamageMods.size(); i++) {
viral.finalBase += raw.base * viralDamageMods.get(i);
}
explosiveViral.finalBase = explosiveViral.base;
for (int i = 0; i < explosiveViralDamageMods.size(); i++) {
explosiveViral.finalBase += explosiveRaw.base * explosiveViralDamageMods.get(i);
}
raw.finalBase = impact.finalBase + puncture.finalBase + slash.finalBase + fire.finalBase + ice.finalBase + electric.finalBase + toxin.finalBase + blast.finalBase + magnetic.finalBase + gas.finalBase + radiation.finalBase + corrosive.finalBase + viral.finalBase;
explosiveRaw.finalBase = explosiveImpact.finalBase + explosivePuncture.finalBase + explosiveSlash.finalBase + explosiveFire.finalBase + explosiveIce.finalBase + explosiveElectric.finalBase + explosiveToxin.finalBase + explosiveBlast.finalBase + explosiveMagnetic.finalBase + explosiveGas.finalBase + explosiveRadiation.finalBase + explosiveCorrosive.finalBase + explosiveViral.finalBase;
finalCorpusMult = 1.0;
for (int i = 0; i < corpusMods.size(); i++) {
finalCorpusMult += corpusMods.get(i);
}
finalGrineerMult = 1.0;
for (int i = 0; i < grineerMods.size(); i++) {
finalGrineerMult += grineerMods.get(i);
}
finalCorruptedMult = 1.0;
for (int i = 0; i < corruptedMods.size(); i++) {
finalCorruptedMult += corruptedMods.get(i);
}
finalInfestedMult = 1.0;
for (int i = 0; i < infestedMods.size(); i++) {
finalInfestedMult += infestedMods.get(i);
}
if (headShots.isSelected()) {
headShot = true;
} else {
headShot = false;
}
if (selectedWeapon.weaponType.equals(Constants.MELEE) && stanceCombo != null) { // Bunch of melee junk
finalMag = stanceCombo.hits.size();
finalProjectileCount = 1;
double tempCombo = startingCombo;
if (startingCombo < 2) {
tempCombo = 0;
} else {
tempCombo-=1;
}
startingCombo = 1; // Melee no long multiplies damage by combo
averageStatusChance += (tempCombo * comboStatus * statusChance);
finalComboCrit = (tempCombo * comboCrit * critChance);
avgHit = 0;
avgDelay = 0;
for (Hit h : stanceCombo.hits) {
avgHit += (h.multiplier / stanceCombo.hits.size());
avgDelay += (h.delay / stanceCombo.hits.size());
}
}
if (weaponMode.equals(Constants.BURST)) {
if (selectedWeapon.isRefireCanceled()) {
finalFireRate += fireRate;
}
double burstDelay = 0.05;
double burstMS = (1 / finalFireRate);
double burstIterationMS = (burstMS * burstCount) + burstDelay;
finalFireRate = (1 / burstIterationMS);
if (finalFireRate > 10.0) {
finalFireRate = 10.0;
}
double numBursts = finalMag / burstCount;
double rawFireTime = numBursts / (finalFireRate / avgDelay);
finalIterationTime = rawFireTime + finalReloadTime;
} else if (weaponMode.equals(Constants.FULL_AUTO_RAMP_UP) || weaponMode.equals(Constants.FULL_AUTO_BULLET_RAMP)) {
double baseFireDelay = ((1 / finalFireRate));
double firstFireDelay = baseFireDelay * 5 / 2;
double secondFireDelay = baseFireDelay * 5 / 3;
double thirdFireDelay = baseFireDelay * 5 / 4;
if (weaponMode.equals(Constants.FULL_AUTO_BULLET_RAMP)) { // Kohm's effective magazine size
finalMag = (int) Math.round(projectileCount + (finalMag - (projectileCount / 3 - 1) - (projectileCount * (projectileCount + 1) / 2) / 3) / (projectileCount / 3));
}
finalIterationTime = (firstFireDelay + secondFireDelay + thirdFireDelay + ((finalMag - 4) * baseFireDelay)) + finalReloadTime;
} else if (weaponMode.equals(Constants.CONTINUOUS)) {
finalMag /= drain;
finalIterationTime = ((finalMag) / finalFireRate) + finalReloadTime;
averageStatusChance *= finalProjectileCount;
} else if (weaponMode.equals(Constants.CHARGE) || weaponMode.equals(Constants.CHARGEBOW) || weaponMode.equals(Constants.LANKA)) {
finalIterationTime = ((finalMag) / finalFireRate) + finalReloadTime;
} else if (selectedWeapon.weaponType.equals(Constants.MELEE)) {
finalIterationTime = ((finalMag) / (finalFireRate / avgDelay));
} else {
finalIterationTime = ((finalMag - 1) / (finalFireRate / avgDelay)) + finalReloadTime;
}
finalIterationsPerMinute = 60.0 / finalIterationTime;
if (headShot) {
headShotMult = 2;
} else {
headShotBonus = 1;
}
vigilante += selectedWeapon.vigiSlider.getValue();
vigilante *= 0.05;
averageCritMult = Math.max(0, 1 - (finalCritChance + finalComboCrit)) + headShotMult * ((finalCritChance + finalComboCrit) * finalCritMult - Math.max(0, (finalCritChance + finalComboCrit) - 1)) + (headShotMult * vigilante * (finalCritMult - 1));
}
/**
* Calculates miscellaneous values
*/
protected static void calculateMiscValues() {
// Status Ratios
double totalprocWeight = raw.finalBase;
slashProcRate = slash.finalBase / raw.finalBase;
fireProcRate = fire.finalBase / raw.finalBase;
toxinProcRate = toxin.finalBase / raw.finalBase;
gasProcRate = gas.finalBase / raw.finalBase;
electricProcRate = electric.finalBase / raw.finalBase;
impactProcRate = impact.finalBase / raw.finalBase;
punctureProcRate = puncture.finalBase / raw.finalBase;
iceProcRate = ice.finalBase / raw.finalBase;
corrosiveProcRate = corrosive.finalBase / raw.finalBase;
viralProcRate = viral.finalBase / raw.finalBase;
blastProcRate = blast.finalBase / raw.finalBase;
radiationProcRate = radiation.finalBase / raw.finalBase;
magneticProcRate = magnetic.finalBase / raw.finalBase;
if (explosiveRaw.finalBase != 0) {
explosiveSlashProcRate = explosiveSlash.finalBase / explosiveRaw.finalBase;
explosiveFireProcRate = explosiveFire.finalBase / explosiveRaw.finalBase;
explosiveToxinProcRate = explosiveToxin.finalBase / explosiveRaw.finalBase;
explosiveGasProcRate = explosiveGas.finalBase / explosiveRaw.finalBase;
explosiveElectricProcRate = explosiveElectric.finalBase / explosiveRaw.finalBase;
explosiveImpactProcRate = explosiveImpact.finalBase / explosiveRaw.finalBase;
explosivePunctureProcRate = explosivePuncture.finalBase / explosiveRaw.finalBase;
explosiveIceProcRate = explosiveIce.finalBase / explosiveRaw.finalBase;
explosiveCorrosiveProcRate = explosiveCorrosive.finalBase / explosiveRaw.finalBase;
explosiveViralProcRate = explosiveViral.finalBase / explosiveRaw.finalBase;
explosiveBlastProcRate = explosiveBlast.finalBase / explosiveRaw.finalBase;
explosiveRadiationProcRate = explosiveRadiation.finalBase / explosiveRaw.finalBase;
explosiveMagneticProcRate = explosiveMagnetic.finalBase / explosiveRaw.finalBase;
}
forcedSlashProcs = 0;
forcedImpactProcs = 0;
forcedPunctureProcs = 0;
forcedKnockdownProcs = 0;
if (selectedWeapon.weaponType.equals(Constants.MELEE) && stanceCombo != null) {
for (Hit h : stanceCombo.hits) {
if (h.procs[0].equals("1")) {
forcedSlashProcs += 1;
}
if (h.procs[8].equals("1")) {
forcedImpactProcs += 1;
}
if (h.procs[9].equals("1")) {
forcedPunctureProcs += 1;
}
if (h.procs[12].equals("1")) {
forcedKnockdownProcs += 1;
}
}
forcedSlashProcs /= stanceCombo.hits.size();
forcedImpactProcs /= stanceCombo.hits.size();
forcedPunctureProcs /= stanceCombo.hits.size();
forcedKnockdownProcs /= stanceCombo.hits.size();
}
// Condition overload
if (conditionOverload > 0) {
double statusLength = 6 * finalStatusDuration;
/* Technically more accurate calculation, but not neccessary
double comboLength = (avgDelay * stanceCombo.hits.size()) / finalFireRate;
COMult += forcedSlashProcs > 0 ? replaceNaN(Math.min(1, statusLength / comboLength)) : 0;
COMult += (forcedSlashProcs > 0 ? 1 - Math.min(1, statusLength / comboLength) : 1) * replaceNaN(1 - Math.pow((1 - slashProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedImpactProcs > 0 ? replaceNaN(Math.min(1, statusLength / comboLength)) : 0;
COMult += (forcedImpactProcs > 0 ? 1 - Math.min(1, statusLength / comboLength) : 1) * replaceNaN(1 - Math.pow((1 - impactProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedPunctureProcs > 0 ? replaceNaN(Math.min(1, statusLength / comboLength)) : 0;
COMult += (forcedPunctureProcs > 0 ? 1 - Math.min(1, statusLength / comboLength) : 1) * replaceNaN(1 - Math.pow((1 - punctureProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedKnockdownProcs > 0 ? replaceNaN(Math.min(1, statusLength / comboLength)) : 0;
COMult += (forcedKnockdownProcs > 0 ? 1 - Math.min(1, statusLength / comboLength) : 1) * replaceNaN(1 - Math.pow((1 - blastProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
*/
// Assuming that forced procs are always active for the sake of CO. It would only be innacruate for builds with very low attack speed.
COMult += forcedSlashProcs > 0 ? 1 : replaceNaN(1 - Math.pow((1 - slashProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedImpactProcs > 0 ? 1 : replaceNaN(1 - Math.pow((1 - impactProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedPunctureProcs > 0 ? 1 : replaceNaN(1 - Math.pow((1 - punctureProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += forcedKnockdownProcs > 0 ? 1 : replaceNaN(1 - Math.pow((1 - blastProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - fireProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - toxinProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - gasProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - electricProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - iceProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - corrosiveProcRate * averageStatusChance), (finalFireRate / avgDelay) * 8 * finalStatusDuration));
COMult += replaceNaN(1 - Math.pow((1 - viralProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - blastProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult += replaceNaN(1 - Math.pow((1 - radiationProcRate * averageStatusChance), (finalFireRate / avgDelay) * 12 * finalStatusDuration));
COMult += replaceNaN(1 - Math.pow((1 - magneticProcRate * averageStatusChance), (finalFireRate / avgDelay) * statusLength));
COMult *= conditionOverload;
}
// adjust COMult for base damage mods
COMult = (COMult + finalDamageMult) / (finalDamageMult);
averageProjectileCount = finalProjectileCount;
if (weaponMode.equals(Constants.FULL_AUTO_BULLET_RAMP)) { // kohm's average projectile count and status chance
averageProjectileCount = finalProjectileCount * ((((projectileCount * (projectileCount + 1) / 2) + projectileCount * (finalMag - projectileCount)) / finalMag) / projectileCount);
averageStatusChance = ((1 - Math.pow((1 - finalStatusChance / 3), 1 / projectileCount)) * 3) * (finalMag - projectileCount) / finalMag;
for (double i = 1; i <= projectileCount; i++) {
double tempstatus = (1 - Math.pow((1 - finalStatusChance / 3), (1 / i))) * 3;
averageStatusChance += tempstatus / finalMag;
}
}
if (weaponMode.equals(Constants.CONTINUOUS)) {
procsPerSecond = (finalMag * averageStatusChance) * (1 / finalIterationTime);
burstProcsPerSecond = averageStatusChance * (finalFireRate / avgDelay);
} else {
procsPerSecond = ((averageProjectileCount * finalMag) * averageStatusChance) * (1 / finalIterationTime);
burstProcsPerSecond = averageProjectileCount * averageStatusChance * (finalFireRate / avgDelay);
}
double potentialProcs = ((averageProjectileCount * finalMag) * (1 / finalIterationTime)) * (6 * finalStatusDuration);
double potentialBurstProcs = (averageProjectileCount * (finalFireRate / avgDelay)) * (6 * finalStatusDuration);
// viral multiplier
if (viralProcRate > 0) {
viralMult = 1;
int procCountTotal = (int) (procsPerSecond * 6 * finalStatusDuration);
double totalChance = binomial(procCountTotal, 0).doubleValue() * Math.pow(viralProcRate, 0) * Math.pow(1 - viralProcRate, procCountTotal - 0);
for (int i = 1; i < Math.min(10, procCountTotal); i++) {
double chance = binomial(procCountTotal, i).doubleValue() * Math.pow(viralProcRate, i) * Math.pow(1 - viralProcRate, procCountTotal - i);
double mult = 1 + (i - 1) * 0.25;
totalChance += chance;
viralMult += chance * mult;
}
if (procCountTotal > 10)
viralMult += (1 - totalChance) * 3.25;
}
// non-stacking fire stacks
if (DPSPanel.fireProcLabel.isSelected()) {
fireStacks = procsPerSecond * fireProcRate * 6;
burstFireStacks = burstProcsPerSecond * fireProcRate * 6;
explosiveFireStacks = procsPerSecond * explosiveFireProcRate * (6 * finalStatusDuration);
explosiveBurstFireStacks = burstProcsPerSecond * explosiveFireProcRate * (6 * finalStatusDuration);
} else if (fireProcRate > 0) {
fireStacks = 1 / Math.pow((1 - fireProcRate * averageStatusChance), potentialProcs);
burstFireStacks = 1 / Math.pow((1 - fireProcRate * averageStatusChance), potentialBurstProcs);
explosiveFireStacks = 1 / Math.pow((1 - explosiveFireProcRate * averageStatusChance), potentialProcs);
explosiveBurstFireStacks = 1 / Math.pow((1 - explosiveFireProcRate * averageStatusChance), potentialBurstProcs);
}
slashStacks = ((slashProcRate * averageStatusChance) + (hunterMunitions * Math.min(1, (finalCritChance + finalComboCrit))) + forcedSlashProcs) * potentialProcs;
slashStacks += (1-slashProcRate)* (1 - (hunterMunitions * Math.min(1, finalCritChance))) * (1 - Math.pow(1 - impactslash, impactProcRate * averageStatusChance)) * potentialProcs; // IB or Hem slash procs
burstSlashStacks = slashStacks * potentialBurstProcs / potentialProcs;
explosiveSlashStacks = ((explosiveSlashProcRate * averageStatusChance) + (hunterMunitions * Math.min(1, (finalCritChance + finalComboCrit))) + forcedSlashProcs) * potentialProcs;
explosiveSlashStacks += (1-explosiveSlashProcRate)* (1 - (hunterMunitions * Math.min(1, finalCritChance))) * (1 - Math.pow(1 - impactslash, explosiveImpactProcRate * averageStatusChance)) * potentialProcs; // IB or Hem slash procs
explosiveBurstSlashStacks = explosiveSlashStacks * potentialBurstProcs / potentialProcs;
toxinStacks = procsPerSecond * toxinProcRate * (6 * finalStatusDuration);
burstToxinStacks = burstProcsPerSecond * toxinProcRate * (6 * finalStatusDuration);
explosiveToxinStacks = procsPerSecond * explosiveToxinProcRate * (6 * finalStatusDuration);
explosiveBurstToxinStacks = burstProcsPerSecond * explosiveToxinProcRate * (6 * finalStatusDuration);
gasStacks = procsPerSecond * gasProcRate * (6 * finalStatusDuration);
burstGasStacks = burstProcsPerSecond * gasProcRate * (6 * finalStatusDuration);
explosiveGasStacks = procsPerSecond * explosiveGasProcRate * (6 * finalStatusDuration);
explosiveBurstGasStacks = burstProcsPerSecond * explosiveGasProcRate * (6 * finalStatusDuration);
electricStacks = procsPerSecond * electricProcRate * (6 * finalStatusDuration);
burstElectricStacks = burstProcsPerSecond * electricProcRate * (6 * finalStatusDuration);
explosiveElectricStacks = procsPerSecond * explosiveElectricProcRate * (6 * finalStatusDuration);
explosiveBurstElectricStacks = burstProcsPerSecond * explosiveElectricProcRate * (6 * finalStatusDuration);
switch (forcedProc) {
case Constants.FIRE_WEAPON_DAMAGE:
fireStacks += potentialProcs;
burstFireStacks += potentialBurstProcs;
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
electricStacks += potentialProcs;
burstElectricStacks += potentialBurstProcs;
break;
case Constants.TOXIN_WEAPON_DAMAGE:
toxinStacks += potentialProcs;
burstToxinStacks += potentialBurstProcs;
break;
case Constants.GAS_WEAPON_DAMAGE:
gasStacks += potentialProcs;
burstGasStacks += potentialBurstProcs;
break;
case Constants.IMPACT_WEAPON_DAMAGE:
slashStacks = ((slashProcRate * averageStatusChance) + (hunterMunitions * Math.min(1, (finalCritChance + finalComboCrit))) + forcedSlashProcs) * potentialProcs;
slashStacks += (1-slashProcRate)* (1 - (hunterMunitions * Math.min(1, finalCritChance))) * impactslash * potentialProcs; // IB or Hem slash procs
burstSlashStacks = slashStacks * potentialBurstProcs / potentialProcs;
break;
}
switch (forcedProcEX) {
case Constants.FIRE_WEAPON_DAMAGE:
explosiveFireStacks += potentialProcs;
explosiveBurstFireStacks += potentialBurstProcs;
break;
case Constants.ELECTRIC_WEAPON_DAMAGE:
explosiveElectricStacks += potentialProcs;
explosiveBurstElectricStacks += potentialBurstProcs;
break;
case Constants.TOXIN_WEAPON_DAMAGE:
explosiveToxinStacks += potentialProcs;
explosiveBurstToxinStacks += potentialBurstProcs;
break;
case Constants.GAS_WEAPON_DAMAGE:
explosiveGasStacks += potentialProcs;
explosiveBurstGasStacks += potentialBurstProcs;
break;
case Constants.IMPACT_WEAPON_DAMAGE:
explosiveSlashStacks = ((explosiveSlashProcRate * averageStatusChance) + (hunterMunitions * Math.min(1, (finalCritChance + finalComboCrit))) + forcedSlashProcs) * potentialProcs;
explosiveSlashStacks += (1-explosiveSlashProcRate)* (1 - (hunterMunitions * Math.min(1, finalCritChance))) * impactslash * potentialProcs; // IB or Hem slash procs
explosiveBurstSlashStacks = explosiveSlashStacks * potentialBurstProcs / potentialProcs;
break;
}
// Final Damage values
impact.finalBase *= finalDamageMult;
explosiveImpact.finalBase *= finalDamageMult;
puncture.finalBase *= finalDamageMult;
explosivePuncture.finalBase *= finalDamageMult;
slash.finalBase *= finalDamageMult;
explosiveSlash.finalBase *= finalDamageMult;
fire.finalBase *= finalDamageMult;
explosiveFire.finalBase *= finalDamageMult;
ice.finalBase *= finalDamageMult;
explosiveIce.finalBase *= finalDamageMult;
electric.finalBase *= finalDamageMult;
explosiveElectric.finalBase *= finalDamageMult;
toxin.finalBase *= finalDamageMult;
explosiveToxin.finalBase *= finalDamageMult;
blast.finalBase *= finalDamageMult;
explosiveBlast.finalBase *= finalDamageMult;
magnetic.finalBase *= finalDamageMult;
explosiveMagnetic.finalBase *= finalDamageMult;
gas.finalBase *= finalDamageMult;
explosiveGas.finalBase *= finalDamageMult;
radiation.finalBase *= finalDamageMult;
explosiveRadiation.finalBase *= finalDamageMult;
corrosive.finalBase *= finalDamageMult;
explosiveCorrosive.finalBase *= finalDamageMult;
viral.finalBase *= finalDamageMult;
explosiveViral.finalBase *= finalDamageMult;
raw.finalBase = impact.finalBase + puncture.finalBase + slash.finalBase + fire.finalBase + ice.finalBase + electric.finalBase + toxin.finalBase + blast.finalBase + magnetic.finalBase + gas.finalBase + radiation.finalBase + corrosive.finalBase + viral.finalBase;
explosiveRaw.finalBase = explosiveImpact.finalBase + explosivePuncture.finalBase + explosiveSlash.finalBase + explosiveFire.finalBase + explosiveIce.finalBase + explosiveElectric.finalBase + explosiveToxin.finalBase + explosiveBlast.finalBase + explosiveMagnetic.finalBase + explosiveGas.finalBase + explosiveRadiation.finalBase + explosiveCorrosive.finalBase + explosiveViral.finalBase;
}
/**
* Calculates the damage per shot values
*/
protected static void calculateDamagePerShot() {
// Calculate base damage per shot values
raw.perShot = (raw.finalBase + explosiveRaw.finalBase) * averageProjectileCount * finalDeadAimMult * COMult * startingCombo * headShotMult * headShotBonus * avgHit * viralMult;
// Calculate crit damage per shot values
raw.critPerShot = raw.perShot * finalCritMult * headShotMult * headShotBonus;
finalFirstShotDamageMult -= 1;
// Calculate first-shot damage
raw.firstShot = raw.perShot * averageCritMult * finalFirstShotDamageMult;
finalLastShotDamageMult -= 1;
// Calculate last-shot damage
raw.lastShot = raw.perShot * averageCritMult * finalLastShotDamageMult;
// factions
corpus.perShot = raw.perShot * finalCorpusMult;
grineer.perShot = raw.perShot * finalGrineerMult;
infested.perShot = raw.perShot * finalInfestedMult;
corrupted.perShot = raw.perShot * finalCorruptedMult;
corpus.firstShot = corpus.perShot * averageCritMult * finalFirstShotDamageMult;
grineer.firstShot = grineer.perShot * averageCritMult * finalFirstShotDamageMult;
infested.firstShot = infested.perShot * averageCritMult * finalFirstShotDamageMult;
corrupted.firstShot = corrupted.perShot * averageCritMult * finalFirstShotDamageMult;
corpus.lastShot = corpus.perShot * averageCritMult * finalLastShotDamageMult;
grineer.lastShot = grineer.perShot * averageCritMult * finalLastShotDamageMult;
infested.lastShot = infested.perShot * averageCritMult * finalLastShotDamageMult;
corrupted.lastShot = corrupted.perShot * averageCritMult * finalLastShotDamageMult;
if (updateOutput) {
corpus.critPerShot = corpus.perShot * finalCritMult;
grineer.critPerShot = grineer.perShot * finalCritMult;
infested.critPerShot = infested.perShot * finalCritMult;
corrupted.critPerShot = corrupted.perShot * finalCritMult;
// Calculate base damage per shot values
impact.perShot = impact.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
puncture.perShot = puncture.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
slash.perShot = slash.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
fire.perShot = fire.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
ice.perShot = ice.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
electric.perShot = electric.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
toxin.perShot = toxin.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
blast.perShot = blast.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
magnetic.perShot = magnetic.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
gas.perShot = gas.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
radiation.perShot = radiation.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
corrosive.perShot = corrosive.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
viral.perShot = viral.finalBase * averageProjectileCount * finalDeadAimMult * COMult * headShotMult * headShotBonus * viralMult;
// Surface-specific
cloneFlesh.perShot += impact.perShot * 0.75;
cloneFlesh.perShot += puncture.perShot;
cloneFlesh.perShot += slash.perShot * 1.25;
cloneFlesh.perShot += fire.perShot * 1.25;
cloneFlesh.perShot += ice.perShot;
cloneFlesh.perShot += electric.perShot;
cloneFlesh.perShot += toxin.perShot;
cloneFlesh.perShot += blast.perShot;
cloneFlesh.perShot += magnetic.perShot;
cloneFlesh.perShot += gas.perShot * 0.5;
cloneFlesh.perShot += radiation.perShot;
cloneFlesh.perShot += corrosive.perShot;
cloneFlesh.perShot += viral.perShot * 1.75;
cloneFlesh.perShot *= finalGrineerMult;
ferrite.perShot += impact.perShot;
ferrite.perShot += puncture.perShot * 1.5;
ferrite.perShot += slash.perShot * 0.85;
ferrite.perShot += fire.perShot;
ferrite.perShot += ice.perShot;
ferrite.perShot += electric.perShot;
ferrite.perShot += toxin.perShot;
ferrite.perShot += blast.perShot * 0.75;
ferrite.perShot += magnetic.perShot;
ferrite.perShot += gas.perShot;
ferrite.perShot += radiation.perShot;
ferrite.perShot += corrosive.perShot * 1.75;
ferrite.perShot += viral.perShot;
alloy.perShot += impact.perShot;
alloy.perShot += puncture.perShot * 1.15;
alloy.perShot += slash.perShot * 0.5;
alloy.perShot += fire.perShot;
alloy.perShot += ice.perShot * 1.25;
alloy.perShot += electric.perShot * 0.5;
alloy.perShot += toxin.perShot;
alloy.perShot += blast.perShot;
alloy.perShot += magnetic.perShot * 0.5;
alloy.perShot += gas.perShot;
alloy.perShot += radiation.perShot * 1.75;
alloy.perShot += corrosive.perShot;
alloy.perShot += viral.perShot;
mechanical.perShot += impact.perShot * 1.25;
mechanical.perShot += puncture.perShot;
mechanical.perShot += slash.perShot;
mechanical.perShot += fire.perShot;
mechanical.perShot += ice.perShot;
mechanical.perShot += electric.perShot * 1.5;
mechanical.perShot += toxin.perShot * 0.75;
mechanical.perShot += blast.perShot * 1.75;
mechanical.perShot += magnetic.perShot;
mechanical.perShot += gas.perShot;
mechanical.perShot += radiation.perShot;
mechanical.perShot += corrosive.perShot;
mechanical.perShot += viral.perShot * 0.75;
mechanical.perShot *= finalGrineerMult;
corpusFlesh.perShot += impact.perShot * 0.75;
corpusFlesh.perShot += puncture.perShot;
corpusFlesh.perShot += slash.perShot * 1.25;
corpusFlesh.perShot += fire.perShot;
corpusFlesh.perShot += ice.perShot;
corpusFlesh.perShot += electric.perShot;
corpusFlesh.perShot += toxin.perShot * 1.5;
corpusFlesh.perShot += blast.perShot;
corpusFlesh.perShot += magnetic.perShot;
corpusFlesh.perShot += gas.perShot * 0.75;
corpusFlesh.perShot += radiation.perShot;
corpusFlesh.perShot += corrosive.perShot;
corpusFlesh.perShot += viral.perShot * 1.5;
corpusFlesh.perShot *= finalCorpusMult;
shield.perShot += impact.perShot * 1.5;
shield.perShot += puncture.perShot * 0.85;
shield.perShot += slash.perShot;
shield.perShot += fire.perShot;
shield.perShot += ice.perShot * 1.5;
shield.perShot += electric.perShot;
shield.perShot += toxin.perShot;
shield.perShot += blast.perShot;
shield.perShot += magnetic.perShot * 1.75;
shield.perShot += gas.perShot;
shield.perShot += radiation.perShot * 0.75;
shield.perShot += corrosive.perShot;
shield.perShot += viral.perShot;
shield.perShot *= finalCorpusMult;
protoShield.perShot += impact.perShot * 1.15;
protoShield.perShot += puncture.perShot * 0.5;
protoShield.perShot += slash.perShot;
protoShield.perShot += fire.perShot * 0.5;
protoShield.perShot += ice.perShot;
protoShield.perShot += electric.perShot;
protoShield.perShot += toxin.perShot * 1.25;
protoShield.perShot += blast.perShot;
protoShield.perShot += magnetic.perShot * 1.75;
protoShield.perShot += gas.perShot;
protoShield.perShot += radiation.perShot;
protoShield.perShot += corrosive.perShot * 0.5;
protoShield.perShot += viral.perShot;
protoShield.perShot *= finalCorpusMult;
robotic.perShot += impact.perShot;
robotic.perShot += puncture.perShot * 1.25;
robotic.perShot += slash.perShot * 0.75;
robotic.perShot += fire.perShot;
robotic.perShot += ice.perShot;
robotic.perShot += electric.perShot * 1.5;
robotic.perShot += toxin.perShot * 0.75;
robotic.perShot += blast.perShot;
robotic.perShot += magnetic.perShot;
robotic.perShot += gas.perShot;
robotic.perShot += radiation.perShot * 1.25;
robotic.perShot += corrosive.perShot;
robotic.perShot += viral.perShot;
robotic.perShot *= finalCorpusMult;
infestedFlesh.perShot += impact.perShot;
infestedFlesh.perShot += puncture.perShot;
infestedFlesh.perShot += slash.perShot * 1.5;
infestedFlesh.perShot += fire.perShot * 1.5;
infestedFlesh.perShot += ice.perShot * 0.5;
infestedFlesh.perShot += electric.perShot;
infestedFlesh.perShot += toxin.perShot;
infestedFlesh.perShot += blast.perShot;
infestedFlesh.perShot += magnetic.perShot;
infestedFlesh.perShot += gas.perShot * 1.5;
infestedFlesh.perShot += radiation.perShot;
infestedFlesh.perShot += corrosive.perShot;
infestedFlesh.perShot += viral.perShot;
infestedFlesh.perShot *= finalInfestedMult;
fossilized.perShot += impact.perShot;
fossilized.perShot += puncture.perShot;
fossilized.perShot += slash.perShot * 1.15;
fossilized.perShot += fire.perShot;
fossilized.perShot += ice.perShot * 0.75;
fossilized.perShot += electric.perShot;
fossilized.perShot += toxin.perShot * 0.5;
fossilized.perShot += blast.perShot * 1.5;
fossilized.perShot += magnetic.perShot;
fossilized.perShot += gas.perShot;
fossilized.perShot += radiation.perShot * 0.25;
fossilized.perShot += corrosive.perShot * 1.75;
fossilized.perShot += viral.perShot;
fossilized.perShot *= finalInfestedMult;
sinew.perShot += impact.perShot;
sinew.perShot += puncture.perShot * 1.25;
sinew.perShot += slash.perShot;
sinew.perShot += fire.perShot;
sinew.perShot += ice.perShot * 1.25;
sinew.perShot += electric.perShot;
sinew.perShot += toxin.perShot;
sinew.perShot += blast.perShot * 0.5;
sinew.perShot += magnetic.perShot;
sinew.perShot += gas.perShot;
sinew.perShot += radiation.perShot * 1.5;
sinew.perShot += corrosive.perShot;
sinew.perShot += viral.perShot;
sinew.perShot *= finalInfestedMult;
// Calculate crit damage per shot values
impact.critPerShot = impact.perShot * finalCritMult;
puncture.critPerShot = puncture.perShot * finalCritMult;
slash.critPerShot = slash.perShot * finalCritMult;
fire.critPerShot = fire.perShot * finalCritMult;
ice.critPerShot = ice.perShot * finalCritMult;
electric.critPerShot = electric.perShot * finalCritMult;
toxin.critPerShot = toxin.perShot * finalCritMult;
blast.critPerShot = blast.perShot * finalCritMult;
magnetic.critPerShot = magnetic.perShot * finalCritMult;
gas.critPerShot = gas.perShot * finalCritMult;
radiation.critPerShot = radiation.perShot * finalCritMult;
corrosive.critPerShot = corrosive.perShot * finalCritMult;
viral.critPerShot = viral.perShot * finalCritMult;
cloneFlesh.critPerShot = cloneFlesh.perShot * finalCritMult;
ferrite.critPerShot = ferrite.perShot * finalCritMult;
alloy.critPerShot = alloy.perShot * finalCritMult;
mechanical.critPerShot = mechanical.perShot * finalCritMult;
corpusFlesh.critPerShot = corpusFlesh.perShot * finalCritMult;
shield.critPerShot = shield.perShot * finalCritMult;
protoShield.critPerShot = protoShield.perShot * finalCritMult;
robotic.critPerShot = robotic.perShot * finalCritMult;
infestedFlesh.critPerShot = infestedFlesh.perShot * finalCritMult;
fossilized.critPerShot = fossilized.perShot * finalCritMult;
sinew.critPerShot = sinew.perShot * finalCritMult;
// Calculate surface first-shot damage
impact.firstShot = impact.perShot * averageCritMult * finalFirstShotDamageMult;
puncture.firstShot = puncture.perShot * averageCritMult * finalFirstShotDamageMult;
slash.firstShot = slash.perShot * averageCritMult * finalFirstShotDamageMult;
fire.firstShot = fire.perShot * averageCritMult * finalFirstShotDamageMult;
ice.firstShot = ice.perShot * averageCritMult * finalFirstShotDamageMult;
electric.firstShot = electric.perShot * averageCritMult * finalFirstShotDamageMult;
toxin.firstShot = toxin.perShot * averageCritMult * finalFirstShotDamageMult;
blast.firstShot = blast.perShot * averageCritMult * finalFirstShotDamageMult;
magnetic.firstShot = magnetic.perShot * averageCritMult * finalFirstShotDamageMult;
gas.firstShot = gas.perShot * averageCritMult * finalFirstShotDamageMult;
radiation.firstShot = radiation.perShot * averageCritMult * finalFirstShotDamageMult;
corrosive.firstShot = corrosive.perShot * averageCritMult * finalFirstShotDamageMult;
viral.firstShot = viral.perShot * averageCritMult * finalFirstShotDamageMult;
cloneFlesh.firstShot = cloneFlesh.perShot * averageCritMult * finalFirstShotDamageMult;
ferrite.firstShot = ferrite.perShot * averageCritMult * finalFirstShotDamageMult;
alloy.firstShot = alloy.perShot * averageCritMult * finalFirstShotDamageMult;
mechanical.firstShot = mechanical.perShot * averageCritMult * finalFirstShotDamageMult;
corpusFlesh.firstShot = corpusFlesh.perShot * averageCritMult * finalFirstShotDamageMult;
shield.firstShot = shield.perShot * averageCritMult * finalFirstShotDamageMult;
protoShield.firstShot = protoShield.perShot * averageCritMult * finalFirstShotDamageMult;
robotic.firstShot = robotic.perShot * averageCritMult * finalFirstShotDamageMult;
infestedFlesh.firstShot = infestedFlesh.perShot * averageCritMult * finalFirstShotDamageMult;
fossilized.firstShot = fossilized.perShot * averageCritMult * finalFirstShotDamageMult;
sinew.firstShot = sinew.perShot * averageCritMult * finalFirstShotDamageMult;
// Calculate surface last-shot damage
impact.lastShot = impact.perShot * averageCritMult * finalLastShotDamageMult;
puncture.lastShot = puncture.perShot * averageCritMult * finalLastShotDamageMult;
slash.lastShot = slash.perShot * averageCritMult * finalLastShotDamageMult;
fire.lastShot = fire.perShot * averageCritMult * finalLastShotDamageMult;
ice.lastShot = ice.perShot * averageCritMult * finalLastShotDamageMult;
electric.lastShot = electric.perShot * averageCritMult * finalLastShotDamageMult;
toxin.lastShot = toxin.perShot * averageCritMult * finalLastShotDamageMult;
blast.lastShot = blast.perShot * averageCritMult * finalLastShotDamageMult;
magnetic.lastShot = magnetic.perShot * averageCritMult * finalLastShotDamageMult;
gas.lastShot = gas.perShot * averageCritMult * finalLastShotDamageMult;
radiation.lastShot = radiation.perShot * averageCritMult * finalLastShotDamageMult;
corrosive.lastShot = corrosive.perShot * averageCritMult * finalLastShotDamageMult;
viral.lastShot = viral.perShot * averageCritMult * finalLastShotDamageMult;
cloneFlesh.lastShot = cloneFlesh.perShot * averageCritMult * finalLastShotDamageMult;
ferrite.lastShot = ferrite.perShot * averageCritMult * finalLastShotDamageMult;
alloy.lastShot = alloy.perShot * averageCritMult * finalLastShotDamageMult;
mechanical.lastShot = mechanical.perShot * averageCritMult * finalLastShotDamageMult;
corpusFlesh.lastShot = corpusFlesh.perShot * averageCritMult * finalLastShotDamageMult;
shield.lastShot = shield.perShot * averageCritMult * finalLastShotDamageMult;
protoShield.lastShot = protoShield.perShot * averageCritMult * finalLastShotDamageMult;
robotic.lastShot = robotic.perShot * averageCritMult * finalLastShotDamageMult;
infestedFlesh.lastShot = infestedFlesh.perShot * averageCritMult * finalLastShotDamageMult;
fossilized.lastShot = fossilized.perShot * averageCritMult * finalLastShotDamageMult;
sinew.lastShot = sinew.perShot * averageCritMult * finalLastShotDamageMult;
}
}
/**
* Calculates the total damage done over an entire magazine
*/
protected static void calculateDamagePerIteration() {
raw.perIteration = raw.perShot * finalMag * averageCritMult + raw.firstShot + raw.lastShot;
corpus.perIteration = corpus.perShot * finalMag * averageCritMult + corpus.firstShot + corpus.lastShot;
grineer.perIteration = grineer.perShot * finalMag * averageCritMult + grineer.firstShot + grineer.lastShot;
infested.perIteration = infested.perShot * finalMag * averageCritMult + infested.firstShot + infested.lastShot;
corrupted.perIteration = corrupted.perShot * finalMag * averageCritMult + corrupted.firstShot + corrupted.lastShot;
if (updateOutput) {
impact.perIteration = impact.perShot * finalMag * averageCritMult + impact.firstShot + impact.lastShot;
puncture.perIteration = puncture.perShot * finalMag * averageCritMult + puncture.firstShot + puncture.lastShot;
slash.perIteration = slash.perShot * finalMag * averageCritMult + slash.firstShot + slash.lastShot;
fire.perIteration = fire.perShot * finalMag * averageCritMult + fire.firstShot + fire.lastShot;
ice.perIteration = ice.perShot * finalMag * averageCritMult + ice.firstShot + ice.lastShot;
electric.perIteration = electric.perShot * finalMag * averageCritMult + electric.firstShot + electric.lastShot;
toxin.perIteration = toxin.perShot * finalMag * averageCritMult + toxin.firstShot + toxin.lastShot;
blast.perIteration = blast.perShot * finalMag * averageCritMult + blast.firstShot + blast.lastShot;
magnetic.perIteration = magnetic.perShot * finalMag * averageCritMult + magnetic.firstShot + magnetic.lastShot;
gas.perIteration = gas.perShot * finalMag * averageCritMult + gas.firstShot + gas.lastShot;
radiation.perIteration = radiation.perShot * finalMag * averageCritMult + radiation.firstShot + radiation.lastShot;
corrosive.perIteration = corrosive.perShot * finalMag * averageCritMult + corrosive.firstShot + corrosive.lastShot;
viral.perIteration = viral.perShot * finalMag * averageCritMult + viral.firstShot + viral.lastShot;
cloneFlesh.perIteration = cloneFlesh.perShot * finalMag * averageCritMult + cloneFlesh.firstShot + cloneFlesh.lastShot;
ferrite.perIteration = ferrite.perShot * finalMag * averageCritMult + ferrite.firstShot + ferrite.lastShot;
alloy.perIteration = alloy.perShot * finalMag * averageCritMult + alloy.firstShot + alloy.lastShot;
mechanical.perIteration = mechanical.perShot * finalMag * averageCritMult + mechanical.firstShot + mechanical.lastShot;
corpusFlesh.perIteration = corpusFlesh.perShot * finalMag * averageCritMult + corpusFlesh.firstShot + corpusFlesh.lastShot;
shield.perIteration = shield.perShot * finalMag * averageCritMult + shield.firstShot + shield.lastShot;
protoShield.perIteration = protoShield.perShot * finalMag * averageCritMult + protoShield.firstShot + protoShield.lastShot;
robotic.perIteration = robotic.perShot * finalMag * averageCritMult + robotic.firstShot + robotic.lastShot;
infestedFlesh.perIteration = infestedFlesh.perShot * finalMag * averageCritMult + infestedFlesh.firstShot + infestedFlesh.lastShot;
fossilized.perIteration = fossilized.perShot * finalMag * averageCritMult + fossilized.firstShot + fossilized.lastShot;
sinew.perIteration = sinew.perShot * finalMag * averageCritMult + sinew.firstShot + sinew.lastShot;
}
}
/**
* Calculates the total damage dealt over a given minute.
*/
protected static void calculateDamagePerMinute() {
raw.perMinute = raw.perIteration * finalIterationsPerMinute;
corpus.perMinute = corpus.perIteration * finalIterationsPerMinute;
grineer.perMinute = grineer.perIteration * finalIterationsPerMinute;
infested.perMinute = infested.perIteration * finalIterationsPerMinute;
corrupted.perMinute = corrupted.perIteration * finalIterationsPerMinute;
if (updateOutput) {
impact.perMinute = impact.perIteration * finalIterationsPerMinute;
puncture.perMinute = puncture.perIteration * finalIterationsPerMinute;
slash.perMinute = slash.perIteration * finalIterationsPerMinute;
fire.perMinute = fire.perIteration * finalIterationsPerMinute;
ice.perMinute = ice.perIteration * finalIterationsPerMinute;
electric.perMinute = electric.perIteration * finalIterationsPerMinute;
toxin.perMinute = toxin.perIteration * finalIterationsPerMinute;
blast.perMinute = blast.perIteration * finalIterationsPerMinute;
magnetic.perMinute = magnetic.perIteration * finalIterationsPerMinute;
gas.perMinute = gas.perIteration * finalIterationsPerMinute;
radiation.perMinute = radiation.perIteration * finalIterationsPerMinute;
corrosive.perMinute = corrosive.perIteration * finalIterationsPerMinute;
viral.perMinute = viral.perIteration * finalIterationsPerMinute;
cloneFlesh.perMinute = cloneFlesh.perIteration * finalIterationsPerMinute;
ferrite.perMinute = ferrite.perIteration * finalIterationsPerMinute;
alloy.perMinute = alloy.perIteration * finalIterationsPerMinute;
mechanical.perMinute = mechanical.perIteration * finalIterationsPerMinute;
corpus.perMinute = corpusFlesh.perIteration * finalIterationsPerMinute;
shield.perMinute = shield.perIteration * finalIterationsPerMinute;
protoShield.perMinute = protoShield.perIteration * finalIterationsPerMinute;
robotic.perMinute = robotic.perIteration * finalIterationsPerMinute;
infestedFlesh.perMinute = infestedFlesh.perIteration * finalIterationsPerMinute;
fossilized.perMinute = fossilized.perIteration * finalIterationsPerMinute;
sinew.perMinute = sinew.perIteration * finalIterationsPerMinute;
}
}
protected static void calculateDamagePerSecond() {
// Calculate base DPS values
raw.perSecond = raw.perMinute / 60.0;
corpus.perSecond = corpus.perMinute / 60.0;
grineer.perSecond = grineer.perMinute / 60.0;
infested.perSecond = infested.perMinute / 60.0;
corrupted.perSecond = corrupted.perMinute / 60.0;
// Add in DoTs
double hunterMult = 1;
if (hunterMunitions > 0) { // Need to fix because hunter munitions stacks are always on crit
double hunterRatio = (Math.min(1, finalCritChance + finalComboCrit) * hunterMunitions) / (1 - ((1 - (slashProcRate * averageStatusChance)) * (1 - (hunterMunitions * Math.min(1, finalCritChance + finalComboCrit)))));
hunterMult = (hunterRatio * finalCritMult * headShotMult * headShotBonus + (1 - hunterRatio) * averageCritMult) / averageCritMult;
}
double stanceSlashMult = 1;
if (selectedWeapon.weaponType.equals(Constants.MELEE) && stanceCombo != null) {
stanceSlashMult = 0;
double stanceSlashes = 0;
for (Hit h : stanceCombo.hits) {
if (h.procs[0].equals("1")) {
stanceSlashMult += h.multiplier;
stanceSlashes += 1;
}
}
stanceSlashMult /= stanceSlashes;
double stanceRatio = (stanceSlashes / stanceCombo.hits.size()) / (1 - ((1 - (slashProcRate * averageStatusChance)) * (1 - stanceSlashes / stanceCombo.hits.size())));
stanceSlashMult = (stanceRatio * stanceSlashMult + (1 - stanceRatio)) / avgHit;
}
if (Double.isNaN(stanceSlashMult)) {
stanceSlashMult = 1;
}
double DoTBase = raw.base * finalDamageMult * COMult * viralMult * finalDeadAimMult * startingCombo * avgHit * (1 + (finalFirstShotDamageMult + finalLastShotDamageMult) / finalMag) * headShotMult * headShotBonus * averageCritMult;
double electricBase = DoTBase * (1 + globalElectric) * 0.5 * headShotMult * headShotBonus;
double bleedDamage = (DoTBase * 0.35 * hunterMult) * stanceSlashMult;
double poisonDamage = (DoTBase * (1 + globalToxin)) * 0.5;
double heatDamage = (DoTBase * (1 + globalFire)) * 0.5;
double cloudDamage = DoTBase * 0.5;
double explosiveDoTBase = explosiveRaw.base * finalDamageMult * COMult * viralMult * finalDeadAimMult * startingCombo * avgHit * (1 + (finalFirstShotDamageMult + finalLastShotDamageMult) / finalMag) * headShotMult * headShotBonus * averageCritMult;
double explosiveElectricBase = explosiveDoTBase * (1 + globalElectric) * 0.5 * headShotMult * headShotBonus;
double explosiveBleedDamage = (explosiveDoTBase * 0.35 * hunterMult) * stanceSlashMult;
double explosivePoisonDamage = (explosiveDoTBase * (1 + globalToxin)) * 0.5;
double explosiveHeatDamage = (explosiveDoTBase * (1 + globalFire)) * 0.5;
double explosiveCloudDamage = explosiveDoTBase * 0.5;
bleedDoTDPS = slashStacks * bleedDamage;
bleedDoTDPS += explosiveSlashStacks * explosiveBleedDamage;
burstBleedDoTDPS = burstSlashStacks * bleedDamage;
burstBleedDoTDPS += explosiveBurstSlashStacks * explosiveBleedDamage;
poisonDoTDPS = toxinStacks * poisonDamage;
poisonDoTDPS += explosiveToxinStacks * explosivePoisonDamage;
burstPoisonDoTDPS = burstToxinStacks * poisonDamage;
burstPoisonDoTDPS += explosiveBurstToxinStacks * explosivePoisonDamage;
heatDoTDPS = fireStacks * heatDamage;
heatDoTDPS += explosiveFireStacks * explosiveHeatDamage;
burstHeatDoTDPS = burstFireStacks * heatDamage;
burstHeatDoTDPS += explosiveBurstFireStacks * explosiveHeatDamage;
cloudDoTDPS = gasStacks * cloudDamage;
cloudDoTDPS += explosiveGasStacks * explosiveCloudDamage;
burstCloudDoTDPS = burstGasStacks * cloudDamage;
burstCloudDoTDPS += explosiveBurstGasStacks * explosiveCloudDamage;
electricProcDPS = electricStacks * electricBase;
electricProcDPS += explosiveElectricStacks * explosiveElectricBase;
burstElectricProcDPS = burstElectricStacks * electricBase;
burstElectricProcDPS += explosiveBurstElectricStacks * explosiveElectricBase;
raw.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS + electricProcDPS);
corpus.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS + electricProcDPS) * finalCorpusMult * finalCorpusMult;
grineer.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS + electricProcDPS) * finalGrineerMult * finalGrineerMult;
infested.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS + electricProcDPS) * finalInfestedMult * finalInfestedMult;
corrupted.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS + electricProcDPS) * finalCorruptedMult * finalCorruptedMult;
if (updateOutput) {
impact.perSecond = impact.perMinute / 60.0;
puncture.perSecond = puncture.perMinute / 60.0;
slash.perSecond = slash.perMinute / 60.0;
fire.perSecond = fire.perMinute / 60.0;
ice.perSecond = ice.perMinute / 60.0;
electric.perSecond = electric.perMinute / 60.0;
toxin.perSecond = toxin.perMinute / 60.0;
blast.perSecond = blast.perMinute / 60.0;
magnetic.perSecond = magnetic.perMinute / 60.0;
gas.perSecond = gas.perMinute / 60.0;
radiation.perSecond = radiation.perMinute / 60.0;
corrosive.perSecond = corrosive.perMinute / 60.0;
viral.perSecond = viral.perMinute / 60.0;
cloneFlesh.perSecond = cloneFlesh.perMinute / 60.0;
ferrite.perSecond = ferrite.perMinute / 60.0;
alloy.perSecond = alloy.perMinute / 60.0;
mechanical.perSecond = mechanical.perMinute / 60.0;
corpusFlesh.perSecond = corpusFlesh.perMinute / 60.0;
shield.perSecond = shield.perMinute / 60.0;
protoShield.perSecond = protoShield.perMinute / 60.0;
robotic.perSecond = robotic.perMinute / 60.0;
infestedFlesh.perSecond = infestedFlesh.perMinute / 60.0;
fossilized.perSecond = fossilized.perMinute / 60.0;
sinew.perSecond = sinew.perMinute / 60.0;
cloneFlesh.perSecond += (bleedDoTDPS + poisonDoTDPS + (heatDoTDPS * 1.25) + cloudDoTDPS);
ferrite.perSecond += (bleedDoTDPS + (poisonDoTDPS) + heatDoTDPS + (cloudDoTDPS));
alloy.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS);
mechanical.perSecond += (bleedDoTDPS + (poisonDoTDPS * 0.75) + heatDoTDPS + (cloudDoTDPS * 0.75));
corpusFlesh.perSecond += (bleedDoTDPS + (poisonDoTDPS * 1.5) + heatDoTDPS + (cloudDoTDPS * 1.5));
shield.perSecond += (heatDoTDPS);
protoShield.perSecond += ((heatDoTDPS * 0.5));
robotic.perSecond += (bleedDoTDPS + (poisonDoTDPS * 0.75) + heatDoTDPS + (cloudDoTDPS * 0.75));
infestedFlesh.perSecond += (bleedDoTDPS + poisonDoTDPS + (heatDoTDPS * 1.5) + cloudDoTDPS);
fossilized.perSecond += (bleedDoTDPS + (poisonDoTDPS * 0.5) + heatDoTDPS + (cloudDoTDPS * 0.5));
sinew.perSecond += (bleedDoTDPS + poisonDoTDPS + heatDoTDPS + cloudDoTDPS);
}
}
protected static void calculateBurstDamagePerSecond() {
// Calculate base Burst DPS values
double burstTime = (1 / (finalIterationTime - finalReloadTime));
raw.rawPerSecond = raw.perIteration * burstTime;
// Add in DoTs
raw.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstElectricProcDPS + burstCloudDoTDPS);
corpus.rawPerSecond = corpus.perIteration * burstTime;
grineer.rawPerSecond = grineer.perIteration * burstTime;
infested.rawPerSecond = infested.perIteration * burstTime;
corrupted.rawPerSecond = corrupted.perIteration * burstTime;
corpus.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstElectricProcDPS + burstCloudDoTDPS) * finalCorpusMult * finalCorpusMult;
grineer.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstElectricProcDPS + burstCloudDoTDPS) * finalGrineerMult * finalGrineerMult;
infested.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstElectricProcDPS + burstCloudDoTDPS) * finalInfestedMult * finalInfestedMult;
corrupted.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstElectricProcDPS + burstCloudDoTDPS) * finalCorruptedMult * finalCorruptedMult;
if (updateOutput) {
impact.rawPerSecond = impact.perIteration * burstTime;
puncture.rawPerSecond = puncture.perIteration * burstTime;
slash.rawPerSecond = slash.perIteration * burstTime;
fire.rawPerSecond = fire.perIteration * burstTime;
ice.rawPerSecond = ice.perIteration * burstTime;
electric.rawPerSecond = electric.perIteration * burstTime;
toxin.rawPerSecond = toxin.perIteration * burstTime;
blast.rawPerSecond = blast.perIteration * burstTime;
magnetic.rawPerSecond = magnetic.perIteration * burstTime;
gas.rawPerSecond = gas.perIteration * burstTime;
radiation.rawPerSecond = radiation.perIteration * burstTime;
corrosive.rawPerSecond = corrosive.perIteration * burstTime;
viral.rawPerSecond = viral.perIteration * burstTime;
cloneFlesh.rawPerSecond = cloneFlesh.perIteration * burstTime;
ferrite.rawPerSecond = ferrite.perIteration * burstTime;
alloy.rawPerSecond = alloy.perIteration * burstTime;
mechanical.rawPerSecond = mechanical.perIteration * burstTime;
corpusFlesh.rawPerSecond = corpusFlesh.perIteration * burstTime;
shield.rawPerSecond = shield.perIteration * burstTime;
protoShield.rawPerSecond = protoShield.perIteration * burstTime;
robotic.rawPerSecond = robotic.perIteration * burstTime;
infestedFlesh.rawPerSecond = infestedFlesh.perIteration * burstTime;
fossilized.rawPerSecond = fossilized.perIteration * burstTime;
sinew.rawPerSecond = sinew.perIteration * burstTime;
cloneFlesh.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + (burstHeatDoTDPS * 1.25) + burstCloudDoTDPS * finalGrineerMult);
ferrite.rawPerSecond += (burstBleedDoTDPS + (burstPoisonDoTDPS) + burstHeatDoTDPS + (burstCloudDoTDPS));
alloy.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstCloudDoTDPS);
mechanical.rawPerSecond += (burstBleedDoTDPS + (burstPoisonDoTDPS * 0.75) + burstHeatDoTDPS + (burstCloudDoTDPS * 0.75 * finalGrineerMult));
corpusFlesh.rawPerSecond += (burstBleedDoTDPS + (burstPoisonDoTDPS * 1.5) + burstHeatDoTDPS + (burstCloudDoTDPS * 1.5 * finalCorpusMult));
shield.rawPerSecond += burstHeatDoTDPS;
protoShield.rawPerSecond += burstHeatDoTDPS * 0.5;
robotic.rawPerSecond += (burstBleedDoTDPS + (burstPoisonDoTDPS * 0.75) + burstHeatDoTDPS + (burstCloudDoTDPS * 0.75 * finalCorpusMult));
infestedFlesh.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + (burstHeatDoTDPS * 1.5) + burstCloudDoTDPS * finalInfestedMult);
fossilized.rawPerSecond += (burstBleedDoTDPS + (burstPoisonDoTDPS * 0.5) + burstHeatDoTDPS + (burstCloudDoTDPS * finalInfestedMult * 0.5));
sinew.rawPerSecond += (burstBleedDoTDPS + burstPoisonDoTDPS + burstHeatDoTDPS + burstCloudDoTDPS * finalInfestedMult);
}
}
/**
* Appends the weapon information to the output text area
*/
protected static void updateOutput() {
// Append to Output
DecimalFormat f = new DecimalFormat("#.###");
output.append("\n");
output.append("\n_____________________________________________________________");
output.append("\nName :: " + weaponName);
output.append("\nMagazine Size :: " + finalMag);
output.append("\nTotal Ammo :: " + (finalMag + finalAmmo));
output.append("\nCrit Chance :: " + f.format((finalCritChance + finalComboCrit) * 100.0) + "%");
output.append("\nCrit Damage Multiplier :: " + f.format(finalCritMult * 100.0) + "%");
String delimiter = "rounds";
String mode = selectedWeapon.getWeaponMode();
if (mode.equals(Constants.BURST)) {
delimiter = "bursts";
} else if (mode.equals(Constants.CONTINUOUS)) {
delimiter = "ticks";
}
output.append("\nFire Rate :: " + f.format(finalFireRate / avgDelay) + " " + delimiter + " per second");
output.append("\nReload Time :: " + f.format(finalReloadTime) + " seconds");
output.append("\nStatus Chance :: " + f.format(averageStatusChance * 100.0) + "%");
output.append("\nAverage Projectiles Per Shot :: " + f.format(averageProjectileCount));
output.append("\nStatus Procs Per Second :: " + f.format(procsPerSecond));
output.append("\nBurst Status Procs Per Second :: " + f.format(burstProcsPerSecond));
output.append("\nTime to Empty magazine :: " + f.format(finalIterationTime - finalReloadTime) + " seconds");
if (slashStacks > 0) {
output.append("\nAverage Bleed Stacks :: " + slashStacks);
}
if (toxinStacks > 0) {
output.append("\nAverage Poison Stacks :: " + toxinStacks);
}
if (gasStacks > 0) {
output.append("\nAverage Poison Cloud Stacks :: " + gasStacks);
}
if (fireStacks > 0) {
output.append("\nAverage Burning Stacks :: " + fireStacks);
}
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw Damage Per Shot :: " + f.format(raw.perShot));
if (impact.perShot > 0.0) {
output.append("\nImpact Damage Per Shot :: " + f.format(impact.perShot));
}
if (puncture.perShot > 0.0) {
output.append("\nPuncture Damage Per Shot :: " + f.format(puncture.perShot));
}
if (slash.perShot > 0.0) {
output.append("\nSlash Damage Per Shot :: " + f.format(slash.perShot));
}
if (fire.perShot > 0.0) {
output.append("\nFire Damage Per Shot :: " + f.format(fire.perShot));
}
if (ice.perShot > 0.0) {
output.append("\nIce Damage Per Shot :: " + f.format(ice.perShot));
}
if (electric.perShot > 0.0) {
output.append("\nElectric Damage Per Shot :: " + f.format(electric.perShot));
}
if (toxin.perShot > 0.0) {
output.append("\nToxin Damage Per Shot :: " + f.format(toxin.perShot));
}
if (blast.perShot > 0.0) {
output.append("\nBlast Damage Per Shot :: " + f.format(blast.perShot));
}
if (magnetic.perShot > 0.0) {
output.append("\nMagnetic Damage Per Shot :: " + f.format(magnetic.perShot));
}
if (gas.perShot > 0.0) {
output.append("\nGas Damage Per Shot :: " + f.format(gas.perShot));
}
if (radiation.perShot > 0.0) {
output.append("\nRadiation Damage Per Shot :: " + f.format(radiation.perShot));
}
if (corrosive.perShot > 0.0) {
output.append("\nCorrosive Damage Per Shot :: " + f.format(corrosive.perShot));
}
if (viral.perShot > 0.0) {
output.append("\nViral Damage Per Shot :: " + f.format(viral.perShot));
}
output.append("\nDamage Per Shot to Clone Flesh :: " + f.format(cloneFlesh.perShot));
output.append("\nDamage Per Shot to Ferrite Armor :: " + f.format(ferrite.perShot));
output.append("\nDamage Per Shot to Alloy Armor :: " + f.format(alloy.perShot));
output.append("\nDamage Per Shot to Mechanical :: " + f.format(mechanical.perShot));
output.append("\nDamage Per Shot to Corpus Flesh :: " + f.format(corpusFlesh.perShot));
output.append("\nDamage Per Shot to Shield :: " + f.format(shield.perShot));
output.append("\nDamage Per Shot to Proto Shield :: " + f.format(protoShield.perShot));
output.append("\nDamage Per Shot to Robotic :: " + f.format(robotic.perShot));
output.append("\nDamage Per Shot to Infested Flesh :: " + f.format(infestedFlesh.perShot));
output.append("\nDamage Per Shot to Fossilized :: " + f.format(fossilized.perShot));
output.append("\nDamage Per Shot to Sinew :: " + f.format(sinew.perShot));
output.append("\nDamage Per Shot to Corpus :: " + f.format(corpus.perShot));
output.append("\nDamage Per Shot to Grineer :: " + f.format(grineer.perShot));
output.append("\nDamage Per Shot to Infested :: " + f.format(infested.perShot));
output.append("\nDamage Per Shot to Corrupted :: " + f.format(corrupted.perShot));
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw Crit Damage Per Shot :: " + f.format(raw.critPerShot));
if (impact.critPerShot > 0.0) {
output.append("\nImpact Crit Damage Per Shot :: " + f.format(impact.critPerShot));
}
if (puncture.critPerShot > 0.0) {
output.append("\nPuncture Crit Damage Per Shot :: " + f.format(puncture.critPerShot));
}
if (slash.critPerShot > 0.0) {
output.append("\nSlash Crit Damage Per Shot :: " + f.format(slash.critPerShot));
}
if (fire.critPerShot > 0.0) {
output.append("\nFire Crit Damage Per Shot :: " + f.format(fire.critPerShot));
}
if (ice.critPerShot > 0.0) {
output.append("\nIce Crit Damage Per Shot :: " + f.format(ice.critPerShot));
}
if (electric.critPerShot > 0.0) {
output.append("\nElectric Crit Damage Per Shot :: " + f.format(electric.critPerShot));
}
if (toxin.critPerShot > 0.0) {
output.append("\nToxin Crit Damage Per Shot :: " + f.format(toxin.critPerShot));
}
if (blast.critPerShot > 0.0) {
output.append("\nBlast Crit Damage Per Shot :: " + f.format(blast.critPerShot));
}
if (magnetic.critPerShot > 0.0) {
output.append("\nMagnetic Crit Damage Per Shot :: " + f.format(magnetic.critPerShot));
}
if (gas.critPerShot > 0.0) {
output.append("\nGas Crit Damage Per Shot :: " + f.format(gas.critPerShot));
}
if (radiation.critPerShot > 0.0) {
output.append("\nRadiation Crit Damage Per Shot :: " + f.format(radiation.critPerShot));
}
if (corrosive.critPerShot > 0.0) {
output.append("\nCorrosive Crit Damage Per Shot :: " + f.format(corrosive.critPerShot));
}
if (viral.critPerShot > 0.0) {
output.append("\nViral Crit Damage Per Shot :: " + f.format(viral.critPerShot));
}
output.append("\nCrit Damage Per Shot to Clone Flesh :: " + f.format(cloneFlesh.critPerShot));
output.append("\nCrit Damage Per Shot to Ferrite Armor :: " + f.format(ferrite.critPerShot));
output.append("\nCrit Damage Per Shot to Alloy Armor :: " + f.format(alloy.critPerShot));
output.append("\nCrit Damage Per Shot to Mechanical :: " + f.format(mechanical.critPerShot));
output.append("\nCrit Damage Per Shot to Corpus Flesh :: " + f.format(corpusFlesh.critPerShot));
output.append("\nCrit Damage Per Shot to Shield :: " + f.format(shield.critPerShot));
output.append("\nCrit Damage Per Shot to Proto Shield :: " + f.format(protoShield.critPerShot));
output.append("\nCrit Damage Per Shot to Robotic :: " + f.format(robotic.critPerShot));
output.append("\nCrit Damage Per Shot to Infested Flesh :: " + f.format(infestedFlesh.critPerShot));
output.append("\nCrit Damage Per Shot to Fossilized :: " + f.format(fossilized.critPerShot));
output.append("\nCrit Damage Per Shot to Sinew :: " + f.format(sinew.critPerShot));
output.append("\nCrit Damage Per Shot to Corpus :: " + f.format(corpus.critPerShot));
output.append("\nCrit Damage Per Shot to Grineer :: " + f.format(grineer.critPerShot));
output.append("\nCrit Damage Per Shot to Infested :: " + f.format(infested.critPerShot));
output.append("\nCrit Damage Per Shot to Corrupted :: " + f.format(corrupted.critPerShot));
if (finalFirstShotDamageMult > 0) {
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw First Shot Damage :: " + f.format(raw.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
if (impact.firstShot > 0.0) {
output.append("\nImpact First Shot Damage :: " + f.format(impact.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (puncture.firstShot > 0.0) {
output.append("\nPuncture First Shot Damage :: " + f.format(puncture.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (slash.firstShot > 0.0) {
output.append("\nSlash First Shot Damage :: " + f.format(slash.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (fire.firstShot > 0.0) {
output.append("\nFire First Shot Damage :: " + f.format(fire.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (ice.firstShot > 0.0) {
output.append("\nIce First Shot Damage :: " + f.format(ice.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (electric.firstShot > 0.0) {
output.append("\nElectric First Shot Damage :: " + f.format(electric.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (toxin.firstShot > 0.0) {
output.append("\nToxin First Shot Damage :: " + f.format(toxin.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (blast.firstShot > 0.0) {
output.append("\nBlast First Shot Damage :: " + f.format(blast.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (magnetic.firstShot > 0.0) {
output.append("\nMagnetic First Shot Damage :: " + f.format(magnetic.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (gas.firstShot > 0.0) {
output.append("\nGas First Shot Damage :: " + f.format(gas.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (radiation.firstShot > 0.0) {
output.append("\nRadiation First Shot Damage :: " + f.format(radiation.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (corrosive.firstShot > 0.0) {
output.append("\nCorrosive First Shot Damage :: " + f.format(corrosive.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
if (viral.firstShot > 0.0) {
output.append("\nViral First Shot Damage :: " + f.format(viral.firstShot * (1 + finalFirstShotDamageMult) / finalFirstShotDamageMult));
}
output.append("\nFirst Shot Damage to Clone Flesh :: " + f.format(cloneFlesh.firstShot));
output.append("\nFirst Shot Damage to Ferrite Armor :: " + f.format(ferrite.firstShot));
output.append("\nFirst Shot Damage to Alloy Armor :: " + f.format(alloy.firstShot));
output.append("\nFirst Shot Damage to Mechanical :: " + f.format(mechanical.firstShot));
output.append("\nFirst Shot Damage to Corpus Flesh :: " + f.format(corpusFlesh.firstShot));
output.append("\nFirst Shot Damage to Shield :: " + f.format(shield.firstShot));
output.append("\nFirst Shot Damage to Proto Shield :: " + f.format(protoShield.firstShot));
output.append("\nFirst Shot Damage to Robotic :: " + f.format(robotic.firstShot));
output.append("\nFirst Shot Damage to Infested Flesh :: " + f.format(infestedFlesh.firstShot));
output.append("\nFirst Shot Damage to Fossilized :: " + f.format(fossilized.firstShot));
output.append("\nFirst Shot Damage to Sinew :: " + f.format(sinew.firstShot));
output.append("\nFirst Shot Damage to Corpus :: " + f.format(corpus.firstShot));
output.append("\nFirst Shot Damage to Grineer :: " + f.format(grineer.firstShot));
output.append("\nFirst Shot Damage to Infested :: " + f.format(infested.firstShot));
output.append("\nFirst Shot Damage to Corrupted :: " + f.format(corrupted.firstShot));
}
if (finalLastShotDamageMult > 0) {
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw Last Shot Damage :: " + f.format(raw.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
if (impact.lastShot > 0.0) {
output.append("\nImpact Last Shot Damage :: " + f.format(impact.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (puncture.lastShot > 0.0) {
output.append("\nPuncture Last Shot Damage :: " + f.format(puncture.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (slash.lastShot > 0.0) {
output.append("\nSlash Last Shot Damage :: " + f.format(slash.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (fire.lastShot > 0.0) {
output.append("\nFire Last Shot Damage :: " + f.format(fire.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (ice.lastShot > 0.0) {
output.append("\nIce Last Shot Damage :: " + f.format(ice.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (electric.lastShot > 0.0) {
output.append("\nElectric Last Shot Damage :: " + f.format(electric.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (toxin.lastShot > 0.0) {
output.append("\nToxin Last Shot Damage :: " + f.format(toxin.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (blast.lastShot > 0.0) {
output.append("\nBlast Last Shot Damage :: " + f.format(blast.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (magnetic.lastShot > 0.0) {
output.append("\nMagnetic Last Shot Damage :: " + f.format(magnetic.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (gas.lastShot > 0.0) {
output.append("\nGas Last Shot Damage :: " + f.format(gas.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (radiation.lastShot > 0.0) {
output.append("\nRadiation Last Shot Damage :: " + f.format(radiation.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (corrosive.lastShot > 0.0) {
output.append("\nCorrosive Last Shot Damage :: " + f.format(corrosive.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
if (viral.lastShot > 0.0) {
output.append("\nViral Last Shot Damage :: " + f.format(viral.lastShot * (1 + finalLastShotDamageMult) / finalLastShotDamageMult));
}
output.append("\nLast Shot Damage to Clone Flesh :: " + f.format(cloneFlesh.lastShot));
output.append("\nLast Shot Damage to Ferrite Armor :: " + f.format(ferrite.lastShot));
output.append("\nLast Shot Damage to Alloy Armor :: " + f.format(alloy.lastShot));
output.append("\nLast Shot Damage to Mechanical :: " + f.format(mechanical.lastShot));
output.append("\nLast Shot Damage to Corpus Flesh :: " + f.format(corpusFlesh.lastShot));
output.append("\nLast Shot Damage to Shield :: " + f.format(shield.lastShot));
output.append("\nLast Shot Damage to Proto Shield :: " + f.format(protoShield.lastShot));
output.append("\nLast Shot Damage to Robotic :: " + f.format(robotic.lastShot));
output.append("\nLast Shot Damage to Infested Flesh :: " + f.format(infestedFlesh.lastShot));
output.append("\nLast Shot Damage to Fossilized :: " + f.format(fossilized.lastShot));
output.append("\nLast Shot Damage to Sinew :: " + f.format(sinew.lastShot));
output.append("\nLast Shot Damage to Corpus :: " + f.format(corpus.lastShot));
output.append("\nLast Shot Damage to Grineer :: " + f.format(grineer.lastShot));
output.append("\nLast Shot Damage to Infested :: " + f.format(infested.lastShot));
output.append("\nLast Shot Damage to Corrupted :: " + f.format(corrupted.lastShot));
}
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw Damage Per Second :: " + f.format(raw.perSecond));
output.append("\nDamage Per Second to Clone Flesh :: " + f.format(cloneFlesh.perSecond));
output.append("\nDamage Per Second to Ferrite Armor :: " + f.format(ferrite.perSecond));
output.append("\nDamage Per Second to Alloy Armor :: " + f.format(alloy.perSecond));
output.append("\nDamage Per Second to Mechanical :: " + f.format(mechanical.perSecond));
output.append("\nDamage Per Second to Corpus Flesh :: " + f.format(corpusFlesh.perSecond));
output.append("\nDamage Per Second to Shield :: " + f.format(shield.perSecond));
output.append("\nDamage Per Second to Proto Shield :: " + f.format(protoShield.perSecond));
output.append("\nDamage Per Second to Robotic :: " + f.format(robotic.perSecond));
output.append("\nDamage Per Second to Infested Flesh :: " + f.format(infestedFlesh.perSecond));
output.append("\nDamage Per Second to Fossilized :: " + f.format(fossilized.perSecond));
output.append("\nDamage Per Second to Sinew :: " + f.format(sinew.perSecond));
output.append("\nDamage Per Second to Corpus :: " + f.format(corpus.perSecond));
output.append("\nDamage Per Second to Grineer :: " + f.format(grineer.perSecond));
output.append("\nDamage Per Second to Infested :: " + f.format(infested.perSecond));
output.append("\nDamage Per Second to Corrupted :: " + f.format(corrupted.perSecond));
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append("\nRaw Burst Damage Per Second :: " + f.format(raw.rawPerSecond));
output.append("\nBurst Damage Per Second to Clone Flesh :: " + f.format(cloneFlesh.rawPerSecond));
output.append("\nBurst Damage Per Second to Ferrite Armor :: " + f.format(ferrite.rawPerSecond));
output.append("\nBurst Damage Per Second to Alloy Armor :: " + f.format(alloy.rawPerSecond));
output.append("\nBurst Damage Per Second to Mechanical :: " + f.format(mechanical.rawPerSecond));
output.append("\nBurst Damage Per Second to Corpus Flesh :: " + f.format(corpusFlesh.rawPerSecond));
output.append("\nBurst Damage Per Second to Shield :: " + f.format(shield.rawPerSecond));
output.append("\nBurst Damage Per Second to Proto Shield :: " + f.format(protoShield.rawPerSecond));
output.append("\nBurst Damage Per Second to Robotic :: " + f.format(robotic.rawPerSecond));
output.append("\nBurst Damage Per Second to Infested Flesh :: " + f.format(infestedFlesh.rawPerSecond));
output.append("\nBurst Damage Per Second to Fossilized :: " + f.format(fossilized.rawPerSecond));
output.append("\nBurst Damage Per Second to Sinew :: " + f.format(sinew.rawPerSecond));
output.append("\nBurst Damage Per Second to Corpus :: " + f.format(corpus.rawPerSecond));
output.append("\nBurst Damage Per Second to Grineer :: " + f.format(grineer.rawPerSecond));
output.append("\nBurst Damage Per Second to Infested :: " + f.format(infested.rawPerSecond));
output.append("\nBurst Damage Per Second to Corrupted :: " + f.format(corrupted.rawPerSecond));
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
output.append(selectedWeapon.getModsOutput());
output.append("\nCorrosive Projections: " + corrosiveProjectionBox.getSelectedItem());
output.append("\nShieldDisruptions: " + shieldDisruptionBox.getSelectedItem());
if (useComplexTTK) {
output.append("\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
String ttkTableHeader = "\nTarget Name";
Font font = output.getFont();
FontMetrics metric = output.getFontMetrics(font);
int spaceWidth = metric.stringWidth(".");
int nameFieldWidth = metric.stringWidth(longestTTKName);
double nameDiff = (nameFieldWidth - metric.stringWidth("Target Name")) / spaceWidth;
nameDiff = Math.ceil(nameDiff);
nameDiff += 2;
for (int i = 0; i < nameDiff; i++) {
ttkTableHeader += ".";
}
ttkTableHeader += "|........TTK.......|....MinTTK.....|....MaxTTK";
output.append(ttkTableHeader);
String ttkTableSep = "\n";
spaceWidth = metric.stringWidth("-");
int headerWidth = metric.stringWidth(ttkTableHeader);
int headerLength = headerWidth / spaceWidth;
for (int i = 0; i < headerLength; i++) {
ttkTableSep += "-";
}
output.append(ttkTableSep);
int targetGroup = Integer.parseInt((String) targetGroupBox.getSelectedItem());
Vector<TTKTarget> groupTargets = new Vector<TTKTarget>();
for (TTKTarget target : theTTKManager.targets) {
if (target.groups.contains(targetGroup)) {
groupTargets.add(target);
}
}
// Vector<TTKNamePair> TTKGraphVec = new Vector<TTKNamePair>();
for (TTKTarget target : groupTargets) {
output.append(target.printAdvancedData());
// TTKGraphVec.add(target.getTTKNamePair());
}
}
}
/**
* Update the instant stats
*/
public static void updateStats() {
if (!setup) {
useComplexTTK = false;
updateOutput = false;
calculateDPS();
updateOutput = true;
DecimalFormat f = new DecimalFormat("#.###");
double totalmult = finalProjectileCount * averageCritMult * startingCombo * avgHit * finalDeadAimMult * COMult * viralMult * headShotMult * headShotBonus * (1 + (finalFirstShotDamageMult + finalLastShotDamageMult) / finalMag);
DPSPanel.impactField.setText(f.format(totalmult * (impact.finalBase + explosiveImpact.finalBase)));
DPSPanel.punctureField.setText(f.format(totalmult * (puncture.finalBase + explosivePuncture.finalBase)));
DPSPanel.slashField.setText(f.format(totalmult * (slash.finalBase + explosiveSlash.finalBase)));
DPSPanel.fireField.setText(f.format(totalmult * (fire.finalBase + explosiveFire.finalBase)));
DPSPanel.iceField.setText(f.format(totalmult * (ice.finalBase + explosiveIce.finalBase)));
DPSPanel.electricField.setText(f.format(totalmult * (electric.finalBase + explosiveElectric.finalBase)));
DPSPanel.toxinField.setText(f.format(totalmult * (toxin.finalBase + explosiveToxin.finalBase)));
DPSPanel.blastField.setText(f.format(totalmult * (blast.finalBase + explosiveBlast.finalBase)));
DPSPanel.magneticField.setText(f.format(totalmult * (magnetic.finalBase + explosiveMagnetic.finalBase)));
DPSPanel.gasField.setText(f.format(totalmult * (gas.finalBase + explosiveGas.finalBase)));
DPSPanel.radiationField.setText(f.format(totalmult * (radiation.finalBase + explosiveRadiation.finalBase)));
DPSPanel.corrosiveField.setText(f.format(totalmult * (corrosive.finalBase + explosiveCorrosive.finalBase)));
DPSPanel.viralField.setText(f.format(totalmult * (viral.finalBase + explosiveViral.finalBase)));
DPSPanel.projectilesField.setText(f.format(finalProjectileCount));
if (weaponMode.equals(Constants.CONTINUOUS)) {
DPSPanel.projectilesField.setText(f.format(1));
}
DPSPanel.FRField.setText(f.format(finalFireRate));
DPSPanel.CCField.setText(f.format(100 * (finalCritChance + finalComboCrit)) + "%");
DPSPanel.CDField.setText(f.format(finalCritMult));
DPSPanel.SCField.setText(f.format(100 * averageStatusChance) + "%");
DPSPanel.magField.setText(f.format(finalMag));
DPSPanel.reloadField.setText(f.format(finalReloadTime));
DPSPanel.damageField.setText(f.format(totalmult * (raw.finalBase + explosiveRaw.finalBase)));
DPSPanel.slashProcField.setText(f.format(bleedDoTDPS));
DPSPanel.toxinProcField.setText(f.format(poisonDoTDPS));
DPSPanel.gasProcField.setText(f.format(cloudDoTDPS));
DPSPanel.electricProcField.setText(f.format(electricProcDPS));
DPSPanel.fireProcField.setText(f.format(heatDoTDPS));
DPSPanel.burstField.setText(f.format(raw.rawPerSecond));
DPSPanel.sustainedField.setText(f.format(raw.perSecond));
DPSPanel.corpusField.setText(f.format(corpus.perSecond));
DPSPanel.grineerField.setText(f.format(grineer.perSecond));
DPSPanel.infestedField.setText(f.format(infested.perSecond));
DPSPanel.corruptedField.setText(f.format(corrupted.perSecond));
DPSPanel.impactChanceField.setText(f.format(averageStatusChance * 100 * (impactProcRate + explosiveImpactProcRate)) + "%");
DPSPanel.punctureChanceField.setText(f.format(averageStatusChance * 100 * (punctureProcRate + explosivePunctureProcRate)) + "%");
DPSPanel.slashChanceField.setText(f.format(averageStatusChance * 100 * (slashProcRate + explosiveSlashProcRate)) + "%");
DPSPanel.fireChanceField.setText(f.format(averageStatusChance * 100 * (fireProcRate + explosiveFireProcRate)) + "%");
DPSPanel.iceChanceField.setText(f.format(averageStatusChance * 100 * (iceProcRate + explosiveIceProcRate)) + "%");
DPSPanel.electricChanceField.setText(f.format(averageStatusChance * 100 * (electricProcRate + explosiveElectricProcRate)) + "%");
DPSPanel.toxinChanceField.setText(f.format(averageStatusChance * 100 * (toxinProcRate + explosiveToxinProcRate)) + "%");
DPSPanel.blastChanceField.setText(f.format(averageStatusChance * 100 * (blastProcRate + explosiveBlastProcRate)) + "%");
DPSPanel.magneticChanceField.setText(f.format(averageStatusChance * 100 * (magneticProcRate + explosiveMagneticProcRate)) + "%");
DPSPanel.gasChanceField.setText(f.format(averageStatusChance * 100 * (gasProcRate + explosiveGasProcRate)) + "%");
DPSPanel.radiationChanceField.setText(f.format(averageStatusChance * 100 * (radiationProcRate + explosiveRadiationProcRate)) + "%");
DPSPanel.corrosiveChanceField.setText(f.format(averageStatusChance * 100 * (corrosiveProcRate + explosiveCorrosiveProcRate)) + "%");
DPSPanel.viralChanceField.setText(f.format(averageStatusChance * 100 * (viralProcRate + explosiveViralProcRate)) + "%");
DPSPanel.burstPanel.setVisible(false);
DPSPanel.reloadPanel.setVisible(false);
DPSPanel.magPanel.setVisible(false);
DPSPanel.impactPanel.setVisible(false);
DPSPanel.puncturePanel.setVisible(false);
DPSPanel.slashPanel.setVisible(false);
DPSPanel.firePanel.setVisible(false);
DPSPanel.icePanel.setVisible(false);
DPSPanel.electricPanel.setVisible(false);
DPSPanel.toxinPanel.setVisible(false);
DPSPanel.blastPanel.setVisible(false);
DPSPanel.magneticPanel.setVisible(false);
DPSPanel.gasPanel.setVisible(false);
DPSPanel.radiationPanel.setVisible(false);
DPSPanel.corrosivePanel.setVisible(false);
DPSPanel.viralPanel.setVisible(false);
DPSPanel.slashProcPanel.setVisible(false);
DPSPanel.toxinProcPanel.setVisible(false);
DPSPanel.gasProcPanel.setVisible(false);
DPSPanel.electricProcPanel.setVisible(false);
DPSPanel.fireProcPanel.setVisible(false);
DPSPanel.impactChancePanel.setVisible(false);
DPSPanel.punctureChancePanel.setVisible(false);
DPSPanel.slashChancePanel.setVisible(false);
DPSPanel.fireChancePanel.setVisible(false);
DPSPanel.iceChancePanel.setVisible(false);
DPSPanel.electricChancePanel.setVisible(false);
DPSPanel.toxinChancePanel.setVisible(false);
DPSPanel.blastChancePanel.setVisible(false);
DPSPanel.magneticChancePanel.setVisible(false);
DPSPanel.gasChancePanel.setVisible(false);
DPSPanel.radiationChancePanel.setVisible(false);
DPSPanel.corrosiveChancePanel.setVisible(false);
DPSPanel.viralChancePanel.setVisible(false);
DPSPanel.corpusPanel.setVisible(false);
DPSPanel.grineerPanel.setVisible(false);
DPSPanel.infestedPanel.setVisible(false);
DPSPanel.corruptedPanel.setVisible(false);
if (!selectedWeapon.weaponType.equals(Constants.MELEE)) {
DPSPanel.reloadPanel.setVisible(true);
DPSPanel.magPanel.setVisible(true);
DPSPanel.burstPanel.setVisible(true);
}
if (impact.finalBase > 0 || explosiveImpact.finalBase > 0) {
DPSPanel.impactPanel.setVisible(true);
DPSPanel.impactChancePanel.setVisible(true);
}
if (puncture.finalBase > 0 || explosivePuncture.finalBase > 0) {
DPSPanel.puncturePanel.setVisible(true);
DPSPanel.punctureChancePanel.setVisible(true);
}
if (slash.finalBase > 0 || explosiveSlash.finalBase > 0) {
DPSPanel.slashPanel.setVisible(true);
DPSPanel.slashChancePanel.setVisible(true);
}
if (fire.finalBase > 0 || explosiveFire.finalBase > 0) {
DPSPanel.firePanel.setVisible(true);
DPSPanel.fireChancePanel.setVisible(true);
}
if (ice.finalBase > 0 || explosiveIce.finalBase > 0) {
DPSPanel.icePanel.setVisible(true);
DPSPanel.iceChancePanel.setVisible(true);
}
if (electric.finalBase > 0 || explosiveElectric.finalBase > 0) {
DPSPanel.electricPanel.setVisible(true);
DPSPanel.electricChancePanel.setVisible(true);
}
if (toxin.finalBase > 0 || explosiveToxin.finalBase > 0) {
DPSPanel.toxinPanel.setVisible(true);
DPSPanel.toxinChancePanel.setVisible(true);
}
if (blast.finalBase > 0 || explosiveBlast.finalBase > 0) {
DPSPanel.blastPanel.setVisible(true);
DPSPanel.blastChancePanel.setVisible(true);
}
if (magnetic.finalBase > 0 || explosiveMagnetic.finalBase > 0) {
DPSPanel.magneticPanel.setVisible(true);
DPSPanel.magneticChancePanel.setVisible(true);
}
if (gas.finalBase > 0 || explosiveGas.finalBase > 0) {
DPSPanel.gasPanel.setVisible(true);
DPSPanel.gasChancePanel.setVisible(true);
}
if (radiation.finalBase > 0 || explosiveRadiation.finalBase > 0) {
DPSPanel.radiationPanel.setVisible(true);
DPSPanel.radiationChancePanel.setVisible(true);
}
if (corrosive.finalBase > 0 || explosiveCorrosive.finalBase > 0) {
DPSPanel.corrosivePanel.setVisible(true);
DPSPanel.corrosiveChancePanel.setVisible(true);
}
if (viral.finalBase > 0 || explosiveViral.finalBase > 0) {
DPSPanel.viralPanel.setVisible(true);
DPSPanel.viralChancePanel.setVisible(true);
}
if (bleedDoTDPS > 0) {
DPSPanel.slashProcPanel.setVisible(true);
}
if (poisonDoTDPS > 0) {
DPSPanel.toxinProcPanel.setVisible(true);
}
if (cloudDoTDPS > 0) {
DPSPanel.gasProcPanel.setVisible(true);
}
if (electricProcDPS > 0) {
DPSPanel.electricProcPanel.setVisible(true);
}
if (heatDoTDPS > 0) {
DPSPanel.fireProcPanel.setVisible(true);
}
String faction = "";
Double factionMult = 1.0;
if (finalCorpusMult > 1) {
DPSPanel.corpusPanel.setVisible(true);
faction = "to Corpus";
factionMult = finalCorpusMult;
}
if (finalGrineerMult > 1) {
DPSPanel.grineerPanel.setVisible(true);
faction = "to Grineer";
factionMult = finalGrineerMult;
}
if (finalInfestedMult > 1) {
DPSPanel.infestedPanel.setVisible(true);
faction = "to Infested";
factionMult = finalInfestedMult;
}
if (finalCorruptedMult > 1) {
DPSPanel.corruptedPanel.setVisible(true);
faction = "to Infested";
factionMult = finalInfestedMult;
}
DPSPanel.slashProcField.setToolTipText(f.format(factionMult * factionMult * (bleedDoTDPS) / slashStacks) + " Damage per tick" + faction);
DPSPanel.toxinProcField.setToolTipText(f.format(factionMult * factionMult * (poisonDoTDPS) / toxinStacks) + " Damage per tick" + faction);
DPSPanel.gasProcField.setToolTipText(f.format(factionMult * factionMult * (cloudDoTDPS) / gasStacks) + " Damage per tick" + faction);
DPSPanel.fireProcField.setToolTipText(f.format(factionMult * factionMult * (heatDoTDPS) / fireStacks) + " Damage per tick" + faction);
}
useComplexTTK = true;
repack();
}
/**
* Method to display the mod manager
*/
protected static void displayModManager() {
if (!modManagerInit) {
modManagerInit = true;
theModManager.Init();
modManagerFrame.add(theModManager);
modManagerFrame.pack();
modManagerFrame.addWindowListener(new ModWindowListener());
modManagerFrame.setTitle("Mod Manager");
modManagerFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
modManagerFrame.setVisible(true);
}
/**
* Method to display the weapon manager
*/
protected static void displayWeaponManager() {
if (!weaponManagerInit) {
weaponManagerInit = true;
weaponManagerFrame.add(theWeaponManager);
weaponManagerFrame.pack();
weaponManagerFrame.addWindowListener(new WeaponWindowListener());
weaponManagerFrame.setTitle("Weapon Manager");
weaponManagerFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
weaponManagerFrame.setVisible(true);
}
/**
* Method to display the target manager
*/
protected static void displayTargetManager() {
if (!targetManagerInit) {
targetManagerInit = true;
targetManagerFrame.add(theTTKManager);
targetManagerFrame.pack();
targetManagerFrame.addWindowListener(new TTKWindowListener());
targetManagerFrame.setTitle("Target Manager");
targetManagerFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
targetManagerFrame.setVisible(true);
}
/**
* Method to display the color options manager
*/
protected static void displayColorOptions() {
if (!colorOptionsInit) {
colorOptionsInit = true;
colorOptionsFrame.add(theColorPanel);
colorOptionsFrame.pack();
colorOptionsFrame.setTitle("Color Options");
colorOptionsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
colorOptionsFrame.setVisible(true);
}
/**
* Method to display the stance manager
*/
protected static void displayStanceManager() {
if (!stanceManagerInit) {
stanceManagerInit = true;
stanceManagerFrame.add(theStanceManager);
stanceManagerFrame.pack();
stanceManagerFrame.addWindowListener(new StanceWindowListener());
stanceManagerFrame.setTitle("Stance Manager");
stanceManagerFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
stanceManagerFrame.setVisible(true);
}
/**
* Method to toggle the enabled state of the mod manager menu item
*/
protected static void updateModMenuState(boolean enabled) {
modMenu.setEnabled(enabled);
}
/**
* Method to toggle the enabled state of the target manager menu item
*/
protected static void updateTTKMenuState(boolean enabled) {
TTKMenu.setEnabled(enabled);
quickTargetButton.setEnabled(enabled);
removeTargetButton.setEnabled(enabled);
}
/**
* Method to toggle the enabled state of the weapon manager menu item
*/
protected static void updateWeaponMenuState(boolean enabled) {
weaponMenu.setEnabled(enabled);
}
/**
* Method to toggle the enabled state of the stance manager menu item
*/
protected static void updateStanceMenuState(boolean enabled) {
stanceMenu.setEnabled(enabled);
}
/**
* ____________________________________________________________ INTERNAL CLASSES
* ____________________________________________________________
*/
/**
* change Listener Local Class
*/
protected static class MainChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
updateStats();
}
}
/**
* Action Listener Local Class
*
* @author GottFuast
*
*/
public static class MainActionListener implements ActionListener {
/**
* Default CTOR
*/
public MainActionListener() {
// Do Nothing
}
/**
* Action Listener Callback
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(calculateButton)) {
updateOutput = true;
useComplexTTK = true;
calculateDPS();
} else if (e.getSource().equals(maximizeButton)) {
selectedWeapon = (WeaponPanel) weaponPane.getSelectedComponent();
loadingScreen.setVisible(true);
progressBar.setValue(0);
useComplexTTK = true;
updateOutput = false;
setup = true;
maxxing = true;
theMaximizer = new Maximizer();
new Thread(new Runnable() {
public void run() {
theMaximizer.Maximize();
loadingScreen.setVisible(false);
setup = false;
maxxing = false;
}
}).start();
} else if (e.getSource().equals(stopButton)) {
stop = true;
} else if (e.getSource().equals(quickTargetButton)) {
displayTargetManager();
updateTTKMenuState(false);
quickGroup = true;
theTTKManager.targetGroupPanel.setVisible(false);
theTTKManager.deleteButton.setVisible(false);
theTTKManager.saveButton.setVisible(false);
} else if (e.getSource().equals(removeTargetButton)) {
if (enemyList.getSelectedIndex() >= 0) {
String targetName = (String) enemyListModel.get(enemyList.getSelectedIndex());
TTKTarget selectedTarget = theTTKManager.getTargetByName(targetName);
TTKTarget foundTarget = theTTKManager.getTargetByName(targetName);
if (theTTKManager.targets.contains(selectedTarget)) {
for (int i = 0; i < selectedTarget.groups.size(); i++) {
if (selectedTarget.groups.get(i) == targetGroupBox.getSelectedIndex()) {
selectedTarget.groups.remove(i);
break;
}
}
theTTKManager.targets.set(theTTKManager.targets.indexOf(foundTarget), selectedTarget);
}
updateTargetList();
theTTKManager.updateTargetList();
}
} else if (e.getSource().equals(targetGroupBox)) {
updateTargetList();
} else if (e.getSource().equals(clearOutputButton)) {
output.setText("");
} else if (e.getSource().equals(headShots)) {
updateStats();
} else if (e.getSource().equals(loadItem)) {
int returnVal = chooser.showOpenDialog(mainPanel);
if (returnVal == JFileChooser.APPROVE_OPTION) {
setup = true;
riflePanel.clear();
shotgunPanel.clear();
pistolPanel.clear();
meleePanel.clear();
clearValues();
File file = chooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String header = reader.readLine();
reader.close();
if (header.equals(Constants.RIFLE)) {
weaponPane.setSelectedIndex(weaponPane.indexOfTab(Constants.RIFLE));
riflePanel.loadFromFile(file);
} else if (header.equals(Constants.PISTOL)) {
weaponPane.setSelectedIndex(weaponPane.indexOfTab(Constants.PISTOL));
pistolPanel.loadFromFile(file);
} else if (header.equals(Constants.SHOTGUN)) {
weaponPane.setSelectedIndex(weaponPane.indexOfTab(Constants.SHOTGUN));
shotgunPanel.loadFromFile(file);
} else if (header.equals(Constants.ARCHGUN)) {
weaponPane.setSelectedIndex(weaponPane.indexOfTab(Constants.ARCHGUN));
arcGunPanel.loadFromFile(file);
} else if (header.equals(Constants.MELEE)) {
weaponPane.setSelectedIndex(weaponPane.indexOfTab(Constants.MELEE));
meleePanel.loadFromFile(file);
}
} catch (Exception ex) {
// Do Nothing
}
setup = false;
updateStats();
} else {
// Do Nothing
}
} else if (e.getSource().equals(saveItem)) {
int returnVal = chooser.showSaveDialog(mainPanel);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getAbsolutePath().endsWith(".wdc")) {
file = new File(file.getAbsolutePath() + ".wdc");
}
WeaponPanel selected = (WeaponPanel) weaponPane.getSelectedComponent();
selected.saveToFile(file);
} else {
// Do Nothing
}
} else if (e.getSource().equals(modMenu)) {
displayModManager();
updateModMenuState(false);
} else if (e.getSource().equals(TTKMenu)) {
displayTargetManager();
updateTTKMenuState(false);
quickGroup = false;
theTTKManager.targetGroupPanel.setVisible(true);
theTTKManager.deleteButton.setVisible(true);
theTTKManager.saveButton.setVisible(true);
} else if (e.getSource().equals(weaponMenu)) {
displayWeaponManager();
updateWeaponMenuState(false);
} else if (e.getSource().equals(stanceMenu)) {
displayStanceManager();
updateStanceMenuState(false);
} else if (e.getSource().equals(colorOptionsItem)) {
displayColorOptions();
}
}
}
public static double getCorrosiveProjectionMult() {
double mult = 1.0 - (0.18 * Double.parseDouble((String) corrosiveProjectionBox.getSelectedItem()));
if (mult < 0.0) {
mult = 0.0;
}
return mult;
}
public static double getShieldDisruptionMult() {
double mult = 1.0 - (0.24 * Double.parseDouble((String) shieldDisruptionBox.getSelectedItem()));
return mult;
}
public static void repack() {
mainFrame.pack();
}
/**
* Window Listener Local Class
*
* @author GottFuast
*
*/
protected static class MainWindowListener implements WindowListener {
/**
* Default CTOR
*/
public MainWindowListener() {
// Do Nothing
}
/**
* Event to indicate that the window has closed
*/
public void windowClosed(WindowEvent e) {
System.exit(0);
}
/**
* Event to indicate taht the window is closing
*/
public void windowClosing(WindowEvent e) {
System.exit(0);
}
/**
* Unused
*/
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
/**
* Window Listener Local Class
*
* @author GottFaust
*
*/
protected static class ModWindowListener implements WindowListener {
/**
* Default CTOR
*/
public ModWindowListener() {
// Do Nothing
}
/**
* Event to indicate that the window has closed
*/
public void windowClosed(WindowEvent e) {
updateModMenuState(true);
}
/**
* Unused
*/
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
/**
* Window Listener Local Class
*
* @author GottFaust
*
*/
protected static class TTKWindowListener implements WindowListener {
/**
* Default CTOR
*/
public TTKWindowListener() {
// Do Nothing
}
/**
* Event to indicate that the window has closed
*/
public void windowClosed(WindowEvent e) {
updateTTKMenuState(true);
}
/**
* Unused
*/
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
/**
* Window Listener Local Class
*
* @author GottFaust
*
*/
protected static class WeaponWindowListener implements WindowListener {
/**
* Default CTOR
*/
public WeaponWindowListener() {
// Do Nothing
}
/**
* Event to indicate that the window has closed
*/
public void windowClosed(WindowEvent e) {
updateWeaponMenuState(true);
}
/**
* Unused
*/
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
protected static class StanceWindowListener implements WindowListener {
/**
* Default CTOR
*/
public StanceWindowListener() {
// Do Nothing
}
/**
* Event to indicate that the window has closed
*/
public void windowClosed(WindowEvent e) {
updateStanceMenuState(true);
}
/**
* Unused
*/
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
static BigInteger binomial(final int N, final int K) {
BigInteger ret = BigInteger.ONE;
for (int k = 0; k < K; k++) {
ret = ret.multiply(BigInteger.valueOf(N - k)).divide(BigInteger.valueOf(k + 1));
}
return ret;
}
static double replaceNaN(double n) {
if (Double.isNaN(n)) {
n = 1;
}
return n;
}
}
| GottFaust/WWDC | src/main/Main.java |
179,751 | package jnibwapi.model;
import java.awt.Point;
/**
* Represents a StarCraft player.
*
* For a description of fields see: http://code.google.com/p/bwapi/wiki/Player
*/
public class Player {
public static final int numAttributes = 11;
private final int ID;
private final int raceID;
private final int typeID;
private final int startLocationX;
private final int startLocationY;
private final boolean self;
private final boolean ally;
private final boolean enemy;
private final boolean neutral;
private final boolean observer;
private final int color;
private final String name;
private int minerals;
private int gas;
private int supplyUsed;
private int supplyTotal;
private int cumulativeMinerals;
private int cumulativeGas;
private int unitScore;
private int killScore;
private int buildingScore;
private int razingScore;
private boolean[] researching = null;
private boolean[] researched = null;
private boolean[] upgrading = null;
private int[] upgradeLevel = null;
public Player(int[] data, int index, String name) {
ID = data[index++];
raceID = data[index++];
typeID = data[index++];
startLocationX = data[index++];
startLocationY = data[index++];
self = (data[index++] == 1);
ally = (data[index++] == 1);
enemy = (data[index++] == 1);
neutral = (data[index++] == 1);
observer = (data[index++] == 1);
color = data[index++];
this.name = name;
}
public void update(int[] data) {
int index = 0;
minerals = data[index++];
gas = data[index++];
supplyUsed = data[index++];
supplyTotal = data[index++];
cumulativeMinerals = data[index++];
cumulativeGas = data[index++];
unitScore = data[index++];
killScore = data[index++];
buildingScore = data[index++];
razingScore = data[index++];
}
public void updateResearch(int[] researchData, int[] upgradeData) {
researched = new boolean[researchData.length / 2];
researching = new boolean[researchData.length / 2];
for (int i = 0; i < researchData.length; i += 2) {
researched[i / 2] = (researchData[i] == 1);
researching[i / 2] = (researchData[i + 1] == 1);
}
upgradeLevel = new int[upgradeData.length / 2];
upgrading = new boolean[upgradeData.length / 2];
for (int i = 0; i < upgradeData.length; i += 2) {
upgradeLevel[i / 2] = upgradeData[i];
upgrading[i / 2] = (upgradeData[i + 1] == 1);
}
}
public int getID() {
return ID;
}
public int getRaceID() {
return raceID;
}
public int getTypeID() {
return typeID;
}
/**
* Returns the starting tile position of the Player, or null if unknown (eg. for enemy players
* without complete map information).
*/
public Point getStartLocation() {
if (startLocationX == 1000) {
return null; // In the case of Invalid/None/Unknown TilePosition
}
return new Point(startLocationX, startLocationY);
}
public boolean isSelf() {
return self;
}
public boolean isAlly() {
return ally;
}
public boolean isEnemy() {
return enemy;
}
public boolean isNeutral() {
return neutral;
}
public boolean isObserver() {
return observer;
}
public int getColor() {
return color;
}
public String getName() {
return name;
}
public int getMinerals() {
return minerals;
}
public int getGas() {
return gas;
}
public int getSupplyUsed() {
return supplyUsed;
}
public int getSupplyTotal() {
return supplyTotal;
}
public int getCumulativeMinerals() {
return cumulativeMinerals;
}
public int getCumulativeGas() {
return cumulativeGas;
}
public int getUnitScore() {
return unitScore;
}
public int getKillScore() {
return killScore;
}
public int getBuildingScore() {
return buildingScore;
}
public int getRazingScore() {
return razingScore;
}
public boolean hasResearched(int techID) {
return (researched != null && techID < researched.length) ? researched[techID] : false;
}
public boolean isResearching(int techID) {
return (researching != null && techID < researching.length) ? researching[techID] : false;
}
public int upgradeLevel(int upgradeID) {
return (upgradeLevel != null && upgradeID < upgradeLevel.length) ?
upgradeLevel[upgradeID] : 0;
}
public boolean isUpgrading(int upgradeID) {
return (upgrading != null && upgradeID < upgrading.length) ? upgrading[upgradeID] : false;
}
}
| thieman/korhal-starter | jnibwapi/src/java/jnibwapi/model/Player.java |
179,752 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.infn.mw.voms.aa.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static it.infn.mw.voms.aa.VOMSResponse.Outcome.SUCCESS;
import static it.infn.mw.voms.aa.VOMSWarningMessage.shortenedAttributeValidity;
import java.time.Clock;
import java.time.Instant;
import java.util.Date;
import java.util.Optional;
import it.infn.mw.iam.persistence.model.IamAccount;
import it.infn.mw.voms.aa.AttributeAuthority;
import it.infn.mw.voms.aa.VOMSErrorMessage;
import it.infn.mw.voms.aa.VOMSRequest;
import it.infn.mw.voms.aa.VOMSRequestContext;
import it.infn.mw.voms.aa.VOMSResponse.Outcome;
import it.infn.mw.voms.properties.VomsProperties;
public class VOMSAAImpl implements AttributeAuthority {
private final IamVOMSAccountResolver accountResolver;
private final AttributeResolver attributeResolver;
private final VomsProperties vomsProperties;
private final Clock clock;
public VOMSAAImpl(IamVOMSAccountResolver accountResolver, AttributeResolver attributeResolver,
VomsProperties props, Clock clock) {
this.accountResolver = accountResolver;
this.attributeResolver = attributeResolver;
this.vomsProperties = props;
this.clock = clock;
}
protected void checkMembershipValidity(VOMSRequestContext context) {
IamAccount account = context.getIamAccount();
VOMSRequest r = context.getRequest();
if (!account.isActive()) {
failResponse(context,
VOMSErrorMessage.suspendedUser(r.getHolderSubject(), r.getHolderIssuer()));
context.setHandled(true);
}
}
private void handleRequestedValidity(VOMSRequestContext context) {
final long MAX_VALIDITY = vomsProperties.getAa().getMaxAcLifetimeInSeconds();
long validity = MAX_VALIDITY;
long requestedValidity = context.getRequest().getRequestedValidity();
if (requestedValidity > 0 && requestedValidity < MAX_VALIDITY) {
validity = requestedValidity;
}
if (requestedValidity > MAX_VALIDITY) {
context.getResponse().getWarnings().add(shortenedAttributeValidity(context.getVOName()));
}
Instant now = clock.instant();
Date startDate = Date.from(now);
Date endDate = Date.from(now.plusSeconds(validity));
context.getResponse().setNotAfter(endDate);
context.getResponse().setNotBefore(startDate);
}
private void requestSanityChecks(VOMSRequest request) {
checkNotNull(request);
checkNotNull(request.getRequesterSubject());
checkNotNull(request.getHolderSubject());
}
private void resolveAccount(VOMSRequestContext context) {
Optional<IamAccount> account = accountResolver.resolveAccountFromRequest(context);
if (account.isPresent()) {
context.setIamAccount(account.get());
} else {
VOMSErrorMessage m = VOMSErrorMessage.noSuchUser(context.getRequest().getHolderSubject(),
context.getRequest().getHolderIssuer());
context.getResponse().setOutcome(Outcome.FAILURE);
context.getResponse().getErrorMessages().add(m);
context.setHandled(true);
}
}
@Override
public boolean getAttributes(VOMSRequestContext context) {
requestSanityChecks(context.getRequest());
if (!context.isHandled()) {
resolveAccount(context);
}
if (!context.isHandled()) {
checkMembershipValidity(context);
}
if (!context.isHandled()) {
resolveFQANs(context);
resolveGAs(context);
}
if (!context.isHandled()) {
handleRequestedValidity(context);
}
context.setHandled(true);
return context.getResponse().getOutcome() == SUCCESS;
}
private void resolveFQANs(VOMSRequestContext context) {
attributeResolver.resolveFQANs(context);
}
private void resolveGAs(VOMSRequestContext context) {
attributeResolver.resolveGAs(context);
}
protected void failResponse(VOMSRequestContext context, VOMSErrorMessage em) {
context.getResponse().setOutcome(Outcome.FAILURE);
context.getResponse().getErrorMessages().add(em);
}
}
| indigo-iam/iam | iam-voms-aa/src/main/java/it/infn/mw/voms/aa/impl/VOMSAAImpl.java |
179,753 | package com.alphawallet.app.service;
import android.text.TextUtils;
import com.alphawallet.app.entity.EIP1559FeeOracleResult;
import com.alphawallet.app.repository.EthereumNetworkBase;
import com.alphawallet.app.repository.KeyProviderFactory;
import com.alphawallet.app.util.BalanceUtils;
import com.alphawallet.app.util.JsonUtils;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import io.reactivex.Single;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import timber.log.Timber;
public class BlockNativeGasAPI
{
public static BlockNativeGasAPI instance;
private final OkHttpClient httpClient;
public static BlockNativeGasAPI get(OkHttpClient httpClient)
{
if (instance == null)
{
instance = new BlockNativeGasAPI(httpClient);
}
return instance;
}
public BlockNativeGasAPI(OkHttpClient httpClient)
{
this.httpClient = httpClient;
}
private Request buildRequest(String api)
{
Request.Builder requestB = new Request.Builder()
.url(api)
.header("Content-Type", "application/json")
.addHeader("Authorization", KeyProviderFactory.get().getBlockNativeKey())
.get();
return requestB.build();
}
public Single<Map<Integer, EIP1559FeeOracleResult>> get1559GasEstimates(Map<Integer, EIP1559FeeOracleResult> result, long chainId)
{
if (result.size() > 0)
{
return Single.fromCallable(() -> result);
}
String oracleAPI = EthereumNetworkBase.getBlockNativeOracle(chainId);
return Single.fromCallable(() -> buildOracleResult(executeRequest(oracleAPI))); // any kind of error results in blank mapping,
// if blank, fall back to calculation method
}
private Map<Integer, EIP1559FeeOracleResult> buildOracleResult(String oracleReturn)
{
Map<Integer, EIP1559FeeOracleResult> results = new HashMap<>();
try
{
JSONObject prices = new JSONObject(oracleReturn);
//get base fee per gas
JSONArray blockPrices = prices.getJSONArray("blockPrices");
JSONObject blockPrice0 = blockPrices.getJSONObject(0);
String baseFeePerGasStr = blockPrice0.getString("baseFeePerGas");
BigDecimal baseFeePerGas = new BigDecimal(baseFeePerGasStr);
BigInteger baseFeePerGasWei = BalanceUtils.gweiToWei(baseFeePerGas);
//get the array
String estimatedPrices = blockPrice0.getJSONArray("estimatedPrices").toString();
PriceElement[] priceElements = new Gson().fromJson(estimatedPrices, PriceElement[].class);
results.put(0, new EIP1559FeeOracleResult(priceElements[0].getFeeOracleResult(baseFeePerGasWei)));
results.put(1, new EIP1559FeeOracleResult(priceElements[2].getFeeOracleResult(baseFeePerGasWei)));
results.put(2, new EIP1559FeeOracleResult(priceElements[3].getFeeOracleResult(baseFeePerGasWei)));
results.put(3, new EIP1559FeeOracleResult(priceElements[4].getFeeOracleResult(baseFeePerGasWei)));
}
catch (JSONException e)
{
// map will be empty; default to using backup calculation method
Timber.w(e);
}
return results;
}
private String executeRequest(String api)
{
if (!TextUtils.isEmpty(api))
{
try (okhttp3.Response response = httpClient.newCall(buildRequest(api)).execute())
{
if (response.isSuccessful())
{
ResponseBody responseBody = response.body();
if (responseBody != null)
{
return responseBody.string();
}
}
else
{
return Objects.requireNonNull(response.body()).string();
}
}
catch (Exception e)
{
Timber.e(e);
return e.getMessage();
}
}
return JsonUtils.EMPTY_RESULT;
}
private static class PriceElement
{
public String confidence;
public String price;
public String maxPriorityFeePerGas;
public String maxFeePerGas;
public BigInteger getMaxPriorityFeePerGasWei()
{
return elementToWei(maxPriorityFeePerGas);
}
public BigInteger getMaxFeePerGasWei()
{
return elementToWei(maxFeePerGas);
}
private BigInteger elementToWei(String value)
{
try
{
BigDecimal gweiValue = new BigDecimal(value);
return BalanceUtils.gweiToWei(gweiValue);
}
catch (Exception e)
{
return BigInteger.ZERO;
}
}
public EIP1559FeeOracleResult getFeeOracleResult(BigInteger baseFee)
{
return new EIP1559FeeOracleResult(getMaxFeePerGasWei(), getMaxPriorityFeePerGasWei(), baseFee);
}
}
}
| AlphaWallet/alpha-wallet-android | app/src/main/java/com/alphawallet/app/service/BlockNativeGasAPI.java |
179,755 | package edu.stanford.nlp.sempre.interactive;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Sets;
import org.testng.util.Strings;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import edu.stanford.nlp.sempre.Json;
import edu.stanford.nlp.sempre.JsonValue;
import fig.basic.IOUtils;
import fig.basic.LogInfo;
import fig.basic.MapUtils;
import fig.basic.Option;
import java.util.concurrent.ThreadLocalRandom;
/**
* Vega-specific code that loads the schema, colors, and generate paths and type maps
* @author sidaw
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class VegaResources {
public static class Options {
@Option(gloss = "File containing the vega schema") String vegaSchema;
@Option(gloss = "Path elements to exclude") Set<String> excludedPaths;
@Option(gloss = "File containing all the colors") String colorFile;
@Option(gloss = "File containing initial plot templates") String initialTemplates;
@Option int verbose = 0;
}
public static Options opts = new Options();
private final Path savePath = Paths.get(JsonMaster.opts.intOutputPath, "vegaResource");
public static VegaLitePathMatcher allPathsMatcher;
private static List<List<String>> filteredPaths;
private static List<JsonSchema> descendants;
public static JsonSchema vegaSchema;
private static Map<String, List<JsonValue>> typeToValues = new HashMap<>();
private static Map<String, Set<String>> enumValueToTypes;
private static Map<String, Set<List<String>>> enumValueToPaths;
private static Set<String> colorSet;
public static final Set<String> CHANNELS = Sets.newHashSet("x", "y", "color", "opacity", "shape", "size", "row", "column");
public static final Set<String> MARKS = Sets.newHashSet("area", "bar", "circle", "line", "point", "rect", "rule", "square", "text", "tick");
public static final Set<String> AGGREGATES = Sets.newHashSet("max", "mean", "min", "median", "sum");
static class InitialTemplate {
@JsonProperty("mark") public String mark;
@JsonProperty("encoding") public Map<String, String> encoding;
}
private static List<InitialTemplate> initialTemplates;
public VegaResources() {
try {
if (!Strings.isNullOrEmpty(opts.vegaSchema)) {
LogInfo.begin_track("Loading schemas from %s", opts.vegaSchema);
vegaSchema = JsonSchema.fromFile(new File(opts.vegaSchema));
LogInfo.end_track();
}
List<JsonSchema> allDescendants = vegaSchema.descendents();
descendants = allDescendants.stream().filter(s -> s.node().has("type")).collect(Collectors.toList());
LogInfo.logs("Got %d descendants, %d typed", allDescendants.size(), descendants.size());
filteredPaths = allSimplePaths(descendants);
LogInfo.logs("Got %d distinct simple path not containing %s", filteredPaths.size(), opts.excludedPaths);
allPathsMatcher = new VegaLitePathMatcher(filteredPaths);
Json.prettyWriteValueHard(new File(savePath.toString()+".path_elements.json"),
filteredPaths.stream()
.collect(Collectors.toSet()).stream().collect(Collectors.toList()) );
// generate valueToTypes and valueToSet, for enum types
generateValueMaps();
LogInfo.logs("gathering valueToTypes: %d distinct enum values", enumValueToTypes.size());
Json.prettyWriteValueHard(new File(savePath.toString()+".enums.json"),
enumValueToTypes.keySet().stream().collect(Collectors.toList())
);
Json.prettyWriteValueHard(new File(savePath.toString()+".enums-kv.json"),
enumValueToTypes.entrySet().stream().map(e -> {
return Lists.newArrayList(e.getKey(), e.getValue().stream().collect(Collectors.toList()));
}).collect(Collectors.toList())
);
if (!Strings.isNullOrEmpty(opts.colorFile)) {
colorSet = Json.readMapHard(String.join("\n", IOUtils.readLines(opts.colorFile))).keySet();
LogInfo.logs("loaded %d colors from %s", colorSet.size(), opts.colorFile);
}
if (!Strings.isNullOrEmpty(opts.initialTemplates)) {
initialTemplates = new ArrayList<>();
for (JsonNode node : Json.readValueHard(String.join("\n", IOUtils.readLines(opts.initialTemplates)), JsonNode.class)) {
initialTemplates.add(Json.getMapper().treeToValue(node, InitialTemplate.class));
}
LogInfo.logs("Read %d initial templates", initialTemplates.size());
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
private List<List<String>> allSimplePaths(List<JsonSchema> descendents) {
Set<List<String>> simplePaths = descendents.stream().map(s -> s.simplePath()).collect(Collectors.toSet());
LogInfo.logs("Got %d distinct simple paths", simplePaths.size());
Set<List<String>> filteredPaths = descendents.stream().map(s -> s.simplePath())
.filter(p -> p.stream().allMatch(s -> !opts.excludedPaths.contains(s)))
.collect(Collectors.toSet());
return Lists.newArrayList(filteredPaths);
}
private void generateValueMaps() {
Set<JsonSchema> descendentsSet = descendants.stream().collect(Collectors.toSet());
enumValueToTypes = new HashMap<>();
enumValueToPaths = new HashMap<>();
for (JsonSchema schema: descendentsSet) {
if (schema.enums() != null) {
for (String e : schema.enums()) {
MapUtils.addToSet(enumValueToTypes, e, schema.schemaTypes().get(0));
MapUtils.addToSet(enumValueToPaths, e, schema.simplePath());
}
}
}
}
public static boolean checkType(List<String> path, JsonValue value) {
JsonSchema jsonSchema = VegaResources.vegaSchema;
List<JsonSchema> pathSchemas = jsonSchema.schemas(path);
String stringValue = value.getJsonNode().asText();
for (JsonSchema schema : pathSchemas) {
String valueType = value.getSchemaType();
List<String> schemaTypes = schema.schemaTypes();
if (opts.verbose > 1)
LogInfo.logs("schema.simplePath: %s | schemaTypes: %s | valueType: %s", schema.simplePath(), schemaTypes, valueType);
for (String schemaType : schemaTypes) {
List<String> simplePath = schema.simplePath();
String last = simplePath.get(simplePath.size() - 1);
if (schemaType.equals("string") && (last.endsWith("color") || last.endsWith("Color")
|| last.equals("fill")
|| last.equals("stroke") || last.equals("background"))) {
if (valueType.equals("color"))
return true;
else return false;
}
if (schemaType.equals("string") && last.equals("field")) {
if (valueType.equals("field"))
return true;
else return false;
}
if (schemaType.equals("enum") && schema.enums().contains(stringValue))
return true;
if (valueType.equals(schemaType))
return true;
if (schemaType.equals(JsonSchema.NOTYPE))
throw new RuntimeException("JsonFn: schema has no type: " + schema);
}
}
return false;
}
public static List<JsonValue> getValues(List<String> path) {
List<JsonSchema> schemas = vegaSchema.schemas(path);
List<JsonValue> values = new ArrayList<>();
for (JsonSchema schema : schemas) {
for (String type : schema.schemaTypes()) {
if (opts.verbose > 0)
LogInfo.logs("getValues %s %s", type, path.toString());
if (type.equals(JsonSchema.NOTYPE))
return values;
else if (type.endsWith("enum")) {
for (String v : schema.enums())
values.add(new JsonValue(v).withSchemaType(type));
} else if (type.equals("boolean")) {
values.add(new JsonValue(true).withSchemaType("boolean"));
values.add(new JsonValue(false).withSchemaType("boolean"));
} else if (type.equals("number")) {
values.add(new JsonValue(ThreadLocalRandom.current().nextInt(0, 100)).withSchemaType("number"));
values.add(new JsonValue(0.1 * ThreadLocalRandom.current().nextInt(1, 10)).withSchemaType("number"));
} else if (type.equals("string")) {
values.add(new JsonValue("X").withSchemaType("string"));
}
}
}
return values;
}
public static Set<String> getEnumTypes(String value) {
if (enumValueToTypes.containsKey(value)) return enumValueToTypes.get(value);
return null;
}
public static Set<String> getColorSet() {
return colorSet;
}
public static List<InitialTemplate> getInitialTemplates() {
return initialTemplates;
}
}
| sidaw/sempre-interactive | src/edu/stanford/nlp/sempre/interactive/VegaResources.java |
179,756 | import java.math.BigInteger;
import java.util.Random;
/**
* The {@code RabinKarp} class finds the first occurrence of a pattern string
* in a text string.
* This implementation uses the Rabin-Karp algorithm.
*/
public class RabinKarp {
private String pat; // the pattern // needed only for Las Vegas
private long patHash; // pattern hash value
private int m; // pattern length
private long q; // a large prime, small enough to avoid long overflow
private int R; // radix
private long RM; // R^(M-1) % Q
/**
* Preprocesses the pattern string.
*
* @param pattern the pattern string
* @param R the alphabet size
*/
public RabinKarp(char[] pattern, int R) {
this.pat = String.valueOf(pattern);
this.R = R;
throw new UnsupportedOperationException("Operation not supported yet");
}
/**
* Preprocesses the pattern string.
*
* @param pat the pattern string
*/
public RabinKarp(String pat) {
this.pat = pat; // save pattern (needed only for Las Vegas)
R = 256;
m = pat.length();
q = longRandomPrime();
// precompute R^(m-1) % q for use in removing leading digit
RM = 1;
for (int i = 1; i <= m-1; i++)
RM = (R * RM) % q;
patHash = hash(pat, m);
}
// Compute hash for key[0..m-1].
private long hash(String key, int m) {
long h = 0;
for (int j = 0; j < m; j++)
h = (R * h + key.charAt(j)) % q;
return h;
}
// Las Vegas version: does pat[] match txt[i..i-m+1] ?
private boolean check(String txt, int i) {
for (int j = 0; j < m; j++)
if (pat.charAt(j) != txt.charAt(i + j))
return false;
return true;
}
// Monte Carlo version: always return true
// private boolean check(int i) {
// return true;
//}
/**
* Returns the index of the first occurrrence of the pattern string
* in the text string.
*
* @param txt the text string
* @return the index of the first occurrence of the pattern string
* in the text string; n if no such match
*/
public int search(String txt) {
int n = txt.length();
if (n < m) return n;
long txtHash = hash(txt, m);
// check for match at offset 0
if ((patHash == txtHash) && check(txt, 0))
return 0;
// check for hash match; if hash match, check for exact match
for (int i = m; i < n; i++) {
// Remove leading digit, add trailing digit, check for match.
txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q;
txtHash = (txtHash*R + txt.charAt(i)) % q;
// match
int offset = i - m + 1;
if ((patHash == txtHash) && check(txt, offset))
return offset;
}
// no match
return n;
}
// a random 31-bit prime
private static long longRandomPrime() {
BigInteger prime = BigInteger.probablePrime(31, new Random());
return prime.longValue();
}
/**
* Takes a pattern string and an input string as command-line arguments;
* searches for the pattern string in the text string; and prints
* the first occurrence of the pattern string in the text string.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String pat = args[0];
String txt = args[1];
RabinKarp searcher = new RabinKarp(pat);
int offset = searcher.search(txt);
// print results
StdOut.println("text: " + txt);
// from brute force search method 1
StdOut.print("pattern: ");
for (int i = 0; i < offset; i++)
StdOut.print(" ");
StdOut.println(pat);
}
} | mxc19912008/Key-Algorithms | Chapter 5 字符串 Strings/5.8 substring search (Rabin–Karp).java |
179,757 | /*
* Copyright (c) 2023 Team Galacticraft
*
* Licensed under the MIT license.
* See LICENSE file in the project root for details.
*/
package micdoodle8.mods.galacticraft.planets.mars.tile;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.Optional.Interface;
import net.minecraftforge.fml.relauncher.Side;
import micdoodle8.mods.miccore.Annotations.NetworkedField;
import micdoodle8.mods.galacticraft.annotations.ForRemoval;
import micdoodle8.mods.galacticraft.annotations.ReplaceWith;
import micdoodle8.mods.galacticraft.api.tile.IDisableableMachine;
import micdoodle8.mods.galacticraft.api.transmission.NetworkType;
import micdoodle8.mods.galacticraft.api.transmission.tile.IOxygenReceiver;
import micdoodle8.mods.galacticraft.api.transmission.tile.IOxygenStorage;
import micdoodle8.mods.galacticraft.api.vector.BlockVec3;
import micdoodle8.mods.galacticraft.core.GCFluids;
import micdoodle8.mods.galacticraft.core.energy.EnergyConfigHandler;
import micdoodle8.mods.galacticraft.core.energy.EnergyUtil;
import micdoodle8.mods.galacticraft.core.energy.item.ItemElectricBase;
import micdoodle8.mods.galacticraft.core.energy.tile.TileBaseElectricBlockWithInventory;
import micdoodle8.mods.galacticraft.core.fluid.FluidNetwork;
import micdoodle8.mods.galacticraft.core.fluid.NetworkHelper;
import micdoodle8.mods.galacticraft.core.tile.TileEntityOxygenStorageModule;
import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore;
import micdoodle8.mods.galacticraft.core.util.FluidUtil;
import micdoodle8.mods.galacticraft.core.wrappers.FluidHandlerWrapper;
import micdoodle8.mods.galacticraft.core.wrappers.IFluidHandlerWrapper;
import micdoodle8.mods.galacticraft.planets.asteroids.AsteroidsModule;
import micdoodle8.mods.galacticraft.planets.asteroids.items.ItemAtmosphericValve;
import micdoodle8.mods.galacticraft.planets.mars.blocks.BlockMachineMarsT2;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import mekanism.common.capabilities.Capabilities;
@Interface(iface = "mekanism.api.gas.IGasHandler", modid = "mekanism")
public class TileEntityElectrolyzer extends TileBaseElectricBlockWithInventory implements ISidedInventory, IDisableableMachine, IFluidHandlerWrapper, IOxygenStorage, IOxygenReceiver, IGasHandler
{
private final int tankCapacity = 4000;
@NetworkedField(targetSide = Side.CLIENT)
public FluidTank waterTank = new FluidTank(this.tankCapacity);
@NetworkedField(targetSide = Side.CLIENT)
public FluidTank liquidTank = new FluidTank(this.tankCapacity);
@NetworkedField(targetSide = Side.CLIENT)
public FluidTank liquidTank2 = new FluidTank(this.tankCapacity);
public int processTimeRequired = 3;
@NetworkedField(targetSide = Side.CLIENT)
public int processTicks = 0;
public TileEntityElectrolyzer()
{
super("tile.mars_machine.6.name");
this.storage.setMaxExtract(ConfigManagerCore.hardMode ? 150 : 120);
this.setTierGC(2);
this.inventory = NonNullList.withSize(4, ItemStack.EMPTY);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)
return true;
if (EnergyUtil.checkMekGasHandler(capability))
return true;
return super.hasCapability(capability, facing);
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)
{
return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(new FluidHandlerWrapper(this, facing));
}
if (EnergyUtil.checkMekGasHandler(capability))
{
return Capabilities.GAS_HANDLER_CAPABILITY.cast(this);
}
return super.getCapability(capability, facing);
}
@Override
public void update()
{
super.update();
if (!this.world.isRemote)
{
final FluidStack liquid = FluidUtil.getFluidContained(this.getInventory().get(1));
if (FluidUtil.isFluidStrict(liquid, FluidRegistry.WATER.getName()))
{
FluidUtil.loadFromContainer(waterTank, FluidRegistry.WATER, this.getInventory(), 1, liquid.amount);
}
// Only drain with atmospheric valve
checkFluidTankTransfer(2, this.liquidTank);
checkFluidTankTransfer(3, this.liquidTank2);
if (this.hasEnoughEnergyToRun && this.canProcess())
{
// 50% extra speed boost for Tier 2 machine if powered by Tier 2
// power
if (this.tierGC == 2)
{
this.processTimeRequired = Math.max(1, 4 - this.poweredByTierGC);
}
if (this.processTicks == 0)
{
this.processTicks = this.processTimeRequired;
}
else
{
if (--this.processTicks <= 0)
{
this.doElectrolysis();
this.processTicks = this.canProcess() ? this.processTimeRequired : 0;
}
}
}
else
{
this.processTicks = 0;
}
this.produceOxygen(this.getOxygenOutputDirection());
this.produceHydrogen(this.getHydrogenOutputDirection());
}
}
private void doElectrolysis()
{
// Can't be called if the gasTank fluid is null
final int waterAmount = this.waterTank.getFluid().amount;
if (waterAmount == 0)
{
return;
}
this.placeIntoFluidTanks(2);
this.waterTank.drain(1, true);
}
private int placeIntoFluidTanks(int amountToDrain)
{
final int fuelSpace = this.liquidTank.getCapacity() - this.liquidTank.getFluidAmount();
final int fuelSpace2 = this.liquidTank2.getCapacity() - this.liquidTank2.getFluidAmount();
int amountToDrain2 = amountToDrain * 2;
if (amountToDrain > fuelSpace)
{
amountToDrain = fuelSpace;
}
this.liquidTank.fill(FluidRegistry.getFluidStack("oxygen", amountToDrain), true);
if (amountToDrain2 > fuelSpace2)
{
amountToDrain2 = fuelSpace2;
}
this.liquidTank2.fill(FluidRegistry.getFluidStack("hydrogen", amountToDrain2), true);
return amountToDrain;
}
private void checkFluidTankTransfer(int slot, FluidTank tank)
{
if (!this.getInventory().get(slot).isEmpty() && this.getInventory().get(slot).getItem() instanceof ItemAtmosphericValve)
{
tank.drain(4, true);
}
}
public int getScaledGasLevel(int i)
{
return this.waterTank.getFluid() != null ? this.waterTank.getFluid().amount * i / this.waterTank.getCapacity() : 0;
}
public int getScaledFuelLevel(int i)
{
return this.liquidTank.getFluid() != null ? this.liquidTank.getFluid().amount * i / this.liquidTank.getCapacity() : 0;
}
public int getScaledFuelLevel2(int i)
{
return this.liquidTank2.getFluid() != null ? this.liquidTank2.getFluid().amount * i / this.liquidTank2.getCapacity() : 0;
}
public boolean canProcess()
{
if (this.waterTank.getFluid() == null || this.waterTank.getFluid().amount <= 0 || this.getDisabled(0))
{
return false;
}
boolean tank1HasSpace = this.liquidTank.getFluidAmount() < this.liquidTank.getCapacity();
boolean tank2HasSpace = this.liquidTank2.getFluidAmount() < this.liquidTank2.getCapacity();
return tank1HasSpace || tank2HasSpace;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.processTicks = nbt.getInteger("processTicks");
if (nbt.hasKey("waterTank"))
{
this.waterTank.readFromNBT(nbt.getCompoundTag("waterTank"));
}
if (nbt.hasKey("gasTank"))
{
this.liquidTank.readFromNBT(nbt.getCompoundTag("gasTank"));
}
if (nbt.hasKey("gasTank2"))
{
this.liquidTank2.readFromNBT(nbt.getCompoundTag("gasTank2"));
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setInteger("processTicks", this.processTicks);
if (this.waterTank.getFluid() != null)
{
nbt.setTag("waterTank", this.waterTank.writeToNBT(new NBTTagCompound()));
}
if (this.liquidTank.getFluid() != null)
{
nbt.setTag("gasTank", this.liquidTank.writeToNBT(new NBTTagCompound()));
}
if (this.liquidTank2.getFluid() != null)
{
nbt.setTag("gasTank2", this.liquidTank2.writeToNBT(new NBTTagCompound()));
}
return nbt;
}
@Override
public boolean hasCustomName()
{
return true;
}
// ISidedInventory Implementation:
@Override
public int[] getSlotsForFace(EnumFacing side)
{
return new int[] {0, 1};
}
@Override
public boolean canInsertItem(int slotID, ItemStack itemstack, EnumFacing side)
{
if (this.isItemValidForSlot(slotID, itemstack))
{
switch (slotID)
{
case 0:
return ItemElectricBase.isElectricItemCharged(itemstack);
case 1:
return itemstack.getItem() == Items.WATER_BUCKET;
default:
return false;
}
}
return false;
}
@Override
public boolean canExtractItem(int slotID, ItemStack itemstack, EnumFacing side)
{
if (this.isItemValidForSlot(slotID, itemstack))
{
switch (slotID)
{
case 0:
return ItemElectricBase.isElectricItemEmpty(itemstack);
case 1:
return itemstack.getItem() == Items.BUCKET;
default:
return false;
}
}
return false;
}
@Override
public boolean isItemValidForSlot(int slotID, ItemStack itemstack)
{
Item item = itemstack.getItem();
switch (slotID)
{
case 0:
return ItemElectricBase.isElectricItem(item);
case 1:
return item == Items.BUCKET || item == Items.WATER_BUCKET;
}
return false;
}
@Override
public boolean shouldUseEnergy()
{
return this.canProcess();
}
@Override
public double getPacketRange()
{
return 320.0D;
}
@Override
public EnumFacing getElectricInputDirection()
{
return EnumFacing.DOWN;
}
@Override
public boolean canDrain(EnumFacing from, Fluid fluid)
{
if (from == this.getHydrogenOutputDirection())
{
return this.liquidTank2.getFluid() != null && this.liquidTank2.getFluidAmount() > 0;
}
if (from == this.getOxygenOutputDirection())
{
return this.liquidTank.getFluid() != null && this.liquidTank.getFluidAmount() > 0;
}
return false;
}
@Override
public FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain)
{
if (from == this.getHydrogenOutputDirection())
{
if (resource != null && resource.isFluidEqual(this.liquidTank2.getFluid()))
{
return this.liquidTank2.drain(resource.amount, doDrain);
}
}
if (from == this.getOxygenOutputDirection())
{
if (resource != null && resource.isFluidEqual(this.liquidTank.getFluid()))
{
return this.liquidTank.drain(resource.amount, doDrain);
}
}
return null;
}
@Override
public FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain)
{
if (from == this.getHydrogenOutputDirection())
{
return this.liquidTank2.drain(maxDrain, doDrain);
}
if (from == this.getOxygenOutputDirection())
{
return this.liquidTank.drain(maxDrain, doDrain);
}
return null;
}
@Override
public boolean canFill(EnumFacing from, Fluid fluid)
{
if (from == this.byIndex().rotateY())
{
// Can fill with water
return fluid == null || fluid.getName().equals(FluidRegistry.WATER.getName());
}
return false;
}
@Override
public int fill(EnumFacing from, FluidStack resource, boolean doFill)
{
int used = 0;
if (resource != null && this.canFill(from, resource.getFluid()))
{
used = this.waterTank.fill(resource, doFill);
}
return used;
}
@Override
public FluidTankInfo[] getTankInfo(EnumFacing from)
{
FluidTankInfo[] tankInfo = new FluidTankInfo[] {};
if (from == this.byIndex().rotateY())
{
tankInfo = new FluidTankInfo[] {new FluidTankInfo(this.waterTank)};
}
else if (from == this.getHydrogenOutputDirection())
{
tankInfo = new FluidTankInfo[] {new FluidTankInfo(this.liquidTank2)};
}
else if (from == this.getOxygenOutputDirection())
{
tankInfo = new FluidTankInfo[] {new FluidTankInfo(this.liquidTank)};
}
return tankInfo;
}
@Override
public int getBlockMetadata()
{
return getBlockType().getMetaFromState(this.world.getBlockState(getPos()));
}
@Override
@Optional.Method(modid = "mekanism")
public int receiveGas(EnumFacing side, GasStack stack, boolean doTransfer)
{
return 0;
}
@Optional.Method(modid = "mekanism")
public int receiveGas(EnumFacing side, GasStack stack)
{
return 0;
}
@Override
@Optional.Method(modid = "mekanism")
public GasStack drawGas(EnumFacing from, int amount, boolean doTransfer)
{
if (from == this.getHydrogenOutputDirection() && this.liquidTank2.getFluid() != null)
{
int amountH = Math.min(8, this.liquidTank2.getFluidAmount());
amountH = this.liquidTank2.drain(amountH, doTransfer).amount;
return new GasStack((Gas) EnergyConfigHandler.gasHydrogen, amountH);
}
else if (from == this.getOxygenOutputDirection() && this.liquidTank.getFluid() != null)
{
int amountO = Math.min(8, this.liquidTank.getFluidAmount());
amountO = this.liquidTank.drain(amountO, doTransfer).amount;
return new GasStack((Gas) EnergyConfigHandler.gasOxygen, amountO);
}
return null;
}
@Optional.Method(modid = "mekanism")
public GasStack drawGas(EnumFacing from, int amount)
{
return this.drawGas(from, amount, true);
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canReceiveGas(EnumFacing side, Gas type)
{
return false;
}
@Override
@Optional.Method(modid = "mekanism")
public boolean canDrawGas(EnumFacing from, Gas type)
{
if (from == this.getHydrogenOutputDirection())
{
return type.getName().equals("hydrogen");
}
else if (from == this.getOxygenOutputDirection())
{
return type.getName().equals("oxygen");
}
return false;
}
@Optional.Method(modid = "mekanism")
public boolean canTubeConnect(EnumFacing from)
{
if (from == this.getHydrogenOutputDirection())
{
return true;
}
else if (from == this.getOxygenOutputDirection())
{
return true;
}
return false;
}
@Override
public void setOxygenStored(int amount)
{
this.liquidTank.setFluid(new FluidStack(AsteroidsModule.fluidOxygenGas, amount));
}
@Override
public int getOxygenStored()
{
return this.liquidTank.getFluidAmount();
}
public int getHydrogenStored()
{
return this.liquidTank2.getFluidAmount();
}
@Override
public int getMaxOxygenStored()
{
return this.liquidTank.getCapacity();
}
private EnumFacing getOxygenOutputDirection()
{
return this.byIndex().getOpposite();
}
private EnumFacing getHydrogenOutputDirection()
{
return this.byIndex().rotateYCCW();
}
private boolean produceOxygen(EnumFacing outputDirection)
{
int provide = this.getOxygenProvide(outputDirection);
if (provide > 0)
{
TileEntity outputTile = new BlockVec3(this).modifyPositionFromSide(outputDirection).getTileEntity(this.world);
FluidNetwork outputNetwork = NetworkHelper.getFluidNetworkFromTile(outputTile, outputDirection);
if (outputNetwork != null)
{
int gasRequested = outputNetwork.getRequest();
if (gasRequested > 0)
{
int usedGas = outputNetwork.emitToBuffer(new FluidStack(GCFluids.fluidOxygenGas, Math.min(gasRequested, provide)), true);
this.drawOxygen(usedGas, true);
return true;
}
}
else if (outputTile instanceof IOxygenReceiver)
{
float requestedOxygen = ((IOxygenReceiver) outputTile).getOxygenRequest(outputDirection.getOpposite());
if (requestedOxygen > 0)
{
int toSend = Math.min(this.getOxygenStored(), provide);
int acceptedOxygen = ((IOxygenReceiver) outputTile).receiveOxygen(outputDirection.getOpposite(), toSend, true);
this.drawOxygen(acceptedOxygen, true);
return true;
}
}
}
return false;
}
private boolean produceHydrogen(EnumFacing outputDirection)
{
int provide = this.getHydrogenProvide(outputDirection);
if (provide > 0)
{
TileEntity outputTile = new BlockVec3(this).modifyPositionFromSide(outputDirection).getTileEntity(this.world);
FluidNetwork outputNetwork = NetworkHelper.getFluidNetworkFromTile(outputTile, outputDirection);
if (outputNetwork != null)
{
int gasRequested = outputNetwork.getRequest();
if (gasRequested > 0)
{
int usedGas = outputNetwork.emitToBuffer(new FluidStack(FluidRegistry.getFluid("hydrogen"), Math.min(gasRequested, provide)), true);
this.drawHydrogen(usedGas, true);
return true;
}
}
else if (outputTile instanceof TileEntityMethaneSynthesizer)
{
float requestedHydrogen = ((TileEntityMethaneSynthesizer) outputTile).getHydrogenRequest(outputDirection.getOpposite());
if (requestedHydrogen > 0)
{
int toSend = Math.min(this.getHydrogenStored(), provide);
int acceptedHydrogen = ((TileEntityMethaneSynthesizer) outputTile).receiveHydrogen(outputDirection.getOpposite(), toSend, true);
this.drawHydrogen(acceptedHydrogen, true);
return true;
}
}
}
return false;
}
@Override
public int provideOxygen(EnumFacing from, int request, boolean doProvide)
{
if (this.getOxygenOutputDirection() == from)
{
return this.drawOxygen(request, doProvide);
}
return 0;
}
public int drawOxygen(int request, boolean doProvide)
{
if (request > 0)
{
int requestedOxygen = Math.min(request, this.liquidTank.getFluidAmount());
if (doProvide)
{
this.setOxygenStored(this.liquidTank.getFluidAmount() - requestedOxygen);
}
return requestedOxygen;
}
return 0;
}
public int drawHydrogen(int request, boolean doProvide)
{
if (request > 0)
{
int currentHydrogen = this.liquidTank2.getFluidAmount();
int requestedHydrogen = Math.min(request, currentHydrogen);
if (doProvide)
{
this.liquidTank2.setFluid(new FluidStack(FluidRegistry.getFluid("hydrogen"), currentHydrogen - requestedHydrogen));
}
return requestedHydrogen;
}
return 0;
}
@Override
public int getOxygenProvide(EnumFacing direction)
{
return this.getOxygenOutputDirection() == direction ? Math.min(TileEntityOxygenStorageModule.OUTPUT_PER_TICK, this.getOxygenStored()) : 0;
}
public int getHydrogenProvide(EnumFacing direction)
{
return this.getHydrogenOutputDirection() == direction ? Math.min(TileEntityOxygenStorageModule.OUTPUT_PER_TICK, this.getHydrogenStored()) : 0;
}
@Override
public boolean shouldPullOxygen()
{
return false;
}
@Override
public int receiveOxygen(EnumFacing from, int receive, boolean doReceive)
{
return 0;
}
@Override
public int getOxygenRequest(EnumFacing direction)
{
return 0;
}
@Override
public boolean canConnect(EnumFacing direction, NetworkType type)
{
if (direction == null)
{
return false;
}
if (type == NetworkType.FLUID)
{
return this.getOxygenOutputDirection() == direction || this.getHydrogenOutputDirection() == direction || direction == this.byIndex().rotateY();
}
if (type == NetworkType.POWER)
{
return direction == this.getElectricInputDirection();
}
return false;
}
@Override
public EnumFacing byIndex()
{
IBlockState state = this.world.getBlockState(getPos());
if (state.getBlock() instanceof BlockMachineMarsT2)
{
return state.getValue(BlockMachineMarsT2.FACING);
}
return EnumFacing.NORTH;
}
@Override
@Deprecated
@ForRemoval(deadline = "4.1.0")
@ReplaceWith("byIndex()")
public EnumFacing getFront()
{
return this.byIndex();
}
}
| TeamGalacticraft/Galacticraft-Legacy | src/main/java/micdoodle8/mods/galacticraft/planets/mars/tile/TileEntityElectrolyzer.java |
179,758 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.apache.phoenix.util.TestUtil.analyzeTable;
import static org.apache.phoenix.util.TestUtil.getAllSplits;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;
import org.apache.phoenix.jdbc.PhoenixResultSet;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ParallelStatsEnabledTest.class)
public class TenantSpecificTablesDMLIT extends BaseTenantSpecificTablesIT {
@Test
public void testSelectWithLimit() throws Exception {
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, PropertiesUtil.deepCopy(TEST_PROPERTIES));
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM " + TENANT_TABLE_NAME + " LIMIT 100");
while(rs.next()) {}
}
@Test
public void testPointLookupOnBaseTable() throws Exception {
final String tableName = "T_" + generateUniqueName();
final String viewName = "V_" + generateUniqueName();
final String tenantId = "tenant1";
final String kp = "abc";
String ddl = String.format("CREATE TABLE %s (ORG_ID CHAR(15) NOT NULL, KP CHAR(3) NOT NULL, V1 INTEGER, V2 VARCHAR," +
"CONSTRAINT PK PRIMARY KEY(ORG_ID, KP)) MULTI_TENANT=true", tableName);
int nRows = 16;
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement().execute(ddl);
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
try (Connection tconn = DriverManager.getConnection(getUrl(), props)) {
ddl = String.format("CREATE VIEW %s (PK1 VARCHAR PRIMARY KEY, V3 VARCHAR)" +
" AS SELECT * FROM %s WHERE KP='%s'", viewName, tableName, kp);
tconn.createStatement().execute(ddl);
tconn.commit();
// upsert through the tenant
try(PreparedStatement ps = tconn.prepareStatement(
String.format("UPSERT INTO %s(V1,V2,PK1,V3) VALUES (?, ?, ?, ?)", viewName))) {
for (int i = 0; i < nRows; i++) {
ps.setInt(1, i); // V1
ps.setString(2, "v2"); // V2
ps.setString(3, "pk_" + i); // PK1
ps.setString(4, "v3"); // V3
ps.executeUpdate();
}
tconn.commit();
}
}
// Do a point lookup on the base table
String dql = String.format("SELECT * FROM %s where org_id='%s' AND kp='%s' LIMIT 1",
tableName, tenantId, kp);
try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
assertTrue(explainPlan.contains("POINT LOOKUP ON 1 KEY"));
assertTrue(rs.next());
assertEquals(tenantId, rs.getString(1));
assertEquals(kp, rs.getString(2));
}
dql = String.format("SELECT count(*) FROM %s where org_id='%s' AND kp='%s'",
tableName, tenantId, kp);
try (ResultSet rs = conn.createStatement().executeQuery(dql)) {
PhoenixResultSet prs = rs.unwrap(PhoenixResultSet.class);
String explainPlan = QueryUtil.getExplainPlan(prs.getUnderlyingIterator());
assertTrue(explainPlan.contains("POINT LOOKUP ON 1 KEY"));
assertTrue(rs.next());
assertEquals(nRows, rs.getInt(1));
}
}
}
@Test
public void testBasicUpsertSelect() throws Exception {
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, PropertiesUtil.deepCopy(TEST_PROPERTIES));
try {
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (1, 'Cheap Sunglasses')");
conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (2, 'Viva Las Vegas')");
conn.commit();
analyzeTable(conn, TENANT_TABLE_NAME);
ResultSet rs = conn.createStatement().executeQuery("select tenant_col from " + TENANT_TABLE_NAME + " where id = 1");
assertTrue("Expected 1 row in result set", rs.next());
assertEquals("Cheap Sunglasses", rs.getString(1));
assertFalse("Expected 1 row in result set", rs.next());
}
finally {
conn.close();
}
}
@Test
public void testBasicUpsertSelect2() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL2, TENANT_TABLE_DDL);
Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL2, props);
try {
conn1.setAutoCommit(false);
conn1.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " values ('me','" + TENANT_TYPE_ID + "',1,'Cheap Sunglasses')");
conn1.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " values ('you','" + TENANT_TYPE_ID +"',2,'Viva Las Vegas')");
conn1.commit();
analyzeTable(conn1, TENANT_TABLE_NAME);
conn2.setAutoCommit(true);
conn2.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " values ('them','" + TENANT_TYPE_ID + "',1,'Long Hair')");
conn2.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " values ('us','" + TENANT_TYPE_ID + "',2,'Black Hat')");
ResultSet rs = conn1.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME + " where id = 1");
assertTrue("Expected 1 row in result set", rs.next());
assertEquals(1, rs.getInt(3));
assertEquals("Cheap Sunglasses", rs.getString(4));
assertFalse("Expected 1 row in result set", rs.next());
analyzeTable(conn2, TENANT_TABLE_NAME);
rs = conn2.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME + " where id = 2");
assertTrue("Expected 1 row in result set", rs.next());
assertEquals(2, rs.getInt(3));
assertEquals("Black Hat", rs.getString(4));
assertFalse("Expected 1 row in result set", rs.next());
analyzeTable(conn1, TENANT_TABLE_NAME);
conn2.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " select * from " + TENANT_TABLE_NAME );
conn2.commit();
rs = conn2.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME);
assertTrue("Expected row in result set", rs.next());
assertEquals(1, rs.getInt(3));
assertEquals("Long Hair", rs.getString(4));
assertTrue("Expected row in result set", rs.next());
assertEquals(2, rs.getInt(3));
assertEquals("Black Hat", rs.getString(4));
assertFalse("Expected 2 rows total", rs.next());
conn2.setAutoCommit(true);;
conn2.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " select 'all', tenant_type_id, id, 'Big ' || tenant_col from " + TENANT_TABLE_NAME );
analyzeTable(conn2, TENANT_TABLE_NAME);
rs = conn2.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME);
assertTrue("Expected row in result set", rs.next());
assertEquals("all", rs.getString(1));
assertEquals(TENANT_TYPE_ID, rs.getString(2));
assertEquals(1, rs.getInt(3));
assertEquals("Big Long Hair", rs.getString(4));
assertTrue("Expected row in result set", rs.next());
assertEquals("all", rs.getString(1));
assertEquals(TENANT_TYPE_ID, rs.getString(2));
assertEquals(2, rs.getInt(3));
assertEquals("Big Black Hat", rs.getString(4));
assertFalse("Expected 2 rows total", rs.next());
rs = conn1.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME);
assertTrue("Expected row row in result set", rs.next());
assertEquals(1, rs.getInt(3));
assertEquals("Cheap Sunglasses", rs.getString(4));
assertTrue("Expected 1 row in result set", rs.next());
assertEquals(2, rs.getInt(3));
assertEquals("Viva Las Vegas", rs.getString(4));
List<KeyRange> splits = getAllSplits(conn1, TENANT_TABLE_NAME);
assertEquals(3, splits.size());
}
finally {
conn1.close();
conn2.close();
}
}
@Test
public void testJoinWithGlobalTable() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.createStatement().execute("create table foo (k INTEGER NOT NULL PRIMARY KEY)");
conn.createStatement().execute("upsert into foo(k) values(1)");
conn.commit();
conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (1, 'Cheap Sunglasses')");
conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (2, 'Viva Las Vegas')");
conn.commit();
analyzeTable(conn, TENANT_TABLE_NAME);
ResultSet rs = conn.createStatement().executeQuery("select tenant_col from " + TENANT_TABLE_NAME + " join foo on k=id");
assertTrue("Expected 1 row in result set", rs.next());
assertEquals("Cheap Sunglasses", rs.getString(1));
assertFalse("Expected 1 row in result set", rs.next());
}
finally {
conn.close();
}
}
@Test
public void testSelectOnlySeesTenantData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'abc', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 1, 'Billy Gibbons')");
conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
ResultSet rs = conn.createStatement().executeQuery("select \"user\" from " + TENANT_TABLE_NAME);
assertTrue("Expected 1 row in result set", rs.next());
assertEquals("Billy Gibbons", rs.getString(1));
assertFalse("Expected 1 row in result set", rs.next());
rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME);
analyzeTable(conn, PARENT_TABLE_NAME);
assertTrue("Expected 1 row in result set", rs.next());
assertEquals(1, rs.getInt(1));
assertFalse("Expected 1 row in result set", rs.next());
}
finally {
conn.close();
}
}
@Test
public void testDeleteOnlyDeletesTenantData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'abc', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 1, 'Billy Gibbons')");
conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
conn.setAutoCommit(true);
int count = conn.createStatement().executeUpdate("delete from " + TENANT_TABLE_NAME);
assertEquals("Expected 1 row have been deleted", 1, count);
ResultSet rs = conn.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME);
assertFalse("Expected no rows in result set", rs.next());
conn = DriverManager.getConnection(getUrl(), props);
analyzeTable(conn, PARENT_TABLE_NAME);
rs = conn.createStatement().executeQuery("select count(*) from " + PARENT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
}
finally {
conn.close();
}
}
@Test
public void testDeleteWhenImmutableIndex() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'abc', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 1, 'Billy Gibbons')");
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
tsConn.setAutoCommit(true);
tsConn.createStatement().executeUpdate("create index idx1 on " + TENANT_TABLE_NAME + "(\"user\")");
int count = tsConn.createStatement().executeUpdate("delete from " + TENANT_TABLE_NAME + " where \"user\"='Billy Gibbons'");
assertEquals("Expected 1 row have been deleted", 1, count);
ResultSet rs = tsConn.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME);
assertFalse("Expected no rows in result set", rs.next());
tsConn.close();
analyzeTable(conn, PARENT_TABLE_NAME);
rs = conn.createStatement().executeQuery("select count(*) from " + PARENT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
}
finally {
conn.close();
}
}
@Test
public void testDeleteOnlyDeletesTenantDataWithNoTenantTypeId() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('AC/DC', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('" + TENANT_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('" + TENANT_ID + "', 2, 'Billy Gibbons')");
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
tsConn.setAutoCommit(true);
int count = tsConn.createStatement().executeUpdate("delete from " + TENANT_TABLE_NAME_NO_TENANT_TYPE_ID);
assertEquals("Expected 2 rows have been deleted", 2, count);
ResultSet rs = tsConn.createStatement().executeQuery("select * from " + TENANT_TABLE_NAME_NO_TENANT_TYPE_ID);
assertFalse("Expected no rows in result set", rs.next());
rs = conn.createStatement().executeQuery("select count(*) from " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
rs.next();
assertEquals(1, rs.getInt(1));
}
finally {
conn.close();
}
}
@Test
public void testDeleteAllTenantTableData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'abc', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 1, 'Billy Gibbons')");
analyzeTable(tsConn, PARENT_TABLE_NAME);
tsConn.createStatement().execute("delete from " + TENANT_TABLE_NAME);
tsConn.commit();
ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + PARENT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
}
finally {
if (conn != null) conn.close();
if (tsConn != null) tsConn.close();
}
}
@Test
public void testDropTenantTableDeletesNoData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('AC/DC', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('" + TENANT_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID + " (tenant_id, id, \"user\") values ('" + TENANT_ID + "', 2, 'Billy Gibbons')");
tsConn.createStatement().execute("drop view " + TENANT_TABLE_NAME_NO_TENANT_TYPE_ID);
analyzeTable(conn, PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
rs.next();
assertEquals(3, rs.getInt(1));
}
finally {
if (conn != null) conn.close();
if (tsConn != null) tsConn.close();
}
}
@Test
public void testUpsertSelectOnlyUpsertsTenantData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'aaa', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 2, 'Billy Gibbons')");
analyzeTable(tsConn, TENANT_TABLE_NAME);
int count = tsConn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + "(id, \"user\") select id+100, \"user\" from " + TENANT_TABLE_NAME);
tsConn.commit();
assertEquals("Expected 1 row to have been inserted", 1, count);
ResultSet rs = tsConn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
}
finally {
if (conn != null) conn.close();
if (tsConn != null) tsConn.close();
}
}
@Test
public void testUpsertSelectOnlyUpsertsTenantDataWithDifferentTenantTable() throws Exception {
String anotherTableName = "V_" + generateUniqueName();
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + anotherTableName + " ( " +
"tenant_col VARCHAR) AS SELECT * FROM " + PARENT_TABLE_NAME + " WHERE tenant_type_id = 'def'");
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
Connection tsConn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.setAutoCommit(true);
conn.createStatement().executeUpdate("delete from " + PARENT_TABLE_NAME);
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('AC/DC', 'aaa', 1, 'Bon Scott')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', '" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_id, tenant_type_id, id, \"user\") values ('" + TENANT_ID + "', 'def', 2, 'Billy Gibbons')");
analyzeTable(tsConn, TENANT_TABLE_NAME);
tsConn.setAutoCommit(true);
int count = tsConn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + "(id, \"user\")"
+ "select id+100, \"user\" from " + anotherTableName + " where id=2");
assertEquals("Expected 1 row to have been inserted", 1, count);
ResultSet rs = tsConn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
}
finally {
if (conn != null) conn.close();
if (tsConn != null) tsConn.close();
}
}
@Test
public void testUpsertValuesOnlyUpsertsTenantData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
int count = conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, \"user\") values (1, 'Bon Scott')");
conn.commit();
assertEquals("Expected 1 row to have been inserted", 1, count);
ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME);
rs.next();
assertEquals(1, rs.getInt(1));
}
finally {
conn.close();
}
}
@Test
public void testBaseTableCanBeUsedInStatementsInMultitenantConnections() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
ResultSet rs = conn.createStatement().executeQuery("select * from " + PARENT_TABLE_NAME);
assertFalse(rs.next());
conn.createStatement().executeUpdate("upsert into " + PARENT_TABLE_NAME + " (tenant_type_id, id, \"user\") values ('" + TENANT_TYPE_ID + "', 1, 'Billy Gibbons')");
conn.commit();
analyzeTable(conn, PARENT_TABLE_NAME);
rs = conn.createStatement().executeQuery("select \"user\" from " + PARENT_TABLE_NAME);
assertTrue(rs.next());
assertEquals(rs.getString(1),"Billy Gibbons");
assertFalse(rs.next());
}
finally {
conn.close();
}
}
@Test
public void testTenantTableCannotBeUsedInStatementsInNonMultitenantConnections() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
try {
conn.createStatement().execute("select * from " + TENANT_TABLE_NAME);
fail();
}
catch (TableNotFoundException expected) {};
}
finally {
conn.close();
}
}
@Test
public void testUpsertValuesUsingViewWithNoWhereClause() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME_NO_TENANT_TYPE_ID + " (id) values (0)");
conn.commit();
ResultSet rs = conn.createStatement().executeQuery("select id from " + TENANT_TABLE_NAME_NO_TENANT_TYPE_ID);
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
}
| apache/phoenix | phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDMLIT.java |
179,759 | package handling.channel.handler;
import client.MapleCharacter;
import client.MapleClient;
import client.PlayerStats;
import client.SkillFactory;
import client.inventory.Equip;
import client.inventory.Item;
import client.inventory.ItemFlag;
import client.inventory.MapleInventoryType;
import client.inventory.ModifyInventory;
import constants.ItemConstants;
import constants.ServerConstants;
import java.util.ArrayList;
import java.util.List;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import tools.MaplePacketCreator;
import tools.data.input.SeekableLittleEndianAccessor;
import tools.packet.InventoryPacket;
public class ItemScrollHandler {
/**
* 砸卷
* @param slea
* @param c
* @param chr
* @param cash
*/
public static void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c, MapleCharacter chr, boolean cash) {
// 2D 05 00 FF FF
if ((chr == null) || (chr.getMap() == null)) {
return;
}
byte slot = (byte) slea.readShort();
byte dst = (byte) slea.readShort();
if (cash) {
Item scroll = chr.getInventory(MapleInventoryType.CASH).getItem(slot);
if (scroll == null) {
scroll = chr.getInventory(MapleInventoryType.USE).getItem(slot);
if (scroll == null) {
return;
}
cash = false;
}
}
byte ws = 0;
if (slea.available() >= 3L) {
ws = (byte) slea.readShort();
}
UseUpgradeScroll((short) slot, (short) dst, (short) ws, c, chr, 0, cash);
}
/**
* 使用卷轴
* @param slot
* @param dst
* @param ws
* @param c
* @param chr
* @param vegas
* @param cash
* @return
*/
public static boolean UseUpgradeScroll(short slot, short dst, short ws, MapleClient c, MapleCharacter chr, int vegas, boolean cash) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
chr.setScrolledPosition((short) 0);
Equip toScroll;
if (dst < 0) {
toScroll = (Equip) chr.getInventory(MapleInventoryType.EQUIPPED).getItem(dst);
} else {
toScroll = (Equip) chr.getInventory(MapleInventoryType.EQUIP).getItem(dst);
}
if ((toScroll == null) || (c.getPlayer().hasBlockedInventory())) {
return false;
}
byte oldLevel = toScroll.getLevel();
Item scroll;
if (cash) {
scroll = chr.getInventory(MapleInventoryType.CASH).getItem(slot);
} else {
scroll = chr.getInventory(MapleInventoryType.USE).getItem(slot);
}
if (scroll == null) {
if (chr.isShowPacket()) {
chr.dropMessage(0, "砸卷错误: 卷轴道具为空");
}
c.getSession().write(InventoryPacket.getInventoryFull());
return false;
}
if (chr.isShowPacket()) {
chr.dropSpouseMessage(10, new StringBuilder().append("砸卷信息: 卷轴ID ").append(scroll.getItemId()).append(" 卷轴名字 ").append(ii.getName(scroll.getItemId())).toString());
}
if ((!ItemConstants.canScroll(toScroll.getItemId()))) {
if (chr.isShowPacket()) {
chr.dropMessage(0, new StringBuilder().append("砸卷错误: 卷轴是否能对装备进行砸卷 ").append(!ItemConstants.canScroll(toScroll.getItemId())).toString());
}
c.getSession().write(InventoryPacket.getInventoryFull());
return false;
}
List scrollReqs = ii.getScrollReqs(scroll.getItemId());
if ((scrollReqs != null) && (scrollReqs.size() > 0) && (!scrollReqs.contains(toScroll.getItemId()))) {
if (chr.isShowPacket()) {
chr.dropMessage(0, "砸卷错误: 特定卷轴只能对指定的卷轴进行砸卷.");
}
c.getSession().write(InventoryPacket.getInventoryFull());
return false;
}
int scrollCount = scroll.getQuantity();
if (scrollCount <= 0) {
chr.dropSpouseMessage(0, new StringBuilder().append("砸卷错误,背包卷轴[").append(ii.getName(scroll.getItemId())).append("]数量为 0 .").toString());
c.getSession().write(InventoryPacket.getInventoryFull());
return false;
}
Equip scrolled = (Equip) ii.scrollEquipWithId(toScroll, scroll, false, chr, vegas);
Equip.ScrollResult scrollSuccess;
if (scrolled != null) {
if ((scrolled.getLevel() > oldLevel)) {
scrollSuccess = Equip.ScrollResult.成功;
} else {
scrollSuccess = Equip.ScrollResult.失败;
}
} else {
scrollSuccess = Equip.ScrollResult.消失;
}
// 消耗卷轴
chr.getInventory(ItemConstants.getInventoryType(scroll.getItemId())).removeItem(scroll.getPosition(), (short) 1, false);
if (scrollCount == 1) {
// 如果只有一个道具了,那么就需要移除道具,否则是更新道具数量
c.getSession().write(InventoryPacket.clearInventoryItem(ItemConstants.getInventoryType(scroll.getItemId()), scroll.getPosition(), false));
} else {
c.getSession().write(InventoryPacket.updateInventorySlot(ItemConstants.getInventoryType(scroll.getItemId()), scroll, false));
}
c.getSession().write(InventoryPacket.scrolledItem(scroll, toScroll, false));
chr.getMap().broadcastMessage(chr, InventoryPacket.getScrollEffect(chr.getId(), scrollSuccess), vegas == 0);
if (scrollSuccess == Equip.ScrollResult.消失) {
chr.dropMessage(1,"由于诅咒卷轴的力量,道具消失了!消失了!消失了!" );
c.getSession().write(InventoryPacket.clearInventoryItem(ItemConstants.getInventoryType(toScroll.getItemId()),toScroll.getPosition(), false));
if (dst < 0) {
chr.getInventory(MapleInventoryType.EQUIPPED).removeItem(toScroll.getPosition());
} else {
chr.getInventory(MapleInventoryType.EQUIP).removeItem(toScroll.getPosition());
}
chr.equipChanged();
}
return scrollSuccess == Equip.ScrollResult.成功;
}
}
| icelemon1314/mapleLemon | src/handling/channel/handler/ItemScrollHandler.java |
179,760 | /*
* Copyright 2019 Web3 Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.tx.response;
import java.math.BigInteger;
import java.util.List;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
/**
* An empty transaction receipt object containing only the transaction hash. This is to support the
* {@link QueuingTransactionReceiptProcessor} and {@link NoOpProcessor}.
*/
public class EmptyTransactionReceipt extends TransactionReceipt {
public EmptyTransactionReceipt(String transactionHash) {
super();
this.setTransactionHash(transactionHash);
}
@Override
public String getTransactionHash() {
return super.getTransactionHash();
}
@Override
public void setTransactionHash(String transactionHash) {
super.setTransactionHash(transactionHash);
}
private UnsupportedOperationException unsupportedOperation() {
return new UnsupportedOperationException(
"Empty transaction receipt, only transaction hash is available");
}
@Override
public BigInteger getTransactionIndex() {
throw unsupportedOperation();
}
@Override
public String getTransactionIndexRaw() {
throw unsupportedOperation();
}
@Override
public void setTransactionIndex(String transactionIndex) {
throw unsupportedOperation();
}
@Override
public String getBlockHash() {
throw unsupportedOperation();
}
@Override
public void setBlockHash(String blockHash) {
throw unsupportedOperation();
}
@Override
public BigInteger getBlockNumber() {
throw unsupportedOperation();
}
@Override
public String getBlockNumberRaw() {
throw unsupportedOperation();
}
@Override
public void setBlockNumber(String blockNumber) {
throw unsupportedOperation();
}
@Override
public BigInteger getCumulativeGasUsed() {
throw unsupportedOperation();
}
@Override
public String getCumulativeGasUsedRaw() {
throw unsupportedOperation();
}
@Override
public void setCumulativeGasUsed(String cumulativeGasUsed) {
throw unsupportedOperation();
}
@Override
public BigInteger getGasUsed() {
throw unsupportedOperation();
}
@Override
public String getGasUsedRaw() {
throw unsupportedOperation();
}
@Override
public void setGasUsed(String gasUsed) {
throw unsupportedOperation();
}
@Override
public String getContractAddress() {
throw unsupportedOperation();
}
@Override
public void setContractAddress(String contractAddress) {
throw unsupportedOperation();
}
@Override
public String getRoot() {
throw unsupportedOperation();
}
@Override
public void setRoot(String root) {
throw unsupportedOperation();
}
@Override
public String getStatus() {
throw unsupportedOperation();
}
@Override
public void setStatus(String status) {
throw unsupportedOperation();
}
@Override
public String getFrom() {
throw unsupportedOperation();
}
@Override
public void setFrom(String from) {
throw unsupportedOperation();
}
@Override
public String getTo() {
throw unsupportedOperation();
}
@Override
public void setTo(String to) {
throw unsupportedOperation();
}
@Override
public List<Log> getLogs() {
throw unsupportedOperation();
}
@Override
public void setLogs(List<Log> logs) {
throw unsupportedOperation();
}
@Override
public String getLogsBloom() {
throw unsupportedOperation();
}
@Override
public void setLogsBloom(String logsBloom) {
throw unsupportedOperation();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TransactionReceipt)) {
return false;
}
TransactionReceipt that = (TransactionReceipt) o;
return getTransactionHash() != null
? getTransactionHash().equals(that.getTransactionHash())
: that.getTransactionHash() == null;
}
@Override
public int hashCode() {
return getTransactionHash() != null ? getTransactionHash().hashCode() : 0;
}
}
| hyperledger/web3j | core/src/main/java/org/web3j/tx/response/EmptyTransactionReceipt.java |
179,761 | package com.markwatson.nlp;
import public_domain.Stemmer;
import java.io.FileInputStream;
import java.util.*;
import javax.xml.parsers.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.markwatson.nlp.util.NameValue;
/**
* Associate pre-trained classification categories (tags) with input text: assigns
* categories for news story types, technology category types, social information
* types, etc. to input text.
*
* <p/>
* Copyright 1998-2012 by Mark Watson. All rights reserved.
* <p/>
* This software is can be used under either of the following licenses:
* <p/>
* 1. LGPL v3<br/>
* 2. Apache 2
* <p/>
*/
public class AutoTagger {
private static Hashtable<String, Hashtable<String, Float>> tagClasses;
private static String[] tagClassNames;
private static List<Hashtable<String, Float>> hashes = new ArrayList<Hashtable<String, Float>>();
/**
*
* Static initialization of data from an XML file that contains
* word count statistics for several common topics
*
*/
static {
DefaultHandler handler = new TagsSAXHandler();
SAXParserFactory factory = SAXParserFactory.newInstance(); // Use the default non-validating parser
try {
FileInputStream xml_input_stream = new FileInputStream(System.getProperty("user.dir") + "/" + "test_data/classification_tags.xml");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(xml_input_stream, handler );
} catch (Throwable t) {
t.printStackTrace();
}
tagClassNames = new String[tagClasses.size()];
int count = 0;
for (Enumeration<String> e = tagClasses.keys() ; e.hasMoreElements() ;) {
String cname = e.nextElement();
System.out.println("cname="+cname);
hashes.add(tagClasses.get(cname));
tagClassNames[count++] = cname;
}
tagClasses = null;
}
public AutoTagger() {
}
public List<NameValue<String, Float>> getTags(String text) {
List<NameValue<String, Float>> results = new ArrayList<NameValue<String, Float>>();
List<SFtriple> tag_data = getTagsHelper(text);
for (SFtriple triple : tag_data) {
results.add(new NameValue<String,Float>(triple.getS(), triple.getF()));
}
return results;
}
/**
*
* @param text input text processed to identify categories
* @return
*/
private List<SFtriple> getTagsHelper(String text) {
Stemmer stemmer = new Stemmer();
List<String> stems = stemmer.stemString(text);
return getTagsHelper(stems);
}
/**
*
* @param stems
* @return
*/
private List<SFtriple> getTagsHelper(List<String> stems) {
List<SFtriple> ret = new ArrayList<SFtriple>();
int size = tagClassNames.length;
float[] scores = new float[size];
for (String stem : stems) {
for (int i = 0; i < size; i++) {
Float f = hashes.get(i).get(stem);
if (f != null) scores[i] += f;
}
}
float max_score=0.001f;
for (int i=0; i<size; i++) if (max_score < scores[i]) max_score = scores[i];
float cutoff = 0.2f * max_score;
for (int i=0; i<size; i++) {
if (scores[i] > cutoff) ret.add(new SFtriple(tagClassNames[i], scores[i]/max_score, i));
}
//for (int i=0; i<size; i++) System.out.println(tagClassNames[i]+"\t"+scores[i]);
Collections.sort(ret, new SFtripleComparator());
return ret;
}
class SFtripleComparator implements Comparator<SFtriple> {
public int compare(SFtriple o1, SFtriple o2) {
return (int) (1000 * (o2.getF() - o1.getF()));
}
}
/**
*
* @param text
* @return
*/
float[] getWordImportanceWeights(String text) {
List<String> stems = new Stemmer().stemString(text);
List<SFtriple> best_tags = getTagsHelper(stems);
return getWordImportanceWeights(stems, best_tags);
}
/**
*
* @param stems
* @return
*/
float[] getWordImportanceWeights(List<String> stems) {
List<SFtriple> best_tags = getTagsHelper(stems);
return getWordImportanceWeights(stems, best_tags);
}
/**
* Find the words that are most important for determining tags and use
* this information to find which words in input text are most important for
* summarization, semantic understanding, etc.
* @param stems stems for words in text
* @param best_tags the best tags for this text
* @return
*/
private float[] getWordImportanceWeights(List<String> stems, List<SFtriple> best_tags) {
int num = stems.size();
float[] ret = new float[num];
float scale = 1.0f / best_tags.size();
for (SFtriple tag : best_tags) {
Hashtable<String, Float> h = hashes.get(tag.getTopic_index());
for (int i=0; i<num; i++) {
Float f = h.get(stems.get(i));
if (f!=null) ret[i] += h.get(stems.get(i)) * scale;
}
}
return ret;
}
/**
* Test program
*
* @param args not used
*/
public static void main(String[] args) {
AutoTagger test = new AutoTagger();
List<NameValue<String, Float>> results = test.getTags("The President went to Congress to argue for his tax bill before leaving on a vacation to Las Vegas to see some shows and gamble.");
for (NameValue<String, Float> result : results) {
System.out.println(result);
}
}
static class TagsSAXHandler extends org.xml.sax.helpers.DefaultHandler {
int depth = 0;
String last_topic="";
Hashtable <String, Float>hash;
// override default methods for a few SAX events:
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes)
throws SAXException
{
if (depth==0) {
tagClasses = new Hashtable<String, Hashtable<String, Float>>();
}
if (depth==1) {
last_topic=attributes.getValue(0);
hash = new Hashtable<String, Float>();
tagClasses.put(last_topic, hash);
}
if (depth==2) {
hash.put(attributes.getValue(0), Float.parseFloat(attributes.getValue(1)));
}
// debug:
/*for (int i=0; i<depth; i++) System.out.print(" ");
System.out.println("" + depth + " element: " + qName);
if (attributes != null) {
int num = attributes.getLength();
for (int i=0; i<num; i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
for (int k=0; k<depth; k++) System.out.print(" ");
System.out.println(" attribute: " + name + " value: " + value);
}
}*/
depth++;
}
@Override
public void endElement (String uri, String localName, String qName)
throws SAXException
{
depth--;
}
@Override
public void characters (char ch[], int start, int length)
throws SAXException
{
}
}
class SFtriple implements Comparable {
public SFtriple(String s, float f, int topic_index) { this.s = s; this.f = f; this.topic_index = topic_index; }
public String toString() { return "[SFtriple: "+s + " : " + f + " : " + topic_index + "]"; }
public int compareTo(Object o) {
return (int)(1000f*(((SFtriple)o).getF() - f));
}
private String s;
private float f;
private int topic_index;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public float getF() {
return f;
}
public void setF(float f) {
this.f = f;
}
public int getTopic_index() {
return topic_index;
}
public void setTopic_index(int topic_index) {
this.topic_index = topic_index;
}
}
}
| mark-watson/Java-AI-Book-Code | nlp/src/main/java/com/markwatson/nlp/AutoTagger.java |
179,762 | package edu.stanford.nlp.sempre.interactive;
import com.fasterxml.jackson.databind.JsonNode;
import edu.stanford.nlp.sempre.Json;
import fig.basic.LogInfo;
import fig.basic.Option;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.script.ScriptEngineManager;
/**
* Java bindings to Vega and Vega-lite
*/
public class VegaEngine {
public static class Options {
@Option(gloss = "Verbosity")
public int verbose = 0;
@Option(gloss = "Compile to SVG")
public boolean compileToSVG = true;
@Option(gloss = "Cache vega compilation calls")
public boolean useCache = true;
}
public static Options opts = new Options();
/**
* Results of compiling a Vega or Vega-lite spec
*/
public static class VegaResponse {
public VegaResponse(JsonNode vegaSpec, VegaImage image, String message) {
this.vegaSpec = vegaSpec;
this.image = image;
this.message = message;
}
public final JsonNode vegaSpec;
public final VegaImage image;
public final String message;
public boolean isClean() {
return !VegaEngine.isCompilerIssue(message);
}
/**
* Checks if compiled without issue and might be different from |context|
*/
public boolean isGoodChange(VegaResponse context) {
if (!isClean()) return false;
if (context == null) return true;
if (vegaSpec == null) return true;
if (vegaSpec.equals(context.vegaSpec)) return false;
if (image == null || image.svg == null) return true;
if (context.image == null || context.image.svg == null) return true;
return !image.equals(context.image);
}
@Override
public String toString() {
return "spec=(" + Json.writeValueAsStringHard(vegaSpec) + "), image=(" + image + "), message=" + message;
}
}
/**
* Represents an image. SVG is insufficient because it doesn't have background.
*/
public static class VegaImage {
public VegaImage(String svg, String background) {
this.svg = svg;
this.background = background;
}
public final String svg;
public final String background;
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof VegaImage)) return false;
VegaImage other = (VegaImage) obj;
if (svg == null && other.svg != null) return false;
if (svg != null && !svg.equals(other.svg)) return false;
if (background == null && other.background != null) return false;
if (background != null && !background.equals(other.background)) return false;
return true;
}
@Override
public String toString() {
return "Background=" + background + ", SVG=" + svg;
}
}
private final ScriptEngine scriptEngine;
public final Map<String, VegaResponse> cache = new HashMap<String, VegaResponse>();
/**
* Check if compiler complained.
*/
public static boolean isCompilerIssue(String compilerMsg) {
return compilerMsg.contains("WARN") || compilerMsg.contains("Error");
}
public VegaEngine() {
if (opts.verbose >= 1) {
LogInfo.begin_track("VegaEngine setup");
}
ScriptEngineManager factory = new ScriptEngineManager();
scriptEngine = factory.getEngineByName("nashorn");
try {
scriptEngine.eval(new java.io.FileReader("plot/js-lib/nashorn-polyfill.js"));
scriptEngine.eval(new java.io.FileReader("plot/js-lib/synchronous-promise.js"));
scriptEngine.eval(new java.io.FileReader("plot/js-lib/vega.js"));
scriptEngine.eval(new java.io.FileReader("plot/js-lib/vega-lite.js"));
if (opts.verbose >= 1) {
LogInfo.logs("Vega version: %s", scriptEngine.eval("vega['version']"));
LogInfo.logs("Vega-lite version: %s", scriptEngine.eval("vl['version']"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (opts.verbose >= 1) {
LogInfo.end_track();
}
}
}
public static final String COMPILE_SCRIPT =
"var vega_spec = vl.compile(JSON.parse(vl_str)).spec;" +
"var vega_spec_str = JSON.stringify(vega_spec);";
public static final String SVG_SCRIPT =
"var view = new vega.View(vega.parse(vega_spec, {logLevel: vega.Info})).renderer('none').initialize();" +
"var background = view._background;" +
"var svg = null;" +
"view.toSVG().then(function(x){ svg = x });";
/**
* Compile a Vega-lite spec into Vega, then into SVG if compilation worked.
*/
public VegaResponse compileVegaLite(JsonNode vlSpec, VegaResponse contextResponse) {
String vlSpecStr = Json.writeValueAsStringHard(vlSpec);
String cacheKey = vlSpecStr + "|||" + contextResponse; // Okay this is a silly hack
if (opts.useCache) {
if (cache.containsKey(cacheKey)) {
return cache.get(cacheKey);
}
}
Invocable inv = (Invocable) scriptEngine;
ScriptContext sc = scriptEngine.getContext();
Bindings bindings = sc.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("vl_str", Json.writeValueAsStringHard(vlSpec));
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Writer oldWriter = sc.getWriter();
sc.setWriter(pw);
VegaResponse vr = null;
JsonNode vegaSpec = null;
String svg = null;
String background = null;
long t0, t1;
try {
scriptEngine.eval(COMPILE_SCRIPT);
String vegaStr = (String) scriptEngine.get("vega_spec_str");
vegaSpec = Json.readValueHard(vegaStr, JsonNode.class);
String message = sw.toString();
vr = new VegaResponse(vegaSpec, null, message);
if (vr.isGoodChange(contextResponse) && opts.compileToSVG) {
// Abort if we already know this is not a good change
// i.e. compiler complained or vegaSpec is identical
scriptEngine.eval(SVG_SCRIPT);
String msg2 = sw.toString();
if (opts.verbose >= 2) {
LogInfo.logs("SVG Rendering Logs: " + msg2);
}
svg = (String) scriptEngine.get("svg");
background = (String) scriptEngine.get("background");
vr = new VegaResponse(vegaSpec, new VegaImage(svg, background) , message);
}
} catch (ScriptException e) {
if (opts.verbose >= 2) {
e.printStackTrace();
}
vr = new VegaResponse(vegaSpec, new VegaImage(svg, background), e.getMessage());
} finally {
sc.setWriter(oldWriter);
// Just to be safe, remove bindings
bindings.remove("vl_spec");
bindings.remove("vega_spec");
bindings.remove("vega_spec_str");
bindings.remove("view");
bindings.remove("svg");
bindings.remove("background");
}
if (opts.useCache) {
cache.put(cacheKey, vr);
}
return vr;
}
public VegaResponse compileVegaLite(JsonNode vlSpec) {
return compileVegaLite(vlSpec, null);
}
}
| stanfordnlp/sempre-plot | src/edu/stanford/nlp/sempre/interactive/VegaEngine.java |
179,763 | M
检查字符串是否可以组成回文. 用hashmap
```
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Summer has reached a casino in Las Vegas and she wanted to gamble in the slot machines, Casino manager has given her some chances to play (T) ,where T is the no of different slot machines; each one has it's own unique combination of letters and numbers blinking in the panel(N).
The condition of winning is to have a pallindromic sequence within those N characters provided she can press the randomization switch as many times she wants untill all the combinations with those letters are complete.
Help summer to identify in which of those slot machines she has a chance of winning.
Constraints:
1≤T≤10000
1≤N≤100 (characters)
Input Format
The first line contains an integer T (The no of slot machines).
The second line contains the string of characters(N) blinking on the slot machine.
The string inputed in the second line may cotain any numbers or letters of any length .
Note :
The string(N) may have repetitive letters or numbers in it. Capital letters and small letters are considered separate characters.
Output Format
if a slot machine has a possibility of winning then display yes, else display no
Sample Input
2
abac11c
dkvvfvd
Sample Output
yes
no
Explanation
Since the 1st string contains a permutation which is palindromic in nature 'ca1b1ac' therefore output is yes.
In the 2nd case there is no such permutation hence the output is no.
*/
//check pallidromic by counting chars in HashMap. O(n). If more than 1 single char, that is no.
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int line = Integer.parseInt(in.nextLine());
while (in.hasNextLine()) {
if (checkPalindrome(in.nextLine())) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
public static boolean checkPalindrome(String s) {
if (s == null || s.length() == 0) {
return false;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!map.containsKey(c)) {
map.put(c, 0);
}
map.put(c, map.get(c) + 1);
}
int countSingle = 0;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
countSingle += entry.getValue() % 2;
if (countSingle > 1) {
return false;
}
}
return true;
}
}
``` | awangdev/leet-code | Others/亚麻/Slot Machine.java |
179,765 | package com.alphawallet.app.entity;
/**
* Created by James on 26/03/2018.
*/
public class EtherscanTransaction
{
public String blockNumber;
long timeStamp;
String hash;
public int nonce;
String blockHash;
int transactionIndex;
String from;
String to;
String value;
String gas;
String gasPrice;
String isError;
String txreceipt_status;
String input;
String contractAddress;
String cumulativeGasUsed;
String gasUsed;
int confirmations;
String functionName;
public Transaction createTransaction(String walletAddress, long chainId)
{
Transaction tx = new Transaction(hash, isError, blockNumber, timeStamp, nonce, from, to, value, gas, gasPrice, input,
gasUsed, chainId, contractAddress, functionName);
if (walletAddress != null)
{
if (!tx.getWalletInvolvedInTransaction(walletAddress))
{
tx = null;
}
}
return tx;
}
public String getHash() { return hash; }
public EtherscanTransaction(CovalentTransaction transaction, Transaction tx)
{
blockNumber = tx.blockNumber;
timeStamp = tx.timeStamp;
hash = transaction.tx_hash;
nonce = tx.nonce;
blockHash = "";
transactionIndex = transaction.tx_offset;
from = transaction.from_address;
to = transaction.to_address;
value = transaction.value;
gas = transaction.gas_spent;
gasPrice = transaction.gas_price;
isError = transaction.successful ? "0" : "1";
txreceipt_status = "";
input = tx.input;
contractAddress = "";
cumulativeGasUsed = "";
gasUsed = transaction.gas_spent;
confirmations = 0;
if (tx.isConstructor)
{
to = tx.to;
contractAddress = tx.to;
}
}
}
| AlphaWallet/alpha-wallet-android | app/src/main/java/com/alphawallet/app/entity/EtherscanTransaction.java |
179,766 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Camunda License 1.0. You may not use this file
* except in compliance with the Camunda License 1.0.
*/
package io.camunda.zeebe.broker.system.configuration.backpressure;
import static io.camunda.zeebe.broker.system.configuration.ConfigurationUtil.checkPositive;
public class VegasCfg {
private int alpha = 3;
private int beta = 6;
private int initialLimit = 20;
public int getAlpha() {
return alpha;
}
public void setAlpha(final int alpha) {
checkPositive(alpha, "alpha");
this.alpha = alpha;
}
public int getBeta() {
return beta;
}
public void setBeta(final int beta) {
checkPositive(beta, "beta");
this.beta = beta;
}
public int getInitialLimit() {
return initialLimit;
}
public void setInitialLimit(final int initialLimit) {
checkPositive(initialLimit, "initialLimit");
this.initialLimit = initialLimit;
}
@Override
public String toString() {
return "VegasCfg{"
+ "alpha="
+ alpha
+ ", beta="
+ beta
+ ", initialLimit="
+ initialLimit
+ '}';
}
}
| camunda/zeebe | zeebe/broker/src/main/java/io/camunda/zeebe/broker/system/configuration/backpressure/VegasCfg.java |
179,767 | /*
* Copyright (C) 2012 Cyril Mottier (http://www.cyrilmottier.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyrilmottier.android.polarissample;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.cyrilmottier.android.polarissample.util.Config;
import com.cyrilmottier.polaris.Annotation;
import com.cyrilmottier.polaris.MapCalloutView;
import com.cyrilmottier.polaris.MapViewUtils;
import com.cyrilmottier.polaris.PolarisMapView;
import com.cyrilmottier.polaris.PolarisMapView.OnAnnotationSelectionChangedListener;
import com.cyrilmottier.polaris.PolarisMapView.OnRegionChangedListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
public class MainActivity extends MapActivity implements OnRegionChangedListener, OnAnnotationSelectionChangedListener {
private static final String LOG_TAG = "MainActivity";
//@formatter:off
private static final Annotation[] sFrance = {
new Annotation(new GeoPoint(48635600, -1510600), "Mont Saint Michel", "Mont Saint-Michel is a rocky tidal island and a commune in Normandy, France. It is located approximately one kilometre (just over half a mile) off the country's north-western coast, at the mouth of the Couesnon River near Avranches."),
new Annotation(new GeoPoint(48856600, 2351000), "Paris", "The city of love"),
new Annotation(new GeoPoint(44837400, -576100), "Bordeaux", "A port city in southwestern France"),
new Annotation(new GeoPoint(48593100, -647500), "Domfront", "A commune in the Orne department in north-western France"),
};
private static final Annotation[] sEurope = {
new Annotation(new GeoPoint(55755800, 37617600), "Moscow"),
new Annotation(new GeoPoint(59332800, 18064500), "Stockholm"),
new Annotation(new GeoPoint(59939000, 30315800), "Saint Petersburg"),
new Annotation(new GeoPoint(60169800, 24938200), "Helsinki"),
new Annotation(new GeoPoint(60451400, 22268700), "Turku"),
new Annotation(new GeoPoint(65584200, 22154700), "Lule\u00E5"),
new Annotation(new GeoPoint(59438900, 24754500), "Talinn"),
new Annotation(new GeoPoint(66498700, 25721100), "Rovaniemi"),
};
private static final Annotation[] sUsaWestCoast = {
new Annotation(new GeoPoint(40714400, -74006000), "New York City"),
new Annotation(new GeoPoint(39952300, -75163800), "Philadelphia"),
new Annotation(new GeoPoint(38895100, -77036400), "Washington"),
new Annotation(new GeoPoint(41374800, -83651300), "Bowling Green"),
new Annotation(new GeoPoint(42331400, -83045800), "Detroit"),
};
private static final Annotation[] sUsaEastCoast = {
new Annotation(new GeoPoint(37774900, -122419400), "San Francisco"),
new Annotation(new GeoPoint(37770600, -119510800), "Yosemite National Park"),
new Annotation(new GeoPoint(36878200, -121947300), "Monteray Bay"),
new Annotation(new GeoPoint(35365800, -120849900), "Morro Bay"),
new Annotation(new GeoPoint(34420800, -119698200), "Santa Barbara"),
new Annotation(new GeoPoint(34052200, -118243700), "Los Angeles"),
new Annotation(new GeoPoint(32715300, -117157300), "San Diego"),
new Annotation(new GeoPoint(36114600, -115172800), "Las Vegas"),
new Annotation(new GeoPoint(36220100, -116881700), "Death Valley"),
new Annotation(new GeoPoint(36355200, -112661200), "Grand Canyon"),
new Annotation(new GeoPoint(37289900, -113048900), "Zion National Park"),
new Annotation(new GeoPoint(37628300, -112167700), "Bryce Canyon"),
new Annotation(new GeoPoint(36936900, -111483800), "Lake Powell"),
};
private static final Annotation[][] sRegions = {sFrance, sEurope, sUsaEastCoast, sUsaWestCoast};
//@formatter:on
private PolarisMapView mMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mMapView = new PolarisMapView(this, Config.GOOGLE_MAPS_API_KEY);
mMapView.setUserTrackingButtonEnabled(true);
mMapView.setOnRegionChangedListenerListener(this);
mMapView.setOnAnnotationSelectionChangedListener(this);
// Prepare an alternate pin Drawable
final Drawable altMarker = MapViewUtils.boundMarkerCenterBottom(getResources().getDrawable(R.drawable.map_pin_holed_purple));
// Prepare the list of Annotation using the alternate Drawable for all
// Annotation located in France
final ArrayList<Annotation> annotations = new ArrayList<Annotation>();
for (Annotation[] region : sRegions) {
for (Annotation annotation : region) {
if (region == sFrance) {
annotation.setMarker(altMarker);
}
annotations.add(annotation);
}
}
mMapView.setAnnotations(annotations, R.drawable.map_pin_holed_blue);
final FrameLayout mapViewContainer = (FrameLayout) findViewById(R.id.map_view_container);
mapViewContainer.addView(mMapView, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
@Override
protected void onStart() {
super.onStart();
mMapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mMapView.onStop();
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public void onRegionChanged(PolarisMapView mapView) {
if (Config.INFO_LOGS_ENABLED) {
Log.i(LOG_TAG, "onRegionChanged");
}
}
@Override
public void onRegionChangeConfirmed(PolarisMapView mapView) {
if (Config.INFO_LOGS_ENABLED) {
Log.i(LOG_TAG, "onRegionChangeConfirmed");
}
}
@Override
public void onAnnotationSelected(PolarisMapView mapView, MapCalloutView calloutView, int position, Annotation annotation) {
if (Config.INFO_LOGS_ENABLED) {
Log.i(LOG_TAG, "onAnnotationSelected");
}
calloutView.setDisclosureEnabled(true);
calloutView.setClickable(true);
if (!TextUtils.isEmpty(annotation.getSnippet())) {
calloutView.setLeftAccessoryView(getLayoutInflater().inflate(R.layout.accessory, calloutView, false));
} else {
calloutView.setLeftAccessoryView(null);
}
}
@Override
public void onAnnotationDeselected(PolarisMapView mapView, MapCalloutView calloutView, int position, Annotation annotation) {
if (Config.INFO_LOGS_ENABLED) {
Log.i(LOG_TAG, "onAnnotationDeselected");
}
}
@Override
public void onAnnotationClicked(PolarisMapView mapView, MapCalloutView calloutView, int position, Annotation annotation) {
if (Config.INFO_LOGS_ENABLED) {
Log.i(LOG_TAG, "onAnnotationClicked");
}
Toast.makeText(this, getString(R.string.annotation_clicked, annotation.getTitle()), Toast.LENGTH_SHORT).show();
}
}
| cyrilmottier/Polaris | sample/src/com/cyrilmottier/android/polarissample/MainActivity.java |
179,768 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.valuetypes.vega.applib.stringify;
import org.apache.causeway.valuetypes.vega.applib.value.Vega;
import lombok.experimental.UtilityClass;
/**
* @since 2.0
*/
@UtilityClass
public class VegaStringifier {
public Vega destring(final String data) {
if(data==null) {
return null;
}
return Vega.valueOf(data);
}
public String enstring(final Vega vega) {
if(vega==null) {
return null;
}
return vega.getJson();
}
}
| ep-infosec/33_apache_isis | valuetypes/vega/applib/src/main/java/org/apache/causeway/valuetypes/vega/applib/stringify/VegaStringifier.java |
179,769 | /*
* Copyright 2019-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.managedblockchainquery.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.managedblockchainquery.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* TransactionMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TransactionMarshaller {
private static final MarshallingInfo<String> NETWORK_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("network").build();
private static final MarshallingInfo<String> BLOCKHASH_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("blockHash").build();
private static final MarshallingInfo<String> TRANSACTIONHASH_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transactionHash").build();
private static final MarshallingInfo<String> BLOCKNUMBER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("blockNumber").build();
private static final MarshallingInfo<java.util.Date> TRANSACTIONTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transactionTimestamp").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<Long> TRANSACTIONINDEX_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transactionIndex").build();
private static final MarshallingInfo<Long> NUMBEROFTRANSACTIONS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("numberOfTransactions").build();
private static final MarshallingInfo<String> TO_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("to").build();
private static final MarshallingInfo<String> FROM_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("from").build();
private static final MarshallingInfo<String> CONTRACTADDRESS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("contractAddress").build();
private static final MarshallingInfo<String> GASUSED_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("gasUsed").build();
private static final MarshallingInfo<String> CUMULATIVEGASUSED_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("cumulativeGasUsed").build();
private static final MarshallingInfo<String> EFFECTIVEGASPRICE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("effectiveGasPrice").build();
private static final MarshallingInfo<Integer> SIGNATUREV_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("signatureV").build();
private static final MarshallingInfo<String> SIGNATURER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("signatureR").build();
private static final MarshallingInfo<String> SIGNATURES_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("signatureS").build();
private static final MarshallingInfo<String> TRANSACTIONFEE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transactionFee").build();
private static final MarshallingInfo<String> TRANSACTIONID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("transactionId").build();
private static final MarshallingInfo<String> CONFIRMATIONSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("confirmationStatus").build();
private static final MarshallingInfo<String> EXECUTIONSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("executionStatus").build();
private static final TransactionMarshaller instance = new TransactionMarshaller();
public static TransactionMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Transaction transaction, ProtocolMarshaller protocolMarshaller) {
if (transaction == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(transaction.getNetwork(), NETWORK_BINDING);
protocolMarshaller.marshall(transaction.getBlockHash(), BLOCKHASH_BINDING);
protocolMarshaller.marshall(transaction.getTransactionHash(), TRANSACTIONHASH_BINDING);
protocolMarshaller.marshall(transaction.getBlockNumber(), BLOCKNUMBER_BINDING);
protocolMarshaller.marshall(transaction.getTransactionTimestamp(), TRANSACTIONTIMESTAMP_BINDING);
protocolMarshaller.marshall(transaction.getTransactionIndex(), TRANSACTIONINDEX_BINDING);
protocolMarshaller.marshall(transaction.getNumberOfTransactions(), NUMBEROFTRANSACTIONS_BINDING);
protocolMarshaller.marshall(transaction.getTo(), TO_BINDING);
protocolMarshaller.marshall(transaction.getFrom(), FROM_BINDING);
protocolMarshaller.marshall(transaction.getContractAddress(), CONTRACTADDRESS_BINDING);
protocolMarshaller.marshall(transaction.getGasUsed(), GASUSED_BINDING);
protocolMarshaller.marshall(transaction.getCumulativeGasUsed(), CUMULATIVEGASUSED_BINDING);
protocolMarshaller.marshall(transaction.getEffectiveGasPrice(), EFFECTIVEGASPRICE_BINDING);
protocolMarshaller.marshall(transaction.getSignatureV(), SIGNATUREV_BINDING);
protocolMarshaller.marshall(transaction.getSignatureR(), SIGNATURER_BINDING);
protocolMarshaller.marshall(transaction.getSignatureS(), SIGNATURES_BINDING);
protocolMarshaller.marshall(transaction.getTransactionFee(), TRANSACTIONFEE_BINDING);
protocolMarshaller.marshall(transaction.getTransactionId(), TRANSACTIONID_BINDING);
protocolMarshaller.marshall(transaction.getConfirmationStatus(), CONFIRMATIONSTATUS_BINDING);
protocolMarshaller.marshall(transaction.getExecutionStatus(), EXECUTIONSTATUS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-managedblockchainquery/src/main/java/com/amazonaws/services/managedblockchainquery/model/transform/TransactionMarshaller.java |
179,771 | package util.twitter;
import java.util.regex.*;
public class Regex {
private static final String UNICODE_SPACES = "[" +
"\\u0009-\\u000d" + // # White_Space # Cc [5] <control-0009>..<control-000D>
"\\u0020" + // White_Space # Zs SPACE
"\\u0085" + // White_Space # Cc <control-0085>
"\\u00a0" + // White_Space # Zs NO-BREAK SPACE
"\\u1680" + // White_Space # Zs OGHAM SPACE MARK
"\\u180E" + // White_Space # Zs MONGOLIAN VOWEL SEPARATOR
"\\u2000-\\u200a" + // # White_Space # Zs [11] EN QUAD..HAIR SPACE
"\\u2028" + // White_Space # Zl LINE SEPARATOR
"\\u2029" + // White_Space # Zp PARAGRAPH SEPARATOR
"\\u202F" + // White_Space # Zs NARROW NO-BREAK SPACE
"\\u205F" + // White_Space # Zs MEDIUM MATHEMATICAL SPACE
"\\u3000" + // White_Space # Zs IDEOGRAPHIC SPACE
"]";
private static String LATIN_ACCENTS_CHARS = "\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff" + // Latin-1
"\\u0100-\\u024f" + // Latin Extended A and B
"\\u0253\\u0254\\u0256\\u0257\\u0259\\u025b\\u0263\\u0268\\u026f\\u0272\\u0289\\u028b" + // IPA Extensions
"\\u02bb" + // Hawaiian
"\\u0300-\\u036f" + // Combining diacritics
"\\u1e00-\\u1eff"; // Latin Extended Additional (mostly for Vietnamese)
private static final String HASHTAG_ALPHA_CHARS = "a-z" + LATIN_ACCENTS_CHARS +
"\\u0400-\\u04ff\\u0500-\\u0527" + // Cyrillic
"\\u2de0-\\u2dff\\ua640-\\ua69f" + // Cyrillic Extended A/B
"\\u0591-\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7" +
"\\u05d0-\\u05ea\\u05f0-\\u05f4" + // Hebrew
"\\ufb1d-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41" +
"\\ufb43-\\ufb44\\ufb46-\\ufb4f" + // Hebrew Pres. Forms
"\\u0610-\\u061a\\u0620-\\u065f\\u066e-\\u06d3\\u06d5-\\u06dc" +
"\\u06de-\\u06e8\\u06ea-\\u06ef\\u06fa-\\u06fc\\u06ff" + // Arabic
"\\u0750-\\u077f\\u08a0\\u08a2-\\u08ac\\u08e4-\\u08fe" + // Arabic Supplement and Extended A
"\\ufb50-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb" + // Pres. Forms A
"\\ufe70-\\ufe74\\ufe76-\\ufefc" + // Pres. Forms B
"\\u200c" + // Zero-Width Non-Joiner
"\\u0e01-\\u0e3a\\u0e40-\\u0e4e" + // Thai
"\\u1100-\\u11ff\\u3130-\\u3185\\uA960-\\uA97F\\uAC00-\\uD7AF\\uD7B0-\\uD7FF" + // Hangul (Korean)
"\\p{InHiragana}\\p{InKatakana}" + // Japanese Hiragana and Katakana
"\\p{InCJKUnifiedIdeographs}" + // Japanese Kanji / Chinese Han
"\\u3003\\u3005\\u303b" + // Kanji/Han iteration marks
"\\uff21-\\uff3a\\uff41-\\uff5a" + // full width Alphabet
"\\uff66-\\uff9f" + // half width Katakana
"\\uffa1-\\uffdc"; // half width Hangul (Korean)
private static final String HASHTAG_ALPHA_NUMERIC_CHARS = "0-9\\uff10-\\uff19_" + HASHTAG_ALPHA_CHARS;
private static final String HASHTAG_ALPHA = "[" + HASHTAG_ALPHA_CHARS +"]";
private static final String HASHTAG_ALPHA_NUMERIC = "[" + HASHTAG_ALPHA_NUMERIC_CHARS +"]";
/* URL related hash regex collection */
private static final String URL_VALID_PRECEEDING_CHARS = "(?:[^A-Z0-9@@$##\u202A-\u202E]|^)";
private static final String URL_VALID_CHARS = "[\\p{Alnum}" + LATIN_ACCENTS_CHARS + "]";
private static final String URL_VALID_SUBDOMAIN = "(?>(?:" + URL_VALID_CHARS + "[" + URL_VALID_CHARS + "\\-_]*)?" + URL_VALID_CHARS + "\\.)";
private static final String URL_VALID_DOMAIN_NAME = "(?:(?:" + URL_VALID_CHARS + "[" + URL_VALID_CHARS + "\\-]*)?" + URL_VALID_CHARS + "\\.)";
/* Any non-space, non-punctuation characters. \p{Z} = any kind of whitespace or invisible separator. */
private static final String URL_VALID_UNICODE_CHARS = "[.[^\\p{Punct}\\s\\p{Z}\\p{InGeneralPunctuation}]]";
private static final String URL_VALID_GTLD =
"(?:(?:" +
"academy|accountants|active|actor|aero|agency|airforce|allfinanz|alsace|archi|army|arpa|asia|associates|" +
"attorney|auction|audio|autos|axa|bar|bargains|bayern|beer|berlin|best|bid|bike|bio|biz|black|blackfriday|blue|" +
"bmw|bnpparibas|boo|boutique|brussels|budapest|build|builders|business|buzz|bzh|cab|cal|camera|camp|" +
"cancerresearch|capetown|capital|caravan|cards|care|career|careers|casa|cash|cat|catering|center|ceo|cern|" +
"channel|cheap|christmas|chrome|church|citic|city|claims|cleaning|click|clinic|clothing|club|codes|coffee|" +
"college|cologne|com|community|company|computer|condos|construction|consulting|contractors|cooking|cool|coop|" +
"country|credit|creditcard|cruises|cuisinella|cymru|dad|dance|dating|day|deals|degree|democrat|dental|dentist|" +
"desi|diamonds|diet|digital|direct|directory|discount|dnp|domains|durban|dvag|eat|edu|education|email|engineer|" +
"engineering|enterprises|equipment|esq|estate|eus|events|exchange|expert|exposed|fail|farm|feedback|finance|" +
"financial|fish|fishing|fitness|flights|florist|fly|foo|forsale|foundation|frl|frogans|fund|furniture|futbol|" +
"gal|gallery|gbiz|gent|gift|gifts|gives|glass|gle|global|globo|gmail|gmo|gmx|google|gop|gov|graphics|gratis|" +
"green|gripe|guide|guitars|guru|hamburg|haus|healthcare|help|here|hiphop|hiv|holdings|holiday|homes|horse|host|" +
"hosting|house|how|ibm|immo|immobilien|industries|info|ing|ink|institute|insure|int|international|investments|" +
"jetzt|jobs|joburg|juegos|kaufen|kim|kitchen|kiwi|koeln|krd|kred|lacaixa|land|lawyer|lease|lgbt|life|lighting|" +
"limited|limo|link|loans|london|lotto|ltda|luxe|luxury|maison|management|mango|market|marketing|media|meet|" +
"melbourne|meme|menu|miami|mil|mini|mobi|moda|moe|monash|mortgage|moscow|motorcycles|mov|museum|nagoya|name|" +
"navy|net|network|neustar|new|nexus|ngo|nhk|ninja|nra|nrw|nyc|okinawa|ong|onl|ooo|org|organic|otsuka|ovh|paris|" +
"partners|parts|pharmacy|photo|photography|photos|physio|pics|pictures|pink|pizza|place|plumbing|pohl|post|" +
"praxi|press|pro|prod|productions|prof|properties|property|pub|qpon|quebec|realtor|recipes|red|rehab|reise|" +
"reisen|ren|rentals|repair|report|republican|rest|restaurant|reviews|rich|rio|rocks|rodeo|rsvp|ruhr|ryukyu|" +
"saarland|sarl|sca|scb|schmidt|schule|scot|services|sexy|shiksha|shoes|singles|social|software|sohu|solar|" +
"solutions|soy|space|spiegel|supplies|supply|support|surf|surgery|suzuki|systems|tatar|tattoo|tax|technology|" +
"tel|tienda|tips|tirol|today|tokyo|tools|top|town|toys|trade|training|travel|tui|university|uno|uol|vacations|" +
"vegas|ventures|vermögensberater|vermögensberatung|versicherung|vet|viajes|villas|vision|vlaanderen|vodka|vote|" +
"voting|voto|voyage|wales|wang|watch|webcam|website|wed|whoswho|wien|wiki|williamhill|wme|work|works|world|wtc|" +
"wtf|xxx|xyz|yachts|yandex|yokohama|youtube|zip|zone|дети|москва|онлайн|орг|рус|сайт|بازار|شبكة|موقع|संगठन|みんな|" +
"世界|中信|中文网|企业|佛山|公司|公益|商城|商标|在线|广东|我爱你|手机|政务|机构|游戏|移动|组织机构|网址|网络|集团|삼성" +
")(?=[^\\p{Alnum}@]|$))";
private static final String URL_VALID_CCTLD =
"(?:(?:" +
"ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|bq|br|bs|bt|bv|" +
"bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|" +
"fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|" +
"io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|" +
"mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|" +
"pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|" +
"sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|" +
"za|zm|zw|бел|мкд|мон|рф|срб|укр|қаз|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بھارت|تونس|سودان|سورية|عراق|" +
"عمان|فلسطين|قطر|مصر|مليسيا|پاکستان|भारत|বাংলা|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|ไทย|გე|中国|" +
"中國|台湾|台灣|新加坡|香港|한국" +
")(?=[^\\p{Alnum}@]|$))";
private static final String URL_PUNYCODE = "(?:xn--[0-9a-z]+)";
private static final String SPECIAL_URL_VALID_CCTLD = "(?:(?:" + "co|tv" + ")(?=[^\\p{Alnum}@]|$))";
private static final String URL_VALID_DOMAIN =
"(?:" + // subdomains + domain + TLD
URL_VALID_SUBDOMAIN + "+" + URL_VALID_DOMAIN_NAME + // e.g. www.twitter.com, foo.co.jp, bar.co.uk
"(?:" + URL_VALID_GTLD + "|" + URL_VALID_CCTLD + "|" + URL_PUNYCODE + ")" +
")" +
"|(?:" + // domain + gTLD + some ccTLD
URL_VALID_DOMAIN_NAME + // e.g. twitter.com
"(?:" + URL_VALID_GTLD + "|" + URL_PUNYCODE + "|" + SPECIAL_URL_VALID_CCTLD + ")" +
")" +
"|(?:" + "(?<=https?://)" +
"(?:" +
"(?:" + URL_VALID_DOMAIN_NAME + URL_VALID_CCTLD + ")" + // protocol + domain + ccTLD
"|(?:" +
URL_VALID_UNICODE_CHARS + "+\\." + // protocol + unicode domain + TLD
"(?:" + URL_VALID_GTLD + "|" + URL_VALID_CCTLD + ")" +
")" +
")" +
")" +
"|(?:" + // domain + ccTLD + '/'
URL_VALID_DOMAIN_NAME + URL_VALID_CCTLD + "(?=/)" + // e.g. t.co/
")";
private static final String URL_VALID_PORT_NUMBER = "[0-9]++";
private static final String URL_VALID_GENERAL_PATH_CHARS = "[a-z0-9!\\*';:=\\+,.\\$/%#\\[\\]\\-_~\\|&@" + LATIN_ACCENTS_CHARS + "]";
/** Allow URL paths to contain up to two nested levels of balanced parens
* 1. Used in Wikipedia URLs like /Primer_(film)
* 2. Used in IIS sessions like /S(dfd346)/
* 3. Used in Rdio URLs like /track/We_Up_(Album_Version_(Edited))/
**/
private static final String URL_BALANCED_PARENS = "\\(" +
"(?:" +
URL_VALID_GENERAL_PATH_CHARS + "+" +
"|" +
// allow one nested level of balanced parentheses
"(?:" +
URL_VALID_GENERAL_PATH_CHARS + "*" +
"\\(" +
URL_VALID_GENERAL_PATH_CHARS + "+" +
"\\)" +
URL_VALID_GENERAL_PATH_CHARS + "*" +
")" +
")" +
"\\)";
/** Valid end-of-path characters (so /foo. does not gobble the period).
* 2. Allow =&# for empty URL parameters and other URL-join artifacts
**/
private static final String URL_VALID_PATH_ENDING_CHARS = "[a-z0-9=_#/\\-\\+" + LATIN_ACCENTS_CHARS + "]|(?:" + URL_BALANCED_PARENS +")";
private static final String URL_VALID_PATH = "(?:" +
"(?:" +
URL_VALID_GENERAL_PATH_CHARS + "*" +
"(?:" + URL_BALANCED_PARENS + URL_VALID_GENERAL_PATH_CHARS + "*)*" +
URL_VALID_PATH_ENDING_CHARS +
")|(?:@" + URL_VALID_GENERAL_PATH_CHARS + "+/)" +
")";
private static final String URL_VALID_URL_QUERY_CHARS = "[a-z0-9!?\\*'\\(\\);:&=\\+\\$/%#\\[\\]\\-_\\.,~\\|@]";
private static final String URL_VALID_URL_QUERY_ENDING_CHARS = "[a-z0-9_&=#/]";
private static final String VALID_URL_PATTERN_STRING =
"(" + // $1 total match
"(" + URL_VALID_PRECEEDING_CHARS + ")" + // $2 Preceeding chracter
"(" + // $3 URL
"(https?://)?" + // $4 Protocol (optional)
"(" + URL_VALID_DOMAIN + ")" + // $5 Domain(s)
"(?::(" + URL_VALID_PORT_NUMBER +"))?" + // $6 Port number (optional)
"(/" +
URL_VALID_PATH + "*+" +
")?" + // $7 URL Path and anchor
"(\\?" + URL_VALID_URL_QUERY_CHARS + "*" + // $8 Query String
URL_VALID_URL_QUERY_ENDING_CHARS + ")?" +
")" +
")";
private static String AT_SIGNS_CHARS = "@\uFF20";
private static final String DOLLAR_SIGN_CHAR = "\\$";
private static final String CASHTAG = "[a-z]{1,6}(?:[._][a-z]{1,2})?";
/* Begin public constants */
public static final Pattern VALID_HASHTAG = Pattern.compile("(^|[^&" + HASHTAG_ALPHA_NUMERIC_CHARS + "])(#|\uFF03)(" + HASHTAG_ALPHA_NUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHA_NUMERIC + "*)", Pattern.CASE_INSENSITIVE);
public static final int VALID_HASHTAG_GROUP_BEFORE = 1;
public static final int VALID_HASHTAG_GROUP_HASH = 2;
public static final int VALID_HASHTAG_GROUP_TAG = 3;
public static final Pattern INVALID_HASHTAG_MATCH_END = Pattern.compile("^(?:[##]|://)");
public static final Pattern RTL_CHARACTERS = Pattern.compile("[\u0600-\u06FF\u0750-\u077F\u0590-\u05FF\uFE70-\uFEFF]");
public static final Pattern AT_SIGNS = Pattern.compile("[" + AT_SIGNS_CHARS + "]");
public static final Pattern VALID_MENTION_OR_LIST = Pattern.compile("([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?", Pattern.CASE_INSENSITIVE);
public static final int VALID_MENTION_OR_LIST_GROUP_BEFORE = 1;
public static final int VALID_MENTION_OR_LIST_GROUP_AT = 2;
public static final int VALID_MENTION_OR_LIST_GROUP_USERNAME = 3;
public static final int VALID_MENTION_OR_LIST_GROUP_LIST = 4;
public static final Pattern VALID_REPLY = Pattern.compile("^(?:" + UNICODE_SPACES + ")*" + AT_SIGNS + "([a-z0-9_]{1,20})", Pattern.CASE_INSENSITIVE);
public static final int VALID_REPLY_GROUP_USERNAME = 1;
public static final Pattern INVALID_MENTION_MATCH_END = Pattern.compile("^(?:[" + AT_SIGNS_CHARS + LATIN_ACCENTS_CHARS + "]|://)");
public static final Pattern VALID_URL = Pattern.compile(VALID_URL_PATTERN_STRING, Pattern.CASE_INSENSITIVE);
public static final int VALID_URL_GROUP_ALL = 1;
public static final int VALID_URL_GROUP_BEFORE = 2;
public static final int VALID_URL_GROUP_URL = 3;
public static final int VALID_URL_GROUP_PROTOCOL = 4;
public static final int VALID_URL_GROUP_DOMAIN = 5;
public static final int VALID_URL_GROUP_PORT = 6;
public static final int VALID_URL_GROUP_PATH = 7;
public static final int VALID_URL_GROUP_QUERY_STRING = 8;
public static final Pattern VALID_TCO_URL = Pattern.compile("^https?:\\/\\/t\\.co\\/[a-z0-9]+", Pattern.CASE_INSENSITIVE);
public static final Pattern INVALID_URL_WITHOUT_PROTOCOL_MATCH_BEGIN = Pattern.compile("[-_./]$");
public static final Pattern VALID_CASHTAG = Pattern.compile("(^|" + UNICODE_SPACES + ")(" + DOLLAR_SIGN_CHAR + ")(" + CASHTAG + ")" +"(?=$|\\s|\\p{Punct})", Pattern.CASE_INSENSITIVE);
public static final int VALID_CASHTAG_GROUP_BEFORE = 1;
public static final int VALID_CASHTAG_GROUP_DOLLAR = 2;
public static final int VALID_CASHTAG_GROUP_CASHTAG = 3;
}
| wlin12/JNN | src/util/twitter/Regex.java |
179,772 | /*
* Copyright (c) 2022 Acadia, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.acadiasoft.im.simm.engine.margin;
import com.acadiasoft.im.base.margin.ModelMargin;
import com.acadiasoft.im.base.margin.SiloMargin;
import com.acadiasoft.im.base.model.imtree.identifiers.ImModelClass;
import com.acadiasoft.im.base.util.BigDecimalUtils;
import com.acadiasoft.im.base.util.ListUtils;
import com.acadiasoft.im.simm.config.SimmCalculationType;
import com.acadiasoft.im.simm.config.SimmConfig;
import com.acadiasoft.im.simm.model.Sensitivity;
import com.acadiasoft.im.simm.model.SensitivityIdentifier;
import com.acadiasoft.im.simm.model.imtree.identifiers.ProductClass;
import com.acadiasoft.im.simm.model.imtree.identifiers.RiskClass;
import com.acadiasoft.im.simm.model.imtree.identifiers.SensitivityClass;
import com.acadiasoft.im.simm.model.utils.CurvatureSensitivityUtils;
import com.acadiasoft.im.simm.model.utils.VolWeightUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
public class SimmMargin extends ModelMargin {
private static final long serialVersionUID = 1L;
private SimmMargin(BigDecimal margin, List<SiloMargin> children) {
super(ImModelClass.SIMM, margin, children);
}
public static SimmMargin calculate(List<Sensitivity> sensitivities, SimmConfig config) {
// separate the add on and regular sensitivity types
List<Sensitivity> filterForStandard = sensitivities.stream() //
.filter(SensitivityIdentifier::isSimmStandard) //
.collect(Collectors.toList());
// filter out any fx delta risk to the calculation currency
List<Sensitivity> fxFiltered = filterDeltaFxRiskInCalcCurrency(filterForStandard, config.calculationCurrency());
// build any curvature sensitivities from vegas, and then vol-weight the vega and curvature
List<Sensitivity> weighted = addCurvaturesAndVolWeight(fxFiltered, config);
// calculate the exposure for each product class present
List<ProductMargin> marginByProductClass = getMarginByProductClass(weighted, config);
BigDecimal productSum = BigDecimalUtils.sum(marginByProductClass, ProductMargin::getMargin);
// now determine which mode we are in and calculate accordingly
if (config.simmCalculationType().equals(SimmCalculationType.STANDARD)) {
return new SimmMargin(productSum, new ArrayList<>(marginByProductClass));
} else {
// calculate the add on exposure
List<Sensitivity> addOns = sensitivities.stream() //
.filter(SensitivityIdentifier::isAddOn) //
.collect(Collectors.toList());
AddOnMargin addOnMargin = AddOnMargin.calculate(addOns, marginByProductClass, config);
// now return the add on exposure based on the settings
if (config.simmCalculationType().equals(SimmCalculationType.ADDITIONAL)) {
return new SimmMargin(addOnMargin.getMargin(), Collections.singletonList(addOnMargin));
} else if (addOnMargin.getMargin().setScale(0, RoundingMode.UP).equals(BigDecimal.ZERO)) {
return new SimmMargin(productSum, new ArrayList<>(marginByProductClass));
} else if (productSum.setScale(0, RoundingMode.UP).equals(BigDecimal.ZERO)) {
return new SimmMargin(addOnMargin.getMargin(), Collections.singletonList(addOnMargin));
} else {
List<SiloMargin> simmSiloMargin = new ArrayList<>(marginByProductClass);
simmSiloMargin.add(addOnMargin);
return new SimmMargin(productSum.add(addOnMargin.getMargin()), simmSiloMargin);
}
}
}
private static List<ProductMargin> getMarginByProductClass(List<Sensitivity> sensitivities, SimmConfig config) {
// map sensitivities by product class, build the exposure of each product class
return ListUtils.groupBy(sensitivities, SensitivityIdentifier::getProductIdentifier).entrySet().stream().map(entry -> {
ProductClass productClass = config.useSingleProductClass() ? ProductClass.SINGLE : entry.getKey();
return ProductMargin.calculate(productClass, entry.getValue(), config);
}).collect(Collectors.toList());
}
private static List<Sensitivity> filterDeltaFxRiskInCalcCurrency(List<Sensitivity> list, String calculationCurrency) {
return list.stream()
.filter(sensitivity -> !(sensitivity.getRiskType().equalsIgnoreCase(RiskClass.RISK_TYPE_FX) && sensitivity.getQualifier().equalsIgnoreCase(calculationCurrency)))
.collect(Collectors.toList());
}
/**
* First, we make the curvature sensitivities from the vega sensitivities and then scale them by SF(t) we get all the
* sensitivities on the same "level" EQ, FX, and CM vega & curvature sensitivities have not been multiplied by
* volatility factor, while IR, CRQ, and CRNQ sensitivities have been, so we do this multiplication now
*
* @param sensitivities
* the set of sensitivities
* @return the set of sensitivities with curvatures added and scaled, and curvatures/vegas vol-weighted
*/
private static List<Sensitivity> addCurvaturesAndVolWeight(List<Sensitivity> sensitivities, SimmConfig config) {
Map<SensitivityClass, List<Sensitivity>> map = ListUtils.groupBy(sensitivities, SensitivityIdentifier::getSensitivityClass);
if (map.containsKey(SensitivityClass.VEGA)) {
// get the vegas and the scaled curvature sensitivities
List<Sensitivity> baseVegas = map.get(SensitivityClass.VEGA);
List<Sensitivity> scaledCurvatures = CurvatureSensitivityUtils.makeAndScaleCurvatures(baseVegas, config);
// vol weight both sets of sensitivities
List<Sensitivity> volWeightedVegas = VolWeightUtils.volWeightSensitivities(baseVegas, config);
List<Sensitivity> volWeightedCurvatures = VolWeightUtils.volWeightSensitivities(scaledCurvatures, config);
// add them back to the set of delta sensitivities
List<Sensitivity> list = Optional.ofNullable(map.get(SensitivityClass.DELTA)).orElse(new ArrayList<>());
list.addAll(Optional.ofNullable(map.get(SensitivityClass.BASECORR)).orElse(Collections.emptyList()));
list.addAll(volWeightedVegas);
list.addAll(volWeightedCurvatures);
return list;
} else {
// there are no vega sensitivities so just return the original list as we don't have to do anything
return sensitivities;
}
}
}
| AcadiaSoft/simm-lib | simm/src/main/java/com/acadiasoft/im/simm/engine/margin/SimmMargin.java |
179,773 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.end2end;
import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_DROP_PK;
import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_MUTATE_TABLE;
import static org.apache.phoenix.exception.SQLExceptionCode.TABLE_UNDEFINED;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.KEY_SEQ;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ORDINAL_POSITION;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_FUNCTION_TABLE;
import static org.apache.phoenix.schema.PTableType.SYSTEM;
import static org.apache.phoenix.schema.PTableType.TABLE;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.phoenix.coprocessor.TaskRegionObserver;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.ColumnAlreadyExistsException;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.TableAlreadyExistsException;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.util.MetaDataUtil;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.StringUtil;
import org.apache.phoenix.util.TestUtil;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(ParallelStatsEnabledTest.class)
public class TenantSpecificTablesDDLIT extends BaseTenantSpecificTablesIT {
@Test
public void testCreateTenantSpecificTable() throws Exception {
// ensure we didn't create a physical HBase table for the tenant-specific table
Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES));
Admin admin = conn.unwrap(PhoenixConnection.class).getQueryServices().getAdmin();
assertEquals(0, admin.listTableDescriptors(Pattern.compile(TENANT_TABLE_NAME)).size());
}
@Test
public void testCreateTenantTableTwice() throws Exception {
try {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
conn.createStatement().execute(TENANT_TABLE_DDL);
fail();
}
catch (TableAlreadyExistsException expected) {}
}
@Test
public void testCreateTenantViewFromNonMultiTenant() throws Exception {
String tableName = generateUniqueName();
createTestTable(getUrl(), "CREATE TABLE " + tableName + " (K VARCHAR PRIMARY KEY)");
try {
String viewName = generateUniqueName();
// Only way to get this exception is to attempt to derive from a global, multi-type table, as we won't find
// a tenant-specific table when we attempt to resolve the base table.
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + viewName + " (COL VARCHAR) AS SELECT * FROM " + tableName);
}
catch (TableNotFoundException expected) {
}
}
@Test
public void testAlteringMultiTenancyForTableWithViewsNotAllowed() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
String multiTenantTable = "MT_" + generateUniqueName();
String globalTable = "G_" + generateUniqueName();
// create the two base tables
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
String ddl = "CREATE TABLE " + multiTenantTable + " (TENANT_ID VARCHAR NOT NULL, PK1 VARCHAR NOT NULL, V1 VARCHAR, V2 VARCHAR, V3 VARCHAR CONSTRAINT NAME_PK PRIMARY KEY(TENANT_ID, PK1)) MULTI_TENANT = true ";
conn.createStatement().execute(ddl);
ddl = "CREATE TABLE " + globalTable + " (TENANT_ID VARCHAR NOT NULL, PK1 VARCHAR NOT NULL, V1 VARCHAR, V2 VARCHAR, V3 VARCHAR CONSTRAINT NAME_PK PRIMARY KEY(TENANT_ID, PK1)) ";
conn.createStatement().execute(ddl);
}
String t1 = generateUniqueName();
props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, t1);
// create view on multi-tenant table
try (Connection tenantConn = DriverManager.getConnection(getUrl(), props)) {
String viewName = "V_" + generateUniqueName();
String viewDDL = "CREATE VIEW " + viewName + " AS SELECT * FROM " + multiTenantTable;
tenantConn.createStatement().execute(viewDDL);
}
props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
// create view on global table
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
String viewName = "V_" + generateUniqueName();
conn.createStatement().execute("CREATE VIEW " + viewName + " AS SELECT * FROM " + globalTable);
}
props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
try {
conn.createStatement().execute("ALTER TABLE " + globalTable + " SET MULTI_TENANT = " + true);
fail();
} catch (SQLException e) {
assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode());
}
try {
conn.createStatement().execute("ALTER TABLE " + multiTenantTable + " SET MULTI_TENANT = " + false);
fail();
} catch (SQLException e) {
assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode());
}
}
}
@Test(expected=TableNotFoundException.class)
public void testDeletionOfParentTableFailsOnTenantSpecificConnection() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, TENANT_ID); // connection is tenant-specific
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.createStatement().execute("DROP TABLE " + PARENT_TABLE_NAME);
conn.close();
}
public void testCreationOfParentTableFailsOnTenantSpecificConnection() throws Exception {
try {
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE TABLE " + generateUniqueName() + "( \n" +
" \"user\" VARCHAR ,\n" +
" id INTEGER not null primary key desc\n" +
" ) ");
fail();
} catch (SQLException e) {
assertEquals(SQLExceptionCode.CANNOT_CREATE_TENANT_SPECIFIC_TABLE.getErrorCode(), e.getErrorCode());
}
}
@Test
public void testTenantSpecificAndParentTablesMayBeInDifferentSchemas() throws SQLException {
String fullTableName = "DIFFSCHEMA." + generateUniqueName();
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + fullTableName + " ( \n" +
" tenant_col VARCHAR) AS SELECT * \n" +
" FROM " + PARENT_TABLE_NAME + " WHERE tenant_type_id = 'aaa'");
try {
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + fullTableName + "( \n" +
" tenant_col VARCHAR) AS SELECT *\n"+
" FROM DIFFSCHEMA." + PARENT_TABLE_NAME + " WHERE tenant_type_id = 'aaa'");
fail();
}
catch (SQLException expected) {
assertEquals(TABLE_UNDEFINED.getErrorCode(), expected.getErrorCode());
}
String newDDL =
"CREATE TABLE DIFFSCHEMA." + PARENT_TABLE_NAME + " ( \n" +
" \"user\" VARCHAR ,\n" +
" tenant_id VARCHAR(5) NOT NULL,\n" +
" tenant_type_id VARCHAR(3) NOT NULL, \n" +
" id INTEGER NOT NULL\n" +
" CONSTRAINT pk PRIMARY KEY (tenant_id, tenant_type_id, id)) MULTI_TENANT=true";
createTestTable(getUrl(), newDDL);
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + fullTableName + "( \n" +
" tenant_col VARCHAR) AS SELECT *\n"+
" FROM DIFFSCHEMA." + PARENT_TABLE_NAME + " WHERE tenant_type_id = 'aaa'");
}
@Test
public void testTenantSpecificTableCanDeclarePK() throws SQLException {
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + generateUniqueName() + "( \n" +
" tenant_col VARCHAR PRIMARY KEY) AS SELECT *\n" +
" FROM " + PARENT_TABLE_NAME);
}
@Test(expected=ColumnAlreadyExistsException.class)
public void testTenantSpecificTableCannotOverrideParentCol() throws SQLException {
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL, "CREATE VIEW " + generateUniqueName() + " ( \n" +
" \"user\" INTEGER) AS SELECT *\n" +
" FROM " + PARENT_TABLE_NAME);
}
@Test
public void testBaseTableWrongFormatWithTenantTypeId() throws Exception {
// only two PK columns for multi_tenant, multi_type
try {
createTestTable(getUrl(),
"CREATE TABLE " + generateUniqueName() +
"(TENANT_ID VARCHAR NOT NULL PRIMARY KEY, ID VARCHAR, A INTEGER) MULTI_TENANT=true");
fail();
}
catch (SQLException expected) {
assertEquals(SQLExceptionCode.INSUFFICIENT_MULTI_TENANT_COLUMNS.getErrorCode(), expected.getErrorCode());
}
}
@Test
public void testAddDropColumn() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
conn.setAutoCommit(true);
try {
conn.createStatement().execute("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (1, 'Viva Las Vegas')");
conn.createStatement().execute("alter view " + TENANT_TABLE_NAME + " add tenant_col2 char(1) null");
conn.createStatement().execute("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col2) values (2, 'a')");
ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME);
rs.next();
assertEquals(2, rs.getInt(1));
rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + " where tenant_col2 = 'a'");
rs.next();
assertEquals(1, rs.getInt(1));
conn.createStatement().execute("alter view " + TENANT_TABLE_NAME + " drop column tenant_col");
rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + "");
rs.next();
assertEquals(2, rs.getInt(1));
try {
rs = conn.createStatement().executeQuery("select tenant_col from " + TENANT_TABLE_NAME);
fail();
}
catch (ColumnNotFoundException expected) {}
}
finally {
conn.close();
}
}
@Test
public void testDropOfPKInTenantTablesNotAllowed() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
// try removing a PK col
try {
conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " drop column id");
fail();
}
catch (SQLException expected) {
assertEquals(CANNOT_DROP_PK.getErrorCode(), expected.getErrorCode());
}
}
finally {
conn.close();
}
}
@Test
public void testColumnMutationInParentTableWithExistingTenantTable() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
try {
conn.createStatement().execute("alter table " + PARENT_TABLE_NAME + " drop column id");
fail();
}
catch (SQLException expected) {
assertEquals(CANNOT_DROP_PK.getErrorCode(), expected.getErrorCode());
}
// try removing a non-PK col, which is allowed
try {
conn.createStatement().execute("alter table " + PARENT_TABLE_NAME + " drop column \"user\"");
}
catch (SQLException expected) {
fail("We should be able to drop a non pk base table column");
}
}
finally {
conn.close();
}
}
@Test
public void testDisallowDropParentTableWithExistingTenantTable() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
conn.createStatement().executeUpdate("drop table " + PARENT_TABLE_NAME);
fail("Should not have been allowed to drop a parent table to which tenant-specific tables still point.");
}
catch (SQLException expected) {
assertEquals(CANNOT_MUTATE_TABLE.getErrorCode(), expected.getErrorCode());
}
finally {
conn.close();
}
}
@Test
public void testAllowDropParentTableWithCascadeAndSingleTenantTable() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
Connection connTenant = null;
try {
// Drop Parent Table
conn.createStatement().executeUpdate("DROP TABLE " + PARENT_TABLE_NAME + " CASCADE");
connTenant = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
validateTenantViewIsDropped(conn);
} finally {
if (conn != null) {
conn.close();
}
if (connTenant != null) {
connTenant.close();
}
}
}
@Test
public void testAllDropParentTableWithCascadeWithMultipleTenantTablesAndIndexes() throws Exception {
// Create a second tenant table
String tenantTable2 = "V_" + generateUniqueName();
createTestTable(PHOENIX_JDBC_TENANT_SPECIFIC_URL2, TENANT_TABLE_DDL.replace(TENANT_TABLE_NAME, tenantTable2));
//TODO Create some tenant specific table indexes
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = null;
Connection connTenant1 = null;
Connection connTenant2 = null;
try {
List<String> sortedCatalogs = Arrays.asList(TENANT_ID, TENANT_ID2);
Collections.sort(sortedCatalogs);
conn = DriverManager.getConnection(getUrl(), props);
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, "", StringUtil.escapeLike(TENANT_TABLE_NAME), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertEquals(TENANT_ID, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertTableMetaData(rs, null, TENANT_TABLE_NAME, PTableType.VIEW);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(tenantTable2), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertEquals(TENANT_ID2, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertTableMetaData(rs, null, tenantTable2, PTableType.VIEW);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(TENANT_TABLE_NAME_NO_TENANT_TYPE_ID), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertEquals(TENANT_ID, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertTableMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, PTableType.VIEW);
assertFalse(rs.next());
// Drop Parent Table
conn.createStatement().executeUpdate("DROP TABLE " + PARENT_TABLE_NAME + " CASCADE");
TaskRegionObserver.SelfHealingTask task = new TaskRegionObserver.SelfHealingTask
(TaskRegionEnvironment,
QueryServicesOptions.DEFAULT_TASK_HANDLING_MAX_INTERVAL_MS);
task.run();
// Validate Tenant Views are dropped
connTenant1 = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
validateTenantViewIsDropped(connTenant1);
connTenant2 = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL2, props);
validateTenantViewIsDropped(connTenant2);
// Validate Tenant Metadata is gone for the Tenant Table TENANT_TABLE_NAME
rs = meta.getTables(null, "",
StringUtil.escapeLike(TENANT_TABLE_NAME),
new String[] {PTableType.VIEW.getValue().getString()});
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(tenantTable2)
, new String[] {PTableType.VIEW.getValue().getString()});
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(TENANT_TABLE_NAME_NO_TENANT_TYPE_ID), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertEquals(TENANT_ID, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertTableMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, PTableType.VIEW);
assertFalse(rs.next());
} finally {
if (conn != null) {
conn.close();
}
if (connTenant1 != null) {
connTenant1.close();
}
if (connTenant2 != null) {
connTenant2.close();
}
}
}
private void validateTenantViewIsDropped(Connection connTenant) throws SQLException {
try {
connTenant.unwrap(PhoenixConnection.class).getTableNoCache(TENANT_TABLE_NAME);
fail("Tenant specific view " + TENANT_TABLE_NAME
+ " should have been dropped when parent was dropped");
} catch (TableNotFoundException e) {
//Expected
}
// Try and drop tenant view, should throw TableNotFoundException
try {
String ddl = "DROP VIEW " + TENANT_TABLE_NAME;
connTenant.createStatement().execute(ddl);
fail("Tenant specific view " + TENANT_TABLE_NAME + " should have been dropped when parent was dropped");
} catch (TableNotFoundException e) {
//Expected
}
}
@Test
public void testShowTablesMultiTenant() throws Exception {
// Each tenant should only be able list tables corresponding to their TENANT_ID
String tenantId2 = "T_" + generateUniqueName();
String secondTenantConnectionURL =
PHOENIX_JDBC_TENANT_SPECIFIC_URL.replace(TENANT_ID, tenantId2);
String tenantTable2 = "V_" + generateUniqueName();
createTestTable(
secondTenantConnectionURL, TENANT_TABLE_DDL.replace(TENANT_TABLE_NAME, tenantTable2));
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
// Non-tenant connections should list all the tables.
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
Set<String> tables = new HashSet<>();
ResultSet rs = conn.prepareStatement("show tables").executeQuery();
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME"));
}
assertTrue(tables.contains(PARENT_TABLE_NAME));
assertTrue(tables.contains(TENANT_TABLE_NAME));
assertTrue(tables.contains(tenantTable2));
}
// Tenant specific connections should not list tables from other tenants.
try (Connection conn = DriverManager.getConnection(secondTenantConnectionURL, props)) {
Set<String> tables = new HashSet<>();
ResultSet rs = conn.prepareStatement("show tables").executeQuery();
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME"));
}
assertTrue(tables.contains(PARENT_TABLE_NAME));
assertFalse(tables.contains(TENANT_TABLE_NAME));
assertTrue(tables.contains(tenantTable2));
}
}
@Test
public void testTableMetadataScan() throws Exception {
// create a tenant table with same name for a different tenant to make sure we are not picking it up in metadata scans for TENANT_ID
String tenantId2 = "T_" + generateUniqueName();
String secondTenantConnectionURL =
PHOENIX_JDBC_TENANT_SPECIFIC_URL.replace(TENANT_ID, tenantId2);
String tenantTable2 = "V_" + generateUniqueName();
createTestTable(
secondTenantConnectionURL, TENANT_TABLE_DDL.replace(TENANT_TABLE_NAME, tenantTable2));
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// empty string means global tenant id
// make sure connections w/o tenant id only see non-tenant-specific tables, both SYSTEM and USER
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables("", "", StringUtil.escapeLike(PARENT_TABLE_NAME), new String[] {TABLE.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, PARENT_TABLE_NAME, TABLE);
assertFalse(rs.next());
rs = meta.getTables("", "", StringUtil.escapeLike(PARENT_TABLE_NAME_NO_TENANT_TYPE_ID), new String[] {TABLE.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, PARENT_TABLE_NAME_NO_TENANT_TYPE_ID, TABLE);
assertFalse(rs.next());
// make sure connections w/o tenant id only see non-tenant-specific columns
rs = meta.getColumns("", null, null, null);
while (rs.next()) {
assertNotEquals(TENANT_TABLE_NAME, rs.getString("TABLE_NAME"));
assertNotEquals(tenantTable2, rs.getString("TABLE_NAME"));
}
List<String> sortedTableNames = Arrays.asList(TENANT_TABLE_NAME, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID);
Collections.sort(sortedTableNames);
List<String> sortedParentNames;
if (sortedTableNames.get(0).equals(TENANT_TABLE_NAME)) {
sortedParentNames = Arrays.asList(PARENT_TABLE_NAME, PARENT_TABLE_NAME_NO_TENANT_TYPE_ID);
} else {
sortedParentNames = Arrays.asList(PARENT_TABLE_NAME_NO_TENANT_TYPE_ID, PARENT_TABLE_NAME);
}
rs = meta.getSuperTables(TENANT_ID, null, null);
assertTrue(rs.next());
assertEquals(TENANT_ID, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertEquals(sortedTableNames.get(0), rs.getString(PhoenixDatabaseMetaData.TABLE_NAME));
assertEquals(sortedParentNames.get(0), rs.getString(PhoenixDatabaseMetaData.SUPERTABLE_NAME));
assertTrue(rs.next());
assertEquals(TENANT_ID, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertEquals(sortedTableNames.get(1), rs.getString(PhoenixDatabaseMetaData.TABLE_NAME));
assertEquals(sortedParentNames.get(1), rs.getString(PhoenixDatabaseMetaData.SUPERTABLE_NAME));
assertFalse(rs.next());
rs = meta.getSuperTables(tenantId2, null, null);
assertTrue(rs.next());
assertEquals(tenantId2, rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
assertEquals(tenantTable2, rs.getString(PhoenixDatabaseMetaData.TABLE_NAME));
assertEquals(PARENT_TABLE_NAME, rs.getString(PhoenixDatabaseMetaData.SUPERTABLE_NAME));
assertFalse(rs.next());
Set<String> sortedCatalogs = new HashSet<>(Arrays.asList(TENANT_ID, tenantId2));
rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
sortedCatalogs.remove(rs.getString(PhoenixDatabaseMetaData.TABLE_CAT));
}
assertTrue("Should have found both tenant IDs", sortedCatalogs.isEmpty());
} finally {
props.clear();
conn.close();
}
conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);
try {
// make sure tenant-specific connections only see their own tables and the global tables
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables("", SYSTEM_CATALOG_SCHEMA, null, new String[] {PTableType.SYSTEM.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_TABLE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, SYSTEM_FUNCTION_TABLE, SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_LOG_TABLE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_MUTEX_TABLE_NAME, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.TYPE_SEQUENCE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_TASK_TABLE, PTableType.SYSTEM);
assertTrue(rs.next());
assertTableMetaData(rs, SYSTEM_CATALOG_SCHEMA, PhoenixDatabaseMetaData.SYSTEM_TRANSFORM_TABLE, PTableType.SYSTEM);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(tenantTable2), new String[] {TABLE.getValue().getString()});
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(PARENT_TABLE_NAME), new String[] {TABLE.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, PARENT_TABLE_NAME, TABLE);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(PARENT_TABLE_NAME_NO_TENANT_TYPE_ID), new String[] {TABLE.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, PARENT_TABLE_NAME_NO_TENANT_TYPE_ID, TABLE);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(TENANT_TABLE_NAME), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, TENANT_TABLE_NAME, PTableType.VIEW);
assertFalse(rs.next());
rs = meta.getTables(null, "", StringUtil.escapeLike(TENANT_TABLE_NAME_NO_TENANT_TYPE_ID), new String[] {PTableType.VIEW.getValue().getString()});
assertTrue(rs.next());
assertTableMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, PTableType.VIEW);
assertFalse(rs.next());
// make sure tenants see parent table's columns and their own
rs = meta.getColumns(null, null, StringUtil.escapeLike(TENANT_TABLE_NAME), null);
assertTrue(rs.next());
assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "\"user\"", 1);
assertTrue(rs.next());
// (tenant_id column is not visible in tenant-specific connection)
assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "tenant_type_id", 2);
assertEquals(1, rs.getShort(KEY_SEQ));
assertTrue(rs.next());
assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "id", 3);
assertTrue(rs.next());
assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "tenant_col", 4);
assertFalse(rs.next());
rs = meta.getColumns(null, null, StringUtil.escapeLike(TENANT_TABLE_NAME_NO_TENANT_TYPE_ID), null);
assertTrue(rs.next());
assertColumnMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, "\"user\"", 1);
assertTrue(rs.next());
// (tenant_id column is not visible in tenant-specific connection)
assertColumnMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, "id", 2);
assertTrue(rs.next());
assertColumnMetaData(rs, null, TENANT_TABLE_NAME_NO_TENANT_TYPE_ID, "tenant_col", 3);
assertFalse(rs.next());
}
finally {
conn.close();
}
}
@Test
public void testIndexHintWithTenantView() throws Exception {
String schemaName = generateUniqueName();
String dataTableName = generateUniqueName();
String fullDataTableName = SchemaUtil.getTableName(schemaName, dataTableName);
String viewName = generateUniqueName();
String fullViewName = SchemaUtil.getTableName(schemaName, viewName);
String viewIndexName = generateUniqueName();
try(Connection conn = DriverManager.getConnection(getUrl());
Statement stmt = conn.createStatement()) {
String createDataTable = "create table " + fullDataTableName + " (orgid varchar(10) not null, "
+ "id1 varchar(10) not null, id2 varchar(10) not null, id3 integer not null, "
+ "val1 varchar(10), val2 varchar(10) " +
"CONSTRAINT PK PRIMARY KEY (orgid, id1, id2, id3)) MULTI_TENANT=true";
stmt.execute(createDataTable);
stmt.execute("create view " + fullViewName + " as select * from " + fullDataTableName);
stmt.execute("create index " + viewIndexName + " on " + fullViewName + "(id3, id2, id1) include (val1, val2)");
}
try(Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL);
Statement stmt = conn.createStatement()) {
String grandChildViewName = generateUniqueName();
String fullGrandChildViewName = SchemaUtil.getTableName(schemaName, grandChildViewName);
stmt.execute("create view " + fullGrandChildViewName + " as select * from " + fullViewName);
PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
pconn.getTableNoCache(pconn.getTenantId(), fullGrandChildViewName);
stmt.execute("upsert into " + fullGrandChildViewName + " values ('a1', 'a2', 3, 'a4', 'a5')");
conn.commit();
stmt.execute("upsert into " + fullGrandChildViewName + " values ('b1', 'b2', 3, 'b4', 'b5')");
conn.commit();
String physicalViewIndexTableName = MetaDataUtil.getViewIndexPhysicalName(fullDataTableName);
TableName viewIndexHBaseTable = TableName.valueOf(physicalViewIndexTableName);
TestUtil.assertRawRowCount(conn, viewIndexHBaseTable, 2);
String sql = "SELECT /*+ INDEX(" + fullGrandChildViewName + " " + viewIndexName + ")*/ "
+ "val2, id2, val1, id3, id1 FROM " + fullGrandChildViewName
+ " WHERE id2 = 'a2' AND (id1 = 'a1' OR id1 = 'b1') AND id3 = 3";
ResultSet rs = stmt.executeQuery("EXPLAIN " + sql);
String actualQueryPlan = QueryUtil.getExplainPlan(rs);
assertTrue(actualQueryPlan.contains("1-WAY POINT LOOKUP ON 2 KEYS OVER " + physicalViewIndexTableName));
rs = stmt.executeQuery(sql);
assertTrue(rs.next());
assertFalse(rs.next());
sql = "SELECT val2, id2, val1, id3, id1 FROM " + fullGrandChildViewName
+ " WHERE id2 = 'a2' AND (id1 = 'a1' OR id1 = 'b1') AND id3 = 3";
rs = stmt.executeQuery("EXPLAIN " + sql);
actualQueryPlan = QueryUtil.getExplainPlan(rs);
assertTrue(actualQueryPlan.contains("1-WAY POINT LOOKUP ON 2 KEYS OVER " + fullDataTableName));
rs = stmt.executeQuery(sql);
assertTrue(rs.next());
assertFalse(rs.next());
}
}
private void assertTableMetaData(ResultSet rs, String schema, String table, PTableType tableType) throws SQLException {
assertEquals(schema, rs.getString("TABLE_SCHEM"));
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(tableType.toString(), rs.getString("TABLE_TYPE"));
}
private void assertColumnMetaData(ResultSet rs, String schema, String table, String column) throws SQLException {
assertEquals(schema, rs.getString("TABLE_SCHEM"));
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier(column), rs.getString("COLUMN_NAME"));
}
private void assertColumnMetaData(ResultSet rs, String schema, String table, String column, int ordinalPosition)
throws SQLException {
assertColumnMetaData(rs, schema, table, column);
assertEquals(ordinalPosition, rs.getInt(ORDINAL_POSITION));
}
} | apache/phoenix | phoenix-core/src/it/java/org/apache/phoenix/end2end/TenantSpecificTablesDDLIT.java |
179,774 | /***********************************************************
* @Description : 指纹字符串查找算法(蒙特卡罗算法)
* @author : 梁山广(Laing Shan Guang)
* @date : 2018/3/18 下午12:30
* @email : liangshanguang2@gmail.com
***********************************************************/
package com.huawei.l00379880.algs4.chapter5string;
import java.math.BigInteger;
import java.util.Random;
public class P508RabinKarp {
/**
* the pattern // needed only for Las Vegas
*/
private String pat;
/**
* pattern hash value
*/
private long patHash;
/**
* pattern length
*/
private int m;
/**
* a large prime, small enough to avoid long overflow
*/
private long q;
/**
* radix
*/
private int R;
/**
* R^(M-1) % Q
*/
private long RM;
/**
* Preprocesses the pattern string.
*
* @param pattern the pattern string
* @param R the alphabet size
*/
public P508RabinKarp(char[] pattern, int R) {
this.pat = String.valueOf(pattern);
this.R = R;
throw new UnsupportedOperationException("Operation not supported yet");
}
/**
* Preprocesses the pattern string.
*
* @param pat the pattern string
*/
public P508RabinKarp(String pat) {
// save pattern (needed only for Las Vegas)
this.pat = pat;
R = 256;
m = pat.length();
q = longRandomPrime();
// precompute R^(m-1) % q for use in removing leading digit
RM = 1;
for (int i = 1; i <= m - 1; i++) {
RM = (R * RM) % q;
}
patHash = hash(pat, m);
}
/**
* Compute hash for key[0..m-1].
*/
private long hash(String key, int m) {
long h = 0;
for (int j = 0; j < m; j++) {
h = (R * h + key.charAt(j)) % q;
}
return h;
}
/**
* Las Vegas version: does pat[] match txt[i..i-m+1] ?
*/
private boolean check(String txt, int i) {
for (int j = 0; j < m; j++) {
if (pat.charAt(j) != txt.charAt(i + j)) {
return false;
}
}
return true;
}
/**
* Returns the index of the first occurrrence of the pattern string
* in the text string.
*
* @param txt the text string
* @return the index of the first occurrence of the pattern string
* in the text string; n if no such match
*/
public int search(String txt) {
int n = txt.length();
if (n < m) {
return n;
}
long txtHash = hash(txt, m);
// check for match at offset 0
if ((patHash == txtHash) && check(txt, 0)) {
return 0;
}
// check for hash match; if hash match, check for exact match
for (int i = m; i < n; i++) {
// Remove leading digit, add trailing digit, check for match.
txtHash = (txtHash + q - RM * txt.charAt(i - m) % q) % q;
txtHash = (txtHash * R + txt.charAt(i)) % q;
// match
int offset = i - m + 1;
if ((patHash == txtHash) && check(txt, offset)) {
return offset;
}
}
// no match
return n;
}
/**
* a random 31-bit prime
*/
private static long longRandomPrime() {
BigInteger prime = BigInteger.probablePrime(31, new Random());
return prime.longValue();
}
}
| lsgwr/algorithms | Part6Algs4/MyAlgs4/src/main/java/com/huawei/l00379880/algs4/chapter5string/P508RabinKarp.java |
179,776 | /*
* Copyright 2019 Web3 Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.protocol.core.methods.response;
import java.math.BigInteger;
import java.util.List;
import org.web3j.utils.Numeric;
/** TransactionReceipt object used by {@link EthGetTransactionReceipt}. */
public class TransactionReceipt {
private String transactionHash;
private String transactionIndex;
private String blockHash;
private String blockNumber;
private String cumulativeGasUsed;
private String gasUsed;
private String contractAddress;
private String root;
// status is only present on Byzantium transactions onwards
// see EIP 658 https://github.com/ethereum/EIPs/pull/658
private String status;
private String from;
private String to;
private List<Log> logs;
private String logsBloom;
private String revertReason;
private String type;
private String effectiveGasPrice;
private String blobGasPrice;
private String blobGasUsed;
public TransactionReceipt() {}
public TransactionReceipt(
String transactionHash,
String transactionIndex,
String blockHash,
String blockNumber,
String cumulativeGasUsed,
String gasUsed,
String contractAddress,
String root,
String status,
String from,
String to,
List<Log> logs,
String logsBloom,
String revertReason,
String type,
String effectiveGasPrice) {
this.transactionHash = transactionHash;
this.transactionIndex = transactionIndex;
this.blockHash = blockHash;
this.blockNumber = blockNumber;
this.cumulativeGasUsed = cumulativeGasUsed;
this.gasUsed = gasUsed;
this.contractAddress = contractAddress;
this.root = root;
this.status = status;
this.from = from;
this.to = to;
this.logs = logs;
this.logsBloom = logsBloom;
this.revertReason = revertReason;
this.type = type;
this.effectiveGasPrice = effectiveGasPrice;
}
public TransactionReceipt(
String transactionHash,
String transactionIndex,
String blockHash,
String blockNumber,
String cumulativeGasUsed,
String gasUsed,
String contractAddress,
String root,
String status,
String from,
String to,
List<Log> logs,
String logsBloom,
String revertReason,
String type,
String effectiveGasPrice,
String blobGasPrice,
String blobGasUsed) {
this.transactionHash = transactionHash;
this.transactionIndex = transactionIndex;
this.blockHash = blockHash;
this.blockNumber = blockNumber;
this.cumulativeGasUsed = cumulativeGasUsed;
this.gasUsed = gasUsed;
this.contractAddress = contractAddress;
this.root = root;
this.status = status;
this.from = from;
this.to = to;
this.logs = logs;
this.logsBloom = logsBloom;
this.revertReason = revertReason;
this.type = type;
this.effectiveGasPrice = effectiveGasPrice;
this.blobGasPrice = blobGasPrice;
this.blobGasUsed = blobGasUsed;
}
public String getTransactionHash() {
return transactionHash;
}
public void setTransactionHash(String transactionHash) {
this.transactionHash = transactionHash;
}
public BigInteger getTransactionIndex() {
return Numeric.decodeQuantity(transactionIndex);
}
public String getTransactionIndexRaw() {
return transactionIndex;
}
public void setTransactionIndex(String transactionIndex) {
this.transactionIndex = transactionIndex;
}
public String getBlockHash() {
return blockHash;
}
public void setBlockHash(String blockHash) {
this.blockHash = blockHash;
}
public BigInteger getBlockNumber() {
return Numeric.decodeQuantity(blockNumber);
}
public String getBlockNumberRaw() {
return blockNumber;
}
public void setBlockNumber(String blockNumber) {
this.blockNumber = blockNumber;
}
public BigInteger getCumulativeGasUsed() {
return Numeric.decodeQuantity(cumulativeGasUsed);
}
public String getCumulativeGasUsedRaw() {
return cumulativeGasUsed;
}
public void setCumulativeGasUsed(String cumulativeGasUsed) {
this.cumulativeGasUsed = cumulativeGasUsed;
}
public BigInteger getGasUsed() {
return Numeric.decodeQuantity(gasUsed);
}
public String getGasUsedRaw() {
return gasUsed;
}
public void setGasUsed(String gasUsed) {
this.gasUsed = gasUsed;
}
public String getContractAddress() {
return contractAddress;
}
public void setContractAddress(String contractAddress) {
this.contractAddress = contractAddress;
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isStatusOK() {
if (null == getStatus()) {
return true;
}
BigInteger statusQuantity = Numeric.decodeQuantity(getStatus());
return BigInteger.ONE.equals(statusQuantity);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public List<Log> getLogs() {
return logs;
}
public void setLogs(List<Log> logs) {
this.logs = logs;
}
public String getLogsBloom() {
return logsBloom;
}
public void setLogsBloom(String logsBloom) {
this.logsBloom = logsBloom;
}
public String getRevertReason() {
return revertReason;
}
public void setRevertReason(String revertReason) {
this.revertReason = revertReason;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEffectiveGasPrice() {
return effectiveGasPrice;
}
public void setEffectiveGasPrice(String effectiveGasPrice) {
this.effectiveGasPrice = effectiveGasPrice;
}
public String getBlobGasPrice() {
return blobGasPrice;
}
public void setBlobGasPrice(String blobGasPrice) {
this.blobGasPrice = blobGasPrice;
}
public String getBlobGasUsed() {
return blobGasUsed;
}
public void setBlobGasUsed(String blobGasUsed) {
this.blobGasUsed = blobGasUsed;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TransactionReceipt)) {
return false;
}
TransactionReceipt that = (TransactionReceipt) o;
if (getTransactionHash() != null
? !getTransactionHash().equals(that.getTransactionHash())
: that.getTransactionHash() != null) {
return false;
}
if (transactionIndex != null
? !transactionIndex.equals(that.transactionIndex)
: that.transactionIndex != null) {
return false;
}
if (getBlockHash() != null
? !getBlockHash().equals(that.getBlockHash())
: that.getBlockHash() != null) {
return false;
}
if (blockNumber != null
? !blockNumber.equals(that.blockNumber)
: that.blockNumber != null) {
return false;
}
if (cumulativeGasUsed != null
? !cumulativeGasUsed.equals(that.cumulativeGasUsed)
: that.cumulativeGasUsed != null) {
return false;
}
if (gasUsed != null ? !gasUsed.equals(that.gasUsed) : that.gasUsed != null) {
return false;
}
if (getContractAddress() != null
? !getContractAddress().equals(that.getContractAddress())
: that.getContractAddress() != null) {
return false;
}
if (getRoot() != null ? !getRoot().equals(that.getRoot()) : that.getRoot() != null) {
return false;
}
if (getStatus() != null
? !getStatus().equals(that.getStatus())
: that.getStatus() != null) {
return false;
}
if (getFrom() != null ? !getFrom().equals(that.getFrom()) : that.getFrom() != null) {
return false;
}
if (getTo() != null ? !getTo().equals(that.getTo()) : that.getTo() != null) {
return false;
}
if (getLogs() != null ? !getLogs().equals(that.getLogs()) : that.getLogs() != null) {
return false;
}
if (getLogsBloom() != null
? !getLogsBloom().equals(that.getLogsBloom())
: that.getLogsBloom() != null) {
return false;
}
if (getType() != null ? !getType().equals(that.getType()) : that.getType() != null) {
return false;
}
if (getEffectiveGasPrice() != null
? !getEffectiveGasPrice().equals(that.getEffectiveGasPrice())
: that.getEffectiveGasPrice() != null) {
return false;
}
if (blobGasPrice != null
? !blobGasPrice.equals(that.blobGasPrice)
: that.blobGasPrice != null) {
return false;
}
if (blobGasUsed != null
? !blobGasUsed.equals(that.blobGasUsed)
: that.blobGasUsed != null) {
return false;
}
return getRevertReason() != null
? getRevertReason().equals(that.getRevertReason())
: that.getRevertReason() == null;
}
@Override
public int hashCode() {
int result = getTransactionHash() != null ? getTransactionHash().hashCode() : 0;
result = 31 * result + (transactionIndex != null ? transactionIndex.hashCode() : 0);
result = 31 * result + (getBlockHash() != null ? getBlockHash().hashCode() : 0);
result = 31 * result + (blockNumber != null ? blockNumber.hashCode() : 0);
result = 31 * result + (cumulativeGasUsed != null ? cumulativeGasUsed.hashCode() : 0);
result = 31 * result + (gasUsed != null ? gasUsed.hashCode() : 0);
result = 31 * result + (getContractAddress() != null ? getContractAddress().hashCode() : 0);
result = 31 * result + (getRoot() != null ? getRoot().hashCode() : 0);
result = 31 * result + (getStatus() != null ? getStatus().hashCode() : 0);
result = 31 * result + (getFrom() != null ? getFrom().hashCode() : 0);
result = 31 * result + (getTo() != null ? getTo().hashCode() : 0);
result = 31 * result + (getLogs() != null ? getLogs().hashCode() : 0);
result = 31 * result + (getLogsBloom() != null ? getLogsBloom().hashCode() : 0);
result = 31 * result + (getRevertReason() != null ? getRevertReason().hashCode() : 0);
result = 31 * result + (getType() != null ? getType().hashCode() : 0);
result =
31 * result
+ (getEffectiveGasPrice() != null ? getEffectiveGasPrice().hashCode() : 0);
result = 31 * result + (blobGasPrice != null ? blobGasPrice.hashCode() : 0);
result = 31 * result + (blobGasUsed != null ? blobGasUsed.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "TransactionReceipt{"
+ "transactionHash='"
+ transactionHash
+ '\''
+ ", transactionIndex='"
+ transactionIndex
+ '\''
+ ", blockHash='"
+ blockHash
+ '\''
+ ", blockNumber='"
+ blockNumber
+ '\''
+ ", cumulativeGasUsed='"
+ cumulativeGasUsed
+ '\''
+ ", gasUsed='"
+ gasUsed
+ '\''
+ ", contractAddress='"
+ contractAddress
+ '\''
+ ", root='"
+ root
+ '\''
+ ", status='"
+ status
+ '\''
+ ", from='"
+ from
+ '\''
+ ", to='"
+ to
+ '\''
+ ", logs="
+ logs
+ ", logsBloom='"
+ logsBloom
+ '\''
+ ", revertReason='"
+ revertReason
+ '\''
+ ", type='"
+ type
+ '\''
+ ", effectiveGasPrice='"
+ effectiveGasPrice
+ '\''
+ ", blobGasPrice='"
+ blobGasPrice
+ '\''
+ ", blobGasused='"
+ blobGasUsed
+ '\''
+ '}';
}
}
| hyperledger/web3j | core/src/main/java/org/web3j/protocol/core/methods/response/TransactionReceipt.java |
179,777 | package edu.princeton.cs.algorithms;
/***************************************************************
* Compilation: javac RabinKarp.java
* Execution: java RabinKarp pat txt
*
* Reads in two strings, the pattern and the input text, and
* searches for the pattern in the input text using the
* Las Vegas version of the Rabin-Karp algorithm.
*
* % java RabinKarp abracadabra abacadabrabracabracadabrabrabracad
* pattern: abracadabra
* text: abacadabrabracabracadabrabrabracad
* match: abracadabra
*
* % java RabinKarp rab abacadabrabracabracadabrabrabracad
* pattern: rab
* text: abacadabrabracabracadabrabrabracad
* match: rab
*
* % java RabinKarp bcara abacadabrabracabracadabrabrabracad
* pattern: bcara
* text: abacadabrabracabracadabrabrabracad
*
* % java RabinKarp rabrabracad abacadabrabracabracadabrabrabracad
* text: abacadabrabracabracadabrabrabracad
* pattern: rabrabracad
*
* % java RabinKarp abacad abacadabrabracabracadabrabrabracad
* text: abacadabrabracabracadabrabrabracad
* pattern: abacad
*
***************************************************************/
import java.math.BigInteger;
import java.util.Random;
import edu.princeton.cs.introcs.StdOut;
public class RabinKarp {
private String pat; // the pattern // needed only for Las Vegas
private long patHash; // pattern hash value
private int M; // pattern length
private long Q; // a large prime, small enough to avoid long overflow
private int R; // radix
private long RM; // R^(M-1) % Q
public RabinKarp(int R, char[] pattern) {
throw new UnsupportedOperationException("Operation not supported yet");
}
public RabinKarp(String pat) {
this.pat = pat; // save pattern (needed only for Las Vegas)
R = 256;
M = pat.length();
Q = longRandomPrime();
// precompute R^(M-1) % Q for use in removing leading digit
RM = 1;
for (int i = 1; i <= M-1; i++)
RM = (R * RM) % Q;
patHash = hash(pat, M);
}
// Compute hash for key[0..M-1].
private long hash(String key, int M) {
long h = 0;
for (int j = 0; j < M; j++)
h = (R * h + key.charAt(j)) % Q;
return h;
}
// Las Vegas version: does pat[] match txt[i..i-M+1] ?
private boolean check(String txt, int i) {
for (int j = 0; j < M; j++)
if (pat.charAt(j) != txt.charAt(i + j))
return false;
return true;
}
// Monte Carlo version: always return true
private boolean check(int i) {
return true;
}
// check for exact match
public int search(String txt) {
int N = txt.length();
if (N < M) return N;
long txtHash = hash(txt, M);
// check for match at offset 0
if ((patHash == txtHash) && check(txt, 0))
return 0;
// check for hash match; if hash match, check for exact match
for (int i = M; i < N; i++) {
// Remove leading digit, add trailing digit, check for match.
txtHash = (txtHash + Q - RM*txt.charAt(i-M) % Q) % Q;
txtHash = (txtHash*R + txt.charAt(i)) % Q;
// match
int offset = i - M + 1;
if ((patHash == txtHash) && check(txt, offset))
return offset;
}
// no match
return N;
}
// a random 31-bit prime
private static long longRandomPrime() {
BigInteger prime = BigInteger.probablePrime(31, new Random());
return prime.longValue();
}
// test client
public static void main(String[] args) {
String pat = args[0];
String txt = args[1];
char[] pattern = pat.toCharArray();
char[] text = txt.toCharArray();
RabinKarp searcher = new RabinKarp(pat);
int offset = searcher.search(txt);
// print results
StdOut.println("text: " + txt);
// from brute force search method 1
StdOut.print("pattern: ");
for (int i = 0; i < offset; i++)
StdOut.print(" ");
StdOut.println(pat);
}
}
| fracpete/princeton-java-algorithms | src/main/java/edu/princeton/cs/algorithms/RabinKarp.java |
179,778 | /*******************************************************************************
* Copyright (c) 2015 David Lamparter, Daniel Marbach
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package ch.unil.genescore.vegas;
/**
* Refactored from R package CompQuadForm by Pierre Lafaye de Micheaux and Pierre Duchesne. See bottom of file for original code.
*
* Distribution function (survival function in fact) of quadratic forms in normal variables using Davies algorithm.
*
*/
public class Davies implements WeightedChisquareAlgorithm {
// ARGUMENTS
private final double log28 = .0866; /* log(2.0) / 8.0 */
private double sigsq, lmax, lmin, mean, c;
private double intl, ersm;
private int count, r, lim;
private boolean ndtsrt, fail;
private int n[], th[];
private double lb[], nc[];
double sigma_ = 0;
// // void qfc(double* lb1, double* nc1, int* n1, int *r1, double *sigma, double *c1, int *lim1, double *acc, double* trace, int* ifault, double *res)
//double[] lb1;
//double[] nc1;
//int[] n1;
//int[] r1;
//double[] sigma;
//double[] c1;
//int[] lim1;
//double[] acc;
double[] trace;
/** Value point at which the survival function is to be evaluated */
private double q_ = -1;
/** Distinct non-zero characteristic roots of A\Sigma */
private double[] lambda_ = null;
/** Respective orders of multiplicity of the lambdas (degrees of the chi2 variables) */
private int[] h_ = null;
/** Non-centrality parameters of the chi2 variables */
private double[] delta_ = null;
/** Error bound. R documentation: error bound. Suitable values for acc range from 0.001 to 0.00005 */
private double acc_ = -1;
/**
* Maximum number of integration terms. Realistic values for lim range from 1000 if the procedure is
* to be called repeatedly up to 50 000 if it is to be called only occasionally
*/
private int lim_ = -1;
/** The result */
private double qfval = -1;
/** Error code */
private int ifault = 0;
public class NonCovergeneceException extends RuntimeException {
private static final long serialVersionUID = 7845175270361304271L;
};
// ============================================================================
// PUBLIC METHODS
// davies <- function (q, lambda, h = rep(1, length(lambda)), delta = rep(0,
// length(lambda)), sigma = 0, lim = 10000, acc = 1e-04)
// {
// r <- length(lambda)
// if (length(h) != r)
// stop("lambda and h should have the same length!")
// if (length(delta) != r)
// stop("lambda and delta should have the same length!")
// out <- .C("qfc", lambdas = as.double(lambda), noncentral = as.double(delta),
// df = as.integer(h), r = as.integer(r), sigma = as.double(sigma),
// q = as.double(q), lim = as.integer(lim), acc = as.double(acc),
// trace = as.double(rep(0, 7)), ifault = as.integer(0),
// res = as.double(0), PACKAGE = "CompQuadForm")
// out$res <- 1 - out$res
// return(list(trace = out$trace, ifault = out$ifault, Qq = out$res))
// }
// <environment: namespace:CompQuadForm>
/** Constructor */
public Davies(double[] lambda) {
lambda_ = lambda;
h_ = new int[lambda.length];
for (int i=0; i<lambda.length; i++)
h_[i] = 1;
delta_ = new double[lambda.length];
for (int i=0; i<lambda.length; i++)
delta_[i] = 0;
acc_ = 1e-20;
lim_ = 50000;
}
// ----------------------------------------------------------------------------
/** Compute P(Q > q) */
public double probQsupx(double q) {
// initialize
q_ = q;
ifault = 0;
qfval = -41;
trace = new double[7];
for (int i=0; i<7; i++)
trace[i] = 0.0;
// compute
qfc();
qfval = 1 - qfval;
return qfval;
}
public int getIfault() {
return ifault;
}
// ============================================================================
// PRIVATE FUNCTIONS
/* to avoid underflows */
private double exp1(double x) {
return x < -50.0 ? 0.0 : Math.exp(x);
}
/* count number of calls to errbd, truncation, cfe */
private void counter() {
count = count + 1;
if ( count > lim ) {
ifault = 4;
throw new NonCovergeneceException();
}
}
private double square(double x) { return x*x; }
private double cube(double x) { return x*x*x; }
/* if (first) log(1 + x) ; else log(1 + x) - x */
private double log1(double x, boolean first) {
if (Math.abs(x) > 0.1)
{
return (first ? Math.log(1.0 + x) : (Math.log(1.0 + x) - x));
}
else
{
double s, s1, term, y, k;
y = x / (2.0 + x); term = 2.0 * cube(y); k = 3.0;
s = (first ? 2.0 : - x) * y;
y = square(y);
for (s1 = s + term / k; s1 != s; s1 = s + term / k)
{ k = k + 2.0; term = term * y; s = s1; }
return s;
}
}
/* find order of absolute values of lb */
private void order() {
int j, k; double lj;
//extern double *lb; extern int *th; extern int r; extern BOOL ndtsrt;
for ( j=0; j<r; j++ )
{
lj = Math.abs(lb[j]);
boolean gotol1 = false;
for (k = j-1; k>=0; k--)
{
if ( lj > Math.abs(lb[th[k]]) ) th[k + 1] = th[k];
//else goto l1;
else {
gotol1 = true;
break;
}
}
if (!gotol1)
k = -1;
//l1 :
th[k + 1] = j;
}
ndtsrt = false;
}
private double errbd(double u, double[] cx)
/* find bound on tail probability using mgf, cutoff
point returned to *cx */
{
double sum1, lj, ncj, x, y, xconst; int j, nj;
//extern double sigsq,*lb,*nc; extern int *n; extern int r;
counter();
xconst = u * sigsq; sum1 = u * xconst; u = 2.0 * u;
for (j=r-1; j>=0; j--)
{
nj = n[j]; lj = lb[j]; ncj = nc[j];
x = u * lj; y = 1.0 - x;
xconst = xconst + lj * (ncj / y + nj) / y;
sum1 = sum1 + ncj * square(x / y)
+ nj * (square(x) / y + log1(-x, false ));
}
cx[0] = xconst; return exp1(-0.5 * sum1);
}
private double ctff(double accx, double[] upn)
/* find ctff so that p(qf > ctff) < accx if (upn > 0,
p(qf < ctff) < accx otherwise */
{
double u1, u2, u, rb, c1;// c2;
double[] c2 = new double[1];
double[] xconst = new double[1];
//extern double lmin,lmax,mean;
u2 = upn[0]; u1 = 0.0; c1 = mean;
rb = 2.0 * ((u2 > 0.0) ? lmax : lmin);
for (u = u2 / (1.0 + u2 * rb); errbd(u, c2) > accx;
u = u2 / (1.0 + u2 * rb))
{
u1 = u2; c1 = c2[0]; u2 = 2.0 * u2;
}
for (u = (c1 - mean) / (c2[0] - mean); u < 0.9;
u = (c1 - mean) / (c2[0] - mean))
{
u = (u1 + u2) / 2.0;
if (errbd(u / (1.0 + u * rb), xconst) > accx)
{ u1 = u; c1 = xconst[0]; }
else
{ u2 = u; c2[0] = xconst[0]; }
}
upn[0] = u2; return c2[0];
}
private double truncation(double u, double tausq)
/* bound integration error due to truncation at u */
{
double sum1, sum2, prod1, prod2, prod3, lj, ncj,
x, y, err1, err2;
int j, nj, s;
//extern double sigsq,*lb,*nc; extern int *n; extern int r;
counter();
sum1 = 0.0; prod2 = 0.0; prod3 = 0.0; s = 0;
sum2 = (sigsq + tausq) * square(u); prod1 = 2.0 * sum2;
u = 2.0 * u;
for (j=0; j<r; j++ )
{
lj = lb[j]; ncj = nc[j]; nj = n[j];
x = square(u * lj);
sum1 = sum1 + ncj * x / (1.0 + x);
if (x > 1.0)
{
prod2 = prod2 + nj * Math.log(x);
prod3 = prod3 + nj * log1(x, true );
s = s + nj;
}
else prod1 = prod1 + nj * log1(x, true );
}
sum1 = 0.5 * sum1;
prod2 = prod1 + prod2; prod3 = prod1 + prod3;
x = exp1(-sum1 - 0.25 * prod2) / Math.PI;
y = exp1(-sum1 - 0.25 * prod3) / Math.PI;
err1 = ( s == 0 ) ? 1.0 : x * 2.0 / s;
err2 = ( prod3 > 1.0 ) ? 2.5 * y : 1.0;
if (err2 < err1) err1 = err2;
x = 0.5 * sum2;
err2 = ( x <= y ) ? 1.0 : y / x;
return ( err1 < err2 ) ? err1 : err2;
}
private void findu(double[] utx, double accx)
/* find u such that truncation(u) < accx and truncation(u / 1.2) > accx */
{
double u, ut; int i;
final double divis[]= { 2.0,1.4,1.2,1.1 };
ut = utx[0]; u = ut / 4.0;
if ( truncation(u, 0.0) > accx )
{
for ( u = ut; truncation(u, 0.0) > accx; u = ut) ut = ut * 4.0;
}
else
{
ut = u;
for ( u = u / 4.0; truncation(u, 0.0) <= accx; u = u / 4.0 )
ut = u;
}
for ( i=0;i<4;i++)
{ u = ut/divis[i]; if ( truncation(u, 0.0) <= accx ) ut = u; }
utx[0] = ut;
}
private void integrate(int nterm, double interv, double tausq, boolean mainx)
/* carry out integration with nterm terms, at stepsize
interv. if (! mainx) multiply integrand by
1.0-exp(-0.5*tausq*u^2) */
{
double inpi, u, sum1, sum2, sum3, x, y, z;
int k, j, nj;
//extern double intl,ersm; extern double sigsq,c;
//extern int *n; extern double *lb,*nc; extern int r;
inpi = interv / Math.PI;
for ( k = nterm; k>=0; k--)
{
u = (k + 0.5) * interv;
sum1 = - 2.0 * u * c; sum2 = Math.abs(sum1);
sum3 = - 0.5 * sigsq * square(u);
for ( j = r-1; j>=0; j--)
{
nj = n[j]; x = 2.0 * lb[j] * u; y = square(x);
sum3 = sum3 - 0.25 * nj * log1(y, true );
y = nc[j] * x / (1.0 + y);
z = nj * Math.atan(x) + y;
sum1 = sum1 + z; sum2 = sum2 + Math.abs(z);
sum3 = sum3 - 0.5 * x * y;
}
x = inpi * exp1(sum3) / u;
if ( ! mainx )
x = x * (1.0 - exp1(-0.5 * tausq * square(u)));
sum1 = Math.sin(0.5 * sum1) * x; sum2 = 0.5 * sum2 * x;
intl = intl + sum1; ersm = ersm + sum2;
}
}
private double cfe(double x)
/* coef of tausq in error when convergence factor of
exp1(-0.5*tausq*u^2) is used when df is evaluated at x */
{
double axl, axl1, axl2, sxl, sum1, lj; int j, k, t;
//extern BOOL ndtsrt,fail; extern int *th,*n; extern double *lb,*nc;
//extern int r;
counter();
if (ndtsrt) order();
axl = Math.abs(x); sxl = (x>0.0) ? 1.0 : -1.0; sum1 = 0.0;
for ( j = r-1; j>=0; j-- ) {
t = th[j];
if ( lb[t] * sxl > 0.0 )
{
lj = Math.abs(lb[t]);
axl1 = axl - lj * (n[t] + nc[t]); axl2 = lj / log28;
if ( axl1 > axl2 )
axl = axl1;
else
{
if ( axl > axl2 )
axl = axl2;
sum1 = (axl - axl1) / lj;
for ( k = j-1; k>=0; k--)
sum1 = sum1 + (n[th[k]] + nc[th[k]]);
//goto l;
break;
}
}
}
//l:
if (sum1 > 100.0) {
fail = true;
return 1.0;
} else
return Math.pow(2.0,(sum1 / 4.0)) / (Math.PI * square(axl));
}
private void qfc()
/* distribution function of a linear combination of non-central
chi-squared random variables :
input:
lb[j] coefficient of j-th chi-squared variable
nc[j] non-centrality parameter
n[j] degrees of freedom
j = 0, 2 ... r-1
sigma coefficient of standard normal variable
c1 point at which df is to be evaluated
lim maximum number of terms in integration
acc maximum error
output:
ifault = 1 required accuracy NOT achieved
2 round-off error possibly significant
3 invalid parameters
4 unable to locate integration parameters
5 out of memory
trace[0] absolute sum
trace[1] total number of integration terms
trace[2] number of integrations
trace[3] integration interval in final integration
trace[4] truncation point in initial integration
trace[5] s.d. of initial convergence factor
trace[6] cycles to locate integration parameters */
{
int j, nj, nt, ntm; double acc1, almx, xlim, xnt, xntm;
double tausq, sd, intv, intv1, x, d1, d2, lj, ncj;
double[] utx = new double[1];
double[] up = new double[1];
double[] un = new double[1];
//extern double sigsq, lmax, lmin, mean;
//extern double intl,ersm;
//extern int r,lim; extern double c;
//extern int *n,*th; extern double *lb,*nc;
qfval = -1.0;
final int rats[]={1,2,4,8};
//if (setjmp(env) != 0) { *ifault=4; goto endofproc; }
r=lambda_.length; lim=lim_; c=q_;
n=h_; lb=lambda_; nc=delta_;
for ( j = 0; j<7; j++ ) trace[j] = 0.0;
ifault = 0; count = 0;
intl = 0.0; ersm = 0.0;
qfval = -1.0; acc1 = acc_; ndtsrt = true; fail = false;
xlim = (double)lim;
th= new int[r]; //(int*)malloc(r*(sizeof(int)));
/* find mean, sd, max and min of lb,
check that parameter values are valid */
sigsq = square(sigma_); sd = sigsq;
lmax = 0.0; lmin = 0.0; mean = 0.0;
for (j=0; j<r; j++ )
{
nj = n[j]; lj = lb[j]; ncj = nc[j];
if ( nj < 0 || ncj < 0.0 ) { ifault = 3; return; } //goto endofproc; }
sd = sd + square(lj) * (2 * nj + 4.0 * ncj);
mean = mean + lj * (nj + ncj);
if (lmax < lj) lmax = lj ; else if (lmin > lj) lmin = lj;
}
if ( sd == 0.0 )
{ qfval = (c > 0.0) ? 1.0 : 0.0; return; } //goto endofproc; }
if ( lmin == 0.0 && lmax == 0.0 && sigma_ == 0.0 )
{ ifault = 3; return; } //goto endofproc; }
sd = Math.sqrt(sd);
almx = (lmax < - lmin) ? - lmin : lmax;
/* starting values for findu, ctff */
utx[0] = 16.0 / sd; up[0] = 4.5 / sd; un[0] = - up[0];
/* truncation point with no convergence factor */
findu(utx, .5 * acc1);
/* does convergence factor help */
if (c != 0.0 && (almx > 0.07 * sd))
{
tausq = .25 * acc1 / cfe(c);
if (fail) fail = false ;
else if (truncation(utx[0], tausq) < .2 * acc1)
{
sigsq = sigsq + tausq;
findu(utx, .25 * acc1);
trace[5] = Math.sqrt(tausq);
}
}
trace[4] = utx[0]; acc1 = 0.5 * acc1;
/* find RANGE of distribution, quit if outside this */
//l1:
while (true) {
d1 = ctff(acc1, up) - c;
if (d1 < 0.0) { qfval = 1.0; return; }
d2 = c - ctff(acc1, un);
if (d2 < 0.0) { qfval = 0.0; return; }
/* find integration interval */
intv = 2.0 * Math.PI / ((d1 > d2) ? d1 : d2);
/* calculate number of terms required for main and
auxillary integrations */
xnt = utx[0] / intv; xntm = 3.0 / Math.sqrt(acc1);
if (!(xnt > xntm * 1.5))
break;
/* parameters for auxillary integration */
if (xntm > xlim) { ifault = 1; return; }
ntm = (int)Math.floor(xntm+0.5);
intv1 = utx[0] / ntm; x = 2.0 * Math.PI / intv1;
if (x <= Math.abs(c)) break;
/* calculate convergence factor */
tausq = .33 * acc1 / (1.1 * (cfe(c - x) + cfe(c + x)));
if (fail) break;
acc1 = .67 * acc1;
/* auxillary integration */
integrate(ntm, intv1, tausq, false );
xlim = xlim - xntm; sigsq = sigsq + tausq;
trace[2] = trace[2] + 1; trace[1] = trace[1] + ntm + 1;
/* find truncation point with new convergence factor */
findu(utx, .25 * acc1); acc1 = 0.75 * acc1;
//goto l1;
}
/* main integration */
// l2:
trace[3] = intv;
if (xnt > xlim) { ifault = 1; return; }
nt = (int)Math.floor(xnt+0.5);
integrate(nt, intv, 0.0, true );
trace[2] = trace[2] + 1; trace[1] = trace[1] + nt + 1;
qfval = 0.5 - intl;
trace[0] = ersm;
/* test whether round-off error could be significant
allow for radix 8 or 16 machines */
up[0]=ersm; x = up[0] + acc_ / 10.0;
for (j=0;j<4;j++) { if (rats[j] * x == rats[j] * up[0]) ifault = 2; }
//endofproc :
//trace[6] = (double)count;
//res[0] = qfval;
//return;
}
}
// #define UseDouble 0 /* all floating point double */
//
// #include <stdio.h>
// #include <stdlib.h>
// #include <math.h>
// #include <setjmp.h>
//
// #define TRUE 1
// #define FALSE 0
// typedef int BOOL;
//
//
// #define pi 3.14159265358979
// #define log28 .0866 /* log(2.0) / 8.0 */
//
// extern "C" {
//
// static double sigsq, lmax, lmin, mean, c;
// static double intl, ersm;
// static int count, r, lim; static BOOL ndtsrt, fail;
// static int *n,*th; static double *lb,*nc;
// static jmp_buf env;
//
//
//
// static double exp1(double x) /* to avoid underflows */
// { return x < -50.0 ? 0.0 : exp(x); }
//
// static void counter(void)
// /* count number of calls to errbd, truncation, cfe */
// {
// extern int count,lim;
// count = count + 1;
// if ( count > lim ) longjmp(env,1);
// }
//
// static double square(double x) { return x*x; }
//
// static double cube(double x) { return x*x*x; }
//
// static double log1(double x, BOOL first)
// /* if (first) log(1 + x) ; else log(1 + x) - x */
// {
// if (fabs(x) > 0.1)
// {
// return (first ? log(1.0 + x) : (log(1.0 + x) - x));
// }
// else
// {
// double s, s1, term, y, k;
// y = x / (2.0 + x); term = 2.0 * cube(y); k = 3.0;
// s = (first ? 2.0 : - x) * y;
// y = square(y);
// for (s1 = s + term / k; s1 != s; s1 = s + term / k)
// { k = k + 2.0; term = term * y; s = s1; }
// return s;
// }
// }
//
// static void order(void)
// /* find order of absolute values of lb */
// {
// int j, k; double lj;
// extern double *lb; extern int *th; extern int r; extern BOOL ndtsrt;
// for ( j=0; j<r; j++ )
// {
// lj = fabs(lb[j]);
// for (k = j-1; k>=0; k--)
// {
// if ( lj > fabs(lb[th[k]]) ) th[k + 1] = th[k];
// else goto l1;
// }
// k = -1;
// l1 :
// th[k + 1] = j;
// }
// ndtsrt = FALSE;
// }
//
//
// static double errbd(double u, double* cx)
// /* find bound on tail probability using mgf, cutoff
// point returned to *cx */
// {
// double sum1, lj, ncj, x, y, xconst; int j, nj;
// extern double sigsq,*lb,*nc; extern int *n; extern int r;
// counter();
// xconst = u * sigsq; sum1 = u * xconst; u = 2.0 * u;
// for (j=r-1; j>=0; j--)
// {
// nj = n[j]; lj = lb[j]; ncj = nc[j];
// x = u * lj; y = 1.0 - x;
// xconst = xconst + lj * (ncj / y + nj) / y;
// sum1 = sum1 + ncj * square(x / y)
// + nj * (square(x) / y + log1(-x, FALSE ));
// }
// *cx = xconst; return exp1(-0.5 * sum1);
// }
//
// static double ctff(double accx, double* upn)
// /* find ctff so that p(qf > ctff) < accx if (upn > 0,
// p(qf < ctff) < accx otherwise */
// {
// double u1, u2, u, rb, xconst, c1, c2;
// extern double lmin,lmax,mean;
// u2 = *upn; u1 = 0.0; c1 = mean;
// rb = 2.0 * ((u2 > 0.0) ? lmax : lmin);
// for (u = u2 / (1.0 + u2 * rb); errbd(u, &c2) > accx;
// u = u2 / (1.0 + u2 * rb))
// {
// u1 = u2; c1 = c2; u2 = 2.0 * u2;
// }
// for (u = (c1 - mean) / (c2 - mean); u < 0.9;
// u = (c1 - mean) / (c2 - mean))
// {
// u = (u1 + u2) / 2.0;
// if (errbd(u / (1.0 + u * rb), &xconst) > accx)
// { u1 = u; c1 = xconst; }
// else
// { u2 = u; c2 = xconst; }
// }
// *upn = u2; return c2;
// }
//
// static double truncation(double u, double tausq)
// /* bound integration error due to truncation at u */
// {
// double sum1, sum2, prod1, prod2, prod3, lj, ncj,
// x, y, err1, err2;
// int j, nj, s;
// extern double sigsq,*lb,*nc; extern int *n; extern int r;
//
// counter();
// sum1 = 0.0; prod2 = 0.0; prod3 = 0.0; s = 0;
// sum2 = (sigsq + tausq) * square(u); prod1 = 2.0 * sum2;
// u = 2.0 * u;
// for (j=0; j<r; j++ )
// {
// lj = lb[j]; ncj = nc[j]; nj = n[j];
// x = square(u * lj);
// sum1 = sum1 + ncj * x / (1.0 + x);
// if (x > 1.0)
// {
// prod2 = prod2 + nj * log(x);
// prod3 = prod3 + nj * log1(x, TRUE );
// s = s + nj;
// }
// else prod1 = prod1 + nj * log1(x, TRUE );
// }
// sum1 = 0.5 * sum1;
// prod2 = prod1 + prod2; prod3 = prod1 + prod3;
// x = exp1(-sum1 - 0.25 * prod2) / pi;
// y = exp1(-sum1 - 0.25 * prod3) / pi;
// err1 = ( s == 0 ) ? 1.0 : x * 2.0 / s;
// err2 = ( prod3 > 1.0 ) ? 2.5 * y : 1.0;
// if (err2 < err1) err1 = err2;
// x = 0.5 * sum2;
// err2 = ( x <= y ) ? 1.0 : y / x;
// return ( err1 < err2 ) ? err1 : err2;
// }
//
// static void findu(double* utx, double accx)
// /* find u such that truncation(u) < accx and truncation(u / 1.2) > accx */
// {
// double u, ut; int i;
// static double divis[]={2.0,1.4,1.2,1.1};
// ut = *utx; u = ut / 4.0;
// if ( truncation(u, 0.0) > accx )
// {
// for ( u = ut; truncation(u, 0.0) > accx; u = ut) ut = ut * 4.0;
// }
// else
// {
// ut = u;
// for ( u = u / 4.0; truncation(u, 0.0) <= accx; u = u / 4.0 )
// ut = u;
// }
// for ( i=0;i<4;i++)
// { u = ut/divis[i]; if ( truncation(u, 0.0) <= accx ) ut = u; }
// *utx = ut;
// }
//
//
// static void integrate(int nterm, double interv, double tausq, BOOL mainx)
// /* carry out integration with nterm terms, at stepsize
// interv. if (! mainx) multiply integrand by
// 1.0-exp(-0.5*tausq*u^2) */
// {
// double inpi, u, sum1, sum2, sum3, x, y, z;
// int k, j, nj;
// extern double intl,ersm; extern double sigsq,c;
// extern int *n; extern double *lb,*nc; extern int r;
// inpi = interv / pi;
// for ( k = nterm; k>=0; k--)
// {
// u = (k + 0.5) * interv;
// sum1 = - 2.0 * u * c; sum2 = fabs(sum1);
// sum3 = - 0.5 * sigsq * square(u);
// for ( j = r-1; j>=0; j--)
// {
// nj = n[j]; x = 2.0 * lb[j] * u; y = square(x);
// sum3 = sum3 - 0.25 * nj * log1(y, TRUE );
// y = nc[j] * x / (1.0 + y);
// z = nj * atan(x) + y;
// sum1 = sum1 + z; sum2 = sum2 + fabs(z);
// sum3 = sum3 - 0.5 * x * y;
// }
// x = inpi * exp1(sum3) / u;
// if ( ! mainx )
// x = x * (1.0 - exp1(-0.5 * tausq * square(u)));
// sum1 = sin(0.5 * sum1) * x; sum2 = 0.5 * sum2 * x;
// intl = intl + sum1; ersm = ersm + sum2;
// }
// }
//
// static double cfe(double x)
// /* coef of tausq in error when convergence factor of
// exp1(-0.5*tausq*u^2) is used when df is evaluated at x */
// {
// double axl, axl1, axl2, sxl, sum1, lj; int j, k, t;
// extern BOOL ndtsrt,fail; extern int *th,*n; extern double *lb,*nc;
// extern int r;
// counter();
// if (ndtsrt) order();
// axl = fabs(x); sxl = (x>0.0) ? 1.0 : -1.0; sum1 = 0.0;
// for ( j = r-1; j>=0; j-- )
// { t = th[j];
// if ( lb[t] * sxl > 0.0 )
// {
// lj = fabs(lb[t]);
// axl1 = axl - lj * (n[t] + nc[t]); axl2 = lj / log28;
// if ( axl1 > axl2 ) axl = axl1 ; else
// {
// if ( axl > axl2 ) axl = axl2;
// sum1 = (axl - axl1) / lj;
// for ( k = j-1; k>=0; k--)
// sum1 = sum1 + (n[th[k]] + nc[th[k]]);
// goto l;
// }
// }
// }
// l:
// if (sum1 > 100.0)
// { fail = TRUE; return 1.0; } else
// return pow(2.0,(sum1 / 4.0)) / (pi * square(axl));
// }
//
//
// void qfc(double* lb1, double* nc1, int* n1, int *r1, double *sigma, double *c1, int *lim1, double *acc, double* trace, int* ifault, double *res)
//
// /* distribution function of a linear combination of non-central
// chi-squared random variables :
//
// input:
// lb[j] coefficient of j-th chi-squared variable
// nc[j] non-centrality parameter
// n[j] degrees of freedom
// j = 0, 2 ... r-1
// sigma coefficient of standard normal variable
// c1 point at which df is to be evaluated
// lim maximum number of terms in integration
// acc maximum error
//
// output:
// ifault = 1 required accuracy NOT achieved
// 2 round-off error possibly significant
// 3 invalid parameters
// 4 unable to locate integration parameters
// 5 out of memory
//
// trace[0] absolute sum
// trace[1] total number of integration terms
// trace[2] number of integrations
// trace[3] integration interval in final integration
// trace[4] truncation point in initial integration
// trace[5] s.d. of initial convergence factor
// trace[6] cycles to locate integration parameters */
//
// {
// int j, nj, nt, ntm; double acc1, almx, xlim, xnt, xntm;
// double utx, tausq, sd, intv, intv1, x, up, un, d1, d2, lj, ncj;
// extern double sigsq, lmax, lmin, mean;
// extern double intl,ersm;
// extern int r,lim; extern double c;
// extern int *n,*th; extern double *lb,*nc;
// double qfval = -1.0;
// static int rats[]={1,2,4,8};
//
// if (setjmp(env) != 0) { *ifault=4; goto endofproc; }
// r=r1[0]; lim=lim1[0]; c=c1[0];
// n=n1; lb=lb1; nc=nc1;
// for ( j = 0; j<7; j++ ) trace[j] = 0.0;
// *ifault = 0; count = 0;
// intl = 0.0; ersm = 0.0;
// qfval = -1.0; acc1 = acc[0]; ndtsrt = TRUE; fail = FALSE;
// xlim = (double)lim;
// th=(int*)malloc(r*(sizeof(int)));
// if (! th) { *ifault=5; goto endofproc; }
//
// /* find mean, sd, max and min of lb,
// check that parameter values are valid */
// sigsq = square(sigma[0]); sd = sigsq;
// lmax = 0.0; lmin = 0.0; mean = 0.0;
// for (j=0; j<r; j++ )
// {
// nj = n[j]; lj = lb[j]; ncj = nc[j];
// if ( nj < 0 || ncj < 0.0 ) { *ifault = 3; goto endofproc; }
// sd = sd + square(lj) * (2 * nj + 4.0 * ncj);
// mean = mean + lj * (nj + ncj);
// if (lmax < lj) lmax = lj ; else if (lmin > lj) lmin = lj;
// }
// if ( sd == 0.0 )
// { qfval = (c > 0.0) ? 1.0 : 0.0; goto endofproc; }
// if ( lmin == 0.0 && lmax == 0.0 && sigma[0] == 0.0 )
// { *ifault = 3; goto endofproc; }
// sd = sqrt(sd);
// almx = (lmax < - lmin) ? - lmin : lmax;
//
// /* starting values for findu, ctff */
// utx = 16.0 / sd; up = 4.5 / sd; un = - up;
// /* truncation point with no convergence factor */
// findu(&utx, .5 * acc1);
// /* does convergence factor help */
// if (c != 0.0 && (almx > 0.07 * sd))
// {
// tausq = .25 * acc1 / cfe(c);
// if (fail) fail = FALSE ;
// else if (truncation(utx, tausq) < .2 * acc1)
// {
// sigsq = sigsq + tausq;
// findu(&utx, .25 * acc1);
// trace[5] = sqrt(tausq);
// }
// }
// trace[4] = utx; acc1 = 0.5 * acc1;
//
// /* find RANGE of distribution, quit if outside this */
// l1:
// d1 = ctff(acc1, &up) - c;
// if (d1 < 0.0) { qfval = 1.0; goto endofproc; }
// d2 = c - ctff(acc1, &un);
// if (d2 < 0.0) { qfval = 0.0; goto endofproc; }
// /* find integration interval */
// intv = 2.0 * pi / ((d1 > d2) ? d1 : d2);
// /* calculate number of terms required for main and
// auxillary integrations */
// xnt = utx / intv; xntm = 3.0 / sqrt(acc1);
// if (xnt > xntm * 1.5)
// {
// /* parameters for auxillary integration */
// if (xntm > xlim) { *ifault = 1; goto endofproc; }
// ntm = (int)floor(xntm+0.5);
// intv1 = utx / ntm; x = 2.0 * pi / intv1;
// if (x <= fabs(c)) goto l2;
// /* calculate convergence factor */
// tausq = .33 * acc1 / (1.1 * (cfe(c - x) + cfe(c + x)));
// if (fail) goto l2;
// acc1 = .67 * acc1;
// /* auxillary integration */
// integrate(ntm, intv1, tausq, FALSE );
// xlim = xlim - xntm; sigsq = sigsq + tausq;
// trace[2] = trace[2] + 1; trace[1] = trace[1] + ntm + 1;
// /* find truncation point with new convergence factor */
// findu(&utx, .25 * acc1); acc1 = 0.75 * acc1;
// goto l1;
// }
//
// /* main integration */
// l2:
// trace[3] = intv;
// if (xnt > xlim) { *ifault = 1; goto endofproc; }
// nt = (int)floor(xnt+0.5);
// integrate(nt, intv, 0.0, TRUE );
// trace[2] = trace[2] + 1; trace[1] = trace[1] + nt + 1;
// qfval = 0.5 - intl;
// trace[0] = ersm;
//
// /* test whether round-off error could be significant
// allow for radix 8 or 16 machines */
// up=ersm; x = up + acc[0] / 10.0;
// for (j=0;j<4;j++) { if (rats[j] * x == rats[j] * up) *ifault = 2; }
//
// endofproc :
// free((char*)th);
// trace[6] = (double)count;
// res[0] = qfval;
// return;
// }
//
//
// }
| Bonder-MJ/systemsgenetics | Downstreamer/src/main/java/ch/unil/genescore/vegas/Davies.java |
179,779 | /*******************************************************************************
* Copyright (c) 2015 David Lamparter, Daniel Marbach
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package ch.unil.genescore.vegas;
import org.apache.commons.math3.distribution.NormalDistribution;
/**
* Refactored from R package CompQuadForm by Pierre Lafaye de Micheaux and Pierre Duchesne. See bottom of file for original code.
*
* Distribution function (survival function in fact) of quadratic forms in normal variables using Fare- brothers algorithm.
*
* Algorithm AS 204 Appl. Statist. (1984) Vol. 33, No.3
* ruben evaluates the probability that a positive definite quadratic form in Normal variates is less than a given value
*/
public class Farebrother implements WeightedChisquareAlgorithm {
// ARGUMENTS
/** Value point at which the survival function is to be evaluated */
private double q_ = -1;
/** Distinct non-zero characteristic roots of A\Sigma */
private double[] lambda_ = null;
/** Respective orders of multiplicity of the lambdas (degrees of the chi2 variables) */
private int[] h_ = null;
/** Non-centrality parameters of the chi2 variables */
private double[] delta_ = null;
/** Accuracy requested */
private double eps_ = -1;
/** Max number of iterations */
private int maxit_ = -1;
/** if mode>0 then beta = mode * lambda_min otherwise beta = beta*B = 2/(1/lambda_min + 1/lambda_max) */
private double mode_ = 1;
/** Normal distribution */
private NormalDistribution normal_ = new NormalDistribution(0.0, 1.0);
/** The result */
private double res_ = -1;
/** Error code */
private int ifault_ = 0;
// ============================================================================
// PUBLIC METHODS
/** Constructor */
public Farebrother(double[] lambda) {
lambda_ = lambda;
h_ = new int[lambda.length];
for (int i=0; i<lambda.length; i++)
h_[i] = 1;
delta_ = new double[lambda.length];
for (int i=0; i<lambda.length; i++)
delta_[i] = 0;
eps_ = 1e-16;
maxit_ = 1000000;
mode_ = -1.0;
}
// ----------------------------------------------------------------------------
/** Compute P(Q > q) */
public double probQsupx(double q) {
// initialize
q_ = q;
ifault_ = 0;
res_ = -41;
// compute
ruben();
res_ = 1 - res_;
if(res_<1E-15){
res_=1E-15;
}
return res_;
}
// ============================================================================
// PRIVATE FUNCTIONS
/**
* ruben.cpp:
* Algorithm AS 204 Appl. Statist. (1984) Vol. 33, No.3
* ruben evaluates the probability that a positive definite quadratic form in Normal variates is less than a given value
*/
private void ruben() {
ifault_ = -41; // I added this initialization --daniel
//void ruben(double *lambda, int *mult, double *delta, int *n, double *c, double *mode, int *maxit, double *eps, double *dnsty, int *ifault, double *res) {
// Initialized at 0 in the R code
double dnsty = 0.0;
int i,k,m,j;
//double pnorm(double q, double mean, double sd, int lower_tail, int log_p);
double ao, aoinv, z, bbeta, eps2, hold, hold2, sum, sum1, dans, lans, pans, prbty, tol;
double[] gamma = new double[lambda_.length];
double[] theta = new double[lambda_.length];
double[] a = new double[maxit_];
double[] b = new double[maxit_];
hold = 0;//TMP
if ((lambda_.length<1) || (q_<=0) || (maxit_ <1) || (eps_<=0.0)) {
res_ = -2.0;
ifault_ = 2;
return;
}
tol = -200.0;
// Preliminaries
sum = lambda_[0];
bbeta = sum;
for (i=1;i<=lambda_.length;i++) {
hold = lambda_[i-1];
if ((hold<=0.0) || (h_[i-1]<1) || (delta_[i-1]<0.0)) {
res_ = -7.0;
ifault_ = -i;
return;
}
if (bbeta > hold) bbeta = hold; // calcul du max des lambdas
if (sum < hold) sum = hold; // calcul du min des lambdas
}
if (mode_ > 0.0) {
// if ((2.0/(1.0/bbeta+1.0/sum))>1.8*sum) bbeta = sum; // comme dans NAG : methode avec betaA
bbeta = mode_*bbeta;
} else {
bbeta = 2.0/(1.0/bbeta+1.0/sum); // methode avec betaB
}
k = 0;
sum = 1.0;
sum1 = 0.0;
for (i=1;i<=lambda_.length;i++) {
hold = bbeta/lambda_[i-1];
gamma[i-1] = 1.0 - hold;
sum = sum*Math.pow(hold,h_[i-1]); //???? pas sur ..
sum1 = sum1 + delta_[i-1];
k = k + h_[i-1];
theta[i-1] = 1.0;
}
// System.out.println("sum: " + sum);
// System.out.println("sum1: " + sum1);
// System.out.println("hold: " + hold);
ao = Math.exp(0.5*(Math.log(sum)-sum1));
// System.out.println("ao:" + ao);
if (ao <= 0.0) {
res_ = 0.0;
dnsty = 0.0;
ifault_ = 1; // returns after this (the rest of the function is in the else)
} else { // evaluate probability and density of chi-squared on k degrees of freedom. The constant 0.22579135264473 is ln(sqrt(pi/2))
z = q_/bbeta;
if ((k%2) == 0) { // k est un entier donc on regarde si k est divisible par 2: k == (k/2)*k
i = 2;
lans = -0.5*z;
dans = Math.exp(lans);
pans = 1.0 - dans;
} else {
i = 1;
lans = -0.5*(z+Math.log(z)) - 0.22579135264473;
dans = Math.exp(lans);
//pans = pnorm(Math.sqrt(z),0.0,1.0,1,0) - pnorm(-Math.sqrt(z),0.0,1.0,1,0);
pans = normal_.cumulativeProbability(Math.sqrt(z)) - normal_.cumulativeProbability(-Math.sqrt(z));
}
k = k-2;
for (j=i;j<=k;j=j+2) {
if (lans < tol) {
lans = lans + Math.log(z/(double)j);
dans = Math.exp(lans);
} else {
dans = dans*z/(double)j;
}
pans = pans -dans;
}
// evaluate successive terms of expansion
prbty = pans;
dnsty = dans;
eps2 = eps_/ao;
aoinv = 1.0/ao;
sum = aoinv - 1.0;
for (m=1;m<=maxit_;m++) {
sum1 = 0.0;
for (i=1;i<=lambda_.length;i++) {
hold = theta[i-1];
hold2 = hold*gamma[i-1];
theta[i-1] = hold2;
sum1 = sum1 + hold2*h_[i-1]+m*delta_[i-1]*(hold-hold2);
}
sum1 = 0.5*sum1;
b[m-1] = sum1;
for (i=m-1;i>=1;i--) {
sum1 = sum1 + b[i-1]*a[m-i-1];
}
sum1 = sum1/(double)m;
a[m-1] = sum1;
k = k + 2;
if (lans < tol) {
lans = lans + Math.log(z/(double)k);
dans = Math.exp(lans);
} else {
dans = dans*z/(double)k;
}
pans = pans - dans;
sum = sum - sum1;
dnsty = dnsty + dans*sum1;
sum1 = pans*sum1;
prbty = prbty + sum1;
if (prbty<(-aoinv)) {
res_ = -3.0;
ifault_ = 3;
return;
}
// if(m == 1 || m % 1000 == 0){
// System.out.println(sum + "\t" + sum1 + "\t" + lans + "\t" + dans + "\t" + pans + "\t" + dnsty + "\t" + prbty);
// }
if (Math.abs(pans*sum) < eps2) {
if (Math.abs(sum1) < eps2) {
ifault_ = 0; // this is overwritten below (ifault_=4) -- I now changed the code below
// I COMMENTED THIS SO WE CAN See IF THERE WAS CONVERGENCE OR NOT -daniel
//m = maxit_+1; // and WHY would you do that?
break;
}
}
}
if (m > maxit_) // I ADDED THIS IF, OTHERWISE IT MAKES NO SENSE -daniel
ifault_ = 4;
// Check if I understood correctly
if(!(ifault_ == 0 || ifault_ == 4)){
throw new RuntimeException();
}
// System.out.println("ao : " + ao);
// System.out.println("prbty: " + prbty);
//
dnsty = ao*dnsty/(bbeta+bbeta);
prbty = ao*prbty;
// With my edits above, this now makes a bit mores sense
if (prbty<0.0 || prbty>1.0) {ifault_ = ifault_ + 5; // why the ... would they write it like this? I.e., ifault_ = 9
} else {
if (dnsty<0.0) ifault_ = ifault_ + 6;
}
res_ = prbty;
}
return;
}
// ============================================================================
// GETTERS AND SETTERS
public int getIfault() { return ifault_; }
}
// Original code from the R-package
// ================================
//farebrother <- function(q,lambda,h = rep(1,length(lambda)),delta = rep(0,length(lambda)),maxit=100000,eps=10^(-10),mode=1) {
//
//
// r <- length(lambda)
// if (length(h) != r) stop("lambda and h should have the same length!")
// if (length(delta) != r) stop("lambda and delta should have the same length!")
//
// # mode <- 1 # ??
//
// dnsty <- 0.0
// ifault <- 0
// res <- 0
//
//
// out <- .C("ruben",lambda=as.double(lambda),h=as.integer(h),delta=as.double(delta),r=as.integer(r),q=as.double(q),mode=as.double(mode),maxit=as.integer(maxit),eps=as.double(eps),dnsty=as.double(dnsty),ifault=as.integer(ifault),res=as.double(res),PACKAGE="CompQuadForm")
//
// out$res <- 1 - out$res
//
// return(out)
//
// }
//
//
//
//#include <R.h>
//#include "Rmath.h"
//
//extern "C" {
//
////Algorithm AS 204 Appl. Statist. (1984) Vol. 33, No.3
////ruben evaluates the probability that a positive definite quadratic form in Normal variates is less than a given value
//
// void ruben(double *lambda, int *mult, double *delta, int *n, double *c, double *mode, int *maxit, double *eps, double *dnsty, int *ifault, double *res) {
//
// int i,k,m,j;
// double pnorm(double q, double mean, double sd, int lower_tail, int log_p);
// double ao, aoinv, z, bbeta, eps2, hold, hold2, sum, sum1, dans, lans, pans, prbty, tol;
// double *gamma, *theta, *a, *b;
// gamma = new double[n[0]];
// theta = new double[n[0]];
// a = new double[maxit[0]];
// b = new double[maxit[0]];
//
//
//
// if ((n[0]<1) || (c[0]<=0) || (maxit[0] <1) || (eps[0]<=0.0)) {
// res[0] = -2.0;
// ifault[0] = 2;
// delete[] gamma;
// delete[] theta;
// delete[] a;
// delete[] b;
// return;
// } else {
// tol = -200.0;
//
// // Preliminaries
// sum = lambda[0];
// bbeta = sum;
//
// for (i=1;i<=n[0];i++) {
// hold = lambda[i-1];
// if ((hold<=0.0) || (mult[i-1]<1) || (delta[i-1]<0.0)) {
// res[0] = -7.0;
// ifault[0] = -i;
// delete[] gamma;
// delete[] theta;
// delete[] a;
// delete[] b;
// return;
// }
// if (bbeta > hold) bbeta = hold; // calcul du max des lambdas
// if (sum < hold) sum = hold; // calcul du min des lambdas
// }
//
//
// if (mode[0] > 0.0) {
// // if ((2.0/(1.0/bbeta+1.0/sum))>1.8*sum) bbeta = sum; // comme dans NAG : methode avec betaA
// bbeta = mode[0]*bbeta;
// } else {
// bbeta = 2.0/(1.0/bbeta+1.0/sum); // methode avec betaB
// }
//
// k = 0;
// sum = 1.0;
// sum1 = 0.0;
// for (i=1;i<=n[0];i++) {
// hold = bbeta/lambda[i-1];
// gamma[i-1] = 1.0 - hold;
// sum = sum*R_pow(hold,mult[i-1]); //???? pas sur ..
// sum1 = sum1 + delta[i-1];
// k = k + mult[i-1];
// theta[i-1] = 1.0;
// }
//
// ao = exp(0.5*(log(sum)-sum1));
// if (ao <= 0.0) {
// res[0] = 0.0;
// dnsty[0] = 0.0;
// ifault[0] = 1;
// } else { // evaluate probability and density of chi-squared on k degrees of freedom. The constant 0.22579135264473 is ln(sqrt(pi/2))
// z = c[0]/bbeta;
//
// if ((k%2) == 0) { // k est un entier donc on regarde si k est divisible par 2: k == (k/2)*k
// i = 2;
// lans = -0.5*z;
// dans = exp(lans);
// pans = 1.0 - dans;
// } else {
// i = 1;
// lans = -0.5*(z+log(z)) - 0.22579135264473;
// dans = exp(lans);
// pans = pnorm(sqrt(z),0.0,1.0,1,0) - pnorm(-sqrt(z),0.0,1.0,1,0);
// }
//
// k = k-2;
// for (j=i;j<=k;j=j+2) {
// if (lans < tol) {
// lans = lans + log(z/(double)j);
// dans = exp(lans);
// } else {
// dans = dans*z/(double)j;
// }
// pans = pans -dans;
// }
//
// // evaluate successive terms of expansion
//
// prbty = pans;
// dnsty[0] = dans;
// eps2 = eps[0]/ao;
// aoinv = 1.0/ao;
// sum = aoinv - 1.0;
//
//
// for (m=1;m<=maxit[0];m++) {
// sum1 = 0.0;
// for (i=1;i<=n[0];i++) {
// hold = theta[i-1];
// hold2 = hold*gamma[i-1];
// theta[i-1] = hold2;
// sum1 = sum1 + hold2*mult[i-1]+m*delta[i-1]*(hold-hold2);
// }
// sum1 = 0.5*sum1;
// b[m-1] = sum1;
// for (i=m-1;i>=1;i--) {
// sum1 = sum1 + b[i-1]*a[m-i-1];
// }
// sum1 = sum1/(double)m;
// a[m-1] = sum1;
// k = k + 2;
// if (lans < tol) {
// lans = lans + log(z/(double)k);
// dans = exp(lans);
// } else {
// dans = dans*z/(double)k;
// }
// pans = pans - dans;
// sum = sum - sum1;
// dnsty[0] = dnsty[0] + dans*sum1;
// sum1 = pans*sum1;
// prbty = prbty + sum1;
// if (prbty<(-aoinv)) {
// res[0] = -3.0;
// ifault[0] = 3;
// return;
// }
// if (fabs(pans*sum) < eps2) {
// if (fabs(sum1) < eps2) {
// ifault[0] = 0;
//
// m = maxit[0]+1;
// break;
//
// }
// }
// }
//
// ifault[0] = 4;
// dnsty[0] = ao*dnsty[0]/(bbeta+bbeta);
// prbty = ao*prbty;
// if (prbty<0.0 || prbty>1.0) {ifault[0] = ifault[0] + 5;
// } else {
// if (dnsty[0]<0.0) ifault[0] = ifault[0] + 6;
// }
// res[0] = prbty;
// }
//
// delete[] gamma;
// delete[] theta;
// delete[] a;
// delete[] b;
// return;
// }
//
// }
//}
| Bonder-MJ/systemsgenetics | Downstreamer/src/main/java/ch/unil/genescore/vegas/Farebrother.java |
179,780 | package org.telegram.messenger;
import java.util.regex.Pattern;
public class LinkifyPort {
private static String IANA_TOP_LEVEL_DOMAINS =
"(?:"
+ "(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active"
+ "|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam"
+ "|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates"
+ "|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])"
+ "|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva"
+ "|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black"
+ "|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique"
+ "|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business"
+ "|buzz|bzh|b[abdefghijmnorstvwyz])"
+ "|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards"
+ "|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo"
+ "|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco"
+ "|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach"
+ "|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos"
+ "|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses"
+ "|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])"
+ "|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta"
+ "|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount"
+ "|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])"
+ "|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises"
+ "|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed"
+ "|express|e[cegrstu])"
+ "|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film"
+ "|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth"
+ "|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi"
+ "|f[ijkmor])"
+ "|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving"
+ "|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger"
+ "|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])"
+ "|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings"
+ "|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai"
+ "|h[kmnrtu])"
+ "|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute"
+ "|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])"
+ "|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])"
+ "|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])"
+ "|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc"
+ "|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live"
+ "|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])"
+ "|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba"
+ "|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda"
+ "|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar"
+ "|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])"
+ "|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk"
+ "|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])"
+ "|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka"
+ "|otsuka|ovh|om)"
+ "|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography"
+ "|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing"
+ "|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property"
+ "|protection|pub|p[aefghklmnrstwy])"
+ "|(?:qpon|quebec|qa)"
+ "|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals"
+ "|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks"
+ "|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])"
+ "|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo"
+ "|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security"
+ "|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski"
+ "|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting"
+ "|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies"
+ "|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])"
+ "|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica"
+ "|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools"
+ "|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])"
+ "|(?:ubs|university|uno|uol|u[agksyz])"
+ "|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin"
+ "|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])"
+ "|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill"
+ "|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])"
+ "|(?:\u03b5\u03bb|\u0431\u0435\u043b|\u0434\u0435\u0442\u0438|\u043a\u043e\u043c|\u043c\u043a\u0434"
+ "|\u043c\u043e\u043d|\u043c\u043e\u0441\u043a\u0432\u0430|\u043e\u043d\u043b\u0430\u0439\u043d"
+ "|\u043e\u0440\u0433|\u0440\u0443\u0441|\u0440\u0444|\u0441\u0430\u0439\u0442|\u0441\u0440\u0431"
+ "|\u0443\u043a\u0440|\u049b\u0430\u0437|\u0570\u0561\u0575|\u05e7\u05d5\u05dd|\u0627\u0631\u0627\u0645\u0643\u0648"
+ "|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629"
+ "|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0627\u06cc\u0631\u0627\u0646"
+ "|\u0628\u0627\u0632\u0627\u0631|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633"
+ "|\u0633\u0648\u062f\u0627\u0646|\u0633\u0648\u0631\u064a\u0629|\u0634\u0628\u0643\u0629"
+ "|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0641\u0644\u0633\u0637\u064a\u0646"
+ "|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0645\u0644\u064a\u0633\u064a\u0627"
+ "|\u0645\u0648\u0642\u0639|\u0915\u0949\u092e|\u0928\u0947\u091f|\u092d\u093e\u0930\u0924"
+ "|\u0938\u0902\u0917\u0920\u0928|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4"
+ "|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd"
+ "|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e04\u0e2d\u0e21|\u0e44\u0e17\u0e22"
+ "|\u10d2\u10d4|\u307f\u3093\u306a|\u30b0\u30fc\u30b0\u30eb|\u30b3\u30e0|\u4e16\u754c"
+ "|\u4e2d\u4fe1|\u4e2d\u56fd|\u4e2d\u570b|\u4e2d\u6587\u7f51|\u4f01\u4e1a|\u4f5b\u5c71"
+ "|\u4fe1\u606f|\u5065\u5eb7|\u516b\u5366|\u516c\u53f8|\u516c\u76ca|\u53f0\u6e7e|\u53f0\u7063"
+ "|\u5546\u57ce|\u5546\u5e97|\u5546\u6807|\u5728\u7ebf|\u5927\u62ff|\u5a31\u4e50|\u5de5\u884c"
+ "|\u5e7f\u4e1c|\u6148\u5584|\u6211\u7231\u4f60|\u624b\u673a|\u653f\u52a1|\u653f\u5e9c"
+ "|\u65b0\u52a0\u5761|\u65b0\u95fb|\u65f6\u5c1a|\u673a\u6784|\u6de1\u9a6c\u9521|\u6e38\u620f"
+ "|\u70b9\u770b|\u79fb\u52a8|\u7ec4\u7ec7\u673a\u6784|\u7f51\u5740|\u7f51\u5e97|\u7f51\u7edc"
+ "|\u8c37\u6b4c|\u96c6\u56e2|\u98de\u5229\u6d66|\u9910\u5385|\u9999\u6e2f|\ub2f7\ub137"
+ "|\ub2f7\ucef4|\uc0bc\uc131|\ud55c\uad6d|xbox"
+ "|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g"
+ "|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim"
+ "|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks"
+ "|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a"
+ "|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd"
+ "|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h"
+ "|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s"
+ "|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c"
+ "|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i"
+ "|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d"
+ "|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt"
+ "|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e"
+ "|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab"
+ "|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema"
+ "|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh"
+ "|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c"
+ "|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb"
+ "|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a"
+ "|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o"
+ "|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)"
+ "|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])"
+ "|(?:zara|zip|zone|zuerich|z[amw]))";
private static final String UCS_CHAR = "[" +
"\u00A0-\uD7FF" +
"\uF900-\uFDCF" +
"\uFDF0-\uFFEF" +
"\uD800\uDC00-\uD83F\uDFFD" +
"\uD840\uDC00-\uD87F\uDFFD" +
"\uD880\uDC00-\uD8BF\uDFFD" +
"\uD8C0\uDC00-\uD8FF\uDFFD" +
"\uD900\uDC00-\uD93F\uDFFD" +
"\uD940\uDC00-\uD97F\uDFFD" +
"\uD980\uDC00-\uD9BF\uDFFD" +
"\uD9C0\uDC00-\uD9FF\uDFFD" +
"\uDA00\uDC00-\uDA3F\uDFFD" +
"\uDA40\uDC00-\uDA7F\uDFFD" +
"\uDA80\uDC00-\uDABF\uDFFD" +
"\uDAC0\uDC00-\uDAFF\uDFFD" +
"\uDB00\uDC00-\uDB3F\uDFFD" +
"\uDB44\uDC00-\uDB7F\uDFFD" +
"&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]";
private static final String UCS_CHAR_FIXED = "[" +
"\u00A0-\uD7FF" +
"\uF900-\uFDCF" +
"\uFDF0-\uFFEF" +
// "\uD800\uDC00-\uD83F\uDFFD" +
"\uD840\uDC00-\uD87F\uDFFD" +
"\uD880\uDC00-\uD8BF\uDFFD" +
"\uD8C0\uDC00-\uD8FF\uDFFD" +
"\uD900\uDC00-\uD93F\uDFFD" +
"\uD940\uDC00-\uD97F\uDFFD" +
"\uD980\uDC00-\uD9BF\uDFFD" +
"\uD9C0\uDC00-\uD9FF\uDFFD" +
"\uDA00\uDC00-\uDA3F\uDFFD" +
"\uDA40\uDC00-\uDA7F\uDFFD" +
"\uDA80\uDC00-\uDABF\uDFFD" +
"\uDAC0\uDC00-\uDAFF\uDFFD" +
"\uDB00\uDC00-\uDB3F\uDFFD" +
"\uDB44\uDC00-\uDB7F\uDFFD" +
"&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]";
private static final String IP_ADDRESS_STRING =
"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
+ "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
+ "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
+ "|[1-9][0-9]|[0-9]))";
private static final String TLD_CHAR = "a-zA-Z" + UCS_CHAR;
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String LABEL_CHAR = "a-zA-Z0-9" + UCS_CHAR_FIXED;
private static final String IRI_LABEL = "[" + LABEL_CHAR + "](?:[" + LABEL_CHAR + "_\\-]{0,61}[" + LABEL_CHAR + "]){0,1}";
private static String STRICT_TLD = "(?:" + IANA_TOP_LEVEL_DOMAINS + "|" + PUNYCODE_TLD + ")";
private static final String STRICT_HOST_NAME = "(?:(?:" + IRI_LABEL + "\\.)+" + STRICT_TLD + ")";
private static final String STRICT_DOMAIN_NAME = "(?:" + STRICT_HOST_NAME + "|" + IP_ADDRESS_STRING + ")";
private static final String TLD = "(" + PUNYCODE_TLD + "|" + "[" + TLD_CHAR + "]{2,63}" + ")";
private static final String HOST_NAME = "(" + IRI_LABEL + "\\.)+" + TLD;
private static final String DOMAIN_NAME_STR = "(" + HOST_NAME + "|" + IP_ADDRESS_STRING + ")";
private static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
private static final String PROTOCOL = "(?i:http|https|ton|tg)://";
private static final String PROXY_PROTOCOL = "(?i:vmess|vmess1|ss|ssr|trojan|ws|wss)://";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
+ "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
+ "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[" + LABEL_CHAR + ";/\\?:@&=#~" + "\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
private static final String BASE64 = "(?:[A-Za-z0-9+\\/]{4}\\\\n?)*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)";
private static final String PATH_AND_QUERY_BASE64 = "[/\\?]?(?:(?:[" + LABEL_CHAR + ";/\\?:@&=#~" + "\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2})|" + BASE64 + ")*";
private static final String RELAXED_DOMAIN_NAME = "(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" + ")*" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" + "?)" + "|" + IP_ADDRESS_STRING + ")";
private static final String WEB_URL_WITHOUT_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?<!:\\/\\/)"
+ "("
+ "(?:" + STRICT_DOMAIN_NAME + ")"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
private static final String WEB_URL_WITH_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?:"
+ "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")"
+ "(?:" + RELAXED_DOMAIN_NAME + ")?"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
private static final String PROXY_URL = "("
+ WORD_BOUNDARY
+ "(?:"
+ "(?:" + PROXY_PROTOCOL + "(?:" + USER_INFO + ")?" + ")"
+ "(?:" + RELAXED_DOMAIN_NAME + ")?"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY_BASE64 + ")?"
+ WORD_BOUNDARY
+ ")";
public static Pattern WEB_URL = null;
public static Pattern PROXY_PATTERN = Pattern.compile(PROXY_URL);
static {
try {
WEB_URL = Pattern.compile("(" + WEB_URL_WITH_PROTOCOL + "|" + WEB_URL_WITHOUT_PROTOCOL + ")");
} catch (Exception e) {
FileLog.e(e);
}
}
}
| NextAlone/Nagram | TMessagesProj/src/main/java/org/telegram/messenger/LinkifyPort.java |
179,781 | final class Config {
// Change this when setting up a new installation!
// it's used for Canopy and must be unique for each installation
static final String installationId = "ggp";
static final boolean autoplayBMSet = true;
static final boolean enableAPC40 = true;
static final boolean enableSoundSyphon = false;
static final boolean enableOutputMinitree = false;
static final boolean enableOutputBigtree = true;
// these configure the mandated "pause" to keep crowds down
// set either to 0 to disable
static final double pauseRunMinutes = 0.0;
static final double pausePauseMinutes = 0.0;
static final double pauseFadeInSeconds = 0.0;
static final double pauseFadeOutSeconds = 0.0;
// Initial Value of the Autoplay Brightness setting, to allow
// the sculpture to start with a different value
static final double autoplayBrightness = 1.0;
// the interaction server. Set to null to disable.
static final String canopyServer = "";
//static final String canopyServer = "http://localhost:3000/lx";
//static final String canopyServer = "https://entwined-api.charliestigler.com/lx";
static final String NDB_CONFIG_FILE = "data/entwinedNDBs.json";
static final String CUBE_CONFIG_FILE = "data/entwinedCubes.json";
static final String TREE_CONFIG_FILE = "data/entwinedTrees.json";
static final String SHRUB_CUBE_CONFIG_FILE = "data/entwinedShrubCubes.json";
static final String SHRUB_CONFIG_FILE = "data/entwinedShrubs.json";
static final String FAIRY_CIRCLE_CONFIG_FILE = "data/entwinedFairyCircles.json";
// if this file doesn't exist you get a crash
static final String AUTOPLAY_FILE = "data/entwinedSetDec2021.json";
}
| squaredproject/Entwined | oldlx/installations/Vegas2022/Config.java |
179,782 | /*
* Copyright 2019-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.managedblockchainquery.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* There are two possible types of transactions used for this data type:
* </p>
* <ul>
* <li>
* <p>
* A Bitcoin transaction is a movement of BTC from one address to another.
* </p>
* </li>
* <li>
* <p>
* An Ethereum transaction refers to an action initiated by an externally owned account, which is an account managed by
* a human, not a contract. For example, if Bob sends Alice 1 ETH, Bob's account must be debited and Alice's must be
* credited. This state-changing action occurs within a transaction.
* </p>
* </li>
* </ul>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/managedblockchain-query-2023-05-04/Transaction"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Transaction implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The blockchain network where the transaction occurred.
* </p>
*/
private String network;
/**
* <p>
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using the
* information in the block. The block hash is used to verify the integrity of the data in the block.
* </p>
*/
private String blockHash;
/**
* <p>
* The hash of a transaction. It is generated when a transaction is created.
* </p>
*/
private String transactionHash;
/**
* <p>
* The block number in which the transaction is recorded.
* </p>
*/
private String blockNumber;
/**
* <p>
* The <code>Timestamp</code> of the transaction.
* </p>
*/
private java.util.Date transactionTimestamp;
/**
* <p>
* The index of the transaction within a blockchain.
* </p>
*/
private Long transactionIndex;
/**
* <p>
* The number of transactions in the block.
* </p>
*/
private Long numberOfTransactions;
/**
* <p>
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
* </p>
*/
private String to;
/**
* <p>
* The initiator of the transaction. It is either in the form a public key or a contract address.
* </p>
*/
private String from;
/**
* <p>
* The blockchain address for the contract.
* </p>
*/
private String contractAddress;
/**
* <p>
* The amount of gas used for the transaction.
* </p>
*/
private String gasUsed;
/**
* <p>
* The amount of gas used up to the specified point in the block.
* </p>
*/
private String cumulativeGasUsed;
/**
* <p>
* The effective gas price.
* </p>
*/
private String effectiveGasPrice;
/**
* <p>
* The signature of the transaction. The Z coordinate of a point V.
* </p>
*/
private Integer signatureV;
/**
* <p>
* The signature of the transaction. The X coordinate of a point R.
* </p>
*/
private String signatureR;
/**
* <p>
* The signature of the transaction. The Y coordinate of a point S.
* </p>
*/
private String signatureS;
/**
* <p>
* The transaction fee.
* </p>
*/
private String transactionFee;
/**
* <p>
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
* </p>
*/
private String transactionId;
/**
* <p>
* Specifies whether the transaction has reached Finality.
* </p>
*/
private String confirmationStatus;
/**
* <p>
* Identifies whether the transaction has succeeded or failed.
* </p>
*/
private String executionStatus;
/**
* <p>
* The blockchain network where the transaction occurred.
* </p>
*
* @param network
* The blockchain network where the transaction occurred.
* @see QueryNetwork
*/
public void setNetwork(String network) {
this.network = network;
}
/**
* <p>
* The blockchain network where the transaction occurred.
* </p>
*
* @return The blockchain network where the transaction occurred.
* @see QueryNetwork
*/
public String getNetwork() {
return this.network;
}
/**
* <p>
* The blockchain network where the transaction occurred.
* </p>
*
* @param network
* The blockchain network where the transaction occurred.
* @return Returns a reference to this object so that method calls can be chained together.
* @see QueryNetwork
*/
public Transaction withNetwork(String network) {
setNetwork(network);
return this;
}
/**
* <p>
* The blockchain network where the transaction occurred.
* </p>
*
* @param network
* The blockchain network where the transaction occurred.
* @return Returns a reference to this object so that method calls can be chained together.
* @see QueryNetwork
*/
public Transaction withNetwork(QueryNetwork network) {
this.network = network.toString();
return this;
}
/**
* <p>
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using the
* information in the block. The block hash is used to verify the integrity of the data in the block.
* </p>
*
* @param blockHash
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using
* the information in the block. The block hash is used to verify the integrity of the data in the block.
*/
public void setBlockHash(String blockHash) {
this.blockHash = blockHash;
}
/**
* <p>
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using the
* information in the block. The block hash is used to verify the integrity of the data in the block.
* </p>
*
* @return The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using
* the information in the block. The block hash is used to verify the integrity of the data in the block.
*/
public String getBlockHash() {
return this.blockHash;
}
/**
* <p>
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using the
* information in the block. The block hash is used to verify the integrity of the data in the block.
* </p>
*
* @param blockHash
* The block hash is a unique identifier for a block. It is a fixed-size string that is calculated by using
* the information in the block. The block hash is used to verify the integrity of the data in the block.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withBlockHash(String blockHash) {
setBlockHash(blockHash);
return this;
}
/**
* <p>
* The hash of a transaction. It is generated when a transaction is created.
* </p>
*
* @param transactionHash
* The hash of a transaction. It is generated when a transaction is created.
*/
public void setTransactionHash(String transactionHash) {
this.transactionHash = transactionHash;
}
/**
* <p>
* The hash of a transaction. It is generated when a transaction is created.
* </p>
*
* @return The hash of a transaction. It is generated when a transaction is created.
*/
public String getTransactionHash() {
return this.transactionHash;
}
/**
* <p>
* The hash of a transaction. It is generated when a transaction is created.
* </p>
*
* @param transactionHash
* The hash of a transaction. It is generated when a transaction is created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTransactionHash(String transactionHash) {
setTransactionHash(transactionHash);
return this;
}
/**
* <p>
* The block number in which the transaction is recorded.
* </p>
*
* @param blockNumber
* The block number in which the transaction is recorded.
*/
public void setBlockNumber(String blockNumber) {
this.blockNumber = blockNumber;
}
/**
* <p>
* The block number in which the transaction is recorded.
* </p>
*
* @return The block number in which the transaction is recorded.
*/
public String getBlockNumber() {
return this.blockNumber;
}
/**
* <p>
* The block number in which the transaction is recorded.
* </p>
*
* @param blockNumber
* The block number in which the transaction is recorded.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withBlockNumber(String blockNumber) {
setBlockNumber(blockNumber);
return this;
}
/**
* <p>
* The <code>Timestamp</code> of the transaction.
* </p>
*
* @param transactionTimestamp
* The <code>Timestamp</code> of the transaction.
*/
public void setTransactionTimestamp(java.util.Date transactionTimestamp) {
this.transactionTimestamp = transactionTimestamp;
}
/**
* <p>
* The <code>Timestamp</code> of the transaction.
* </p>
*
* @return The <code>Timestamp</code> of the transaction.
*/
public java.util.Date getTransactionTimestamp() {
return this.transactionTimestamp;
}
/**
* <p>
* The <code>Timestamp</code> of the transaction.
* </p>
*
* @param transactionTimestamp
* The <code>Timestamp</code> of the transaction.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTransactionTimestamp(java.util.Date transactionTimestamp) {
setTransactionTimestamp(transactionTimestamp);
return this;
}
/**
* <p>
* The index of the transaction within a blockchain.
* </p>
*
* @param transactionIndex
* The index of the transaction within a blockchain.
*/
public void setTransactionIndex(Long transactionIndex) {
this.transactionIndex = transactionIndex;
}
/**
* <p>
* The index of the transaction within a blockchain.
* </p>
*
* @return The index of the transaction within a blockchain.
*/
public Long getTransactionIndex() {
return this.transactionIndex;
}
/**
* <p>
* The index of the transaction within a blockchain.
* </p>
*
* @param transactionIndex
* The index of the transaction within a blockchain.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTransactionIndex(Long transactionIndex) {
setTransactionIndex(transactionIndex);
return this;
}
/**
* <p>
* The number of transactions in the block.
* </p>
*
* @param numberOfTransactions
* The number of transactions in the block.
*/
public void setNumberOfTransactions(Long numberOfTransactions) {
this.numberOfTransactions = numberOfTransactions;
}
/**
* <p>
* The number of transactions in the block.
* </p>
*
* @return The number of transactions in the block.
*/
public Long getNumberOfTransactions() {
return this.numberOfTransactions;
}
/**
* <p>
* The number of transactions in the block.
* </p>
*
* @param numberOfTransactions
* The number of transactions in the block.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withNumberOfTransactions(Long numberOfTransactions) {
setNumberOfTransactions(numberOfTransactions);
return this;
}
/**
* <p>
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
* </p>
*
* @param to
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
*/
public void setTo(String to) {
this.to = to;
}
/**
* <p>
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
* </p>
*
* @return The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
*/
public String getTo() {
return this.to;
}
/**
* <p>
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
* </p>
*
* @param to
* The identifier of the transaction. It is generated whenever a transaction is verified and added to the
* blockchain.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTo(String to) {
setTo(to);
return this;
}
/**
* <p>
* The initiator of the transaction. It is either in the form a public key or a contract address.
* </p>
*
* @param from
* The initiator of the transaction. It is either in the form a public key or a contract address.
*/
public void setFrom(String from) {
this.from = from;
}
/**
* <p>
* The initiator of the transaction. It is either in the form a public key or a contract address.
* </p>
*
* @return The initiator of the transaction. It is either in the form a public key or a contract address.
*/
public String getFrom() {
return this.from;
}
/**
* <p>
* The initiator of the transaction. It is either in the form a public key or a contract address.
* </p>
*
* @param from
* The initiator of the transaction. It is either in the form a public key or a contract address.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withFrom(String from) {
setFrom(from);
return this;
}
/**
* <p>
* The blockchain address for the contract.
* </p>
*
* @param contractAddress
* The blockchain address for the contract.
*/
public void setContractAddress(String contractAddress) {
this.contractAddress = contractAddress;
}
/**
* <p>
* The blockchain address for the contract.
* </p>
*
* @return The blockchain address for the contract.
*/
public String getContractAddress() {
return this.contractAddress;
}
/**
* <p>
* The blockchain address for the contract.
* </p>
*
* @param contractAddress
* The blockchain address for the contract.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withContractAddress(String contractAddress) {
setContractAddress(contractAddress);
return this;
}
/**
* <p>
* The amount of gas used for the transaction.
* </p>
*
* @param gasUsed
* The amount of gas used for the transaction.
*/
public void setGasUsed(String gasUsed) {
this.gasUsed = gasUsed;
}
/**
* <p>
* The amount of gas used for the transaction.
* </p>
*
* @return The amount of gas used for the transaction.
*/
public String getGasUsed() {
return this.gasUsed;
}
/**
* <p>
* The amount of gas used for the transaction.
* </p>
*
* @param gasUsed
* The amount of gas used for the transaction.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withGasUsed(String gasUsed) {
setGasUsed(gasUsed);
return this;
}
/**
* <p>
* The amount of gas used up to the specified point in the block.
* </p>
*
* @param cumulativeGasUsed
* The amount of gas used up to the specified point in the block.
*/
public void setCumulativeGasUsed(String cumulativeGasUsed) {
this.cumulativeGasUsed = cumulativeGasUsed;
}
/**
* <p>
* The amount of gas used up to the specified point in the block.
* </p>
*
* @return The amount of gas used up to the specified point in the block.
*/
public String getCumulativeGasUsed() {
return this.cumulativeGasUsed;
}
/**
* <p>
* The amount of gas used up to the specified point in the block.
* </p>
*
* @param cumulativeGasUsed
* The amount of gas used up to the specified point in the block.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withCumulativeGasUsed(String cumulativeGasUsed) {
setCumulativeGasUsed(cumulativeGasUsed);
return this;
}
/**
* <p>
* The effective gas price.
* </p>
*
* @param effectiveGasPrice
* The effective gas price.
*/
public void setEffectiveGasPrice(String effectiveGasPrice) {
this.effectiveGasPrice = effectiveGasPrice;
}
/**
* <p>
* The effective gas price.
* </p>
*
* @return The effective gas price.
*/
public String getEffectiveGasPrice() {
return this.effectiveGasPrice;
}
/**
* <p>
* The effective gas price.
* </p>
*
* @param effectiveGasPrice
* The effective gas price.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withEffectiveGasPrice(String effectiveGasPrice) {
setEffectiveGasPrice(effectiveGasPrice);
return this;
}
/**
* <p>
* The signature of the transaction. The Z coordinate of a point V.
* </p>
*
* @param signatureV
* The signature of the transaction. The Z coordinate of a point V.
*/
public void setSignatureV(Integer signatureV) {
this.signatureV = signatureV;
}
/**
* <p>
* The signature of the transaction. The Z coordinate of a point V.
* </p>
*
* @return The signature of the transaction. The Z coordinate of a point V.
*/
public Integer getSignatureV() {
return this.signatureV;
}
/**
* <p>
* The signature of the transaction. The Z coordinate of a point V.
* </p>
*
* @param signatureV
* The signature of the transaction. The Z coordinate of a point V.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withSignatureV(Integer signatureV) {
setSignatureV(signatureV);
return this;
}
/**
* <p>
* The signature of the transaction. The X coordinate of a point R.
* </p>
*
* @param signatureR
* The signature of the transaction. The X coordinate of a point R.
*/
public void setSignatureR(String signatureR) {
this.signatureR = signatureR;
}
/**
* <p>
* The signature of the transaction. The X coordinate of a point R.
* </p>
*
* @return The signature of the transaction. The X coordinate of a point R.
*/
public String getSignatureR() {
return this.signatureR;
}
/**
* <p>
* The signature of the transaction. The X coordinate of a point R.
* </p>
*
* @param signatureR
* The signature of the transaction. The X coordinate of a point R.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withSignatureR(String signatureR) {
setSignatureR(signatureR);
return this;
}
/**
* <p>
* The signature of the transaction. The Y coordinate of a point S.
* </p>
*
* @param signatureS
* The signature of the transaction. The Y coordinate of a point S.
*/
public void setSignatureS(String signatureS) {
this.signatureS = signatureS;
}
/**
* <p>
* The signature of the transaction. The Y coordinate of a point S.
* </p>
*
* @return The signature of the transaction. The Y coordinate of a point S.
*/
public String getSignatureS() {
return this.signatureS;
}
/**
* <p>
* The signature of the transaction. The Y coordinate of a point S.
* </p>
*
* @param signatureS
* The signature of the transaction. The Y coordinate of a point S.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withSignatureS(String signatureS) {
setSignatureS(signatureS);
return this;
}
/**
* <p>
* The transaction fee.
* </p>
*
* @param transactionFee
* The transaction fee.
*/
public void setTransactionFee(String transactionFee) {
this.transactionFee = transactionFee;
}
/**
* <p>
* The transaction fee.
* </p>
*
* @return The transaction fee.
*/
public String getTransactionFee() {
return this.transactionFee;
}
/**
* <p>
* The transaction fee.
* </p>
*
* @param transactionFee
* The transaction fee.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTransactionFee(String transactionFee) {
setTransactionFee(transactionFee);
return this;
}
/**
* <p>
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
* </p>
*
* @param transactionId
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
*/
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
/**
* <p>
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
* </p>
*
* @return The identifier of a Bitcoin transaction. It is generated when a transaction is created.
*/
public String getTransactionId() {
return this.transactionId;
}
/**
* <p>
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
* </p>
*
* @param transactionId
* The identifier of a Bitcoin transaction. It is generated when a transaction is created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Transaction withTransactionId(String transactionId) {
setTransactionId(transactionId);
return this;
}
/**
* <p>
* Specifies whether the transaction has reached Finality.
* </p>
*
* @param confirmationStatus
* Specifies whether the transaction has reached Finality.
* @see ConfirmationStatus
*/
public void setConfirmationStatus(String confirmationStatus) {
this.confirmationStatus = confirmationStatus;
}
/**
* <p>
* Specifies whether the transaction has reached Finality.
* </p>
*
* @return Specifies whether the transaction has reached Finality.
* @see ConfirmationStatus
*/
public String getConfirmationStatus() {
return this.confirmationStatus;
}
/**
* <p>
* Specifies whether the transaction has reached Finality.
* </p>
*
* @param confirmationStatus
* Specifies whether the transaction has reached Finality.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConfirmationStatus
*/
public Transaction withConfirmationStatus(String confirmationStatus) {
setConfirmationStatus(confirmationStatus);
return this;
}
/**
* <p>
* Specifies whether the transaction has reached Finality.
* </p>
*
* @param confirmationStatus
* Specifies whether the transaction has reached Finality.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConfirmationStatus
*/
public Transaction withConfirmationStatus(ConfirmationStatus confirmationStatus) {
this.confirmationStatus = confirmationStatus.toString();
return this;
}
/**
* <p>
* Identifies whether the transaction has succeeded or failed.
* </p>
*
* @param executionStatus
* Identifies whether the transaction has succeeded or failed.
* @see ExecutionStatus
*/
public void setExecutionStatus(String executionStatus) {
this.executionStatus = executionStatus;
}
/**
* <p>
* Identifies whether the transaction has succeeded or failed.
* </p>
*
* @return Identifies whether the transaction has succeeded or failed.
* @see ExecutionStatus
*/
public String getExecutionStatus() {
return this.executionStatus;
}
/**
* <p>
* Identifies whether the transaction has succeeded or failed.
* </p>
*
* @param executionStatus
* Identifies whether the transaction has succeeded or failed.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionStatus
*/
public Transaction withExecutionStatus(String executionStatus) {
setExecutionStatus(executionStatus);
return this;
}
/**
* <p>
* Identifies whether the transaction has succeeded or failed.
* </p>
*
* @param executionStatus
* Identifies whether the transaction has succeeded or failed.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionStatus
*/
public Transaction withExecutionStatus(ExecutionStatus executionStatus) {
this.executionStatus = executionStatus.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getNetwork() != null)
sb.append("Network: ").append(getNetwork()).append(",");
if (getBlockHash() != null)
sb.append("BlockHash: ").append(getBlockHash()).append(",");
if (getTransactionHash() != null)
sb.append("TransactionHash: ").append(getTransactionHash()).append(",");
if (getBlockNumber() != null)
sb.append("BlockNumber: ").append(getBlockNumber()).append(",");
if (getTransactionTimestamp() != null)
sb.append("TransactionTimestamp: ").append(getTransactionTimestamp()).append(",");
if (getTransactionIndex() != null)
sb.append("TransactionIndex: ").append(getTransactionIndex()).append(",");
if (getNumberOfTransactions() != null)
sb.append("NumberOfTransactions: ").append(getNumberOfTransactions()).append(",");
if (getTo() != null)
sb.append("To: ").append(getTo()).append(",");
if (getFrom() != null)
sb.append("From: ").append(getFrom()).append(",");
if (getContractAddress() != null)
sb.append("ContractAddress: ").append(getContractAddress()).append(",");
if (getGasUsed() != null)
sb.append("GasUsed: ").append(getGasUsed()).append(",");
if (getCumulativeGasUsed() != null)
sb.append("CumulativeGasUsed: ").append(getCumulativeGasUsed()).append(",");
if (getEffectiveGasPrice() != null)
sb.append("EffectiveGasPrice: ").append(getEffectiveGasPrice()).append(",");
if (getSignatureV() != null)
sb.append("SignatureV: ").append(getSignatureV()).append(",");
if (getSignatureR() != null)
sb.append("SignatureR: ").append(getSignatureR()).append(",");
if (getSignatureS() != null)
sb.append("SignatureS: ").append(getSignatureS()).append(",");
if (getTransactionFee() != null)
sb.append("TransactionFee: ").append(getTransactionFee()).append(",");
if (getTransactionId() != null)
sb.append("TransactionId: ").append(getTransactionId()).append(",");
if (getConfirmationStatus() != null)
sb.append("ConfirmationStatus: ").append(getConfirmationStatus()).append(",");
if (getExecutionStatus() != null)
sb.append("ExecutionStatus: ").append(getExecutionStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Transaction == false)
return false;
Transaction other = (Transaction) obj;
if (other.getNetwork() == null ^ this.getNetwork() == null)
return false;
if (other.getNetwork() != null && other.getNetwork().equals(this.getNetwork()) == false)
return false;
if (other.getBlockHash() == null ^ this.getBlockHash() == null)
return false;
if (other.getBlockHash() != null && other.getBlockHash().equals(this.getBlockHash()) == false)
return false;
if (other.getTransactionHash() == null ^ this.getTransactionHash() == null)
return false;
if (other.getTransactionHash() != null && other.getTransactionHash().equals(this.getTransactionHash()) == false)
return false;
if (other.getBlockNumber() == null ^ this.getBlockNumber() == null)
return false;
if (other.getBlockNumber() != null && other.getBlockNumber().equals(this.getBlockNumber()) == false)
return false;
if (other.getTransactionTimestamp() == null ^ this.getTransactionTimestamp() == null)
return false;
if (other.getTransactionTimestamp() != null && other.getTransactionTimestamp().equals(this.getTransactionTimestamp()) == false)
return false;
if (other.getTransactionIndex() == null ^ this.getTransactionIndex() == null)
return false;
if (other.getTransactionIndex() != null && other.getTransactionIndex().equals(this.getTransactionIndex()) == false)
return false;
if (other.getNumberOfTransactions() == null ^ this.getNumberOfTransactions() == null)
return false;
if (other.getNumberOfTransactions() != null && other.getNumberOfTransactions().equals(this.getNumberOfTransactions()) == false)
return false;
if (other.getTo() == null ^ this.getTo() == null)
return false;
if (other.getTo() != null && other.getTo().equals(this.getTo()) == false)
return false;
if (other.getFrom() == null ^ this.getFrom() == null)
return false;
if (other.getFrom() != null && other.getFrom().equals(this.getFrom()) == false)
return false;
if (other.getContractAddress() == null ^ this.getContractAddress() == null)
return false;
if (other.getContractAddress() != null && other.getContractAddress().equals(this.getContractAddress()) == false)
return false;
if (other.getGasUsed() == null ^ this.getGasUsed() == null)
return false;
if (other.getGasUsed() != null && other.getGasUsed().equals(this.getGasUsed()) == false)
return false;
if (other.getCumulativeGasUsed() == null ^ this.getCumulativeGasUsed() == null)
return false;
if (other.getCumulativeGasUsed() != null && other.getCumulativeGasUsed().equals(this.getCumulativeGasUsed()) == false)
return false;
if (other.getEffectiveGasPrice() == null ^ this.getEffectiveGasPrice() == null)
return false;
if (other.getEffectiveGasPrice() != null && other.getEffectiveGasPrice().equals(this.getEffectiveGasPrice()) == false)
return false;
if (other.getSignatureV() == null ^ this.getSignatureV() == null)
return false;
if (other.getSignatureV() != null && other.getSignatureV().equals(this.getSignatureV()) == false)
return false;
if (other.getSignatureR() == null ^ this.getSignatureR() == null)
return false;
if (other.getSignatureR() != null && other.getSignatureR().equals(this.getSignatureR()) == false)
return false;
if (other.getSignatureS() == null ^ this.getSignatureS() == null)
return false;
if (other.getSignatureS() != null && other.getSignatureS().equals(this.getSignatureS()) == false)
return false;
if (other.getTransactionFee() == null ^ this.getTransactionFee() == null)
return false;
if (other.getTransactionFee() != null && other.getTransactionFee().equals(this.getTransactionFee()) == false)
return false;
if (other.getTransactionId() == null ^ this.getTransactionId() == null)
return false;
if (other.getTransactionId() != null && other.getTransactionId().equals(this.getTransactionId()) == false)
return false;
if (other.getConfirmationStatus() == null ^ this.getConfirmationStatus() == null)
return false;
if (other.getConfirmationStatus() != null && other.getConfirmationStatus().equals(this.getConfirmationStatus()) == false)
return false;
if (other.getExecutionStatus() == null ^ this.getExecutionStatus() == null)
return false;
if (other.getExecutionStatus() != null && other.getExecutionStatus().equals(this.getExecutionStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getNetwork() == null) ? 0 : getNetwork().hashCode());
hashCode = prime * hashCode + ((getBlockHash() == null) ? 0 : getBlockHash().hashCode());
hashCode = prime * hashCode + ((getTransactionHash() == null) ? 0 : getTransactionHash().hashCode());
hashCode = prime * hashCode + ((getBlockNumber() == null) ? 0 : getBlockNumber().hashCode());
hashCode = prime * hashCode + ((getTransactionTimestamp() == null) ? 0 : getTransactionTimestamp().hashCode());
hashCode = prime * hashCode + ((getTransactionIndex() == null) ? 0 : getTransactionIndex().hashCode());
hashCode = prime * hashCode + ((getNumberOfTransactions() == null) ? 0 : getNumberOfTransactions().hashCode());
hashCode = prime * hashCode + ((getTo() == null) ? 0 : getTo().hashCode());
hashCode = prime * hashCode + ((getFrom() == null) ? 0 : getFrom().hashCode());
hashCode = prime * hashCode + ((getContractAddress() == null) ? 0 : getContractAddress().hashCode());
hashCode = prime * hashCode + ((getGasUsed() == null) ? 0 : getGasUsed().hashCode());
hashCode = prime * hashCode + ((getCumulativeGasUsed() == null) ? 0 : getCumulativeGasUsed().hashCode());
hashCode = prime * hashCode + ((getEffectiveGasPrice() == null) ? 0 : getEffectiveGasPrice().hashCode());
hashCode = prime * hashCode + ((getSignatureV() == null) ? 0 : getSignatureV().hashCode());
hashCode = prime * hashCode + ((getSignatureR() == null) ? 0 : getSignatureR().hashCode());
hashCode = prime * hashCode + ((getSignatureS() == null) ? 0 : getSignatureS().hashCode());
hashCode = prime * hashCode + ((getTransactionFee() == null) ? 0 : getTransactionFee().hashCode());
hashCode = prime * hashCode + ((getTransactionId() == null) ? 0 : getTransactionId().hashCode());
hashCode = prime * hashCode + ((getConfirmationStatus() == null) ? 0 : getConfirmationStatus().hashCode());
hashCode = prime * hashCode + ((getExecutionStatus() == null) ? 0 : getExecutionStatus().hashCode());
return hashCode;
}
@Override
public Transaction clone() {
try {
return (Transaction) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.managedblockchainquery.model.transform.TransactionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-managedblockchainquery/src/main/java/com/amazonaws/services/managedblockchainquery/model/Transaction.java |
179,783 | /**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.connectors.flink.sink;
import io.pravega.client.ClientConfig;
import io.pravega.client.stream.Stream;
import io.pravega.connectors.flink.PravegaEventRouter;
import org.apache.flink.annotation.Experimental;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.connector.sink2.Sink;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nullable;
/**
* Pravega Sink writes data into a Pravega stream. It supports all delivery guarantee
* described by {@link DeliveryGuarantee}.
*
* <p>For {@link DeliveryGuarantee#AT_LEAST_ONCE} and {@link DeliveryGuarantee#AT_LEAST_ONCE},
* a {@link PravegaEventSink} will be returned after {@link PravegaSinkBuilder#build()}.
*
* <p>For {@link DeliveryGuarantee#EXACTLY_ONCE}, a {@link PravegaTransactionalSink}
* will be returned after {@link PravegaSinkBuilder#build()}.
*
* @param <T> The type of the event to be written.
*/
@Experimental
public abstract class PravegaSink<T> implements Sink<T> {
// The Pravega client config.
final ClientConfig clientConfig;
// The destination stream.
final Stream stream;
// The supplied event serializer.
final SerializationSchema<T> serializationSchema;
// The router used to partition events within a stream, can be null for random routing
@Nullable
final PravegaEventRouter<T> eventRouter;
/**
* Set common parameters for {@link PravegaEventSink} and {@link PravegaTransactionalSink}.
*
* @param clientConfig The Pravega client configuration.
* @param stream The destination stream.
* @param serializationSchema The implementation for serializing every event into pravega's storage format.
* @param eventRouter The implementation to extract the partition key from the event.
*/
PravegaSink(ClientConfig clientConfig, Stream stream, SerializationSchema<T> serializationSchema,
PravegaEventRouter<T> eventRouter) {
this.clientConfig = Preconditions.checkNotNull(clientConfig, "clientConfig");
this.stream = Preconditions.checkNotNull(stream, "stream");
this.serializationSchema = Preconditions.checkNotNull(serializationSchema, "serializationSchema");
this.eventRouter = eventRouter;
}
// --------------- configurations -------------------------------
/**
* Gets a builder for {@link PravegaSink} to read Pravega streams using the Flink streaming API.
* @param <T> the element type.
* @return A new builder of {@link PravegaSink}
*/
public static <T> PravegaSinkBuilder<T> builder() {
return new PravegaSinkBuilder<>();
}
}
| pravega/flink-connectors | src/main/java/io/pravega/connectors/flink/sink/PravegaSink.java |
179,784 | package magic.model.player;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import magic.ai.MagicAIImpl;
import magic.utility.MagicFileSystem;
import magic.utility.MagicFileSystem.DataPath;
public final class PlayerProfiles {
private PlayerProfiles() {}
// default AI avatars.
private static final Path AVATARS_PATH = MagicFileSystem.getDataPath(DataPath.AVATARS);
private static final Path AVATAR_LesVegas = AVATARS_PATH.resolve("tux").resolve("tux25.png");
private static final Path AVATAR_MontyCarlo = AVATARS_PATH.resolve("default").resolve("face09.png");
private static final Path AVATAR_MiniMax = AVATARS_PATH.resolve("default").resolve("face18.png");
private static final Path profilesPath = MagicFileSystem.getDataPath(DataPath.PLAYERS);
private static final HashMap<String, PlayerProfile> profilesMap = new HashMap<>();
static {
refreshMap();
}
public static void refreshMap() {
profilesMap.clear();
// Humans
for (Path path : getProfilePaths("human")) {
final String profileId = path.getFileName().toString();
final HumanProfile player = new HumanProfile(profileId);
profilesMap.put(profileId, player);
}
// AIs
for (Path path : getProfilePaths("ai")) {
final String profileId = path.getFileName().toString();
final AiProfile player = new AiProfile(profileId);
profilesMap.put(profileId, player);
}
}
private static List<Path> getProfilePaths(final String playerType) {
final Path playersPath = profilesPath.resolve(playerType);
List<Path> profilePaths = getDirectoryPaths(playersPath);
if (profilePaths.isEmpty()) {
if ("human".equals(playerType)) {
createDefaultHumanPlayerProfiles();
} else {
createDefaultAiPlayerProfiles();
}
profilePaths = getDirectoryPaths(playersPath);
}
return profilePaths;
}
private static List<Path> getDirectoryPaths(final Path rootPath) {
final List<Path> paths = new ArrayList<>();
if (Files.exists(rootPath)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(rootPath, new DirectoriesFilter())) {
for (Path p : ds) {
paths.add(p.getFileName());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return paths;
}
private static class DirectoriesFilter implements Filter<Path> {
@Override
public boolean accept(Path entry) {
return Files.isDirectory(entry);
}
}
public static void createDefaultHumanPlayerProfiles() {
final HumanProfile profile = HumanProfile.create(getDefaultPlayerProfileName());
profile.save();
}
private static String getDefaultPlayerProfileName() {
final String systemUserName = System.getProperty("user.name");
return systemUserName == null ? "Player" : systemUserName;
}
public static void createDefaultAiPlayerProfiles() {
createAiPlayerProfile("Les Vegas", MagicAIImpl.VEGAS, 6, PlayerProfiles.AVATAR_LesVegas);
createAiPlayerProfile("Mini Max", MagicAIImpl.MMAB, 6, PlayerProfiles.AVATAR_MiniMax);
createAiPlayerProfile("Monty Carlo", MagicAIImpl.MCTS, 6, PlayerProfiles.AVATAR_MontyCarlo);
}
private static void createAiPlayerProfile(
final String name,
final MagicAIImpl aiImpl,
final int level,
final Path avatarPath) {
final AiProfile profile = AiProfile.create(name, aiImpl, level);
profile.save();
setPlayerAvatar(profile, avatarPath);
}
public static void setPlayerAvatar(final PlayerProfile profile, final Path avatarPath) {
final Path targetPath = profile.getProfilePath().resolve("player.avatar");
try {
Files.copy(avatarPath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (NoSuchFileException ex) {
System.err.println(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static PlayerProfile getDefaultHumanPlayer() {
return getHumanPlayerProfiles().values().iterator().next();
}
public static PlayerProfile getDefaultAiPlayer() {
for (PlayerProfile profile : getAiPlayerProfiles().values()) {
final AiProfile aiProfile = (AiProfile) profile;
if (aiProfile.getAiType() == MagicAIImpl.MCTS) {
return profile;
}
}
// No MCTS profile exists which can happen when importing
// previous set of players and default AI profiles have
// been deleted or changed by user. (see github issue #329).
return getAiPlayerProfiles().values().iterator().next();
}
private static HashMap<String, PlayerProfile> getPlayerProfiles(final Class<? extends PlayerProfile> profileClass) {
final HashMap<String, PlayerProfile> filteredProfiles = new HashMap<>();
for (PlayerProfile profile : profilesMap.values()) {
if (profile.getClass().equals(profileClass)) {
filteredProfiles.put(profile.getId(), profile);
}
}
return filteredProfiles;
}
public static HashMap<String, PlayerProfile> getHumanPlayerProfiles() {
return getPlayerProfiles(HumanProfile.class);
}
public static HashMap<String, PlayerProfile> getAiPlayerProfiles() {
return getPlayerProfiles(AiProfile.class);
}
/**
* @param duelConfigId
* @return
*/
public static PlayerProfile getPlayerProfile(String duelConfigId) {
return profilesMap.get(duelConfigId);
}
public static HashMap<String, PlayerProfile> getPlayerProfiles() {
return profilesMap;
}
public static void deletePlayer(final PlayerProfile playerProfile) {
MagicFileSystem.deleteDirectory(getPlayerProfileDirectory(playerProfile));
profilesMap.remove(playerProfile.getId());
}
private static Path getPlayerProfileDirectory(final PlayerProfile playerProfile) {
return profilesPath.resolve(playerProfile.getPlayerType()).resolve(playerProfile.getId());
}
public static boolean canDeleteProfile(final PlayerProfile playerProfile) {
return getPlayerProfiles(playerProfile.getClass()).size() > 1;
}
}
| magarena/magarena | src/magic/model/player/PlayerProfiles.java |
179,785 | package com.alphawallet.app.repository;
import com.alphawallet.app.entity.ContractLocator;
import com.alphawallet.app.entity.KnownContract;
import com.alphawallet.app.entity.NetworkInfo;
import com.alphawallet.app.entity.Wallet;
import com.alphawallet.app.entity.tokens.Token;
import org.web3j.protocol.Web3j;
import java.math.BigInteger;
import java.util.List;
import io.reactivex.Single;
public interface EthereumNetworkRepositoryType {
NetworkInfo getActiveBrowserNetwork();
void setActiveBrowserNetwork(NetworkInfo networkInfo);
NetworkInfo getNetworkByChain(long chainId);
Single<BigInteger> getLastTransactionNonce(Web3j web3j, String walletAddress);
NetworkInfo[] getAvailableNetworkList();
NetworkInfo[] getAllActiveNetworks();
void addOnChangeDefaultNetwork(OnNetworkChangeListener onNetworkChanged);
String getNameById(long chainId);
List<Long> getFilterNetworkList();
List<Long> getSelectedFilters();
Long getDefaultNetwork();
void setFilterNetworkList(Long[] networkList);
List<ContractLocator> getAllKnownContracts(List<Long> networkFilters);
Single<Token[]> getBlankOverrideTokens(Wallet wallet);
Token getBlankOverrideToken();
Token getBlankOverrideToken(NetworkInfo networkInfo);
KnownContract readContracts();
boolean getIsPopularToken(long chainId, String address);
String getCurrentWalletAddress();
boolean hasSetNetworkFilters();
void setHasSetNetworkFilters();
void saveCustomRPCNetwork(String networkName, String rpcUrl, long chainId, String symbol, String blockExplorerUrl, String explorerApiUrl, boolean isTestnet, Long oldChainId);
void removeCustomRPCNetwork(long chainId);
boolean isChainContract(long chainId, String address);
boolean hasLockedGas(long chainId);
boolean hasBlockNativeGasAPI(long chainId);
NetworkInfo getBuiltInNetwork(long chainId);
void commitPrefs();
}
| AlphaWallet/alpha-wallet-android | app/src/main/java/com/alphawallet/app/repository/EthereumNetworkRepositoryType.java |
179,786 | /**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.connectors.flink.source;
import io.pravega.client.ClientConfig;
import io.pravega.client.stream.Checkpoint;
import io.pravega.client.stream.ReaderGroupConfig;
import io.pravega.connectors.flink.AbstractStreamingReaderBuilder;
import io.pravega.connectors.flink.serialization.CheckpointSerializer;
import io.pravega.connectors.flink.source.enumerator.PravegaSplitEnumerator;
import io.pravega.connectors.flink.source.reader.PravegaRecordEmitter;
import io.pravega.connectors.flink.source.reader.PravegaSourceReader;
import io.pravega.connectors.flink.source.reader.PravegaSplitReader;
import io.pravega.connectors.flink.source.split.PravegaSplit;
import io.pravega.connectors.flink.source.split.PravegaSplitSerializer;
import org.apache.flink.annotation.Experimental;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.connector.source.Boundedness;
import org.apache.flink.api.connector.source.Source;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.SplitEnumerator;
import org.apache.flink.api.connector.source.SplitEnumeratorContext;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.function.Supplier;
/**
* The Source implementation of Pravega. Please use a {@link PravegaSourceBuilder} to construct a {@link
* PravegaSource}. The {@link PravegaSource} has two main components, {@link PravegaSplitEnumerator} and {@link PravegaSourceReader}.
*
* <p>The Split Enumerator will discover the splits(which represent Pravega EventStreamReaders) and then assign them to the Source Readers.
* For Pravega, {@link PravegaSplitEnumerator} will assign splits of the same amount as the current parallelism to Source Readers,
* while there will be one split assigned per Source Reader only.
*
* <p>The Source Reader will read the actual data. {@link PravegaSourceReader} encapsulates a Pravega EventStreamReader
* from the split assigned by Split Enumerator, which will read events from Pravega stream.
*
* <p>The following example shows how to create a PravegaSource emitting records of <code>
* Integer</code> type.
*
* <pre>{@code
* PravegaSource<Integer> pravegaSource = PravegaSource.<Integer>builder()
* .forStream(streamName)
* .enableMetrics(false)
* .withPravegaConfig(pravegaConfig)
* .withReaderGroupName("flink-reader")
* .withDeserializationSchema(new IntegerDeserializationSchema())
* .build();
* }</pre>
*
* @param <T> the output type of the source.
*/
@Experimental
@PublicEvolving
public class PravegaSource<T>
implements Source<T, PravegaSplit, Checkpoint>, ResultTypeQueryable<T> {
private static final Logger LOG = LoggerFactory.getLogger(PravegaSource.class);
// The Pravega client config.
final ClientConfig clientConfig;
// The Pravega reader group config.
final ReaderGroupConfig readerGroupConfig;
// The scope name of the reader group.
final String scope;
// The readergroup name to colordinate the parallel readers. This should be unique for a Flink job.
final String readerGroupName;
// The supplied event deserializer.
final DeserializationSchema<T> deserializationSchema;
// the timeout for reading events from Pravega
final Time eventReadTimeout;
// the timeout for call that initiates the Pravega checkpoint
final Time checkpointInitiateTimeout;
// flag to enable/disable metrics
final boolean enableMetrics;
/**
* Creates a new Pravega Source instance which can be added as a source to a Flink job.
* It manages a reader group with a builder style constructor with user provided ReaderGroupConfig.
* We can use {@link AbstractStreamingReaderBuilder} to build such a source.
*
* @param clientConfig The Pravega client configuration.
* @param readerGroupConfig The Pravega reader group configuration.
* @param scope The reader group scope name.
* @param readerGroupName The reader group name.
* @param deserializationSchema The implementation to deserialize events from Pravega streams.
* @param eventReadTimeout The event read timeout.
* @param checkpointInitiateTimeout The checkpoint initiation timeout.
* @param enableMetrics Flag to indicate whether metrics needs to be enabled or not.
*/
public PravegaSource(ClientConfig clientConfig,
ReaderGroupConfig readerGroupConfig, String scope, String readerGroupName,
DeserializationSchema<T> deserializationSchema,
Time eventReadTimeout, Time checkpointInitiateTimeout,
boolean enableMetrics) {
this.clientConfig = Preconditions.checkNotNull(clientConfig, "clientConfig");
this.readerGroupConfig = Preconditions.checkNotNull(readerGroupConfig, "readerGroupConfig");
this.scope = Preconditions.checkNotNull(scope, "scope");
this.readerGroupName = Preconditions.checkNotNull(readerGroupName, "readerGroupName");
this.deserializationSchema = Preconditions.checkNotNull(deserializationSchema, "deserializationSchema");
this.eventReadTimeout = Preconditions.checkNotNull(eventReadTimeout, "eventReadTimeout");
this.checkpointInitiateTimeout = Preconditions.checkNotNull(checkpointInitiateTimeout, "checkpointInitiateTimeout");
this.enableMetrics = enableMetrics;
}
@Override
public Boundedness getBoundedness() {
return Boundedness.CONTINUOUS_UNBOUNDED;
}
@Internal
@Override
public SourceReader<T, PravegaSplit> createReader(SourceReaderContext readerContext) {
Supplier<PravegaSplitReader> splitReaderSupplier =
() -> new PravegaSplitReader(scope, clientConfig,
readerGroupName, readerContext.getIndexOfSubtask());
return new PravegaSourceReader<>(
splitReaderSupplier,
new PravegaRecordEmitter<>(deserializationSchema),
new Configuration(),
readerContext);
}
@Internal
@Override
public SplitEnumerator<PravegaSplit, Checkpoint> createEnumerator(
SplitEnumeratorContext<PravegaSplit> enumContext) {
return new PravegaSplitEnumerator(
enumContext,
this.scope,
this.readerGroupName,
this.clientConfig,
this.readerGroupConfig,
null);
}
@Internal
@Override
public SplitEnumerator<PravegaSplit, Checkpoint> restoreEnumerator(
SplitEnumeratorContext<PravegaSplit> enumContext, Checkpoint checkpoint) throws IOException {
return new PravegaSplitEnumerator(
enumContext,
this.scope,
this.readerGroupName,
this.clientConfig,
this.readerGroupConfig,
checkpoint);
}
@Internal
@Override
public SimpleVersionedSerializer<PravegaSplit> getSplitSerializer() {
return new PravegaSplitSerializer();
}
@Internal
@Override
public SimpleVersionedSerializer<Checkpoint> getEnumeratorCheckpointSerializer() {
return new CheckpointSerializer();
}
@Override
public TypeInformation<T> getProducedType() {
return this.deserializationSchema.getProducedType();
}
// --------------- configurations -------------------------------
/**
* Gets a builder for {@link PravegaSource} to read Pravega streams using the Flink streaming API.
* @param <T> the element type.
* @return A new builder of {@link PravegaSource}
*/
public static <T> PravegaSourceBuilder<T> builder() {
return new PravegaSourceBuilder<>();
}
}
| pravega/flink-connectors | src/main/java/io/pravega/connectors/flink/source/PravegaSource.java |
179,787 | /*
* This file is part of RskJ
* Copyright (C) 2017 RSK Labs Ltd.
* (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.core;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import org.ethereum.vm.LogInfo;
import org.spongycastle.util.BigIntegers;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.apache.commons.lang3.ArrayUtils.nullToEmpty;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
/**
* The transaction receipt is a tuple of three items
* comprising the transaction, together with the post-transaction state,
* and the cumulative gas used in the block containing the transaction receipt
* as of immediately after the transaction has happened,
*/
public class TransactionReceipt {
private Transaction transaction;
protected static final byte[] FAILED_STATUS = EMPTY_BYTE_ARRAY;
protected static final byte[] SUCCESS_STATUS = new byte[]{0x01};
private byte[] postTxState = EMPTY_BYTE_ARRAY;
private byte[] cumulativeGas = EMPTY_BYTE_ARRAY;
private byte[] gasUsed = EMPTY_BYTE_ARRAY;
private byte[] status = EMPTY_BYTE_ARRAY;
private Bloom bloomFilter = new Bloom();
private List<LogInfo> logInfoList = new ArrayList<>();
/* Tx Receipt in encoded form */
private byte[] rlpEncoded;
public TransactionReceipt() {
}
public TransactionReceipt(byte[] rlp) {
ArrayList<RLPElement> params = RLP.decode2(rlp);
RLPList receipt = (RLPList) params.get(0);
RLPItem postTxStateRLP = (RLPItem) receipt.get(0);
RLPItem cumulativeGasRLP = (RLPItem) receipt.get(1);
RLPItem bloomRLP = (RLPItem) receipt.get(2);
RLPList logs = (RLPList) receipt.get(3);
RLPItem gasUsedRLP = (RLPItem) receipt.get(4);
postTxState = nullToEmpty(postTxStateRLP.getRLPData());
cumulativeGas = cumulativeGasRLP.getRLPData() == null ? EMPTY_BYTE_ARRAY : cumulativeGasRLP.getRLPData();
bloomFilter = new Bloom(bloomRLP.getRLPData());
gasUsed = gasUsedRLP.getRLPData() == null ? EMPTY_BYTE_ARRAY : gasUsedRLP.getRLPData();
if (receipt.size() > 5 ) {
byte[] transactionStatus = nullToEmpty(receipt.get(5).getRLPData());
this.status = transactionStatus;
}
for (RLPElement log : logs) {
LogInfo logInfo = new LogInfo(log.getRLPData());
logInfoList.add(logInfo);
}
rlpEncoded = rlp;
}
public TransactionReceipt(byte[] postTxState, byte[] cumulativeGas, byte[] gasUsed,
Bloom bloomFilter, List<LogInfo> logInfoList, byte[] status) {
this.postTxState = postTxState;
this.cumulativeGas = cumulativeGas;
this.gasUsed = gasUsed;
this.bloomFilter = bloomFilter;
this.logInfoList = logInfoList;
if (Arrays.equals(status, FAILED_STATUS) || Arrays.equals(status, SUCCESS_STATUS)) {
this.status = status;
}
}
public byte[] getPostTxState() {
return postTxState;
}
public byte[] getCumulativeGas() {
return cumulativeGas;
}
// TODO: return gas used for this transaction instead of cumulative gas
public byte[] getGasUsed() {
return gasUsed;
}
public long getCumulativeGasLong() {
return new BigInteger(1, cumulativeGas).longValue();
}
public Bloom getBloomFilter() {
return bloomFilter;
}
public List<LogInfo> getLogInfoList() {
return logInfoList;
}
/* [postTxState, cumulativeGas, bloomFilter, logInfoList] */
public byte[] getEncoded() {
if (rlpEncoded != null) {
return rlpEncoded;
}
byte[] postTxStateRLP = RLP.encodeElement(this.postTxState);
byte[] cumulativeGasRLP = RLP.encodeElement(this.cumulativeGas);
byte[] gasUsedRLP = RLP.encodeElement(this.gasUsed);
byte[] bloomRLP = RLP.encodeElement(this.bloomFilter.data);
byte[] statusRLP = RLP.encodeElement(this.status);
final byte[] logInfoListRLP;
if (logInfoList != null) {
byte[][] logInfoListE = new byte[logInfoList.size()][];
int i = 0;
for (LogInfo logInfo : logInfoList) {
logInfoListE[i] = logInfo.getEncoded();
++i;
}
logInfoListRLP = RLP.encodeList(logInfoListE);
} else {
logInfoListRLP = RLP.encodeList();
}
rlpEncoded = RLP.encodeList(postTxStateRLP, cumulativeGasRLP, bloomRLP, logInfoListRLP, gasUsedRLP, statusRLP);
return rlpEncoded;
}
public void setStatus(byte[] status) {
if (Arrays.equals(status, FAILED_STATUS)){
this.status = FAILED_STATUS;
} else if (Arrays.equals(status, SUCCESS_STATUS)){
this.status = SUCCESS_STATUS;
}
}
public boolean isSuccessful() {
return Arrays.equals(this.status, SUCCESS_STATUS);
}
public void setTxStatus(boolean success) {
this.postTxState = success ? new byte[]{1} : new byte[0];
rlpEncoded = null;
}
public boolean hasTxStatus() {
return postTxState != null && postTxState.length <= 1;
}
public boolean isTxStatusOK() {
return postTxState != null && postTxState.length == 1 && postTxState[0] == 1;
}
public void setPostTxState(byte[] postTxState) {
this.postTxState = postTxState;
}
public void setCumulativeGas(long cumulativeGas) {
this.cumulativeGas = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(cumulativeGas));
}
public void setGasUsed(long gasUsed) {
this.gasUsed = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(gasUsed));
}
public void setCumulativeGas(byte[] cumulativeGas) {
this.cumulativeGas = cumulativeGas;
}
public void setGasUsed(byte[] gasUsed) {
this.gasUsed = gasUsed;
}
public void setLogInfoList(List<LogInfo> logInfoList) {
if (logInfoList == null) {
return;
}
this.rlpEncoded = null;
this.logInfoList = logInfoList;
for (LogInfo loginfo : logInfoList) {
bloomFilter.or(loginfo.getBloom());
}
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public Transaction getTransaction() {
return transaction;
}
@Override
public String toString() {
// todo: fix that
return "TransactionReceipt[" +
"\n , " + (hasTxStatus() ? ("txStatus=" + (isSuccessful()? "OK" : "FAILED"))
: ("postTxState=" + Hex.toHexString(postTxState))) +
"\n , cumulativeGas=" + Hex.toHexString(cumulativeGas) +
"\n , bloom=" + bloomFilter.toString() +
"\n , logs=" + logInfoList +
']';
}
public byte[] getStatus() {
return this.status;
}
}
| projectpai/rskj | rskj-core/src/main/java/org/ethereum/core/TransactionReceipt.java |
179,788 | // Auto-generated by conformance/Rakefile
package com.twitter;
import java.util.Arrays;
import java.util.List;
public class TldLists {
public static final List<String> GTLDS = Arrays.asList(
"abb",
"abbott",
"abogado",
"academy",
"accenture",
"accountant",
"accountants",
"aco",
"active",
"actor",
"ads",
"adult",
"aeg",
"aero",
"afl",
"agency",
"aig",
"airforce",
"airtel",
"allfinanz",
"alsace",
"amsterdam",
"android",
"apartments",
"app",
"aquarelle",
"archi",
"army",
"arpa",
"asia",
"associates",
"attorney",
"auction",
"audio",
"auto",
"autos",
"axa",
"azure",
"band",
"bank",
"bar",
"barcelona",
"barclaycard",
"barclays",
"bargains",
"bauhaus",
"bayern",
"bbc",
"bbva",
"bcn",
"beer",
"bentley",
"berlin",
"best",
"bet",
"bharti",
"bible",
"bid",
"bike",
"bing",
"bingo",
"bio",
"biz",
"black",
"blackfriday",
"bloomberg",
"blue",
"bmw",
"bnl",
"bnpparibas",
"boats",
"bond",
"boo",
"boots",
"boutique",
"bradesco",
"bridgestone",
"broker",
"brother",
"brussels",
"budapest",
"build",
"builders",
"business",
"buzz",
"bzh",
"cab",
"cafe",
"cal",
"camera",
"camp",
"cancerresearch",
"canon",
"capetown",
"capital",
"caravan",
"cards",
"care",
"career",
"careers",
"cars",
"cartier",
"casa",
"cash",
"casino",
"cat",
"catering",
"cba",
"cbn",
"ceb",
"center",
"ceo",
"cern",
"cfa",
"cfd",
"chanel",
"channel",
"chat",
"cheap",
"chloe",
"christmas",
"chrome",
"church",
"cisco",
"citic",
"city",
"claims",
"cleaning",
"click",
"clinic",
"clothing",
"cloud",
"club",
"coach",
"codes",
"coffee",
"college",
"cologne",
"com",
"commbank",
"community",
"company",
"computer",
"condos",
"construction",
"consulting",
"contractors",
"cooking",
"cool",
"coop",
"corsica",
"country",
"coupons",
"courses",
"credit",
"creditcard",
"cricket",
"crown",
"crs",
"cruises",
"cuisinella",
"cymru",
"cyou",
"dabur",
"dad",
"dance",
"date",
"dating",
"datsun",
"day",
"dclk",
"deals",
"degree",
"delivery",
"delta",
"democrat",
"dental",
"dentist",
"desi",
"design",
"dev",
"diamonds",
"diet",
"digital",
"direct",
"directory",
"discount",
"dnp",
"docs",
"dog",
"doha",
"domains",
"doosan",
"download",
"drive",
"durban",
"dvag",
"earth",
"eat",
"edu",
"education",
"email",
"emerck",
"energy",
"engineer",
"engineering",
"enterprises",
"epson",
"equipment",
"erni",
"esq",
"estate",
"eurovision",
"eus",
"events",
"everbank",
"exchange",
"expert",
"exposed",
"express",
"fage",
"fail",
"faith",
"family",
"fan",
"fans",
"farm",
"fashion",
"feedback",
"film",
"finance",
"financial",
"firmdale",
"fish",
"fishing",
"fit",
"fitness",
"flights",
"florist",
"flowers",
"flsmidth",
"fly",
"foo",
"football",
"forex",
"forsale",
"forum",
"foundation",
"frl",
"frogans",
"fund",
"furniture",
"futbol",
"fyi",
"gal",
"gallery",
"game",
"garden",
"gbiz",
"gdn",
"gent",
"genting",
"ggee",
"gift",
"gifts",
"gives",
"giving",
"glass",
"gle",
"global",
"globo",
"gmail",
"gmo",
"gmx",
"gold",
"goldpoint",
"golf",
"goo",
"goog",
"google",
"gop",
"gov",
"graphics",
"gratis",
"green",
"gripe",
"group",
"guge",
"guide",
"guitars",
"guru",
"hamburg",
"hangout",
"haus",
"healthcare",
"help",
"here",
"hermes",
"hiphop",
"hitachi",
"hiv",
"hockey",
"holdings",
"holiday",
"homedepot",
"homes",
"honda",
"horse",
"host",
"hosting",
"hoteles",
"hotmail",
"house",
"how",
"hsbc",
"ibm",
"icbc",
"ice",
"icu",
"ifm",
"iinet",
"immo",
"immobilien",
"industries",
"infiniti",
"info",
"ing",
"ink",
"institute",
"insure",
"int",
"international",
"investments",
"ipiranga",
"irish",
"ist",
"istanbul",
"itau",
"iwc",
"java",
"jcb",
"jetzt",
"jewelry",
"jlc",
"jll",
"jobs",
"joburg",
"jprs",
"juegos",
"kaufen",
"kddi",
"kim",
"kitchen",
"kiwi",
"koeln",
"komatsu",
"krd",
"kred",
"kyoto",
"lacaixa",
"lancaster",
"land",
"lasalle",
"lat",
"latrobe",
"law",
"lawyer",
"lds",
"lease",
"leclerc",
"legal",
"lexus",
"lgbt",
"liaison",
"lidl",
"life",
"lighting",
"limited",
"limo",
"link",
"live",
"lixil",
"loan",
"loans",
"lol",
"london",
"lotte",
"lotto",
"love",
"ltda",
"lupin",
"luxe",
"luxury",
"madrid",
"maif",
"maison",
"man",
"management",
"mango",
"market",
"marketing",
"markets",
"marriott",
"mba",
"media",
"meet",
"melbourne",
"meme",
"memorial",
"men",
"menu",
"miami",
"microsoft",
"mil",
"mini",
"mma",
"mobi",
"moda",
"moe",
"mom",
"monash",
"money",
"montblanc",
"mormon",
"mortgage",
"moscow",
"motorcycles",
"mov",
"movie",
"movistar",
"mtn",
"mtpc",
"museum",
"nadex",
"nagoya",
"name",
"navy",
"nec",
"net",
"netbank",
"network",
"neustar",
"new",
"news",
"nexus",
"ngo",
"nhk",
"nico",
"ninja",
"nissan",
"nokia",
"nra",
"nrw",
"ntt",
"nyc",
"office",
"okinawa",
"omega",
"one",
"ong",
"onion",
"onl",
"online",
"ooo",
"oracle",
"orange",
"org",
"organic",
"osaka",
"otsuka",
"ovh",
"page",
"panerai",
"paris",
"partners",
"parts",
"party",
"pet",
"pharmacy",
"philips",
"photo",
"photography",
"photos",
"physio",
"piaget",
"pics",
"pictet",
"pictures",
"pink",
"pizza",
"place",
"play",
"plumbing",
"plus",
"pohl",
"poker",
"porn",
"post",
"praxi",
"press",
"pro",
"prod",
"productions",
"prof",
"properties",
"property",
"pub",
"qpon",
"quebec",
"racing",
"realtor",
"realty",
"recipes",
"red",
"redstone",
"rehab",
"reise",
"reisen",
"reit",
"ren",
"rent",
"rentals",
"repair",
"report",
"republican",
"rest",
"restaurant",
"review",
"reviews",
"rich",
"ricoh",
"rio",
"rip",
"rocks",
"rodeo",
"rsvp",
"ruhr",
"run",
"ryukyu",
"saarland",
"sakura",
"sale",
"samsung",
"sandvik",
"sandvikcoromant",
"sanofi",
"sap",
"sarl",
"saxo",
"sca",
"scb",
"schmidt",
"scholarships",
"school",
"schule",
"schwarz",
"science",
"scor",
"scot",
"seat",
"seek",
"sener",
"services",
"sew",
"sex",
"sexy",
"shiksha",
"shoes",
"show",
"shriram",
"singles",
"site",
"ski",
"sky",
"skype",
"sncf",
"soccer",
"social",
"software",
"sohu",
"solar",
"solutions",
"sony",
"soy",
"space",
"spiegel",
"spreadbetting",
"srl",
"starhub",
"statoil",
"studio",
"study",
"style",
"sucks",
"supplies",
"supply",
"support",
"surf",
"surgery",
"suzuki",
"swatch",
"swiss",
"sydney",
"systems",
"taipei",
"tatamotors",
"tatar",
"tattoo",
"tax",
"taxi",
"team",
"tech",
"technology",
"tel",
"telefonica",
"temasek",
"tennis",
"thd",
"theater",
"tickets",
"tienda",
"tips",
"tires",
"tirol",
"today",
"tokyo",
"tools",
"top",
"toray",
"toshiba",
"tours",
"town",
"toyota",
"toys",
"trade",
"trading",
"training",
"travel",
"trust",
"tui",
"ubs",
"university",
"uno",
"uol",
"vacations",
"vegas",
"ventures",
"vermögensberater",
"vermögensberatung",
"versicherung",
"vet",
"viajes",
"video",
"villas",
"vin",
"vision",
"vista",
"vistaprint",
"vlaanderen",
"vodka",
"vote",
"voting",
"voto",
"voyage",
"wales",
"walter",
"wang",
"watch",
"webcam",
"website",
"wed",
"wedding",
"weir",
"whoswho",
"wien",
"wiki",
"williamhill",
"win",
"windows",
"wine",
"wme",
"work",
"works",
"world",
"wtc",
"wtf",
"xbox",
"xerox",
"xin",
"xperia",
"xxx",
"xyz",
"yachts",
"yandex",
"yodobashi",
"yoga",
"yokohama",
"youtube",
"zip",
"zone",
"zuerich",
"дети",
"ком",
"москва",
"онлайн",
"орг",
"рус",
"сайт",
"קום",
"بازار",
"شبكة",
"كوم",
"موقع",
"कॉम",
"नेट",
"संगठन",
"คอม",
"みんな",
"グーグル",
"コム",
"世界",
"中信",
"中文网",
"企业",
"佛山",
"信息",
"健康",
"八卦",
"公司",
"公益",
"商城",
"商店",
"商标",
"在线",
"大拿",
"娱乐",
"工行",
"广东",
"慈善",
"我爱你",
"手机",
"政务",
"政府",
"新闻",
"时尚",
"机构",
"淡马锡",
"游戏",
"点看",
"移动",
"组织机构",
"网址",
"网店",
"网络",
"谷歌",
"集团",
"飞利浦",
"餐厅",
"닷넷",
"닷컴",
"삼성"
);
public static final List<String> CTLDS = Arrays.asList(
"ac",
"ad",
"ae",
"af",
"ag",
"ai",
"al",
"am",
"an",
"ao",
"aq",
"ar",
"as",
"at",
"au",
"aw",
"ax",
"az",
"ba",
"bb",
"bd",
"be",
"bf",
"bg",
"bh",
"bi",
"bj",
"bl",
"bm",
"bn",
"bo",
"bq",
"br",
"bs",
"bt",
"bv",
"bw",
"by",
"bz",
"ca",
"cc",
"cd",
"cf",
"cg",
"ch",
"ci",
"ck",
"cl",
"cm",
"cn",
"co",
"cr",
"cu",
"cv",
"cw",
"cx",
"cy",
"cz",
"de",
"dj",
"dk",
"dm",
"do",
"dz",
"ec",
"ee",
"eg",
"eh",
"er",
"es",
"et",
"eu",
"fi",
"fj",
"fk",
"fm",
"fo",
"fr",
"ga",
"gb",
"gd",
"ge",
"gf",
"gg",
"gh",
"gi",
"gl",
"gm",
"gn",
"gp",
"gq",
"gr",
"gs",
"gt",
"gu",
"gw",
"gy",
"hk",
"hm",
"hn",
"hr",
"ht",
"hu",
"id",
"ie",
"il",
"im",
"in",
"io",
"iq",
"ir",
"is",
"it",
"je",
"jm",
"jo",
"jp",
"ke",
"kg",
"kh",
"ki",
"km",
"kn",
"kp",
"kr",
"kw",
"ky",
"kz",
"la",
"lb",
"lc",
"li",
"lk",
"lr",
"ls",
"lt",
"lu",
"lv",
"ly",
"ma",
"mc",
"md",
"me",
"mf",
"mg",
"mh",
"mk",
"ml",
"mm",
"mn",
"mo",
"mp",
"mq",
"mr",
"ms",
"mt",
"mu",
"mv",
"mw",
"mx",
"my",
"mz",
"na",
"nc",
"ne",
"nf",
"ng",
"ni",
"nl",
"no",
"np",
"nr",
"nu",
"nz",
"om",
"pa",
"pe",
"pf",
"pg",
"ph",
"pk",
"pl",
"pm",
"pn",
"pr",
"ps",
"pt",
"pw",
"py",
"qa",
"re",
"ro",
"rs",
"ru",
"rw",
"sa",
"sb",
"sc",
"sd",
"se",
"sg",
"sh",
"si",
"sj",
"sk",
"sl",
"sm",
"sn",
"so",
"sr",
"ss",
"st",
"su",
"sv",
"sx",
"sy",
"sz",
"tc",
"td",
"tf",
"tg",
"th",
"tj",
"tk",
"tl",
"tm",
"tn",
"to",
"tp",
"tr",
"tt",
"tv",
"tw",
"tz",
"ua",
"ug",
"uk",
"um",
"us",
"uy",
"uz",
"va",
"vc",
"ve",
"vg",
"vi",
"vn",
"vu",
"wf",
"ws",
"ye",
"yt",
"za",
"zm",
"zw",
"ελ",
"бел",
"мкд",
"мон",
"рф",
"срб",
"укр",
"қаз",
"հայ",
"الاردن",
"الجزائر",
"السعودية",
"المغرب",
"امارات",
"ایران",
"بھارت",
"تونس",
"سودان",
"سورية",
"عراق",
"عمان",
"فلسطين",
"قطر",
"مصر",
"مليسيا",
"پاکستان",
"भारत",
"বাংলা",
"ভারত",
"ਭਾਰਤ",
"ભારત",
"இந்தியா",
"இலங்கை",
"சிங்கப்பூர்",
"భారత్",
"ලංකා",
"ไทย",
"გე",
"中国",
"中國",
"台湾",
"台灣",
"新加坡",
"澳門",
"香港",
"한국"
);
}
| Qoracoin/Qora | Qora/src/com/twitter/TldLists.java |
179,789 | /** *****************************************************************************
* Copyright (c) 2015 David Lamparter, Daniel Marbach
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
****************************************************************************** */
package ch.unil.genescore.vegas;
import java.math.BigDecimal;
/**
* Refactored from R package CompQuadForm by Pierre Lafaye de Micheaux and
* Pierre Duchesne. See bottom of file for original code.
*
* Distribution function (survival function in fact) of quadratic forms in
* normal variables using Davies algorithm.
*
*/
public class DaviesBigDecimal implements WeightedChisquareAlgorithm {
// ARGUMENTS
private final double log28 = .0866;
/* log(2.0) / 8.0 */
private double sigsq, lmax, lmin, mean, c;
private BigDecimal intl;
private double ersm;
private int count, r, lim;
private boolean ndtsrt, fail;
private int n[], th[];
private double lb[], nc[];
double sigma_ = 0;
// // void qfc(double* lb1, double* nc1, int* n1, int *r1, double *sigma, double *c1, int *lim1, double *acc, double* trace, int* ifault, double *res)
//double[] lb1;
//double[] nc1;
//int[] n1;
//int[] r1;
//double[] sigma;
//double[] c1;
//int[] lim1;
//double[] acc;
double[] trace;
/**
* Value point at which the survival function is to be evaluated
*/
private double q_ = -1;
/**
* Distinct non-zero characteristic roots of A\Sigma
*/
private double[] lambda_ = null;
/**
* Respective orders of multiplicity of the lambdas (degrees of the chi2
* variables)
*/
private int[] h_ = null;
/**
* Non-centrality parameters of the chi2 variables
*/
private double[] delta_ = null;
/**
* Error bound. R documentation: error bound. Suitable values for acc range
* from 0.001 to 0.00005
*/
private double acc_ = -1;
/**
* Maximum number of integration terms. Realistic values for lim range from
* 1000 if the procedure is to be called repeatedly up to 50 000 if it is to
* be called only occasionally
*/
private int lim_ = -1;
/**
* The result
*/
private BigDecimal qfval;
/**
* Error code
*/
private int ifault = 0;
public class NonCovergeneceException extends RuntimeException {
private static final long serialVersionUID = 7845175270361304271L;
};
// ============================================================================
// PUBLIC METHODS
// davies <- function (q, lambda, h = rep(1, length(lambda)), delta = rep(0,
// length(lambda)), sigma = 0, lim = 10000, acc = 1e-04)
// {
// r <- length(lambda)
// if (length(h) != r)
// stop("lambda and h should have the same length!")
// if (length(delta) != r)
// stop("lambda and delta should have the same length!")
// out <- .C("qfc", lambdas = as.double(lambda), noncentral = as.double(delta),
// df = as.integer(h), r = as.integer(r), sigma = as.double(sigma),
// q = as.double(q), lim = as.integer(lim), acc = as.double(acc),
// trace = as.double(rep(0, 7)), ifault = as.integer(0),
// res = as.double(0), PACKAGE = "CompQuadForm")
// out$res <- 1 - out$res
// return(list(trace = out$trace, ifault = out$ifault, Qq = out$res))
// }
// <environment: namespace:CompQuadForm>
/**
* Constructor
*/
public DaviesBigDecimal(double[] lambda) {
lambda_ = lambda;
h_ = new int[lambda.length];
for (int i = 0; i < lambda.length; i++) {
h_[i] = 1;
}
delta_ = new double[lambda.length];
for (int i = 0; i < lambda.length; i++) {
delta_[i] = 0;
}
acc_ = 1e-20;
lim_ = 50000;
}
// ----------------------------------------------------------------------------
/**
* Compute P(Q > q)
*/
public double probQsupx(double q) {
// initialize
q_ = q;
ifault = 0;
//qfval = -41;
trace = new double[7];
for (int i = 0; i < 7; i++) {
trace[i] = 0.0;
}
// compute
qfc();
qfval = BigDecimal.ONE.subtract(qfval);
return qfval.doubleValue();
}
public int getIfault() {
return ifault;
}
// ============================================================================
// PRIVATE FUNCTIONS
/* to avoid underflows */
private double exp1(double x) {
return x < -50.0 ? 0.0 : Math.exp(x);
}
/* count number of calls to errbd, truncation, cfe */
private void counter() {
count = count + 1;
if (count > lim) {
ifault = 4;
throw new NonCovergeneceException();
}
}
private double square(double x) {
return x * x;
}
private double cube(double x) {
return x * x * x;
}
/* if (first) log(1 + x) ; else log(1 + x) - x */
private double log1(double x, boolean first) {
if (Math.abs(x) > 0.1) {
return (first ? Math.log(1.0 + x) : (Math.log(1.0 + x) - x));
} else {
double s, s1, term, y, k;
y = x / (2.0 + x);
term = 2.0 * cube(y);
k = 3.0;
s = (first ? 2.0 : -x) * y;
y = square(y);
for (s1 = s + term / k; s1 != s; s1 = s + term / k) {
k = k + 2.0;
term = term * y;
s = s1;
}
return s;
}
}
/* find order of absolute values of lb */
private void order() {
int j, k;
double lj;
//extern double *lb; extern int *th; extern int r; extern BOOL ndtsrt;
for (j = 0; j < r; j++) {
lj = Math.abs(lb[j]);
boolean gotol1 = false;
for (k = j - 1; k >= 0; k--) {
if (lj > Math.abs(lb[th[k]])) {
th[k + 1] = th[k];
} //else goto l1;
else {
gotol1 = true;
break;
}
}
if (!gotol1) {
k = -1;
}
//l1 :
th[k + 1] = j;
}
ndtsrt = false;
}
private double errbd(double u, double[] cx) /* find bound on tail probability using mgf, cutoff
point returned to *cx */ {
double sum1, lj, ncj, x, y, xconst;
int j, nj;
//extern double sigsq,*lb,*nc; extern int *n; extern int r;
counter();
xconst = u * sigsq;
sum1 = u * xconst;
u = 2.0 * u;
for (j = r - 1; j >= 0; j--) {
nj = n[j];
lj = lb[j];
ncj = nc[j];
x = u * lj;
y = 1.0 - x;
xconst = xconst + lj * (ncj / y + nj) / y;
sum1 = sum1 + ncj * square(x / y)
+ nj * (square(x) / y + log1(-x, false));
}
cx[0] = xconst;
return exp1(-0.5 * sum1);
}
private double ctff(double accx, double[] upn) /* find ctff so that p(qf > ctff) < accx if (upn > 0,
p(qf < ctff) < accx otherwise */ {
double u1, u2, u, rb, c1;// c2;
double[] c2 = new double[1];
double[] xconst = new double[1];
//extern double lmin,lmax,mean;
u2 = upn[0];
u1 = 0.0;
c1 = mean;
rb = 2.0 * ((u2 > 0.0) ? lmax : lmin);
for (u = u2 / (1.0 + u2 * rb); errbd(u, c2) > accx;
u = u2 / (1.0 + u2 * rb)) {
u1 = u2;
c1 = c2[0];
u2 = 2.0 * u2;
}
for (u = (c1 - mean) / (c2[0] - mean); u < 0.9;
u = (c1 - mean) / (c2[0] - mean)) {
u = (u1 + u2) / 2.0;
if (errbd(u / (1.0 + u * rb), xconst) > accx) {
u1 = u;
c1 = xconst[0];
} else {
u2 = u;
c2[0] = xconst[0];
}
}
upn[0] = u2;
return c2[0];
}
private double truncation(double u, double tausq) /* bound integration error due to truncation at u */ {
double sum1, sum2, prod1, prod2, prod3, lj, ncj,
x, y, err1, err2;
int j, nj, s;
//extern double sigsq,*lb,*nc; extern int *n; extern int r;
counter();
sum1 = 0.0;
prod2 = 0.0;
prod3 = 0.0;
s = 0;
sum2 = (sigsq + tausq) * square(u);
prod1 = 2.0 * sum2;
u = 2.0 * u;
for (j = 0; j < r; j++) {
lj = lb[j];
ncj = nc[j];
nj = n[j];
x = square(u * lj);
sum1 = sum1 + ncj * x / (1.0 + x);
if (x > 1.0) {
prod2 = prod2 + nj * Math.log(x);
prod3 = prod3 + nj * log1(x, true);
s = s + nj;
} else {
prod1 = prod1 + nj * log1(x, true);
}
}
sum1 = 0.5 * sum1;
prod2 = prod1 + prod2;
prod3 = prod1 + prod3;
x = exp1(-sum1 - 0.25 * prod2) / Math.PI;
y = exp1(-sum1 - 0.25 * prod3) / Math.PI;
err1 = (s == 0) ? 1.0 : x * 2.0 / s;
err2 = (prod3 > 1.0) ? 2.5 * y : 1.0;
if (err2 < err1) {
err1 = err2;
}
x = 0.5 * sum2;
err2 = (x <= y) ? 1.0 : y / x;
return (err1 < err2) ? err1 : err2;
}
private void findu(double[] utx, double accx) /* find u such that truncation(u) < accx and truncation(u / 1.2) > accx */ {
double u, ut;
int i;
final double divis[] = {2.0, 1.4, 1.2, 1.1};
ut = utx[0];
u = ut / 4.0;
if (truncation(u, 0.0) > accx) {
for (u = ut; truncation(u, 0.0) > accx; u = ut) {
ut = ut * 4.0;
}
} else {
ut = u;
for (u = u / 4.0; truncation(u, 0.0) <= accx; u = u / 4.0) {
ut = u;
}
}
for (i = 0; i < 4; i++) {
u = ut / divis[i];
if (truncation(u, 0.0) <= accx) {
ut = u;
}
}
utx[0] = ut;
}
private void integrate(int nterm, double interv, double tausq, boolean mainx) /* carry out integration with nterm terms, at stepsize
interv. if (! mainx) multiply integrand by
1.0-exp(-0.5*tausq*u^2) */ {
double inpi, u, sum1, sum2, sum3, x, y, z;
int k, j, nj;
//extern double intl,ersm; extern double sigsq,c;
//extern int *n; extern double *lb,*nc; extern int r;
inpi = interv / Math.PI;
for (k = nterm; k >= 0; k--) {
u = (k + 0.5) * interv;
sum1 = -2.0 * u * c;
sum2 = Math.abs(sum1);
sum3 = -0.5 * sigsq * square(u);
for (j = r - 1; j >= 0; j--) {
nj = n[j];
x = 2.0 * lb[j] * u;
y = square(x);
sum3 = sum3 - 0.25 * nj * log1(y, true);
y = nc[j] * x / (1.0 + y);
z = nj * Math.atan(x) + y;
sum1 = sum1 + z;
sum2 = sum2 + Math.abs(z);
sum3 = sum3 - 0.5 * x * y;
}
x = inpi * exp1(sum3) / u;
if (!mainx) {
x = x * (1.0 - exp1(-0.5 * tausq * square(u)));
}
sum1 = Math.sin(0.5 * sum1) * x;
sum2 = 0.5 * sum2 * x;
intl = intl.add(new BigDecimal(sum1));
ersm = ersm + sum2;
}
}
private double cfe(double x) /* coef of tausq in error when convergence factor of
exp1(-0.5*tausq*u^2) is used when df is evaluated at x */ {
double axl, axl1, axl2, sxl, sum1, lj;
int j, k, t;
//extern BOOL ndtsrt,fail; extern int *th,*n; extern double *lb,*nc;
//extern int r;
counter();
if (ndtsrt) {
order();
}
axl = Math.abs(x);
sxl = (x > 0.0) ? 1.0 : -1.0;
sum1 = 0.0;
for (j = r - 1; j >= 0; j--) {
t = th[j];
if (lb[t] * sxl > 0.0) {
lj = Math.abs(lb[t]);
axl1 = axl - lj * (n[t] + nc[t]);
axl2 = lj / log28;
if (axl1 > axl2) {
axl = axl1;
} else {
if (axl > axl2) {
axl = axl2;
}
sum1 = (axl - axl1) / lj;
for (k = j - 1; k >= 0; k--) {
sum1 = sum1 + (n[th[k]] + nc[th[k]]);
}
//goto l;
break;
}
}
}
//l:
if (sum1 > 100.0) {
fail = true;
return 1.0;
} else {
return Math.pow(2.0, (sum1 / 4.0)) / (Math.PI * square(axl));
}
}
private void qfc() /* distribution function of a linear combination of non-central
chi-squared random variables :
input:
lb[j] coefficient of j-th chi-squared variable
nc[j] non-centrality parameter
n[j] degrees of freedom
j = 0, 2 ... r-1
sigma coefficient of standard normal variable
c1 point at which df is to be evaluated
lim maximum number of terms in integration
acc maximum error
output:
ifault = 1 required accuracy NOT achieved
2 round-off error possibly significant
3 invalid parameters
4 unable to locate integration parameters
5 out of memory
trace[0] absolute sum
trace[1] total number of integration terms
trace[2] number of integrations
trace[3] integration interval in final integration
trace[4] truncation point in initial integration
trace[5] s.d. of initial convergence factor
trace[6] cycles to locate integration parameters */ {
int j, nj, nt, ntm;
double acc1, almx, xlim, xnt, xntm;
double tausq, sd, intv, intv1, x, d1, d2, lj, ncj;
double[] utx = new double[1];
double[] up = new double[1];
double[] un = new double[1];
//extern double sigsq, lmax, lmin, mean;
//extern double intl,ersm;
//extern int r,lim; extern double c;
//extern int *n,*th; extern double *lb,*nc;
//qfval = -1.0;
final int rats[] = {1, 2, 4, 8};
//if (setjmp(env) != 0) { *ifault=4; goto endofproc; }
r = lambda_.length;
lim = lim_;
c = q_;
n = h_;
lb = lambda_;
nc = delta_;
for (j = 0; j < 7; j++) {
trace[j] = 0.0;
}
ifault = 0;
count = 0;
intl = BigDecimal.ZERO;
ersm = 0.0;
//qfval = -1.0;
acc1 = acc_;
ndtsrt = true;
fail = false;
xlim = (double) lim;
th = new int[r]; //(int*)malloc(r*(sizeof(int)));
/* find mean, sd, max and min of lb,
check that parameter values are valid */
sigsq = square(sigma_);
sd = sigsq;
lmax = 0.0;
lmin = 0.0;
mean = 0.0;
for (j = 0; j < r; j++) {
nj = n[j];
lj = lb[j];
ncj = nc[j];
if (nj < 0 || ncj < 0.0) {
ifault = 3;
return;
} //goto endofproc; }
sd = sd + square(lj) * (2 * nj + 4.0 * ncj);
mean = mean + lj * (nj + ncj);
if (lmax < lj) {
lmax = lj;
} else if (lmin > lj) {
lmin = lj;
}
}
if (sd == 0.0) {
qfval = (c > 0.0) ? BigDecimal.ONE : BigDecimal.ZERO;
return;
} //goto endofproc; }
if (lmin == 0.0 && lmax == 0.0 && sigma_ == 0.0) {
ifault = 3;
return;
} //goto endofproc; }
sd = Math.sqrt(sd);
almx = (lmax < -lmin) ? -lmin : lmax;
/* starting values for findu, ctff */
utx[0] = 16.0 / sd;
up[0] = 4.5 / sd;
un[0] = -up[0];
/* truncation point with no convergence factor */
findu(utx, .5 * acc1);
/* does convergence factor help */
if (c != 0.0 && (almx > 0.07 * sd)) {
tausq = .25 * acc1 / cfe(c);
if (fail) {
fail = false;
} else if (truncation(utx[0], tausq) < .2 * acc1) {
sigsq = sigsq + tausq;
findu(utx, .25 * acc1);
trace[5] = Math.sqrt(tausq);
}
}
trace[4] = utx[0];
acc1 = 0.5 * acc1;
/* find RANGE of distribution, quit if outside this */
//l1:
while (true) {
d1 = ctff(acc1, up) - c;
if (d1 < 0.0) {
qfval = BigDecimal.ONE;
return;
}
d2 = c - ctff(acc1, un);
if (d2 < 0.0) {
qfval = BigDecimal.ONE;
return;
}
/* find integration interval */
intv = 2.0 * Math.PI / ((d1 > d2) ? d1 : d2);
/* calculate number of terms required for main and
auxillary integrations */
xnt = utx[0] / intv;
xntm = 3.0 / Math.sqrt(acc1);
if (!(xnt > xntm * 1.5)) {
break;
}
/* parameters for auxillary integration */
if (xntm > xlim) {
ifault = 1;
return;
}
ntm = (int) Math.floor(xntm + 0.5);
intv1 = utx[0] / ntm;
x = 2.0 * Math.PI / intv1;
if (x <= Math.abs(c)) {
break;
}
/* calculate convergence factor */
tausq = .33 * acc1 / (1.1 * (cfe(c - x) + cfe(c + x)));
if (fail) {
break;
}
acc1 = .67 * acc1;
/* auxillary integration */
integrate(ntm, intv1, tausq, false);
xlim = xlim - xntm;
sigsq = sigsq + tausq;
trace[2] = trace[2] + 1;
trace[1] = trace[1] + ntm + 1;
/* find truncation point with new convergence factor */
findu(utx, .25 * acc1);
acc1 = 0.75 * acc1;
//goto l1;
}
/* main integration */
// l2:
trace[3] = intv;
if (xnt > xlim) {
ifault = 1;
return;
}
nt = (int) Math.floor(xnt + 0.5);
integrate(nt, intv, 0.0, true);
trace[2] = trace[2] + 1;
trace[1] = trace[1] + nt + 1;
qfval = new BigDecimal(0.5).subtract(intl);
trace[0] = ersm;
/* test whether round-off error could be significant
allow for radix 8 or 16 machines */
up[0] = ersm;
x = up[0] + acc_ / 10.0;
for (j = 0; j < 4; j++) {
if (rats[j] * x == rats[j] * up[0]) {
ifault = 2;
}
}
//endofproc :
//trace[6] = (double)count;
//res[0] = qfval;
//return;
}
}
// #define UseDouble 0 /* all floating point double */
//
// #include <stdio.h>
// #include <stdlib.h>
// #include <math.h>
// #include <setjmp.h>
//
// #define TRUE 1
// #define FALSE 0
// typedef int BOOL;
//
//
// #define pi 3.14159265358979
// #define log28 .0866 /* log(2.0) / 8.0 */
//
// extern "C" {
//
// static double sigsq, lmax, lmin, mean, c;
// static double intl, ersm;
// static int count, r, lim; static BOOL ndtsrt, fail;
// static int *n,*th; static double *lb,*nc;
// static jmp_buf env;
//
//
//
// static double exp1(double x) /* to avoid underflows */
// { return x < -50.0 ? 0.0 : exp(x); }
//
// static void counter(void)
// /* count number of calls to errbd, truncation, cfe */
// {
// extern int count,lim;
// count = count + 1;
// if ( count > lim ) longjmp(env,1);
// }
//
// static double square(double x) { return x*x; }
//
// static double cube(double x) { return x*x*x; }
//
// static double log1(double x, BOOL first)
// /* if (first) log(1 + x) ; else log(1 + x) - x */
// {
// if (fabs(x) > 0.1)
// {
// return (first ? log(1.0 + x) : (log(1.0 + x) - x));
// }
// else
// {
// double s, s1, term, y, k;
// y = x / (2.0 + x); term = 2.0 * cube(y); k = 3.0;
// s = (first ? 2.0 : - x) * y;
// y = square(y);
// for (s1 = s + term / k; s1 != s; s1 = s + term / k)
// { k = k + 2.0; term = term * y; s = s1; }
// return s;
// }
// }
//
// static void order(void)
// /* find order of absolute values of lb */
// {
// int j, k; double lj;
// extern double *lb; extern int *th; extern int r; extern BOOL ndtsrt;
// for ( j=0; j<r; j++ )
// {
// lj = fabs(lb[j]);
// for (k = j-1; k>=0; k--)
// {
// if ( lj > fabs(lb[th[k]]) ) th[k + 1] = th[k];
// else goto l1;
// }
// k = -1;
// l1 :
// th[k + 1] = j;
// }
// ndtsrt = FALSE;
// }
//
//
// static double errbd(double u, double* cx)
// /* find bound on tail probability using mgf, cutoff
// point returned to *cx */
// {
// double sum1, lj, ncj, x, y, xconst; int j, nj;
// extern double sigsq,*lb,*nc; extern int *n; extern int r;
// counter();
// xconst = u * sigsq; sum1 = u * xconst; u = 2.0 * u;
// for (j=r-1; j>=0; j--)
// {
// nj = n[j]; lj = lb[j]; ncj = nc[j];
// x = u * lj; y = 1.0 - x;
// xconst = xconst + lj * (ncj / y + nj) / y;
// sum1 = sum1 + ncj * square(x / y)
// + nj * (square(x) / y + log1(-x, FALSE ));
// }
// *cx = xconst; return exp1(-0.5 * sum1);
// }
//
// static double ctff(double accx, double* upn)
// /* find ctff so that p(qf > ctff) < accx if (upn > 0,
// p(qf < ctff) < accx otherwise */
// {
// double u1, u2, u, rb, xconst, c1, c2;
// extern double lmin,lmax,mean;
// u2 = *upn; u1 = 0.0; c1 = mean;
// rb = 2.0 * ((u2 > 0.0) ? lmax : lmin);
// for (u = u2 / (1.0 + u2 * rb); errbd(u, &c2) > accx;
// u = u2 / (1.0 + u2 * rb))
// {
// u1 = u2; c1 = c2; u2 = 2.0 * u2;
// }
// for (u = (c1 - mean) / (c2 - mean); u < 0.9;
// u = (c1 - mean) / (c2 - mean))
// {
// u = (u1 + u2) / 2.0;
// if (errbd(u / (1.0 + u * rb), &xconst) > accx)
// { u1 = u; c1 = xconst; }
// else
// { u2 = u; c2 = xconst; }
// }
// *upn = u2; return c2;
// }
//
// static double truncation(double u, double tausq)
// /* bound integration error due to truncation at u */
// {
// double sum1, sum2, prod1, prod2, prod3, lj, ncj,
// x, y, err1, err2;
// int j, nj, s;
// extern double sigsq,*lb,*nc; extern int *n; extern int r;
//
// counter();
// sum1 = 0.0; prod2 = 0.0; prod3 = 0.0; s = 0;
// sum2 = (sigsq + tausq) * square(u); prod1 = 2.0 * sum2;
// u = 2.0 * u;
// for (j=0; j<r; j++ )
// {
// lj = lb[j]; ncj = nc[j]; nj = n[j];
// x = square(u * lj);
// sum1 = sum1 + ncj * x / (1.0 + x);
// if (x > 1.0)
// {
// prod2 = prod2 + nj * log(x);
// prod3 = prod3 + nj * log1(x, TRUE );
// s = s + nj;
// }
// else prod1 = prod1 + nj * log1(x, TRUE );
// }
// sum1 = 0.5 * sum1;
// prod2 = prod1 + prod2; prod3 = prod1 + prod3;
// x = exp1(-sum1 - 0.25 * prod2) / pi;
// y = exp1(-sum1 - 0.25 * prod3) / pi;
// err1 = ( s == 0 ) ? 1.0 : x * 2.0 / s;
// err2 = ( prod3 > 1.0 ) ? 2.5 * y : 1.0;
// if (err2 < err1) err1 = err2;
// x = 0.5 * sum2;
// err2 = ( x <= y ) ? 1.0 : y / x;
// return ( err1 < err2 ) ? err1 : err2;
// }
//
// static void findu(double* utx, double accx)
// /* find u such that truncation(u) < accx and truncation(u / 1.2) > accx */
// {
// double u, ut; int i;
// static double divis[]={2.0,1.4,1.2,1.1};
// ut = *utx; u = ut / 4.0;
// if ( truncation(u, 0.0) > accx )
// {
// for ( u = ut; truncation(u, 0.0) > accx; u = ut) ut = ut * 4.0;
// }
// else
// {
// ut = u;
// for ( u = u / 4.0; truncation(u, 0.0) <= accx; u = u / 4.0 )
// ut = u;
// }
// for ( i=0;i<4;i++)
// { u = ut/divis[i]; if ( truncation(u, 0.0) <= accx ) ut = u; }
// *utx = ut;
// }
//
//
// static void integrate(int nterm, double interv, double tausq, BOOL mainx)
// /* carry out integration with nterm terms, at stepsize
// interv. if (! mainx) multiply integrand by
// 1.0-exp(-0.5*tausq*u^2) */
// {
// double inpi, u, sum1, sum2, sum3, x, y, z;
// int k, j, nj;
// extern double intl,ersm; extern double sigsq,c;
// extern int *n; extern double *lb,*nc; extern int r;
// inpi = interv / pi;
// for ( k = nterm; k>=0; k--)
// {
// u = (k + 0.5) * interv;
// sum1 = - 2.0 * u * c; sum2 = fabs(sum1);
// sum3 = - 0.5 * sigsq * square(u);
// for ( j = r-1; j>=0; j--)
// {
// nj = n[j]; x = 2.0 * lb[j] * u; y = square(x);
// sum3 = sum3 - 0.25 * nj * log1(y, TRUE );
// y = nc[j] * x / (1.0 + y);
// z = nj * atan(x) + y;
// sum1 = sum1 + z; sum2 = sum2 + fabs(z);
// sum3 = sum3 - 0.5 * x * y;
// }
// x = inpi * exp1(sum3) / u;
// if ( ! mainx )
// x = x * (1.0 - exp1(-0.5 * tausq * square(u)));
// sum1 = sin(0.5 * sum1) * x; sum2 = 0.5 * sum2 * x;
// intl = intl + sum1; ersm = ersm + sum2;
// }
// }
//
// static double cfe(double x)
// /* coef of tausq in error when convergence factor of
// exp1(-0.5*tausq*u^2) is used when df is evaluated at x */
// {
// double axl, axl1, axl2, sxl, sum1, lj; int j, k, t;
// extern BOOL ndtsrt,fail; extern int *th,*n; extern double *lb,*nc;
// extern int r;
// counter();
// if (ndtsrt) order();
// axl = fabs(x); sxl = (x>0.0) ? 1.0 : -1.0; sum1 = 0.0;
// for ( j = r-1; j>=0; j-- )
// { t = th[j];
// if ( lb[t] * sxl > 0.0 )
// {
// lj = fabs(lb[t]);
// axl1 = axl - lj * (n[t] + nc[t]); axl2 = lj / log28;
// if ( axl1 > axl2 ) axl = axl1 ; else
// {
// if ( axl > axl2 ) axl = axl2;
// sum1 = (axl - axl1) / lj;
// for ( k = j-1; k>=0; k--)
// sum1 = sum1 + (n[th[k]] + nc[th[k]]);
// goto l;
// }
// }
// }
// l:
// if (sum1 > 100.0)
// { fail = TRUE; return 1.0; } else
// return pow(2.0,(sum1 / 4.0)) / (pi * square(axl));
// }
//
//
// void qfc(double* lb1, double* nc1, int* n1, int *r1, double *sigma, double *c1, int *lim1, double *acc, double* trace, int* ifault, double *res)
//
// /* distribution function of a linear combination of non-central
// chi-squared random variables :
//
// input:
// lb[j] coefficient of j-th chi-squared variable
// nc[j] non-centrality parameter
// n[j] degrees of freedom
// j = 0, 2 ... r-1
// sigma coefficient of standard normal variable
// c1 point at which df is to be evaluated
// lim maximum number of terms in integration
// acc maximum error
//
// output:
// ifault = 1 required accuracy NOT achieved
// 2 round-off error possibly significant
// 3 invalid parameters
// 4 unable to locate integration parameters
// 5 out of memory
//
// trace[0] absolute sum
// trace[1] total number of integration terms
// trace[2] number of integrations
// trace[3] integration interval in final integration
// trace[4] truncation point in initial integration
// trace[5] s.d. of initial convergence factor
// trace[6] cycles to locate integration parameters */
//
// {
// int j, nj, nt, ntm; double acc1, almx, xlim, xnt, xntm;
// double utx, tausq, sd, intv, intv1, x, up, un, d1, d2, lj, ncj;
// extern double sigsq, lmax, lmin, mean;
// extern double intl,ersm;
// extern int r,lim; extern double c;
// extern int *n,*th; extern double *lb,*nc;
// double qfval = -1.0;
// static int rats[]={1,2,4,8};
//
// if (setjmp(env) != 0) { *ifault=4; goto endofproc; }
// r=r1[0]; lim=lim1[0]; c=c1[0];
// n=n1; lb=lb1; nc=nc1;
// for ( j = 0; j<7; j++ ) trace[j] = 0.0;
// *ifault = 0; count = 0;
// intl = 0.0; ersm = 0.0;
// qfval = -1.0; acc1 = acc[0]; ndtsrt = TRUE; fail = FALSE;
// xlim = (double)lim;
// th=(int*)malloc(r*(sizeof(int)));
// if (! th) { *ifault=5; goto endofproc; }
//
// /* find mean, sd, max and min of lb,
// check that parameter values are valid */
// sigsq = square(sigma[0]); sd = sigsq;
// lmax = 0.0; lmin = 0.0; mean = 0.0;
// for (j=0; j<r; j++ )
// {
// nj = n[j]; lj = lb[j]; ncj = nc[j];
// if ( nj < 0 || ncj < 0.0 ) { *ifault = 3; goto endofproc; }
// sd = sd + square(lj) * (2 * nj + 4.0 * ncj);
// mean = mean + lj * (nj + ncj);
// if (lmax < lj) lmax = lj ; else if (lmin > lj) lmin = lj;
// }
// if ( sd == 0.0 )
// { qfval = (c > 0.0) ? 1.0 : 0.0; goto endofproc; }
// if ( lmin == 0.0 && lmax == 0.0 && sigma[0] == 0.0 )
// { *ifault = 3; goto endofproc; }
// sd = sqrt(sd);
// almx = (lmax < - lmin) ? - lmin : lmax;
//
// /* starting values for findu, ctff */
// utx = 16.0 / sd; up = 4.5 / sd; un = - up;
// /* truncation point with no convergence factor */
// findu(&utx, .5 * acc1);
// /* does convergence factor help */
// if (c != 0.0 && (almx > 0.07 * sd))
// {
// tausq = .25 * acc1 / cfe(c);
// if (fail) fail = FALSE ;
// else if (truncation(utx, tausq) < .2 * acc1)
// {
// sigsq = sigsq + tausq;
// findu(&utx, .25 * acc1);
// trace[5] = sqrt(tausq);
// }
// }
// trace[4] = utx; acc1 = 0.5 * acc1;
//
// /* find RANGE of distribution, quit if outside this */
// l1:
// d1 = ctff(acc1, &up) - c;
// if (d1 < 0.0) { qfval = 1.0; goto endofproc; }
// d2 = c - ctff(acc1, &un);
// if (d2 < 0.0) { qfval = 0.0; goto endofproc; }
// /* find integration interval */
// intv = 2.0 * pi / ((d1 > d2) ? d1 : d2);
// /* calculate number of terms required for main and
// auxillary integrations */
// xnt = utx / intv; xntm = 3.0 / sqrt(acc1);
// if (xnt > xntm * 1.5)
// {
// /* parameters for auxillary integration */
// if (xntm > xlim) { *ifault = 1; goto endofproc; }
// ntm = (int)floor(xntm+0.5);
// intv1 = utx / ntm; x = 2.0 * pi / intv1;
// if (x <= fabs(c)) goto l2;
// /* calculate convergence factor */
// tausq = .33 * acc1 / (1.1 * (cfe(c - x) + cfe(c + x)));
// if (fail) goto l2;
// acc1 = .67 * acc1;
// /* auxillary integration */
// integrate(ntm, intv1, tausq, FALSE );
// xlim = xlim - xntm; sigsq = sigsq + tausq;
// trace[2] = trace[2] + 1; trace[1] = trace[1] + ntm + 1;
// /* find truncation point with new convergence factor */
// findu(&utx, .25 * acc1); acc1 = 0.75 * acc1;
// goto l1;
// }
//
// /* main integration */
// l2:
// trace[3] = intv;
// if (xnt > xlim) { *ifault = 1; goto endofproc; }
// nt = (int)floor(xnt+0.5);
// integrate(nt, intv, 0.0, TRUE );
// trace[2] = trace[2] + 1; trace[1] = trace[1] + nt + 1;
// qfval = 0.5 - intl;
// trace[0] = ersm;
//
// /* test whether round-off error could be significant
// allow for radix 8 or 16 machines */
// up=ersm; x = up + acc[0] / 10.0;
// for (j=0;j<4;j++) { if (rats[j] * x == rats[j] * up) *ifault = 2; }
//
// endofproc :
// free((char*)th);
// trace[6] = (double)count;
// res[0] = qfval;
// return;
// }
//
//
// }
| Bonder-MJ/systemsgenetics | Downstreamer/src/main/java/ch/unil/genescore/vegas/DaviesBigDecimal.java |
179,794 | import javax.swing.*;
import java.util.List;
import java.util.Scanner;
public class Main {
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static void main(String[] args) {
JFrame frame = new JFrame("Vector Graphics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
Scene scene = new Scene();
scene.addItem(new Segment(new Point(100, 250), new Point(200, 200)));
scene.addItem(new Circle(new Point(300, 75), false, 50));
Triangle triangle = new Triangle(true, new Point(400, 420), new Point(510, 370), new Point(420, 300));
scene.addItem(triangle);
Triangle triangle2 = new Triangle(false, new Point(400, 420), new Point(510, 370), new Point(420, 300));
scene.addItem(triangle2);
ComplexItem complexItem = new ComplexItem(new Point(0, 0), List.of(
new Circle(new Point(0, 200), false, 100),
new Circle(new Point(10, 120), false, 80),
new Circle(new Point(20, 60), false, 60)
));
scene.addItem(complexItem);
complexItem.translate(new Point(600, 200));
TextItem textItem = new TextItem(new Point(200, 400), "Wesołych świąt xD");
scene.addItem(textItem);
// Add path to frame
Path path = new Path(new Point(0, 0), List.of(
new Point(500, 100),
new Point(550, 120),
new Point(500, 140),
new Point(550, 160),
new Point(500, 180),
new Point(550, 200),
new Point(500, 220),
new Point(550, 240)
));
scene.addItem(path);
frame.add(scene);
frame.setVisible(true);
while (true) {
Scanner scanner = new Scanner(System.in);
//Print list of items
System.out.println("List of items:");
for (int i = 0; i < scene.getItems().size(); i++) {
System.out.println(i + ". " + scene.getItems().get(i));
}
//Get item index
System.out.println("Enter item index:");
int itemIndex = scanner.nextInt();
//Get item
IItem item = scene.getItems().get(itemIndex);
//Remove item from the scene and replace it with a decorated version
scene.getItems().remove(itemIndex);
scene.addItem(new ItemDecorator(item));
//Repaint the scene
scene.repaint();
}
}
private static void drawBoundingBox(Scene scene, List<Point> boundingBox) {
int width = boundingBox.get(1).getX() - boundingBox.get(0).getX();
int height = boundingBox.get(2).getY() - boundingBox.get(1).getY();
scene.addItem(new Rect(boundingBox.get(0), false, width, height));
}
} | jakubik307/paradygmaty | Main.java |
179,796 | package org.application.pages;
import com.microsoft.playwright.Page;
public class HorseManager extends BasePage{
public HorseManager(Page page) {
super(page);
}
public Horse horseManager(String horseName){
HorseRoutine horse = new HorseRoutine(page);
switch(horseName){
case "Cutter":
horseCompetitionRoutine(".competition-cutting", horse);
break;
case "Galoper":
case "Achilles":
case "Wesołych Świąt":
horseCompetitionRoutine(".competition-galop", horse);
break;
case "Barrel":
horseCompetitionRoutine(".competition-barrel", horse);
break;
case "Reiner":
horseCompetitionRoutine(".competition-reining", horse);
break;
case "Trail":
horseCompetitionRoutine(".competition-trail-class", horse);
break;
case "Bieg":
case "Ulisses":
horseCompetitionRoutine(".competition-cross", horse);
break;
case "Skacz":
case "Atalanta":
horseCompetitionRoutine(".competition-saut", horse);
break;
case "Trot":
horseCompetitionRoutine(".competition-trot", horse);
break;
case "Tarpan":
horseCompetitionRoutine(".competition-western-pleasure", horse);
case "Mistrz":
horseGrandPrix(horse);
break;
default:
horseWorkRoutine(horse);
}
horse.nextHorse();
horse.logRoutine(horseName);
return horse;
}
protected void horseCompetitionRoutine(String selector, HorseRoutine horse) {
try {
horse.competitionRoutine(selector);
}
catch (Exception e) {
System.out.println("I can't compete");
horseWorkRoutine(horse);
}
}
protected void horseWorkRoutine(HorseRoutine horse) {
try{
horse.workRoutine();
}
catch (Exception x) {
System.out.println("I will try breed");
try {
horse
.giveBirth()
.workRoutine();
}
catch (Exception y) {
System.out.println("Is it baby");
try {
horse.foalCare();
}
catch (Exception z) {
System.out.println("Nothing is possible");
page.navigate(ImABotNotTest.getLastHorse());
}
}
}
}
protected void horseGrandPrix(HorseRoutine horse) {
try {
horse.goGrandPrix();
}
catch (Exception e) {
System.out.println("I can't GrandPrix");
}
horseWorkRoutine(horse);
}
}
| krasodomska/PlaywriteBot | src/main/java/org/application/pages/HorseManager.java |
179,797 | package Scene;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import Item.*;
import Point.Point;
import Shape.*;
import javax.swing.*;
import Segment.*;
import Decorator.*;
class CreateItemPanel extends JPanel implements ITriangleSingleton{
protected Scene scene;
public CreateItemPanel(Scene scene) {
super();
this.scene = scene;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(130, 0));
setBackground(Color.LIGHT_GRAY);
createButtons();
}
private Item getRandomSegment(Random random){
int x1 = random.nextInt(500);
int y1 = random.nextInt(500);
int x2 = random.nextInt(500);
int y2 = random.nextInt(500);
return new Segment(new Point(x1, y1), new Point(x2, y2));
}
private Item getRandomTriangle(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int x1 = x + random.nextInt(-100, 100);
int y1 = y + random.nextInt(-100, 100);
int x2 = x + random.nextInt(-100, 100);
int y2 = y + random.nextInt(-100, 100);
int x3 = x + random.nextInt(-100, 100);
int y3 = y + random.nextInt(-100, 100);
boolean filled = random.nextBoolean();
return createTriangleSingleton(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3), filled);
//return new Triangle(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3), filled); //old way
//return Triangle.getInstance(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3), filled); //normal way for singleton
}
@Override
public Triangle createTriangleSingleton(Point p1, Point p2, Point p3, boolean filled){
ArrayList<Item> items = scene.getItems();
for(int i = 0; i < items.size(); i++){
if(items.get(i) instanceof Triangle) {
items.remove(i);
i--;
}
}
return new Triangle(p1, p2, p3, filled);
}
private Item getRandomCircle(Random random){
int x = random.nextInt(500);
int y = random.nextInt(500);
int radius = random.nextInt(100);
boolean filled = random.nextBoolean();
return new Circle(new Point(Math.abs(x - radius), Math.abs(y - radius)), radius, filled);
}
private Item getRandomRect(Random random){
int x = random.nextInt(500);
int y = random.nextInt(500);
int width = random.nextInt(100);
int height = random.nextInt(100);
boolean filled = random.nextBoolean();
return new Rect(new Point(x, y), new Point(x + width, y + height), filled);
}
private Item getRandomStar(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int innerRadius = random.nextInt(40);
int outerRadius = random.nextInt(40);
int n = random.nextInt(5, 12);
boolean filled = random.nextBoolean();
return new Star(new Point(x, y), innerRadius, outerRadius, n, filled);
}
private Item getRandomText(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
String text = "Wesołych świąt xD";
return new TextItem(new Point(x, y), text);
}
private void createButtons() {
Random random = new Random();
add(new JLabel("Create Example Item:"));
JButton clearSceneButton = new JButton("Wyczyść Scenę");
clearSceneButton.addActionListener(e -> {scene.clearItems(); scene.draw();});
add(clearSceneButton);
//------ ZAD 3 MODYFIKACJA ------
//JCheckBox checkBox = new JCheckBox("Bounding Box");
//checkBox.addActionListener(e -> scene.toggleBoundingBoxVisible());
//add(checkBox);
JButton segmentButton = createSegmentButton(random);
JButton triangleButton = createTriangleButton(random);
JButton circleButton = createCircleButton(random);
JButton rectButton = createRectButton(random);
JButton starButton = createStarButton(random);
JButton textButton = createTextButton(random);
JButton complexButton = createComplexButton(random);
add(textButton);
add(segmentButton);
add(triangleButton);
add(circleButton);
add(rectButton);
add(starButton);
add(complexButton);
repaint();
revalidate();
}
private JButton createComplexButton(Random random) {
JButton complexButton = new JButton("Draw Complex");
complexButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int n = random.nextInt(2, 8);
ArrayList<Item> items = new ArrayList<Item>();
for(int i = 0; i < n; i++){
int j = random.nextInt(6);
switch (j){
case 0:
items.add(getRandomSegment(random));
break;
case 1:
items.add(getRandomTriangle(random));
break;
case 2:
items.add(getRandomCircle(random));
break;
case 3:
items.add(getRandomRect(random));
break;
case 4:
items.add(getRandomStar(random));
break;
case 5:
items.add(getRandomText(random));
break;
}
}
scene.addItem(new ComplexItem(new Point(x, y), items));
scene.draw();
System.out.println("Complex added, total items on Scene: " + scene.getItems().size());
});
return complexButton;
}
private JButton createSegmentButton(Random random) {
JButton segmentButton = new JButton("Draw Segment");
segmentButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomSegment(random));
scene.draw();
System.out.println("Segment added, total items on Scene: " + scene.getItems().size());
});
return segmentButton;
}
private JButton createTextButton(Random random) {
JButton textButton = new JButton("Draw Text");
textButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomText(random));
scene.draw();
System.out.println("Text added, total items on Scene: " + scene.getItems().size());
});
return textButton;
}
private JButton createCircleButton(Random random) {
JButton circleButton = new JButton("Draw Circle");
circleButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomCircle(random));
scene.draw();
System.out.println("Circle added, total items on Scene: " + scene.getItems().size());
});
return circleButton;
}
private JButton createTriangleButton(Random random) {
JButton triangleButton = new JButton("Draw Triangle");
triangleButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomTriangle(random));
scene.draw();
System.out.println("Triangle added, total items on Scene: " + scene.getItems().size());
});
return triangleButton;
}
private JButton createRectButton(Random random) {
JButton rectangleButton = new JButton("Draw Rectangle");
rectangleButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomRect(random));
scene.draw();
System.out.println("Rect added, total items on Scene: " + scene.getItems().size());
});
return rectangleButton;
}
private JButton createStarButton(Random random) {
JButton starButton = new JButton("Draw Star");
starButton.addActionListener(e -> {
if(scene.drawnItemListPanel.isEditPanelOpen) return;
scene.addItem(getRandomStar(random));
scene.draw();
System.out.println("Star added, total items on Scene: " + scene.getItems().size());
});
return starButton;
}
} | zawodev/PWR | sem3/PP-java/lab10java/src/Scene/CreateItemPanel.java |
179,799 | /**
* @author Świątek (klasa) + Chęciński (algorytm przesuwania)
*/
package wildpark.model;
import java.util.ArrayList;
import java.util.Random;
import wildpark.WildPark;
import wildpark.model.animals.Animal;
public class WildParkArea {
private static ArrayList<Animal> animalList = new ArrayList<>();
public static void addAnimal(Animal animal) {
animalList.add(animal);
}
// public static void moveAnimal( Animal animal, float speed ) {
// int currentX = animal.getWildParkAreaCell().getX();
// int currentY = animal.getWildParkAreaCell().getY();
// int angle, newX, newY;
// double radians;
// do {
// angle = animal.getDirection();
// System.out.printf( "WildParkArea moveAnimal(): ID %6d speed: %7.1f angle:
// %03d Original %s\r\n", animal.getId(), speed, angle,
// animal.getAnimalState().getWildParkAreaCell().toString() );
// radians = Math.toRadians(angle);
// newX = currentX + (int) Math.round( speed * Math.sin(radians) );
// newY = currentY + (int) Math.round( speed * Math.cos(radians) );
// System.out.println( "Target: " + newX + ":" + newY );
// } while( newX >= WildPark.WILD_PARK_AREA_WIDTH || newX < 0
// || newY >= WildPark.WILD_PARK_AREA_HEIGHT || newY < 0
// || !animal.acceptsCellType( WildPark.getWildParkAreaCell( newX, newY
// ).getCellType() ) );
// animal.move(newX,newY);
// }
public static ArrayList<Animal> getAnimals() {
return animalList;
}
public static WildParkAreaCell getRandomCell() {
return null;
}
/**
* Get a random WildParkAreaCell that meets the requirement of cellType
*
* @param cellTypes[]
* @return Acceptable WildParkAreaCell
* @author Xtry333
*/
public static WildParkAreaCell getRandomAcceptableCell(CellType[] cellTypes) {
WildParkAreaCell areaCell = null;
boolean isValid = false;
int x, y;
do {
x = new Random().nextInt(WildPark.WILD_PARK_AREA_WIDTH);
y = new Random().nextInt(WildPark.WILD_PARK_AREA_HEIGHT);
areaCell = WildPark.getWildParkAreaCell(x, y);
for (CellType type : cellTypes) {
if (areaCell.getCellType().equals(type)) {
isValid = true;
System.out.println( "Cell acceptable");
}
}
//if (acceptsCellType(areaCell.getCellType())) {
// isAcceptable = true;
//}
// System.out.println( "Random cell for " + SPECIES_NAME + " ----- cellType: " +
// areaCell.getCellType() + " --- " + isAcceptable );
} while (!isValid);
return areaCell;
}
}
| WSB-Java-1-2017/WildPark | src/wildpark/model/WildParkArea.java |
179,801 | import GameMechanisms.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
public class EnemyHandler {
private static Enemy currentEnemy;
private static ArrayList<Enemy> allEnemies;
public static void initEnemies() {
allEnemies = new ArrayList<>();
allEnemies.add(new Enemy(40,10,5,10,"Wściekły lis",20,"assets/enemies/angry_fox.png"));
allEnemies.add(new Enemy(50,20,5,30,"Świąteczne zombie",40,"assets/enemies/christmas_zombie.png"));
allEnemies.add(new Enemy(60,20,10,25,"Wilk",60,"assets/enemies/wolf.png"));
allEnemies.add(new Enemy(100,30,20,40,"Wampir",80,"assets/enemies/vampir.png"));
allEnemies.add(new Enemy(30,15,5,50,"Dziki wąż",30,"assets/enemies/snake.png"));
}
public static Enemy pickEnemy() {
// ArrayList<Enemy> allEnemies = new ArrayList<>();
// allEnemies.add(new Enemy(50,10,10,0.10,"Wściekły lis",15,"assets/enemies/angry_fox.png"));
if (!HeroHandler.getHero().isEscapeSuccess())
return getCurrentEnemy();
ArrayList<Enemy> availableEnemies = getAvailableEnemies();
currentEnemy = availableEnemies.get(new Random().nextInt(0, availableEnemies.size()));
return getCurrentEnemy();
}
public static ArrayList<Enemy> getAvailableEnemies() {
return (ArrayList<Enemy>) allEnemies.stream().filter(enemy->!enemy.isDefeated()).collect(Collectors.toList());
}
public static boolean attackHero() {
Hero hero = HeroHandler.getHero();
boolean isCrit = getCurrentEnemy().getCritChance()/100>Math.random();
int defendValue = hero.getDefendPoints();
int damageValue = Math.max(getCurrentEnemy().getAttackPoints()-defendValue,5);
if (isCrit) damageValue *= 1.5;
if (hero.isGuarded()) {
damageValue = 0;
hero.setGuarded(false);
}
if (getCurrentEnemy().getHealthPoints()>0) {
hero.getHit(damageValue);
return true;
} else return false;
}
public static Enemy getCurrentEnemy() {
return currentEnemy;
}
}
| skoorupa/java_GUI_game_studies | src/EnemyHandler.java |
179,805 | package com.softarea.mpktarnow.utils;
import androidx.fragment.app.FragmentActivity;
import com.softarea.mpktarnow.R;
import java.util.Calendar;
public class TimeUtils {
public static String min2HHMM(int n) {
int t = n / 60;
int i = n - t * 60;
return (t < 10 ? " " + t : t) + ":" + (i < 10 ? "0" + i : i);
}
public static String sec2HHMM(int n) {
n = n % 86400;
int i = Integer.parseInt(String.valueOf(n / 3600));
int t = Integer.parseInt(String.valueOf(n % 3600 / 60));
return i + ":" + (t < 10 ? "0" + t : t);
}
public static String calcDelayInfo(FragmentActivity activity, int value) {
if (value < 0) {
return activity.getString(R.string.current_acceleration);
} else {
return activity.getString(R.string.current_delay);
}
}
public static String calcDelayValue(int value) {
value = MathUtils.makePositive(value);
if (value / 60 < 1) {
return " < 1 min";
} else if (value / 60 >= 60) {
int hours = (int) value / 3600;
int minutes = (int) (value - hours * 3600) / 60;
return " " + hours + " h " + minutes + " min";
} else {
return " " + (int) (value / 60) + " min";
}
}
public static String getCurrentTime() {
Calendar rightNow = Calendar.getInstance();
return StringUtils.join(makeZero(rightNow.get(Calendar.HOUR_OF_DAY)), ":", makeZero(rightNow.get(Calendar.MINUTE)));
}
public static int getCurrentTimeInMin() {
Calendar rightNow = Calendar.getInstance();
return rightNow.get(Calendar.HOUR_OF_DAY) * 60 + rightNow.get(Calendar.MINUTE);
}
public static String getCurrentDate() {
// yyyy-mm-dd
Calendar rightNow = Calendar.getInstance();
return StringUtils.join(makeZero(rightNow.get(Calendar.YEAR)), "-", makeZero(rightNow.get(Calendar.MONTH)), "-", makeZero(rightNow.get(Calendar.DAY_OF_MONTH)));
}
public static String makeZero(int content) {
String text = String.valueOf(content);
if (text.length() == 1) {
return StringUtils.join("0", text);
}
return text;
}
public static String translateDayShortcutToDayName( String shortcut ) {
switch (shortcut) {
case "RO":
return "DNI ROBOCZE";
case "WS":
return "SOBOTY";
case "SW":
return "DNI ŚWIĄTECZNE";
default:
return "INNE";
}
}
}
| dpajak99/tarbus-poc | app/src/main/java/com/softarea/mpktarnow/utils/TimeUtils.java |
179,807 | package homeworks.homework2.point2;
import java.util.Random;
/**
* Napisz program wyświetlający świąteczną choinkę
* składającą się z losowych elementów następującego zbioru znaków ASCII: ‘+', ‘.', ‘*', ‘~', ‘^', ‘o'.
* Wysokość choinki powinna być podawana jako argument programu.
* Jeżeli wysokość nie zostanie określona to powinna zostać przyjęta domyślna wartość 18.
*/
public class ChristmasTree {
private int height = 18;
private char[] signs = {'+', '.', '*', '~', '^', 'o'};
public ChristmasTree(int height) {
this.height = height;
}
public static void main(String[] args) {
ChristmasTree christmasTree = new ChristmasTree(args.length > 0 ? Integer.parseInt(args[0]) : 18);
christmasTree.display();
}
private void display() {
Random random = new Random();
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.height - i; j++) {
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++) {
System.out.print(this.signs[random.nextInt(6)]);
}
for (int j = 0; j < this.height - i; j++) {
System.out.print(" ");
}
System.out.println();
}
}
}
| rafalsamek/jwd | src/homeworks/homework2/point2/ChristmasTree.java |
179,818 | /**
* @author Świątek (klasa) + Chęciński (algorytm przesuwania)
*/
package wildpark.model;
import wildpark.*;
import wildpark.model.animals.*;
import wildpark.model.*;
import java.util.*;
public class WildParkArea {
private static ArrayList<Animal> animalList = new ArrayList<>();
public static void addAnimal( Animal animal ) {
animalList.add( animal );
}
public static void moveAnimal( Animal animal ) {
float speed = animal.getStandardSpeed();
double angle = animal.getDirection();
double radians = Math.toRadians(angle);
int x = (int) Math.round(speed * Math.sin(radians));
int y = (int) Math.round(speed * Math.cos(radians));
int currentX = animal.getWildParkAreaCell().getX();
int currentY = animal.getWildParkAreaCell().getY();
// update
if(currentX > WildPark.WILD_PARK_AREA_WIDTH || currentX < 0
|| currentY > WildPark.WILD_PARK_AREA_HEIGHT || currentY < 0) {
angle -= 180.0;
radians = Math.toRadians(angle);
x = (int) Math.round( speed * Math.sin(radians) );
y = (int) Math.round( speed * Math.cos(radians) );
}
animal.move(x,y);
//
}
public static ArrayList<Animal> getAnimals() {
return animalList;
}
}
| Lukasmar/WildPark | src/wildpark/model/WildParkArea.java |
179,823 | package pl.programowaniezespolowe.planner.controllers;
import io.swagger.models.auth.In;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pl.programowaniezespolowe.planner.dtos.CalendarEventDto;
import pl.programowaniezespolowe.planner.dtos.EventDto;
import pl.programowaniezespolowe.planner.event.Event;
import pl.programowaniezespolowe.planner.event.EventRepository;
import pl.programowaniezespolowe.planner.note.Note;
import pl.programowaniezespolowe.planner.note.NoteRepository;
import pl.programowaniezespolowe.planner.user.User;
import pl.programowaniezespolowe.planner.user.UserRepository;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
@RestController
public class EventController {
@Autowired
EventRepository eventRepository;
@Autowired
NoteRepository noteRepository;
@Autowired
UserRepository userRepository;
public boolean checkIsUserLogged(String userid) {
List<User> users = userRepository.findAll();
for(User u : users) {
if(u.getId().toString().equals(userid)) {
if (u.isLogged()) {
return true;
}
}
}
return false;
}
@CrossOrigin
@GetMapping(path = "/{userid}/events")
public List<EventDto> getEvents(@PathVariable String userid) {
boolean canReturn = checkIsUserLogged(userid);
List<EventDto> userEvents = new ArrayList<>();
for(EventDto e : getAllEvents()) {
if(e.getUserID().toString().equals(userid)) {
userEvents.add(e);
}
}
System.out.println(canReturn);
if(canReturn) {
return userEvents;
}
return null;
}
@CrossOrigin
@GetMapping(path = "/{userid}/event/{id}")
public Optional<Event> getEvent(@PathVariable String userid, @PathVariable String id) {
boolean canReturn = checkIsUserLogged(userid);
int eventId = Integer.parseInt(id);
if(canReturn) return eventRepository.findById(eventId);
else return null;
}
@CrossOrigin
@PostMapping("/{userid}/event")
public List<EventDto> createEvent(@PathVariable String userid, @RequestBody EventDto event) {
boolean canReturn = checkIsUserLogged(userid);
System.out.println(event);
List<EventDto> userEvents = new ArrayList<>();
for(EventDto e : getAllEvents()) {
if(e.getUserID().toString().equals(userid)) {
userEvents.add(e);
}
}
if(canReturn) {
eventRepository.save(new Event(Integer.valueOf(userid), event.getCalendarEvent().getTitle(), Date.from(event.getCalendarEvent().getStart()), Date.from(event.getCalendarEvent().getEnd())));
return userEvents;
}
else return null;
}
@CrossOrigin
@PutMapping("/{userid}/event/{eventId}")
public ResponseEntity<?> updateEvent(@PathVariable String userid, @RequestBody EventDto event, @PathVariable Integer eventId) {
boolean canReturn = checkIsUserLogged(userid);
Optional<Event> updateEvent = eventRepository.findById(eventId);
if(updateEvent.isPresent()) {
updateEvent.get().setStart(Date.from(event.getCalendarEvent().getStart()));
updateEvent.get().setEnd(Date.from(event.getCalendarEvent().getEnd()));
updateEvent.get().setTitle(String.valueOf(event.getCalendarEvent().getTitle()));
updateEvent.get().setUserID(Integer.valueOf(userid));
eventRepository.save(updateEvent.get());
if(canReturn) return new ResponseEntity<>(HttpStatus.OK);
else return null;
}
else{
if(canReturn) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
else return null;
}
}
@CrossOrigin
@DeleteMapping("/{userid}/event/{id}")
public List<EventDto> deleteEvent(@PathVariable String userid, @PathVariable String id) {
boolean canReturn = checkIsUserLogged(userid);
List<EventDto> userEvents = new ArrayList<>();
for(EventDto e : getAllEvents()) {
if(e.getUserID().toString().equals(userid)) {
userEvents.add(e);
}
}
int eventId = Integer.parseInt(id);
List<Note> notes = noteRepository.findAll();
List<Note> notesEventId = new ArrayList<Note>();
for(Note n : notes) {
if(n.getEventid() == eventId) {
notesEventId.add(n);
}
}
for(Note n : notesEventId) {
if(canReturn) noteRepository.delete(n);
}
eventRepository.deleteById(eventId);
if(canReturn) return userEvents;
else return null;
}
public List<EventDto> getAllEvents() {
List<Event> events = eventRepository.findAll();
ArrayList<EventDto> mapedEvents = new ArrayList<>();
for (Event event : events) {
if(event.getStart() != null)
mapedEvents.add(new EventDto(new CalendarEventDto(event.getId(), event.getTitle(), Instant.ofEpochMilli(event.getStart().getTime()), Instant.ofEpochMilli(event.getEnd().getTime())), event.getUserID()));
}
return mapedEvents;
}
@CrossOrigin
@PostMapping("/{userid}/getTermEvents")
public List<EventDto> getEventsFromPage(@PathVariable String userid) {
// List<Event> events = eventRepository.findAll();
// ArrayList<EventDto> mapedEvents = new ArrayList<>();
// for (Event event : events) {
// if(event.getStart() != null)
// mapedEvents.add(new EventDto(new CalendarEventDto(event.getId(), event.getTitle(), Instant.ofEpochMilli(event.getStart().getTime()), Instant.ofEpochMilli(event.getEnd().getTime())), event.getUserID()));
// }
URL url;
String inputLine = "";
String html = "";
try {
// get URL content
String a="https://www.p.lodz.pl/pl/rozklad-roku-akademickiego-202021";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((inputLine = br.readLine()) != null) {
html += inputLine;
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String startWinter = "";
String endWinter = "";
String startLessonWinter = "";
String endLessonWinter = "";
String christmasBreakStart = "";
String christmasBreakEnd = "";
String winterSessionPartOneStart = "";
String winterSessionPartOneEnd = "";
String winterSessionPartTwoStart = "";
String winterSessionPartTwoEnd = "";
String winterHolidayStart = "";
String winterHolidayEnd = "";
String winterExtraDaysStart = "";
String winterExtraDaysEnd = "";
String startSummer = "";
String endSummer = "";
String startLessonSummer = "";
String endLessonSummer = "";
String springBreakStart = "";
String springBreakEnd = "";
String summerSessionPartOneStart = "";
String summerSessionPartOneEnd = "";
String summerSessionPartTwoStart = "";
String summerSessionPartTwoEnd = "";
String summerHolidayStart = "";
String summerHolidayEnd = "";
String summerExtraDaysStart = "";
String summerExtraDaysEnd = "";
if(html != null)
{
Document doc = Jsoup.parse(html);
Element text = doc.select("div.text").first();
System.out.println(text.toString());
String [] lines = text.toString().split("\n");
for(int i = 0; i < lines.length; i++) {
//WINTER
//Get start and end of term winter
if(lines[i].contains("Semestr zimowy")) {
startWinter = lines[i];
endWinter = lines[i];
}
//Get start and end lessons
else if(lines[i].contains("Okres zajęć")) {
startLessonWinter = lines[i];
endLessonWinter = lines[i];
}
//Get start and end lessons
else if(lines[i].contains("Przerwa świąteczna")) {
christmasBreakStart = lines[i];
christmasBreakEnd = lines[i];
}
else if(lines[i].contains("Zimowa sesja egzaminacyjna:")) {
winterSessionPartOneStart = lines[i + 1];
winterSessionPartOneEnd = lines[i + 1];
winterSessionPartTwoStart = lines[i + 2];
winterSessionPartTwoEnd = lines[i + 2];
}
else if(lines[i].contains("Wakacje zimowe")) {
winterHolidayStart = lines[i + 1];
winterHolidayEnd = lines[i + 1];
}
else if(lines[i].contains("Dodatkowe dni wolne od zajęć:")) {
winterExtraDaysStart = lines[i + 1];
winterExtraDaysEnd = lines[i + 1];
}
//SUMMER
//Get start and end of term winter
if(lines[i].contains("Semestr letni")) {
startSummer = lines[i];
endSummer = lines[i];
}
else if(lines[i].contains("Okres zajęć:")) {
startLessonSummer = lines[i];
endLessonSummer = lines[i];
}
else if(lines[i].contains("Ferie wiosenne")) {
springBreakStart = lines[i];
springBreakEnd = lines[i];
}
else if(lines[i].contains("Letnia sesja egzaminacyjna:")) {
summerSessionPartOneStart = lines[i + 1];
summerSessionPartOneEnd = lines[i + 1];
summerSessionPartTwoStart = lines[i + 2];
summerSessionPartTwoEnd = lines[i + 2];
}
else if(lines[i].contains("Wakacje letnie")) {
summerHolidayStart = lines[i + 1];
summerHolidayEnd = lines[i + 1];
}
}
}
try {
//Get dates of events for WINTER
System.out.println("Obrobione wydarzenia");
startWinter = startWinter.split("–")[0].substring(41, startWinter.split("–")[0].length() - 4);
EventDto eventDto1 = createEventFromTime(startWinter, startWinter, "Poczatek semestru zimowego");
endWinter = endWinter.split("–")[1].substring(1, endWinter.split("–")[1].length() - 9);
EventDto eventDto2 = createEventFromTime(endWinter, endWinter, "Koniec semestru zimowego");
startLessonWinter = startLessonWinter.split("–")[0].substring(34, startLessonWinter.split("–")[0].length() - 4);
EventDto eventDto3 = createEventFromTime(startLessonWinter, startLessonWinter, "Poczatek zajec semestru zimowego");
endLessonWinter = endLessonWinter.split("–")[1].substring(1, endLessonWinter.split("–")[1].length() - 7);
EventDto eventDto4 = createEventFromTime(endLessonWinter, endLessonWinter, "Koniec zajec semestru zimowego");
christmasBreakStart = christmasBreakStart.split("–")[0].substring(41, christmasBreakStart.split("–")[0].length() - 4);
christmasBreakEnd = christmasBreakEnd.split("–")[1].substring(1, christmasBreakEnd.split("–")[1].length() - 7);
EventDto eventDto5 = createEventFromTime(christmasBreakStart, christmasBreakEnd, "Przerwa swiateczna swieta Bozego Narodzenia");
winterSessionPartOneStart = winterSessionPartOneStart.split("–")[0].substring(4, winterSessionPartOneStart.split("–")[0].length() - 4);
winterSessionPartOneEnd = winterSessionPartOneEnd.split("–")[1].substring(1, winterSessionPartOneEnd.split("–")[1].length() - 7);
EventDto eventDto6 = createEventFromTime(winterSessionPartOneStart, winterSessionPartOneEnd, "Sesja zimowa");
winterSessionPartTwoStart = winterSessionPartTwoStart.split("–")[0].substring(4, winterSessionPartTwoStart.split("–")[0].length() - 4);
winterSessionPartTwoEnd = winterSessionPartTwoEnd.split("–")[1].substring(1, winterSessionPartTwoEnd.split("–")[1].length() - 7);
EventDto eventDto7 = createEventFromTime(winterSessionPartTwoStart, winterSessionPartTwoEnd, "Sesja zimowa");
winterHolidayStart = winterHolidayStart.split("–")[0].substring(4, winterHolidayStart.split("–")[0].length() - 4);
winterHolidayEnd = winterHolidayEnd.split("–")[1].substring(1, winterHolidayEnd.split("–")[1].length() - 7);
EventDto eventDto8 = createEventFromTime(winterHolidayStart, winterHolidayEnd, "Wakacje zimowe");
winterExtraDaysStart = winterExtraDaysStart.split("do")[0].substring(7, winterExtraDaysStart.split("do")[0].length() - 4);
winterExtraDaysEnd = winterExtraDaysEnd.split("do")[1].substring(1, winterExtraDaysEnd.split("do")[1].length() - 7);
EventDto eventDto9 = createEventFromTime(winterExtraDaysStart, winterExtraDaysEnd, "Dodatkowy dzien wolny od zajec");
eventRepository.save(new Event(Integer.valueOf(userid), eventDto1.getCalendarEvent().getTitle(), Date.from(eventDto1.getCalendarEvent().getStart()), Date.from(eventDto1.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto2.getCalendarEvent().getTitle(), Date.from(eventDto2.getCalendarEvent().getStart()), Date.from(eventDto2.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto3.getCalendarEvent().getTitle(), Date.from(eventDto3.getCalendarEvent().getStart()), Date.from(eventDto3.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto4.getCalendarEvent().getTitle(), Date.from(eventDto4.getCalendarEvent().getStart()), Date.from(eventDto4.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto5.getCalendarEvent().getTitle(), Date.from(eventDto5.getCalendarEvent().getStart()), Date.from(eventDto5.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto6.getCalendarEvent().getTitle(), Date.from(eventDto6.getCalendarEvent().getStart()), Date.from(eventDto6.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto7.getCalendarEvent().getTitle(), Date.from(eventDto7.getCalendarEvent().getStart()), Date.from(eventDto7.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto8.getCalendarEvent().getTitle(), Date.from(eventDto8.getCalendarEvent().getStart()), Date.from(eventDto8.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto9.getCalendarEvent().getTitle(), Date.from(eventDto9.getCalendarEvent().getStart()), Date.from(eventDto9.getCalendarEvent().getEnd())));
//Get dates of events for SUMMER
startSummer = startSummer.split("–")[0].substring(40, startSummer.split("–")[0].length() - 4);
EventDto eventDto10 = createEventFromTime(startSummer, startSummer, "Poczatek semestru letniego");
endSummer = endSummer.split("–")[1].substring(1, endSummer.split("–")[1].length() - 9);
EventDto eventDto11 = createEventFromTime(endSummer, endSummer, "Koniec semestru letniego");
startLessonSummer = startLessonSummer.split("–")[0].substring(34, startLessonSummer.split("–")[0].length() - 4);
EventDto eventDto12 = createEventFromTime(startLessonSummer, startLessonSummer, "Poczatek zajec semestru letniego");
endLessonSummer = endLessonSummer.split("–")[1].substring(1, endLessonSummer.split("–")[1].length() - 7);
EventDto eventDto13 = createEventFromTime(endLessonSummer, endLessonSummer, "Koniec zajec semestru letniego");
springBreakStart = springBreakStart.split("–")[0].substring(37, springBreakStart.split("–")[0].length() - 4);
springBreakEnd = springBreakEnd.split("–")[1].substring(1, springBreakEnd.split("–")[1].length() - 7);
EventDto eventDto14 = createEventFromTime(springBreakStart, springBreakEnd, "Przerwa swiateczna swieta Wielkanocne");
summerSessionPartOneStart = summerSessionPartOneStart.split("–")[0].substring(4, summerSessionPartOneStart.split("–")[0].length() - 4);
summerSessionPartOneEnd = summerSessionPartOneEnd.split("–")[1].substring(1, summerSessionPartOneEnd.split("–")[1].length() - 7);
EventDto eventDto15 = createEventFromTime(summerSessionPartOneStart, summerSessionPartOneEnd, "Sesja letnia");
summerSessionPartTwoStart = summerSessionPartTwoStart.split("–")[0].substring(4, summerSessionPartTwoStart.split("–")[0].length() - 4);
summerSessionPartTwoEnd = summerSessionPartTwoEnd.split("–")[1].substring(1, summerSessionPartTwoEnd.split("–")[1].length() - 7);
EventDto eventDto16 = createEventFromTime(summerSessionPartTwoStart, summerSessionPartTwoEnd, "Sesja letnia");
summerHolidayStart = summerHolidayStart.split("–")[0].substring(4, summerHolidayStart.split("–")[0].length() - 4);
summerHolidayEnd = summerHolidayEnd.split("–")[1].substring(1, summerHolidayEnd.split("–")[1].length() - 7);
EventDto eventDto17 = createEventFromTime(summerHolidayStart, summerHolidayEnd, "Wakacje letnie");
// System.out.println(eventDto10);
// System.out.println(eventDto11);
// System.out.println(eventDto12);
// System.out.println(eventDto13);
// System.out.println(eventDto14);
// System.out.println(eventDto15);
// System.out.println(eventDto16);
// System.out.println(eventDto17);
eventRepository.save(new Event(Integer.valueOf(userid), eventDto10.getCalendarEvent().getTitle(), Date.from(eventDto10.getCalendarEvent().getStart()), Date.from(eventDto10.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto11.getCalendarEvent().getTitle(), Date.from(eventDto11.getCalendarEvent().getStart()), Date.from(eventDto11.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto12.getCalendarEvent().getTitle(), Date.from(eventDto12.getCalendarEvent().getStart()), Date.from(eventDto12.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto13.getCalendarEvent().getTitle(), Date.from(eventDto13.getCalendarEvent().getStart()), Date.from(eventDto13.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto14.getCalendarEvent().getTitle(), Date.from(eventDto14.getCalendarEvent().getStart()), Date.from(eventDto14.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto15.getCalendarEvent().getTitle(), Date.from(eventDto15.getCalendarEvent().getStart()), Date.from(eventDto15.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto16.getCalendarEvent().getTitle(), Date.from(eventDto16.getCalendarEvent().getStart()), Date.from(eventDto16.getCalendarEvent().getEnd())));
eventRepository.save(new Event(Integer.valueOf(userid), eventDto17.getCalendarEvent().getTitle(), Date.from(eventDto17.getCalendarEvent().getStart()), Date.from(eventDto17.getCalendarEvent().getEnd())));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
// System.out.println(eventDto1);
// System.out.println(eventDto2);
// System.out.println(eventDto3);
// System.out.println(eventDto4);
// System.out.println(eventDto5);
// System.out.println(eventDto6);
// System.out.println(eventDto7);
// System.out.println(eventDto8);
// System.out.println(eventDto9);
List<EventDto> userEvents = new ArrayList<>();
for(EventDto e : getAllEvents()) {
if(e.getUserID().toString().equals(userid)) {
userEvents.add(e);
}
}
return userEvents;
}
@CrossOrigin
@DeleteMapping("/{userid}/deleteTermEvents")
public List<EventDto> deleteEventsFromPage(@PathVariable String userid) {
List<Event> events = eventRepository.findAll();
ArrayList<EventDto> mapedEvents = new ArrayList<>();
for (Event event : events) {
if(event.getStart() != null)
mapedEvents.add(new EventDto(new CalendarEventDto(event.getId(), event.getTitle(), Instant.ofEpochMilli(event.getStart().getTime()), Instant.ofEpochMilli(event.getEnd().getTime())), event.getUserID()));
}
for( EventDto event : mapedEvents) {
if(event.getCalendarEvent().getTitle().equals("Poczatek semestru zimowego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Koniec semestru zimowego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Poczatek zajec semestru zimowego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Koniec zajec semestru zimowego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Przerwa swiateczna swieta Bozego Narodzenia") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Sesja zimowa") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Dodatkowy dzien wolny od zajec") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Wakacje zimowe") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Poczatek semestru letniego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Koniec semestru letniego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Poczatek zajec semestru letniego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Koniec zajec semestru letniego") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Przerwa swiateczna swieta Wielkanocne") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Sesja letnia") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
else if(event.getCalendarEvent().getTitle().equals("Wakacje letnie") && event.getUserID().equals(Integer.valueOf(userid))) {
eventRepository.deleteById(event.getCalendarEvent().getId());
}
}
List<EventDto> userEvents = new ArrayList<>();
for(EventDto e : getAllEvents()) {
if(e.getUserID().toString().equals(Integer.valueOf(userid))) {
userEvents.add(e);
}
}
//System.out.println(userEvents);
return userEvents;
}
public EventDto createEventFromTime(String start, String end, String name) {
CalendarEventDto event = new CalendarEventDto();
event.setTitle(name);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String timestamp = start;
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
LocalDate localDateTime = LocalDate.from(temporalAccessor);
Instant result = localDateTime.atStartOfDay(ZoneId.systemDefault()).toInstant();
String timestamp1 = end;
TemporalAccessor temporalAccessor1 = formatter.parse(timestamp1);
LocalDate localDateTime1 = LocalDate.from(temporalAccessor1);
Instant result1 = localDateTime1.atStartOfDay(ZoneId.systemDefault()).toInstant();
event.setStart(result);
event.setEnd(result1);
EventDto eventDto = new EventDto();
eventDto.setCalendarEvent(event);
return eventDto;
}
}
| 7GitHub7/planner_backend | src/main/java/pl/programowaniezespolowe/planner/controllers/EventController.java |
179,854 | package homeworks.homework2.point2;
import java.util.Random;
/**
* Napisz program wyświetlający świąteczną choinkę składającą się z losowych elementów
* następującego zbioru znaków ASCII: '+’, '.’, '*’, '~’, '^’, 'o’.
* Wysokość choinki powinna być podawana jako argument programu. Jeżeli wysokość nie
* zostanie określona to powinna zostać przyjęta domyślna wartość 18.
* Przykład:
* <p>
* _ChristmasTree
*/
public class ChristmasTree {
public static void main(String[] args) {
Random random = new Random();
int length = args.length >= 1 ? Integer.parseInt(args[0]): 18;
char blankSpace = ' ';
char[] chars = {'+', '.', '*', '~', '^', 'o'};
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - 1 - i; j++) {
System.out.print(blankSpace);
}
for (int k = 0; k < i * 2 - 1; k++) {
int x = random.nextInt(6);
System.out.print(chars[x]);
}
System.out.println();
}
}
} | ewaslota/jwd | src/homeworks/homework2/point2/ChristmasTree.java |
179,863 | package Scene;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import Item.*;
import Point.Point;
import Shape.*;
import javax.swing.*;
import Segment.*;
class CreateItemPanel extends JPanel {
protected Scene scene;
public CreateItemPanel(Scene scene) {
super();
this.scene = scene;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(130, 0));
setBackground(Color.LIGHT_GRAY);
createButtons();
}
private Item getRandomSegment(Random random){
int x1 = random.nextInt(500);
int y1 = random.nextInt(500);
int x2 = random.nextInt(500);
int y2 = random.nextInt(500);
return new Segment(new Point(x1, y1), new Point(x2, y2));
}
private Item getRandomTriangle(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int x1 = x + random.nextInt(-100, 100);
int y1 = y + random.nextInt(-100, 100);
int x2 = x + random.nextInt(-100, 100);
int y2 = y + random.nextInt(-100, 100);
int x3 = x + random.nextInt(-100, 100);
int y3 = y + random.nextInt(-100, 100);
boolean filled = random.nextBoolean();
return new Triangle(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3), filled);
}
private Item getRandomCircle(Random random){
int x = random.nextInt(500);
int y = random.nextInt(500);
int radius = random.nextInt(100);
boolean filled = random.nextBoolean();
return new Circle(new Point(Math.abs(x - radius), Math.abs(y - radius)), radius, filled);
}
private Item getRandomRect(Random random){
int x = random.nextInt(500);
int y = random.nextInt(500);
int width = random.nextInt(100);
int height = random.nextInt(100);
boolean filled = random.nextBoolean();
return new Rect(new Point(x, y), new Point(x + width, y + height), filled);
}
private Item getRandomStar(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int innerRadius = random.nextInt(40);
int outerRadius = random.nextInt(40);
int n = random.nextInt(5, 12);
boolean filled = random.nextBoolean();
return new Star(new Point(x, y), innerRadius, outerRadius, n, filled);
}
private Item getRandomText(Random random){
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
String text = "Wesołych świąt xD";
return new TextItem(new Point(x, y), text);
}
private void createButtons() {
Random random = new Random();
add(new JLabel("Create Example Item:"));
JButton clearSceneButton = new JButton("Wyczyść Scenę");
clearSceneButton.addActionListener(e -> {scene.clearItems(); scene.draw();});
add(clearSceneButton);
JCheckBox checkBox = new JCheckBox("Bounding Box");
checkBox.addActionListener(e -> scene.toggleBoundingBoxVisible());
add(checkBox);
JButton segmentButton = createSegmentButton(random);
JButton triangleButton = createTriangleButton(random);
JButton circleButton = createCircleButton(random);
JButton rectButton = createRectButton(random);
JButton starButton = createStarButton(random);
JButton textButton = createTextButton(random);
JButton complexButton = createComplexButton(random);
add(textButton);
add(segmentButton);
add(triangleButton);
add(circleButton);
add(rectButton);
add(starButton);
add(complexButton);
repaint();
revalidate();
}
private JButton createComplexButton(Random random) {
JButton complexButton = new JButton("Draw Complex");
complexButton.addActionListener(e -> {
int x = random.nextInt(100, 400);
int y = random.nextInt(100, 400);
int n = random.nextInt(2, 8);
ArrayList<Item> items = new ArrayList<Item>();
for(int i = 0; i < n; i++){
int j = random.nextInt(6);
switch (j){
case 0:
items.add(getRandomSegment(random));
break;
case 1:
items.add(getRandomTriangle(random));
break;
case 2:
items.add(getRandomCircle(random));
break;
case 3:
items.add(getRandomRect(random));
break;
case 4:
items.add(getRandomStar(random));
break;
case 5:
items.add(getRandomText(random));
break;
}
}
scene.addItem(new ComplexItem(new Point(x, y), items));
scene.draw();
System.out.println("Complex added, total items on Scene: " + scene.getItems().size());
});
return complexButton;
}
private JButton createSegmentButton(Random random) {
JButton segmentButton = new JButton("Draw Segment");
segmentButton.addActionListener(e -> {
scene.addItem(getRandomSegment(random));
scene.draw();
System.out.println("Segment added, total items on Scene: " + scene.getItems().size());
});
return segmentButton;
}
private JButton createTextButton(Random random) {
JButton textButton = new JButton("Draw Text");
textButton.addActionListener(e -> {
scene.addItem(getRandomText(random));
scene.draw();
System.out.println("Text added, total items on Scene: " + scene.getItems().size());
});
return textButton;
}
private JButton createCircleButton(Random random) {
JButton circleButton = new JButton("Draw Circle");
circleButton.addActionListener(e -> {
scene.addItem(getRandomCircle(random));
scene.draw();
System.out.println("Circle added, total items on Scene: " + scene.getItems().size());
});
return circleButton;
}
private JButton createTriangleButton(Random random) {
JButton triangleButton = new JButton("Draw Triangle");
triangleButton.addActionListener(e -> {
scene.addItem(getRandomTriangle(random));
scene.draw();
System.out.println("Triangle added, total items on Scene: " + scene.getItems().size());
});
return triangleButton;
}
private JButton createRectButton(Random random) {
JButton rectangleButton = new JButton("Draw Rectangle");
rectangleButton.addActionListener(e -> {
scene.addItem(getRandomRect(random));
scene.draw();
System.out.println("Rect added, total items on Scene: " + scene.getItems().size());
});
return rectangleButton;
}
private JButton createStarButton(Random random) {
JButton starButton = new JButton("Draw Star");
starButton.addActionListener(e -> {
scene.addItem(getRandomStar(random));
scene.draw();
System.out.println("Star added, total items on Scene: " + scene.getItems().size());
});
return starButton;
}
} | zawodev/PWR | sem3/PP-java/lab9new/src/Scene/CreateItemPanel.java |
179,864 | /**
* Copyright (C) 2006 - 2012
* Pawel Kedzior
* Tomasz Kmiecik
* Kamil Pietak
* Krzysztof Sikora
* Adam Wos
* Lukasz Faber
* Daniel Krzywicki
* and other students of AGH University of Science and Technology.
*
* This file is part of AgE.
*
* AgE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AgE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AgE. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Tomasz Sławek & Marcin Świątek
*/
package org.jage.random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Tests for CauchyGenerator.
*
* @author AGH AgE Team
*/
@RunWith(MockitoJUnitRunner.class)
public class CauchyGeneratorTest {
@Mock
private INormalizedDoubleRandomGenerator rand;
@InjectMocks
private CauchyGenerator underTest = new CauchyGenerator();
@Test
public void testBounds() {
assertThat(underTest.getLowerDouble(), is(equalTo(Double.MIN_VALUE)));
assertThat(underTest.getUpperDouble(), is(equalTo(Double.MAX_VALUE)));
}
@Test
public void testNextDouble() {
// given
given(rand.nextDouble()).willReturn(0.0, 0.5, 1.0);
// then
assertThat(underTest.nextDouble(), is(equalTo(Math.tan(Math.PI * -0.5))));
assertThat(underTest.nextDouble(), is(equalTo(Math.tan(0.0))));
assertThat(underTest.nextDouble(), is(equalTo(Math.tan(Math.PI * 0.5))));
}
}
| ghik/intobl | jage/algorithms/solutions/random/src/test/java/org/jage/random/CauchyGeneratorTest.java |
179,865 | /**
* Copyright (C) 2006 - 2012
* Pawel Kedzior
* Tomasz Kmiecik
* Kamil Pietak
* Krzysztof Sikora
* Adam Wos
* Lukasz Faber
* Daniel Krzywicki
* and other students of AGH University of Science and Technology.
*
* This file is part of AgE.
*
* AgE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AgE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AgE. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Tomasz Sławek & Marcin Świątek
*/
package org.jage.random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Test of GaussianGenerator.
*
* @author AGH AgE Team
*/
@RunWith(MockitoJUnitRunner.class)
public class GaussianGeneratorTest {
@Mock
private INormalizedDoubleRandomGenerator rand;
@InjectMocks
private GaussianGenerator underTest = new GaussianGenerator();
@Test
public void testBounds() {
assertThat(underTest.getLowerDouble(), is(equalTo(Double.MIN_VALUE)));
assertThat(underTest.getUpperDouble(), is(equalTo(Double.MAX_VALUE)));
}
@Test
public void testNextDouble() {
// given
given(rand.nextDouble()).willReturn(0.5);
// then
assertThat(underTest.nextDouble(), is(equalTo(0.0)));
}
}
| ghik/intobl | jage/algorithms/solutions/random/src/test/java/org/jage/random/GaussianGeneratorTest.java |
179,867 | /**
* Copyright (C) 2006 - 2012
* Pawel Kedzior
* Tomasz Kmiecik
* Kamil Pietak
* Krzysztof Sikora
* Adam Wos
* Lukasz Faber
* Daniel Krzywicki
* and other students of AGH University of Science and Technology.
*
* This file is part of AgE.
*
* AgE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AgE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AgE. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Tomasz Sławek & Marcin Świątek
*/
package org.jage.random;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for SimpleGenerator.
*
* @author AGH AgE Team
*/
public class SimpleGeneratorTest {
private long seed = 1234567890L;
private SimpleGenerator generator;
@Before
public void setUp() throws Exception {
generator = new SimpleGenerator(seed);
}
@Test
public void testBounds() {
assertThat(generator.getLowerDouble(), is(equalTo(0.0)));
assertThat(generator.getUpperDouble(), is(equalTo(1.0)));
assertThat(generator.getLowerInt(), is(equalTo(Integer.MIN_VALUE)));
assertThat(generator.getUpperInt(), is(equalTo(Integer.MAX_VALUE)));
}
@Test
public void testSeed() {
// given
SimpleGenerator generator2 = new SimpleGenerator(seed);
// then
assertThat(generator.nextInt(), is(equalTo(generator2.nextInt())));
assertThat(generator.nextDouble(), is(equalTo(generator2.nextDouble())));
}
@Test
public void testNextDouble() {
// given
Random rand = new Random(seed);
// then
for (int i = 0; i < 10000; i++) {
assertThat(generator.nextDouble(), is(equalTo(rand.nextDouble())));
}
}
@Test
public void testNextInt() {
// given
Random rand = new Random(seed);
// then
for (int i = 0; i < 10000; i++) {
assertThat(generator.nextInt(), is(equalTo(rand.nextInt())));
}
}
}
| ghik/intobl | jage/algorithms/solutions/random/src/test/java/org/jage/random/SimpleGeneratorTest.java |
179,868 | package pl.put.poznan.transformer.logic;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ReverseTransformerTest {
private InterfaceTextTransformer iTransformer;
@BeforeEach
public void setUp(){
iTransformer = new EmptyTextTransformer();
iTransformer = new ReverseTransformer(iTransformer);
}
@Test
void testTransformationExample(){
String actualTransformation = iTransformer.getTransformation("MirEk");
String expectedTransformation = "KerIm";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationLowerWord(){
String actualTransformation = iTransformer.getTransformation("natalia");
String expectedTransformation = "ailatan";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationUpperWord(){
String actualTransformation = iTransformer.getTransformation("JANEK");
String expectedTransformation = "KENAJ";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationMixedWord(){
String actualTransformation = iTransformer.getTransformation("MAti");
String expectedTransformation = "ITam";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationLowerSentence(){
String actualTransformation = iTransformer.getTransformation("julia czokłowicz");
String expectedTransformation = "zciwołkozc ailuj";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationUpperSentence(){
String actualTransformation = iTransformer.getTransformation("MATEUSZ ŚWIĄTEK");
String expectedTransformation = "KETĄIWŚ ZSUETAM";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
@Test
void testTransformationMixedSentence(){
String actualTransformation = iTransformer.getTransformation("niE WieM juŻ");
String expectedTransformation = "żuJ MeiW eiN";
Assertions.assertEquals(expectedTransformation, actualTransformation);
}
} | natalia-szymczyk/text-transformer-io | src/test/java/pl/put/poznan/transformer/logic/ReverseTransformerTest.java |