hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
844b981b422a0fcd1cd06542e46108efff555a06
29,688
/** * Copyright (c) 2012 Selventa. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributors: * Selventa - initial API and implementation */ package org.openbel.editor.core.common.enums; import static java.util.Collections.unmodifiableSet; import static org.openbel.editor.core.common.BELUtilities.constrainedHashMap; import static org.openbel.editor.core.common.BELUtilities.constrainedHashSet; import java.util.Map; import java.util.Set; import org.openbel.editor.core.common.Strings; import org.openbel.editor.core.common.lang.*; /** * Enumerated representation of function. * <p> * Portions of this enum have been automatically generated. * </p> */ public enum FunctionEnum { /** * Abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ ABUNDANCE(0, Strings.ABUNDANCE, Strings.ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Biological process term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#BIOLOGICAL_PROCESS}</dd> * </dl> */ BIOLOGICAL_PROCESS(1, Strings.BIOLOGICAL_PROCESS, Strings.BIOLOGICAL_PROCESS_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.BIOLOGICAL_PROCESS; } }, /** * Catalytic activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ CATALYTIC_ACTIVITY(2, Strings.CATALYTIC_ACTIVITY, Strings.CATALYTIC_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Cell secretion term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ CELL_SECRETION(3, Strings.CELL_SECRETION, Strings.CELL_SECRETION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Cell surface expression term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ CELL_SURFACE_EXPRESSION(4, Strings.CELL_SURFACE_EXPRESSION, Strings.CELL_SURFACE_EXPRESSION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Chaperone activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ CHAPERONE_ACTIVITY(5, Strings.CHAPERONE_ACTIVITY, Strings.CHAPERONE_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Complex abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#COMPLEX_ABUNDANCE}</dd> * </dl> */ COMPLEX_ABUNDANCE(6, Strings.COMPLEX_ABUNDANCE, Strings.COMPLEX_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.COMPLEX_ABUNDANCE; } }, /** * Composite abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ COMPOSITE_ABUNDANCE(7, Strings.COMPOSITE_ABUNDANCE, Strings.COMPOSITE_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Degradation term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ DEGRADATION(8, Strings.DEGRADATION, Strings.DEGRADATION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Fusion term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#PROTEIN_ABUNDANCE}</dd> * </dl> */ FUSION(9, Strings.FUSION, Strings.FUSION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.PROTEIN_ABUNDANCE; } }, /** * Gene abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#GENE_ABUNDANCE}</dd> * </dl> */ GENE_ABUNDANCE(10, Strings.GENE_ABUNDANCE, Strings.GENE_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.GENE_ABUNDANCE; } }, /** * GTP-bound activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ GTP_BOUND_ACTIVITY(11, Strings.GTP_BOUND_ACTIVITY, Strings.GTP_BOUND_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Kinase activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ KINASE_ACTIVITY(12, Strings.KINASE_ACTIVITY, Strings.KINASE_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * MicroRNA abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#MICRORNA_ABUNDANCE}</dd> * </dl> */ MICRORNA_ABUNDANCE(13, Strings.MICRO_RNA_ABUNDANCE, Strings.MICRO_RNA_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.MICRORNA_ABUNDANCE; } }, /** * Molecular activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ MOLECULAR_ACTIVITY(14, Strings.MOLECULAR_ACTIVITY, Strings.MOLECULAR_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Pathology term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#PATHOLOGY}</dd> * </dl> */ PATHOLOGY(15, Strings.PATHOLOGY, Strings.PATHOLOGY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.PATHOLOGY; } }, /** * Peptidase activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ PEPTIDASE_ACTIVITY(16, Strings.PEPTIDASE_ACTIVITY, Strings.PEPTIDASE_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Phosphatase activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ PHOSPHATASE_ACTIVITY(17, Strings.PHOSPHATASE_ACTIVITY, Strings.PHOSPHATASE_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Products term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#PRODUCTS}</dd> * </dl> */ PRODUCTS(18, Strings.PRODUCTS) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.PRODUCTS; } }, /** * Protein abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#PROTEIN_ABUNDANCE}</dd> * </dl> */ PROTEIN_ABUNDANCE(19, Strings.PROTEIN_ABUNDANCE, Strings.PROTEIN_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.PROTEIN_ABUNDANCE; } }, /** * ProteinModification term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#PROTEIN_MODIFICATION}</dd> * </dl> */ PROTEIN_MODIFICATION(20, Strings.PROTEIN_MODIFICATION, Strings.PROTEIN_MODIFICATION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.PROTEIN_MODIFICATION; } }, /** * Reactants term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#REACTANTS}</dd> * </dl> */ REACTANTS(21, Strings.REACTANTS) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.REACTANTS; } }, /** * Reaction term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ REACTION(22, Strings.REACTION, Strings.REACTION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Ribosylation activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ RIBOSYLATION_ACTIVITY(23, Strings.RIBOSYLATION_ACTIVITY, Strings.RIBOSYLATION_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * RNA abundance term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#GENE_ABUNDANCE}</dd> * </dl> */ RNA_ABUNDANCE(24, Strings.RNA_ABUNDANCE, Strings.RNA_ABUNDANCE_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.GENE_ABUNDANCE; } }, /** * Substitution term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#SUBSTITUTION}</dd> * </dl> */ SUBSTITUTION(25, Strings.SUBSTITUTION, Strings.SUBSTITUTION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.SUBSTITUTION; } }, /** * List term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#LIST}</dd> * </dl> */ LIST(26, Strings.LIST) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.LIST; } }, /** * Transcriptional activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ TRANSCRIPTIONAL_ACTIVITY(27, Strings.TRANSCRIPTIONAL_ACTIVITY, Strings.TRANSCRIPTIONAL_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Translocation term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ TRANSLOCATION(28, Strings.TRANSLOCATION, Strings.TRANSLOCATION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Transport activity term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#ABUNDANCE}</dd> * </dl> */ TRANSPORT_ACTIVITY(29, Strings.TRANSPORT_ACTIVITY, Strings.TRANSPORT_ACTIVITY_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.ABUNDANCE; } }, /** * Truncation term function. * <dl> * <dt>Function return type:</dt> * <dd>{@link ReturnType#TRUNCATION}</dd> * </dl> */ TRUNCATION(30, Strings.TRUNCATION, Strings.TRUNCATION_ABBREV) { /** * {@inheritDoc} */ @Override public ReturnType getReturnType() { return ReturnType.TRUNCATION; } }; private static final Map<String, FunctionEnum> DISPVAL_TO_ENUM; private static final Map<String, FunctionEnum> ABBR_TO_ENUM; private static final Map<Integer, FunctionEnum> VALUETOENUM; private static final Map<FunctionEnum, Function> FUNCTIONS; private static final Set<FunctionEnum> PROTEIN_DECORATION_FUNCTIONS; private static final Set<FunctionEnum> ABUNDANCE_FUNCTIONS; private static final Set<FunctionEnum> ACTIVITY_FUNCTIONS; private static final Set<FunctionEnum> MUTATION_FUNCTIONS; static { final int length = values().length; DISPVAL_TO_ENUM = constrainedHashMap(length); VALUETOENUM = constrainedHashMap(length); FUNCTIONS = constrainedHashMap(length); int abbrs = 0; for (final FunctionEnum e : values()) { if (e.abbreviation != null) { abbrs++; } } ABBR_TO_ENUM = constrainedHashMap(abbrs); for (final FunctionEnum e : values()) { DISPVAL_TO_ENUM.put(e.displayValue, e); VALUETOENUM.put(e.value, e); FUNCTIONS.put(e, getFunction(e)); if (e.abbreviation != null) { ABBR_TO_ENUM.put(e.abbreviation, e); } } final Set<FunctionEnum> decorators = constrainedHashSet(4); decorators.add(PROTEIN_MODIFICATION); decorators.add(SUBSTITUTION); decorators.add(TRUNCATION); decorators.add(FUSION); PROTEIN_DECORATION_FUNCTIONS = unmodifiableSet(decorators); final Set<FunctionEnum> abundances = constrainedHashSet(7); abundances.add(ABUNDANCE); abundances.add(COMPLEX_ABUNDANCE); abundances.add(COMPOSITE_ABUNDANCE); abundances.add(GENE_ABUNDANCE); abundances.add(MICRORNA_ABUNDANCE); abundances.add(PROTEIN_ABUNDANCE); abundances.add(RNA_ABUNDANCE); ABUNDANCE_FUNCTIONS = unmodifiableSet(abundances); final Set<FunctionEnum> activities = constrainedHashSet(10); activities.add(CATALYTIC_ACTIVITY); activities.add(CHAPERONE_ACTIVITY); activities.add(GTP_BOUND_ACTIVITY); activities.add(KINASE_ACTIVITY); activities.add(MOLECULAR_ACTIVITY); activities.add(PEPTIDASE_ACTIVITY); activities.add(PHOSPHATASE_ACTIVITY); activities.add(RIBOSYLATION_ACTIVITY); activities.add(TRANSCRIPTIONAL_ACTIVITY); activities.add(TRANSPORT_ACTIVITY); ACTIVITY_FUNCTIONS = unmodifiableSet(activities); final Set<FunctionEnum> mutations = constrainedHashSet(3); mutations.add(SUBSTITUTION); mutations.add(TRUNCATION); mutations.add(FUSION); MUTATION_FUNCTIONS = unmodifiableSet(mutations); } /** * Enumeration abbreviation. */ private String abbreviation; /** * Enumeration display value. */ private String displayValue; /** * Value unique to each enumeration. */ private final Integer value; /** * Constructor for setting enum, display value, and abbreviation. * * @param val * Enum value * @param dispVal * Display value * @param abbr * Abbreviation */ private FunctionEnum(Integer val, String dispVal, String abbr) { this.value = val; this.displayValue = dispVal; this.abbreviation = abbr; } /** * Constructor for setting enum and display value. * * @param val * Enum value * @param dispVal * Display value */ private FunctionEnum(Integer val, String dispVal) { this.value = val; this.displayValue = dispVal; } /** * Returns the function enum's abbreviation. * * @return abbreviation; may be null */ public String getAbbreviation() { return abbreviation; } /** * Returns the long form of the function name. * * @return display value */ public String getDisplayValue() { return displayValue; } /** * Returns this function enum's {@link ReturnType return type}. * * @return ReturnType */ public ReturnType getReturnType() { throw new AbstractMethodError(); } /** * Returns the function enum's value. * * @return value * @see java.lang.Enum#ordinal() Contrast with {@code ordinal} */ public Integer getValue() { return value; } /** * {@inheritDoc} */ @Override public String toString() { return displayValue; } /** * Returns this function enum's language function. * * @return {@link Function} */ public Function getFunction() { return FUNCTIONS.get(this); } /** * Returns the function enum by its string representation, which may be * null. * * @param s * Function enum string representation * @return FunctionEnum- null if the provided string has no function * representation * @see #getFunctionEnum(String) */ public static FunctionEnum fromString(final String s) { return getFunctionEnum(s); } /** * Returns the function enum for the <tt>value</tt> representation. * * @param value * {@link Integer}, the value for the function enum * @return {@link FunctionEnum}, the function enum, or null if: * <ul> * <li><tt>value</tt> parameter is null</li> * <li><tt>value</tt> parameter does not map to a function enum</li> * </ul> */ public static FunctionEnum fromValue(final Integer value) { if (value == null) { return null; } return VALUETOENUM.get(value); } /** * Returns the function enum's language function. * * @param e * Function enum * @return {@link Function} */ public static Function getFunction(final FunctionEnum e) { switch (e) { case ABUNDANCE: return new Abundance(); case BIOLOGICAL_PROCESS: return new BiologicalProcess(); case CATALYTIC_ACTIVITY: return new CatalyticActivity(); case CELL_SECRETION: return new CellSecretion(); case CELL_SURFACE_EXPRESSION: return new CellSurfaceExpression(); case CHAPERONE_ACTIVITY: return new ChaperoneActivity(); case COMPLEX_ABUNDANCE: return new ComplexAbundance(); case COMPOSITE_ABUNDANCE: return new CompositeAbundance(); case DEGRADATION: return new Degradation(); case FUSION: return new Fusion(); case GENE_ABUNDANCE: return new GeneAbundance(); case GTP_BOUND_ACTIVITY: return new GTPBoundActivity(); case KINASE_ACTIVITY: return new KinaseActivity(); case MICRORNA_ABUNDANCE: return new MicroRNAAbundance(); case MOLECULAR_ACTIVITY: return new MolecularActivity(); case PATHOLOGY: return new Pathology(); case PEPTIDASE_ACTIVITY: return new PeptidaseActivity(); case PHOSPHATASE_ACTIVITY: return new PhosphataseActivity(); case PRODUCTS: return new Products(); case PROTEIN_ABUNDANCE: return new ProteinAbundance(); case PROTEIN_MODIFICATION: return new ProteinModification(); case REACTANTS: return new Reactants(); case REACTION: return new Reaction(); case RIBOSYLATION_ACTIVITY: return new RibosylationActivity(); case RNA_ABUNDANCE: return new RNAAbundance(); case SUBSTITUTION: return new Substitution(); case TRANSCRIPTIONAL_ACTIVITY: return new TranscriptionalActivity(); case TRANSLOCATION: return new Translocation(); case TRANSPORT_ACTIVITY: return new TransportActivity(); case TRUNCATION: return new Truncation(); case LIST: return new TermList(); default: throw new UnsupportedOperationException(e.toString()); } } /** * Returns {@code true} if {@code count} is a valid number of arguments for * the enum's {@link #getFunction() function}. * <p> * This method simply delegates to {@link Function#validArgumentCount(int)}. * </p> * * @param e * Function enum * @param count * Argument count * @return boolean */ public static boolean isValidArgumentCount(final FunctionEnum e, int count) { return e.getFunction().validArgumentCount(count); } /** * Returns {@code true} if {@code count} is a valid number of arguments for * the {@link #getFunction() function}. * <p> * This method simply delegates to {@link Function#validArgumentCount(int)}. * </p> * * @param count * Argument count * @return boolean */ public boolean isValidArgumentCount(int count) { return getFunction().validArgumentCount(count); } /** * Returns the function enum by its display or abbreviation string * representation (case-insensitive), which may be null. * <p> * This method is favored in place of {@link #fromString(String)} as it * provides disambiguation with other enums when used as a static import. * </p> * * @param s * Function enum string representation * @return FunctionEnum - null if the provided string has no function * representation */ public static FunctionEnum getFunctionEnum(final String s) { FunctionEnum e = DISPVAL_TO_ENUM.get(s); if (e != null) { return e; } e = ABBR_TO_ENUM.get(s); if (e != null) { return e; } for (final String val : DISPVAL_TO_ENUM.keySet()) { if (val.equalsIgnoreCase(s)) return DISPVAL_TO_ENUM.get(val); } for (final String val : ABBR_TO_ENUM.keySet()) { if (val.equalsIgnoreCase(s)) return ABBR_TO_ENUM.get(val); } return null; } /** * Returns the set of {@link FunctionEnum functions} that are considered * protein <i>decorators</i>. * <p> * This set contains: * <ul> * <li>{@link #PROTEIN_MODIFICATION}</li> * <li>{@link #SUBSTITUTION}</li> * <li>{@link #TRUNCATION}</li> * </ul> * </p> * * @return an unmodifiable {@link Set} of protein decoration * {@link FunctionEnum functions} */ public static Set<FunctionEnum> getProteinDecorators() { return PROTEIN_DECORATION_FUNCTIONS; } /** * Returns the set of {@link FunctionEnum functions} that are considered * abundance functions. * <p> * This set contains: * <ul> * <li>{@link #ABUNDANCE}</li> * <li>{@link #COMPLEX_ABUNDANCE}</li> * <li>{@link #COMPOSITE_ABUNDANCE}</li> * <li>{@link #GENE_ABUNDANCE}</li> * <li>{@link #MICRORNA_ABUNDANCE}</li> * <li>{@link #PROTEIN_ABUNDANCE}</li> * <li>{@link #RNA_ABUNDANCE}</li> * </ul> * </p> * * @return an unmodifiable {@link Set} of abundance {@link FunctionEnum * functions} */ public static Set<FunctionEnum> getAbundances() { return ABUNDANCE_FUNCTIONS; } /** * Returns the set of {@link FunctionEnum functions} that are considered * activity functions. * <p> * This set contains: * <ul> * <li>{@link #CATALYTIC_ACTIVITY}</li> * <li>{@link #CHAPERONE_ACTIVITY}</li> * <li>{@link #GTP_BOUND_ACTIVITY}</li> * <li>{@link #KINASE_ACTIVITY}</li> * <li>{@link #MOLECULAR_ACTIVITY}</li> * <li>{@link #PEPTIDASE_ACTIVITY}</li> * <li>{@link #PHOSPHATASE_ACTIVITY}</li> * <li>{@link #RIBOSYLATION_ACTIVITY}</li> * <li>{@link #TRANSCRIPTIONAL_ACTIVITY}</li> * <li>{@link #TRANSPORT_ACTIVITY}</li> * </ul> * </p> * * @return an unmodifiable {@link Set} of activity {@link FunctionEnum * functions} */ public static Set<FunctionEnum> getActivities() { return ACTIVITY_FUNCTIONS; } /** * Returns the set of {@link FunctionEnum functions} that are considered * mutation functions. * <p> * This set contains: * <ul> * <li>{@link #SUBSTITUTION}</li> * <li>{@link #TRUNCATION}</li> * <li>{@link #FUSION}</li> * </ul> * </p> * * @return an unmodifiable {@link Set} of mutation {@link FunctionEnum * functions} */ public static Set<FunctionEnum> getMutations() { return MUTATION_FUNCTIONS; } /** * Returns {@code true} if this {@link FunctionEnum function} is considered * a protein <i>decorator</i>, {@code false} otherwise. * * @return boolean */ public boolean isProteinDecorator() { return isProteinDecorator(this); } /** * Returns {@code true} if the {@link FunctionEnum function} is considered a * protein <i>decorator</i>, {@code false} otherwise. * * @param f * {@link FunctionEnum}, the function, which may be null * @return boolean */ public static boolean isProteinDecorator(final FunctionEnum f) { if (f == null) { return false; } switch (f) { case PROTEIN_MODIFICATION: case SUBSTITUTION: case TRUNCATION: case FUSION: return true; default: return false; } } /** * Returns {@code true} if this {@link FunctionEnum function} is considered * a mutation, {@code false} otherwise. * * @return boolean */ public boolean isMutation() { return isMutation(this); } /** * Returns {@code true} if the {@link FunctionEnum function} is considered a * mutation, {@code false} otherwise. * * @param f * {@link FunctionEnum}, the function, which may be null * @return boolean */ public static boolean isMutation(final FunctionEnum f) { if (f == null) { return false; } switch (f) { case SUBSTITUTION: case TRUNCATION: case FUSION: return true; default: return false; } } /** * Returns {@code true} if this function's arguments follow a logical order, * {@code false} if order is not important. * * @return boolean */ public boolean isSequential() { return isSequential(this); } /** * Returns {@code true} if the {@link FunctionEnum function's} argument * follow a logical order, {@code false} if order is not important. * * @param f * {@link FunctionEnum}, the function, which may be null * @return boolean */ public static boolean isSequential(final FunctionEnum f) { if (f == null) { return false; } switch (f) { case COMPLEX_ABUNDANCE: case COMPOSITE_ABUNDANCE: case PRODUCTS: case REACTANTS: case LIST: return false; default: return true; } } }
26.866968
82
0.560496
1d5f253e14bba64e8b098bbfd47b21ea2dda280b
390
package io.wilson.basic.concurrent; import java.util.concurrent.locks.ReentrantLock; /** * TempLock * * @author Wilson * @date 2020/8/14 */ public class TempLock { private static final ReentrantLock FAIR_LOCK = new ReentrantLock(true); public static void main(String[] args) { FAIR_LOCK.lock(); System.out.println("aaa"); FAIR_LOCK.unlock(); } }
19.5
75
0.664103
0cb7f7583c1bc52c2ecd0482a51482544a8a87a3
923
package com.deskera.sdk.common.util.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * The ConflictException. * */ @ResponseStatus(value = HttpStatus.CONFLICT) public class ConflictException extends ServiceException { /** * The Constant serialVersionUID. */ private static final long serialVersionUID = 8533333646842447026L; /** * The Constant HTTP_STATUS. */ private static final HttpStatus HTTP_STATUS = HttpStatus.CONFLICT; /** * Instantiates a new ConflictException. * * @param errorMessage the error message */ public ConflictException(final String errorMessage) { super(errorMessage, HTTP_STATUS); } /** * Instantiates a new ConflictException. * * @param throwable the throwable */ public ConflictException(final Throwable throwable) { super(throwable, HTTP_STATUS); } }
22.512195
68
0.729144
6ef260b2e20bbcfec95736e7766a803181830861
563
package org.saatsch.framework.base.swt.widgets; import org.eclipse.swt.widgets.Shell; import org.junit.Test; import org.saatsch.framework.base.swt.MinimalParentShell; import org.saatsch.framework.base.swt.Openable; public class LoadingDialogDemo extends MinimalParentShell implements Openable<Void> { @Test public void test() { LoadingDialogDemo testedClass = new LoadingDialogDemo(); testedClass.open(); } @Override public Openable<Void> init(Shell parentShell) { return new Loading(parentShell); } }
20.851852
86
0.724689
22a3f5358c9b7fdd9990f5774db65e73712208a1
1,003
package org.knowm.xchange.bleutrade.service; import org.knowm.xchange.Exchange; import org.knowm.xchange.bleutrade.BleutradeAuthenticated; import org.knowm.xchange.service.BaseExchangeService; import org.knowm.xchange.service.BaseService; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.RestProxyFactory; public class BleutradeBaseService extends BaseExchangeService implements BaseService { protected final String apiKey; protected final BleutradeAuthenticated bleutrade; protected final ParamsDigest signatureCreator; /** * Constructor * * @param exchange */ public BleutradeBaseService(Exchange exchange) { super(exchange); this.bleutrade = RestProxyFactory.createProxy(BleutradeAuthenticated.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig()); this.apiKey = exchange.getExchangeSpecification().getApiKey(); this.signatureCreator = BleutradeDigest.createInstance(exchange.getExchangeSpecification().getSecretKey()); } }
31.34375
148
0.801595
e69f4745532972681f48c363b3e8cb2237b6c9d5
1,183
package org.conggroup.vizard.comparsion.config.kafka; import org.apache.kafka.clients.consumer.ConsumerConfig; import java.util.HashMap; import java.util.Map; public class KafkaConsumerConfigTemplate { public static Map<String, Object> GenerateConfig(String bootstrapServer, String groupId) { Map<String, Object> props = new HashMap<String, Object>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer); props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 100); props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10000); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.springframework.kafka.support.serializer.JsonDeserializer"); props.put("spring.json.trusted.packages", "*"); return props; } }
43.814815
95
0.725275
530ad533a94eb6fd0ce3ed08c4fae3ab8420b20a
1,501
package com.zhcs.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; import com.zhcs.dao.SignDao; import com.zhcs.entity.SignEntity; import com.zhcs.service.SignService; //***************************************************************************** /** * <p>Title:SignServiceImpl</p> * <p>Description: 招牌申请</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司 </p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** @Service("signService") public class SignServiceImpl implements SignService { @Autowired private SignDao signDao; @Override public SignEntity queryObject(Long id){ return signDao.queryObject(id); } @Override public List<SignEntity> queryList(Map<String, Object> map){ return signDao.queryList(map); } @Override public int queryTotal(Map<String, Object> map){ return signDao.queryTotal(map); } @Override @Transactional public void save(SignEntity sign){ signDao.save(sign); } @Override @Transactional public void update(SignEntity sign){ signDao.update(sign); } @Override @Transactional public void delete(Long id){ signDao.delete(id); } @Override @Transactional public void deleteBatch(Long[] ids){ signDao.deleteBatch(ids); } }
21.140845
79
0.662225
afb87d5b4f117cf7519d44907f991ee914b7f4a7
837
/** * */ package com.mudit.SideWall.Configurations; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * @author Mudit * @since Dec 26, 2016 */ public class MyEntityManagerFactory { private static EntityManagerFactory myEntityManagerFactory; private MyEntityManagerFactory() { // TODO Auto-generated constructor stub } public static EntityManagerFactory getMy_factory() { if (myEntityManagerFactory == null) { synchronized (MyEntityManagerFactory.class) { myEntityManagerFactory = Persistence.createEntityManagerFactory("sidewalljpa"); } } return myEntityManagerFactory; } public static void setMy_factory(EntityManagerFactory myEntityManagerFactory) { MyEntityManagerFactory.myEntityManagerFactory = myEntityManagerFactory; } }
25.363636
84
0.756272
41618b8155174bac6f3d74ba6ac09712e4e1f1af
1,682
package com.webcheckers.model; import com.webcheckers.appl.MasterEnum; import org.junit.Before; import org.junit.Test; import spark.Request; import spark.Session; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Created by wor3835 on 11/7/2017. */ public class KingTest { /** * Variables */ private King CuT; private King king; private Request request; private Session session; /** * Sets up the mock objects and the CuT */ @Before public void setup() { king = new King(MasterEnum.Color.RED); //set up mock objects request = mock(Request.class); session = mock(Session.class); when(request.session()).thenReturn(session); // create a unique CuT for each test CuT = new King(MasterEnum.Color.RED); } /** * Test for the makeKing() function */ @Test public void makeKing() { King k = new King(MasterEnum.Color.WHITE); assertNotNull(k); } /** * Test for the getColor() function */ @Test public void getColor() { assertEquals(MasterEnum.Color.RED, CuT.getColor()); } /** * Test for the getType() function */ @Test public void getType() { assertEquals(MasterEnum.PieceType.KING, CuT.getType()); } /** * Test for the makeKingOutofPawn function */ @Test public void makeKingOutOfPawn(){ Piece p = new Pawn(MasterEnum.Color.RED); Piece k = new King(p); assertNotNull(k); } }
20.765432
63
0.612961
8cb566986ecb3f3b52ccc391b35d285b1c93770b
631
package fr.romainmoreau.epaper.jaxb.api.table; import javax.xml.bind.annotation.XmlAttribute; import fr.romainmoreau.epaper.client.api.Color; public class Border { private int size; private Color color; public fr.romainmoreau.epaper.client.api.table.Border toBorder() { return new fr.romainmoreau.epaper.client.api.table.Border(size, color); } @XmlAttribute(required = true) public int getSize() { return size; } public void setSize(int size) { this.size = size; } @XmlAttribute(required = true) public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } }
18.558824
73
0.730586
93cdc1da4c6a3e5c44ca4c91eee56fe164d5c2cb
111
package almost; /** * * @author ArNoB */ public class brick { public int exist; public int x, y; }
10.090909
21
0.585586
3b50cb2bf40d0ddfbacfddac2a67045374582696
1,405
/* * Copyright 2013-2021 the original author or 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 * * https://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.springframework.cloud.kubernetes.fabric8.config; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = TestApplication.class, properties = { "spring.main.cloud-platform=KUBERNETES", "spring.application.name=testapp", "spring.cloud.kubernetes.client.namespace=testns", "spring.cloud.kubernetes.client.trustCerts=true", "spring.cloud.kubernetes.config.namespace=testns", "spring.cloud.kubernetes.secrets.enableApi=true", "spring.cloud.bootstrap.enabled=true" }) public class BootstrapCoreTestClientViaSystemProperties extends CoreTestClientViaSystemProperties { }
42.575758
104
0.785053
abc45e5ae8dc072873657c714c9e4eb32f2268f6
449
package gov.healthit.chpl.web.controller; import java.util.List; public class CertificationIdVerificationBody { private List<String> ids; public CertificationIdVerificationBody() { } public CertificationIdVerificationBody(final List<String> ids) { this.ids = ids; } public List<String> getIds() { return this.ids; } public void setIds(final List<String> ids) { this.ids = ids; } }
17.96
68
0.659243
b41f9abe8f8c5b03c1ec64147b15c7be03ae5151
675
package com.oodexamples.patterns.creational.factory; import com.oodexamples.modules.BoeingStandardEngine; import com.oodexamples.patterns.creational.builder.models.PassengerWings; import com.oodexamples.modules.BoeingEngine; import lombok.Data; @Data public class BoeingPlane { private String model; private PassengerWings wings; private BoeingEngine engine; public BoeingPlane make(){ this.model = "Standard"; this.wings = new PassengerWings(); this.engine = new BoeingStandardEngine(); return this; } public void fly(){ make(); System.out.println("Boeing " + this.model + " is flying"); } }
24.107143
73
0.697778
f29e128d04c287b54160ee3a2647a782c68487e9
7,359
package me.cthorne.kioku.statistics; import android.content.Context; import android.graphics.Color; import android.util.Log; import com.github.mikephil.charting.charts.Chart; import com.github.mikephil.charting.charts.RadarChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.RadarDataSet; import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; import me.cthorne.kioku.DatabaseHelper; import me.cthorne.kioku.test.WordInformationTestType; import me.cthorne.kioku.test.tests.Tests; /** * Created by chris on 30/01/16. */ public class PerformanceGraph extends Graph { /*final private static WordInformationTestType testTypes[] = new WordInformationTestType[]{ WordInformationTestType.VOCABULARY_RECALL, WordInformationTestType.VOCABULARY_COMPREHENSION, WordInformationTestType.SENTENCE_COMPREHENSION, WordInformationTestType.KANJI_WRITING, WordInformationTestType.KANJI_READING };*/ private RadarChart performanceChart; private Set<WordInformationTestType> testTypes; private HashMap<WordInformationTestType, Long> forgotCounts; private HashMap<WordInformationTestType, Long> rememberedCounts; private long minForgot; private long maxForgot; private long minRemembered; private long maxRemembered; @Override public void clear() { forgotCounts = new HashMap<>(); rememberedCounts = new HashMap<>(); minForgot = 0; maxForgot = 0; minRemembered = 0; maxRemembered = 0; } @Override public void loadThisWeek(DatabaseHelper dbHelper) throws SQLException { for (WordInformationTestType testType : testTypes) { long forgotCount = dbHelper.qbUserTestAnswersThisWeek(testType, 0).countOf(); long rememberedCount = dbHelper.qbUserTestAnswersThisWeek(testType, 1).countOf(); putCounts(testType, forgotCount, rememberedCount); } } @Override public void loadThisMonth(DatabaseHelper dbHelper) throws SQLException { for (WordInformationTestType testType : testTypes) { long forgotCount = dbHelper.qbUserTestAnswersThisMonth(testType, 0).countOf(); long rememberedCount = dbHelper.qbUserTestAnswersThisMonth(testType, 1).countOf(); putCounts(testType, forgotCount, rememberedCount); } } @Override public void loadThisYear(DatabaseHelper dbHelper) throws SQLException { for (WordInformationTestType testType : testTypes) { long forgotCount = dbHelper.qbUserTestAnswersThisYear(testType, 0).countOf(); long rememberedCount = dbHelper.qbUserTestAnswersThisYear(testType, 1).countOf(); putCounts(testType, forgotCount, rememberedCount); } } @Override public void loadAllTime(DatabaseHelper dbHelper) throws SQLException { for (WordInformationTestType testType : testTypes) { long forgotCount = dbHelper.qbUserTestAnswers(testType, 0).countOf(); long rememberedCount = dbHelper.qbUserTestAnswers(testType, 1).countOf(); putCounts(testType, forgotCount, rememberedCount); } } @Override public void populate() { // Data ArrayList<Entry> rememberedEntries = new ArrayList<>(); //ArrayList<Entry> forgotEntries = new ArrayList<>(); int i = 0; for (WordInformationTestType testType : testTypes) { //Long forgotCount = forgotCounts.get(testType); Long rememberedCount = rememberedCounts.get(testType); //Log.d("kioku-stats", "test type " + testType + " f" + forgotCount + "r" + rememberedCount); Log.d("kioku-stats", "test type " + testType + " r" + rememberedCount); /*if (maxForgot == 0 || forgotCount == null) forgotEntries.add(new Entry(0.1f, i)); else forgotEntries.add(new Entry(forgotCount, i));*/ //if (rememberedCount == 0) // rememberedEntries.add(new Entry(0.1f, i)); //else rememberedEntries.add(new Entry(rememberedCount, i++)); } /*RadarDataSet forgotSet = new RadarDataSet(forgotEntries, "Forgot"); forgotSet.setDrawFilled(true); forgotSet.setDrawValues(false); forgotSet.setColor(Color.YELLOW); forgotSet.setLineWidth(1f); if (maxForgot == 0) forgotSet.setVisible(false);*/ RadarDataSet rememberedSet = new RadarDataSet(rememberedEntries, "Remembered"); rememberedSet.setDrawFilled(true); rememberedSet.setDrawValues(false); rememberedSet.setColor(Color.parseColor("#02C01F")); rememberedSet.setLineWidth(2f); if (maxRemembered == 0) rememberedSet.setVisible(false); ArrayList<IRadarDataSet> dataSets = new ArrayList<>(); dataSets.add(rememberedSet); //dataSets.add(forgotSet); ArrayList<String> xVals = new ArrayList<>(); for (WordInformationTestType testType : testTypes) { xVals.add(testType.toName()); } RadarData data = new RadarData(xVals, dataSets); performanceChart.getYAxis().setAxisMaxValue(120.0f); performanceChart.setData(data); performanceChart.notifyDataSetChanged(); performanceChart.invalidate(); } @Override public Chart create(Context context) { // Get test types testTypes = new TreeSet<>(Tests.getAll().keySet()); // Create chart performanceChart = new RadarChart(context); // Axes XAxis xAxis = performanceChart.getXAxis(); xAxis.setTextSize(6.0f); YAxis yAxis = performanceChart.getYAxis(); yAxis.setDrawLabels(false); // Legend //performanceChart.getLegend().setPosition(Legend.LegendPosition.BELOW_CHART_CENTER); performanceChart.getLegend().setEnabled(false); return performanceChart; } @Override public String getTitle() { return "Performance"; } private void putCounts(WordInformationTestType testType, long forgotCount, long rememberedCount) { Log.d("kioku-stats", "forgot " + forgotCount + ", remembered " + rememberedCount); long newRememberedCount = (long)((rememberedCount/((float)rememberedCount+forgotCount*3l))*100); Log.d("kioku-stats", "=> " + newRememberedCount); // Put into map //forgotCounts.put(testType, forgotCount); //rememberedCounts.put(testType, rememberedCount); rememberedCounts.put(testType, newRememberedCount); // Update min max //maxForgot = Math.max(maxForgot, forgotCount); maxRemembered = Math.max(maxRemembered, rememberedCount); /*if (minForgot == 0 || forgotCount < minForgot) minForgot = forgotCount; if (minRemembered == 0 || rememberedCount < minRemembered) minRemembered = rememberedCount;*/ } }
35.897561
105
0.671015
c9cf6abd448accb609c32435cbfb65f70debe917
1,547
package com.msgilligan.bitcoin.rpc; import java.net.MalformedURLException; import java.net.URL; /** * Utility class with default connection information for Bitcoin/Mastercoin JSON-RPC */ public class RPCURL { public static final String rpcproto = "http"; public static final String rpcssl = "https"; public static final String rpchost = "127.0.0.1"; public static final String rpcfile = "/"; public static final String stableMscRpcHost = "core.stage.merchantcoin.net"; public static final int RPCPORT_MAINNET = 8332; public static final int RPCPORT_TESTNET = 18332; public static final int RPCPORT_REGTEST = 18332; public static URL getDefaultMainNetURL() { try { return new URL(rpcproto, rpchost, RPCPORT_MAINNET, rpcfile); } catch (MalformedURLException e) { return null; } } public static URL getDefaultTestNetURL() { try { return new URL(rpcproto, rpchost, RPCPORT_TESTNET, rpcfile); } catch (MalformedURLException e) { return null; } } public static URL getDefaultRegTestURL() { try { return new URL(rpcproto, rpchost, RPCPORT_REGTEST, rpcfile); } catch (MalformedURLException e) { return null; } } public static URL getStablePublicMainNetURL() { try { return new URL(rpcssl, stableMscRpcHost, RPCPORT_MAINNET, rpcfile); } catch (MalformedURLException e) { return null; } } }
29.188679
84
0.641888
7bcfdb3bbebd5be739805bf85438b32881aec772
1,870
package website.skylorbeck.minecraft.ghostmod.client; import net.minecraft.client.render.entity.BipedEntityRenderer; import net.minecraft.client.render.entity.EntityRendererFactory; import net.minecraft.client.render.entity.feature.ArmorFeatureRenderer; import net.minecraft.client.render.entity.model.EntityModelLayer; import net.minecraft.client.render.entity.model.EntityModelLayers; import net.minecraft.client.render.entity.model.ZombieEntityModel; import net.minecraft.entity.mob.ZombieEntity; import net.minecraft.util.Identifier; public class GhostZombieEntityRenderer <T extends ZombieEntity, M extends ZombieEntityModel<T>> extends BipedEntityRenderer<T, M> { private static final Identifier TEXTURE = new Identifier("ghostmod:textures/entity/zombie/zombie.png"); public GhostZombieEntityRenderer(EntityRendererFactory.Context context) { this(context, EntityModelLayers.ZOMBIE, EntityModelLayers.ZOMBIE_INNER_ARMOR, EntityModelLayers.ZOMBIE_OUTER_ARMOR); } public GhostZombieEntityRenderer(EntityRendererFactory.Context ctx, EntityModelLayer layer, EntityModelLayer legsArmorLayer, EntityModelLayer bodyArmorLayer) { this(ctx, new ZombieEntityModel(ctx.getPart(layer)), new ZombieEntityModel(ctx.getPart(legsArmorLayer)), new ZombieEntityModel(ctx.getPart(bodyArmorLayer))); } public GhostZombieEntityRenderer(EntityRendererFactory.Context ctx, ZombieEntityModel bodyModel, ZombieEntityModel legsArmorModel, ZombieEntityModel bodyArmorModel) { super(ctx, (M) bodyModel, 0.5F); this.addFeature(new ArmorFeatureRenderer(this, legsArmorModel, bodyArmorModel)); } public Identifier getTexture(ZombieEntity zombieEntity) { return TEXTURE; } protected boolean isShaking(T zombieEntity) { return super.isShaking(zombieEntity) || zombieEntity.isConvertingInWater(); } }
53.428571
170
0.806417
8ab18c58146c836533e94eafe4d0e853e2e90cb3
154
package creationalPatterns.factoryMethod; public class WhiteCar extends Car { @Override void setColor() { color = "white"; } }
14
41
0.62987
8683c7418399244e191d27cbce4e8fea06df7b3f
443
package edu.psu.compbio.seqcode.gse.datasets.seqdata; import java.util.Comparator; public class SeqAnalysisResultEnrichmentComparator implements Comparator<SeqAnalysisResult> { public boolean equals(Object o) { return o instanceof SeqAnalysisResultEnrichmentComparator; } public int compare(SeqAnalysisResult a, SeqAnalysisResult b) { return Double.compare(b.getFoldEnrichment(), a.getFoldEnrichment()); } }
31.642857
93
0.769752
41cd967fc4eb3b4919275686fc6c64c551a69b15
507
package chapter03.section01.thread_3_1_11.pro_3_stack_1; /** * Project Name:java-multi-thread-programming <br/> * Package Name:chapter03.section01.thread_3_1_11.pro_3_stack_1 <br/> * Date:2019/11/23 14:35 <br/> * * @author <a href="[email protected]">chenzy</a><br/> */ public class C { private MyStack myStack; public C(MyStack myStack) { super(); this.myStack = myStack; } public void popService() { System.out.println("pop=" + myStack.pop()); } }
21.125
69
0.646943
0a2f65b060ef8fb270c10e162f19bff2cfc33778
2,483
package com.midtrans.sdk.corekit.models; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; /** * Contains information required to execute BCA KlikPay request. * * @author rakawm */ public class BCAKlikPayModel extends TransactionModel { public static final String PAYMENT_TYPE = "bca_klikpay"; /** * payment_type : bca_klik_pay bca_klikpay : BCAKlikPayDescriptionModel Object * transaction_details : {"gross_amount":"100","order_id":"10938011"} */ @SerializedName("bca_klikpay") private BCAKlikPayDescriptionModel bcaKlikPayDescriptionModel; /** * Default constructor for creating this class' object. * * @param bcaKlikPayDescriptionModel BCA specific transaction description. * @param transactionDetails Transaction details. * @param itemDetails List of item detail. * @param billingAddresses List of billing address. * @param shippingAddresses List of shipping address. * @param customerDetails Detail of the customer. */ public BCAKlikPayModel(BCAKlikPayDescriptionModel bcaKlikPayDescriptionModel, TransactionDetails transactionDetails, ArrayList<ItemDetails> itemDetails, ArrayList<BillingAddress> billingAddresses, ArrayList<ShippingAddress> shippingAddresses, CustomerDetails customerDetails) { setBcaKlikPayDescriptionModel(bcaKlikPayDescriptionModel); setTransactionDetails(transactionDetails); this.paymentType = PAYMENT_TYPE; this.itemDetails = itemDetails; this.billingAddresses = billingAddresses; this.shippingAddresses = shippingAddresses; this.customerDetails = customerDetails; } public String getPaymentType() { return PAYMENT_TYPE; } public TransactionDetails getTransactionDetails() { return transactionDetails; } public void setTransactionDetails(TransactionDetails transactionDetails) { this.transactionDetails = transactionDetails; } public BCAKlikPayDescriptionModel getBcaKlikPayDescriptionModel() { return bcaKlikPayDescriptionModel; } public void setBcaKlikPayDescriptionModel(BCAKlikPayDescriptionModel bcaKlikPayDescriptionModel) { this.bcaKlikPayDescriptionModel = bcaKlikPayDescriptionModel; } }
36.514706
102
0.697141
5dc1ee329d908d2d993a1d9b200f0a70e5501f7d
710
package com.zyb.coolweather.utils; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; public class MyAdapter extends FragmentPagerAdapter { private List<MyBaseFragment> list; public MyAdapter(FragmentManager fm,List<MyBaseFragment>list) { super(fm); this.list = list; // TODO Auto-generated constructor stub } @Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub return list.get(arg0); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } }
20.882353
64
0.76338
9b079b0f0e8462e4d5cafe6cf768f361213505e5
2,351
package com.github.cc3002.finalreality.model.character.player; import com.github.cc3002.finalreality.model.character.Enemy; import com.github.cc3002.finalreality.model.weapon.IWeapon; import com.github.cc3002.finalreality.model.weapon.StaffWeapon; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * Set of tests for the White Mage character. * * @author Sebastian Olmos. * @see WhiteMage */ public class WhiteMageTest extends AbstractPlayerTest { private static final String WHITE_MAGE_NAME = "Eiko"; /** * Setup method. * Creates a new white mage named Eiko with 10 speed and links it to a turn queue. * Create the main weapon */ @BeforeEach void setUp() { super.basicSetup(new StaffWeapon("mainWeapon", 3, 10)); super.assignCharacter(new WhiteMage(turns, WHITE_MAGE_NAME)); } /** * Checks that the class' constructor and equals method works properly. */ @Test void constructorTest() { super.checkConstruction(new WhiteMage(turns, WHITE_MAGE_NAME), new WhiteMage(turns, "Test"), new Knight(turns, WHITE_MAGE_NAME), new Enemy("Enemy", 10, turns)); assertNotEquals(testCharacter, new BlackMage(turns, WHITE_MAGE_NAME)); super.checkSameClassConstruction( new WhiteMage(turns, "CHARACTER_NAME", 100, 20), new WhiteMage(turns, "OTHER_NAME", 100, 20), new WhiteMage(turns, "CHARACTER_NAME", 200, 20), new WhiteMage(turns, "CHARACTER_NAME", 100, 10)); assertEquals(testCharacter.getCharacterClass(), CharacterClass.WHITE_MAGE); } /** * Checks that the White Mage character only equip compatible weapons. */ @Test void weaponEquipmentTest(){ ArrayList<IWeapon> supported = new ArrayList<>(Arrays.asList( testStaff )); equipSupportedWeapons(supported); ArrayList<IWeapon> unSupported = new ArrayList<>(Arrays.asList( testSword, testAxe, testBow, testKnife )); equipUnsupportedWeapons(unSupported); } }
32.652778
86
0.670778
b64171d68625ad53624f7ce382d0ce68e8379792
2,092
package sam.io.serilizers; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.nio.file.Path; import java.util.Objects; import sam.io.IOConstants; import sam.io.WritableByteChannelCustom; public class StringWriter2 { private CharsetEncoder encoder; private boolean append; private ByteBuffer buffer; public void encoder(Charset charset) { this.encoder = IOConstants.newEncoder(charset); } public StringWriter2 encoder(CharsetEncoder encoder) { this.encoder = Objects.requireNonNull(encoder); return this; } public StringWriter2 buffer(ByteBuffer buffer) { this.buffer = buffer; return this; } public StringWriter2 append(boolean append) { this.append = append; return this; } public void encoder(Charset charset, CodingErrorAction onUnmappableCharacter, CodingErrorAction onMalformedInput) { this.encoder = charset.newEncoder() .onMalformedInput(onMalformedInput) .onUnmappableCharacter(onUnmappableCharacter); } public void write(CharSequence data, WritableByteChannel target) throws IOException { StringIOUtils.write(WritableByteChannelCustom.of(target, buffer), data, encoder); if(buffer != null) buffer.clear(); } public void write(CharSequence data, Path target) throws IOException { try(FileChannel fc = FileChannel.open(target, CREATE, WRITE, append ? APPEND : TRUNCATE_EXISTING)) { write(data, fc); } } public static void setText(Path path, CharSequence data) throws IOException{ new StringWriter2().write(data, path); } public static void appendText(Path path, CharSequence data) throws IOException{ new StringWriter2().append(true).write(data, path); } }
30.318841
116
0.784417
137b9e08882135eb9d324686f2bbdd18a348d279
8,511
package cc.mrbird.common.util; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class Constant { static final String XLSX_SUFFIX = ".xlsx"; static final String XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; /** * 默认时间格式 */ public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 小红花默认发放时间 09:00:00 */ public static final String DEFAULT_DATE_TIME = " 09:00:00"; public static final String AccessKey = "ZjT_FX0FsSXMHBjKzEfA90BzyEoT0-O_B67QRPiL"; public static final String SecretKey = "DxEBsZxKo4NdiLUi5QBKliLYVFffrs9dOTpeL9gP"; public static final String bucket = "ywy-pro"; /** * 无头像用户展示照片 */ public static final String NOT_HEAD_IMAGE = "http://yycmedia.image.alimmdn.com/RetailShare/d981c674-10dc-4861-9422-1fd4a8240b91"; /** * 一次同步日志的默认条数 */ public static final Integer SYNC_LOG_NUMBER = 1000; /** * 福利充值系统交易号在redis中key */ public static final String WELFARE_RECHARGE_KEY = "welfare_recharge_key"; /** * 福利账户交易流水号在redis中key */ public static final String WELFARE_SERIAL_KEY = "welfare_serial_key"; /** * 固定时间发放积分在redis中key */ public static final String FIXED_REWARD_KEY = "fixed_reward_key"; /** * 日期格式 */ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; /** * Latin-1字符格式 */ public static final String LATIN_1_ENCODING = "ISO-8859-1"; /** * 默认字符格式 */ public static final String DEFAULT_ENCODING = "UTF-8"; /** * 是否 (正常),是1 */ public static final Byte DEFULT_YES = 1; /** * 是否(不正常) ,否0 */ public static final Byte DEFULT_NO = 0; /** * 默认最大时间 */ public static final String DEFAULT_MAX_DATE = "3000"; /** * 商品默认skardingKey */ public static final Long DEFAULT_SHARDING_KEY = 2016010000000000L; /** * 导出excel异常的后缀标识 */ public static final String SUFFIX_EXCEL_ERROR = "_EXCEL_ERROR"; /** * 预付款充值系统交易号在redis中key */ public static final String RECHARGE_KEY = "recharge_key"; /** * 系统异常的后缀标识 */ public static final String MSG_SYSTEM_EXCEPTION = "系统可能存在网络中断、数据库无法连接,内存不足等系统性问题,请与管理员联系。"; /** * 批量更新成功的后缀标识 */ public static final String SUFFIX_BATCH_SUCCESS = "_BATCH_SUCCESS"; /** * 批量更新失败的后缀标识 */ public static final String SUFFIX_BATCH_ERROR = "_BATCH_ERROR"; /** * 蜂采易订单自动更新已完成状态的设置时间名称 */ public static final String CHANNEL_UPDATE_STATUS_FINISH = "ordChannelStatusFinished"; /** * 普通订单自动更新已收货状态的设置时间名称 */ public static final String UPDATE_STATUS_COM_RECEIPT = "ordCommonReceiptTime"; /** * 跨境订单自动更新已收货状态的设置时间名称 */ public static final String UPDATE_STATUS_CROSS_RECEIPT = "ordCrossReceiptTime"; /** * 同步到来店易记录最多100条 */ public static final Integer MAX_SYNC_NUM = 100; /** * 采购订单自动更新已完成状态的设置时间名称 */ public static final String UPDATE_STATUS_FINISH = "ordStatusFinished"; /** * Json格式化对象 */ public static final ObjectMapper OBJECT_MAPPAER = new ObjectMapper(); static { OBJECT_MAPPAER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); OBJECT_MAPPAER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } /** * 订单来源:蜂采易交易单号 */ public static final String SOURCE_FCY = "7"; /** * 预付款交易流水号在redis中key */ public static final String SERIAL_KEY = "serial_key"; /** * 订单号在redis中key */ public static final String ORDER_KEY = "order_key"; /** * 分页默认页数 */ public static final int DEFAULT_PAGE = 0; /** * 分页默认数据数量 */ public static final int DEFAULT_SIZE = 20; /** * 不分页默认全量 */ public static final int DEFAULT_ALL = -1; /** * 设置cookie过期时间为1年 */ public static final int EXPIRATION_TIME = 365 * 24 * 60 * 60; /** * 设置直采易cookie过期时间 */ public static final int ENTERPRISE_LOGOUT_TIME = 60 * 60; /** * 未设置订单更新为已完成时间时取该默认时间(单位:小时) */ public static final Integer DEFAULT_DATE = 15 * 24; /** * 设置session超时时间(单位:秒) */ public static final int SESSION_TIMEOUT = 7200; /** * 必填字段的默认值 */ public static final Long DEFAULT_LONG = 0L; /** * 必填字段的默认值 */ public static final Integer DEFAULT_INT = 0; /** * 必填字段的默认值 */ public static final Byte DEFAULT_BYTE = 0; /** * 初始化密码 */ public static final String DEFAULT_PWD = "888888"; /** * 查询类型 1:按创建时间查询 */ public static final Byte QUERY_TYPE = 1; /** * APP对接请求超时时间(默认24小时,86400000ms) */ public static final String APP_REQUEST_TIME_OUT = "appRequestTimeOut"; /** * 无头像用户展示照片 */ public static final String DEFAULT_IMAGE = "http://yycmedia.image.alimmdn.com/RetailShare/d981c674-10dc-4861-9422-1fd4a8240b91"; /** * 顽兔生成圆角参数 */ public static final String WAN_TU_PARAMETER = "@100w_100h_1e_1c_25-2ci"; /** * 直采易商城信息 */ public static final String ENTERPRISE_STORE_INFO = "enterprise_store_info"; /** * 直采易商城子账号信息 */ public static final String ENTERPRISE_STORE_USER_INFO = "enterprise_store_user_info"; /** * 直采易商城资源权限 */ public static final String ENTERPRISE_STORE_RESOURCE = "enterprise_store_resource"; /** * 预存款确认充值短信通知号码 */ public static final String RECHARGE_SMS_CHECK_PHONE = "rechargeSmsCheckPhone"; /** * 商品中心-编辑图片时,限制图片大小 读取系统设置 */ public static final String IMAGE_LIMIT_SIZE = "imageLimitSize"; /** * 商品中心-编辑图片时,限制图片宽高 读取系统设置 */ public static final String IMAGE_LIMIT_WIDTH = "imageLimitWidth"; /** * 商品中心-编辑图片时,限制图片大小默认 最大不超过200k */ public static final int IMAGE_DEFAULT_SIZE = 200 * 1000; /** * 商品中心-编辑图片时,限制图片宽高默认 最大不超过800像素 */ public static final int IMAGE_DEFAULT_WIDTH = 800; /** * GBK编码 */ public static final String ENCODING_GBK = "GBK"; /** * 友盟推送消息最多一次50条 */ public static final Integer MAX_SYNC_NUM_YM = 50; /** * 降序 */ public static final Integer SORT_DESC = 0; /** * 升序 */ public static final Integer SORT_ASC = 1; /** * 物流对照字典组名称 */ public static final String EXPRESS_COMPARE = "ExpressCompare"; /** * 等于 */ public static final String OPERATE_EQUAL = "equal"; /** * 不等于 */ public static final String OPERATE_UNEQUAL = "unequal"; /** * 升序 */ public static final String DIRECTION_ASC = "asc"; /** * 降序 */ public static final String DIRECTION_DESC = "desc"; /** * 默认sku单位 */ public static final String DEFAULT_UNIT = "件"; /** * 默认sku单位 */ public static final String DEFAULT_PSD_TYPE = "/psd"; /** * 海关限额 */ public static final String CUSTOMS_QUOTA = "customsQuota"; /** * 短信默认前缀 */ public static final String SMS_PREFIX_FCY = "【蜂采易】"; /** * 用户标识 */ public static final String USER_NAME_FLAG = "FCY_USERNAME"; /** * 代理商shardingKey */ public static final String CHANNEL_SHARDINGKEY = "FCY_SHARDINGKEY"; /** * 获取平台商家id */ public static final String CHANNELID = "channelId"; /** * 商城企业id */ public static final String ENTERPRISE_STORE_ID = "enterprise_store_id"; /** * 微信小程序第三放session key */ public static final String MINI_PROGRAM_THIRD_SESSION_KEY = "mini_program_third_session_key"; /** * API项目 SESSION */ public static final String WEB_API_SESSION = "webApiSession"; /** * 是否授权全部商品:1是 0否 */ public static final Byte IS_HAVE_ALL_GOODS = 1; /** * 是否授权全部商品:1是 0否 */ public static final Byte NOT_HAVE_ALL_GOODS = 0; /** * 微信门店id */ public static final String WECHAT_STORE_ID = "wechat_store_id"; /** * 短信默认类型 0为通知 */ public static final String SMS_NOTICFE = "0"; /** * 微信开放平台服务器推送ticket 10分钟推送一次 */ public static final String COMPONET_VERIFY_TICKET = "component_verify_ticket"; /** * 微信开放平台component_access_token */ public static final String COMPONET_ACCESS_TOKEN = "component_access_token"; /** * redis 失效时间(单位:分钟) */ public static final Long REDIS_CLEAR_TIME = 30L; /** * 调用微信接口返回代码 */ public static final Integer WX_ERROR_CODE = 0; /** * 调用微信接口返回代码(TOKEN过期) */ public static final Integer WX_ERROR_CODE_EXPIRED = 42001; /** * 小程序模板的页面集合 */ public static final String MINIPROGRAM_PAGES = "miniprogram_pages"; /** * 每个ip每分钟最大访问次数 */ public static final String REQUEST_LIMIT_TIMES = "request_limit_times"; /** * 区域运营系统登录地址 */ public static final String KEY_FCY_LOGIN_URL = "fcy_login_url"; /** * 区域运营系统DES加密Key */ public static final String KEY_FCY_LOGIN_DES_KEY = "fcy_login_des_key"; /** * 开启负库存开关返回默认库存数 */ public static final int MINUS_INVENTORY_NUM = 9999; /** * 积分别名 */ public static final String REWARD_NICK_NAME = "REWARD_NICK_NAME"; }
19.040268
130
0.69745
a3675abd3cb84bc875e96968f30253ec5dd9b4b6
1,512
package org.group.jcommon.protobuf.jackson.buildin.deserializers; import java.io.IOException; import java.text.ParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.google.protobuf.Duration; import com.google.protobuf.util.Durations; public class DurationDeserializer extends StdDeserializer<Duration> { /** * */ private static final long serialVersionUID = 1L; public DurationDeserializer() { super(Duration.class); } @Override public Duration deserialize(final JsonParser parser, final DeserializationContext context) throws IOException { switch (parser.getCurrentToken()) { case VALUE_STRING: try { return Durations.parse(parser.getText()); } catch (final ParseException e) { throw context.weirdStringException(parser.getText(), Duration.class, e.getMessage()); } default: context.reportWrongTokenException(Duration.class, JsonToken.VALUE_STRING, wrongTokenMessage(context)); // the previous method should have thrown throw new AssertionError(); } } // TODO share this? private static String wrongTokenMessage(final DeserializationContext context) { return "Can not deserialize instance of com.google.protobuf.Duration out of " + context.getParser().currentToken() + " token"; } }
32.869565
118
0.738757
614bb639258adb7f5e4a40cadf035d1fde315a54
7,775
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/protobuf/saved_object_graph.proto package org.tensorflow.proto.framework; public interface SavedObjectOrBuilder extends // @@protoc_insertion_point(interface_extends:tensorflow.SavedObject) com.google.protobuf.MessageOrBuilder { /** * <pre> * Objects which this object depends on: named edges in the dependency * graph. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference children = 1;</code> */ java.util.List<org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.ObjectReference> getChildrenList(); /** * <pre> * Objects which this object depends on: named edges in the dependency * graph. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference children = 1;</code> */ org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.ObjectReference getChildren(int index); /** * <pre> * Objects which this object depends on: named edges in the dependency * graph. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference children = 1;</code> */ int getChildrenCount(); /** * <pre> * Objects which this object depends on: named edges in the dependency * graph. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference children = 1;</code> */ java.util.List<? extends org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.ObjectReferenceOrBuilder> getChildrenOrBuilderList(); /** * <pre> * Objects which this object depends on: named edges in the dependency * graph. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference children = 1;</code> */ org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.ObjectReferenceOrBuilder getChildrenOrBuilder( int index); /** * <pre> * Slot variables owned by this object. This describes the three-way * (optimizer, variable, slot variable) relationship; none of the three * depend on the others directly. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference slot_variables = 3;</code> */ java.util.List<org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.SlotVariableReference> getSlotVariablesList(); /** * <pre> * Slot variables owned by this object. This describes the three-way * (optimizer, variable, slot variable) relationship; none of the three * depend on the others directly. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference slot_variables = 3;</code> */ org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.SlotVariableReference getSlotVariables(int index); /** * <pre> * Slot variables owned by this object. This describes the three-way * (optimizer, variable, slot variable) relationship; none of the three * depend on the others directly. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference slot_variables = 3;</code> */ int getSlotVariablesCount(); /** * <pre> * Slot variables owned by this object. This describes the three-way * (optimizer, variable, slot variable) relationship; none of the three * depend on the others directly. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference slot_variables = 3;</code> */ java.util.List<? extends org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.SlotVariableReferenceOrBuilder> getSlotVariablesOrBuilderList(); /** * <pre> * Slot variables owned by this object. This describes the three-way * (optimizer, variable, slot variable) relationship; none of the three * depend on the others directly. * Note: currently only valid if kind == "user_object". * </pre> * * <code>repeated .tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference slot_variables = 3;</code> */ org.tensorflow.proto.framework.TrackableObjectGraph.TrackableObject.SlotVariableReferenceOrBuilder getSlotVariablesOrBuilder( int index); /** * <code>.tensorflow.SavedUserObject user_object = 4;</code> */ boolean hasUserObject(); /** * <code>.tensorflow.SavedUserObject user_object = 4;</code> */ org.tensorflow.proto.framework.SavedUserObject getUserObject(); /** * <code>.tensorflow.SavedUserObject user_object = 4;</code> */ org.tensorflow.proto.framework.SavedUserObjectOrBuilder getUserObjectOrBuilder(); /** * <code>.tensorflow.SavedAsset asset = 5;</code> */ boolean hasAsset(); /** * <code>.tensorflow.SavedAsset asset = 5;</code> */ org.tensorflow.proto.framework.SavedAsset getAsset(); /** * <code>.tensorflow.SavedAsset asset = 5;</code> */ org.tensorflow.proto.framework.SavedAssetOrBuilder getAssetOrBuilder(); /** * <code>.tensorflow.SavedFunction function = 6;</code> */ boolean hasFunction(); /** * <code>.tensorflow.SavedFunction function = 6;</code> */ org.tensorflow.proto.framework.SavedFunction getFunction(); /** * <code>.tensorflow.SavedFunction function = 6;</code> */ org.tensorflow.proto.framework.SavedFunctionOrBuilder getFunctionOrBuilder(); /** * <code>.tensorflow.SavedVariable variable = 7;</code> */ boolean hasVariable(); /** * <code>.tensorflow.SavedVariable variable = 7;</code> */ org.tensorflow.proto.framework.SavedVariable getVariable(); /** * <code>.tensorflow.SavedVariable variable = 7;</code> */ org.tensorflow.proto.framework.SavedVariableOrBuilder getVariableOrBuilder(); /** * <code>.tensorflow.SavedBareConcreteFunction bare_concrete_function = 8;</code> */ boolean hasBareConcreteFunction(); /** * <code>.tensorflow.SavedBareConcreteFunction bare_concrete_function = 8;</code> */ org.tensorflow.proto.framework.SavedBareConcreteFunction getBareConcreteFunction(); /** * <code>.tensorflow.SavedBareConcreteFunction bare_concrete_function = 8;</code> */ org.tensorflow.proto.framework.SavedBareConcreteFunctionOrBuilder getBareConcreteFunctionOrBuilder(); /** * <code>.tensorflow.SavedConstant constant = 9;</code> */ boolean hasConstant(); /** * <code>.tensorflow.SavedConstant constant = 9;</code> */ org.tensorflow.proto.framework.SavedConstant getConstant(); /** * <code>.tensorflow.SavedConstant constant = 9;</code> */ org.tensorflow.proto.framework.SavedConstantOrBuilder getConstantOrBuilder(); /** * <code>.tensorflow.SavedResource resource = 10;</code> */ boolean hasResource(); /** * <code>.tensorflow.SavedResource resource = 10;</code> */ org.tensorflow.proto.framework.SavedResource getResource(); /** * <code>.tensorflow.SavedResource resource = 10;</code> */ org.tensorflow.proto.framework.SavedResourceOrBuilder getResourceOrBuilder(); public org.tensorflow.proto.framework.SavedObject.KindCase getKindCase(); }
35.99537
127
0.717042
fab56007e04c9c6f6ccccefeb33c95c823c6f281
11,455
/* * Copyright (C) 2014 - 2016 Softwaremill <https://softwaremill.com> * Copyright (C) 2016 - 2020 Lightbend Inc. <https://www.lightbend.com> */ package akka.kafka.testkit.internal; import akka.annotation.InternalApi; import com.github.dockerjava.api.DockerClient; import org.rnorth.ducttape.unreliables.Unreliables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.Container; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.images.builder.Transferable; import org.testcontainers.lifecycle.Startable; import org.testcontainers.lifecycle.Startables; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.concurrent.TimeUnit.SECONDS; /** Provides an easy way to launch a Kafka cluster with multiple brokers. */ @InternalApi public class KafkaContainerCluster implements Startable { public static final String CONFLUENT_PLATFORM_VERSION = AlpakkaKafkaContainer.DEFAULT_CONFLUENT_PLATFORM_VERSION; public static final int START_TIMEOUT_SECONDS = 120; private static final String READINESS_CHECK_SCRIPT = "/testcontainers_readiness_check.sh"; private static final String READINESS_CHECK_TOPIC = "ready-kafka-container-cluster"; private static final Version BOOTSTRAP_PARAM_MIN_VERSION = new Version("5.2.0"); private final Logger log = LoggerFactory.getLogger(getClass()); private final Version confluentPlatformVersion; private final int brokersNum; private final Boolean useSchemaRegistry; private final Network network; private final GenericContainer zookeeper; private final Collection<AlpakkaKafkaContainer> brokers; private Optional<SchemaRegistryContainer> schemaRegistry; public KafkaContainerCluster(int brokersNum, int internalTopicsRf) { this(CONFLUENT_PLATFORM_VERSION, brokersNum, internalTopicsRf, false); } public KafkaContainerCluster( String confluentPlatformVersion, int brokersNum, int internalTopicsRf, boolean useSchemaRegistry) { if (brokersNum < 0) { throw new IllegalArgumentException("brokersNum '" + brokersNum + "' must be greater than 0"); } if (internalTopicsRf < 0 || internalTopicsRf > brokersNum) { throw new IllegalArgumentException( "internalTopicsRf '" + internalTopicsRf + "' must be less than brokersNum and greater than 0"); } this.confluentPlatformVersion = new Version(confluentPlatformVersion); this.brokersNum = brokersNum; this.useSchemaRegistry = useSchemaRegistry; this.network = Network.newNetwork(); this.zookeeper = new GenericContainer("confluentinc/cp-zookeeper:" + confluentPlatformVersion) .withNetwork(network) .withNetworkAliases("zookeeper") .withEnv("ZOOKEEPER_CLIENT_PORT", String.valueOf(AlpakkaKafkaContainer.ZOOKEEPER_PORT)); this.brokers = IntStream.range(0, this.brokersNum) .mapToObj( brokerNum -> new AlpakkaKafkaContainer(confluentPlatformVersion) .withNetwork(this.network) .withNetworkAliases("broker-" + brokerNum) .withRemoteJmxService() .dependsOn(this.zookeeper) .withExternalZookeeper("zookeeper:" + AlpakkaKafkaContainer.ZOOKEEPER_PORT) .withEnv("KAFKA_BROKER_ID", brokerNum + "") .withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", internalTopicsRf + "") .withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", internalTopicsRf + "") .withEnv( "KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", internalTopicsRf + "") .withEnv("KAFKA_TRANSACTION_STATE_LOG_MIN_ISR", internalTopicsRf + "")) .collect(Collectors.toList()); } public Network getNetwork() { return this.network; } public GenericContainer getZooKeeper() { return this.zookeeper; } public Optional<SchemaRegistryContainer> getSchemaRegistry() { return this.schemaRegistry; } public Collection<AlpakkaKafkaContainer> getBrokers() { return this.brokers; } public String getBootstrapServers() { return brokers.stream() .map(AlpakkaKafkaContainer::getBootstrapServers) .collect(Collectors.joining(",")); } public String getInternalNetworkBootstrapServers() { return IntStream.range(0, this.brokersNum) .mapToObj(brokerNum -> String.format("broker-%s:%s", brokerNum, "9092")) .collect(Collectors.joining(",")); } /** for backwards compatibility with Java 8 */ private <T> Stream<T> optionalStream(Optional<T> option) { if (option.isPresent()) return Stream.of(option.get()); else return Stream.empty(); } private Stream<GenericContainer> allContainers() { return Stream.concat( Stream.concat(this.brokers.stream(), Stream.of(this.zookeeper)), optionalStream(this.schemaRegistry)); } @Override public void start() { try { Stream<Startable> startables = this.brokers.stream().map(Startable.class::cast); Startables.deepStart(startables).get(START_TIMEOUT_SECONDS, SECONDS); this.brokers.stream() .findFirst() .ifPresent( broker -> { broker.copyFileToContainer( Transferable.of(readinessCheckScript().getBytes(StandardCharsets.UTF_8), 0777), READINESS_CHECK_SCRIPT); }); waitForClusterFormation(); this.schemaRegistry = useSchemaRegistry ? Optional.of( new SchemaRegistryContainer(confluentPlatformVersion.get()) .withNetworkAliases("schema-registry") .withCluster(this)) : Optional.empty(); // start schema registry if the container is initialized Startables.deepStart(optionalStream(this.schemaRegistry)).get(START_TIMEOUT_SECONDS, SECONDS); } catch (Exception ex) { throw new RuntimeException(ex); } } private void waitForClusterFormation() { // assert that cluster has formed Unreliables.retryUntilTrue( START_TIMEOUT_SECONDS, TimeUnit.SECONDS, () -> { Container.ExecResult result = this.zookeeper.execInContainer( "sh", "-c", "zookeeper-shell zookeeper:" + AlpakkaKafkaContainer.ZOOKEEPER_PORT + " ls /brokers/ids | tail -n 1"); String brokers = result.getStdout(); return brokers != null && brokers.split(",").length == this.brokersNum; }); // test produce & consume message with full cluster involvement Unreliables.retryUntilTrue( START_TIMEOUT_SECONDS, TimeUnit.SECONDS, () -> this.brokers.stream().findFirst().map(this::runReadinessCheck).orElse(false)); } public void stopKafka() { this.brokers.forEach(AlpakkaKafkaContainer::stopKafka); } public void startKafka() { this.brokers.forEach(AlpakkaKafkaContainer::startKafka); waitForClusterFormation(); } private String readinessCheckScript() { String connect = kafkaTopicConnectParam(); String command = "#!/bin/bash \n"; command += "set -e \n"; command += "[[ $(kafka-topics " + connect + " --describe --topic " + READINESS_CHECK_TOPIC + " | wc -l) > 1 ]] && " + "kafka-topics " + connect + " --delete --topic " + READINESS_CHECK_TOPIC + " \n"; command += "kafka-topics " + connect + " --topic " + READINESS_CHECK_TOPIC + " --create --partitions " + this.brokersNum + " --replication-factor " + this.brokersNum + " --config min.insync.replicas=" + this.brokersNum + " \n"; command += "MESSAGE=\"`date -u`\" \n"; command += "echo \"$MESSAGE\" | kafka-console-producer --broker-list localhost:9092 --topic " + READINESS_CHECK_TOPIC + " --producer-property acks=all \n"; command += "kafka-console-consumer --bootstrap-server localhost:9092 --topic " + READINESS_CHECK_TOPIC + " --from-beginning --timeout-ms 2000 --max-messages 1 | grep \"$MESSAGE\" \n"; command += "kafka-topics " + connect + " --delete --topic " + READINESS_CHECK_TOPIC + " \n"; command += "echo \"test succeeded\" \n"; return command; } private String kafkaTopicConnectParam() { if (this.confluentPlatformVersion.compareTo(BOOTSTRAP_PARAM_MIN_VERSION) >= 0) { return "--bootstrap-server localhost:9092"; } else { return "--zookeeper zookeeper:" + AlpakkaKafkaContainer.ZOOKEEPER_PORT; } } private Boolean runReadinessCheck(GenericContainer c) { try { Container.ExecResult result = c.execInContainer("sh", "-c", READINESS_CHECK_SCRIPT); if (result.getExitCode() != 0 || !result.getStdout().contains("test succeeded")) { log.debug( "Readiness check returned errors:\nSTDOUT:\n{}\nSTDERR\n{}", result.getStdout(), result.getStderr()); return false; } return true; } catch (Exception ex) { throw new RuntimeException(ex); } } @Override public void stop() { allContainers().parallel().forEach(GenericContainer::stop); } } @InternalApi class Version implements Comparable<Version> { private String version; public final String get() { return this.version; } public Version(String version) { if (version == null) throw new IllegalArgumentException("Version can not be null"); if (!version.matches("[0-9]+(\\.[0-9]+)*")) throw new IllegalArgumentException("Invalid version format"); this.version = version; } @Override public int compareTo(Version that) { if (that == null) return 1; String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); int length = Math.max(thisParts.length, thatParts.length); for (int i = 0; i < length; i++) { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; if (thisPart < thatPart) return -1; if (thisPart > thatPart) return 1; } return 0; } @Override public boolean equals(Object that) { if (this == that) return true; if (that == null) return false; if (this.getClass() != that.getClass()) return false; return this.compareTo((Version) that) == 0; } }
36.022013
101
0.62907
f80b389414418d00052e8d0a6f61425a02f94727
3,904
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.modules.forms.handler; import java.util.Locale; import java.util.UUID; import org.olat.core.CoreSpringFactory; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.impl.Form; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.modules.ceditor.PageElement; import org.olat.modules.ceditor.PageElementEditorController; import org.olat.modules.ceditor.PageElementRenderingHints; import org.olat.modules.ceditor.PageRunElement; import org.olat.modules.ceditor.SimpleAddPageElementHandler; import org.olat.modules.ceditor.ui.PageRunControllerElement; import org.olat.modules.forms.EvaluationFormsModule; import org.olat.modules.forms.model.xml.FileUpload; import org.olat.modules.forms.ui.FileUploadController; import org.olat.modules.forms.ui.FileUploadEditorController; import org.olat.modules.forms.ui.model.EvaluationFormExecutionElement; import org.olat.modules.forms.ui.model.EvaluationFormResponseController; import org.olat.modules.forms.ui.model.EvaluationFormResponseControllerElement; /** * * Initial date: 02.02.2018<br> * @author uhensler, [email protected], http://www.frentix.com * */ public class FileUploadHandler implements EvaluationFormElementHandler, SimpleAddPageElementHandler { private final boolean restrictedEdit; public FileUploadHandler(boolean restrictedEdit) { this.restrictedEdit = restrictedEdit; } @Override public String getType() { return "formfileupload"; } @Override public String getIconCssClass() { return "o_icon_fileupload"; } @Override public PageRunElement getContent(UserRequest ureq, WindowControl wControl, PageElement element, PageElementRenderingHints hints) { if(element instanceof FileUpload) { FileUpload fileUpload = (FileUpload) element; Controller ctrl = new FileUploadController(ureq, wControl, fileUpload); return new PageRunControllerElement(ctrl); } return null; } @Override public PageElementEditorController getEditor(UserRequest ureq, WindowControl wControl, PageElement element) { if(element instanceof FileUpload) { FileUpload fileUpload = (FileUpload) element; return new FileUploadEditorController(ureq, wControl, fileUpload, restrictedEdit); } return null; } @Override public PageElement createPageElement(Locale locale) { EvaluationFormsModule evaluationFormModule = CoreSpringFactory.getImpl(EvaluationFormsModule.class); FileUpload part = new FileUpload(); part.setId(UUID.randomUUID().toString()); part.setMaxUploadSizeKB(evaluationFormModule.getMaxFileUploadLimitKB()); return part; } @Override public EvaluationFormExecutionElement getExecutionElement(UserRequest ureq, WindowControl wControl, Form rootForm, PageElement element) { if (element instanceof FileUpload) { FileUpload fileUpload = (FileUpload) element; EvaluationFormResponseController ctrl = new FileUploadController(ureq, wControl, fileUpload, rootForm); return new EvaluationFormResponseControllerElement(ctrl); } return null; } }
36.148148
131
0.786629
13a3945037404b842a13cb009ffe4338b50d5de2
705
package io.nbs.ipfs.mm.ui.listener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * @Package : com.nbs.ui.listener * @Description : <p></p> * @Author : lambor.c * @Date : 2018/6/24-8:44 * Copyright (c) 2018, NBS , lambor.c<[email protected]>. * All rights reserved. */ public class AbstractMouseListener implements MouseListener { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
17.625
61
0.660993
8776e684e9b1d9547251a67a6657ae2446c85819
7,367
package com.mapswithme.maps.widget.placepage; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.facebook.ads.Ad; import com.facebook.ads.AdError; import com.facebook.ads.AdListener; import com.facebook.ads.NativeAd; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.Banner; import com.mapswithme.util.Config; import com.mapswithme.util.UiUtils; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.LoggerFactory; import com.mapswithme.util.statistics.Statistics; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static com.mapswithme.util.SharedPropertiesUtils.isShowcaseSwitchedOnLocal; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_CLICK; import static com.mapswithme.util.statistics.Statistics.EventName.PP_BANNER_SHOW; final class BannerController implements AdListener { private static final Logger LOGGER = LoggerFactory.INSTANCE .getLogger(LoggerFactory.Type.MISC); private static final String TAG = BannerController.class.getName(); private static final int MAX_MESSAGE_LINES = 100; private static final int MIN_MESSAGE_LINES = 3; private static final int MAX_TITLE_LINES = 2; private static final int MIN_TITLE_LINES = 1; private static boolean isTouched(@Nullable View view, @NonNull MotionEvent event) { return view != null && !UiUtils.isHidden(view) && UiUtils.isViewTouched(event, view); } @Nullable private Banner mBanner; @NonNull private final View mFrame; @NonNull private final ImageView mIcon; @NonNull private final TextView mTitle; @NonNull private final TextView mMessage; @NonNull private final TextView mActionSmall; @NonNull private final TextView mActionLarge; @NonNull private final View mAds; private final float mCloseFrameHeight; @Nullable private final BannerListener mListener; @Nullable private NativeAd mNativeAd; private boolean mOpened = false; private boolean mProgress = false; private boolean mError = false; BannerController(@NonNull View bannerView, @Nullable BannerListener listener) { mFrame = bannerView; mListener = listener; Resources resources = mFrame.getResources(); mCloseFrameHeight = resources.getDimension(R.dimen.placepage_banner_height); mIcon = (ImageView) bannerView.findViewById(R.id.iv__banner_icon); mTitle = (TextView) bannerView.findViewById(R.id.tv__banner_title); mMessage = (TextView) bannerView.findViewById(R.id.tv__banner_message); mActionSmall = (TextView) bannerView.findViewById(R.id.tv__action_small); mActionLarge = (TextView) bannerView.findViewById(R.id.tv__action_large); mAds = bannerView.findViewById(R.id.tv__ads); } private void showProgress() { mProgress = true; updateVisibility(); } private void hideProgress() { mProgress = false; updateVisibility(); } private boolean isDownloading() { return mProgress; } private void showError(boolean value) { mError = value; } boolean hasErrorOccurred() { return mError; } private void updateVisibility() { UiUtils.showIf(!hasErrorOccurred(), mFrame); if (isDownloading() || hasErrorOccurred()) { UiUtils.hide(mIcon, mTitle, mMessage, mActionSmall, mActionLarge, mAds); } else { UiUtils.show(mIcon, mTitle, mMessage, mActionSmall, mActionLarge, mAds); if (mOpened) UiUtils.hide(mActionSmall); else UiUtils.hide(mActionLarge, mIcon); } } void updateData(@Nullable Banner banner) { UiUtils.hide(mFrame); showError(false); mBanner = banner; if (mBanner == null || TextUtils.isEmpty(mBanner.getId()) || !isShowcaseSwitchedOnLocal() || Config.getAdForbidden()) return; mNativeAd = new NativeAd(mFrame.getContext(), mBanner.getId()); mNativeAd.setAdListener(BannerController.this); mNativeAd.loadAd(EnumSet.of(NativeAd.MediaCacheFlag.ICON)); UiUtils.show(mFrame); showProgress(); if (mOpened && mListener != null) mListener.onSizeChanged(); } boolean isBannerVisible() { return !UiUtils.isHidden(mFrame); } void open() { if (!isBannerVisible() || mNativeAd == null || mBanner == null || mOpened) return; mOpened = true; setFrameHeight(WRAP_CONTENT); loadIcon(mNativeAd); mMessage.setMaxLines(MAX_MESSAGE_LINES); mTitle.setMaxLines(MAX_TITLE_LINES); updateVisibility(); Statistics.INSTANCE.trackFacebookBanner(PP_BANNER_SHOW, mBanner, 1); } boolean close() { if (!isBannerVisible() || mNativeAd == null || mBanner == null || !mOpened) return false; mOpened = false; setFrameHeight((int) mCloseFrameHeight); UiUtils.hide(mIcon); mMessage.setMaxLines(MIN_MESSAGE_LINES); mTitle.setMaxLines(MIN_TITLE_LINES); updateVisibility(); return true; } int getLastBannerHeight() { return mFrame.getHeight(); } private void setFrameHeight(int height) { ViewGroup.LayoutParams lp = mFrame.getLayoutParams(); lp.height = height; mFrame.setLayoutParams(lp); } private void loadIcon(@NonNull NativeAd nativeAd) { UiUtils.show(mIcon); NativeAd.Image icon = nativeAd.getAdIcon(); NativeAd.downloadAndDisplayImage(icon, mIcon); } @Override public void onError(Ad ad, AdError adError) { showError(true); updateVisibility(); if (mListener != null) mListener.onSizeChanged(); LOGGER.e(TAG, adError.getErrorMessage()); Statistics.INSTANCE.trackFacebookBannerError(mBanner, adError, mOpened ? 1 : 0); } @Override public void onAdLoaded(Ad ad) { if (mNativeAd == null || mBanner == null) return; hideProgress(); updateVisibility(); mTitle.setText(mNativeAd.getAdTitle()); mMessage.setText(mNativeAd.getAdBody()); mActionSmall.setText(mNativeAd.getAdCallToAction()); mActionLarge.setText(mNativeAd.getAdCallToAction()); List<View> clickableViews = new ArrayList<>(); clickableViews.add(mTitle); clickableViews.add(mActionSmall); clickableViews.add(mActionLarge); mNativeAd.registerViewForInteraction(mFrame, clickableViews); if (UiUtils.isLandscape(mFrame.getContext())) { if (!mOpened) open(); else loadIcon(mNativeAd); } else if (!mOpened) { close(); Statistics.INSTANCE.trackFacebookBanner(PP_BANNER_SHOW, mBanner, 0); } else { loadIcon(mNativeAd); } if (mListener != null && mOpened) mListener.onSizeChanged(); } @Override public void onAdClicked(Ad ad) { if (mBanner == null) return; Statistics.INSTANCE.trackFacebookBanner(PP_BANNER_CLICK, mBanner, mOpened ? 1 : 0); } boolean isActionButtonTouched(@NonNull MotionEvent event) { return isTouched(mActionSmall, event) || isTouched(mActionLarge, event) || isTouched(mTitle, event); } interface BannerListener { void onSizeChanged(); } }
26.124113
93
0.714809
42e2576486abb5294aaa2bc795e77fee1894d2c6
357
package com.kornos.lint.demo.other; import com.android.tools.lint.detector.api.Detector; import java.util.List; /** * 避免混淆产生的实体类问题 * 实体类必须加@Keep */ public class EntityDetector extends Detector implements Detector.UastScanner{ @Override public List<String> getApplicableMethodNames() { return super.getApplicableMethodNames(); } }
19.833333
77
0.742297
e5ad6ad40295f871eb82c95c34facd85aa3f4894
2,734
package gov.nasa.pds.registry.common.meta; import java.util.HashSet; import java.util.Set; import gov.nasa.pds.registry.common.es.dao.dd.DataDictionaryDao; import gov.nasa.pds.registry.common.es.dao.schema.SchemaDao; /** * A cache of field names in Elasticsearch schema for the registry index. * @author karpenko */ public class FieldNameCache { private Set<String> schemaFieldNames; private Set<String> boolFieldNames; private Set<String> dateFieldNames; private SchemaDao schemaDao; private DataDictionaryDao ddDao; /** * Private constructor. Use getInstance() instead. */ public FieldNameCache(DataDictionaryDao ddDao, SchemaDao schemaDao) { schemaFieldNames = new HashSet<>(); boolFieldNames = new HashSet<>(); dateFieldNames = new HashSet<>(); this.ddDao = ddDao; this.schemaDao = schemaDao; } /** * Set field names present in "registry" Elasticsearch schema * @param fieldNames collection of field names */ public void setSchemaFieldNames(Set<String> fieldNames) { this.schemaFieldNames = fieldNames; } /** * Set boolean field names present in LDDs * @param fieldNames collection of field names */ public void setBooleanFieldNames(Set<String> fieldNames) { this.boolFieldNames = fieldNames; } /** * Set date field names present in LDDs * @param fieldNames collection of field names */ public void setDateFieldNames(Set<String> fieldNames) { this.dateFieldNames = fieldNames; } /** * Check if a field name is in the "registry" Elasticsearch schema. * @param name field name * @return true if field name is in "registry" schema. */ public boolean schemaContainsField(String name) { return schemaFieldNames.contains(name); } /** * Check if a field is a boolean field. * @param name field name * @return true if this is a boolean field */ public boolean isBooleanField(String name) { return boolFieldNames.contains(name); } /** * Check if a field is a date field. * @param name field name * @return true if this is a date field */ public boolean isDateField(String name) { return dateFieldNames.contains(name); } /** * Update cache * @throws Exception an exception */ public void update() throws Exception { setSchemaFieldNames(schemaDao.getFieldNames()); setBooleanFieldNames(ddDao.getFieldNamesByEsType("boolean")); setDateFieldNames(ddDao.getFieldNamesByEsType("date")); } }
24.630631
73
0.642648
ede008bde18c48ca01fa033485dc1f32071fbabd
640
package com.gb.rental.service; import com.gb.rental.model.reservation.VehicleReservationType; public class InvoiceServiceFactory { public InvoiceService getInvoiceService(VehicleReservationType vehicleReservationType) { switch (vehicleReservationType) { case FOUR_HOURS: case EIGHT_HOURS: return new PackageInvoiceServiceImpl(); case DAY: return new DayInvoiceService(); case MONTH: return new MonthInvoiceService(); case HOURLY: default: return new HourInvoiceService(); } } }
30.47619
92
0.621875
6eeb94a414fa8250470c5741f65a196142502ff0
331
package org.activitymgr.ui.web.logic; import org.activitymgr.ui.web.logic.IExternalContentDialogLogic.View; public interface IExternalContentDialogLogic extends ILogic<View> { public interface View extends ILogic.IView<IExternalContentDialogLogic> { void setTitle(String title); void setContentUrl(String url); } }
20.6875
74
0.797583
3dabaae6db7bea3fb270b4cf5cfafa9a21a99da1
4,147
/* %% * * JEvolve * * Copyright 2007 Jeff Ridder * * 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.ridderware.jevolve; /** * A GAIndividual with attributes for keeping track of the number of times it has been * evaluated. We expect this to be useful for noisy problems where the number of * evaluations assigned to an individual is some function of the number of times it * has already been evaluated relative to the rest of the population. * * @param E gene type. * @author Jeff Ridder */ public class EvaluationCountingGAIndividual<E> extends GAIndividual<E> { private int total_num_evaluations; private int assigned_evaluations; /** Creates a new instance of EvaluationCountingGAIndividual */ public EvaluationCountingGAIndividual() { super(); this.total_num_evaluations = 0; this.assigned_evaluations = 0; } /** * Constructor for the GAIndividual object * * @param numObjectives number of objectives */ public EvaluationCountingGAIndividual(int numObjectives) { super(numObjectives); this.total_num_evaluations = 0; this.assigned_evaluations = 0; } public int getAssignedEvaluations() { return assigned_evaluations; } public int getTotalNumEvaluations() { return total_num_evaluations; } public void setAssignedEvaluations(int assigned_evaluations) { this.assigned_evaluations = assigned_evaluations; } public void addTotalNumEvaluations(int num_evaluations) { this.total_num_evaluations += num_evaluations; } public void resetTotalNumEvaluations() { this.total_num_evaluations = 0; } public void accumulateFitness(double fitness, int num_evals) { double f = (this.getFitness() * this.total_num_evaluations + fitness * num_evals) / (this.total_num_evaluations + num_evals); this.setFitness(f); this.total_num_evaluations += num_evals; } public void accumulateFitness(double[] fitness, int num_evals) { for (int i = 0; i < this.getNumObjectives(); i++) { double f = (this.getFitness(i) * this.total_num_evaluations + fitness[i] * num_evals) / (this.total_num_evaluations + num_evals); this.setFitness(i, f); } this.total_num_evaluations += num_evals; } /** * Clones the individual. This is very useful during breeding. * * @return a clone of the individual. */ @Override public EvaluationCountingGAIndividual<E> clone() { EvaluationCountingGAIndividual<E> obj = (EvaluationCountingGAIndividual<E>) super.clone(); obj.assigned_evaluations = this.assigned_evaluations; obj.total_num_evaluations = this.total_num_evaluations; return obj; } /** * Deep copies the individual. Deep copies ensure that the individual * has its own copies of "deep" attributes, and not just sharing with somebody else. * * @param obj individual to be deep copied. */ @Override public void deepCopy(Individual obj) { super.deepCopy(obj); EvaluationCountingGAIndividual<E> ga_obj = (EvaluationCountingGAIndividual<E>) obj; this.assigned_evaluations = ga_obj.assigned_evaluations; this.total_num_evaluations = ga_obj.total_num_evaluations; } }
29.834532
89
0.649144
4745eb4870ea3be6ccfcec1b566cefc47148c607
16,472
package rr.snowhack.snow.event; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.gui.inventory.GuiShulkerBox; import net.minecraft.entity.passive.AbstractHorse; import net.minecraftforge.client.event.ClientChatEvent; import net.minecraftforge.client.event.InputUpdateEvent; import net.minecraftforge.client.event.PlayerSPPushOutOfBlocksEvent; import net.minecraftforge.client.event.RenderBlockOverlayEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.client.event.RenderGameOverlayEvent.Pre; import net.minecraftforge.client.event.RenderPlayerEvent.Post; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent.Start; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock; import net.minecraftforge.event.world.ChunkEvent.Load; import net.minecraftforge.event.world.ChunkEvent.Unload; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import rr.snowhack.snow.SnowMod; import rr.snowhack.snow.command.Command; import rr.snowhack.snow.command.commands.PeekCommand; import rr.snowhack.snow.event.events.DisplaySizeChangedEvent; import rr.snowhack.snow.gui.UIRenderer; import rr.snowhack.snow.gui.rgui.component.container.use.Frame; import rr.snowhack.snow.gui.snow.SnowGUI; import rr.snowhack.snow.module.ModuleManager; import rr.snowhack.snow.module.modules.render.BossStack; import rr.snowhack.snow.util.SnowTessellator; import rr.snowhack.snow.util.Wrapper; public class ForgeEventProcessor { // $FF: synthetic field private int displayHeight; // $FF: synthetic field private static final String[] lIIIlIIIlIIll; // $FF: synthetic field static final Minecraft mc; // $FF: synthetic field private int displayWidth; // $FF: synthetic field private static final int[] lIIIlIIIlIllI; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent lllllllllllllllIIlllIlIllIIIllII) { if (!lIlIlllIlllIlI(lllllllllllllllIIlllIlIllIIIllII.isCanceled())) { ModuleManager.onWorldRender(lllllllllllllllIIlllIlIllIIIllII); } } private static boolean lIlIlllIllllIl(Object var0) { return var0 != null; } @SubscribeEvent public void onRenderBlockOverlay(RenderBlockOverlayEvent lllllllllllllllIIlllIlIlIlIIIlll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIIIlll); } private static void lIlIlllIlllIIl() { lIIIlIIIlIllI = new int[9]; lIIIlIIIlIllI[0] = (56 ^ 33) & ~(13 ^ 20); lIIIlIIIlIllI[1] = " ".length(); lIIIlIIIlIllI[2] = " ".length() << " ".length(); lIIIlIIIlIllI[3] = " ".length(); lIIIlIIIlIllI[4] = " ".length() << (" ".length() << " ".length()); lIIIlIIIlIllI[5] = 7 ^ 2; lIIIlIIIlIllI[6] = " ".length() << " ".length(); lIIIlIIIlIllI[7] = (94 ^ 75) << " ".length() ^ 137 ^ 164; lIIIlIIIlIllI[8] = " ".length() << " ".length(); } private static boolean lIlIlllIlllIll(int var0, int var1) { return var0 == var1; } private static boolean lIlIlllIlllllI(Object var0) { return var0 == null; } @SubscribeEvent public void onLivingDamageEvent(LivingDamageEvent lllllllllllllllIIlllIlIlIlIllIll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIllIll); } @SubscribeEvent( priority = EventPriority.HIGHEST ) public void onPlayerDrawn(Post lllllllllllllllIIlllIlIlIlllIIII) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlllIIII); } private static boolean lIlIlllIllllII(int var0, int var1) { return var0 != var1; } @SubscribeEvent public void onUpdate(LivingUpdateEvent lllllllllllllllIIlllIlIllIIlIlll) { if (!lIlIlllIlllIlI(lllllllllllllllIIlllIlIllIIlIlll.isCanceled())) { if (!lIlIlllIlllIll(mc.field_71443_c, lllllllllllllllIIlllIlIllIIlIllI.displayWidth) || lIlIlllIllllII(mc.field_71440_d, lllllllllllllllIIlllIlIllIIlIllI.displayHeight)) { SnowMod.EVENT_BUS.post(new DisplaySizeChangedEvent()); lllllllllllllllIIlllIlIllIIlIllI.displayWidth = mc.field_71443_c; lllllllllllllllIIlllIlIllIIlIllI.displayHeight = mc.field_71440_d; SnowMod.getInstance().getGuiManager().getChildren().stream().filter((lllllllllllllllIIlllIlIlIlIIIIlI) -> { return lllllllllllllllIIlllIlIlIlIIIIlI instanceof Frame; }).forEach((lllllllllllllllIIlllIlIlIlIIIlIl) -> { SnowGUI.dock((Frame)lllllllllllllllIIlllIlIlIlIIIlIl); }); } if (lIlIlllIllllIl(PeekCommand.sb)) { String lllllllllllllllIIlllIlIllIIlIlII = new ScaledResolution(mc); int lllllllllllllllIIlllIlIllIIllIll = lllllllllllllllIIlllIlIllIIlIlII.func_78326_a(); double lllllllllllllllIIlllIlIllIIlIIlI = lllllllllllllllIIlllIlIllIIlIlII.func_78328_b(); GuiShulkerBox lllllllllllllllIIlllIlIllIIllIIl = new GuiShulkerBox(Wrapper.getPlayer().field_71071_by, PeekCommand.sb); lllllllllllllllIIlllIlIllIIllIIl.func_146280_a(Wrapper.getMinecraft(), lllllllllllllllIIlllIlIllIIllIll, lllllllllllllllIIlllIlIllIIlIIlI); mc.func_147108_a(lllllllllllllllIIlllIlIllIIllIIl); PeekCommand.sb = null; } } } @SubscribeEvent public void onPlayerPush(PlayerSPPushOutOfBlocksEvent lllllllllllllllIIlllIlIlIlIlIIll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIlIIll); } @SubscribeEvent public void onRenderPre(Pre lllllllllllllllIIlllIlIllIIIIlll) { if (lIlIlllIllllll(lllllllllllllllIIlllIlIllIIIIlll.getType(), ElementType.BOSSINFO) && lIlIlllIlllIlI(ModuleManager.isModuleEnabled(lIIIlIIIlIIll[lIIIlIIIlIllI[0]]))) { lllllllllllllllIIlllIlIllIIIIlll.setCanceled((boolean)lIIIlIIIlIllI[1]); } } private static String lIlIlllIllIlIl(String lllllllllllllllIIlllIlIlIIlIllII, String lllllllllllllllIIlllIlIlIIlIlIll) { try { byte lllllllllllllllIIlllIlIlIIlIlIII = new SecretKeySpec(Arrays.copyOf(MessageDigest.getInstance("MD5").digest(lllllllllllllllIIlllIlIlIIlIlIll.getBytes(StandardCharsets.UTF_8)), lIIIlIIIlIllI[8]), "DES"); short lllllllllllllllIIlllIlIlIIlIIlll = Cipher.getInstance("DES"); lllllllllllllllIIlllIlIlIIlIIlll.init(lIIIlIIIlIllI[2], lllllllllllllllIIlllIlIlIIlIlIII); return new String(lllllllllllllllIIlllIlIlIIlIIlll.doFinal(Base64.getDecoder().decode(lllllllllllllllIIlllIlIlIIlIllII.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8); } catch (Exception var4) { var4.printStackTrace(); return null; } } @SubscribeEvent( priority = EventPriority.HIGHEST ) public void onPlayerDrawn(net.minecraftforge.client.event.RenderPlayerEvent.Pre lllllllllllllllIIlllIlIlIlllIlII) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlllIlII); } @SubscribeEvent public void onLeftClickBlock(LeftClickBlock lllllllllllllllIIlllIlIlIlIlIIII) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIlIIII); } @SubscribeEvent public void onLivingEntityUseItemEventTick(Start lllllllllllllllIIlllIlIlIllIIIII) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIllIIIII); } @SubscribeEvent( priority = EventPriority.HIGHEST ) public void onChatSent(ClientChatEvent lllllllllllllllIIlllIlIlIllllIII) { if (lIlIlllIlllIlI(lllllllllllllllIIlllIlIlIllllIII.getMessage().startsWith(Command.getCommandPrefix()))) { lllllllllllllllIIlllIlIlIllllIII.setCanceled((boolean)lIIIlIIIlIllI[1]); label22: { try { Wrapper.getMinecraft().field_71456_v.func_146158_b().func_146239_a(lllllllllllllllIIlllIlIlIllllIII.getMessage()); if (lIlIllllIIIIIl(lllllllllllllllIIlllIlIlIllllIII.getMessage().length(), lIIIlIIIlIllI[1])) { SnowMod.getInstance().commandManager.callCommand(lllllllllllllllIIlllIlIlIllllIII.getMessage().substring(Command.getCommandPrefix().length() - lIIIlIIIlIllI[1])); "".length(); if (null != null) { return; } } else { Command.sendChatMessage(lIIIlIIIlIIll[lIIIlIIIlIllI[3]]); } } catch (Exception var3) { var3.printStackTrace(); Command.sendChatMessage(String.valueOf((new StringBuilder()).append(lIIIlIIIlIIll[lIIIlIIIlIllI[4]]).append(var3.getMessage()).append(lIIIlIIIlIIll[lIIIlIIIlIllI[5]]))); break label22; } "".length(); if (((96 ^ 89) & ~(249 ^ 192)) >= " ".length() << " ".length()) { return; } } lllllllllllllllIIlllIlIlIllllIII.setMessage(lIIIlIIIlIIll[lIIIlIIIlIllI[6]]); } } private static boolean lIlIllllIIIIIl(int var0, int var1) { return var0 > var1; } @SubscribeEvent public void onTick(ClientTickEvent lllllllllllllllIIlllIlIllIIIllll) { if (!lIlIlllIlllllI(Wrapper.getPlayer())) { ModuleManager.onUpdate(); SnowMod.getInstance().getGuiManager().callTick(SnowMod.getInstance().getGuiManager()); } } private static boolean lIlIlllIllllll(Object var0, Object var1) { return var0 == var1; } @SubscribeEvent public void onAttackEntity(AttackEntityEvent lllllllllllllllIIlllIlIlIlIIlIll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIIlIll); } static { lIlIlllIlllIIl(); lIlIlllIlllIII(); mc = Minecraft.func_71410_x(); } @SubscribeEvent public void onChunkLoaded(Unload lllllllllllllllIIlllIlIlIllIlIII) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIllIlIII); } private static String lIlIlllIllIllI(String lllllllllllllllIIlllIlIlIIIlIlll, String lllllllllllllllIIlllIlIlIIIlIllI) { lllllllllllllllIIlllIlIlIIIlIlll = new String(Base64.getDecoder().decode(lllllllllllllllIIlllIlIlIIIlIlll.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); StringBuilder lllllllllllllllIIlllIlIlIIIllIlI = new StringBuilder(); Exception lllllllllllllllIIlllIlIlIIIlIlII = lllllllllllllllIIlllIlIlIIIlIllI.toCharArray(); int lllllllllllllllIIlllIlIlIIIllIII = lIIIlIIIlIllI[0]; int lllllllllllllllIIlllIlIlIIIlIIlI = lllllllllllllllIIlllIlIlIIIlIlll.toCharArray(); Exception lllllllllllllllIIlllIlIlIIIlIIIl = lllllllllllllllIIlllIlIlIIIlIIlI.length; int lllllllllllllllIIlllIlIlIIIlIIII = lIIIlIIIlIllI[0]; do { if (!lIlIllllIIIIlI(lllllllllllllllIIlllIlIlIIIlIIII, lllllllllllllllIIlllIlIlIIIlIIIl)) { return String.valueOf(lllllllllllllllIIlllIlIlIIIllIlI); } char lllllllllllllllIIlllIlIlIIIIllll = lllllllllllllllIIlllIlIlIIIlIIlI[lllllllllllllllIIlllIlIlIIIlIIII]; lllllllllllllllIIlllIlIlIIIllIlI.append((char)(lllllllllllllllIIlllIlIlIIIIllll ^ lllllllllllllllIIlllIlIlIIIlIlII[lllllllllllllllIIlllIlIlIIIllIII % lllllllllllllllIIlllIlIlIIIlIlII.length])); "".length(); ++lllllllllllllllIIlllIlIlIIIllIII; ++lllllllllllllllIIlllIlIlIIIlIIII; "".length(); } while(" ".length() >= 0); return null; } @SubscribeEvent public void onInputUpdate(InputUpdateEvent lllllllllllllllIIlllIlIlIllIIIll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIllIIIll); } private static boolean lIlIllllIIIIII(int var0) { return var0 == 0; } private static void lIlIlllIlllIII() { lIIIlIIIlIIll = new String[lIIIlIIIlIllI[7]]; lIIIlIIIlIIll[lIIIlIIIlIllI[0]] = lIlIlllIllIlIl("2dIr91MRPDBV2umhgp0GCw==", "OtssY"); lIIIlIIIlIIll[lIIIlIIIlIllI[1]] = lIlIlllIllIllI("DigXCjo4JgcS", "LGdyi"); lIIIlIIIlIIll[lIIIlIIIlIllI[2]] = lIlIlllIllIlll("aXiryXQQxBI=", "jwleL"); lIIIlIIIlIIll[lIIIlIIIlIllI[3]] = lIlIlllIllIllI("JC0HEAQRYQcfAxEzQhBXFy4PHBYaJUw=", "tAbqw"); lIIIlIIIlIIll[lIIIlIIIlIllI[4]] = lIlIlllIllIllI("MRQnKTFUCTYlNgYDMWY0HA85I2MGEzsoKhoBdSUsGQs0KCdVRn0=", "tfUFC"); lIIIlIIIlIIll[lIIIlIIIlIllI[5]] = lIlIlllIllIllI("Tg==", "gdQaB"); lIIIlIIIlIIll[lIIIlIIIlIllI[6]] = lIlIlllIllIllI("", "ZPBcI"); } private static boolean lIlIllllIIIIlI(int var0, int var1) { return var0 < var1; } @SubscribeEvent( priority = EventPriority.NORMAL, receiveCanceled = true ) public void onKeyInput(KeyInputEvent lllllllllllllllIIlllIlIlIllllllI) { if (!lIlIllllIIIIII(Keyboard.getEventKeyState())) { if (lIlIlllIlllIlI(String.valueOf((new StringBuilder()).append(lIIIlIIIlIIll[lIIIlIIIlIllI[2]]).append(Keyboard.getEventCharacter())).equalsIgnoreCase(Command.getCommandPrefix()))) { mc.func_147108_a(new GuiChat(Command.getCommandPrefix())); "".length(); if (((229 ^ 194) << (" ".length() << " ".length()) ^ 95 + 51 - 1 + 8) <= 0) { return; } } else { ModuleManager.onBind(Keyboard.getEventKey()); } } } @SubscribeEvent public void onRender(net.minecraftforge.client.event.RenderGameOverlayEvent.Post lllllllllllllllIIlllIlIllIIIIIIl) { if (!lIlIlllIlllIlI(lllllllllllllllIIlllIlIllIIIIIIl.isCanceled())) { Exception lllllllllllllllIIlllIlIllIIIIIII = ElementType.EXPERIENCE; if (lIlIllllIIIIII(Wrapper.getPlayer().func_184812_l_()) && lIlIlllIlllIlI(Wrapper.getPlayer().func_184187_bx() instanceof AbstractHorse)) { lllllllllllllllIIlllIlIllIIIIIII = ElementType.HEALTHMOUNT; } if (lIlIlllIllllll(lllllllllllllllIIlllIlIllIIIIIIl.getType(), lllllllllllllllIIlllIlIllIIIIIII)) { ModuleManager.onRender(); GL11.glPushMatrix(); UIRenderer.renderAndUpdateFrames(); GL11.glPopMatrix(); SnowTessellator.releaseGL(); "".length(); if (((123 ^ 30 ^ (86 ^ 107) << " ".length()) & ((4 ^ 23) << " ".length() ^ 86 + 0 - 7 + 56 ^ -" ".length())) > 0) { return; } } else if (lIlIlllIllllll(lllllllllllllllIIlllIlIllIIIIIIl.getType(), ElementType.BOSSINFO) && lIlIlllIlllIlI(ModuleManager.isModuleEnabled(lIIIlIIIlIIll[lIIIlIIIlIllI[1]]))) { BossStack.render(lllllllllllllllIIlllIlIllIIIIIIl); } } } private static boolean lIlIlllIlllIlI(int var0) { return var0 != 0; } private static String lIlIlllIllIlll(String lllllllllllllllIIlllIlIlIIllIlll, String lllllllllllllllIIlllIlIlIIllIllI) { try { SecretKeySpec lllllllllllllllIIlllIlIlIIllllII = new SecretKeySpec(MessageDigest.getInstance("MD5").digest(lllllllllllllllIIlllIlIlIIllIllI.getBytes(StandardCharsets.UTF_8)), "Blowfish"); int lllllllllllllllIIlllIlIlIIllIlII = Cipher.getInstance("Blowfish"); lllllllllllllllIIlllIlIlIIllIlII.init(lIIIlIIIlIllI[2], lllllllllllllllIIlllIlIlIIllllII); return new String(lllllllllllllllIIlllIlIlIIllIlII.doFinal(Base64.getDecoder().decode(lllllllllllllllIIlllIlIlIIllIlll.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8); } catch (Exception var4) { var4.printStackTrace(); return null; } } @SubscribeEvent public void onChunkLoaded(Load lllllllllllllllIIlllIlIlIllIlIll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIllIlIll); } @SubscribeEvent public void onEntityJoinWorldEvent(EntityJoinWorldEvent lllllllllllllllIIlllIlIlIlIlIlll) { SnowMod.EVENT_BUS.post(lllllllllllllllIIlllIlIlIlIlIlll); } }
44.639566
215
0.728205
50577025da59952f4471e75907a44a81afc8c26c
1,616
package mda.generator.beans; import mda.generator.exceptions.MdaGeneratorException; /** * Domain representing a type in the model file with some constraints : * - maxLength * - precision * * @author Fabien Crapart */ public class UmlDomain { private String name; private String typeName; private String maxLength; private String precision; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the typeName */ public String getTypeName() { return typeName; } /** * @param typeName the typeName to set */ public void setTypeName(String typeName) { if(typeName == null) { throw new MdaGeneratorException("GenericType undefined for domain " + name); } this.typeName = typeName; } /** * @return the maxLength */ public String getMaxLength() { return maxLength; } /** * @param maxLength the maxLength to set */ public void setMaxLength(String maxLength) { this.maxLength = maxLength; } /** * @return the precision */ public String getPrecision() { return precision; } /** * @param precision the precision to set */ public void setPrecision(String precision) { this.precision = precision; } public String toString() { return "\n\t" + name + "(" + typeName + ")" + (maxLength != null && !maxLength.equals("0")?" maxLength="+maxLength:"" + (precision != null && !precision.equals("0")?" precision="+precision:"") ); } }
20.987013
80
0.626238
6fa124222d981b8b609de3a0b077270e214a9bac
1,840
package com.mastertheboss.model; import java.io.Serializable; import javax.persistence.*; @Entity public class Info implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; private String address; private String city; private String state; public String toString() { return "address; = " + address+ " - city: " +city + " - state: " +state; } /* * the Child object I was adding to the Parent wasn't saved in the database yet. So when I added the Child to the Parent, then saved the Parent, Hibernate would toss the "object references an unsaved transient instance - save the transient instance before flushing" message when saving the Parent. Adding in the cascade = {CascadeType.ALL} on the Parent's reference to the Child solved the problem in both cases. This saved the Child and the Parent. */ @OneToOne(mappedBy = "info") private Worker worker; public Info() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public Worker getWorker() { return this.worker; } public void setWorker(Worker worker) { this.worker = worker; } }
23.896104
303
0.610326
15149226c6e98302702d7bc09242e15caebe12db
2,425
package appleoctopus.lastword; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.google.gson.Gson; import appleoctopus.lastword.firebase.FirebaseDB; import appleoctopus.lastword.models.Video; import appleoctopus.lastword.upload.UploadIntentService; import appleoctopus.lastword.util.SharePreference; import appleoctopus.lastword.util.Util; public class StoryActivity extends AppCompatActivity { private ImageView bgImageView; private ImageButton imageButton; private TextView textView; private int catogory; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_story); catogory = getIntent().getIntExtra(CategoryDetailActivity.CATEGORY_KEY, -1); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); startActivityForResult(takeVideoIntent, catogory); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { Uri videoUri = data.getData(); String path = Util.getPathFromUri(this, Uri.parse(videoUri.toString())); Video v = new Video(); v.setLocalVideoUri(videoUri.toString()); v.setCategory(requestCode); v.setLocalVideoPath(path); String videoKey = FirebaseDB.getInstance().saveNewVideo(v, SharePreference.getFirebaseId(this)); v.setVideoKey(videoKey); Intent intent = new Intent(Intent.ACTION_SYNC, null, this, UploadIntentService.class); intent.putExtra("url", path); intent.putExtra("video", new Gson().toJson(v)); startService(intent); finish(); } } }
34.15493
108
0.693608
a3698d1e08e9f96c6cddb44ee96ad3b0c644ef9a
2,165
/* * Copyright 2013-2019 the original author or 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 * * https://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 releaser.cloud.buildsystem; /** * @author Marcin Grzejszczak */ final class SpringCloudBomConstants { // boot static final String SPRING_BOOT = "spring-boot"; static final String BOOT_STARTER_ARTIFACT_ID = "spring-boot-starter"; static final String BOOT_STARTER_PARENT_ARTIFACT_ID = BOOT_STARTER_ARTIFACT_ID + "-parent"; static final String BOOT_DEPENDENCIES_ARTIFACT_ID = "spring-boot-dependencies"; // sc-build static final String CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID = "spring-cloud-dependencies-parent"; static final String BUILD_ARTIFACT_ID = "spring-cloud-build"; // sc-release static final String CLOUD_DEPENDENCIES_ARTIFACT_ID = "spring-cloud-dependencies"; static final String CLOUD_ARTIFACT_ID = "spring-cloud"; static final String CLOUD_RELEASE_ARTIFACT_ID = "spring-cloud-release"; static final String CLOUD_STARTER_ARTIFACT_ID = "spring-cloud-starter"; static final String CLOUD_STARTER_PARENT_ARTIFACT_ID = "spring-cloud-starter-parent"; // sc-stream static final String STREAM_DEPS_ARTIFACT_ID = "spring-cloud-stream-dependencies"; static final String STREAM_STARTER_ARTIFACT_ID = "spring-cloud-stream-starter"; static final String STREAM_STARTER_BUILD_ARTIFACT_ID = "spring-cloud-stream-starter-build"; static final String STREAM_STARTER_PARENT_ARTIFACT_ID = "spring-cloud-stream-starter-parent"; static final String STREAM_DOCS_ARTIFACT_ID = "spring-cloud-stream-docs"; private SpringCloudBomConstants() { throw new IllegalStateException("Don't instantiate a utility class"); } }
40.092593
96
0.785219
1db50aeebe451710ab8624ccd49895ff5fa602aa
1,615
package de.digitalcollections.iiif.model.jackson.serialization; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import de.digitalcollections.iiif.model.Profile; import de.digitalcollections.iiif.model.image.ImageApiProfile; import java.io.IOException; import java.net.URI; import java.util.stream.Stream; public class ProfileDeserializer extends JsonDeserializer<Profile> { private final JsonDeserializer<Object> defaultDeserializer; public ProfileDeserializer(JsonDeserializer<Object> defaultDeserializer) { this.defaultDeserializer = defaultDeserializer; } private boolean isImageApiProfile(final String profile) { return Stream.of(ImageApiProfile.LEVEL_ZERO, ImageApiProfile.LEVEL_ONE, ImageApiProfile.LEVEL_TWO) .map(p -> p.getIdentifier().toString()) .anyMatch(profile::equals) || ImageApiProfile.V1_PROFILES.contains(profile); } @Override public Profile deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.getCurrentToken() == JsonToken.VALUE_STRING) { if (isImageApiProfile(p.getValueAsString())) { return ImageApiProfile.fromUrl(p.getValueAsString()); } else { return new Profile(URI.create(p.getValueAsString())); } } else if (p.getCurrentToken() == JsonToken.START_OBJECT) { return p.getCodec().readValue(p, ImageApiProfile.class); } else { return (Profile) defaultDeserializer.deserialize(p, ctxt); } } }
38.452381
102
0.765325
d93d2df6eb1ca1aa646da5d439fa669cc3a48032
106,841
package com.hbm.main; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.logging.log4j.Logger; import com.hbm.blocks.ModBlocks; import com.hbm.blocks.generic.BlockCrate; import com.hbm.blocks.generic.EntityGrenadeTau; import com.hbm.capability.HbmCapability; import com.hbm.capability.RadiationCapability; import com.hbm.command.CommandHbm; import com.hbm.command.CommandRadiation; import com.hbm.config.BombConfig; import com.hbm.config.GeneralConfig; import com.hbm.config.MachineConfig; import com.hbm.config.MobConfig; import com.hbm.config.PotionConfig; import com.hbm.config.RadiationConfig; import com.hbm.config.ToolConfig; import com.hbm.config.WeaponConfig; import com.hbm.config.WorldConfig; import com.hbm.creativetabs.BlockTab; import com.hbm.creativetabs.ConsumableTab; import com.hbm.creativetabs.ControlTab; import com.hbm.creativetabs.MachineTab; import com.hbm.creativetabs.MissileTab; import com.hbm.creativetabs.NukeTab; import com.hbm.creativetabs.PartsTab; import com.hbm.creativetabs.TemplateTab; import com.hbm.creativetabs.WeaponTab; import com.hbm.entity.effect.EntityBlackHole; import com.hbm.entity.effect.EntityCloudFleija; import com.hbm.entity.effect.EntityCloudFleijaRainbow; import com.hbm.entity.effect.EntityCloudSolinium; import com.hbm.entity.effect.EntityCloudTom; import com.hbm.entity.effect.EntityEMPBlast; import com.hbm.entity.effect.EntityFalloutRain; import com.hbm.entity.effect.EntityNukeCloudBig; import com.hbm.entity.effect.EntityNukeCloudNoShroom; import com.hbm.entity.effect.EntityNukeCloudSmall; import com.hbm.entity.effect.EntityRagingVortex; import com.hbm.entity.effect.EntityVortex; import com.hbm.entity.grenade.EntityGrenadeASchrab; import com.hbm.entity.grenade.EntityGrenadeBlackHole; import com.hbm.entity.grenade.EntityGrenadeBreach; import com.hbm.entity.grenade.EntityGrenadeBurst; import com.hbm.entity.grenade.EntityGrenadeCloud; import com.hbm.entity.grenade.EntityGrenadeCluster; import com.hbm.entity.grenade.EntityGrenadeElectric; import com.hbm.entity.grenade.EntityGrenadeFire; import com.hbm.entity.grenade.EntityGrenadeFlare; import com.hbm.entity.grenade.EntityGrenadeFrag; import com.hbm.entity.grenade.EntityGrenadeGas; import com.hbm.entity.grenade.EntityGrenadeGascan; import com.hbm.entity.grenade.EntityGrenadeGeneric; import com.hbm.entity.grenade.EntityGrenadeIFBouncy; import com.hbm.entity.grenade.EntityGrenadeIFBrimstone; import com.hbm.entity.grenade.EntityGrenadeIFConcussion; import com.hbm.entity.grenade.EntityGrenadeIFGeneric; import com.hbm.entity.grenade.EntityGrenadeIFHE; import com.hbm.entity.grenade.EntityGrenadeIFHopwire; import com.hbm.entity.grenade.EntityGrenadeIFImpact; import com.hbm.entity.grenade.EntityGrenadeIFIncendiary; import com.hbm.entity.grenade.EntityGrenadeIFMystery; import com.hbm.entity.grenade.EntityGrenadeIFNull; import com.hbm.entity.grenade.EntityGrenadeIFSpark; import com.hbm.entity.grenade.EntityGrenadeIFSticky; import com.hbm.entity.grenade.EntityGrenadeIFToxic; import com.hbm.entity.grenade.EntityGrenadeLemon; import com.hbm.entity.grenade.EntityGrenadeMIRV; import com.hbm.entity.grenade.EntityGrenadeMk2; import com.hbm.entity.grenade.EntityGrenadeNuclear; import com.hbm.entity.grenade.EntityGrenadeNuke; import com.hbm.entity.grenade.EntityGrenadePC; import com.hbm.entity.grenade.EntityGrenadePlasma; import com.hbm.entity.grenade.EntityGrenadePoison; import com.hbm.entity.grenade.EntityGrenadePulse; import com.hbm.entity.grenade.EntityGrenadeSchrabidium; import com.hbm.entity.grenade.EntityGrenadeShrapnel; import com.hbm.entity.grenade.EntityGrenadeSmart; import com.hbm.entity.grenade.EntityGrenadeStrong; import com.hbm.entity.grenade.EntityGrenadeZOMG; import com.hbm.entity.item.EntityFireworks; import com.hbm.entity.item.EntityMovingItem; import com.hbm.entity.logic.EntityBalefire; import com.hbm.entity.logic.EntityBlast; import com.hbm.entity.logic.EntityBomber; import com.hbm.entity.logic.EntityDeathBlast; import com.hbm.entity.logic.EntityEMP; import com.hbm.entity.logic.EntityNukeExplosionMK3; import com.hbm.entity.logic.EntityNukeExplosionMK4; import com.hbm.entity.logic.EntityNukeExplosionPlus; import com.hbm.entity.logic.EntityTomBlast; import com.hbm.entity.logic.IChunkLoader; import com.hbm.entity.missile.EntityBobmazon; import com.hbm.entity.missile.EntityBombletSelena; import com.hbm.entity.missile.EntityBombletTheta; import com.hbm.entity.missile.EntityBooster; import com.hbm.entity.missile.EntityCarrier; import com.hbm.entity.missile.EntityMIRV; import com.hbm.entity.missile.EntityMinerRocket; import com.hbm.entity.missile.EntityMissileAntiBallistic; import com.hbm.entity.missile.EntityMissileBHole; import com.hbm.entity.missile.EntityMissileBunkerBuster; import com.hbm.entity.missile.EntityMissileBurst; import com.hbm.entity.missile.EntityMissileBusterStrong; import com.hbm.entity.missile.EntityMissileCluster; import com.hbm.entity.missile.EntityMissileClusterStrong; import com.hbm.entity.missile.EntityMissileCustom; import com.hbm.entity.missile.EntityMissileDoomsday; import com.hbm.entity.missile.EntityMissileDrill; import com.hbm.entity.missile.EntityMissileEMP; import com.hbm.entity.missile.EntityMissileEMPStrong; import com.hbm.entity.missile.EntityMissileEndo; import com.hbm.entity.missile.EntityMissileExo; import com.hbm.entity.missile.EntityMissileGeneric; import com.hbm.entity.missile.EntityMissileIncendiary; import com.hbm.entity.missile.EntityMissileIncendiaryStrong; import com.hbm.entity.missile.EntityMissileInferno; import com.hbm.entity.missile.EntityMissileMicro; import com.hbm.entity.missile.EntityMissileMirv; import com.hbm.entity.missile.EntityMissileNuclear; import com.hbm.entity.missile.EntityMissileRain; import com.hbm.entity.missile.EntityMissileSchrabidium; import com.hbm.entity.missile.EntityMissileStrong; import com.hbm.entity.missile.EntityMissileTaint; import com.hbm.entity.missile.EntitySoyuz; import com.hbm.entity.missile.EntitySoyuzCapsule; import com.hbm.entity.mob.EntityCyberCrab; import com.hbm.entity.mob.EntityDuck; import com.hbm.entity.mob.EntityFBI; import com.hbm.entity.mob.EntityHunterChopper; import com.hbm.entity.mob.EntityMaskMan; import com.hbm.entity.mob.EntityNuclearCreeper; import com.hbm.entity.mob.EntityQuackos; import com.hbm.entity.mob.EntityRADBeast; import com.hbm.entity.mob.EntityTaintCrab; import com.hbm.entity.mob.EntityTaintedCreeper; import com.hbm.entity.mob.EntityTeslaCrab; import com.hbm.entity.mob.botprime.EntityBOTPrimeBody; import com.hbm.entity.mob.botprime.EntityBOTPrimeHead; import com.hbm.entity.particle.EntityBSmokeFX; import com.hbm.entity.particle.EntityChlorineFX; import com.hbm.entity.particle.EntityCloudFX; import com.hbm.entity.particle.EntityDSmokeFX; import com.hbm.entity.particle.EntityFogFX; import com.hbm.entity.particle.EntityGasFX; import com.hbm.entity.particle.EntityGasFlameFX; import com.hbm.entity.particle.EntityOilSpillFX; import com.hbm.entity.particle.EntityOrangeFX; import com.hbm.entity.particle.EntityPinkCloudFX; import com.hbm.entity.particle.EntitySSmokeFX; import com.hbm.entity.particle.EntitySmokeFX; import com.hbm.entity.particle.EntityTSmokeFX; import com.hbm.entity.projectile.EntityAAShell; import com.hbm.entity.projectile.EntityBaleflare; import com.hbm.entity.projectile.EntityBeamVortex; import com.hbm.entity.projectile.EntityBombletZeta; import com.hbm.entity.projectile.EntityBoxcar; import com.hbm.entity.projectile.EntityBuilding; import com.hbm.entity.projectile.EntityBullet; import com.hbm.entity.projectile.EntityBulletBase; import com.hbm.entity.projectile.EntityBurningFOEQ; import com.hbm.entity.projectile.EntityChopperMine; import com.hbm.entity.projectile.EntityCombineBall; import com.hbm.entity.projectile.EntityDischarge; import com.hbm.entity.projectile.EntityDuchessGambit; import com.hbm.entity.projectile.EntityExplosiveBeam; import com.hbm.entity.projectile.EntityFallingNuke; import com.hbm.entity.projectile.EntityFire; import com.hbm.entity.projectile.EntityLN2; import com.hbm.entity.projectile.EntityLaser; import com.hbm.entity.projectile.EntityLaserBeam; import com.hbm.entity.projectile.EntityMeteor; import com.hbm.entity.projectile.EntityMinerBeam; import com.hbm.entity.projectile.EntityMiniMIRV; import com.hbm.entity.projectile.EntityMiniNuke; import com.hbm.entity.projectile.EntityModBeam; import com.hbm.entity.projectile.EntityOilSpill; import com.hbm.entity.projectile.EntityPlasmaBeam; import com.hbm.entity.projectile.EntityRailgunBlast; import com.hbm.entity.projectile.EntityRainbow; import com.hbm.entity.projectile.EntityRocket; import com.hbm.entity.projectile.EntityRocketHoming; import com.hbm.entity.projectile.EntityRubble; import com.hbm.entity.projectile.EntitySchrab; import com.hbm.entity.projectile.EntityShrapnel; import com.hbm.entity.projectile.EntitySparkBeam; import com.hbm.entity.projectile.EntityTom; import com.hbm.entity.projectile.EntityWaterSplash; import com.hbm.forgefluid.FFPipeNetwork; import com.hbm.forgefluid.FluidContainerRegistry; import com.hbm.forgefluid.FluidTypeHandler; import com.hbm.forgefluid.ModForgeFluids; import com.hbm.handler.BobmazonOfferFactory; import com.hbm.handler.BulletConfigSyncingUtil; import com.hbm.handler.GuiHandler; import com.hbm.handler.HTTPHandler; import com.hbm.handler.HazmatRegistry; import com.hbm.handler.MultiblockBBHandler; import com.hbm.inventory.AssemblerRecipes; import com.hbm.inventory.BreederRecipes; import com.hbm.inventory.CentrifugeRecipes; import com.hbm.inventory.CrystallizerRecipes; import com.hbm.inventory.CyclotronRecipes; import com.hbm.inventory.HadronRecipes; import com.hbm.inventory.MagicRecipes; import com.hbm.inventory.OreDictManager; import com.hbm.inventory.ShredderRecipes; import com.hbm.inventory.control_panel.ControlEvent; import com.hbm.inventory.control_panel.ControlRegistry; import com.hbm.items.ModItems; import com.hbm.lib.HBMSoundHandler; import com.hbm.lib.HbmWorld; import com.hbm.lib.Library; import com.hbm.lib.RefStrings; import com.hbm.packet.PacketDispatcher; import com.hbm.potion.HbmPotion; import com.hbm.saveddata.satellites.Satellite; import com.hbm.tileentity.TileEntityKeypadBase; import com.hbm.tileentity.TileEntityProxyCombo; import com.hbm.tileentity.TileEntityProxyEnergy; import com.hbm.tileentity.TileEntityProxyInventory; import com.hbm.tileentity.TileEntitySlidingBlastDoorKeypad; import com.hbm.tileentity.bomb.TileEntityBombMulti; import com.hbm.tileentity.bomb.TileEntityCompactLauncher; import com.hbm.tileentity.bomb.TileEntityCrashedBomb; import com.hbm.tileentity.bomb.TileEntityFireworks; import com.hbm.tileentity.bomb.TileEntityLandmine; import com.hbm.tileentity.bomb.TileEntityLaunchPad; import com.hbm.tileentity.bomb.TileEntityLaunchTable; import com.hbm.tileentity.bomb.TileEntityNukeBalefire; import com.hbm.tileentity.bomb.TileEntityNukeBoy; import com.hbm.tileentity.bomb.TileEntityNukeCustom; import com.hbm.tileentity.bomb.TileEntityNukeFleija; import com.hbm.tileentity.bomb.TileEntityNukeGadget; import com.hbm.tileentity.bomb.TileEntityNukeMan; import com.hbm.tileentity.bomb.TileEntityNukeMike; import com.hbm.tileentity.bomb.TileEntityNukeN2; import com.hbm.tileentity.bomb.TileEntityNukeN45; import com.hbm.tileentity.bomb.TileEntityNukePrototype; import com.hbm.tileentity.bomb.TileEntityNukeSolinium; import com.hbm.tileentity.bomb.TileEntityNukeTsar; import com.hbm.tileentity.bomb.TileEntityRailgun; import com.hbm.tileentity.bomb.TileEntityTurretCIWS; import com.hbm.tileentity.bomb.TileEntityTurretCheapo; import com.hbm.tileentity.bomb.TileEntityTurretFlamer; import com.hbm.tileentity.bomb.TileEntityTurretHeavy; import com.hbm.tileentity.bomb.TileEntityTurretLight; import com.hbm.tileentity.bomb.TileEntityTurretRocket; import com.hbm.tileentity.bomb.TileEntityTurretSpitfire; import com.hbm.tileentity.bomb.TileEntityTurretTau; import com.hbm.tileentity.conductor.TileEntityCable; import com.hbm.tileentity.conductor.TileEntityCableSwitch; import com.hbm.tileentity.conductor.TileEntityFFFluidDuct; import com.hbm.tileentity.conductor.TileEntityFFFluidDuctMk2; import com.hbm.tileentity.conductor.TileEntityFFFluidSuccMk2; import com.hbm.tileentity.conductor.TileEntityFFGasDuct; import com.hbm.tileentity.conductor.TileEntityFFGasDuctSolid; import com.hbm.tileentity.conductor.TileEntityFFOilDuct; import com.hbm.tileentity.conductor.TileEntityFFOilDuctSolid; import com.hbm.tileentity.deco.TileEntityDecoBlock; import com.hbm.tileentity.deco.TileEntityDecoBlockAlt; import com.hbm.tileentity.deco.TileEntityDecoPoleSatelliteReceiver; import com.hbm.tileentity.deco.TileEntityGeysir; import com.hbm.tileentity.deco.TileEntityObjTester; import com.hbm.tileentity.deco.TileEntitySpinnyLight; import com.hbm.tileentity.deco.TileEntityTestRender; import com.hbm.tileentity.deco.TileEntityTrappedBrick; import com.hbm.tileentity.deco.TileEntityVent; import com.hbm.tileentity.generic.TileEntityCloudResidue; import com.hbm.tileentity.generic.TileEntityTaint; import com.hbm.tileentity.machine.*; import com.hbm.tileentity.machine.TileEntityMachineReactorLarge.ReactorFuelType; import com.hbm.world.generator.CellularDungeonFactory; import net.minecraft.block.BlockDispenser; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.dispenser.BehaviorProjectileDispense; import net.minecraft.dispenser.IPosition; import net.minecraft.entity.IProjectile; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.RangedAttribute; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.LoadingCallback; import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.ReflectionHelper; @Mod(modid = RefStrings.MODID, version = RefStrings.VERSION, name = RefStrings.NAME) public class MainRegistry { static { HBMSoundHandler.init(); FluidRegistry.enableUniversalBucket(); } @SidedProxy(clientSide = RefStrings.CLIENTSIDE, serverSide = RefStrings.SERVERSIDE) public static ServerProxy proxy; @Mod.Instance(RefStrings.MODID) public static MainRegistry instance; public static Logger logger; public static List<FFPipeNetwork> allPipeNetworks = new ArrayList<FFPipeNetwork>(); // Creative Tabs // ingots, nuggets, wires, machine parts public static CreativeTabs partsTab = new PartsTab(CreativeTabs.getNextID(), "tabParts"); // items that belong in machines, fuels, etc public static CreativeTabs controlTab = new ControlTab(CreativeTabs.getNextID(), "tabControl"); // templates, siren tracks public static CreativeTabs templateTab = new TemplateTab(CreativeTabs.getNextID(), "tabTemplate"); // ore and mineral blocks public static CreativeTabs blockTab = new BlockTab(CreativeTabs.getNextID(), "tabBlocks"); // machines, structure parts public static CreativeTabs machineTab = new MachineTab(CreativeTabs.getNextID(), "tabMachine"); // bombs public static CreativeTabs nukeTab = new NukeTab(CreativeTabs.getNextID(), "tabNuke"); // missiles, satellites public static CreativeTabs missileTab = new MissileTab(CreativeTabs.getNextID(), "tabMissile"); // turrets, weapons, ammo public static CreativeTabs weaponTab = new WeaponTab(CreativeTabs.getNextID(), "tabWeapon"); // drinks, kits, tools public static CreativeTabs consumableTab = new ConsumableTab(CreativeTabs.getNextID(), "tabConsumable"); public static int generalOverride = 0; public static int polaroidID = 1; public static final int schrabFromUraniumChance = 100; public static int x; public static int y; public static int z; public static long time; // Armor Materials // Drillgon200: I have no idea what the two strings and the number at the // end are. public static ArmorMaterial enumArmorMaterialT45 = EnumHelper.addArmorMaterial(RefStrings.MODID + ":T45", RefStrings.MODID + ":T45", 150, new int[] { 3, 6, 8, 3 }, 0, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatBJ = EnumHelper.addArmorMaterial(RefStrings.MODID + ":BLACKJACK", RefStrings.MODID + ":HBM_BLACKJACK", 150, new int[] { 3, 6, 8, 3 }, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatAJR = EnumHelper.addArmorMaterial(RefStrings.MODID + ":T45AJR", RefStrings.MODID + ":T45AJR", 150, new int[] { 3, 6, 8, 3 }, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatFAU = EnumHelper.addArmorMaterial(RefStrings.MODID + ":FAU", RefStrings.MODID + ":FAU", 150, new int[] { 3, 8, 6, 3 }, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatHEV = EnumHelper.addArmorMaterial(RefStrings.MODID + ":HEV", RefStrings.MODID + ":HEV", 150, new int[] { 3, 6, 8, 3 }, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialHazmat = EnumHelper.addArmorMaterial(RefStrings.MODID + ":HAZMAT", RefStrings.MODID + ":HAZMAT", 60, new int[] { 1, 4, 5, 2 }, 5, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialHazmat2 = EnumHelper.addArmorMaterial(RefStrings.MODID + ":HAZMAT2", RefStrings.MODID + ":HAZMAT2", 60, new int[] { 1, 4, 5, 2 }, 5, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialHazmat3 = EnumHelper.addArmorMaterial(RefStrings.MODID + ":HAZMAT3", RefStrings.MODID + ":HAZMAT3", 60, new int[] { 1, 4, 5, 2 }, 5, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialPaa = EnumHelper.addArmorMaterial(RefStrings.MODID + ":PAA", RefStrings.MODID + ":PAA", 75, new int[] { 3, 6, 8, 3 }, 25, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialSchrabidium = EnumHelper.addArmorMaterial(RefStrings.MODID + ":SCHRABIDIUM", RefStrings.MODID + ":SCHRABIDIUM", 100, new int[] { 3, 6, 8, 3 }, 50, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialEuphemium = EnumHelper.addArmorMaterial(RefStrings.MODID + ":EUPHEMIUM", RefStrings.MODID + ":EUPHEMIUM", 15000000, new int[] { 3, 6, 8, 3 }, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialSteel = EnumHelper.addArmorMaterial(RefStrings.MODID + ":STEEL", RefStrings.MODID + ":STEEL", 20, new int[] { 2, 5, 6, 2 }, 5, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialAlloy = EnumHelper.addArmorMaterial(RefStrings.MODID + ":ALLOY", RefStrings.MODID + ":ALLOY", 40, new int[] { 3, 6, 8, 3 }, 12, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialAusIII = EnumHelper.addArmorMaterial(RefStrings.MODID + ":AUSIII", RefStrings.MODID + ":AUSIII", 375, new int[] {2, 5, 6, 2}, 0, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial enumArmorMaterialTitanium = EnumHelper.addArmorMaterial(RefStrings.MODID + ":TITANIUM", RefStrings.MODID + ":TITANIUM", 25, new int[] {3, 6, 8, 3}, 9, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialCmb = EnumHelper.addArmorMaterial(RefStrings.MODID + ":CMB", RefStrings.MODID + ":CMB", 60, new int[] {3, 6, 8, 3}, 50, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialSecurity = EnumHelper.addArmorMaterial(RefStrings.MODID + ":SECURITY", RefStrings.MODID + ":SECURITY", 100, new int[] {3, 6, 8, 3}, 15, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial enumArmorMaterialAsbestos = EnumHelper.addArmorMaterial(RefStrings.MODID + ":ASBESTOS", RefStrings.MODID + ":ASBESTOS", 20, new int[] {1, 3, 4, 1}, 5, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 0.0F); public static ArmorMaterial aMatCobalt = EnumHelper.addArmorMaterial(RefStrings.MODID + ":COBALT", RefStrings.MODID + ":COBALT", 70, new int[] {3, 6, 8, 3}, 25, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatStarmetal = EnumHelper.addArmorMaterial(RefStrings.MODID + ":STARMETAL", RefStrings.MODID + ":STARMETAL", 150, new int[] {3, 6, 8, 3}, 100, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); public static ArmorMaterial aMatLiquidator = EnumHelper.addArmorMaterial(RefStrings.MODID + ":LIQUIDATOR", RefStrings.MODID + ":LIQUIDATOR", 750, new int[] { 3, 6, 8, 3 }, 10, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 2.0F); // Tool Materials public static ToolMaterial enumToolMaterialSchrabidium = EnumHelper.addToolMaterial(RefStrings.MODID + ":SCHRABIDIUM", 3, 10000, 50.0F, 100.0F, 200); public static ToolMaterial enumToolMaterialHammer = EnumHelper.addToolMaterial(RefStrings.MODID + ":SCHRABIDIUMHAMMER", 3, 0, 50.0F, 999999996F, 200); public static ToolMaterial enumToolMaterialChainsaw = EnumHelper.addToolMaterial(RefStrings.MODID + ":CHAINSAW", 3, 1500, 50.0F, 22.0F, 0); public static ToolMaterial enumToolMaterialSteel = EnumHelper.addToolMaterial(RefStrings.MODID + ":STEEL", 2, 500, 7.5F, 2.0F, 10); public static ToolMaterial enumToolMaterialTitanium = EnumHelper.addToolMaterial(RefStrings.MODID + ":TITANIUM", 3, 750, 9.0F, 2.5F, 15); public static ToolMaterial enumToolMaterialAlloy = EnumHelper.addToolMaterial(RefStrings.MODID + ":ALLOY", 3, 2000, 15.0F, 5.0F, 5); public static ToolMaterial enumToolMaterialCmb = EnumHelper.addToolMaterial(RefStrings.MODID + ":CMB", 3, 8500, 40.0F, 55F, 100); public static ToolMaterial enumToolMaterialElec = EnumHelper.addToolMaterial(RefStrings.MODID + ":ELEC", 3, 0, 30.0F, 12.0F, 2); public static ToolMaterial enumToolMaterialDesh = EnumHelper.addToolMaterial(RefStrings.MODID + ":DESH", 2, 0, 7.5F, 2.0F, 10); public static ToolMaterial enumToolMaterialCobalt = EnumHelper.addToolMaterial(RefStrings.MODID + ":COBALT", 3, 750, 9.0F, 2.5F, 15); public static ToolMaterial enumToolMaterialSaw = EnumHelper.addToolMaterial(RefStrings.MODID + ":SAW", 2, 750, 2.0F, 3.5F, 25); public static ToolMaterial enumToolMaterialBat = EnumHelper.addToolMaterial(RefStrings.MODID + ":BAT", 0, 500, 1.5F, 3F, 25); public static ToolMaterial enumToolMaterialBatNail = EnumHelper.addToolMaterial(RefStrings.MODID + ":BATNAIL", 0, 450, 1.0F, 4F, 25); public static ToolMaterial enumToolMaterialGolfClub = EnumHelper.addToolMaterial(RefStrings.MODID + ":GOLFCLUB", 1, 1000, 2.0F, 5F, 25); public static ToolMaterial enumToolMaterialPipeRusty = EnumHelper.addToolMaterial(RefStrings.MODID + ":PIPERUSTY", 1, 350, 1.5F, 4.5F, 25); public static ToolMaterial enumToolMaterialPipeLead = EnumHelper.addToolMaterial(RefStrings.MODID + ":PIPELEAD", 1, 250, 1.5F, 5.5F, 25); public static ToolMaterial enumToolMaterialBottleOpener = EnumHelper.addToolMaterial(RefStrings.MODID + ":OPENER", 1, 250, 1.5F, 0.5F, 200); public static ToolMaterial enumToolMaterialSledge = EnumHelper.addToolMaterial(RefStrings.MODID + ":SHIMMERSLEDGE", 1, 0, 25.0F, 26F, 200); public static ToolMaterial enumToolMaterialMultitool = EnumHelper.addToolMaterial(RefStrings.MODID + ":MULTITOOL", 3, 5000, 25F, 5.5F, 25); public static ToolMaterial matMeteorite = EnumHelper.addToolMaterial("HBM_METEORITE", 4, 0, 50F, 0.0F, 200); public static ToolMaterial matCrucible = EnumHelper.addToolMaterial("CRUCIBLE", 3, 10000, 50.0F, 100.0F, 200); public static ToolMaterial matHS = EnumHelper.addToolMaterial("CRUCIBLE", 3, 10000, 50.0F, 100.0F, 200); public static ToolMaterial matHF = EnumHelper.addToolMaterial("CRUCIBLE", 3, 10000, 50.0F, 100.0F, 200); Random rand = new Random(); @EventHandler public void preInit(FMLPreInitializationEvent event) { if(logger == null) logger = event.getModLog(); if(generalOverride > 0 && generalOverride < 19) { polaroidID = generalOverride; } else { polaroidID = rand.nextInt(18) + 1; while(polaroidID == 4 || polaroidID == 9) polaroidID = rand.nextInt(18) + 1; } if(SharedMonsterAttributes.MAX_HEALTH.clampValue(Integer.MAX_VALUE) <= 2000) try{ @SuppressWarnings("deprecation") Field f = ReflectionHelper.findField(RangedAttribute.class, "maximumValue", "field_111118_b"); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(SharedMonsterAttributes.MAX_HEALTH, Integer.MAX_VALUE); } catch(Exception e){} proxy.checkGLCaps(); reloadConfig(); MinecraftForge.EVENT_BUS.register(new ModEventHandler()); MinecraftForge.TERRAIN_GEN_BUS.register(new ModEventHandler()); MinecraftForge.ORE_GEN_BUS.register(new ModEventHandler()); PacketDispatcher.registerPackets(); HbmPotion.init(); CapabilityManager.INSTANCE.register(RadiationCapability.IEntityRadioactive.class, new RadiationCapability.EntityRadioactiveStorage(), RadiationCapability.EntityRadioactive.FACTORY); CapabilityManager.INSTANCE.register(HbmCapability.IHBMData.class, new HbmCapability.HBMDataStorage(), HbmCapability.HBMData.FACTORY); ModForgeFluids.init(); ModItems.preInit(); ModBlocks.preInit(); BulletConfigSyncingUtil.loadConfigsForSync(); CellularDungeonFactory.init(); Satellite.register(); HTTPHandler.loadStats(); AssemblerRecipes.preInit(event.getModConfigurationDirectory()); MultiblockBBHandler.init(); ControlEvent.init(); proxy.registerRenderInfo(); HbmWorld.mainRegistry(); proxy.preInit(event); Library.initSuperusers(); enumArmorMaterialSchrabidium.setRepairItem(new ItemStack(ModItems.ingot_schrabidium)); enumArmorMaterialHazmat.setRepairItem(new ItemStack(ModItems.hazmat_cloth)); enumArmorMaterialHazmat2.setRepairItem(new ItemStack(ModItems.hazmat_cloth_red)); enumArmorMaterialHazmat3.setRepairItem(new ItemStack(ModItems.hazmat_cloth_grey)); enumArmorMaterialT45.setRepairItem(new ItemStack(ModItems.plate_titanium)); aMatBJ.setRepairItem(new ItemStack(ModItems.plate_armor_lunar)); aMatAJR.setRepairItem(new ItemStack(ModItems.plate_armor_ajr)); aMatFAU.setRepairItem(new ItemStack(ModItems.plate_armor_fau)); aMatHEV.setRepairItem(new ItemStack(ModItems.plate_armor_hev)); enumArmorMaterialTitanium.setRepairItem(new ItemStack(ModItems.ingot_titanium)); enumArmorMaterialSteel.setRepairItem(new ItemStack(ModItems.ingot_steel)); enumArmorMaterialAlloy.setRepairItem(new ItemStack(ModItems.ingot_advanced_alloy)); enumArmorMaterialPaa.setRepairItem(new ItemStack(ModItems.plate_paa)); enumArmorMaterialCmb.setRepairItem(new ItemStack(ModItems.ingot_combine_steel)); enumArmorMaterialAusIII.setRepairItem(new ItemStack(ModItems.ingot_australium)); enumArmorMaterialSecurity.setRepairItem(new ItemStack(ModItems.plate_kevlar)); enumToolMaterialSchrabidium.setRepairItem(new ItemStack(ModItems.ingot_schrabidium)); enumToolMaterialHammer.setRepairItem(new ItemStack(Item.getItemFromBlock(ModBlocks.block_schrabidium))); enumToolMaterialChainsaw.setRepairItem(new ItemStack(ModItems.ingot_steel)); enumToolMaterialTitanium.setRepairItem(new ItemStack(ModItems.ingot_titanium)); enumToolMaterialSteel.setRepairItem(new ItemStack(ModItems.ingot_steel)); enumToolMaterialAlloy.setRepairItem(new ItemStack(ModItems.ingot_advanced_alloy)); enumToolMaterialCmb.setRepairItem(new ItemStack(ModItems.ingot_combine_steel)); enumToolMaterialBottleOpener.setRepairItem(new ItemStack(ModItems.plate_steel)); enumToolMaterialDesh.setRepairItem(new ItemStack(ModItems.ingot_desh)); enumArmorMaterialAsbestos.setRepairItem(new ItemStack(ModItems.asbestos_cloth)); matMeteorite.setRepairItem(new ItemStack(ModItems.plate_paa)); aMatLiquidator.setRepairItem(new ItemStack(ModItems.plate_lead)); NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler()); GameRegistry.registerTileEntity(TileEntityDummy.class, new ResourceLocation(RefStrings.MODID, "tileentity_dummy")); GameRegistry.registerTileEntity(TileEntityMachineAssembler.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_assembler")); GameRegistry.registerTileEntity(TileEntityDiFurnace.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_difurnace")); GameRegistry.registerTileEntity(TileEntityMachinePress.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_press")); GameRegistry.registerTileEntity(TileEntityTaint.class, new ResourceLocation(RefStrings.MODID, "tileentity_taint")); GameRegistry.registerTileEntity(TileEntityTestRender.class, new ResourceLocation(RefStrings.MODID, "tileentity_testrenderer")); GameRegistry.registerTileEntity(TileEntityMachineChemplant.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_chemplant")); GameRegistry.registerTileEntity(TileEntityDummyPort.class, new ResourceLocation(RefStrings.MODID, "tileentity_dummy_port")); GameRegistry.registerTileEntity(TileEntityCloudResidue.class, new ResourceLocation(RefStrings.MODID, "tileentity_cloud_residue")); GameRegistry.registerTileEntity(TileEntityNukeMan.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_man")); GameRegistry.registerTileEntity(TileEntityNukeFleija.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_fleija")); GameRegistry.registerTileEntity(TileEntityMachineCoal.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_coal")); GameRegistry.registerTileEntity(TileEntityMachineGenerator.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_generator")); GameRegistry.registerTileEntity(TileEntityMachineReactorSmall.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_reactor_small")); GameRegistry.registerTileEntity(TileEntityMachineRTG.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_rtg_grey")); GameRegistry.registerTileEntity(TileEntityCable.class, new ResourceLocation(RefStrings.MODID, "tileentity_cable")); GameRegistry.registerTileEntity(TileEntityMachineBattery.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_battery")); GameRegistry.registerTileEntity(TileEntityMachineTransformer.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_transformer")); GameRegistry.registerTileEntity(TileEntityConverterHeRf.class, new ResourceLocation(RefStrings.MODID, "tileentity_converter_he_rf")); GameRegistry.registerTileEntity(TileEntityConverterRfHe.class, new ResourceLocation(RefStrings.MODID, "tileentity_converter_rf_he")); GameRegistry.registerTileEntity(TileEntityMachineTurbine.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_turbine")); GameRegistry.registerTileEntity(TileEntityFFFluidDuct.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_fluidduct")); GameRegistry.registerTileEntity(TileEntityTurretCheapo.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_cheapo")); GameRegistry.registerTileEntity(TileEntityTurretRocket.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_rocket")); GameRegistry.registerTileEntity(TileEntityTurretLight.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_light")); GameRegistry.registerTileEntity(TileEntityTurretHeavy.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_heavy")); GameRegistry.registerTileEntity(TileEntityTurretFlamer.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_flamer")); GameRegistry.registerTileEntity(TileEntityTurretTau.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_tau")); GameRegistry.registerTileEntity(TileEntityTurretSpitfire.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_spitfire")); GameRegistry.registerTileEntity(TileEntityTurretCIWS.class, new ResourceLocation(RefStrings.MODID, "tileentity_turret_ciws")); GameRegistry.registerTileEntity(TileEntityDecoBlock.class, new ResourceLocation(RefStrings.MODID, "tileentity_deco_block")); GameRegistry.registerTileEntity(TileEntityLaunchPad.class, new ResourceLocation(RefStrings.MODID, "tileentity_launch_pad")); GameRegistry.registerTileEntity(TileEntityMachineBoiler.class, new ResourceLocation(RefStrings.MODID)); GameRegistry.registerTileEntity(TileEntityMachineBoilerElectric.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_boiler_electric")); GameRegistry.registerTileEntity(TileEntityMachineEPress.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_epress")); GameRegistry.registerTileEntity(TileEntityPylonRedWire.class, new ResourceLocation(RefStrings.MODID, "tileentity_pylon_red_wire")); GameRegistry.registerTileEntity(TileEntityWireCoated.class, new ResourceLocation(RefStrings.MODID, "tileentity_wire_coated")); GameRegistry.registerTileEntity(TileEntityMachineCentrifuge.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_centrifuge")); GameRegistry.registerTileEntity(TileEntityMachineGasCent.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_gascent")); GameRegistry.registerTileEntity(TileEntityMachineUF6Tank.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_uf6_tank")); GameRegistry.registerTileEntity(TileEntityMachinePuF6Tank.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_puf6_tank")); GameRegistry.registerTileEntity(TileEntityRailgun.class, new ResourceLocation(RefStrings.MODID, "tileentity_railgun")); GameRegistry.registerTileEntity(TileEntityMachineReactor.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_reactor")); GameRegistry.registerTileEntity(TileEntityMachineShredder.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_shredder")); GameRegistry.registerTileEntity(TileEntityDummyFluidPort.class, new ResourceLocation(RefStrings.MODID, "tileentity_dummy_fluid_port")); GameRegistry.registerTileEntity(TileEntityMachineFluidTank.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_fluidtank")); GameRegistry.registerTileEntity(TileEntityCableSwitch.class, new ResourceLocation(RefStrings.MODID, "tileentity_cable_switch")); GameRegistry.registerTileEntity(TileEntityFFOilDuctSolid.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_oil_duct_solid")); GameRegistry.registerTileEntity(TileEntityFFGasDuctSolid.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_gas_duct_solid")); GameRegistry.registerTileEntity(TileEntityFFOilDuct.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_oil_duct")); GameRegistry.registerTileEntity(TileEntityFFGasDuct.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_gas_duct")); GameRegistry.registerTileEntity(TileEntityMachineRefinery.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_refinery")); GameRegistry.registerTileEntity(TileEntityMachineCyclotron.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_cyclotron")); GameRegistry.registerTileEntity(TileEntityMachineSchrabidiumTransmutator.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_schrabidium_transmutator")); GameRegistry.registerTileEntity(TileEntityMachineSiren.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_siren")); GameRegistry.registerTileEntity(TileEntityBroadcaster.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_broadcaster")); GameRegistry.registerTileEntity(TileEntityGeiger.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_geiger")); GameRegistry.registerTileEntity(TileEntityHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_hatch")); GameRegistry.registerTileEntity(TileEntityVaultDoor.class, new ResourceLocation(RefStrings.MODID, "tileentity_vault_door")); GameRegistry.registerTileEntity(TileEntityBlastDoor.class, new ResourceLocation(RefStrings.MODID, "tileentity_blastdoor")); GameRegistry.registerTileEntity(TileEntityCrateIron.class, new ResourceLocation(RefStrings.MODID, "tileentity_crate_iron")); GameRegistry.registerTileEntity(TileEntityCrateSteel.class, new ResourceLocation(RefStrings.MODID, "tileentity_crate_steel")); GameRegistry.registerTileEntity(TileEntitySafe.class, new ResourceLocation(RefStrings.MODID, "tileentity_safe")); GameRegistry.registerTileEntity(TileEntityMachineKeyForge.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_key_forge")); GameRegistry.registerTileEntity(TileEntityNukeFurnace.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_furnace")); GameRegistry.registerTileEntity(TileEntityRtgFurnace.class, new ResourceLocation(RefStrings.MODID, "tileentity_rtg_furnace")); GameRegistry.registerTileEntity(TileEntityMachineSeleniumEngine.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_selenium")); GameRegistry.registerTileEntity(TileEntityReactorControl.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_reactor_control")); GameRegistry.registerTileEntity(TileEntityMachineRadGen.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_radgen")); GameRegistry.registerTileEntity(TileEntityMachineAmgen.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_amgen")); GameRegistry.registerTileEntity(TileEntityMachineSPP.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_spp")); GameRegistry.registerTileEntity(TileEntityMachineArcFurnace.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_arc_furnace")); GameRegistry.registerTileEntity(TileEntityMachineElectricFurnace.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_electric_furnace")); GameRegistry.registerTileEntity(TileEntityWasteDrum.class, new ResourceLocation(RefStrings.MODID, "tileentity_waste_drum")); GameRegistry.registerTileEntity(TileEntityMachineOilWell.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_oil_well")); GameRegistry.registerTileEntity(TileEntityMachinePumpjack.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_pumpjack")); GameRegistry.registerTileEntity(TileEntityMachineGasFlare.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_gas_flare")); GameRegistry.registerTileEntity(TileEntityMachineMiningDrill.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_mining_drill")); GameRegistry.registerTileEntity(TileEntityMachineTurbofan.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_turbofan")); GameRegistry.registerTileEntity(TileEntityMachineCMBFactory.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_cmb_factory")); GameRegistry.registerTileEntity(TileEntityMachineTeleporter.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_teleporter")); GameRegistry.registerTileEntity(TileEntityRadiobox.class, new ResourceLocation(RefStrings.MODID, "tileentity_radiobox")); GameRegistry.registerTileEntity(TileEntityRadioRec.class, new ResourceLocation(RefStrings.MODID, "tileentity_radiorec")); GameRegistry.registerTileEntity(TileEntityDecon.class, new ResourceLocation(RefStrings.MODID, "tileentity_decon")); GameRegistry.registerTileEntity(TileEntityVent.class, new ResourceLocation(RefStrings.MODID, "tileentity_vent")); GameRegistry.registerTileEntity(TileEntityChlorineSeal.class, new ResourceLocation(RefStrings.MODID, "tileentity_chlorine_seal")); GameRegistry.registerTileEntity(TileEntityStructureMarker.class, new ResourceLocation(RefStrings.MODID, "tileentity_structure_marker")); GameRegistry.registerTileEntity(TileEntityCoreTitanium.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_titanium")); GameRegistry.registerTileEntity(TileEntityCoreAdvanced.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_advanced")); GameRegistry.registerTileEntity(TileEntityReactorHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_reactor_hatch")); GameRegistry.registerTileEntity(TileEntityMachineReactorLarge.class, new ResourceLocation(RefStrings.MODID, "tileentity_reactor_large")); GameRegistry.registerTileEntity(TileEntityFusionHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_fusion_hatch")); GameRegistry.registerTileEntity(TileEntityFusionMultiblock.class, new ResourceLocation(RefStrings.MODID, "tileentity_fusion_multiblock")); GameRegistry.registerTileEntity(TileEntityWatzHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_watz_hatch")); GameRegistry.registerTileEntity(TileEntityWatzCore.class, new ResourceLocation(RefStrings.MODID, "tileentity_watz_core")); GameRegistry.registerTileEntity(TileEntityFWatzHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_fwatz_hatch")); GameRegistry.registerTileEntity(TileEntityFWatzCore.class, new ResourceLocation(RefStrings.MODID, "tileentity_fwatz_core")); GameRegistry.registerTileEntity(TileEntityNukeGadget.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_gadget")); GameRegistry.registerTileEntity(TileEntityNukeBoy.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_boy")); GameRegistry.registerTileEntity(TileEntityNukeMike.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_mike")); GameRegistry.registerTileEntity(TileEntityNukeTsar.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_tsar")); GameRegistry.registerTileEntity(TileEntityNukePrototype.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_prototype")); GameRegistry.registerTileEntity(TileEntityNukeSolinium.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_solinium")); GameRegistry.registerTileEntity(TileEntityNukeN2.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_n2")); GameRegistry.registerTileEntity(TileEntityNukeN45.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_n45")); GameRegistry.registerTileEntity(TileEntityNukeCustom.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_custom")); GameRegistry.registerTileEntity(TileEntityBombMulti.class, new ResourceLocation(RefStrings.MODID, "tileentity_bomb_multi")); GameRegistry.registerTileEntity(TileEntityCrashedBomb.class, new ResourceLocation(RefStrings.MODID, "tileentity_crashed_bomb")); GameRegistry.registerTileEntity(TileEntityLandmine.class, new ResourceLocation(RefStrings.MODID, "tileentity_landmine")); GameRegistry.registerTileEntity(TileEntityMachineTeleLinker.class, new ResourceLocation(RefStrings.MODID, "tileentity_telelinker")); GameRegistry.registerTileEntity(TileEntityMachineMissileAssembly.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_missile_assembly")); GameRegistry.registerTileEntity(TileEntityCompactLauncher.class, new ResourceLocation(RefStrings.MODID, "tileentity_compact_launcher")); GameRegistry.registerTileEntity(TileEntityMultiblock.class, new ResourceLocation(RefStrings.MODID, "tileentity_launcher_multiblock")); GameRegistry.registerTileEntity(TileEntityLaunchTable.class, new ResourceLocation(RefStrings.MODID, "tileentity_launch_table")); GameRegistry.registerTileEntity(TileEntityAMSEmitter.class, new ResourceLocation(RefStrings.MODID, "tileentity_ams_emitter")); GameRegistry.registerTileEntity(TileEntityAMSLimiter.class, new ResourceLocation(RefStrings.MODID, "tileentity_ams_limiter")); GameRegistry.registerTileEntity(TileEntityAMSBase.class, new ResourceLocation(RefStrings.MODID, "tileentity_ams_base")); GameRegistry.registerTileEntity(TileEntityMachineSatLinker.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_sat_linker")); GameRegistry.registerTileEntity(TileEntityMachineSatDock.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_sat_dock")); GameRegistry.registerTileEntity(TileEntityMachineDiesel.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_diesel")); GameRegistry.registerTileEntity(TileEntityForceField.class, new ResourceLocation(RefStrings.MODID, "tileentity_force_field")); GameRegistry.registerTileEntity(TileEntityMachineRadar.class, new ResourceLocation(RefStrings.MODID, "tileentity_machine_radar")); GameRegistry.registerTileEntity(TileEntityDecoPoleSatelliteReceiver.class, new ResourceLocation(RefStrings.MODID, "tileentity_deco_pole_satellite_receiver")); GameRegistry.registerTileEntity(TileEntityGeysir.class, new ResourceLocation(RefStrings.MODID, "tileentity_geyser")); GameRegistry.registerTileEntity(TileEntityObjTester.class, new ResourceLocation(RefStrings.MODID, "tileentity_obj_tester")); GameRegistry.registerTileEntity(TileEntityDecoBlockAlt.class, new ResourceLocation(RefStrings.MODID, "tileentity_deco_block_alt")); GameRegistry.registerTileEntity(TileEntityFFFluidDuctMk2.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_fludi_duct_mk2")); GameRegistry.registerTileEntity(TileEntityBarrel.class, new ResourceLocation(RefStrings.MODID, "tileentity_barrel")); GameRegistry.registerTileEntity(TileEntityTesla.class, new ResourceLocation(RefStrings.MODID, "tileentity_tesla")); GameRegistry.registerTileEntity(TileEntityCyberCrab.class, new ResourceLocation(RefStrings.MODID, "tileentity_cybercrab")); GameRegistry.registerTileEntity(TileEntityCoreEmitter.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_emitter")); GameRegistry.registerTileEntity(TileEntityCoreReceiver.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_receiver")); GameRegistry.registerTileEntity(TileEntityCoreInjector.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_injector")); GameRegistry.registerTileEntity(TileEntityCoreStabilizer.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_stabilizer")); GameRegistry.registerTileEntity(TileEntityCore.class, new ResourceLocation(RefStrings.MODID, "tileentity_core_core")); GameRegistry.registerTileEntity(TileEntitySoyuzCapsule.class, new ResourceLocation(RefStrings.MODID, "tileentity_soyuz_capsule")); GameRegistry.registerTileEntity(TileEntitySoyuzLauncher.class, new ResourceLocation(RefStrings.MODID, "tileentity_soyuz_launcher")); GameRegistry.registerTileEntity(TileEntityFFFluidSuccMk2.class, new ResourceLocation(RefStrings.MODID, "tileentity_ff_succ_mk2")); GameRegistry.registerTileEntity(TileEntityMachineCrystallizer.class, new ResourceLocation(RefStrings.MODID, "tileentity_acidomatic")); GameRegistry.registerTileEntity(TileEntitySoyuzStruct.class, new ResourceLocation(RefStrings.MODID, "tileentity_soyuz_struct")); GameRegistry.registerTileEntity(TileEntityITERStruct.class, new ResourceLocation(RefStrings.MODID, "tileentity_iter_struct")); GameRegistry.registerTileEntity(TileEntityMachineMiningLaser.class, new ResourceLocation(RefStrings.MODID, "tileentity_mining_laser")); GameRegistry.registerTileEntity(TileEntityProxyInventory.class, new ResourceLocation(RefStrings.MODID, "tileentity_proxy_inventory")); GameRegistry.registerTileEntity(TileEntityProxyEnergy.class, new ResourceLocation(RefStrings.MODID, "tileentity_proxy_power")); GameRegistry.registerTileEntity(TileEntityNukeBalefire.class, new ResourceLocation(RefStrings.MODID, "tileentity_nuke_fstbmb")); GameRegistry.registerTileEntity(TileEntityProxyCombo.class, new ResourceLocation(RefStrings.MODID, "tileentity_proxy_combo")); GameRegistry.registerTileEntity(TileEntityMicrowave.class, new ResourceLocation(RefStrings.MODID, "tileentity_microwave")); GameRegistry.registerTileEntity(TileEntityMachineMiniRTG.class, new ResourceLocation(RefStrings.MODID, "tileentity_mini_rtg")); GameRegistry.registerTileEntity(TileEntityITER.class, new ResourceLocation(RefStrings.MODID, "tileentity_iter")); GameRegistry.registerTileEntity(TileEntityMachinePlasmaHeater.class, new ResourceLocation(RefStrings.MODID, "tileentity_plasma_heater")); GameRegistry.registerTileEntity(TileEntityMachineFENSU.class, new ResourceLocation(RefStrings.MODID, "tileentity_fensu")); GameRegistry.registerTileEntity(TileEntityTrappedBrick.class, new ResourceLocation(RefStrings.MODID, "tileentity_trapped_brick")); GameRegistry.registerTileEntity(TileEntityPlasmaStruct.class, new ResourceLocation(RefStrings.MODID, "tileentity_plasma_struct")); GameRegistry.registerTileEntity(TileEntityMachineLargeTurbine.class, new ResourceLocation(RefStrings.MODID, "tileentity_industrial_turbine")); GameRegistry.registerTileEntity(TileEntitySlidingBlastDoor.class, new ResourceLocation(RefStrings.MODID, "tileentity_sliding_blast_door")); GameRegistry.registerTileEntity(TileEntityKeypadBase.class, new ResourceLocation(RefStrings.MODID, "tileentity_keypad_base")); GameRegistry.registerTileEntity(TileEntitySlidingBlastDoorKeypad.class, new ResourceLocation(RefStrings.MODID, "tileentity_keypad_door")); GameRegistry.registerTileEntity(TileEntityBlackBook.class, new ResourceLocation(RefStrings.MODID, "tileentity_book_crafting")); GameRegistry.registerTileEntity(TileEntityHadronDiode.class, new ResourceLocation(RefStrings.MODID, "tileentity_hadron_diode")); GameRegistry.registerTileEntity(TileEntityHadronPower.class, new ResourceLocation(RefStrings.MODID, "tileentity_hadron_power")); GameRegistry.registerTileEntity(TileEntityHadron.class, new ResourceLocation(RefStrings.MODID, "tileentity_hadron")); GameRegistry.registerTileEntity(TileEntitySolarBoiler.class, new ResourceLocation(RefStrings.MODID, "tileentity_solarboiler")); GameRegistry.registerTileEntity(TileEntitySolarMirror.class, new ResourceLocation(RefStrings.MODID, "tileentity_solarmirror")); GameRegistry.registerTileEntity(TileEntityMachineDetector.class, new ResourceLocation(RefStrings.MODID, "tileentity_he_detector")); GameRegistry.registerTileEntity(TileEntityFireworks.class, new ResourceLocation(RefStrings.MODID, "tileentity_firework_box")); GameRegistry.registerTileEntity(TileEntityMachineIGenerator.class, new ResourceLocation(RefStrings.MODID, "tileentity_igenerator")); GameRegistry.registerTileEntity(TileEntitySiloHatch.class, new ResourceLocation(RefStrings.MODID, "tileentity_silo_hatch")); GameRegistry.registerTileEntity(TileEntitySpinnyLight.class, new ResourceLocation(RefStrings.MODID, "tileentity_spinny_light")); GameRegistry.registerTileEntity(TileEntityControlPanel.class, new ResourceLocation(RefStrings.MODID, "tileentity_control_panel")); int i = 0; EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_mk4"), EntityNukeExplosionMK4.class, "entity_nuke_mk4", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuclear_fog"), EntityFogFX.class, "entity_nuclear_fog", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_d_smoke_fx"), EntityDSmokeFX.class, "entity_d_smoke_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_cloud_small"), EntityNukeCloudSmall.class, "entity_nuke_cloud_small", i++, this, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_fallout_rain"), EntityFalloutRain.class, "entity_fallout_rain", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_smoke_fx"), EntitySmokeFX.class, "entity_smoke_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_b_smoke_fx"), EntityBSmokeFX.class, "entity_b_smoke_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_shrapnel"), EntityShrapnel.class, "enity_shrapnel", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_s_smoke_fx"), EntitySSmokeFX.class, "entity_s_smoke_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_rubble"), EntityRubble.class, "entity_rubble", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_burning_foeq"), EntityBurningFOEQ.class, "entity_burning_foeq", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_mk3"), EntityNukeExplosionMK3.class, "entity_nuke_mk3", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_fleija_rainbow"), EntityCloudFleijaRainbow.class, "entity_fleija_rainbow", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_explosive_beam"), EntityExplosiveBeam.class, "entity_explosive_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_tainted_creeper"), EntityTaintedCreeper.class, "entity_tainted_creeper", i++, MainRegistry.instance, 80, 3, true, 0x813b9b, 0xd71fdd); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuclear_creeper"), EntityNuclearCreeper.class, "entity_nuclear_creeper", i++, MainRegistry.instance, 80, 3, true, 0x204131, 0x75CE00); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_cloud_no"), EntityNukeCloudNoShroom.class, "entity_nuke_cloud_no", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_cloud_fleija"), EntityCloudFleija.class, "entity_cloud_fleija", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_bullet"), EntityBullet.class, "entity_bullet", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_gasflame_fx"), EntityGasFlameFX.class, "entity_gasflame_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_rocket"), EntityRocket.class, "entity_rocket", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_fire"), EntityFire.class, "entity_fire", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_aa_shell"), EntityAAShell.class, "entity_aa_shell", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_bomber"), EntityBomber.class, "entity_bomber", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_agent_orange"), EntityOrangeFX.class, "entity_agent_orange", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_pink_cloud_fx"), EntityPinkCloudFX.class, "entity_pink_cloud_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_cloud_fx"), EntityCloudFX.class, "entity_cloud_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_chlorine_fx"), EntityChlorineFX.class, "entity_chlorine_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_stinger"), EntityRocketHoming.class, "entity_stinger", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_t_smoke_fx"), EntityTSmokeFX.class, "entity_t_smoke_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_boxcar"), EntityBoxcar.class, "entity_boxcar", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_zeta"), EntityBombletZeta.class, "entity_zeta", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_emp"), EntityEMP.class, "entity_emp", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_theta"), EntityBombletTheta.class, "entity_theta", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_selena"), EntityBombletSelena.class, "entity_selena", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_black_hole"), EntityBlackHole.class, "entity_black_hole", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_emp_blast"), EntityEMPBlast.class, "entity_emp_blast", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_bullet_mk2"), EntityBulletBase.class, "entity_bullet_mk2", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_duchessgambit"), EntityDuchessGambit.class, "entity_duchessgambit", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_spark_beam"), EntitySparkBeam.class, "entity_spark_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_mod_beam"), EntityModBeam.class, "entity_mod_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_vortex"), EntityVortex.class, "entity_vortex", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_raging_vortex"), EntityRagingVortex.class, "entity_raging_vortex", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_mini_nuke"), EntityMiniNuke.class, "entity_mini_nuke", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_mini_mirv"), EntityMiniMIRV.class, "entity_mini_mirv", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_baleflare"), EntityBaleflare.class, "entity_baleflare", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_balefire"), EntityBalefire.class, "entity_balefire", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_rainbow"), EntityRainbow.class, "entity_rainbow", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_plasma_beam"), EntityPlasmaBeam.class, "entity_plasma_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_ln2"), EntityLN2.class, "entity_ln2", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_combine_ball"), EntityCombineBall.class, "entity_combine_ball", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_discharge"), EntityDischarge.class, "entity_discharge", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_schrab"), EntitySchrab.class, "entity_schrab", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_generic"), EntityGrenadeGeneric.class, "entity_grenade_generic", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_strong"), EntityGrenadeStrong.class, "entity_grenade_strong", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_frag"), EntityGrenadeFrag.class, "entity_grenade_frag", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_fire"), EntityGrenadeFire.class, "entity_grenade_fire", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_cluster"), EntityGrenadeCluster.class, "entity_grenade_cluster", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_flare"), EntityGrenadeFlare.class, "entity_grenade_flare", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_electric"), EntityGrenadeElectric.class, "entity_grenade_electric", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_poison"), EntityGrenadePoison.class, "entity_grenade_poison", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_gas"), EntityGrenadeGas.class, "entity_grenade_gas", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_schrabidium"), EntityGrenadeSchrabidium.class, "entity_grenade_schrabidium", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_pulse"), EntityGrenadePulse.class, "entity_grenade_pulse", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_plasma"), EntityGrenadePlasma.class, "entity_grenade_plasma", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_tau"), EntityGrenadeTau.class, "entity_grenade_tau", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_cloud"), EntityGrenadeCloud.class, "entity_grenade_cloud", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_pc"), EntityGrenadePC.class, "entity_grenade_pc", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_smart"), EntityGrenadeSmart.class, "entity_grenade_smart", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_mirv"), EntityGrenadeMIRV.class, "entity_grenade_mirv", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_breach"), EntityGrenadeBreach.class, "entity_grenade_breach", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_burst"), EntityGrenadeBurst.class, "entity_grenade_burst", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_lemon"), EntityGrenadeLemon.class, "entity_grenade_lemon", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_mk2"), EntityGrenadeMk2.class, "entity_grenade_mk2", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_aschrab"), EntityGrenadeASchrab.class, "entity_grenade_aschrab", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_zomg"), EntityGrenadeZOMG.class, "entity_grenade_zomg", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_shrapnel"), EntityGrenadeShrapnel.class, "entity_grenade_shrapnel", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_black_hole"), EntityGrenadeBlackHole.class, "entity_grenade_black_hole", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_gascan"), EntityGrenadeGascan.class, "entity_grenade_gascan", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_nuke"), EntityGrenadeNuke.class, "entity_grenade_nuke", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_nuclear"), EntityGrenadeNuclear.class, "entity_grenade_nuclear", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_generic"), EntityGrenadeIFGeneric.class, "entity_grenade_if_generic", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_he"), EntityGrenadeIFHE.class, "entity_grenade_if_he", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_bouncy"), EntityGrenadeIFBouncy.class, "entity_grenade_if_bouncy", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_sticky"), EntityGrenadeIFSticky.class, "entity_grenade_if_sticky", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_impact"), EntityGrenadeIFImpact.class, "entity_grenade_if_impact", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_incendiary"), EntityGrenadeIFIncendiary.class, "entity_grenade_if_incendiary", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_toxic"), EntityGrenadeIFToxic.class, "entity_grenade_if_toxic", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_concussion"), EntityGrenadeIFConcussion.class, "entity_grenade_if_concussion", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_brimstone"), EntityGrenadeIFBrimstone.class, "entity_grenade_if_brimstone", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_mystery"), EntityGrenadeIFMystery.class, "entity_grenade_if_mystery", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_spark"), EntityGrenadeIFSpark.class, "entity_grenade_if_spark", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_hopwire"), EntityGrenadeIFHopwire.class, "entity_grenade_if_hopwire", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_grenade_if_null"), EntityGrenadeIFNull.class, "entity_grenade_if_null", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_generic"), EntityMissileGeneric.class, "entity_missile_generic", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_incendiary"), EntityMissileIncendiary.class, "entity_missile_incendiary", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_cluster"), EntityMissileCluster.class, "entity_missile_cluster", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_bunker_buster"), EntityMissileBunkerBuster.class, "entity_missile_bunker_buster", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_strong"), EntityMissileStrong.class, "entity_missile_strong", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_incendiary_strong"), EntityMissileIncendiaryStrong.class, "entity_missile_incendiary_strong", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_cluster_strong"), EntityMissileClusterStrong.class, "entity_missile_cluster_strong", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_buster_strong"), EntityMissileBusterStrong.class, "entity_missile_buster_strong", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_emp_strong"), EntityMissileEMPStrong.class, "entity_missile_emp_strong", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_burst"), EntityMissileBurst.class, "entity_missile_burst", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_inferno"), EntityMissileInferno.class, "entity_missile_inferno", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_rain"), EntityMissileRain.class, "entity_missile_rain", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_drill"), EntityMissileDrill.class, "entity_missile_drill", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_nuclear"), EntityMissileNuclear.class, "entity_missile_nuclear", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_mirv"), EntityMissileMirv.class, "entity_missile_mirv", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_endo"), EntityMissileEndo.class, "entity_missile_endo", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_exo"), EntityMissileExo.class, "entity_missile_exo", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_doomsday"), EntityMissileDoomsday.class, "entity_missile_doomsday", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_taint"), EntityMissileTaint.class, "entity_missile_taint", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_micro"), EntityMissileMicro.class, "entity_missile_micro", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_bhole"), EntityMissileBHole.class, "entity_missile_bhole", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_schrab"), EntityMissileSchrabidium.class, "entity_missile_schrab", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_emp"), EntityMissileEMP.class, "entity_missile_emp", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_missile_ab"), EntityMissileAntiBallistic.class, "entity_missile_ab", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_carrier"), EntityCarrier.class, "entity_carrier", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_booster"), EntityBooster.class, "entity_booster", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_deathblast"), EntityBlast.class, "entity_deathblast", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_railgun_pellet"), EntityRailgunBlast.class, "entity_railgun_pellet", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_gas_fx"), EntityGasFX.class, "entity_gas_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_oil_spill"), EntityOilSpill.class, "entity_oil_spill", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_oil_spill_fx"), EntityOilSpillFX.class, "entity_oil_spill_fx", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_clound_solinium"), EntityCloudSolinium.class, "entity_clound_solinium", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_cloud_big"), EntityNukeCloudBig.class, "entity_nuke_cloud_big", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_nuke_explosion_advanced"), EntityNukeExplosionPlus.class, "entity_nuke_explosion_advanced", i++, MainRegistry.instance, 250, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_falling_bomb"), EntityFallingNuke.class, "entity_falling_bomb", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_custom_missile"), EntityMissileCustom.class, "entity_custom_missile", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_laser_blast"), EntityDeathBlast.class, "entity_laser_blast", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_miner_rocket"), EntityMinerRocket.class, "entity_miner_rocket", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_meteor"), EntityMeteor.class, "entity_meteor", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_bobmazon"), EntityBobmazon.class, "entity_bobmazon", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_cyber_crab"), EntityCyberCrab.class, "entity_cyber_crab", i++, MainRegistry.instance, 250, 1, true, 0xAAAAAA, 0x444444); //Drillgon200: The hunter chopper is messed up and janky and I don't know what to about it. I'd probably have to recode the whole thing, and I don't have time for that. EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_hunter_chopper"), EntityHunterChopper.class, "entity_hunter_chopper", i++, MainRegistry.instance, 1000, 1, true, 0x000020, 0x2D2D72); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_chopper_mine"), EntityChopperMine.class, "entity_chopper_mine", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_water_splash"), EntityWaterSplash.class, "entity_water_splash", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_miner_beam"), EntityMinerBeam.class, "entity_miner_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_laser_beam"), EntityLaserBeam.class, "entity_laser_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_mirvlet"), EntityMIRV.class, "entity_mirvlet", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_building"), EntityBuilding.class, "entity_building", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_taint_crab"), EntityTaintCrab.class, "entity_taint_crab", i++, MainRegistry.instance, 250, 1, true, 0xAAAAAA, 0xFF00FF); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_tesla_crab"), EntityTeslaCrab.class, "entity_tesla_crab", i++, MainRegistry.instance, 250, 1, true, 0xAAAAAA, 0x440000); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_tom_the_moonstone"), EntityTom.class, "entity_tom_the_moonstone", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_tom_bust"), EntityTomBlast.class, "entity_tom_bust", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_soyuz_capsule"), EntitySoyuzCapsule.class, "entity_soyuz_capsule", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_soyuz"), EntitySoyuz.class, "entity_soyuz", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_laser"), EntityLaser.class, "entity_laser", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_c_item"), EntityMovingItem.class, "entity_c_item", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_moonstone_blast"), EntityCloudTom.class, "entity_moonstone_blast", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_mask_man"), EntityMaskMan.class, "entity_mask_man", i++, MainRegistry.instance, 1000, 1, true, 0xAAAAAA, 0xAAAAAA); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_balls_o_tron"), EntityBOTPrimeHead.class, "entity_balls_o_tron", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_balls_o_tron_seg"), EntityBOTPrimeBody.class, "entity_balls_o_tron_seg", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_fucc_a_ducc"), EntityDuck.class, "entity_fucc_a_ducc", i++, MainRegistry.instance, 1000, 1, true, 0xd0d0d0, 0xFFBF00); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_vortex_beam"), EntityBeamVortex.class, "entity_vortex_beam", i++, MainRegistry.instance, 1000, 1, true); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_elder_one"), EntityQuackos.class, "entity_elder_one", i++, MainRegistry.instance, 1000, 1, true, 0xd0d0d0, 0xFFBF00); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_ntm_fbi"), EntityFBI.class, "entity_ntm_fbi", i++, MainRegistry.instance, 1000, 1, true, 0x008000, 0x404040); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_ntm_radiation_blaze"), EntityRADBeast.class, "entity_ntm_radiation_blaze", i++, MainRegistry.instance, 1000, 1, true, 0x303030, 0x008000); EntityRegistry.registerModEntity(new ResourceLocation(RefStrings.MODID, "entity_firework_ball"), EntityFireworks.class, "entity_firework_ball", i++, MainRegistry.instance, 1000, 1, true); ForgeChunkManager.setForcedChunkLoadingCallback(this, new LoadingCallback() { @Override public void ticketsLoaded(List<Ticket> tickets, World world) { for(Ticket ticket : tickets) { if(ticket.getEntity() instanceof IChunkLoader) { ((IChunkLoader) ticket.getEntity()).init(ticket); } } } }); registerDispenserBehaviors(); } public static void reloadConfig() { Configuration config = new Configuration(new File(proxy.getDataDir().getPath() + "/config/hbm/hbm.cfg")); config.load(); GeneralConfig.loadFromConfig(config); WorldConfig.loadFromConfig(config); MachineConfig.loadFromConfig(config); BombConfig.loadFromConfig(config); RadiationConfig.loadFromConfig(config); PotionConfig.loadFromConfig(config); ToolConfig.loadFromConfig(config); WeaponConfig.loadFromConfig(config); MobConfig.loadFromConfig(config); config.save(); } @EventHandler public void init(FMLInitializationEvent event) { ModItems.init(); ModBlocks.init(); OreDictManager.registerOres(); HazmatRegistry.registerHazmats(); registerReactorFuels(); ControlRegistry.init(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { ModItems.postInit(); ModBlocks.postInit(); BlockCrate.setDrops(); FluidTypeHandler.registerFluidProperties(); ShredderRecipes.registerShredder(); ShredderRecipes.registerOverrides(); CrystallizerRecipes.register(); CentrifugeRecipes.register(); BreederRecipes.registerFuels(); BreederRecipes.registerRecipes(); AssemblerRecipes.loadRecipes(); CyclotronRecipes.register(); HadronRecipes.register(); MagicRecipes.register(); TileEntityNukeCustom.registerBombItems(); FluidContainerRegistry.registerContainer(Item.getItemFromBlock(ModBlocks.lox_barrel), ModItems.tank_steel, new FluidStack(ModForgeFluids.oxygen, 10000)); FluidContainerRegistry.registerContainer(Item.getItemFromBlock(ModBlocks.pink_barrel), ModItems.tank_steel, new FluidStack(ModForgeFluids.kerosene, 10000)); FluidContainerRegistry.registerContainer(Item.getItemFromBlock(ModBlocks.red_barrel), ModItems.tank_steel, new FluidStack(ModForgeFluids.diesel, 10000)); FluidContainerRegistry.registerContainer(ModItems.bottle_mercury, Items.GLASS_BOTTLE, new FluidStack(ModForgeFluids.mercury, 1000)); FluidContainerRegistry.registerContainer(ModItems.particle_hydrogen, ModItems.particle_empty, new FluidStack(ModForgeFluids.hydrogen, 1000)); FluidContainerRegistry.registerContainer(ModItems.particle_amat, ModItems.particle_empty, new FluidStack(ModForgeFluids.amat, 1000)); FluidContainerRegistry.registerContainer(ModItems.particle_aschrab, ModItems.particle_empty, new FluidStack(ModForgeFluids.aschrab, 1000)); FluidContainerRegistry.registerContainer(Item.getItemFromBlock(ModBlocks.ore_gneiss_gas), Item.getItemFromBlock(ModBlocks.stone_gneiss), new FluidStack(ModForgeFluids.petroleum, 250)); //Drillgon200: expand the max entity radius for the hunter chopper if(World.MAX_ENTITY_RADIUS < 5) World.MAX_ENTITY_RADIUS = 5; proxy.postInit(event); } @EventHandler public void serverStarting(FMLServerStartingEvent evt) { evt.registerServerCommand(new CommandRadiation()); evt.registerServerCommand(new CommandHbm()); AdvancementManager.init(evt.getServer()); //MUST be initialized AFTER achievements!! BobmazonOfferFactory.reset(); BobmazonOfferFactory.init(); } private void registerReactorFuels(){ TileEntityMachineReactorLarge.registerFuelEntry(1, ReactorFuelType.URANIUM, ModItems.nugget_uranium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(9, ReactorFuelType.URANIUM, ModItems.ingot_uranium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(6, ReactorFuelType.URANIUM, ModItems.rod_uranium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(12, ReactorFuelType.URANIUM, ModItems.rod_dual_uranium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(24, ReactorFuelType.URANIUM, ModItems.rod_quad_uranium_fuel); TileEntityMachineReactorLarge.registerWasteEntry(6, ReactorFuelType.URANIUM, ModItems.rod_empty, ModItems.rod_uranium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(12, ReactorFuelType.URANIUM, ModItems.rod_dual_empty, ModItems.rod_dual_uranium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(24, ReactorFuelType.URANIUM, ModItems.rod_quad_empty, ModItems.rod_quad_uranium_fuel_depleted); TileEntityMachineReactorLarge.registerFuelEntry(1, ReactorFuelType.PLUTONIUM, ModItems.nugget_plutonium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(9, ReactorFuelType.PLUTONIUM, ModItems.ingot_plutonium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(6, ReactorFuelType.PLUTONIUM, ModItems.rod_plutonium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(12, ReactorFuelType.PLUTONIUM, ModItems.rod_dual_plutonium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(24, ReactorFuelType.PLUTONIUM, ModItems.rod_quad_plutonium_fuel); TileEntityMachineReactorLarge.registerWasteEntry(6, ReactorFuelType.PLUTONIUM, ModItems.rod_empty, ModItems.rod_plutonium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(12, ReactorFuelType.PLUTONIUM, ModItems.rod_dual_empty, ModItems.rod_dual_plutonium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(24, ReactorFuelType.PLUTONIUM, ModItems.rod_quad_empty, ModItems.rod_quad_plutonium_fuel_depleted); TileEntityMachineReactorLarge.registerFuelEntry(1, ReactorFuelType.MOX, ModItems.nugget_mox_fuel); TileEntityMachineReactorLarge.registerFuelEntry(9, ReactorFuelType.MOX, ModItems.ingot_mox_fuel); TileEntityMachineReactorLarge.registerFuelEntry(6, ReactorFuelType.MOX, ModItems.rod_mox_fuel); TileEntityMachineReactorLarge.registerFuelEntry(12, ReactorFuelType.MOX, ModItems.rod_dual_mox_fuel); TileEntityMachineReactorLarge.registerFuelEntry(24, ReactorFuelType.MOX, ModItems.rod_quad_mox_fuel); TileEntityMachineReactorLarge.registerWasteEntry(6, ReactorFuelType.MOX, ModItems.rod_empty, ModItems.rod_mox_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(12, ReactorFuelType.MOX, ModItems.rod_dual_empty, ModItems.rod_dual_mox_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(24, ReactorFuelType.MOX, ModItems.rod_quad_empty, ModItems.rod_quad_mox_fuel_depleted); TileEntityMachineReactorLarge.registerFuelEntry(10, ReactorFuelType.SCHRABIDIUM, ModItems.nugget_schrabidium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(90, ReactorFuelType.SCHRABIDIUM, ModItems.ingot_schrabidium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(60, ReactorFuelType.SCHRABIDIUM, ModItems.rod_schrabidium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(120, ReactorFuelType.SCHRABIDIUM, ModItems.rod_dual_schrabidium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(240, ReactorFuelType.SCHRABIDIUM, ModItems.rod_quad_schrabidium_fuel); TileEntityMachineReactorLarge.registerWasteEntry(60, ReactorFuelType.SCHRABIDIUM, ModItems.rod_empty, ModItems.rod_schrabidium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(120, ReactorFuelType.SCHRABIDIUM, ModItems.rod_dual_empty, ModItems.rod_dual_schrabidium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(240, ReactorFuelType.SCHRABIDIUM, ModItems.rod_quad_empty, ModItems.rod_quad_schrabidium_fuel_depleted); TileEntityMachineReactorLarge.registerFuelEntry(1, ReactorFuelType.THORIUM, ModItems.nugget_thorium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(9, ReactorFuelType.THORIUM, ModItems.ingot_thorium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(6, ReactorFuelType.THORIUM, ModItems.rod_thorium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(12, ReactorFuelType.THORIUM, ModItems.rod_dual_thorium_fuel); TileEntityMachineReactorLarge.registerFuelEntry(24, ReactorFuelType.THORIUM, ModItems.rod_quad_thorium_fuel); TileEntityMachineReactorLarge.registerWasteEntry(6, ReactorFuelType.THORIUM, ModItems.rod_empty, ModItems.rod_thorium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(12, ReactorFuelType.THORIUM, ModItems.rod_dual_empty, ModItems.rod_dual_thorium_fuel_depleted); TileEntityMachineReactorLarge.registerWasteEntry(24, ReactorFuelType.THORIUM, ModItems.rod_quad_empty, ModItems.rod_quad_thorium_fuel_depleted); } private void registerDispenserBehaviors(){ BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_generic, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeGeneric(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_strong, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeStrong(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_frag, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeFrag(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_fire, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeFire(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_cluster, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeCluster(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_flare, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeFlare(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_electric, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeElectric(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_poison, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadePoison(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_gas, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeGas(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_schrabidium, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeSchrabidium(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_nuke, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeNuke(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_nuclear, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeNuclear(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_pulse, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadePulse(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_plasma, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadePlasma(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_tau, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeTau(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_lemon, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeLemon(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_mk2, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeMk2(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_aschrab, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeASchrab(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_zomg, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeZOMG(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_shrapnel, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeShrapnel(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_black_hole, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeBlackHole(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_gascan, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeGascan(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_cloud, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeCloud(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_pink_cloud, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadePC(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_smart, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeSmart(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_mirv, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeMIRV(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_breach, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeBreach(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_burst, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeBurst(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_generic, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFGeneric(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_he, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFHE(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_bouncy, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFBouncy(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_sticky, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFSticky(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_impact, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFImpact(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_incendiary, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFIncendiary(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_toxic, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFToxic(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_concussion, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFConcussion(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_brimstone, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFBrimstone(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_mystery, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFMystery(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_spark, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFSpark(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_hopwire, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFHopwire(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.grenade_if_null, new BehaviorProjectileDispense() { @Override protected IProjectile getProjectileEntity(World p_82499_1_, IPosition p_82499_2_, ItemStack stack) { return new EntityGrenadeIFNull(p_82499_1_, p_82499_2_.getX(), p_82499_2_.getY(), p_82499_2_.getZ()); } }); } }
84.526108
237
0.811411
3639fd09232a3b13b478d7d77499d42dcddf6833
1,552
/* * Copyright 2014 Google 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.google.common.jimfs; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.nio.file.SecureDirectoryStream; import java.util.Iterator; /** * A thin wrapper around a {@link SecureDirectoryStream} that exists only to implement {@link * DirectoryStream} and NOT implement {@link SecureDirectoryStream}. * * @author Colin Decker */ final class DowngradedDirectoryStream implements DirectoryStream<Path> { private final SecureDirectoryStream<Path> secureDirectoryStream; DowngradedDirectoryStream(SecureDirectoryStream<Path> secureDirectoryStream) { this.secureDirectoryStream = checkNotNull(secureDirectoryStream); } @Override public Iterator<Path> iterator() { return secureDirectoryStream.iterator(); } @Override public void close() throws IOException { secureDirectoryStream.close(); } }
30.431373
93
0.765464
bf1b2d51f5c7ab3a9a8a58ac07327250d456863f
651
import java.util.Scanner; public class IndexPatternOfBestIndex { public static void main(String... args) { int n; int terms = 0; int i, j , k; Scanner scan = new Scanner(System.in); n = scan.nextInt(); for(i = 0 ; i < n ; i++) { terms = 0; for(j = i ; j < n - terms ; j++, terms++) { for(k = j ; k <= j + terms ; k++) System.out.print(k + " "); j = k - 1; System.out.print(" * "); } System.out.println(); } scan.close(); } }
25.038462
77
0.379416
f83d1bec1bb71aa143d9bef503eb0dbbda23d6f6
13,812
/* * 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.camel.component.jpa; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import org.apache.camel.Exchange; import org.apache.camel.Expression; import org.apache.camel.Message; import org.apache.camel.language.simple.SimpleLanguage; import org.apache.camel.support.DefaultProducer; import org.apache.camel.support.ExchangeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import static org.apache.camel.component.jpa.JpaHelper.getTargetEntityManager; public class JpaProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(JpaProducer.class); private final EntityManagerFactory entityManagerFactory; private final TransactionTemplate transactionTemplate; private final Expression expression; private String query; private String namedQuery; private String nativeQuery; private boolean findEntity; private Map<String, Object> parameters; private Class<?> resultClass; private QueryFactory queryFactory; private Boolean useExecuteUpdate; public JpaProducer(JpaEndpoint endpoint, Expression expression) { super(endpoint); this.expression = expression; this.entityManagerFactory = endpoint.getEntityManagerFactory(); this.transactionTemplate = endpoint.createTransactionTemplate(); } @Override public JpaEndpoint getEndpoint() { return (JpaEndpoint) super.getEndpoint(); } public QueryFactory getQueryFactory() { if (queryFactory == null) { if (query != null) { queryFactory = QueryBuilder.query(query); } else if (namedQuery != null) { queryFactory = QueryBuilder.namedQuery(namedQuery); } else if (nativeQuery != null) { if (resultClass != null) { queryFactory = QueryBuilder.nativeQuery(nativeQuery, resultClass); } else { queryFactory = QueryBuilder.nativeQuery(nativeQuery); } } } return queryFactory; } public void setQueryFactory(QueryFactory queryFactory) { this.queryFactory = queryFactory; } public void setParameters(Map<String, Object> params) { this.parameters = params; } public Map<String, Object> getParameters() { return parameters; } public String getNamedQuery() { return namedQuery; } public void setNamedQuery(String namedQuery) { this.namedQuery = namedQuery; } public String getNativeQuery() { return nativeQuery; } public void setNativeQuery(String nativeQuery) { this.nativeQuery = nativeQuery; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public boolean isFindEntity() { return findEntity; } public void setFindEntity(boolean findEntity) { this.findEntity = findEntity; } public Class<?> getResultClass() { return resultClass; } public void setResultClass(Class<?> resultClass) { this.resultClass = resultClass; } public void setUseExecuteUpdate(Boolean executeUpdate) { this.useExecuteUpdate = executeUpdate; } public boolean isUseExecuteUpdate() { if (useExecuteUpdate == null) { if (query != null) { if (query.regionMatches(true, 0, "select", 0, 6)) { useExecuteUpdate = false; } else { useExecuteUpdate = true; } } else if (nativeQuery != null) { if (nativeQuery.regionMatches(true, 0, "select", 0, 6)) { useExecuteUpdate = false; } else { useExecuteUpdate = true; } } else { useExecuteUpdate = false; } } return useExecuteUpdate; } @Override public void process(final Exchange exchange) { // resolve the entity manager before evaluating the expression final EntityManager entityManager = getTargetEntityManager(exchange, entityManagerFactory, getEndpoint().isUsePassedInEntityManager(), getEndpoint().isSharedEntityManager(), true); if (findEntity) { processFind(exchange, entityManager); } else if (getQueryFactory() != null) { processQuery(exchange, entityManager); } else { processEntity(exchange, entityManager); } } protected void processQuery(Exchange exchange, EntityManager entityManager) { Query query = getQueryFactory().createQuery(entityManager); configureParameters(query, exchange); transactionTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { if (getEndpoint().isJoinTransaction()) { entityManager.joinTransaction(); } Message target; if (ExchangeHelper.isOutCapable(exchange)) { target = exchange.getOut(); // preserve headers target.getHeaders().putAll(exchange.getIn().getHeaders()); } else { target = exchange.getIn(); } Object answer = isUseExecuteUpdate() ? query.executeUpdate() : query.getResultList(); target.setBody(answer); if (getEndpoint().isFlushOnSend()) { entityManager.flush(); } return null; } }); } @SuppressWarnings("unchecked") private void configureParameters(Query query, Exchange exchange) { int maxResults = getEndpoint().getMaximumResults(); if (maxResults > 0) { query.setMaxResults(maxResults); } // setup the parameters Map<String, ?> params; if (parameters != null) { params = parameters; } else { params = exchange.getIn().getHeader(JpaConstants.JPA_PARAMETERS_HEADER, Map.class); } if (params != null) { params.forEach((key, value) -> { Object resolvedValue = value; if (value instanceof String) { resolvedValue = SimpleLanguage.expression((String) value).evaluate(exchange, Object.class); } query.setParameter(key, resolvedValue); }); } } protected void processFind(Exchange exchange, EntityManager entityManager) { final Object key = exchange.getMessage().getBody(); if (key != null) { transactionTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { if (getEndpoint().isJoinTransaction()) { entityManager.joinTransaction(); } Object answer = entityManager.find(getEndpoint().getEntityType(), key); LOG.debug("Find: {} -> {}", key, answer); Message target; if (ExchangeHelper.isOutCapable(exchange)) { target = exchange.getOut(); // preserve headers target.getHeaders().putAll(exchange.getIn().getHeaders()); } else { target = exchange.getIn(); } target.setBody(answer); if (getEndpoint().isFlushOnSend()) { entityManager.flush(); } return null; } }); } } protected void processEntity(Exchange exchange, EntityManager entityManager) { final Object values = expression.evaluate(exchange, Object.class); if (values != null) { transactionTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { if (getEndpoint().isJoinTransaction()) { entityManager.joinTransaction(); } if (values.getClass().isArray()) { Object[] array = (Object[]) values; // need to create an array to store returned values as they can be updated // by JPA such as setting auto assigned ids Object[] managedArray = new Object[array.length]; Object managedEntity; for (int i = 0; i < array.length; i++) { Object element = array[i]; if (!getEndpoint().isRemove()) { managedEntity = save(element); } else { managedEntity = remove(element); } managedArray[i] = managedEntity; } if (!getEndpoint().isUsePersist()) { // and copy back to original array System.arraycopy(managedArray, 0, array, 0, array.length); exchange.getIn().setBody(array); } } else if (values instanceof Collection) { Collection<?> collection = (Collection<?>) values; // need to create a list to store returned values as they can be updated // by JPA such as setting auto assigned ids Collection managedCollection = new ArrayList<>(collection.size()); Object managedEntity; for (Object entity : collection) { if (!getEndpoint().isRemove()) { managedEntity = save(entity); } else { managedEntity = remove(entity); } managedCollection.add(managedEntity); } if (!getEndpoint().isUsePersist()) { exchange.getIn().setBody(managedCollection); } } else { Object managedEntity; if (!getEndpoint().isRemove()) { managedEntity = save(values); } else { managedEntity = remove(values); } if (!getEndpoint().isUsePersist()) { exchange.getIn().setBody(managedEntity); } } if (getEndpoint().isFlushOnSend()) { entityManager.flush(); } return null; } /** * Save the given entity and return the managed entity * * @return the managed entity */ private Object save(final Object entity) { LOG.debug("save: {}", entity); if (getEndpoint().isUsePersist()) { entityManager.persist(entity); return entity; } else { return entityManager.merge(entity); } } /** * Remove the given entity and return the managed entity * * @return the managed entity */ private Object remove(final Object entity) { LOG.debug("remove: {}", entity); Object managedEntity; // First check if entity is attached to the persistence context if (entityManager.contains(entity)) { managedEntity = entity; } else { // If not, merge entity state into context before removing it managedEntity = entityManager.merge(entity); } entityManager.remove(managedEntity); return managedEntity; } }); } } }
37.129032
111
0.540327
83009de22d85254fa7889356f31c15938980c1e1
3,049
package org.apache.maven.plugin; /* * 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. */ import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.component.repository.exception.ComponentRepositoryException; import org.codehaus.plexus.configuration.PlexusConfigurationException; /** * Exception which occurs to indicate that the plugin cannot be initialized due * to some deeper problem with Plexus. Context information includes the groupId, * artifactId, and version for the plugin; at times, the goal name for which * execution failed; a message detailing the problem; the ClassRealm used to * lookup the plugin; and the Plexus exception that caused this error. * * @author jdcasey * */ public class PluginContainerException extends PluginManagerException { private ClassRealm pluginRealm; public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, Throwable e ) { super( mojoDescriptor, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, ComponentLookupException e ) { super( mojoDescriptor, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, Throwable e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, PlexusConfigurationException e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, ComponentRepositoryException e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public ClassRealm getPluginRealm() { return pluginRealm; } }
34.647727
121
0.71958
26d6721211ec01a8f4d8dfeb12b4453203a3c535
2,114
/* * 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.beam.runners.flink.translation.functions; import com.google.common.collect.Iterables; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.WindowFn; import org.apache.beam.sdk.util.WindowedValue; import org.joda.time.Instant; /** * {@link org.apache.beam.sdk.transforms.windowing.WindowFn.AssignContext} for * Flink functions. */ class FlinkAssignContext<InputT, W extends BoundedWindow> extends WindowFn<InputT, W>.AssignContext { private final WindowedValue<InputT> value; FlinkAssignContext(WindowFn<InputT, W> fn, WindowedValue<InputT> value) { fn.super(); if (Iterables.size(value.getWindows()) != 1) { throw new IllegalArgumentException( String.format( "%s passed to window assignment must be in a single window, but it was in %s: %s", WindowedValue.class.getSimpleName(), Iterables.size(value.getWindows()), value.getWindows())); } this.value = value; } @Override public InputT element() { return value.getValue(); } @Override public Instant timestamp() { return value.getTimestamp(); } @Override public BoundedWindow window() { return Iterables.getOnlyElement(value.getWindows()); } }
33.555556
96
0.720435
3e3da7394198f8665acbbfbf352f4454e7a4a7e3
1,246
package allbegray.slack.webapi.method.files; import java.util.Map; import allbegray.slack.webapi.method.AbstractPagingMethod; import allbegray.slack.webapi.SlackWebApiConstants; public class FileListMethod extends AbstractPagingMethod { protected String user; protected String ts_from; protected String ts_to; protected String types; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getTs_from() { return ts_from; } public void setTs_from(String ts_from) { this.ts_from = ts_from; } public String getTs_to() { return ts_to; } public void setTs_to(String ts_to) { this.ts_to = ts_to; } public String getTypes() { return types; } public void setTypes(String types) { this.types = types; } @Override public String getMethodName() { return SlackWebApiConstants.FILES_LIST; } @Override protected void createParameters(Map<String, String> parameters) { super.createParameters(parameters); if (user != null) { parameters.put("user", user); } parameters.put("ts_from", ts_from != null ? ts_from : "0"); parameters.put("ts_to", ts_to != null ? ts_to : "now"); parameters.put("types", types != null ? types : "all"); } }
19.46875
66
0.714286
0f89f390e51796acb77e55af449bdff8b6e67c25
6,064
package com.wya.uikit.popupwindow; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.PopupWindow; import com.chad.library.adapter.base.BaseQuickAdapter; import com.wya.uikit.R; import java.util.ArrayList; import java.util.List; /** * 创建日期:2018/11/21 16:22 * 作者: Mao Chunjiang * 文件名称: WYAPopupWindow * 类说明:自定义popupwindow */ public class WYAPopupWindow extends PopupWindow { private Activity context; private CustomListener customListener; private int layoutRes; private View contentView; private int backgroundImg = R.drawable.popup_window_icon_other_9; private LinearLayout ll_popup_window; private List<String> list = new ArrayList<>(); private RecyclerView recyclerView; private PopupWindListAdapter popupWindListAdapter; private PopupWindowListOnclickListener popupWindowListOnclickListener;//列表点击监听 private static final long DURATION = 500; private static final float START_ALPHA = 0.7f; private static final float END_ALPHA = 1f; private float bgAlpha = 1f; private boolean bright = false; private AnimUtil animUtil; /** * 设置确定按钮被点击的接口 */ public interface PopupWindowListOnclickListener { void onPopupWindowListClick(int position); } /** * 设置列表点击事件 * * @param popupWindowListOnclickListener */ public void setPopupWindowListOnclickListener(PopupWindowListOnclickListener popupWindowListOnclickListener) { this.popupWindowListOnclickListener = popupWindowListOnclickListener; } public WYAPopupWindow(Builder builder) { super(builder.context); this.context = builder.context; this.list = builder.list; this.customListener = builder.customListener; this.backgroundImg = builder.backgroundImg; this.layoutRes = builder.layoutRes; initView(builder.context); } @SuppressLint("NewApi") private void initView(Context context) { contentView = LayoutInflater.from(context).inflate(layoutRes, null); if (customListener == null) { recyclerView = contentView.findViewById(R.id.popup_window_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(context)); popupWindListAdapter = new PopupWindListAdapter(context, R.layout.popwindow_menu_item, list); recyclerView.setAdapter(popupWindListAdapter); ll_popup_window = contentView.findViewById(R.id.ll_popup_window); ll_popup_window.setBackground(context.getResources().getDrawable(backgroundImg)); //RecyclerView条目点击事件 popupWindListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { popupWindowListOnclickListener.onPopupWindowListClick(position); } }); } else { customListener.customLayout(contentView); } setContentView(contentView); this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); // 设置pop透明效果 this.setBackgroundDrawable(new ColorDrawable(0x0000)); // 设置pop出入动画 this.setAnimationStyle(R.style.pop_add); // 设置pop获取焦点,如果为false点击返回按钮会退出当前Activity,如果pop中有Editor的话,focusable必须要为true this.setFocusable(true); // 设置pop可点击,为false点击事件无效,默认为true this.setTouchable(true); // 设置点击pop外侧消失,默认为false;在focusable为true时点击外侧始终消失 this.setOutsideTouchable(true); // 设置pop关闭监听,用于改变背景透明度 this.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { toggleBright(false); } }); } public static final class Builder { private Activity context; private List<String> list = new ArrayList<>(); private int layoutRes = R.layout.wya_pop_add; private CustomListener customListener; private int backgroundImg = R.drawable.popup_window_icon_other_9; public Builder(Activity context) { this.context = context; } public Builder setLayoutRes(int res, CustomListener listener) { this.layoutRes = res; this.customListener = listener; return this; } public Builder list(List<String> list) { this.list = list; return this; } public Builder backgroundImg(int backgroundImg) { this.backgroundImg = backgroundImg; return this; } public WYAPopupWindow build() { return new WYAPopupWindow(this); } } /** * 显示popupwindow * * @param view * @param xoff * @param yoff */ public void show(View view, int xoff, int yoff) { toggleBright(true); this.showAsDropDown(view, xoff, yoff); } /** * 根据popupwindow修改背景颜色 */ private void toggleBright(final boolean isShow) { WindowManager.LayoutParams lp = context.getWindow().getAttributes(); if (isShow) { lp.alpha = (float) 0.5; context.getWindow().setAttributes(lp); context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } else { lp.alpha = (float) 1.0; context.getWindow().setAttributes(lp); context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } animUtil = new AnimUtil(); animUtil.startAnimator(); } }
32.778378
114
0.670515
263aa6874f6159425742cd5f234a0fd749a1a624
5,270
package com.peralex.utilities.ui.table; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.text.ParseException; import java.util.EventObject; import javax.swing.AbstractAction; import javax.swing.DefaultCellEditor; import javax.swing.JFormattedTextField; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.CellEditorListener; import javax.swing.table.TableCellEditor; import javax.swing.text.DefaultFormatterFactory; import javax.swing.tree.TreeCellEditor; /** * A CellEditor for java.util.Date that displays only the time portion of the value. * * It also has the useful side-effect that it preserves the year/month/days value in the input. * * @author Noel Grandin */ public class TimeCellEditor implements TableCellEditor, TreeCellEditor { private static final Border BORDER_DEFAULT = new LineBorder(Color.black); private static final Border BORDER_ERROR = new LineBorder(Color.red); /* Normally I would subclass DefaultCellEditor, but because I need to construct * other stuff before calling the DefaultCellEditor constructor, I have to delegate * the functionality. */ private final DefaultCellEditor delegate; /** * Override the setValue() method so that when the user hits ESCAPE to revert to the original * value, we can clear the error border. */ private static class MyFormattedTextField extends JFormattedTextField { @Override public void setValue(Object value) { super.setValue(value); if (isEditValid()) { setBorder(BORDER_DEFAULT); } } } public TimeCellEditor() { this.delegate = new DefaultCellEditor(new MyFormattedTextField()); final JFormattedTextField ftf = (JFormattedTextField) delegate.getComponent(); ftf.setFormatterFactory(new DefaultFormatterFactory(new TimeFormatter())); ftf.setFocusLostBehavior(JFormattedTextField.PERSIST); /* * React when the user presses Enter while the editor is active. * (Tab is handled as specified by JFormattedTextField's focusLostBehavior property). */ ftf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check"); ftf.getActionMap().put("check", new AbstractAction() { public void actionPerformed(ActionEvent e) { // if the text is invalid if (!ftf.isEditValid()) { ftf.setBorder(BORDER_ERROR); } else // The text is valid { ftf.setBorder(BORDER_DEFAULT); // reset the border try { ftf.commitEdit(); // use the value } catch (ParseException ex) { ex.printStackTrace(); } ftf.postActionEvent(); } } }); } public boolean stopCellEditing() { JFormattedTextField ftf = (JFormattedTextField) delegate.getComponent(); if (ftf.isEditValid()) { try { ftf.commitEdit(); } catch (java.text.ParseException ex) { ex.printStackTrace(); } } else // text is invalid { ftf.setBorder(BORDER_ERROR); return false; // don't let the editor go away } /* * call the superclass method, which will fire an editting stopped event and return true. */ return delegate.stopCellEditing(); } /** Override to * (a) reset border on the formatted text field. * (b) set the value directly since the DefaultCellEditor class will call toString() before passing * the data to the JFormattedTextField. */ public JFormattedTextField getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { final JFormattedTextField ftf = (JFormattedTextField) delegate.getComponent(); ftf.setValue(value); // reset the border ftf.setBorder(BORDER_DEFAULT); return ftf; } /** Override to * (a) reset border on the formatted text field. * (b) set the value directly since the DefaultCellEditor class will call toString() before passing * the data to the JFormattedTextField. */ public JFormattedTextField getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { final JFormattedTextField ftf = (JFormattedTextField) delegate.getComponent(); ftf.setValue(value); // reset the border ftf.setBorder(BORDER_DEFAULT); return ftf; } /** Override to ensure that the value remains of type java.util.Date. */ public java.util.Date getCellEditorValue() { final JFormattedTextField ftf = (JFormattedTextField) delegate.getComponent(); java.util.Date date = (java.util.Date) ftf.getValue(); return date; } public void addCellEditorListener(CellEditorListener l) { delegate.addCellEditorListener(l); } public void cancelCellEditing() { delegate.cancelCellEditing(); } public boolean isCellEditable(EventObject anEvent) { return delegate.isCellEditable(anEvent); } public void removeCellEditorListener(CellEditorListener l) { delegate.removeCellEditorListener(l); } public boolean shouldSelectCell(EventObject anEvent) { return delegate.shouldSelectCell(anEvent); } }
29.116022
142
0.712524
c9665b8d7de4fc17c9045372c3ecfc5ee83c7785
1,904
package com.poc.urlshortener.config; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.config.AbstractCassandraConfiguration; import org.springframework.data.cassandra.config.SchemaAction; import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification; import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; import lombok.Getter; @Configuration @EnableCassandraRepositories(basePackages = "com.poc.urlshortener.repo") @Getter public class CassandraConfig extends AbstractCassandraConfiguration { @Value("${spring.data.cassandra.contact-points}") private String contactPoints; @Value("${spring.data.cassandra.port}") private int port; @Value("${spring.data.cassandra.username:#{null}}") private String username; @Value("${spring.data.cassandra.password:#{null}}") private String password; @Value("${spring.data.cassandra.schema-action}") private String schemaAction; @Value("${vcap.services.cig-cassandra.credentials.seeds:}") private List<String> seeds; @Override public SchemaAction getSchemaAction() { return SchemaAction.CREATE_IF_NOT_EXISTS; } @Override protected List<CreateKeyspaceSpecification> getKeyspaceCreations() { Integer replicationFactor = seeds.isEmpty() ? 1 : seeds.size(); return List.of(CreateKeyspaceSpecification.createKeyspace(getKeyspaceName()).ifNotExists() .withSimpleReplication(replicationFactor)); } @Value("${spring.data.cassandra.keyspace}") private String keyspace; @Override protected String getKeyspaceName() { return getKeyspace(); } @Override public String getContactPoints() { return contactPoints; } @Override public String[] getEntityBasePackages() { return new String[] { "com.poc.urlshortener.entity" }; } }
28
92
0.788866
85289086bdfae3a28346f46c392d592d4cb5db56
389
package items.weapons; import items.tools.Tool; import util.Constants; public class BoneAxe extends Tool { private static final long serialVersionUID = 1L; public BoneAxe() { super(); this.setHarvestRate(Constants.BONE_TOOL_UNITS_PER_SECOND); setWeight(Constants.BONE_TOOL_WEIGHT); setIsAxe(true); this.setDamage(11); setImageID(2, 13); this.name = "Bone Axe"; } }
16.913043
60
0.737789
21ada3de2bc4c9ae6c04ffc2e4fce40b16a49c24
1,295
package clertonleal.com.nubank.util; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class FormatUtil { private static final SimpleDateFormat shortDateFormat = new SimpleDateFormat("dd MMM", new Locale("pt", "BR")); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd 'de' MMMM", new Locale("pt", "BR")); private static final SimpleDateFormat monthFormat = new SimpleDateFormat("MMM", new Locale("pt", "BR")); private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(new Locale("pt", "BR")); public static String getMonth(Date date) { return monthFormat.format(date).toUpperCase(); } public static String getDate(Date date) { return dateFormat.format(date).toUpperCase(); } public static String getShortDate(Date date) { return shortDateFormat.format(date).toUpperCase(); } public static String getShortMonetaryValue(long value) { Double temp = (double) value; temp = temp/100; return numberFormat.format(temp); } public static String getMonetaryValue(long value) { return numberFormat.getCurrency().getSymbol() + " " + getShortMonetaryValue(value); } }
34.078947
116
0.708108
519f45768973f1571fe2d59442a69b76fc17baa0
2,067
/* * @(#)module-scraper --- PushMail.java */ package com.codebelief.app.pushupdate; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.codebelief.app.bean.Content; import com.codebelief.app.bean.Url; import com.codebelief.app.compare.SingleUpdateRecord; import com.codebelief.app.dao.ContentDao; import com.codebelief.app.dao.UrlDao; import com.codebelief.app.dao.UserDao; import com.codebelief.app.mail.DeltaObject; import com.codebelief.app.mail.SendMail; /** * @author 何涛 * @version 1st on 2017年11月14日 */ @Component public class PushMail { private static ContentDao contentDao; private static UrlDao urlDao; private static UserDao userDao; public static void PushUpdateMail(String UserName) throws Exception{ Map<Object, Object> parameters = new HashMap<Object, Object>(); List<Url> urlList = urlDao.doFindAllEnabled(UserName); if(urlList.size()!=0){ for(int i = 0; i < urlList.size(); i++){ Content content = contentDao.doFindAllByUrlID(urlList.get(i).getUrlID()); LinkedList<SingleUpdateRecord> updateList = new LinkedList<SingleUpdateRecord>(); if(content != null &&!"".equals(content.getDelta())){ String[] Deltas = content.getDelta().split("\n\n"); for(String Delta:Deltas) updateList.add(new SingleUpdateRecord(Delta)); parameters.put("" + i, new DeltaObject(urlList.get(i).getTitle(),urlList.get(i).getUrl(),updateList)); } } String email = userDao.doFindEmail(UserName); Map<Object, Object> urlMap = new HashMap<>(); urlMap.put("urlMap", parameters); SendMail.sendMail("update", "网页更新订阅新内容推送", email, urlMap); } } @Autowired public void setUrlDao(UrlDao urlDao) { PushMail.urlDao = urlDao; } @Autowired public void setContentDao(ContentDao contentDao) { PushMail.contentDao = contentDao; } @Autowired public void setUserDao(UserDao userDao) { PushMail.userDao = userDao; } }
29.112676
107
0.732463
7339514504fd97258a9b91200a05d9d99bb34d84
13,300
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.screens.datasource.management.backend.core.wildfly; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import javax.naming.InitialContext; import org.kie.workbench.common.screens.datasource.management.backend.core.DataSource; import org.kie.workbench.common.screens.datasource.management.backend.core.DataSourceProvider; import org.kie.workbench.common.screens.datasource.management.backend.integration.wildfly.WildflyDataSourceDef; import org.kie.workbench.common.screens.datasource.management.backend.integration.wildfly.WildflyDataSourceManagementClient; import org.kie.workbench.common.screens.datasource.management.model.DataSourceDef; import org.kie.workbench.common.screens.datasource.management.model.DataSourceDeploymentInfo; import org.kie.workbench.common.screens.datasource.management.model.DataSourceStatus; import org.kie.workbench.common.screens.datasource.management.model.DriverDeploymentInfo; import org.kie.workbench.common.screens.datasource.management.util.UUIDGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Wildly based implementation of a DataSourceProvider. */ @ApplicationScoped @Named(value = "WildflyDataSourceProvider" ) public class WildflyDataSourceProvider implements DataSourceProvider { private static final Logger logger = LoggerFactory.getLogger( WildflyDataSourceProvider.class ); private WildflyDriverProvider driverProvider; private WildflyDataSourceManagementClient dataSourceMgmtClient = new WildflyDataSourceManagementClient(); private Map<String, WildlfyDataSource> managedDataSources = new HashMap<>( ); private Map<String, WildlfyDataSource> unManagedDataSources = new HashMap<>( ); public WildflyDataSourceProvider() { } @Inject public WildflyDataSourceProvider( WildflyDriverProvider driverProvider ) { this.driverProvider = driverProvider; } /** * Gets the list of data source definitions for the currently defined data sources in the Wildfly server. * * @return list with the definitions for the defined data sources. * * @throws Exception exceptions may be thrown if e.g. communication with the Wildfly server fails, etc. */ @Override public List<DataSourceDef> getDeployments() throws Exception { List<WildflyDataSourceDef> dataSources; List<DataSourceDef> dataSourceDefs = new ArrayList<>( ); DataSourceDef dataSourceDef; String dataSourceUuid; String driverUuid; dataSources = dataSourceMgmtClient.getDataSources(); for ( WildflyDataSourceDef internalDef : dataSources ) { dataSourceDef = new DataSourceDef(); try { dataSourceUuid = DeploymentIdGenerator.extractUuid( internalDef.getName() ); } catch ( Exception e ) { dataSourceUuid = internalDef.getName(); } try { driverUuid = DeploymentIdGenerator.extractUuid( internalDef.getDriverName() ); } catch ( Exception e ) { driverUuid = internalDef.getDriverName(); } dataSourceDef.setUuid( dataSourceUuid ); dataSourceDef.setName( internalDef.getName() ); dataSourceDef.setConnectionURL( internalDef.getConnectionURL() ); dataSourceDef.setDriverUuid( driverUuid ); dataSourceDef.setUser( internalDef.getUser() ); dataSourceDef.setPassword( internalDef.getPassword() ); dataSourceDefs.add( dataSourceDef ); } return dataSourceDefs; } @Override public DataSourceDeploymentInfo deploy( DataSourceDef dataSourceDef ) throws Exception { //This random identifiers calculation should be removed when WF supports deletion //of data sources without letting them published on server until next restart. String random = "_" + generateRandomUUID(); String deploymentId = DeploymentIdGenerator.generateDeploymentId( dataSourceDef ) + random; String kieJndi = JndiNameGenerator.generateJNDIName( dataSourceDef ); String deploymentJndi = kieJndi + random; DataSourceDeploymentInfo deploymentInfo = deploy( dataSourceDef, deploymentJndi, deploymentId ); javax.sql.DataSource dataSource = (javax.sql.DataSource) jndiLookupDataSource( deploymentJndi ); WildlfyDataSource wfDataSource = new WildlfyDataSource( dataSource, deploymentJndi ); managedDataSources.put( deploymentId, wfDataSource ); return deploymentInfo; } /** * protected for helping tests programming. */ protected String generateRandomUUID() { return UUIDGenerator.generateUUID(); } /** * Creates a data source in the Wildfly server. * * @param dataSourceDef Data source definition to be created. * * @param jndi jndi name to be use the Wildly server to bound the data source in the jndi context. * * @return returns the deployment information for the created data source. * * @throws Exception exceptions may be thrown if the data source couldn't be created. */ private DataSourceDeploymentInfo deploy( final DataSourceDef dataSourceDef, final String jndi, String deploymentId ) throws Exception { DriverDeploymentInfo driverDeploymentInfo = driverProvider.getDeploymentInfo( dataSourceDef.getDriverUuid() ); if ( driverDeploymentInfo == null ) { throw new Exception( "Required driver: " + dataSourceDef.getDriverUuid() + " is not deployed." ); } WildflyDataSourceDef wfDataSourceDef = buildWFDataSource( deploymentId, jndi, dataSourceDef, driverDeploymentInfo.getDriverDeploymentId() ); dataSourceMgmtClient.createDataSource( wfDataSourceDef ); return new DataSourceDeploymentInfo( deploymentId, true, dataSourceDef.getUuid(), jndi, false ); } public DataSourceDeploymentInfo resync( DataSourceDef dataSourceDef, DataSourceDeploymentInfo deploymentInfo ) throws Exception { javax.sql.DataSource dataSource = (javax.sql.DataSource) jndiLookupDataSource( deploymentInfo.getJndi() ); WildlfyDataSource wfDataSource = new WildlfyDataSource( dataSource, deploymentInfo.getJndi() ); managedDataSources.put( deploymentInfo.getDeploymentId(), wfDataSource ); return deploymentInfo; } @Override public void undeploy( final DataSourceDeploymentInfo deploymentInfo ) throws Exception { DataSourceDeploymentInfo currentDeploymentInfo = getDeploymentInfo( deploymentInfo.getUuid() ); if ( currentDeploymentInfo == null ) { throw new Exception( "DataSource: " + deploymentInfo.getUuid() + " is not deployed" ); } dataSourceMgmtClient.deleteDataSource( currentDeploymentInfo.getDeploymentId() ); managedDataSources.remove( currentDeploymentInfo.getDeploymentId() ); } /** * Gets the deployment information about a data source definition. * * @param uuid the data source definition identifier. * * @return the deployment information for the data source definition of null if no data source has been created * with the given uuid. * * @throws Exception exceptions may be thrown if e.g. communication with the Wildfly server fails, etc. */ public DataSourceDeploymentInfo getDeploymentInfo( final String uuid ) throws Exception { for ( DataSourceDeploymentInfo deploymentInfo : getDeploymentsInfo() ) { if ( uuid.equals( deploymentInfo.getUuid() ) ) { return deploymentInfo; } } return null; } /** * Gets the deployment information for all the data sources currently defined on the Wildfly server. * * @return a list with the deployment information for all the data sources. * * @throws Exception exceptions may be thrown if e.g. communication with the Wildfly server fails, etc. */ public List<DataSourceDeploymentInfo> getDeploymentsInfo() throws Exception { List<WildflyDataSourceDef> dataSources = dataSourceMgmtClient.getDataSources(); List<DataSourceDeploymentInfo> result = new ArrayList<>( ); DataSourceDeploymentInfo deploymentInfo; String uuid; WildlfyDataSource managedDataSource; boolean managed; String jndi; for ( WildflyDataSourceDef internalDef : dataSources ) { try { uuid = DeploymentIdGenerator.extractUuid( internalDef.getName() ); } catch ( Exception e ) { uuid = internalDef.getName(); } managedDataSource = managedDataSources.get( internalDef.getName() ); if ( managedDataSource != null ) { managed = true; jndi = managedDataSource.getExternalJndi(); } else { managed = false; jndi = internalDef.getJndi(); } deploymentInfo = new DataSourceDeploymentInfo( internalDef.getName(), managed, uuid, jndi, wasReferenced( internalDef.getName() ) ); result.add( deploymentInfo ); } return result; } @Override public DataSource lookupDataSource( DataSourceDeploymentInfo deploymentInfo ) throws Exception { WildlfyDataSource dataSource = managedDataSources.get( deploymentInfo.getDeploymentId() ); if ( dataSource == null ) { dataSource = unManagedDataSources.get( deploymentInfo.getDeploymentId() ); } if ( dataSource == null ) { DataSourceDeploymentInfo refreshedDeploymentInfo = getDeploymentInfo( deploymentInfo.getUuid() ); if ( refreshedDeploymentInfo != null && refreshedDeploymentInfo.getJndi() != null ) { javax.sql.DataSource sqlDataSource = (javax.sql.DataSource) jndiLookupDataSource( refreshedDeploymentInfo.getJndi() ); if ( sqlDataSource != null) { dataSource = new WildlfyDataSource( sqlDataSource, refreshedDeploymentInfo.getJndi() ); unManagedDataSources.put( deploymentInfo.getDeploymentId(), dataSource ); return dataSource; } } } if ( dataSource != null ) { if ( dataSource.isNew() ) { //first access to the data source dataSource.setStatus( DataSourceStatus.REFERENCED ); } return dataSource; } else { throw new Exception( "Data source for: " + deploymentInfo + " is not deployed in current system." ); } } @Override public void loadConfig( Properties properties ) { dataSourceMgmtClient.loadConfig( properties ); driverProvider.loadConfig( properties ); } /** * protected for helping tests programming. */ protected Object jndiLookupDataSource( String jndi ) { try { InitialContext context = new InitialContext(); return context.lookup( jndi ); } catch ( Exception e ) { logger.warn( "JNDI lookup failed for name: {}", jndi ); return null; } } private WildflyDataSourceDef buildWFDataSource( String deploymentId, String jndi, DataSourceDef dataSourceDef, String driverDeploymentId ) { WildflyDataSourceDef wfDataSourceDef = new WildflyDataSourceDef(); wfDataSourceDef.setName( deploymentId ); wfDataSourceDef.setDriverName( driverDeploymentId ); wfDataSourceDef.setJndi( jndi ); wfDataSourceDef.setConnectionURL( dataSourceDef.getConnectionURL() ); wfDataSourceDef.setUser( dataSourceDef.getUser() ); wfDataSourceDef.setPassword( dataSourceDef.getPassword() ); wfDataSourceDef.setUseJTA( true ); return wfDataSourceDef; } private boolean wasReferenced( String deploymentId ) { WildlfyDataSource dataSource = managedDataSources.get( deploymentId ); if ( dataSource == null ) { dataSource = unManagedDataSources.get( deploymentId ); } if ( dataSource != null ) { return dataSource.isReferenced(); } return false; } public void setDataSourceMgmtClient( WildflyDataSourceManagementClient dataSourceMgmtClient ) { this.dataSourceMgmtClient = dataSourceMgmtClient; } }
43.464052
139
0.68812
cfc0d2f24638f7db9c1c1d70cc4b6fad42807e8b
1,387
/* * Copyright © 2015 www.raisecom.com and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package com.hashcms.sdna.impl; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sdna.rev150105.SdnaService; import org.opendaylight.controller.sal.binding.api.BindingAwareProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SdnaProvider implements BindingAwareProvider, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(SdnaProvider.class); private RpcRegistration<SdnaService> service; private DataBroker dataBroker; @Override public void onSessionInitiated(ProviderContext session) { service = session.addRpcImplementation(SdnaService.class, new SdnaImpl()); dataBroker = session.getSALService(DataBroker.class); LOG.info("SdnaProvider Session Initiated"); } @Override public void close() throws Exception { LOG.info("SdnaProvider Closed"); } }
37.486486
99
0.806777
2b71e9dbeeef8637285151b40804d2914ba809c2
849
//Luis Guzman //Homework 3 //3/21/10 /*PSEUDOCODE: Display dialog that asks the user for the retail price of circuit board and save it to the input variable. Convert input to a double and save it to RetailPrice variable. Multiply RetailPrice by .4 and save result in the profit variable. Diplay dialog message Profit is profit variable*/ import javax.swing.JOptionPane; public class Circuit_board { public static void main (String args[]) { double profit, RetailPrice; String input; input = JOptionPane.showInputDialog("What is the retail price of " + "the circuit board?"); //convert input to a double and save it in the RetailPrice variable. RetailPrice = Double.parseDouble(input); profit = RetailPrice * .4; JOptionPane.showMessageDialog(null, "Profit is " + profit); System.exit(0); } }
33.96
71
0.71967
75efdfaa556dcab97da0244c8853464c95181dd5
6,544
package com.gempukku.swccgo.cards.set13.dark; import com.gempukku.swccgo.cards.AbstractLostInterrupt; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.common.Icon; import com.gempukku.swccgo.common.Side; import com.gempukku.swccgo.common.Uniqueness; import com.gempukku.swccgo.filters.Filter; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.game.state.GameState; import com.gempukku.swccgo.logic.GameUtils; import com.gempukku.swccgo.logic.actions.PlayInterruptAction; import com.gempukku.swccgo.logic.effects.*; import com.gempukku.swccgo.logic.timing.Action; import java.util.Collections; import java.util.List; /** * Set: Reflections III * Type: Interrupt * Subtype: Lost * Title: No Match For A Sith */ public class Card13_079 extends AbstractLostInterrupt { public Card13_079() { super(Side.DARK, 4, "No Match For A Sith", Uniqueness.UNIQUE); setLore("Lightsaber duels are so fast and furious that Jedi don't plan their offensive strategy, but instead rely on instinct and their ability to sense an opponent's next strike."); setGameText("If Maul armed with a lightsaber in battle, use 2 Force to draw two destiny. Opponent draws two destiny. If any of your destinies equal any of opponent's destinies, opponent's Jedi is power = 0 for remainder of battle."); addIcons(Icon.REFLECTIONS_III, Icon.EPISODE_I); } @Override protected List<PlayInterruptAction> getGameTextTopLevelActions(final String playerId, SwccgGame game, final PhysicalCard self) { final String opponent = game.getOpponent(playerId); final Filter targetFilter = Filters.and(Filters.opponents(self), Filters.Jedi, Filters.participatingInBattle); // Check condition(s) if (GameConditions.isDuringBattleWithParticipant(game, Filters.and(Filters.Maul, Filters.armedWith(Filters.lightsaber))) && GameConditions.canUseForceToPlayInterrupt(game, playerId, self, 2) && GameConditions.canTarget(game, self, targetFilter)) { final PlayInterruptAction action = new PlayInterruptAction(game, self); action.setText("Make both players draw two destiny"); // Choose target(s) action.appendTargeting( new TargetCardOnTableEffect(action, playerId, "Choose opponent's Jedi", targetFilter) { @Override protected void cardTargeted(final int targetGroupId, final PhysicalCard targetedCard) { // Pay cost(s) action.appendCost( new UseForceEffect(action, playerId, 2)); // Allow response(s) action.allowResponses("Make both players draw two destiny while targeting " + GameUtils.getCardLink(targetedCard), new RespondablePlayCardEffect(action) { @Override protected void performActionResults(Action targetingAction) { // Get the targeted card(s) from the action using the targetGroupId. // This needs to be done in case the target(s) were changed during the responses. final PhysicalCard finalTarget = targetingAction.getPrimaryTargetCard(targetGroupId); // Perform result(s) action.appendEffect( new DrawDestinyEffect(action, playerId, 2) { @Override protected void destinyDraws(SwccgGame game, List<PhysicalCard> destinyCardDraws, final List<Float> destinyDrawValues1, final Float totalDestiny1) { action.appendEffect( new DrawDestinyEffect(action, opponent, 2) { @Override protected void destinyDraws(SwccgGame game, List<PhysicalCard> destinyCardDraws, List<Float> destinyDrawValues2, Float totalDestiny2) { GameState gameState = game.getGameState(); for (Float drawValues1 : destinyDrawValues1) { for (Float drawValues2 : destinyDrawValues2) { if (drawValues2.equals(drawValues1)) { gameState.sendMessage("Result: Succeeded"); action.appendEffect( new ResetPowerUntilEndOfBattleEffect(action, finalTarget, 0)); return; } } } gameState.sendMessage("Result: Failed"); } } ); } } ); } } ); } } ); return Collections.singletonList(action); } return null; } }
64.156863
241
0.471883
df9b14ddf45ace32a66ce90885097cec8f74fbe0
4,484
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.address.logic.commands.CommandTestUtil.showGroupAtIndex; import static seedu.address.testutil.TypicalGroups.GROUPNAME1; import static seedu.address.testutil.TypicalGroups.GROUPNAME2; import static seedu.address.testutil.TypicalGroups.VALID_UNINSTATITATED_GROUP; import static seedu.address.testutil.TypicalGroups.getTypicalAddressBookWithGroups; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_GROUP; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_STUDENT; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_GROUP; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_STUDENT; import org.junit.jupiter.api.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.group.Group; /** * Contains integration tests (interaction with the Model) and unit tests for * {@code DeleteStudentCommand}. */ public class AddMemberCommandTest { private final Model model = new ModelManager(getTypicalAddressBookWithGroups(), new UserPrefs()); // Pass @Test public void execute_invalidIndexUnfilteredList_throwsCommandException() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredStudentList().size() + 1); Group groupToBeAdded = model.getFilteredGroupList().get(INDEX_FIRST_GROUP.getZeroBased()); AddMemberCommand addMemberCommand = new AddMemberCommand(outOfBoundIndex, groupToBeAdded.getName()); assertCommandFailure(addMemberCommand, model, Messages.MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX); } // Pass @Test public void execute_invalidGroupUnfilteredList_throwsCommandException() { AddMemberCommand addMemberCommand = new AddMemberCommand(INDEX_FIRST_STUDENT, VALID_UNINSTATITATED_GROUP); assertCommandFailure(addMemberCommand, model, Messages.MESSAGE_INVALID_GROUP_DISPLAYED_NAME); } @Test public void execute_invalidIndexAndGroupUnfilteredList_throwsCommandException() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredStudentList().size() + 1); AddMemberCommand addMemberCommand = new AddMemberCommand(outOfBoundIndex, VALID_UNINSTATITATED_GROUP); assertCommandFailure(addMemberCommand, model, Messages.MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX); } // Pass @Test public void execute_invalidIndexFilteredList_throwsCommandException() { showGroupAtIndex(model, INDEX_FIRST_GROUP); Index outOfBoundIndex = INDEX_SECOND_GROUP; // ensures that outOfBoundIndex is still in bounds of address book list assertTrue(outOfBoundIndex.getZeroBased() < model.getAddressBook().getGroupList().size()); AddMemberCommand addMemberCommand = new AddMemberCommand(outOfBoundIndex, GROUPNAME1); assertCommandFailure(addMemberCommand, model, Messages.MESSAGE_INVALID_GROUP_MEMBER_INDEX); } // Pass @Test public void equals() { AddMemberCommand addMemberCommand = new AddMemberCommand(INDEX_FIRST_STUDENT, GROUPNAME1); AddMemberCommand addSecondCommand = new AddMemberCommand(INDEX_SECOND_STUDENT, GROUPNAME2); // same object -> returns true assertTrue(addMemberCommand.equals(addMemberCommand)); // same values -> returns true AddMemberCommand addFirstCommandCopy = new AddMemberCommand(INDEX_FIRST_STUDENT, GROUPNAME1); assertTrue(addMemberCommand.equals(addFirstCommandCopy)); // different types -> returns false assertFalse(addMemberCommand.equals(1)); // null -> returns false assertFalse(addMemberCommand.equals(null)); // different group -> returns false assertFalse(addMemberCommand.equals(addSecondCommand)); } /** * Updates {@code model}'s filtered list to show no one. */ private void showNoGroup(Model model) { model.updateFilteredGroupList(p -> false); assertTrue(model.getFilteredGroupList().isEmpty()); } }
40.035714
104
0.753568
5bca586398cef1f914344c9a1a50aa8e28080c83
4,014
package unquietcode.tools.esm; import org.junit.Test; import unquietcode.tools.esm.sequences.Pattern; import unquietcode.tools.esm.sequences.PatternBuilder; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; /** * @author Ben Fagin * @version 2013-07-08 */ public class Sequence_T { @Test public void test_sequential_match() { GenericStateMachine<Color> sm = new GenericStateMachine<>(Color.Red); sm.addTransition(Color.Red, Color.Blue); sm.addTransition(Color.Blue, Color.Green); sm.addTransition(Color.Green, Color.Orange); sm.addTransition(Color.Orange, Color.Red); final List<Color> _pattern = Arrays.asList(Color.Blue, Color.Green, Color.Orange); final AtomicInteger counter = new AtomicInteger(0); sm.onSequence(_pattern, pattern -> { assertEquals(_pattern, pattern); counter.incrementAndGet(); }); sm.transition(Color.Blue); sm.transition(Color.Green); sm.transition(Color.Orange); sm.transition(Color.Red); assertEquals(1, counter.get()); } @Test public void test_sequential_match_with_wildcard() { EnumStateMachine<Color> sm = new EnumStateMachine<>(); sm.addAll(Color.class, true, true); final Pattern<Color> _pattern = PatternBuilder.<Color>create() .add(Color.Red, Color.Blue) .addWildcard() .add(Color.Green) .build(); final AtomicInteger counter = new AtomicInteger(0); sm.onSequence(_pattern, pattern -> { counter.incrementAndGet(); }); sm.transition(Color.Red); sm.transition(Color.Blue); sm.transition(Color.Orange); sm.transition(Color.Green); assertEquals(1, counter.get()); } @Test public void test_sequential_match_on_initial_state() { EnumStateMachine<Color> sm = new EnumStateMachine<>(Color.Red); sm.addTransition(Color.Red, Color.Green); sm.addTransition(Color.Green, Color.Orange); sm.addTransition(Color.Orange, Color.Red); final List<Color> _pattern = Arrays.asList(Color.Red, Color.Green, Color.Orange); final AtomicInteger counter = new AtomicInteger(0); sm.onSequence(_pattern, pattern -> { assertEquals(_pattern, pattern); counter.incrementAndGet(); }); sm.transition(Color.Green); sm.transition(Color.Orange); assertEquals(1, counter.get()); } @Test public void test_sequential_match_with_null_initial_state() { EnumStateMachine<Color> sm = new EnumStateMachine<>(null); sm.addTransition(null, Color.Green); sm.addTransition(Color.Green, Color.Orange); sm.addTransition(Color.Orange, Color.Red); final List<Color> _pattern = Arrays.asList(null, Color.Green, Color.Orange); final AtomicInteger counter = new AtomicInteger(0); sm.onSequence(_pattern, pattern -> { assertEquals(_pattern, pattern); counter.incrementAndGet(); }); sm.transition(Color.Green); sm.transition(Color.Orange); assertEquals(1, counter.get()); } @Test public void test_sequential_match_with_differing_list_sizes() { EnumStateMachine<ZState> esm = new EnumStateMachine<>(); esm.addAll(ZState.class, true, true); List<ZState> threeStatePattern = Arrays.asList(ZState.One, ZState.Two, ZState.Three); List<ZState> fourStatePattern = Arrays.asList(ZState.One, ZState.Two, ZState.Three, ZState.Four); final AtomicInteger counter1 = new AtomicInteger(0); final AtomicInteger counter2 = new AtomicInteger(0); esm.onSequence(threeStatePattern, pattern -> counter1.incrementAndGet()); esm.onSequence(fourStatePattern, pattern -> counter2.incrementAndGet()); esm.transition(ZState.One); esm.transition(ZState.Two); assertEquals(0, counter1.get()); assertEquals(0, counter2.get()); esm.transition(ZState.Three); assertEquals(1, counter1.get()); assertEquals(0, counter2.get()); esm.transition(ZState.Four); assertEquals(1, counter1.get()); assertEquals(1, counter2.get()); } public enum Color implements State { Red, Blue, Green, Orange } public enum ZState implements State { One, Two, Three, Four, Five } }
27.682759
99
0.736173
9ebc3daf95390d1f8ae625965873090d22e622f1
1,543
package com.k.multithread.chapter04; import com.k.multithread.util.Debug; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; public class DownloadBuffer implements Closeable { /** * 当前Buffer中缓冲的数据相对于整个存储文件的位置偏移 */ private long globaloffset; private long upperBound; private int offset = 0; public final ByteBuffer byteBuf; private final Storage storage; public DownloadBuffer(long globaloffset, long upperBound, final Storage storage) { this.globaloffset = globaloffset; this.upperBound = upperBound; this.byteBuf = ByteBuffer.allocate(1024 * 1024); this.storage = storage; } public void write (ByteBuffer buf) throws IOException { int length = buf.position(); final int capacity = byteBuf.capacity(); //当前缓冲区已满,或者剩余容量不够容纳新数据 if (offset + length > capacity || length == capacity) { //将缓冲区中的数据写入文件 flush(); } byteBuf.position(offset); buf.flip(); byteBuf.put(buf); offset += length; } public void flush() throws IOException { int length; byteBuf.flip(); length = storage.store(globaloffset, byteBuf); byteBuf.clear(); globaloffset += length; offset = 0; } @Override public void close() throws IOException { Debug.info("globalOffset:%s,upperBound:%s", globaloffset, upperBound); if (globaloffset < upperBound) { flush(); } } }
28.054545
86
0.624109
9f93b4b65eea85e6a4a8a99e8c7d52cbdcd0ac0a
1,103
package db.entity; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; /** * The persistent class for the persistent_logins database table. * */ @Entity @Table(name="persistent_logins") @NamedQuery(name="PersistentLogin.findAll", query="SELECT p FROM PersistentLogin p") public class PersistentLogin implements Serializable { private static final long serialVersionUID = 1L; @Id private String series; @Column(name="last_used") private Timestamp lastUsed; private String token; private String username; public PersistentLogin() { } public String getSeries() { return this.series; } public void setSeries(String series) { this.series = series; } public Timestamp getLastUsed() { return this.lastUsed; } public void setLastUsed(Timestamp lastUsed) { this.lastUsed = lastUsed; } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } }
17.507937
84
0.733454
a694bcfcb3e98c9b64683a23b8e00dea1326bc6d
207
package lk.ijse.dep.MostWantedCabs.DAO.custom; import lk.ijse.dep.MostWantedCabs.DAO.CrudDAO; import lk.ijse.dep.MostWantedCabs.Entity.Return; public interface ReturnDAO extends CrudDAO<Return,String> { }
25.875
59
0.816425
ffdef91c7104d3f01720619d4c60f3de69eb36e0
444
package example_14_replace_inheritance_with_delegation; import java.util.Random; public class Congress { private boolean consent; private final int bound = 10; private boolean isConsent() { return consent; } private void setConsent() { Random random = new Random(); if(random.nextInt(bound)<6) { consent = true; return; } consent = false; } public boolean requestConsent() { setConsent(); return isConsent(); } }
17.76
55
0.709459
5d4c071e9eec50e8e88226260c0914b9b355b19a
2,249
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.psi.search; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Processor; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IdFilter; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Set; public class FileNameIndexServiceImpl implements FileNameIndexService { private final FileBasedIndex myIndex; public FileNameIndexServiceImpl(@NotNull FileBasedIndex index) { myIndex = index; } @Override public Collection<VirtualFile> getVirtualFilesByName(Project project, String name, GlobalSearchScope scope, IdFilter filter) { Set<VirtualFile> files = new THashSet<>(); myIndex.processValues(FilenameIndexImpl.NAME, name, null, (file, value) -> { files.add(file); return true; }, scope, filter); return files; } @Override public void processAllFileNames(Processor<String> processor, GlobalSearchScope scope, IdFilter filter) { myIndex.processAllKeys(FilenameIndexImpl.NAME, processor, scope, filter); } @Override public Collection<VirtualFile> getFilesWithFileType(FileType fileType, GlobalSearchScope scope) { return myIndex.getContainingFiles(FileTypeIndexImpl.NAME, fileType, scope); } @Override public boolean processFilesWithFileType(FileType fileType, Processor<VirtualFile> processor, GlobalSearchScope scope) { return myIndex.processValues(FileTypeIndexImpl.NAME, fileType, null, (file, value) -> processor.process(file), scope); } }
36.868852
128
0.771009
24d8367b00c8366307ca2361f379c544ca9e0330
2,115
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.reporting; import org.mockito.invocation.Invocation; import org.mockito.invocation.MatchableInvocation; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Makes sure both wanted and actual are printed consistently (single line or multiline) * <p> * Makes arguments printed with types if necessary */ public class SmartPrinter { private final String wanted; private final List<String> actuals; public SmartPrinter(MatchableInvocation wanted, Invocation actual, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { this(wanted, Collections.singletonList(actual), indexesOfMatchersToBeDescribedWithExtraTypeInfo); } public SmartPrinter(MatchableInvocation wanted, List<Invocation> allActualInvocations, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { PrintSettings printSettings = new PrintSettings(); printSettings.setMultiline(isMultiLine(wanted, allActualInvocations)); printSettings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchersToBeDescribedWithExtraTypeInfo); this.wanted = printSettings.print(wanted); List<String> actuals = new ArrayList<String>(); for (Invocation actual : allActualInvocations) { actuals.add(printSettings.print(actual)); } this.actuals = Collections.unmodifiableList(actuals); } public String getWanted() { return wanted; } public List<String> getActuals() { return actuals; } private static boolean isMultiLine(MatchableInvocation wanted, List<Invocation> allActualInvocations) { boolean isWantedMultiline = wanted.toString().contains("\n"); boolean isAnyActualMultiline = false; for (Invocation invocation : allActualInvocations) { isAnyActualMultiline |= invocation.toString().contains("\n"); } return isWantedMultiline || isAnyActualMultiline; } }
35.25
153
0.734752
34e9788431419bd0b82c1f5e8fa07bde438d1415
1,222
package racingcar; public class InputValidator { private static final int LIMIT_OF_NAME_LENGTH = 5; public void validateNamesWithComma(String namesWithComma) throws IllegalArgumentException { if (namesWithComma.endsWith(",")) { throw new IllegalArgumentException("[ERROR] 이름이 ,로 끝나서는 안됩니다."); } String[] names = namesWithComma.split(","); for (String name : names) { validateName(name); } } public void validateRoundString(String roundString) throws IllegalArgumentException { if (!roundString.chars().allMatch(Character::isDigit)) { throw new IllegalArgumentException("[ERROR] 횟수는 1 이상의 정수여야 합니다."); } int round = Integer.parseInt(roundString); if (round == 0) { throw new IllegalArgumentException("[ERROR] 횟수가 0 이여서는 안됩니다."); } } private void validateName(String name) throws IllegalArgumentException { if (name.isBlank()) { throw new IllegalArgumentException("[ERROR] 이름이 공백이여선 안됩니다."); } if (name.length() > LIMIT_OF_NAME_LENGTH) { throw new IllegalArgumentException("[ERROR] 이름은 5자 이하여야 합니다."); } } }
34.914286
95
0.628478
fb0f886e45f03aa453e6af97f54da3f476b305bd
2,484
package com.liveramp.captain.example.internals; import java.util.Map; import java.util.Optional; import com.liveramp.captain.status.CaptainStatus; import com.liveramp.commons.collections.map.MapBuilder; import static com.liveramp.captain.example.ExampleCaptainWorkflow.APP1; import static com.liveramp.captain.example.ExampleCaptainWorkflow.APP2; import static com.liveramp.captain.example.ExampleCaptainWorkflow.STEP1; import static com.liveramp.captain.example.ExampleCaptainWorkflow.STEP2; import static com.liveramp.captain.example.ExampleCaptainWorkflow.STEP5; /* * code so that the ExampleCaptainWorkflow can run, but not actually useful in learning about captain. */ public class MockDb { // our mock db for the sake of running some requests through our captain workflow. feel free to ignore. use a real db. private static final Map<Long, MockRequest> requests = MapBuilder .of(1L, new MockRequest(1L, CaptainStatus.READY, STEP1, APP1, Optional.empty())) .put(2L, new MockRequest(2L, CaptainStatus.READY, STEP2, APP1, Optional.empty())) .put(3L, new MockRequest(3L, CaptainStatus.READY, STEP1, APP2, Optional.empty())) .get(); private long pointer = 1; public MockRequest getNextRequest() { // if everything is done stop kill the example captain workflow... // normally it would run until you killed it, but for the example, we don't want to run forever. if (requests.values().stream().allMatch(req -> req.step.equals(STEP5))) { Runtime.getRuntime().exit(10); } // find the request we visited least recently that's not done. while (true) { pointer = pointer == 3L ? 1L : pointer + 1; MockRequest request = requests.get(pointer); if (!request.step.equals(STEP5)) { return request; } } } /* * Mock Queries */ public MockRequest getRequest(long id) { return requests.get(id); } public void setRequestState(long id, CaptainStatus status, String step) { requests.put(id, new MockRequest(id, status, step, requests.get(id).appType, requests.get(id).requestHandle)); } public void setRequestState(long id, CaptainStatus status) { setRequestState(id, status, requests.get(id).step); } public void setRequestHandle(long id, long requestHandle) { MockRequest previousState = requests.get(id); requests.put(id, new MockRequest(id, previousState.status, previousState.step, previousState.appType, Optional.of(requestHandle))); } }
37.636364
135
0.730274
bdc36797cc80b90f94e648ae90237773b3598901
2,643
/* * Copyright 2003-2013 JetBrains s.r.o. * * 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 jetbrains.mps.nodeEditor.hintsSettings; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.project.Project; import jetbrains.mps.nodeEditor.hintsSettings.ConceptEditorHintSettingsComponent.HintsState; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Set; /** * Semen Alperovich * 05 15, 2013 */ @State( name = "ConceptEditorHintSettings", storages = @Storage(StoragePathMacros.WORKSPACE_FILE) ) public class ConceptEditorHintSettingsComponent implements PersistentStateComponent<HintsState>, ProjectComponent { private HintsState myState = new HintsState(); public ConceptEditorHintSettingsComponent(Project project) { } @Override public void initComponent() { } @Override public void disposeComponent() { } @NotNull @Override public String getComponentName() { return "Editor Context Hints Configurable"; } @NotNull @Override public HintsState getState() { HintsState state = new HintsState(); state.setEnabledHints(myState.getEnabledHints()); return state; } @Override public void loadState(@NotNull HintsState state) { myState = new HintsState(); myState.setEnabledHints(state.getEnabledHints()); } @Override public void projectOpened() { } @Override public void projectClosed() { } public static ConceptEditorHintSettingsComponent getInstance(Project project) { return project.getComponent(ConceptEditorHintSettingsComponent.class); } public static class HintsState { private Set<String> myEnabledHints = new HashSet<>(); public Set<String> getEnabledHints() { return myEnabledHints; } public void setEnabledHints(Set<String> enabledHints) { myEnabledHints = new HashSet<>(enabledHints); } } }
26.69697
115
0.754067
5faaedec516ba4773653bd469ff7844043a7db43
711
package com.csl.factory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author MaoLongLong * @date 2021-03-17 14:38:10 */ class OperationFactoryTest { @Test void testOperationFactory() { testOperation(3, 1, '+', 2); testOperation(2, 5, '-', 3); testOperation(4.5, 3, '*', 1.5); testOperation(2.5, 5, '/', 2); } void testOperation(double expected, double numberA, char op, double numberB) { Operation operation = OperationFactory.createOperation(op); operation.setNumberA(numberA); operation.setNumberB(numberB); assertEquals(expected, operation.getResult()); } }
25.392857
82
0.64557
8f057c5022461f07fa9161cdd1da2037a2c77dbd
2,853
/* * package : com.antsoft.ant.debugger * source : LoadedClassesTreeCellRenderer.java * date : 1999.8.9 * * Ant ( JDK wrapper Java IDE ) * Version 1.0 * Copyright (c) 1998-1999 Antsoft Co. All rights reserved. * This program and source file is protected by Korea and international * Copyright laws. * * Author: Lee, Chul Mok * $Header: /usr/cvsroot/AntIDE/source/com/antsoft/ant/debugger/LoadedClassesTreeCellRenderer.java,v 1.2 1999/08/10 04:59:36 itree Exp $ * $Revision: 1.2 $ * $History: LoadedClassesTreeCellRenderer.java $ */ package com.antsoft.ant.debugger; import java.awt.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import com.antsoft.ant.util.ImageList; public class LoadedClassesTreeCellRenderer extends DefaultTreeCellRenderer { public LoadedClassesTreeCellRenderer() { super(); } /** * This is messaged from JTree whenever it needs to get the size * of the component or it wants to draw it. * This attempts to set the font based on value, which will be * a TreeNode. */ public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus); // Tooltips used by the tree. setToolTipText(stringValue); DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)value; LoadedClassesEntry entry = (LoadedClassesEntry)dmtn.getUserObject(); switch( entry.getType()) { case LoadedClassesEntry.ROOT: setIcon(ImageList.computerIcon); setText(stringValue); break; case LoadedClassesEntry.ROOTJAVA: setIcon(ImageList.tabIcon); setText(stringValue); break; case LoadedClassesEntry.ROOTSUN: setIcon(ImageList.javaIcon); setText(stringValue); break; case LoadedClassesEntry.ROOTUSER: setIcon(ImageList.addFolderBtnIcon); setText(stringValue); break; case LoadedClassesEntry.JDKPACKAGE: setIcon(ImageList.dirIcon); setText(stringValue); break; case LoadedClassesEntry.SUNPACKAGE: setIcon(ImageList.dirIcon); setText(stringValue); break; case LoadedClassesEntry.USERPACKAGE: setIcon(ImageList.dirIcon); setText(stringValue); break; case LoadedClassesEntry.JDK: setIcon(ImageList.packageIcon); setText(stringValue); break; case LoadedClassesEntry.SUN: setIcon(ImageList.classIcon); setText(stringValue); break; case LoadedClassesEntry.USER: setIcon(ImageList.innerIcon); setText(stringValue); break; default: break; } //setText(stringValue); return this; } }
29.112245
137
0.711532
262fa9f01af147121c2d583354ac90dae3c4b207
850
package net.oschina.app.improve.bean; import java.io.Serializable; /** * 启动页数据 * Created by huanghaibin on 2017/11/25. */ public class Launcher implements Serializable { private boolean isAd;//是否是广告 private String imgUrl;//图片连接 private String href;//打开链接 private boolean isExpired;//是否过期 public boolean isAd() { return isAd; } public void setAd(boolean ad) { isAd = ad; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public boolean isExpired() { return isExpired; } public void setExpired(boolean expired) { isExpired = expired; } }
17.708333
47
0.608235
36c683a8e3d44155d4054f6fe77c051a4c5b1508
282
package com.ratingfund.app.util; import java.util.Comparator; import com.ratingfund.app.model.Fund; public class IndexComparator implements Comparator<Fund>{ @Override public int compare(Fund f1, Fund f2) { return f1.getIndex().compareTo(f2.getIndex()); } }
18.8
58
0.719858
7b1f91aa7ffd1851e8e468208e1e041b3c21dad6
1,090
package cloud.artik.lwm2m.enums; /** * Java enum representing the result of a Firmware download/update. * * @author maneesh.sahu */ public enum FirmwareUpdateResult { DEFAULT(0), // 0: Default value. Once the updating process is initiated, this Resource SHOULD be reset to default value. SUCCESS(1), // 1: Firmware updated successfully, NO_STORAGE(2), // 2: Not enough storage for the new firmware package. OUT_OF_MEMORY(3), // 3. Out of memory during downloading process. CONNECTION_LOST(4), // 4: Connection lost during downloading process. CRC_CHECK_FAILURE(5), // 5: CRC check failure for new downloaded package. UNSUPPORTED_PACKAGE_TYPE(6), // 6: Unsupported package type. INVALID_URI(7), // 7: Invalid URI FAILED(8) // 8: Failed ; private final int resultId; FirmwareUpdateResult(int resultId) { this.resultId = resultId; } public Long getResultAsLong() { return new Long(this.resultId); } }
36.333333
142
0.623853
9254a6637c6266cf2f513a3ccf9d405012b7cbcf
7,943
/* * Copyright 2012-2020 the original author or 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 * * https://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.springframework.boot.web.servlet.error; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * Default implementation of {@link ErrorAttributes}. Provides the following attributes * when possible: * <ul> * <li>timestamp - The time that the errors were extracted</li> * <li>status - The status code</li> * <li>error - The error reason</li> * <li>exception - The class name of the root exception (if configured)</li> * <li>message - The exception message (if configured)</li> * <li>errors - Any {@link ObjectError}s from a {@link BindingResult} exception (if * configured)</li> * <li>trace - The exception stack trace (if configured)</li> * <li>path - The URL path when the exception was raised</li> * </ul> * * @author Phillip Webb * @author Dave Syer * @author Stephane Nicoll * @author Vedran Pavic * @author Scott Frederick * @since 2.0.0 * @see ErrorAttributes */ @Order(Ordered.HIGHEST_PRECEDENCE) public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR"; private final boolean includeException; /** * Create a new {@link DefaultErrorAttributes} instance that does not include the * "exception" attribute. */ public DefaultErrorAttributes() { this(false); } /** * Create a new {@link DefaultErrorAttributes} instance. * @param includeException whether to include the "exception" attribute */ public DefaultErrorAttributes(boolean includeException) { this.includeException = includeException; } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { storeErrorAttributes(request, ex); return null; } private void storeErrorAttributes(HttpServletRequest request, Exception ex) { request.setAttribute(ERROR_ATTRIBUTE, ex); } @Override @Deprecated public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { return this.getErrorAttributes(webRequest, includeStackTrace, false); } @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace, boolean includeDetails) { Map<String, Object> errorAttributes = new LinkedHashMap<>(); errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, webRequest); addErrorDetails(errorAttributes, webRequest, includeStackTrace, includeDetails); addPath(errorAttributes, webRequest); return errorAttributes; } private void addStatus(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) { Integer status = getAttribute(requestAttributes, RequestDispatcher.ERROR_STATUS_CODE); if (status == null) { errorAttributes.put("status", 999); errorAttributes.put("error", "None"); return; } errorAttributes.put("status", status); try { errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase()); } catch (Exception ex) { // Unable to obtain a reason errorAttributes.put("error", "Http Status " + status); } } private void addErrorDetails(Map<String, Object> errorAttributes, WebRequest webRequest, boolean includeStackTrace, boolean includeDetails) { Throwable error = getError(webRequest); if (error != null) { while (error instanceof ServletException && error.getCause() != null) { error = error.getCause(); } if (this.includeException) { errorAttributes.put("exception", error.getClass().getName()); } if (includeStackTrace) { addStackTrace(errorAttributes, error); } } addErrorMessage(errorAttributes, webRequest, error, includeDetails); } private void addErrorMessage(Map<String, Object> errorAttributes, WebRequest webRequest, Throwable error, boolean includeDetails) { BindingResult result = extractBindingResult(error); if (result == null) { addExceptionErrorMessage(errorAttributes, webRequest, error, includeDetails); } else { addBindingResultErrorMessage(errorAttributes, result, includeDetails); } } private void addExceptionErrorMessage(Map<String, Object> errorAttributes, WebRequest webRequest, Throwable error, boolean includeDetails) { if (!includeDetails) { errorAttributes.put("message", "An error occurred while processing the request"); return; } Object message = getAttribute(webRequest, RequestDispatcher.ERROR_MESSAGE); if (StringUtils.isEmpty(message) && error != null) { message = error.getMessage(); } if (StringUtils.isEmpty(message)) { message = "No message available"; } errorAttributes.put("message", message); } private void addBindingResultErrorMessage(Map<String, Object> errorAttributes, BindingResult result, boolean includeDetails) { if (!includeDetails) { errorAttributes.put("message", "Validation failed"); return; } if (result.hasErrors()) { errorAttributes.put("errors", result.getAllErrors()); } errorAttributes.put("message", "Validation failed for object='" + result.getObjectName() + "'. " + "Error count: " + result.getErrorCount()); } private BindingResult extractBindingResult(Throwable error) { if (error instanceof BindingResult) { return (BindingResult) error; } if (error instanceof MethodArgumentNotValidException) { return ((MethodArgumentNotValidException) error).getBindingResult(); } return null; } private void addStackTrace(Map<String, Object> errorAttributes, Throwable error) { StringWriter stackTrace = new StringWriter(); error.printStackTrace(new PrintWriter(stackTrace)); stackTrace.flush(); errorAttributes.put("trace", stackTrace.toString()); } private void addPath(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) { String path = getAttribute(requestAttributes, RequestDispatcher.ERROR_REQUEST_URI); if (path != null) { errorAttributes.put("path", path); } } @Override public Throwable getError(WebRequest webRequest) { Throwable exception = getAttribute(webRequest, ERROR_ATTRIBUTE); return (exception != null) ? exception : getAttribute(webRequest, RequestDispatcher.ERROR_EXCEPTION); } @SuppressWarnings("unchecked") private <T> T getAttribute(RequestAttributes requestAttributes, String name) { return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST); } }
34.385281
116
0.759411
d8e10920cb62c8ef36410c41d509c7248baf0a09
8,872
package components; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class OthelloBoard extends Board { /** * The data structure containing the actual contents/configuration of the board */ public OthelloBoard() { super(8); // Ha, film contents = new Color[width][width]; for (int i = 0; i < contents.length; i++) { for (int j = 0; j < contents[i].length; j++) { contents[i][j] = Color.EMPTY; } } initialize(); } public OthelloBoard(int width) { super(width); contents = new Color[this.width][this.width]; for (int i = 0; i < contents[i].length; i++) { for (int j = 0; i < contents[j].length; j++) { contents[i][j] = Color.EMPTY; } } initialize(); } public OthelloBoard(Board that) { super(that.width); contents = new Color[width][width]; for (int i = 0; i < contents.length; i++) { for (int j = 0; j < contents[i].length; j++) { contents[i][j] = that.contents[i][j]; } } } @Override public boolean place(Color piece, Coordinate coord) { if (!inBounds(coord)) { return false; } else { contents[coord.getRow()][coord.getCol()] = piece; return true; } } @Override public boolean set(Color piece, Coordinate coord) { if (piece == null || coord == null) { return false; } if (!inBounds(coord) || contents[coord.getRow()][coord.getCol()] != Color.EMPTY) { // Position provided is already occupied - don't attempt to place piece on the board // Or the coordinate provided is invalid return false; } else if (checkValidMove(piece, coord)) { // Attempted move is valid - apply move to board applyMove(piece, coord); return true; } else { // Attempted move is not valid - don't apply move to board return false; } } private void applyMove(Color c, Coordinate coord) { contents[coord.getRow()][coord.getCol()] = c; int rowOffset; int colOffset; for (Direction dir : checkValidMoveDirection(c, coord)) { switch(dir) { case COL_DOWN: rowOffset = 1; colOffset = 0; break; case COL_UP: rowOffset = -1; colOffset = 0; break; case DIAG_LOWER_LEFT: rowOffset = 1; colOffset = -1; break; case DIAG_LOWER_RIGHT: rowOffset = 1; colOffset = 1; break; case DIAG_UPPER_LEFT: rowOffset = -1; colOffset = -1; break; case DIAG_UPPER_RIGHT: rowOffset = -1; colOffset = 1; break; case ROW_LEFT: rowOffset = 0; colOffset = -1; break; case ROW_RIGHT: rowOffset = 0; colOffset = 1; break; default: rowOffset = -999; colOffset = -999; } int row = coord.getRow(); int col = coord.getCol(); // (row + rowOffset * mult < width && row + rowOffset * mult >= 0) && (col + colOffset * mult < width && col + colOffset * mult >= 0) && for (int mult = 1; inBounds(row + rowOffset * mult, col + colOffset * mult); mult++) { if(get(row + rowOffset * mult, col + colOffset * mult) != c) { flip(row + rowOffset * mult, col + colOffset * mult); } else { break; } } } } private boolean checkValidMove(Color c, Coordinate coord) { return checkValidMoveDirection(c, coord).size() > 0 && contents[coord.getRow()][coord.getCol()] == Color.EMPTY; } private List<Direction> checkValidMoveDirection(Color c, Coordinate coord) { List<Direction> validDirections = new ArrayList<Direction>(); String vectorStr; for (Direction dir : Direction.values()) { vectorStr = ""; for(Color piece : groupDirection(c, coord, dir)) { vectorStr += piece; } // for c == B, vectorStr matches "BW...B" in which there is at least one "W", but no more "W"s than two less than the width of the board if (vectorStr.matches("[" + c + "]{1}" + "[" + c.flip() + "]{1," + (width - 2) + "}" + "[" + c + "]{1}.*")) { validDirections.add(dir); } } return validDirections; } private List<Color> groupDirection(Color c, Coordinate coord, Direction dir) { int rowOffset; int colOffset; switch(dir) { case COL_DOWN: rowOffset = 1; colOffset = 0; break; case COL_UP: rowOffset = -1; colOffset = 0; break; case DIAG_LOWER_LEFT: rowOffset = 1; colOffset = -1; break; case DIAG_LOWER_RIGHT: rowOffset = 1; colOffset = 1; break; case DIAG_UPPER_LEFT: rowOffset = -1; colOffset = -1; break; case DIAG_UPPER_RIGHT: rowOffset = -1; colOffset = 1; break; case ROW_LEFT: rowOffset = 0; colOffset = -1; break; case ROW_RIGHT: rowOffset = 0; colOffset = 1; break; default: rowOffset = -999; colOffset = -999; } int row = coord.getRow(); int col = coord.getCol(); List<Color> group = new Vector<Color>(); group.add(c); // (row + rowOffset * mult < width && row + rowOffset * mult >= 0) && (col + colOffset * mult < width && col + colOffset * mult >= 0) && for (int mult = 1; inBounds(row + rowOffset * mult, col + colOffset * mult); mult++) { group.add(contents[row + rowOffset * mult][col + colOffset * mult]); } return group; } @Override public int countValidMoves(Color c) { int moveCount = 0; for (int row = 0; row < width; row++) { for (int col = 0; col < width; col++) { if (checkValidMove(c, new Coordinate(row, col))) { moveCount++; } } } return moveCount; } @Override public List<Coordinate> getValidMoves(Color c) { List<Coordinate> moveList = new ArrayList<Coordinate>(); Coordinate currentPos; for (int row = 0; row < width; row++) { for (int col = 0; col < width; col++) { currentPos = new Coordinate(row, col); if (checkValidMove(c, currentPos)) { moveList.add(currentPos); } } } return moveList; } @Override public Color get(Coordinate coord) { return contents[coord.getRow()][coord.getCol()]; } private Color get(int row, int col) { return contents[row][col]; } public Color[][] getContents() { return contents; } public void setContents(Color[][] contents) { this.contents = contents; } @Override public void initialize() { /* * WB * BW <- start at this W and work left and up */ int lowerRight = width / 2; // contents[row][column] contents[lowerRight][lowerRight] = Color.W; contents[lowerRight][lowerRight - 1] = Color.B; contents[lowerRight - 1][lowerRight] = Color.B; contents[lowerRight - 1][lowerRight - 1] = Color.W; } //////////////////// // Helper Methods // //////////////////// public boolean flip(Coordinate coord) { return flip(coord.getRow(), coord.getCol()); } public boolean flip(int row, int col) { if (flippable(row, col)) { contents[row][col] = contents[row][col].flip(); return true; } else { return false; } } private boolean flippable(Coordinate coord) { return inBounds(coord) && contents[coord.getRow()][coord.getCol()] != Color.EMPTY; } private boolean flippable(int row, int col) { return inBounds(row, col) && contents[row][col] != Color.EMPTY; } private boolean inBounds(Coordinate coord) { return coord.getRow() < width && coord.getCol() < width && coord.getRow() >= 0 && coord.getCol() >= 0; } private boolean inBounds(int row, int col) { return row < width && col < width && row >= 0 && col >= 0; } @Override public String toString() { String retString = " A B C D E F G H \n _______________\n"; int rowNum = 1; for (Color[] row : contents) { retString += rowNum++ + " | "; for (Color p : row) { switch(p) { case B: retString += "B "; break; case W: retString += "W "; break; case EMPTY: retString += ". "; break; } } retString += "\n"; } return retString; } public String toString(Color c) { String retString = " A B C D E F G H \n _______________\n"; List<Coordinate> validMoves = getValidMoves(c); int rowNum = 1; for (int row = 0; row < width; row++) { retString += rowNum++ + " | "; for (int col = 0; col < width; col++) { switch(contents[row][col]) { case B: retString += "B "; break; case W: retString += "W "; break; case EMPTY: retString += validMoves.contains(new Coordinate(row, col)) ? "* " : ". "; break; } } retString += "\n"; } return retString; } @Override public Board clone() { return new OthelloBoard(this); } }
23.286089
141
0.569657
479dc0643716e94503c48a960349547c13af6bc1
3,462
/* * The MIT License * Copyright © 2014-2021 Ilkka Seppälä * * 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.iluwatar.activeobject; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ActiveCreature class is the base of the active object example. * @author Noam Greenshtain * */ public abstract class ActiveCreature { private static final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); private BlockingQueue<Runnable> requests; private String name; private Thread thread; // Thread of execution. private int status; // status of the thread of execution. /** * Constructor and initialization. */ protected ActiveCreature(String name) { this.name = name; this.status = 0; this.requests = new LinkedBlockingQueue<>(); thread = new Thread(() -> { boolean infinite = true; while (infinite) { try { requests.take().run(); } catch (InterruptedException e) { if (this.status != 0) { logger.error("Thread was interrupted. --> {}", e.getMessage()); } infinite = false; Thread.currentThread().interrupt(); } } }); thread.start(); } /** * Eats the porridge. * @throws InterruptedException due to firing a new Runnable. */ public void eat() throws InterruptedException { requests.put(() -> { logger.info("{} is eating!",name()); logger.info("{} has finished eating!",name()); }); } /** * Roam in the wastelands. * @throws InterruptedException due to firing a new Runnable. */ public void roam() throws InterruptedException { requests.put(() -> logger.info("{} has started to roam in the wastelands.",name()) ); } /** * Returns the name of the creature. * @return the name of the creature. */ public String name() { return this.name; } /** * Kills the thread of execution. * @param status of the thread of execution. 0 == OK, the rest is logging an error. */ public void kill(int status) { this.status = status; this.thread.interrupt(); } /** * Returns the status of the thread of execution. * @return the status of the thread of execution. */ public int getStatus() { return this.status; } }
29.092437
95
0.670999
ab2389c0a80ff0e583fd6fc4a81e874d6468e6ec
11,684
/******************************************************************************* * * Copyright 2015 Impetus Infotech. * * * * 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.impetus.client; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.impetus.client.entities.AddressMTMRedis; import com.impetus.client.entities.PersonMTMRedis; public class RedisAssociationTestMTM { private EntityManagerFactory emf; private EntityManager em; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { emf = Persistence.createEntityManagerFactory("redis_pu"); em = getNewEM(); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { em.close(); emf.close(); } @Test public void testCrud() { AddressMTMRedis address1 = getAddress(101.0, "NCR"); AddressMTMRedis address2 = getAddress(109.0, "Delhi"); AddressMTMRedis address3 = getAddress(145.0, "Gurgaon"); Set<AddressMTMRedis> addresses1 = new HashSet<AddressMTMRedis>(); addresses1.add(address1); addresses1.add(address2); Set<AddressMTMRedis> addresses2 = new HashSet<AddressMTMRedis>(); addresses2.add(address2); addresses2.add(address3); PersonMTMRedis person1 = getPerson("1", "User1", 20, addresses1); PersonMTMRedis person2 = getPerson("2", "User2", 40, addresses2); em.persist(person1); em.persist(person2); PersonMTMRedis resultPerson1 = em.find(PersonMTMRedis.class, "1"); PersonMTMRedis resultPerson2 = em.find(PersonMTMRedis.class, "2"); notNullCheck(resultPerson1, resultPerson2); Assert.assertEquals("1", resultPerson1.getPersonId()); Assert.assertEquals("User1", resultPerson1.getPersonName()); Assert.assertEquals(20, resultPerson1.getAge().intValue()); Assert.assertEquals("2", resultPerson2.getPersonId()); Assert.assertEquals("User2", resultPerson2.getPersonName()); Assert.assertEquals(40, resultPerson2.getAge().intValue()); Assert.assertEquals(2, resultPerson1.getAddress().size()); Assert.assertEquals(2, resultPerson2.getAddress().size()); for (AddressMTMRedis address : resultPerson1.getAddress()) { if (address.getAddressId().equals(101.0)) { Assert.assertEquals("NCR", address.getAddress()); } else { Assert.assertEquals(109.0, address.getAddressId()); Assert.assertEquals("Delhi", address.getAddress()); } } for (AddressMTMRedis address : resultPerson2.getAddress()) { if (address.getAddressId().equals(109.0)) { Assert.assertEquals("Delhi", address.getAddress()); } else { Assert.assertEquals(145.0, address.getAddressId()); Assert.assertEquals("Gurgaon", address.getAddress()); } } em.clear(); address1.setAddress("Agra"); address2.setAddress("Mathura"); person1.setPersonName("User3"); em.merge(person1); em = getNewEM(); resultPerson1 = em.find(PersonMTMRedis.class, "1"); resultPerson2 = em.find(PersonMTMRedis.class, "2"); notNullCheck(resultPerson1, resultPerson2); Assert.assertEquals("1", resultPerson1.getPersonId()); Assert.assertEquals("User3", resultPerson1.getPersonName()); Assert.assertEquals(20, resultPerson1.getAge().intValue()); for (AddressMTMRedis address : resultPerson1.getAddress()) { if (address.getAddressId().equals(101.0)) { Assert.assertEquals("Agra", address.getAddress()); } else { Assert.assertEquals(109.0, address.getAddressId()); Assert.assertEquals("Mathura", address.getAddress()); } } for (AddressMTMRedis address : resultPerson2.getAddress()) { if (address.getAddressId().equals(109.0)) { Assert.assertEquals("Mathura", address.getAddress()); } else { Assert.assertEquals(145.0, address.getAddressId()); Assert.assertEquals("Gurgaon", address.getAddress()); } } em.remove(resultPerson1); em.remove(resultPerson2); Assert.assertNull(em.find(PersonMTMRedis.class, "1")); Assert.assertNull(em.find(PersonMTMRedis.class, "2")); Assert.assertNull(em.find(AddressMTMRedis.class, 101.0)); Assert.assertNull(em.find(AddressMTMRedis.class, 109.0)); Assert.assertNull(em.find(AddressMTMRedis.class, 145.0)); } @Test public void testQuery() { AddressMTMRedis address1 = getAddress(101.0, "NCR"); AddressMTMRedis address2 = getAddress(109.0, "Delhi"); AddressMTMRedis address3 = getAddress(145.0, "Gurgaon"); Set<AddressMTMRedis> addresses1 = new HashSet<AddressMTMRedis>(); addresses1.add(address1); addresses1.add(address2); Set<AddressMTMRedis> addresses2 = new HashSet<AddressMTMRedis>(); addresses2.add(address2); addresses2.add(address3); PersonMTMRedis person1 = getPerson("1", "User1", 20, addresses1); PersonMTMRedis person2 = getPerson("2", "User2", 40, addresses2); em.persist(person1); em.persist(person2); Query query = em.createQuery("Select e from PersonMTMRedis e"); List<PersonMTMRedis> queryResult = query.getResultList(); Assert.assertEquals(2, queryResult.size()); PersonMTMRedis resultPerson1 = queryResult.get(1); PersonMTMRedis resultPerson2 = queryResult.get(0); notNullCheck(resultPerson1, resultPerson2); Assert.assertEquals("1", resultPerson1.getPersonId()); Assert.assertEquals("User1", resultPerson1.getPersonName()); Assert.assertEquals(20, resultPerson1.getAge().intValue()); Assert.assertEquals("2", resultPerson2.getPersonId()); Assert.assertEquals("User2", resultPerson2.getPersonName()); Assert.assertEquals(40, resultPerson2.getAge().intValue()); Assert.assertEquals(2, resultPerson1.getAddress().size()); Assert.assertEquals(2, resultPerson2.getAddress().size()); for (AddressMTMRedis address : resultPerson1.getAddress()) { if (address.getAddressId().equals(101.0)) { Assert.assertEquals("NCR", address.getAddress()); } else { Assert.assertEquals(109.0, address.getAddressId()); Assert.assertEquals("Delhi", address.getAddress()); } } for (AddressMTMRedis address : resultPerson2.getAddress()) { if (address.getAddressId().equals(109.0)) { Assert.assertEquals("Delhi", address.getAddress()); } else { Assert.assertEquals(145.0, address.getAddressId()); Assert.assertEquals("Gurgaon", address.getAddress()); } } em.clear(); address1.setAddress("Agra"); address2.setAddress("Mathura"); person1.setPersonName("User3"); em.merge(person1); em = getNewEM(); query = em.createQuery("Select e from PersonMTMRedis e"); queryResult = query.getResultList(); Assert.assertEquals(2, queryResult.size()); if (queryResult.get(0).getPersonId().equals(1)) { resultPerson1 = queryResult.get(0); resultPerson2 = queryResult.get(1); } else { resultPerson1 = queryResult.get(1); resultPerson2 = queryResult.get(0); } notNullCheck(resultPerson1, resultPerson2); Assert.assertEquals("1", resultPerson1.getPersonId()); Assert.assertEquals("User3", resultPerson1.getPersonName()); Assert.assertEquals(20, resultPerson1.getAge().intValue()); for (AddressMTMRedis address : resultPerson1.getAddress()) { if (address.getAddressId().equals(101.0)) { Assert.assertEquals("Agra", address.getAddress()); } else { Assert.assertEquals(109.0, address.getAddressId()); Assert.assertEquals("Mathura", address.getAddress()); } } for (AddressMTMRedis address : resultPerson2.getAddress()) { if (address.getAddressId().equals(109.0)) { Assert.assertEquals("Mathura", address.getAddress()); } else { Assert.assertEquals(145.0, address.getAddressId()); Assert.assertEquals("Gurgaon", address.getAddress()); } } em.remove(resultPerson1); em.remove(resultPerson2); Assert.assertNull(em.find(PersonMTMRedis.class, "1")); Assert.assertNull(em.find(PersonMTMRedis.class, "2")); Assert.assertNull(em.find(AddressMTMRedis.class, 101.0)); Assert.assertNull(em.find(AddressMTMRedis.class, 109.0)); Assert.assertNull(em.find(AddressMTMRedis.class, 145.0)); } private boolean notNullCheck(PersonMTMRedis resultPerson1, PersonMTMRedis resultPerson2) { Assert.assertNotNull(resultPerson1); Assert.assertNotNull(resultPerson2); Assert.assertNotNull(resultPerson1.getAddress()); Assert.assertNotNull(resultPerson2.getAddress()); return true; } private PersonMTMRedis getPerson(String personId, String personName, int age, Set<AddressMTMRedis> address) { PersonMTMRedis person = new PersonMTMRedis(personId); person.setAge(age); person.setPersonName(personName); person.setAddress(address); return person; } private AddressMTMRedis getAddress(Double addressId, String personAddress) { AddressMTMRedis address = new AddressMTMRedis(addressId); address.setAddress(personAddress); return address; } private EntityManager getNewEM() { if (em != null && em.isOpen()) { em.close(); } // Delete by query. Query query = em.createQuery("Delete from PersonMTMRedis p"); int updateCount = query.executeUpdate(); return em = emf.createEntityManager(); } }
33.00565
111
0.601763
acdf786eebbdf92fdb26c55974b45f0529170109
2,807
package net.geekstools.floatshort; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.AsyncTask; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AppsReceiver extends BroadcastReceiver{ private PackageManager packageManager = null; Context c; @Override public void onReceive(Context context, Intent intent) { packageManager = context.getPackageManager(); c = context; File f = context.getFileStreamPath(".AppInfo"); if(f.exists()){ context.deleteFile(".AppInfo"); } LoadApplications app = new LoadApplications(); app.execute(); } private class LoadApplications extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA), c); return null; } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); System.out.println("Data Updated"); } } private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list, Context c) { ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>(); int i = 0; Collections.sort(list, new ApplicationInfo.DisplayNameComparator(packageManager)); for (ApplicationInfo info : list) { try { if (null != packageManager.getLaunchIntentForPackage(info.packageName)) { applist.add(info); saveAppInfo(i, info.packageName, appName(info.packageName, c), c); i++; } } catch (Exception e) { e.printStackTrace(); } } return applist; } public void saveAppInfo(int i, String packName, String appName, Context c){ try { String toSave = i + " " + "[" + appName + "]" + " " + "*" + packName + "*" + "\n"; FileOutputStream fOut = c.openFileOutput(".AppInfo", c.MODE_PRIVATE|c.MODE_APPEND); fOut.write((toSave).getBytes()); System.out.println("DONE >> " + toSave); fOut.close(); fOut.flush(); } catch (IOException e) { e.printStackTrace(); System.out.println(e); } } public String appName(String pack, Context c){ String Name = null; try{ PackageManager packManager = c.getPackageManager(); ApplicationInfo app = c.getPackageManager().getApplicationInfo(pack, 0); Name = packManager.getApplicationLabel(app).toString(); } catch(Exception e){ System.out.println(e); } return Name; } }
24.622807
98
0.705379
ae472c557d5a951f04d0ec5cf0e106c9c4f72a96
214
package cottee.myproperty; /** * Created by Administrator on 2018/3/18. */ public class TestTest { @org.junit.Test public void test1() throws Exception { System.out.println("月数格式不正确"); } }
15.285714
42
0.64486
486fcde84623ca36ebc59c2e2cc99f6db9aa8a99
9,908
/* * This file is part of CubicChunksConverter, licensed under the MIT License (MIT). * * Copyright (c) 2017-2021 contributors * * 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 cubicchunks.converter.lib.convert.cc2ccrelocating; import com.flowpowered.nbt.*; import cubicchunks.converter.lib.Dimension; import cubicchunks.converter.lib.conf.ConverterConfig; import cubicchunks.converter.lib.conf.command.EditTaskCommands; import cubicchunks.converter.lib.conf.command.EditTaskContext; import cubicchunks.converter.lib.convert.ChunkDataConverter; import cubicchunks.converter.lib.convert.data.PriorityCubicChunksColumnData; import cubicchunks.converter.lib.util.*; import cubicchunks.converter.lib.util.edittask.EditTask; import cubicchunks.regionlib.impl.EntryLocation2D; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.function.Consumer; import java.util.logging.Logger; import static cubicchunks.converter.lib.util.Utils.readCompressedCC; import static cubicchunks.converter.lib.util.Utils.writeCompressed; public class CC2CCRelocatingDataConverter implements ChunkDataConverter<PriorityCubicChunksColumnData, PriorityCubicChunksColumnData> { private final List<EditTask> relocateTasks; private final EditTaskContext.EditTaskConfig config; private static final Logger LOGGER = Logger.getLogger(CC2CCRelocatingDataConverter.class.getSimpleName()); @SuppressWarnings("unchecked") public CC2CCRelocatingDataConverter(ConverterConfig config) { this.relocateTasks = (List<EditTask>) config.getValue("relocations"); this.config = new EditTaskContext.EditTaskConfig(); } public static ConverterConfig loadConfig(Consumer<Throwable> throwableConsumer) { ConverterConfig conf = new ConverterConfig(new HashMap<>()); try { conf.set("relocations", loadDataFromFile("relocatingConfig.txt")); } catch (IOException | RuntimeException e) { throwableConsumer.accept(e); return null; } return conf; } private static List<EditTask> loadDataFromFile(String filename) throws IOException { List<String> lines = Files.readAllLines(Paths.get(filename)); EditTaskContext context = new EditTaskContext(); for(String line : lines) { line = line.trim(); if(line.isEmpty() || line.startsWith("//") || line.startsWith("#")) continue; EditTaskCommands.handleCommand(context, line); } return context.getTasks(); } @Override public Set<PriorityCubicChunksColumnData> convert(PriorityCubicChunksColumnData input) { Map<Integer, ImmutablePair<Long, ByteBuffer>> inCubes = input.getCubeData(); Map<Integer, ImmutablePair<Long, ByteBuffer>> cubes = new HashMap<>(); //Split out cubes that are only in a keep tasked bounding box Map<Integer, ImmutablePair<Long, ByteBuffer>> noReadCubes = new HashMap<>(); EntryLocation2D inPosition = input.getPosition(); for(Map.Entry<Integer, ImmutablePair<Long, ByteBuffer>> entry : inCubes.entrySet()) { boolean anyBoxNeedsData = false; boolean intersectsSrcBox = false; for(EditTask task : relocateTasks) { List<BoundingBox> srcBoxes = task.getSrcBoxes(); for (BoundingBox srcBox : srcBoxes) { if(srcBox.intersects(inPosition.getEntryX(), entry.getKey(), inPosition.getEntryZ())) { intersectsSrcBox = true; if(task.readsCubeData()) { anyBoxNeedsData = true; break; } } } } if(intersectsSrcBox) { if (anyBoxNeedsData) cubes.put(entry.getKey(), entry.getValue()); else noReadCubes.put(entry.getKey(), entry.getValue()); } else noReadCubes.put(entry.getKey(), entry.getValue()); } Map<Integer, ImmutablePair<Long, CompoundTag>> inCubeData = new HashMap<>(); cubes.forEach((key, value) -> { try { inCubeData.put(key, new ImmutablePair<>(value.getKey(), readCompressedCC(new ByteArrayInputStream(value.getValue().array())))); } catch (IOException e) { e.printStackTrace(); } }); try { Map<Vector2i, Map<Integer, ImmutablePair<Long, CompoundTag>>> outCubeData = relocateCubeData(input.getDimension(), inCubeData, this.config); Set<PriorityCubicChunksColumnData> columnData = new HashSet<>(); for (Map.Entry<Vector2i, Map<Integer, ImmutablePair<Long, CompoundTag>>> entry : outCubeData.entrySet()) { Vector2i key = entry.getKey(); ByteBuffer column = key.getX() != inPosition.getEntryX() || key.getY() != inPosition.getEntryZ() ? null : input.getColumnData(); EntryLocation2D location = new EntryLocation2D(key.getX(), key.getY()); columnData.add(new PriorityCubicChunksColumnData(input.getDimension(), location, column, compressCubeData(entry.getValue()), true)); } if (!noReadCubes.isEmpty()) { PriorityCubicChunksColumnData currentColumnData = columnData.stream() .filter(column -> column.getPosition().equals(inPosition)).findAny() .orElseGet(() -> new PriorityCubicChunksColumnData(input.getDimension(), inPosition, input.getColumnData(), new HashMap<>(), true)); noReadCubes.forEach((yPos, buffer) -> currentColumnData.getCubeData().putIfAbsent(yPos, buffer)); columnData.add(currentColumnData); } return columnData; } catch (IOException e) { throw new Error("Compressing cube data failed!", e); } } Map<Integer, ImmutablePair<Long, ByteBuffer>> compressCubeData(Map<Integer, ImmutablePair<Long, CompoundTag>> cubeData) throws IOException { Map<Integer, ImmutablePair<Long, ByteBuffer>> compressedData = new HashMap<>(); for(Map.Entry<Integer, ImmutablePair<Long, CompoundTag>> entry : cubeData.entrySet()) { compressedData.put(entry.getKey(), new ImmutablePair<>(entry.getValue().getKey(), writeCompressed(entry.getValue().getValue(), false))); } return compressedData; } Map<Vector2i, Map<Integer, ImmutablePair<Long, CompoundTag>>> relocateCubeData(Dimension dimension, Map<Integer, ImmutablePair<Long, CompoundTag>> cubeDataOld, EditTaskContext.EditTaskConfig config) throws IOException { Map<Vector2i, Map<Integer, ImmutablePair<Long, CompoundTag>>> tagMap = new HashMap<>(); for(Map.Entry<Integer, ImmutablePair<Long, CompoundTag>> entry : cubeDataOld.entrySet()) { CompoundMap level = (CompoundMap)entry.getValue().getValue().getValue().get("Level").getValue(); int cubeX = (Integer) level.get("x").getValue(); int cubeY = (Integer) level.get("y").getValue(); int cubeZ = (Integer) level.get("z").getValue(); for (EditTask task : this.relocateTasks) { if (!task.handlesDimension(dimension.getDirectory())) { continue; } task.initialise(config); if(!task.readsCubeData()) { continue; } boolean cubeIsSrc = false; for (BoundingBox sourceBox : task.getSrcBoxes()) { if(sourceBox.intersects(cubeX, cubeY, cubeZ)) { cubeIsSrc = true; break; } } if(!cubeIsSrc) continue; List<ImmutablePair<Vector3i, ImmutablePair<Long, CompoundTag>>> outputCubes = task.actOnCube(new Vector3i(cubeX, cubeY, cubeZ), config, entry.getValue().getValue(), entry.getKey()); outputCubes.forEach(positionTagPriority -> { Vector3i cubePos = positionTagPriority.getKey(); ImmutablePair<Long, CompoundTag> tagPriority = positionTagPriority.getValue(); if(tagPriority.getValue() == null) tagMap.computeIfAbsent(new Vector2i(cubePos.getX(), cubePos.getZ()), pos -> new HashMap<>()).remove(cubePos.getY()); else tagMap.computeIfAbsent(new Vector2i(cubePos.getX(), cubePos.getZ()), pos -> new HashMap<>()).put(cubePos.getY(), tagPriority); }); } } return tagMap; } }
48.097087
223
0.645236
40f0f49a196bd6011b573e350ca6e5188333a5c9
4,615
package projeto_1.user; import at.favre.lib.crypto.bcrypt.BCrypt; import com.google.inject.Inject; import projeto_1.Repository; import projeto_1.exceptions.InternalServerErrorException; import projeto_1.user.beans.User; import javax.inject.Singleton; import java.sql.*; @Singleton public class UserRepository extends Repository<User> { public static final String tableName = "users"; @Inject public UserRepository(Connection connection) { super(User.class, tableName, connection); } @Override public void assertTable() { System.out.println("Ensuring users table exists..."); try (Statement st = this.connection.createStatement()) { st.execute("CREATE TABLE IF NOT EXISTS " + tableName + "(" + "id SERIAL PRIMARY KEY," + "name VARCHAR NOT NULL," + "email VARCHAR NOT NULL," + "password VARCHAR NOT NULL," + "CONSTRAINT unique_email UNIQUE (email))"); } catch (SQLException e) { e.printStackTrace(); System.out.println("Failed to create the users table!"); } } @Override public User updateEntityFromResultSet(ResultSet rs, User user) throws SQLException { final short criticalFailureCount = 3; short failCount = 0; try { user.setId(rs.getInt("id")); } catch (SQLException ignored) { failCount++; } try { user.setName(rs.getString("name")); } catch (SQLException ignored) { failCount++; } try { user.setEmail(rs.getString("email")); } catch (SQLException ignored) { failCount++; } try { user.setPassword(rs.getString("password")); } catch (SQLException e) { if (failCount >= criticalFailureCount) { throw e; } } return user; } private String hashPassword(String password) { return BCrypt.withDefaults().hashToString(12, password.toCharArray()); } public User findByEmail(String email) throws InternalServerErrorException { try (PreparedStatement st = this.connection.prepareStatement( "SELECT * FROM " + tableName + " WHERE " + tableName + ".email = ?" )) { st.setString(1, email); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { return this.createEntityFromResultSet(rs); } } } catch (SQLException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } return null; } @Override public User createOne(User user) throws InternalServerErrorException { try (PreparedStatement st = this.connection .prepareStatement("INSERT INTO " + tableName + "(name, email, password) VALUES(?, ?, ?) RETURNING id, password" )) { st.setString(1, user.getName()); st.setString(2, user.getEmail()); st.setString(3, this.hashPassword(user.getPassword())); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { return this.updateEntityFromResultSet(rs, user); } } } catch (SQLException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } throw new InternalServerErrorException("Unexpected error while creating user"); } @Override public User replaceOne(User user) throws InternalServerErrorException { try (PreparedStatement st = this.connection .prepareStatement("UPDATE " + tableName + " SET name = ?, email = ?, password = ? WHERE id = ? RETURNING *" )) { st.setString(1, user.getName()); st.setString(2, user.getEmail()); st.setString(3, this.hashPassword(user.getPassword())); st.setInt(4, user.getId()); try (ResultSet rs = st.executeQuery()) { while (rs.next()) { return this.createEntityFromResultSet(rs); } } } catch (SQLException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } throw new InternalServerErrorException("Unexpected error, failed to iterate over replace result?"); } }
34.962121
107
0.55753
e952312580e49bf83e27969d36ab42f96e160b07
2,151
package com.twu.biblioteca.utils; import com.twu.biblioteca.beans.User; import com.twu.biblioteca.beans.Role; import java.io.*; public class UserFileUtil { private boolean write(String filepath, String text) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(filepath, true)); bw.write(text); bw.newLine(); return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); return false; } } } private String query(String filepath, String content) { String line; BufferedReader br = null; try { br = new BufferedReader(new FileReader(filepath)); try { while ((line = br.readLine()) != null) if (line.indexOf(content) == 0) return line.substring(content.length() + 1); } catch (IOException e) { e.printStackTrace(); } return ""; } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); return ""; } } } public Role getUser(User user) { String text = query(Constant.USERS_FILE, user.getUsername() + " " + user.getPassword()); String[] strs = text.split(" "); if (strs.length != 3) return Role.NONE; user.setRole(Role.toRole(strs[0])); user.setEmail(strs[1]); user.setTel(strs[2]); return user.getRole(); } public boolean insertUser(User user) { return write(Constant.USERS_FILE, user.getUsername() + " " + user.getPassword() + " " + user.getRole().toString() + " " + user.getEmail() + " " + user.getTel() ); } }
27.576923
96
0.489075
90004ab626b39573bb34c0a14ff17f5af6ddf4b9
4,412
package io.github.artislong.core.ali; import cn.hutool.core.text.CharPool; import cn.hutool.core.util.ObjectUtil; import cn.hutool.extra.spring.SpringUtil; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClient; import com.aliyun.oss.OSSClientBuilder; import io.github.artislong.constant.OssConstant; import io.github.artislong.core.StandardOssClient; import io.github.artislong.core.ali.model.AliOssClientConfig; import io.github.artislong.core.ali.model.AliOssConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import java.util.Map; import java.util.Optional; /** * @author 陈敏 * @version AliOssConfiguration.java, v 1.1 2021/11/16 15:25 chenmin Exp $ * Created on 2021/11/16 */ @SpringBootConfiguration @ConditionalOnClass(OSSClient.class) @EnableConfigurationProperties({AliOssProperties.class}) @ConditionalOnProperty(prefix = OssConstant.OSS, name = OssConstant.OssType.ALI + CharPool.DOT + OssConstant.ENABLE, havingValue = OssConstant.DEFAULT_ENABLE_VALUE) public class AliOssConfiguration { public static final String DEFAULT_BEAN_NAME = "aliOssClient"; @Autowired private AliOssProperties aliOssProperties; @Bean public StandardOssClient aliOssClient() { Map<String, AliOssConfig> aliOssConfigMap = aliOssProperties.getOssConfig(); if (aliOssConfigMap.isEmpty()) { SpringUtil.registerBean(DEFAULT_BEAN_NAME, aliOssClient(aliOssProperties)); } else { String endpoint = aliOssProperties.getEndpoint(); String accessKeyId = aliOssProperties.getAccessKeyId(); String accessKeySecret = aliOssProperties.getAccessKeySecret(); String securityToken = aliOssProperties.getSecurityToken(); AliOssClientConfig clientConfig = aliOssProperties.getClientConfig(); aliOssConfigMap.forEach((name, aliOssConfig) -> { if (ObjectUtil.isEmpty(aliOssConfig.getEndpoint())) { aliOssConfig.setEndpoint(endpoint); } if (ObjectUtil.isEmpty(aliOssConfig.getAccessKeyId())) { aliOssConfig.setAccessKeyId(accessKeyId); } if (ObjectUtil.isEmpty(aliOssConfig.getAccessKeySecret())) { aliOssConfig.setAccessKeySecret(accessKeySecret); } if (ObjectUtil.isEmpty(aliOssConfig.getSecurityToken())) { aliOssConfig.setSecurityToken(securityToken); } if (ObjectUtil.isEmpty(aliOssConfig.getClientConfig())) { aliOssConfig.setClientConfig(clientConfig); } SpringUtil.registerBean(name, aliOssClient(aliOssConfig)); }); } return null; } public StandardOssClient aliOssClient(AliOssConfig aliOssConfig) { return new AliOssClient(ossClient(aliOssConfig), aliOssConfig); } public OSS ossClient(AliOssConfig aliOssConfig) { String securityToken = aliOssConfig.getSecurityToken(); AliOssClientConfig clientConfiguration = aliOssConfig.getClientConfig(); if (ObjectUtil.isEmpty(securityToken) && ObjectUtil.isNotEmpty(clientConfiguration)) { return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret(), clientConfiguration.toClientConfig()); } if (ObjectUtil.isNotEmpty(securityToken) && ObjectUtil.isEmpty(clientConfiguration)) { return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret(), securityToken); } return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret(), securityToken, Optional.ofNullable(clientConfiguration).orElse(new AliOssClientConfig()).toClientConfig()); } }
45.484536
116
0.701496
5a6cb4788f5b2585240194d3c7920093130471cf
3,104
package org.mycompany.myname.model.dao.implement; import org.mycompany.myname.model.dao.INoteDao; import org.mycompany.myname.model.entity.Note; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JDBCNoteDao implements INoteDao { private Connection connection; public JDBCNoteDao(Connection connection) { this.connection = connection; } protected Note extractFromResultSet(ResultSet resultSet) throws SQLException { int id = resultSet.getInt(Note.ID_NOTE); Date dateCreation = resultSet.getDate(Note.DATE_CREATION); return new Note.NoteBuilder() .setIdNote(id) .setDateCreation(dateCreation) .build(); } @Override public void create(Note note) throws Exception { try (PreparedStatement ps = connection.prepareStatement(CREATE)) { ps.setInt(1, note.getIdNote()); ps.setDate(2, note.getDateCreation()); ps.setInt(3, note.getUser().getIdUser()); ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public Note findById(int id) { try (PreparedStatement preparedStatement = connection.prepareStatement(FIND_BY_ID)) { preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Note note = extractFromResultSet(resultSet); return note; } } catch (SQLException e) { throw new RuntimeException(e); } return null; } @Override public List<Note> findAll(int id) { List<Note> list = new ArrayList<>(); try (Statement ps = connection.createStatement()) { ResultSet resultSet = ps.executeQuery(FIND_ALL_NOTES_BY_USER); while (resultSet.next()) { Note note = extractFromResultSet(resultSet); list.add(note); } } catch (SQLException e) { throw new RuntimeException(e); } return list; } @Override public void update(Note note) { try (PreparedStatement preparedStatement = connection.prepareStatement(UPDATE)) { preparedStatement.setInt(1, note.getIdNote()); preparedStatement.setDate(2, note.getDateCreation()); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void delete(int id) { try (PreparedStatement preparedStatement = connection.prepareStatement(DELETE_BY_ID)) { preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void close() throws Exception { try { connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
31.673469
95
0.604704
1a19b29b2c0fe6f8d15f1d788fd8afdd81a7f1c2
4,299
package uk.ac.imperial.lsds.crossbow; import java.io.File; import uk.ac.imperial.lsds.crossbow.cli.CommandLine; import uk.ac.imperial.lsds.crossbow.cli.Options; import uk.ac.imperial.lsds.crossbow.kernel.Noop; import uk.ac.imperial.lsds.crossbow.kernel.conf.NoopConf; import uk.ac.imperial.lsds.crossbow.types.LearningRateDecayPolicy; import uk.ac.imperial.lsds.crossbow.types.Phase; import uk.ac.imperial.lsds.crossbow.types.TrainingUnit; public class NoopApp { public static void main (String [] args) throws Exception { long startTime, dt; Options options = new Options (NoopApp.class.getName()); /* Generic options */ options.addOption ("--N", "Train for N units", true, Integer.class, "2"); options.addOption ("--training-unit", "Training unit", true, String.class, "tasks"); /* Application-specific options */ options.addOption ("--chain", "Dataflow depth", true, Integer.class, "10"); options.addOption ("--dataset-alias", "Dataset alias", true, String.class, "cifar-10"); CommandLine commandLine = new CommandLine (options); /* Override default system configuration (before parsing) */ SystemConf.getInstance () .setCPU (false) .setGPU (true) .setGPUDevices(0,1) .setNumberOfWorkerThreads (1) .setNumberOfCPUModelReplicas (1) .setNumberOfReadersPerModel (1) .setNumberOfGPUModelReplicas (1) .setNumberOfGPUStreams (1) .setNumberOfGPUCallbackHandlers (8) .setDisplayInterval (10000) .displayAccumulatedLossValue (true) .queueMeasurements (true) .setTaskQueueSizeLimit(32) .setPerformanceMonitorInterval(2000) .setNumberOfResultSlots(128); /* Override default model configuration (before parsing) */ ModelConf.getInstance ().setBatchSize (64).setWpc (10000000).setSlack (0); /* Override default solver configuration (before parsing) */ ModelConf.getInstance ().getSolverConf () .setLearningRateDecayPolicy (LearningRateDecayPolicy.FIXED) .setBaseLearningRate (0.01F) .setMomentum (0); /* Parse command line arguments */ commandLine.parse (args); /* Dump configuration on screen */ SystemConf.getInstance ().dump (); ModelConf.getInstance ().dump (); int N = options.getOption("--N").getIntValue (); TrainingUnit unit = TrainingUnit.fromString (options.getOption("--training-unit").getStringValue()); String filename = null; String alias = options.getOption("--dataset-alias").getStringValue (); if (alias.equalsIgnoreCase("cifar-10")) { filename = String.format("/data/crossbow/cifar-10/b-%03d/cifar-train.metadata", ModelConf.getInstance().getBatchSize()); } else if (alias.equalsIgnoreCase("imagenet")) { filename = String.format("/data/crossbow/imagenet/ilsvrc2012/b-%03d/imagenet-train.metadata", ModelConf.getInstance().getBatchSize()); } else { System.err.println(String.format("error: invalid dataset alias: %s", alias)); System.exit(1); } /* Does the metadata file exist? */ if (! (new File (filename)).exists()) { System.err.println(String.format("error: file %s not found", filename)); System.exit(1); } Dataset ds1 = new Dataset (filename); Dataset ds2 = null; startTime = System.nanoTime (); ModelConf.getInstance().setDataset(Phase.TRAIN, ds1).setDataset(Phase.CHECK, ds2); int depth = options.getOption("--chain").getIntValue(); Operator op1 = new Operator ("Noop-1", new Noop (new NoopConf().setAxis(3))); DataflowNode h1 = new DataflowNode (op1); /* Build chain of operators */ if (depth > 1) { DataflowNode node = h1; for (int i = 1; i < depth; i++) { node = node.connectTo(new DataflowNode (new Operator (String.format("Noop-%d", (i + 1)), new Noop (new NoopConf().setAxis(3))))); } } SubGraph g1 = new SubGraph (h1); Dataflow df1 = new Dataflow (g1).setPhase(Phase.TRAIN); Dataflow df2 = null; ExecutionContext context = new ExecutionContext (new Dataflow [] { df1, df2 }); context.init(); context.getDataflow(Phase.TRAIN).dump(); context.getModel().dump(); context.train(N, unit); dt = System.nanoTime() - startTime; System.out.println(String.format("dt = %10.2f secs", (double)(dt) / 1000000000)); context.destroy(); System.out.println("Bye."); System.exit(0); } }
33.325581
137
0.694115
f2d91827ce73fd405b511e67444627d011c47ed0
3,034
package info.seleniumcucumber.userStepDefintions; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import cucumber.api.PendingException; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import env.DriverUtil; public class UserStepDefinitions implements BaseTest { protected WebDriver driver = DriverUtil.getDefaultDriver(); @Given("^I should get logged-in$") public void should_logged_in() throws Throwable { By selection = By.id("flash"); (new WebDriverWait(driver, 30)).until( ExpectedConditions.visibilityOfElementLocated(selection)); String msg = driver.findElement(By.id("flash")).getText(); if(!msg.isEmpty()) msg = msg.split("\n")[0].trim(); Assert.assertEquals("You logged into a secure area!", msg); } @When("^I click on element having id \"(.*?)\"$") public void i_click_on_element_having_id(String arg1) throws Throwable { // Write code here that turns the phrase above into concrete actions // WebElement element = driver.findElement(By.id(arg1)); // element.click(); } @Then("^element having xpath \"(.*?)\" should have text as \"(.*?)\"$") public void element_having_xpath_should_have_text_as(String arg1, String arg2) throws Throwable { // Write code here that turns the phrase above into concrete actions // WebElement element = driver.findElement(By.name("arg2")); // element.sendKeys(arg1); // Assert.assertTrue(element.isDisplayed()); } @Given("^I navigate to \"(.*?)\"$") public void i_navigate_to(String arg1) throws Throwable { // Write code here that turns the phrase above into concrete actions driver.get(arg1); Assert.assertEquals("The Internet", driver.getTitle()); } @Given("^I enter \"(.*?)\" into input field having id \"(.*?)\"$") public void i_enter_into_input_field_having_id(String arg1, String arg2) throws Throwable { // Write code here that turns the phrase above into concrete actions WebElement element = driver.findElement(By.id(arg2)); element.sendKeys(arg1); } @When("^I click on element having class \"(.*?)\"$") public void i_click_on_element_having_class(String arg1) throws Throwable { // Write code here that turns the phrase above into concrete actions WebElement element = driver.findElement(By.className(arg1)); element.click(); } @Then("^I close browser$") public void i_close_browser() throws Throwable { // Write code here that turns the phrase above into concrete actions driver.close(); } @Then("^I Login out$") public void i_Login_out() throws Throwable { // Write code here that turns the phrase above into concrete actions //WebElement element = driver.findElement(By.cssSelector("")); //element.click(); } }
31.936842
98
0.713579
1b849835212556cab0da61edda4ea7a24f16e257
5,380
package com.garowing.gameexp.game.rts.skill.model; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.log4j.Logger; import com.yeto.war.fightcore.attr.constants.UnitType; import com.yeto.war.fightcore.fight.state.FightStateEnum; import com.garowing.gameexp.game.rts.skill.constants.PropsFilterKey; import com.garowing.gameexp.game.rts.skill.constants.PropsFilterType; import com.garowing.gameexp.game.rts.skill.filter.unit.CompositeFilter; import com.garowing.gameexp.game.rts.skill.filter.unit.UnitPropsFilter; import com.yeto.war.utils.StringUtil; import commons.configuration.ConfigurableProcessor; /** * 单位属性过滤器model * @author seg * */ @XmlRootElement(name = "props_filter") @XmlAccessorType(XmlAccessType.NONE) public class PropsFilterModel { private static final Logger mLogger = Logger.getLogger(PropsFilterModel.class); /** * id */ @XmlAttribute private int id; /** * 阵营类型 0-all 1-friend 2-enemy */ @XmlAttribute private int campType; /** * 是否包含自己 */ @XmlAttribute private boolean includeSelf; /** * 允许部队类型 */ @XmlAttribute private List<Integer> allowTroopTypes; /** * 禁止的部队类型 */ @XmlAttribute private List<Integer> forbidTroopTypes; /** * 过滤器类型 */ @XmlAttribute private int type; /** * 组合ids,按顺序筛选 */ @XmlAttribute private List<Integer> compose; /** * 消耗能量 */ @XmlAttribute private List<Integer> consumeEnergy; /** * 允许状态集合 */ @XmlAttribute private List<Integer> allowTroopStatus; /** * 禁止状态集合 */ @XmlAttribute private List<Integer> forbidTroopStatus; /** * 部队id集合 */ @XmlAttribute private List<Integer> troopIds; /** * 属性过滤条件(eg: hp<=20%,hp<=100) */ @XmlAttribute private String attributes; /** * 禁止的召唤类型 0-卡牌或脚本 1-怪物 2-将军 */ @XmlAttribute private String forbidCallerType; /** * 允许部队类型掩码 */ @XmlTransient private int troopTypeMask; /** * 过滤器实体 */ @XmlTransient private UnitPropsFilter filter; /** * 允许状态掩码 */ @XmlTransient private int troopStatusMask; @SuppressWarnings("unchecked") void afterUnmarshal(Unmarshaller u, Object parent) { Set<Integer> allowTypes = new HashSet<Integer>(allowTroopTypes); if(allowTypes.isEmpty()) this.troopTypeMask = 0xffffffff; Set<Integer> forbidTypes = new HashSet<Integer>(forbidTroopTypes); UnitType[] types = UnitType.values(); for(UnitType type : types) { if(allowTypes.contains(type.getCode())) this.troopTypeMask |= type.getMask(); if(forbidTypes.contains(type.getCode())) this.troopTypeMask &= ~type.getMask(); } Set<Integer> allowStatus = new HashSet<Integer>(allowTroopStatus); if(allowTypes.isEmpty()) this.troopStatusMask = 0xffffffff; Set<Integer> forbidStatus = new HashSet<>(forbidTroopStatus); FightStateEnum[] statuses = FightStateEnum.values(); for(FightStateEnum status : statuses) { if(allowStatus.contains(status.code)) this.troopStatusMask |= status.getStates(); if(forbidStatus.contains(status.code)) this.troopTypeMask &= ~status.getStates(); } Map<String, String> initParams = new HashMap<String, String>(); initParams.put(PropsFilterKey.CAMP_TYPE, campType + ""); initParams.put(PropsFilterKey.INCLUDE_SELF, includeSelf + ""); initParams.put(PropsFilterKey.TROOP_TYPE_MASK, troopTypeMask + ""); initParams.put(PropsFilterKey.ALLOW_TROOP_TYPES, StringUtil.ListToXmlFormat(allowTroopTypes)); initParams.put(PropsFilterKey.CONSUME_ENERGY, StringUtil.ListToXmlFormat(consumeEnergy)); initParams.put(PropsFilterKey.TROOP_STATUS_MASK, troopStatusMask + ""); initParams.put(PropsFilterKey.TROOP_IDS, StringUtil.ListToXmlFormat(troopIds)); initParams.put(PropsFilterKey.ATTRIBUTES, attributes); initParams.put(PropsFilterKey.CALLER_TYPE, forbidCallerType); if(compose.isEmpty()) { if(type == PropsFilterType.COMPOSITE.getCode()) { mLogger.error("composite filter's parameters is invalid! id:[" + id + "]"); return; } PropsFilterType filterType = PropsFilterType.getTypeById(type); if(filterType == null) { mLogger.error("filter condition is invalid! id:[" + id + "] condition:[" + type + "]"); return; } try { filter = filterType.getFilterClass().newInstance(); ConfigurableProcessor.process(filter, initParams); } catch (InstantiationException | IllegalAccessException e) { mLogger.error("filter init fail!", e); } } else { filter = new CompositeFilter(); ((CompositeFilter)filter).setFilterIds(compose); } } public int getId() { return id; } public List<Integer> getAllowTroopTypes() { return allowTroopTypes; } public List<Integer> getForbidTroopTypes() { return forbidTroopTypes; } public int getType() { return type; } public List<Integer> getCompose() { return compose; } public boolean isIncludeSelf() { return includeSelf; } public int getTroopTypeMask() { return troopTypeMask; } public UnitPropsFilter getFilter() { return filter; } }
21.349206
96
0.717658
cae4d852e9cfe0d1c0e37d4bc51b84d891ff00e1
1,303
package com.cooey.maya; import android.app.Activity; import chatkit.Message; import chatkit.events.OptionSelectedEvent; import com.google.gson.GsonBuilder; class ContentManager$2 implements Runnable { final /* synthetic */ ContentManager this$0; final /* synthetic */ OptionSelectedEvent val$optionSelectedEvent; class C09631 implements Runnable { C09631() { } public void run() { ContentManager.access$100(ContentManager$2.this.this$0).addToStart(new Message("Maya", ContentManager$2.this.val$optionSelectedEvent.getContent().getParameters()), true); } } ContentManager$2(ContentManager this$0, OptionSelectedEvent optionSelectedEvent) { this.this$0 = this$0; this.val$optionSelectedEvent = optionSelectedEvent; } public void run() { try { Object mayaRequest = new MayaRequest(); mayaRequest.setQuery(this.val$optionSelectedEvent.getContent().getParameters()); ContentManager.access$000(this.this$0).getSession().getBasicRemote().sendText(new GsonBuilder().create().toJson(mayaRequest)); ((Activity) ContentManager.access$200(this.this$0)).runOnUiThread(new C09631()); } catch (Exception e) { e.printStackTrace(); } } }
35.216216
182
0.678434
3b1c39d4c1924900fa7427ca42ced938dbafbfa8
1,013
package com.eSports.system.data.dao; import com.eSports.system.data.entity.GameInfo; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface GameInfoDao { /** * 新增 * * @param gameInfo * @return */ Integer insertGameInfo(@Param("gameInfo") GameInfo gameInfo); /** * 删除 * * @param id * @return */ Integer deleteGameInfo(Integer id); /** * 多条件查询 * * @param gameInfo * @return */ List<GameInfo> selectByGameInfo(@Param("gameInfo") GameInfo gameInfo); /** * 更新 * * @param gameInfo * @return */ Integer updateGameInfo(@Param("gameInfo") GameInfo gameInfo); /** * 查找所有 */ List<GameInfo> selectAll(); /** * 根据id进行查找历史数据 */ GameInfo selectByid(Integer id); /** * 模糊查询 */ List<GameInfo> selectLike(@Param("gameInfo") GameInfo gameInfo); }
17.77193
74
0.584403
b5375de7c6309b4e004451ac65031f32e273b8fa
536
package com.deleidos.rtws.systemcfg.composers; import java.io.InputStream; import javax.xml.bind.MarshalException; import com.deleidos.rtws.systemcfg.beans.SystemConfig; public class ServiceDefinitionComposer implements DefinitionComposer { public void initialize() { } public void writeFile(String version, String fileName) { } public void loadDefaults(InputStream stream) throws MarshalException { } public String compose(SystemConfig systemConfig) { return null; } public void dispose() { } }
17.290323
72
0.755597
4c1550898c6f1238bcefe14b65a6e60792ed9dfc
5,081
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ package com.microsoft.azure.toolkit.intellij.appservice; import com.intellij.icons.AllIcons; import com.intellij.openapi.project.Project; import com.intellij.ui.SimpleListCellRenderer; import com.intellij.ui.components.fields.ExtendableTextComponent; import com.microsoft.azure.toolkit.intellij.common.AzureComboBox; import com.microsoft.azuretools.azurecommons.helpers.NotNull; import com.microsoft.azuretools.azurecommons.helpers.Nullable; import com.microsoft.tooling.msservices.components.DefaultLoader; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import rx.Subscription; import javax.swing.*; import java.io.InterruptedIOException; import java.util.Objects; import static com.microsoft.intellij.util.RxJavaUtils.unsubscribeSubscription; public abstract class AppServiceComboBox<T extends AppServiceComboBoxModel> extends AzureComboBox<T> { protected Project project; protected Subscription subscription; public AppServiceComboBox(final Project project) { super(false); this.project = project; this.setRenderer(new AppCombineBoxRender(this)); } // todo: optimize refreshing logic public synchronized void refreshItemsWithDefaultValue(@NotNull T defaultValue) { unsubscribeSubscription(subscription); this.setLoading(true); this.removeAllItems(); this.addItem(defaultValue); subscription = this.loadItemsAsync() .subscribe(items -> DefaultLoader.getIdeHelper().invokeLater(() -> { synchronized (AppServiceComboBox.this) { AppServiceComboBox.this.removeAllItems(); items.forEach(this::addItem); this.resetDefaultValue(defaultValue); this.setLoading(false); } }), this::handleLoadingError); } private void resetDefaultValue(@NotNull T defaultValue) { final AppServiceComboBoxModel model = getItems() .stream() .filter(item -> AppServiceComboBoxModel.isSameApp(defaultValue, item) && item != defaultValue) .findFirst().orElse(null); if (model != null) { this.setSelectedItem(model); this.removeItem(defaultValue); } else if (defaultValue.isNewCreateResource()) { return; } else { this.setSelectedItem(null); this.removeItem(defaultValue); } } @Override protected void handleLoadingError(final Throwable e) { final Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause instanceof InterruptedIOException || rootCause instanceof InterruptedException) { // Swallow interrupted exception caused by unsubscribe return; } this.setLoading(false); super.handleLoadingError(e); } @Nullable @Override protected ExtendableTextComponent.Extension getExtension() { return ExtendableTextComponent.Extension.create( AllIcons.General.Add, "Create", this::createResource); } @Override protected String getItemText(final Object item) { if (item instanceof AppServiceComboBoxModel) { final AppServiceComboBoxModel selectedItem = (AppServiceComboBoxModel) item; return selectedItem.isNewCreateResource() ? String.format("(New) %s", selectedItem.getAppName()) : selectedItem.getAppName(); } else { return Objects.toString(item, StringUtils.EMPTY); } } protected abstract void createResource(); public class AppCombineBoxRender extends SimpleListCellRenderer { private final JComboBox comboBox; public AppCombineBoxRender(JComboBox comboBox) { this.comboBox = comboBox; } @Override public void customize(JList list, Object value, int index, boolean b, boolean b1) { if (value instanceof AppServiceComboBoxModel) { final AppServiceComboBoxModel app = (AppServiceComboBoxModel) value; if (index >= 0) { setText(getAppServiceLabel(app)); } else { setText(app.getAppName()); } } } private String getAppServiceLabel(AppServiceComboBoxModel appServiceModel) { final String appServiceName = appServiceModel.isNewCreateResource() ? String.format("(New) %s", appServiceModel.getAppName()) : appServiceModel.getAppName(); final String runtime = appServiceModel.getRuntime(); final String resourceGroup = appServiceModel.getResourceGroup(); return String.format("<html><div>%s</div></div><small>Runtime: %s | Resource Group: %s</small></html>", appServiceName, runtime, resourceGroup); } } }
38.78626
115
0.668176
51d5b22f614c436dcad64a43ef5b665319f7be3e
435
package com.silent.leetcode; import java.util.HashMap; import java.util.Map; public class CheckDoubbeTest { public boolean containsDuplicate(int[] nums) { int length=nums.length; Map<Integer,Integer> hashmap=new HashMap<>(length); for (int i=0;i<length;i++){ hashmap.put(nums[i],i); } return length!=hashmap.size(); } public static void main(String[] args) { } }
21.75
59
0.618391
548806c741ac5680d5616be4b78c6a6245944e3b
1,492
package com.zk.module_article.ui; import android.util.Log; import android.view.View; import android.widget.TextView; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.facade.annotation.Route; import com.zk.common_base.base.activity.BaseActivity; import com.zk.common_base.utils.ActivityUtils; import com.zk.module_article.R; import com.zk.module_article.R2; import butterknife.BindView; import butterknife.OnClick; /** * @description: 文章列表页面 * @author: zhukai * @date: 2019/7/9 13:28 */ @Route(path = "/article/articlelist") public class ArticleListActivity extends BaseActivity { @Autowired String name; @BindView(R2.id.tv_name) TextView tvName; @Override protected int getContentViewId() { return R.layout.activity_article_list; } @Override protected boolean showHomeAsUp() { return true; } @Override protected void initView() { super.initView(); tvTitle.setText("文章列表"); } @Override protected void initData() { super.initData(); Log.e(TAG, getIntent().getStringExtra("name")); tvName.setText(name); } @Override protected void initEvent() { super.initEvent(); } @OnClick({R2.id.btn_go_back}) public void onClick(View view) { if (view.getId() == R.id.btn_go_back) { setResult(RESULT_OK); ActivityUtils.finishActivity(mContext); } } }
22.268657
63
0.669571
7890720f8a7eb13ae05d9cfc0618c9e22cdf5689
3,830
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2020 The ZAP Development Team * * 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.zaproxy.zap.extension.automacrobuilder.zap; import java.awt.*; import org.parosproxy.paros.extension.AbstractPanel; import org.parosproxy.paros.extension.ExtensionHook; import org.zaproxy.zap.extension.automacrobuilder.generated.MacroBuilderUI; import org.zaproxy.zap.extension.tab.Tab; /** @author gdgd009xcd */ @SuppressWarnings("serial") public class MyWorkPanel extends AbstractPanel implements Tab { private static final org.apache.logging.log4j.Logger LOGGER4J = org.apache.logging.log4j.LogManager.getLogger(); MyWorkPanel( ExtensionActiveScanWrapper extscanwrapper, MacroBuilderUI mbui, String name, ExtensionHook exthook) { setLayout(new CardLayout()); // JScrollPane jScrollPane = new JScrollPane(); // jScrollPane.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 11)); // jScrollPane.setHorizontalScrollBarPolicy( // javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // jScrollPane.setViewportView(new MacroBuilderUI(pmt).getInnerJPanel()); this.setName( name); // without calling this method, then NULL pointer exception will be occured. javax.swing.JButton scanmacrobtn = mbui.getScanMacroButton(); javax.swing.JPopupMenu requestlistpopupmenu = mbui.getPopupMenuForRequestList(); javax.swing.JPopupMenu requesteditpopupmenu = mbui.getPopupMenuRequestEdit(); exthook.addOptionsParamSet(extscanwrapper.getScannerParam()); BeforeMacroDoActionProvider beforemacroprovider = new BeforeMacroDoActionProvider(); PostMacroDoActionProvider postmacroprovider = new PostMacroDoActionProvider(); PopUpItemSingleSend popupitemsingle = new PopUpItemSingleSend( mbui, extscanwrapper.getStartedActiveScanContainer(), beforemacroprovider, postmacroprovider); requesteditpopupmenu.add(popupitemsingle); PopUpItemActiveScan popupitemscan = new PopUpItemActiveScan(mbui, extscanwrapper); requesteditpopupmenu.add(popupitemscan); requestlistpopupmenu.remove(0); // remove "SendTo" menu that is only used in burp popupitemscan = new PopUpItemActiveScan(mbui, extscanwrapper); requestlistpopupmenu.add(popupitemscan); // create menuitem for each JPopupMenu. popupitemsingle = new PopUpItemSingleSend( mbui, extscanwrapper.getStartedActiveScanContainer(), beforemacroprovider, postmacroprovider); requestlistpopupmenu.add(popupitemsingle); // scanmacrobtn.setEnabled(true); scanmacrobtn.addActionListener( ev -> { System.out.println("Executed event:" + ev.toString()); }); this.add(mbui); if (LOGGER4J != null) { LOGGER4J.debug("new MyWorkPanel"); } } }
40.315789
99
0.675196
5c11f1eaca7985b4042fcd06a3adcc7bbc7eefb0
298
package config; import java.time.Duration; public interface IServerProperties { public int get_LOGIN_SERVER_PORT(); public int get_GAME_SERVER_PORT(); public int get_LOGIN_TOKEN_LENGTH(); public int get_MAX_USERNAME_LENGTH(); public Duration get_LOGIN_TOKEN_DURATION(); }
18.625
47
0.761745
be41fe9a9e099772d07be5d99542e14432a7173d
301
package me.philippheuer.twitch4j.exceptions; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ChannelDoesNotExistException extends RuntimeException { private Long channelId; public ChannelDoesNotExistException(Long channelId) { super(); setChannelId(channelId); } }
17.705882
68
0.803987
8028295832514105705934c089f7693d4481685c
1,246
package org.bocogop.shared.model.voter; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; import com.fasterxml.jackson.annotation.JsonAutoDetect; @JsonAutoDetect(fieldVisibility = NONE, getterVisibility = PUBLIC_ONLY, isGetterVisibility = PUBLIC_ONLY) public class VoterDemographics extends AbstractSimpleVoter<VoterDemographics> { private static final long serialVersionUID = -556040665741732416L; // -------------------------------------------- Fields private String precinct; private String party; private String gender; // add fields here specific to the demographics if needed - CPB public VoterDemographics() { } // -------------------------------------------- Business Methods // -------------------------------------------- Accessor Methods public String getPrecinct() { return precinct; } public void setPrecinct(String precinct) { this.precinct = precinct; } public String getParty() { return party; } public void setParty(String party) { this.party = party; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
23.961538
105
0.686998
7c36f7d21f260a4b88db5165764db8372f8eef63
1,733
package com.zulip.android.satchat.util; /** * List of all Constants used in the projects */ public class Constants { public final static String IS_CONTENT_EDIT_PARAM_SAVED = "isContentEditParamSaved"; public final static String IS_EDITING_ALLOWED = "isEditingAllowed"; public final static String MAXIMUM_CONTENT_EDIT_LIMIT = "maximumContentEditLimit"; //Default maximum time limit for editing message(Same as server) public final static int DEFAULT_MAXIMUM_CONTENT_EDIT_LIMIT = 600; public final static boolean DEFAULT_EDITING_ALLOWED = true; public final static String SERVER_URL = "SERVER_URL"; public static final String CANCEL = "CANCEL"; public static final String DONT_SHOW_APP_UPDATE_DIALOG = "DONT_SHOW_APP_UPDATE_DIALOG"; public static int MILLISECONDS_IN_A_MINUTE = 1000; public static String DATE_FORMAT = "dd/MM/yyyy"; public static final int REQUEST_PICK_FILE = 3; public static final int HIDE_FAB_AFTER_SEC = 5; // row number which is used to differentiate the '@-mentions' in people drawer public static int MENTIONS = -2; public static int REACTION_MARGIN = 64; //end points public static String END_POINT_TERMS_OF_SERVICE = "terms"; public static String END_POINT_PRIVACY = "privacy"; public static String END_POINT_REGISTER = "register"; //if two continuous messages are from same sender and time difference is less than this then hide it public static long HIDE_TIMESTAMP_THRESHOLD = 60 * 1000;// 1 minute public static String ACTION_MESSAGE_PUSH_NOTIFICATION = "ACTION_MESSAGE_PUSH_NOTIFICATION"; public static String NIGHT_THEME = "NIGHT_THEME"; public static String AUTO_NIGHT_THEME = "AUTO_NIGHT_THEME"; }
50.970588
104
0.766301