Java Code Examples for java.util.EnumMap#put()

The following examples show how to use java.util.EnumMap#put() . 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: ClientService.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
final EnumMap<TransactionAttribute, Boolean> getTXFlags() {
  final byte[] txFlags = this.txFlags;
  EnumMap<TransactionAttribute, Boolean> attrs = null;
  for (int ordinal = 0; ordinal < NUM_TXFLAGS; ordinal++) {
    int flag = txFlags[ordinal];
    switch (flag) {
      case 1:
      case -1:
        if (attrs == null) {
          attrs = ThriftUtils.newTransactionFlags();
        }
        attrs.put(TransactionAttribute.findByValue(ordinal), flag == 1);
        break;
      default:
        break;
    }
  }
  return attrs;
}
 
Example 2
Source File: DistinctEntrySetElements.java    From jdk8u60 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 3
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 4
Source File: TransactionLogHeader.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Entry parse(StaticBuffer buffer, Serializer serializer, TimestampProvider times) {
    ReadBuffer read = buffer.asReadBuffer();
    Instant txTimestamp = times.getTime(read.getLong());
    TransactionLogHeader header = new TransactionLogHeader(VariableLong.readPositive(read), txTimestamp, times);
    LogTxStatus status = serializer.readObjectNotNull(read, LogTxStatus.class);
    EnumMap<LogTxMeta, Object> metadata = new EnumMap<>(LogTxMeta.class);
    int metaSize = VariableLong.unsignedByte(read.getByte());
    for (int i = 0; i < metaSize; i++) {
        LogTxMeta meta = LogTxMeta.values()[VariableLong.unsignedByte(read.getByte())];
        metadata.put(meta, serializer.readObjectNotNull(read, meta.dataType()));
    }
    if (read.hasRemaining()) {
        StaticBuffer content = read.subrange(read.getPosition(), read.length() - read.getPosition());
        return new Entry(header, content, status, metadata);
    } else {
        return new Entry(header, null, status, metadata);
    }
}
 
Example 5
Source File: Realm.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * <h1>Extension: Zones</h1>
 * 
 * @param realm
 *            the realm instance
 */
private static void initializeZonesModule(Realm realm) {
    EnumMap<Intrinsics, OrdinaryObject> intrinsics = realm.intrinsics;

    // allocation phase
    ZoneConstructor zoneConstructor = new ZoneConstructor(realm);
    ZonePrototype zonePrototype = new ZonePrototype(realm);

    // registration phase
    intrinsics.put(Intrinsics.Zone, zoneConstructor);
    intrinsics.put(Intrinsics.ZonePrototype, zonePrototype);

    // initialization phase
    zoneConstructor.initialize(realm);
    zonePrototype.initialize(realm);
}
 
Example 6
Source File: DistinctEntrySetElements.java    From jdk8u_jdk 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 7
Source File: MeasureFormat.java    From j2objc with Apache License 2.0 6 votes vote down vote up
void setFormatterIfAbsent(int index, UResource.Value value, int minPlaceholders) {
    if (patterns == null) {
        EnumMap<FormatWidth, String[]> styleToPatterns =
                cacheData.unitToStyleToPatterns.get(unit);
        if (styleToPatterns == null) {
            styleToPatterns =
                    new EnumMap<FormatWidth, String[]>(FormatWidth.class);
            cacheData.unitToStyleToPatterns.put(unit, styleToPatterns);
        } else {
            patterns = styleToPatterns.get(width);
        }
        if (patterns == null) {
            patterns = new String[MeasureFormatData.PATTERN_COUNT];
            styleToPatterns.put(width, patterns);
        }
    }
    if (patterns[index] == null) {
        patterns[index] = SimpleFormatterImpl.compileToStringMinMaxArguments(
                value.getString(), sb, minPlaceholders, 1);
    }
}
 
Example 8
Source File: DistinctEntrySetElements.java    From jdk8u-jdk 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 9
Source File: ProperEntrySetOnClone.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    EnumMap<Test, String> map1 = new EnumMap<Test, String>(Test.class);
    map1.put(Test.ONE, "1");
    map1.put(Test.TWO, "2");

    // We need to force creation of the map1.entrySet
    int size = map1.entrySet().size();
    if (size != 2) {
        throw new RuntimeException(
                "Invalid size in original map. Expected: 2 was: " + size);
    }

    EnumMap<Test, String> map2 = map1.clone();
    map2.remove(Test.ONE);
    size = map2.entrySet().size();
    if (size != 1) {
        throw new RuntimeException(
                "Invalid size in cloned instance. Expected: 1 was: " + size);
    }
}
 
