java.util.EnumMap Java Examples

The following examples show how to use java.util.EnumMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void main(String[] args) {
    // 测试 PayrollDay (策略枚举)
    System.out.println("时薪100的人在周五工作8小时的收入:" + PayrollDay.FRIDAY.pay(8.0, 100));
    System.out.println("时薪100的人在周六工作8小时的收入:" + PayrollDay.SATURDAY.pay(8.0, 100));

    // EnumSet的使用
    System.out.println("EnumSet展示");
    EnumSet<ErrorCodeEn> errSet = EnumSet.allOf(ErrorCodeEn.class);
    for (ErrorCodeEn e : errSet) {
        System.out.println(e.name() + " : " + e.ordinal());
    }

    // EnumMap的使用
    System.out.println("EnumMap展示");
    EnumMap<StateMachineDemo.Signal, String> errMap = new EnumMap(StateMachineDemo.Signal.class);
    errMap.put(StateMachineDemo.Signal.RED, "红灯");
    errMap.put(StateMachineDemo.Signal.YELLOW, "黄灯");
    errMap.put(StateMachineDemo.Signal.GREEN, "绿灯");
    for (Iterator<Map.Entry<StateMachineDemo.Signal, String>> iter = errMap.entrySet().iterator(); iter
        .hasNext(); ) {
        Map.Entry<StateMachineDemo.Signal, String> entry = iter.next();
        System.out.println(entry.getKey().name() + " : " + entry.getValue());
    }
}
 
Example #2
Source File: Cities.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private List<Entry> search(double lat, double lng) throws SQLException {

    EnumMap<Source, Entry> map = new EnumMap<>(Source.class);
    for (Source source : Source.values()) {
        if (source.citiesId == 0) continue;
        CitiesSet entries = new CitiesSet(source);
        for (Entry entry : entries) {
            if (entry == null || entry.getKey() == null) continue;
            Source s = entry.getSource();
            Entry e = map.get(s);
            double latDist = Math.abs(lat - entry.getLat());
            double lngDist = Math.abs(lng - entry.getLng());
            if (e == null) {
                if (latDist < 2 && lngDist < 2)
                    map.put(s, (Entry) entry.clone());
            } else {
                if (latDist + lngDist < Math.abs(lat - e.getLat()) + Math.abs(lng - e.getLng())) {
                    map.put(s, (Entry) entry.clone());
                }
            }
        }
    }
    return new ArrayList<>(map.values());

}
 
Example #3
Source File: UserAnnotationPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private EnumMap<UserAnnotationTag.Type, JCheckBox> createTypeCheckBoxes() {
    EnumMap<UserAnnotationTag.Type, JCheckBox> map = new EnumMap<>(UserAnnotationTag.Type.class);
    for (UserAnnotationTag.Type type : UserAnnotationTag.Type.values()) {
        JCheckBox checkBox;
        switch (type) {
            case FUNCTION:
                checkBox = functionCheckBox;
                break;
            case TYPE:
                checkBox = typeCheckBox;
                break;
            case METHOD:
                checkBox = methodCheckBox;
                break;
            case FIELD:
                checkBox = fieldCheckBox;
                break;
            default:
                throw new IllegalStateException("Unknown type: " + type);
        }
        map.put(type, checkBox);
    }
    return map;
}
 
Example #4
Source File: RelativeDateTimeFormatter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private RelativeDateTimeFormatter(
        EnumMap<Style, EnumMap<AbsoluteUnit, EnumMap<Direction, String>>> qualitativeUnitMap,
        EnumMap<Style, EnumMap<RelativeUnit, String[][]>> patternMap,
        String combinedDateAndTime,
        PluralRules pluralRules,
        NumberFormat numberFormat,
        Style style,
        DisplayContext capitalizationContext,
        BreakIterator breakIterator,
        ULocale locale) {
    this.qualitativeUnitMap = qualitativeUnitMap;
    this.patternMap = patternMap;
    this.combinedDateAndTime = combinedDateAndTime;
    this.pluralRules = pluralRules;
    this.numberFormat = numberFormat;
    this.style = style;
    if (capitalizationContext.type() != DisplayContext.Type.CAPITALIZATION) {
        throw new IllegalArgumentException(capitalizationContext.toString());
    }
    this.capitalizationContext = capitalizationContext;
    this.breakIterator = breakIterator;
    this.locale = locale;
    this.dateFormatSymbols = new DateFormatSymbols(locale);
}
 