Example 10
Source File: DefaultCapacityMonitoringServiceMetrics.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private EnumMap<Tier, EnumMap<ResourceType, AtomicLong>> buildResourceShortageMap(Registry registry) {
    EnumMap<Tier, EnumMap<ResourceType, AtomicLong>> result = new EnumMap<>(Tier.class);
    for (Tier tier : Tier.values()) {
        EnumMap<ResourceType, AtomicLong> resourceMap = new EnumMap<>(ResourceType.class);
        result.put(tier, resourceMap);

        Id tierId = registry.createId(MetricConstants.METRIC_CAPACITY_MANAGEMENT + "monitor.capacityShortage", "tier", tier.name());

        for (ResourceType resourceType : ResourceType.values()) {
            resourceMap.put(
                    resourceType,
                    registry.gauge(tierId.withTag("resourceType", resourceType.name()), new AtomicLong())
            );
        }
    }
    return result;
}
 
Example 11
Source File: GFXDServiceImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Map<TransactionAttribute, Boolean> getTransactionAttributes(
    int connId, ByteBuffer token) throws GFXDException {
  try {
    EmbedConnection conn = getValidConnection(connId, token).getConnection();

    final EnumMap<TransactionAttribute, Boolean> txAttrs = ThriftUtils
        .newTransactionFlags();
    EnumSet<TransactionFlag> txFlags = conn.getTR().getTXFlags();
    txAttrs.put(TransactionAttribute.AUTOCOMMIT, conn.getAutoCommit());
    txAttrs.put(TransactionAttribute.READ_ONLY_CONNECTION,
        conn.isReadOnly());
    if (txFlags != null) {
      txAttrs.put(TransactionAttribute.DISABLE_BATCHING,
          txFlags.contains(TransactionFlag.DISABLE_BATCHING));
      txAttrs.put(TransactionAttribute.SYNC_COMMITS,
          txFlags.contains(TransactionFlag.SYNC_COMMITS));
      txAttrs.put(TransactionAttribute.WAITING_MODE,
          txFlags.contains(TransactionFlag.WAITING_MODE));
    }
    else {
      txAttrs.put(TransactionAttribute.DISABLE_BATCHING, false);
      txAttrs.put(TransactionAttribute.SYNC_COMMITS, false);
      txAttrs.put(TransactionAttribute.WAITING_MODE, false);
    }
    return txAttrs;
  } catch (Throwable t) {
    throw gfxdException(t);
  }
}
 
Example 12
Source File: PlanetChartTestCase.java    From Astrosoft with GNU General Public License v2.0 5 votes vote down vote up
private static void setUpChart2() {
	
	EnumMap<Planet, Integer> planetLoc = new EnumMap<Planet, Integer>(Planet.class);
	
	planetLoc.put(Planet.Sun, 1);
   	planetLoc.put(Planet.Moon, 4);
   	planetLoc.put(Planet.Mars, 4);
   	planetLoc.put(Planet.Mercury, 6);
   	planetLoc.put(Planet.Jupiter, 2);
   	planetLoc.put(Planet.Venus, 2);
   	planetLoc.put(Planet.Saturn, 2);
   	planetLoc.put(Planet.Rahu, 2);
   	planetLoc.put(Planet.Ketu, 2);
   	planetLoc.put(Planet.Ascendant, 1);
   	
   	EnumMap<Planet, Rasi> planetHouse = new EnumMap<Planet, Rasi>(Planet.class);
   	
   	planetHouse.put(Planet.Sun, Rasi.Mesha); //Exalted
   	planetHouse.put(Planet.Moon, Rasi.Kataka); // Own
   	planetHouse.put(Planet.Mars, Rasi.Kataka); // Debilitated
   	planetHouse.put(Planet.Mercury, Rasi.Kanya); //Moola trikona
   	planetHouse.put(Planet.Jupiter, Rasi.Vrishabha);
   	planetHouse.put(Planet.Venus, Rasi.Vrishabha);
   	planetHouse.put(Planet.Saturn, Rasi.Vrishabha);
   	planetHouse.put(Planet.Rahu, Rasi.Vrishabha);
   	planetHouse.put(Planet.Ketu, Rasi.Vrishabha);
   	planetHouse.put(Planet.Ascendant, Rasi.Mesha);
   	
   	chart2 = new PlanetChart(Varga.Rasi,planetLoc, planetHouse );
	
}
 
Example 13
Source File: StellarMicrobenchmark.java    From metron with Apache License 2.0 5 votes vote down vote up
public static EnumMap<BenchmarkOptions, Optional<Object>> createConfig(CommandLine cli) {
  EnumMap<BenchmarkOptions, Optional<Object> > ret = new EnumMap<>(BenchmarkOptions.class);
  for(BenchmarkOptions option : values()) {
    ret.put(option, option.handler.getValue(option, cli));
  }
  return ret;
}
 