Example #5
Source File: Synch.java    From pegasus with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the log.
 *
 * @param properties properties with pegasus prefix stripped.
 * @param level
 * @param jsonFileMap
 * @throws IOException
 */
public void initialze(
        Properties properties, Level level, EnumMap<BATCH_ENTITY_TYPE, String> jsonFileMap)
        throws IOException {
    // "405596411149";
    mLogger = Logger.getLogger(Synch.class.getName());
    mLogger.setLevel(level);
    mAWSAccountID = getProperty(properties, Synch.AWS_PROPERTY_PREFIX, "account");
    mAWSRegion =
            Region.of(
                    getProperty(
                            properties, Synch.AWS_PROPERTY_PREFIX, "region")); // "us-west-2"
    mPrefix = getProperty(properties, Synch.AWS_BATCH_PROPERTY_PREFIX, "prefix");
    mDeleteOnExit = new EnumMap<>(BATCH_ENTITY_TYPE.class);
    mCommonFilesToS3 = new LinkedList<String>();
    mS3BucketKeyPrefix = "";

    mJobstateWriter = new AWSJobstateWriter();
    mJobstateWriter.initialze(new File("."), mPrefix, mLogger);

    mJobMap = new HashMap();
    mExecutorService = Executors.newFixedThreadPool(2);
    mBatchClient = BatchClient.builder().region(mAWSRegion).build();
    mDoneWithJobSubmits = false;
    mExitCode = 0;
}
 
Example #6
Source File: GridCommandHandlerClusterByClassTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Test to verify that the experimental command will not be executed if
 * {@link IgniteSystemProperties#IGNITE_ENABLE_EXPERIMENTAL_COMMAND} =
 * {@code false}, a warning will be displayed instead.
 * */
@Test
@WithSystemProperty(key = IGNITE_ENABLE_EXPERIMENTAL_COMMAND, value = "false")
public void testContainsWarnInsteadExecExperimentalCmdWhenEnableExperimentalFalse() {
    injectTestSystemOut();

    Map<CommandList, Collection<String>> cmdArgs = new EnumMap<>(CommandList.class);

    cmdArgs.put(WAL, asList("print", "delete"));
    cmdArgs.put(METADATA, asList("help", "list"));

    String warning = String.format(
        "For use experimental command add %s=true to JVM_OPTS in %s",
        IGNITE_ENABLE_EXPERIMENTAL_COMMAND,
        UTILITY_NAME
    );

    stream(CommandList.values()).filter(cmd -> cmd.command().experimental())
        .peek(cmd -> assertTrue("Not contains " + cmd, cmdArgs.containsKey(cmd)))
        .forEach(cmd -> cmdArgs.get(cmd).forEach(cmdArg -> {
            assertEquals(EXIT_CODE_OK, execute(cmd.text(), cmdArg));

            assertContains(log, testOut.toString(), warning);
        }));
}
 
Example #7
Source File: ShapeFillingCustomiser.java    From latexdraw with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void initialize(final URL location, final ResourceBundle resources) {
	super.initialize(location, resources);
	mainPane.managedProperty().bind(mainPane.visibleProperty());
	fillPane.managedProperty().bind(fillPane.visibleProperty());
	hatchingsPane.managedProperty().bind(hatchingsPane.visibleProperty());
	gradientPane.managedProperty().bind(gradientPane.visibleProperty());

	final Map<FillingStyle, Image> cache = new EnumMap<>(FillingStyle.class);
	cache.put(FillingStyle.NONE, new Image("/res/hatch/hatch.none.png")); //NON-NLS
	cache.put(FillingStyle.PLAIN, new Image("/res/hatch/hatch.solid.png")); //NON-NLS
	cache.put(FillingStyle.CLINES, new Image("/res/hatch/hatch.cross.png")); //NON-NLS
	cache.put(FillingStyle.CLINES_PLAIN, new Image("/res/hatch/hatchf.cross.png")); //NON-NLS
	cache.put(FillingStyle.HLINES, new Image("/res/hatch/hatch.horiz.png")); //NON-NLS
	cache.put(FillingStyle.HLINES_PLAIN, new Image("/res/hatch/hatchf.horiz.png")); //NON-NLS
	cache.put(FillingStyle.VLINES, new Image("/res/hatch/hatch.vert.png")); //NON-NLS
	cache.put(FillingStyle.VLINES_PLAIN, new Image("/res/hatch/hatchf.vert.png")); //NON-NLS
	cache.put(FillingStyle.GRAD, new Image("/res/hatch/gradient.png")); //NON-NLS
	initComboBox(fillStyleCB, cache, FillingStyle.values());
}
 
Example #8
Source File: ShadBala.java    From Astrosoft with GNU General Public License v2.0 6 votes vote down vote up
private EnumMap<Planet, Double> calcOchchaBala() {

		double[] debiliPos = {190.0, 213.0, 118.0, 345.0, 275.0, 177.0, 20.0};

		EnumMap<Planet, Double> OchchaBala = new EnumMap<Planet, Double>(
				Planet.class);
		for (Planet p : Planet.majorPlanets()) {

			double balaVal = Math.abs(planetPosition.get(p)
					- debiliPos[p.ordinal()]) / 3;

			if (balaVal > 60.00) {
				balaVal = 120.00 - balaVal;
			}

			OchchaBala.put(p, balaVal);
		}

		return OchchaBala;
	}
 
Example #9
Source File: ShadBala.java    From Astrosoft with GNU General Public License v2.0 6 votes vote down vote up
private EnumMap<Planet, Double> calcNatonnataBala() {

		double btimeDeg = SwissHelper.calcNatonnataBalaDeg(birthData.birthSD(),
				birthData.birthTime());

		EnumMap<Planet, Double> NatonnataBala = new EnumMap<Planet, Double>(
				Planet.class);

		NatonnataBala.put(Planet.Sun, btimeDeg / 3);
		NatonnataBala.put(Planet.Jupiter, btimeDeg / 3);
		NatonnataBala.put(Planet.Venus, btimeDeg / 3);

		NatonnataBala.put(Planet.Moon, ((180 - btimeDeg) / 3));
		NatonnataBala.put(Planet.Mars, ((180 - btimeDeg) / 3));
		NatonnataBala.put(Planet.Saturn, ((180 - btimeDeg) / 3));

		NatonnataBala.put(Planet.Mercury, 60.0);

		return NatonnataBala;
		// System.out.println("\nbt : " + birthData.birthTime() + " E: " +
		// AstroUtil.dms(EqnOfTime) + sbErr);
	}
 
Example #10
Source File: DataStyles.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param booleanDataStyle    the style for booleans
 * @param currencyDataStyle   the style for currencies
 * @param dateDataStyle       the style for dates
 * @param floatDataStyle      the style for numbers
 * @param percentageDataStyle the style for percentages
 * @param timeDataStyle       the style for times
 */
public DataStyles(final BooleanStyle booleanDataStyle, final CurrencyStyle currencyDataStyle,
                  final DateStyle dateDataStyle, final FloatStyle floatDataStyle,
                  final PercentageStyle percentageDataStyle, final TimeStyle timeDataStyle) {
    if (booleanDataStyle == null || currencyDataStyle == null || dateDataStyle == null ||
            floatDataStyle == null || percentageDataStyle == null || timeDataStyle == null) {
        throw new IllegalArgumentException();
    }

    this.booleanDataStyle = booleanDataStyle;
    this.currencyDataStyle = currencyDataStyle;
    this.dateDataStyle = dateDataStyle;
    this.floatDataStyle = floatDataStyle;
    this.percentageDataStyle = percentageDataStyle;
    this.timeDataStyle = timeDataStyle;

    this.dataStyleByType = new EnumMap<CellType, DataStyle>(CellType.class);
    this.dataStyleByType.put(CellType.BOOLEAN, this.booleanDataStyle);
    this.dataStyleByType.put(CellType.CURRENCY, this.currencyDataStyle);
    this.dataStyleByType.put(CellType.DATE, this.dateDataStyle);
    this.dataStyleByType.put(CellType.FLOAT, this.floatDataStyle);
    this.dataStyleByType.put(CellType.PERCENTAGE, this.percentageDataStyle);
    this.dataStyleByType.put(CellType.TIME, this.timeDataStyle);
}
 
Example #11
Source File: Cities.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private List<Entry> search(double lat, double lng) throws SQLException {

    EnumMap<Source, Entry> map = new EnumMap<>(Source.class);
    for (Source source : Source.values()) {
        if (source.citiesId == 0) continue;
        CitiesSet entries = new CitiesSet(source);
        for (Entry entry : entries) {
            if (entry == null || entry.getKey() == null) continue;
            Source s = entry.getSource();
            Entry e = map.get(s);
            double latDist = Math.abs(lat - entry.getLat());
            double lngDist = Math.abs(lng - entry.getLng());
            if (e == null) {
                if (latDist < 2 && lngDist < 2)
                    map.put(s, (Entry) entry.clone());
            } else {
                if (latDist + lngDist < Math.abs(lat - e.getLat()) + Math.abs(lng - e.getLng())) {
                    map.put(s, (Entry) entry.clone());
                }
            }
        }
    }
    return new ArrayList<>(map.values());

}
 
Example #12
Source File: MoleculeDescriptor.java    From thunderstorm with GNU General Public License v3.0 6 votes vote down vote up
public static Vector<Units> getCompatibleUnits(Units selected) {
    if((groups == null) || (groupMap == null)) {
        groups = new Vector[5];
        groups[0] = new Vector<Units>(Arrays.asList(new Units[]{Units.PIXEL, Units.NANOMETER, Units.MICROMETER}));
        groups[1] = new Vector<Units>(Arrays.asList(new Units[]{Units.PIXEL_SQUARED, Units.NANOMETER_SQUARED, Units.MICROMETER_SQUARED}));
        groups[2] = new Vector<Units>(Arrays.asList(new Units[]{Units.DIGITAL, Units.PHOTON}));
        groups[3] = new Vector<Units>(Arrays.asList(new Units[]{Units.DEGREE, Units.RADIAN}));
        groups[4] = new Vector<Units>(Arrays.asList(new Units[]{Units.UNITLESS}));
        //
        groupMap = new EnumMap<Units, Integer>(Units.class);
        groupMap.put(Units.PIXEL, 0);
        groupMap.put(Units.NANOMETER, 0);
        groupMap.put(Units.MICROMETER, 0);
        groupMap.put(Units.PIXEL_SQUARED, 1);
        groupMap.put(Units.NANOMETER_SQUARED, 1);
        groupMap.put(Units.MICROMETER_SQUARED, 1);
        groupMap.put(Units.DIGITAL, 2);
        groupMap.put(Units.PHOTON, 2);
        groupMap.put(Units.DEGREE, 3);
        groupMap.put(Units.RADIAN, 3);
        groupMap.put(Units.UNITLESS, 4);
    }
    return groups[groupMap.get(selected)];
}
 
Example #13
Source File: FileSourceGEXF.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <pre>
 * name 		: THICKNESS
 * attributes 	: THICKNESSAttribute { VALUE!, START, STARTOPEN, END, ENDOPEN }
 * structure 	: SPELLS ?
 * </pre>
 */
private void __thickness(final String edgeId) throws IOException, XMLStreamException {
	XMLEvent e;
	EnumMap<THICKNESSAttribute, String> attributes;

	e = getNextEvent();
	checkValid(e, XMLEvent.START_ELEMENT, "thickness");

	attributes = getAttributes(THICKNESSAttribute.class, e.asStartElement());

	checkRequiredAttributes(e, attributes, THICKNESSAttribute.VALUE);

	e = getNextEvent();

	if (isEvent(e, XMLEvent.START_ELEMENT, "spells")) {
		pushback(e);

		__spells();
		e = getNextEvent();
	}

	checkValid(e, XMLEvent.END_ELEMENT, "thickness");
}
 
Example #14
Source File: DistinctEntrySetElements.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final EnumMap<TestEnum, String> enumMap = new EnumMap<>(TestEnum.class);

    for (TestEnum e : TestEnum.values()) {
        enumMap.put(e, e.name());
    }

    Set<Map.Entry<TestEnum, String>> entrySet = enumMap.entrySet();
    HashSet<Map.Entry<TestEnum, String>> hashSet = new HashSet<>(entrySet);

    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example #15
Source File: Locations.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void initHandlers() {
    handlersForLocation = new HashMap<Location, LocationHandler>();
    handlersForOption = new EnumMap<Option, LocationHandler>(Option.class);

    LocationHandler[] handlers = {
        new BootClassPathLocationHandler(),
        new ClassPathLocationHandler(),
        new SimpleLocationHandler(StandardLocation.SOURCE_PATH, Option.SOURCEPATH),
        new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_PATH, Option.PROCESSORPATH),
        new OutputLocationHandler((StandardLocation.CLASS_OUTPUT), Option.D),
        new OutputLocationHandler((StandardLocation.SOURCE_OUTPUT), Option.S),
        new OutputLocationHandler((StandardLocation.NATIVE_HEADER_OUTPUT), Option.H)
    };

    for (LocationHandler h: handlers) {
        handlersForLocation.put(h.location, h);
        for (Option o: h.options)
            handlersForOption.put(o, h);
    }
}
 