Example 14
Source File: MainActivity.java    From SimpleDialogFragments with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return your Image here.
 * NOTE: make sure, your class is public and has a public default constructor!
 *
 * @param tag    The dialog-fragments tag
 * @param extras The extras supplied to {@link SimpleImageDialog#extra(Bundle)}
 * @return the image to be shown
 */
@Override
public Bitmap create(@Nullable String tag, @NonNull Bundle extras) {
    String content = extras.getString(QR_CONTENT);
    if (content == null) return null;

    // Generate
    try {
        EnumMap<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE,
                1024, 1024, hints);
        int width = bitMatrix.getWidth(), height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pixels[y*width + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
            }
        }
        Bitmap qr = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        qr.setPixels(pixels, 0, width, 0, 0, width, height);
        return qr;

    } catch (WriterException ignored) {}

    return null;
}
 
Example 15
Source File: Cast_From_AkIntervalSeconds.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
private static EnumMap<TimeUnit, Double> createPlaceMultiplierMap() {
    // Desired result is something like 20120802120133.000000
    // Nicer format: yyyyMMddHHmmSS.uuuuuu 
    EnumMap<TimeUnit, Double> result = new EnumMap<>(TimeUnit.class);
    result.put(TimeUnit.MICROSECONDS, 1.0d/1000000.0d);
    result.put(TimeUnit.SECONDS,      1d);
    result.put(TimeUnit.MINUTES,    100d);
    result.put(TimeUnit.HOURS,    10000d);
    result.put(TimeUnit.DAYS,   1000000d);
    return result;
}
 
Example 16
Source File: FSEditLog.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private static void incrOpCount(FSEditLogOpCodes opCode,
    EnumMap<FSEditLogOpCodes, Holder<Integer>> opCounts) {
  Holder<Integer> holder = opCounts.get(opCode);
  if (holder == null) {
    holder = new Holder<Integer>(1);
    opCounts.put(opCode, holder);
  } else {
    holder.held++;
  }
}
 
Example 17
Source File: CompileStringsStep.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Similar to {@code scrapeStringNodes}, but for plurals nodes. */
@VisibleForTesting
void scrapePluralsNodes(
    NodeList pluralNodes,
    Map<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap) {

  for (int i = 0; i < pluralNodes.getLength(); ++i) {
    Element element = (Element) pluralNodes.item(i);
    String resourceName = element.getAttribute("name");
    Gender gender = getGender(element);

    Integer resourceId = getResourceId(resourceName, gender, pluralsResourceNameToIdMap);
    // Ignore a resource if R.txt does not contain an entry for it.
    if (resourceId == null) {
      continue;
    }

    EnumMap<Gender, ImmutableMap<String, String>> genderMap = pluralsMap.get(resourceId);
    if (genderMap == null) {
      genderMap = Maps.newEnumMap(Gender.class);
    } else if (genderMap.containsKey(gender)) { // Ignore a resource if it has already been found
      continue;
    }

    ImmutableMap.Builder<String, String> quantityToStringBuilder = ImmutableMap.builder();

    NodeList itemNodes = element.getElementsByTagName("item");
    for (int j = 0; j < itemNodes.getLength(); ++j) {
      Node itemNode = itemNodes.item(j);
      String quantity = itemNode.getAttributes().getNamedItem("quantity").getNodeValue();
      quantityToStringBuilder.put(quantity, itemNode.getTextContent());
    }

    genderMap.put(gender, quantityToStringBuilder.build());
    pluralsMap.put(resourceId, genderMap);
  }
}
 
Example 18
Source File: RoundRobinOperatorStateRepartitioner.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Group by the different named states.
 */
@SuppressWarnings("unchecked, rawtype")
private GroupByStateNameResults groupByStateMode(List<List<OperatorStateHandle>> previousParallelSubtaskStates) {

	//Reorganize: group by (State Name -> StreamStateHandle + StateMetaInfo)
	EnumMap<OperatorStateHandle.Mode,
			Map<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>>> nameToStateByMode =
			new EnumMap<>(OperatorStateHandle.Mode.class);

	for (OperatorStateHandle.Mode mode : OperatorStateHandle.Mode.values()) {

		nameToStateByMode.put(
				mode,
				new HashMap<>());
	}

	for (List<OperatorStateHandle> previousParallelSubtaskState : previousParallelSubtaskStates) {
		for (OperatorStateHandle operatorStateHandle : previousParallelSubtaskState) {

			if (operatorStateHandle == null) {
				continue;
			}

			final Set<Map.Entry<String, OperatorStateHandle.StateMetaInfo>> partitionOffsetEntries =
				operatorStateHandle.getStateNameToPartitionOffsets().entrySet();

			for (Map.Entry<String, OperatorStateHandle.StateMetaInfo> e : partitionOffsetEntries) {
				OperatorStateHandle.StateMetaInfo metaInfo = e.getValue();

				Map<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>> nameToState =
					nameToStateByMode.get(metaInfo.getDistributionMode());

				List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>> stateLocations =
					nameToState.computeIfAbsent(
						e.getKey(),
						k -> new ArrayList<>(previousParallelSubtaskStates.size() * partitionOffsetEntries.size()));

				stateLocations.add(Tuple2.of(operatorStateHandle.getDelegateStateHandle(), e.getValue()));
			}
		}
	}

	return new GroupByStateNameResults(nameToStateByMode);
}
 