Example #16
Source File: PizzaUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {

    List<Pizza> pzList = new ArrayList<>();
    Pizza pz1 = new Pizza();
    pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);

    Pizza pz2 = new Pizza();
    pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);

    Pizza pz3 = new Pizza();
    pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);

    Pizza pz4 = new Pizza();
    pz4.setStatus(Pizza.PizzaStatusEnum.READY);

    pzList.add(pz1);
    pzList.add(pz2);
    pzList.add(pz3);
    pzList.add(pz4);

    EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
    assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
    assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
    assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
}
 
Example #17
Source File: BgpProcess.java    From batfish with Apache License 2.0 6 votes vote down vote up
public BgpProcess(long procnum) {
  _afGroups = new HashMap<>();
  _aggregateNetworks = new HashMap<>();
  _aggregateIpv6Networks = new HashMap<>();
  _allPeerGroups = new HashSet<>();
  _defaultIpv4Activate = true;
  _dynamicIpPeerGroups = new HashMap<>();
  _dynamicIpv6PeerGroups = new HashMap<>();
  _namedPeerGroups = new HashMap<>();
  _ipNetworks = new LinkedHashMap<>();
  _ipPeerGroups = new HashMap<>();
  _ipv6Networks = new LinkedHashMap<>();
  _ipv6PeerGroups = new HashMap<>();
  _peerSessions = new HashMap<>();
  _procnum = procnum;
  _redistributionPolicies = new EnumMap<>(RoutingProtocol.class);
  _masterBgpPeerGroup = new MasterBgpPeerGroup();
  _masterBgpPeerGroup.setAdvertiseInactive(true);
  _masterBgpPeerGroup.setDefaultMetric(DEFAULT_BGP_DEFAULT_METRIC);
}
 
Example #18
Source File: ExpansionComp.java    From scelight with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection< GeneralStats< ExpansionLevel > > calculateStats( final PlayerStats playerStats ) {
	// Calculate stats
	final Map< ExpansionLevel, GeneralStats< ExpansionLevel > > generalStatsMap = new EnumMap<>( ExpansionLevel.class );
	for ( final Game g : playerStats.gameList )
		for ( final Part refPart : g.parts ) { // Have to go through all participants as the zero-toon might be present multiple times
			if ( !playerStats.obj.equals( refPart.toon ) )
				continue;
			
			GeneralStats< ExpansionLevel > gs = generalStatsMap.get( g.expansion );
			if ( gs == null )
				generalStatsMap.put( g.expansion, gs = new GeneralStats<>( g.expansion ) );
			gs.updateWithPartGame( refPart, g );
		}
	
	return generalStatsMap.values();
}
 
Example #19
Source File: Locations.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void initHandlers() {
    handlersForLocation = new HashMap<Location, LocationHandler>();
    handlersForOption = new EnumMap<Option, LocationHandler>(Option.class);

    LocationHandler[] handlers = {
        new BootClassPathLocationHandler(),
        new ClassPathLocationHandler(),
        new SimpleLocationHandler(StandardLocation.SOURCE_PATH, Option.SOURCEPATH),
        new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_PATH, Option.PROCESSORPATH),
        new OutputLocationHandler((StandardLocation.CLASS_OUTPUT), Option.D),
        new OutputLocationHandler((StandardLocation.SOURCE_OUTPUT), Option.S),
        new OutputLocationHandler((StandardLocation.NATIVE_HEADER_OUTPUT), Option.H)
    };

    for (LocationHandler h: handlers) {
        handlersForLocation.put(h.location, h);
        for (Option o: h.options)
            handlersForOption.put(o, h);
    }
}
 