Example 19
Source File: CompileStringsStepTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testScrapePluralsNodes() throws IOException, SAXException {
  String xmlInput =
      "<plurals name='name1' gender='unknown'>"
          + "<item quantity='zero'>%d people saw this</item>"
          + "<item quantity='one'>%d person saw this</item>"
          + "<item quantity='many'>%d people saw this</item>"
          + "</plurals>"
          + "<plurals name='name1_f1gender' gender='female'>"
          + "<item quantity='zero'>%d people saw this f1</item>"
          + "<item quantity='one'>%d person saw this f1</item>"
          + "<item quantity='many'>%d people saw this f1</item>"
          + "</plurals>"
          + "<plurals name='name2' gender='unknown'>"
          + "<item quantity='zero'>%d people ate this</item>"
          + "<item quantity='many'>%d people ate this</item>"
          + "</plurals>"
          + "<plurals name='name2_m2gender' gender='male'>"
          + "<item quantity='zero'>%d people ate this m2</item>"
          + "<item quantity='many'>%d people ate this m2</item>"
          + "</plurals>"
          + "<plurals name='name3' gender='unknown'></plurals>"
          + // Test empty array.
          // Ignored since "name2" already found.
          "<plurals name='name2' gender='unknown'></plurals>";
  NodeList pluralsNodes =
      XmlDomParser.parse(createResourcesXml(xmlInput)).getElementsByTagName("plurals");

  EnumMap<Gender, ImmutableMap<String, String>> map1 = Maps.newEnumMap(Gender.class);
  map1.put(
      Gender.unknown,
      ImmutableMap.of(
          "zero", "%d people saw this",
          "one", "%d person saw this",
          "many", "%d people saw this"));
  map1.put(
      Gender.female,
      ImmutableMap.of(
          "zero", "%d people saw this f1",
          "one", "%d person saw this f1",
          "many", "%d people saw this f1"));
  EnumMap<Gender, ImmutableMap<String, String>> map2 = Maps.newEnumMap(Gender.class);
  map2.put(
      Gender.unknown,
      ImmutableMap.of(
          "zero", "%d people ate this",
          "many", "%d people ate this"));
  map2.put(
      Gender.male,
      ImmutableMap.of(
          "zero", "%d people ate this m2",
          "many", "%d people ate this m2"));
  EnumMap<Gender, ImmutableMap<String, String>> map3 = Maps.newEnumMap(Gender.class);
  map3.put(Gender.unknown, ImmutableMap.of());

  Map<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap = new HashMap<>();
  CompileStringsStep step = createNonExecutingStep();
  step.addPluralsResourceNameToIdMap(
      ImmutableMap.of(
          "name1", 1,
          "name2", 2,
          "name3", 3));
  step.scrapePluralsNodes(pluralsNodes, pluralsMap);

  assertEquals(
      "Incorrect map of resource id to plural values.",
      ImmutableMap.of(
          1, map1,
          2, map2,
          3, map3),
      pluralsMap);
}
 
Example 20
Source File: ShadBala.java    From Astrosoft with GNU General Public License v2.0 3 votes vote down vote up
private EnumMap<Planet, Double> calcDrekkanaBala() {

		int drek = 0;

		EnumMap<Planet, Double> DrekkanaBala = initBala();

		for (Planet p : Planet.majorPlanets()) {

			drek = (int) ((planetPosition.get(p) % 30) / 10) + 1;

			if (((p == Planet.Sun) || (p == Planet.Mars) || (p == Planet.Jupiter))
					&& (drek == 1)) {
				DrekkanaBala.put(p, 15.0);
			}

			if (((p == Planet.Mercury) || (p == Planet.Saturn)) && (drek == 2)) {
				DrekkanaBala.put(p, 15.0);
			}

			if (((p == Planet.Moon) || (p == Planet.Venus)) && (drek == 3)) {
				DrekkanaBala.put(p, 15.0);
			}

		}

		return DrekkanaBala;

	}