Example #20
Source File: WrodlPartyService.java    From mapleLemon with GNU General Public License v2.0 6 votes vote down vote up
private WrodlPartyService() {
    try {
        try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characters SET party = -1, fatigue = 0")) {
            ps.executeUpdate();
            ps.close();
        }
    } catch (SQLException e) {
        FileoutputUtil.log("更新角色组队为-1失败");
    }
    this.runningPartyId = new AtomicInteger(1);
    this.runningExpedId = new AtomicInteger(1);
    this.partyList = new HashMap();
    this.expedsList = new HashMap();
    this.searcheList = new EnumMap(PartySearchType.class);
    for (PartySearchType pst : PartySearchType.values()) {
        this.searcheList.put(pst, new ArrayList());
    }
}
 
Example #21
Source File: ChainConfiguration.java    From aion with MIT License 6 votes vote down vote up
public ParentBlockHeaderValidator createUnityParentBlockHeaderValidator() {
    List<DependentBlockHeaderRule> PoWrules =
            Arrays.asList(
                    new BlockNumberRule(),
                    new ParentOppositeTypeRule(),
                    new TimeStampRule(),
                    new EnergyLimitRule(
                            getConstants().getEnergyDivisorLimitLong(),
                            getConstants().getEnergyLowerBoundLong()));
    
    List<DependentBlockHeaderRule> PoSrules =
            Arrays.asList(
                    new BlockNumberRule(),
                    new ParentOppositeTypeRule(),
                    new StakingBlockTimeStampRule(),
                    new TimeStampRule(),
                    new EnergyLimitRule(
                            getConstants().getEnergyDivisorLimitLong(),
                            getConstants().getEnergyLowerBoundLong()));

    Map<Seal, List<DependentBlockHeaderRule>> unityRules = new EnumMap<>(Seal.class);
    unityRules.put(Seal.PROOF_OF_WORK, PoWrules);
    unityRules.put(Seal.PROOF_OF_STAKE, PoSrules);

    return new ParentBlockHeaderValidator(unityRules);
}
 
Example #22
Source File: AlbumTagEditorActivity.java    From Phonograph with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void save() {
    Map<FieldKey, String> fieldKeyValueMap = new EnumMap<>(FieldKey.class);
    fieldKeyValueMap.put(FieldKey.ALBUM, albumTitle.getText().toString());
    //android seems not to recognize album_artist field so we additionally write the normal artist field
    fieldKeyValueMap.put(FieldKey.ARTIST, albumArtist.getText().toString());
    fieldKeyValueMap.put(FieldKey.ALBUM_ARTIST, albumArtist.getText().toString());
    fieldKeyValueMap.put(FieldKey.GENRE, genre.getText().toString());
    fieldKeyValueMap.put(FieldKey.YEAR, year.getText().toString());

    writeValuesToFiles(fieldKeyValueMap, deleteAlbumArt ? new ArtworkInfo(getId(), null) : albumArtBitmap == null ? null : new ArtworkInfo(getId(), albumArtBitmap));
}
 
Example #23
Source File: QueryGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
void setUpBeforeEach() {
  queryGenerator = new QueryGenerator(documentIdGenerator);

  EnumMap<Operator, QueryClauseGenerator> queryClauseGeneratorMap = new EnumMap<>(Operator.class);
  queryClauseGeneratorMap.put(EQUALS, queryClauseGenerator);
  queryGenerator.setQueryClauseGeneratorMap(queryClauseGeneratorMap);
}
 
Example #24
Source File: EnumMapTagType.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@Override
public @NotNull EnumMap<K, V> fromPrimitive(@NotNull byte @NotNull [] bytes, @NotNull PersistentDataAdapterContext itemTagAdapterContext) {
    ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
    try {
        ObjectInputStream in = new ObjectInputStream(byteIn);
        return (EnumMap<K, V>) in.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    return this.reference.clone();
}
 
Example #25
Source File: DataSourceScanner.java    From tsharding with MIT License 5 votes vote down vote up
/**
 * 根据Properties配置解析得到数据源
 *
 * @param properties
 * @return
 * @throws SQLException
 */
private Map<String, Map<DataSourceType, DataSource>> getDataSources(Properties properties) throws SQLException {
    Map<String, Map<DataSourceType, DataSource>> dataSourcesMapping = new HashMap<>(2);
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String[] parts = entry.getKey().toString().trim().split("\\" + KEY_SEPARATOR);
        if (parts.length == 3) {
            String name = parts[0];
            if (!dataSourcesMapping.containsKey(name)) {
                for (DataSourceType dataSourceType : DataSourceType.values()) {

                    DataSource ds = this.dataSourceFactory.getDataSource(this.parseDataSourceConfig(name,
                            dataSourceType, properties));
                    Map<DataSourceType, DataSource> map = dataSourcesMapping.get(name);
                    if (map == null) {
                        map = new EnumMap<DataSourceType, DataSource>(DataSourceType.class);
                        dataSourcesMapping.put(name, map);
                    }
                    DataSource preValue = map.put(dataSourceType, ds);
                    if (preValue != null) {
                        throw new IllegalArgumentException("dupilicated DataSource of" + name + " "
                                + dataSourceType);
                    }
                }

            }
        } else {
            // It's illegal, ignore.
        }
    }
    return dataSourcesMapping;
}
 
Example #26
Source File: DownholeFractionationDataModel.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
public void prepareMatrixJfMapAquisitionsAquisitions() {
    // build session-wide marixJf for each type of fit function
    matrixJfMapAquisitionsAquisitions = new EnumMap<>(FitFunctionTypeEnum.class);

    // be sure times are prepared for standards AND all the work needed to support smoothing splines
    //if ( Jgammag == null ) {
    // we are now recalculating Jf each time to accomodate changes in included standards ... could be streamlined to only happen on count
    prepareSessionWithAquisitionTimes();
    int countOfAquisitions = activeXvalues.length;

    // prepare spline Jf
    Matrix Jfg = new Matrix(countOfAquisitions, countOfAquisitions);
    Matrix Jfgamma = new Matrix(countOfAquisitions, countOfAquisitions);

    for (int k = 0; k < activeXvalues.length; k++) {
        populateJacobianGAndGamma(k, activeXvalues[k], Jfg, Jfgamma);
    }

    Matrix Jf = Jfg.plus(Jfgamma.times(Jgammag));
    matrixJfMapAquisitionsAquisitions.put(FitFunctionTypeEnum.SMOOTHING_SPLINE, Jf);

    // prepare LM exponential Jf
    Jf = new Matrix(countOfAquisitions, 3);
    // the LM fit function will have to populate Jf on demand as it depends on the fit parameters
    matrixJfMapAquisitionsAquisitions.put(FitFunctionTypeEnum.EXPONENTIAL, Jf);

    // prepare line Jf
    Jf = new Matrix(countOfAquisitions, 2, 1.0);
    for (int i = 0; i < countOfAquisitions; i++) {
        Jf.set(i, 1, activeXvalues[i]);
    }
    matrixJfMapAquisitionsAquisitions.put(FitFunctionTypeEnum.LINE, Jf);

    // mean has no Jf
    matrixJfMapAquisitionsAquisitions.put(FitFunctionTypeEnum.MEAN, null);
}
 
Example #27
Source File: EnumMappingBuilder.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private EnumMappingBuilder(Class<E> enumClass) {
  this.enumClass = enumClass;
  if (Enum.class.isAssignableFrom(enumClass)) {
    this.enumToInteger = new EnumMap(enumClass);
  } else {
    this.enumToInteger = new HashMap<E, Integer>();
  }
}
 
Example #28
Source File: ConfigurableProducer.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void init() {
    effectiveConfig = new EnumMap<>(ConfigurationKey.class);

    Properties configFileProperties = new Properties();
    File configurationFile = findConfigurationFile();
    if (configurationFile != null) {
        load(configFileProperties, configurationFile);
    }

    for (ConfigurationKey configKey : ConfigurationKey.values()) {
        String name = configKey.toString();
        String envName = configKey.toEnvString();

        String value = System.getProperty(name);
        if (value == null && envName != null) {
            value = System.getenv(envName);
        }
        if (value == null) {
            value = configFileProperties.getProperty(name);
        }

        if (configKey.isFlag()) {
            effectiveConfig.put(configKey, String.valueOf(value != null));
        } else {
            effectiveConfig.put(configKey, value != null ? value : configKey.defaultValue());
        }
    }
}
 
Example #29
Source File: TestBoolean2ScorerSupplier.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testDisjunctionLeadCost() throws IOException {
  Map<Occur, Collection<ScorerSupplier>> subs = new EnumMap<>(Occur.class);
  for (Occur occur : Occur.values()) {
    subs.put(occur, new ArrayList<>());
  }
  subs.get(Occur.SHOULD).add(new FakeScorerSupplier(42, 54));
  subs.get(Occur.SHOULD).add(new FakeScorerSupplier(12, 54));
  new Boolean2ScorerSupplier(new FakeWeight(), subs, RandomPicks.randomFrom(random(), ScoreMode.values()), 0).get(100); // triggers assertions as a side-effect

  subs.get(Occur.SHOULD).clear();
  subs.get(Occur.SHOULD).add(new FakeScorerSupplier(42, 20));
  subs.get(Occur.SHOULD).add(new FakeScorerSupplier(12, 20));
  new Boolean2ScorerSupplier(new FakeWeight(), subs, RandomPicks.randomFrom(random(), ScoreMode.values()), 0).get(20); // triggers assertions as a side-effect
}
 
Example #30
Source File: OpTestCase.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected OpTestCase() {
    testScenarios = new EnumMap<>(StreamShape.class);
    testScenarios.put(StreamShape.REFERENCE, Collections.unmodifiableSet(EnumSet.allOf(StreamTestScenario.class)));
    testScenarios.put(StreamShape.INT_VALUE, Collections.unmodifiableSet(EnumSet.allOf(IntStreamTestScenario.class)));
    testScenarios.put(StreamShape.LONG_VALUE, Collections.unmodifiableSet(EnumSet.allOf(LongStreamTestScenario.class)));
    testScenarios.put(StreamShape.DOUBLE_VALUE, Collections.unmodifiableSet(EnumSet.allOf(DoubleStreamTestScenario.class)));
}