private void configureResourceSetContainerState(final List<N4JSProject> allProjects) { // a container is a project. List<String> containers = new LinkedList<>(); BiMap<String, N4JSProject> container2project = HashBiMap.create(); // the URIs of all resources directly contained in a project/container. Multimap<String, URI> container2Uris = HashMultimap.create(); for (N4JSProject project : allProjects) { String container = FileBasedWorkspace.N4FBPRJ + project.getLocation(); container2project.put(container, project); containers.add(container); for (IN4JSSourceContainer sourceContainer : project.getSourceContainers()) { Iterables.addAll(container2Uris.get(container), sourceContainer); } } // Define the Mapping of Resources (URIs to Container === Projects), rsbAcs.configure(containers, container2Uris); }
public Map<Integer, Class<? extends NetoJsonMessage>> opcodeMap(String filePath, String messagePackage) throws Exception { BiMap<Integer, Class<? extends NetoJsonMessage>> classBiMap = HashBiMap.create(); File opcodeJsonFile = getFile(filePath); ObjectMapper ob = new ObjectMapper(); JsonNode jsonNode = ob.readTree(opcodeJsonFile); Iterator<String> it = jsonNode.fieldNames(); while(it.hasNext()) { StringBuilder sb = new StringBuilder(); String className = it.next(); int opcode = jsonNode.get(className).asInt(); sb.append(messagePackage).append('.').append(className); Class<? extends NetoJsonMessage> aClass = (Class<? extends NetoJsonMessage>) Class.forName(sb.toString()); classBiMap.put(opcode, aClass); } return classBiMap; }
GqlInputConverter build() { HashBiMap<String, Descriptor> mapping = HashBiMap.create(); HashBiMap<String, EnumDescriptor> enumMapping = HashBiMap.create(getEnumMap(enumDescriptors)); LinkedList<Descriptor> loop = new LinkedList<>(descriptors); Set<FileDescriptor> fileDescriptorSet = ProtoRegistry.extractDependencies(fileDescriptors); for (FileDescriptor fileDescriptor : fileDescriptorSet) { loop.addAll(fileDescriptor.getMessageTypes()); enumMapping.putAll(getEnumMap(fileDescriptor.getEnumTypes())); } while (!loop.isEmpty()) { Descriptor descriptor = loop.pop(); if (!mapping.containsKey(descriptor.getFullName())) { mapping.put(getReferenceName(descriptor), descriptor); loop.addAll(descriptor.getNestedTypes()); enumMapping.putAll(getEnumMap(descriptor.getEnumTypes())); } } return new GqlInputConverter( ImmutableBiMap.copyOf(mapping), ImmutableBiMap.copyOf(enumMapping)); }
/** Applies the supplied modifications to the GraphQLTypes. */ private static BiMap<String, GraphQLType> modifyTypes( BiMap<String, GraphQLType> mapping, ImmutableListMultimap<String, TypeModification> modifications) { BiMap<String, GraphQLType> result = HashBiMap.create(mapping.size()); for (String key : mapping.keySet()) { if (mapping.get(key) instanceof GraphQLObjectType) { GraphQLObjectType val = (GraphQLObjectType) mapping.get(key); if (modifications.containsKey(key)) { for (TypeModification modification : modifications.get(key)) { val = modification.apply(val); } } result.put(key, val); } else { result.put(key, mapping.get(key)); } } return result; }
public static BiMap<String, String> loadStringToStringBiMap(String file, int from, int to) throws IOException { BiMap<String, String> res = HashBiMap.create(); BufferedReader reader = IOUtils.getBufferedFileReader(file); String line; while ((line = reader.readLine()) != null) { String[] tokens = line.split("\t"); if (res.containsKey(tokens[from])) throw new RuntimeException("Map already contains key: " + tokens[from]); if (res.inverse().containsKey(tokens[to])) throw new RuntimeException("Map already contains value: " + tokens[to]); res.put(tokens[from], tokens[to]); } reader.close(); return res; }
public void testTypeMap() { BiMap<String, Integer> map = HashBiMap.create(); map.put("test1", 1); map.put("test2", 2); map.put("test3", 3); map.put("test4", 4); mappings.addNodeMapping( new ListMapping("collection", "types/type", ArrayList.class, new NodeTypeMapping("", "", map, new Integer(4)))); getBean(); assertEquals(1, bean.collection.get(0)); assertEquals(2, bean.collection.get(1)); assertEquals(3, bean.collection.get(2)); assertEquals(4, bean.collection.get(3)); getPropBagEx(); assertEquals("test1", xml.getNode("types/type[0]")); assertEquals("test2", xml.getNode("types/type[1]")); assertEquals("test3", xml.getNode("types/type[2]")); assertEquals("test4", xml.getNode("types/type[3]")); }
@PostConstruct protected void initWidget() { for (DayOfWeek day : DayOfWeek.values()) { weekStart.addItem(day.toString()); } // TODO: Make this more maintainable templateDurationIndexMap = HashBiMap.create(); templateDuration.addItem("1 Week"); templateDurationIndexMap.put(1, 0); templateDuration.addItem("2 Weeks"); templateDurationIndexMap.put(2, 1); templateDuration.addItem("4 Weeks"); templateDurationIndexMap.put(4, 2); desiredWeightInput.setValidators(new DecimalMinValidator<Integer>(0)); undesiredWeightInput.setValidators(new DecimalMinValidator<Integer>(0)); }
public Multimap<K, InsertPosition<K, G, V, T>> lookup(G queryGraph, boolean exactMatch) { Set<T> queryGraphTags = extractGraphTagsWrapper(queryGraph); Collection<InsertPosition<K, G, V, T>> positions = new LinkedList<>(); findInsertPositions(positions, rootNode, queryGraph, queryGraphTags, HashBiMap.create(), HashBiMap.create(), true, exactMatch); //, writer); Multimap<K, InsertPosition<K, G, V, T>> result = HashMultimap.create(); logger.debug("Lookup result candidates: " + positions.size()); for(InsertPosition<K, G, V, T> pos : positions) { // Match with the children result.put(pos.getNode().getKey(), pos); //System.out.println("Node " + pos.node + " with keys " + pos.node.getKeys() + " iso: " + pos.getGraphIso().getInToOut()); // for(K key : pos.node.getKeys()) { // result.put(key, pos); // } } return result; }
/** * During the insert procedure, the insert graph is never renamed, because we want to figure out * how to remap existing nodes such they become a subgraph of the insertGraph. * * @param graph */ void add(IndexNode<K, G, V, T> node, K key, G insertGraph, Set<T> insertGraphTags, BiMap<V, V> baseIso, boolean forceInsert) { //, IndentedWriter writer) { // The insert graph must be larger than the node Graph Collection<InsertPosition<K, G, V, T>> positions = new LinkedList<>(); HashBiMap<V, V> deltaIso = HashBiMap.create(); findInsertPositions(positions, node, insertGraph, insertGraphTags, baseIso, deltaIso, false, false); //, writer); // positions.forEach(p -> { // System.out.println("Insert pos: " + p.getNode().getKey() + " --- " + p.getIso()); // }); for(InsertPosition<K, G, V, T> pos : positions) { performAdd(key, pos, forceInsert); //, writer); } }
/** * BiMap存储数据时出现冲突 * 存储时,如果key相同,则会覆盖,则逆转后不会有问题 * 存储时,如果key不同,value有相同,则逆转时会抛出异常IllegalArgumentException */ @Test public void testConflictInsertKV() { // 存储相同key数据,此时会覆盖k1=v1 BiMap<String, String> biMap1 = HashBiMap.create(); biMap1.put("k1", "v1"); biMap1.put("k1", "v2"); System.out.println("biMap1: " + biMap1); // 获取的只有 v2=k1 BiMap<String, String> inverseBiMap1 = biMap1.inverse(); System.out.println("inverseBiMap1: " + inverseBiMap1); System.out.println("--------------------------------------"); // 存储相同的value数据 BiMap<String, String> biMap2 = HashBiMap.create(); biMap2.put("k1", "v1"); // 此时抛出异常 java.lang.IllegalArgumentException: value already present: v1 biMap2.put("k2", "v1"); System.out.println("biMap2: " + biMap2); BiMap<String, String> inverseBiMap2 = biMap2.inverse(); System.out.println("inverseBiMap2: " + inverseBiMap2); }
/** * value如果有冲突时会抛异常,此时可以选择强制覆盖, forcePut */ @Test public void testFixedConflict() { BiMap<String, String> biMap = HashBiMap.create(); biMap.put("k1", "v1"); // 此时会强制覆盖,连原来的k1=v1都不存在 biMap.forcePut("k2", "v1"); // biMap: {k2=v1} System.out.println("biMap2: " + biMap); BiMap<String, String> inverseBiMap = biMap.inverse(); // inverseBiMap: {v1=k2} System.out.println("inverseBiMap: " + inverseBiMap); }
/** * HashBiMap key, value 相关校验 */ @Test public void testKeyValueCheck() { BiMap<String, String> biMap = HashBiMap.create(); biMap.put("k1", "v1"); // 校验 map 是否为空 boolean isBiMapEmpty = biMap.isEmpty(); System.out.println("isBiMapEmpty: " + isBiMapEmpty); // 检查某个key是否存在 boolean isKeyExists = biMap.containsKey("k1"); System.out.println("isKeyExists: " + isKeyExists); // 检查某个value是否存在 boolean isValueExists = biMap.containsValue("v1"); System.out.println("isValueExists: " + isValueExists); }
/** * HashBiMap 修改数据 * putAll * remove * replace */ @Test public void testUpdateBiMapDate() { BiMap<String, String> biMap = HashBiMap.create(); biMap.put("k1", "v1"); biMap.put("k2", "v2"); // putAll , 存入另一个Map的数据,此时如果value有重复的依然会抛异常 biMap.putAll(ImmutableBiMap.of("k3", "v3", "k4", "v4", "k5", "v5", "k6", "v6")); System.out.println("biMap putAll after: " + biMap); System.out.println("\n-------------------------------------------\n"); // remove , 移除指定key的元素,如果key不存在,则返回null String v2 = biMap.remove("k2"); String valueNotExists = biMap.remove("keyNotExists"); System.out.println("remove k2 then biMap= " + biMap + ", and remove the value= " + v2); System.out.println("valueNotExists=" + valueNotExists); System.out.println("\n-------------------------------------------\n"); // 清空map里的数据 biMap.clear(); System.out.println("clean biMap=" + biMap); }
@SuppressWarnings("unchecked") @Override public void onCreate(Map<ResourceLocation, ?> slaveset, BiMap<ResourceLocation, ? extends IForgeRegistry<?>> registries) { final ClearableObjectIntIdentityMap<IBlockState> idMap = new ClearableObjectIntIdentityMap<IBlockState>() { @SuppressWarnings("deprecation") @Override public int get(IBlockState key) { Integer integer = (Integer)this.identityMap.get(key); // There are some cases where this map is queried to serialize a state that is valid, //but somehow not in this list, so attempt to get real metadata. Doing this hear saves us 7 patches if (integer == null && key != null) integer = this.identityMap.get(key.getBlock().getStateFromMeta(key.getBlock().getMetaFromState(key))); return integer == null ? -1 : integer.intValue(); } }; ((Map<ResourceLocation,Object>)slaveset).put(BLOCKSTATE_TO_ID, idMap); final HashBiMap<Block, Item> map = HashBiMap.create(); ((Map<ResourceLocation,Object>)slaveset).put(BLOCK_TO_ITEM, map); }
public static Fluid lookupFluidForBlock(Block block) { if (fluidBlocks == null) { BiMap<Block, Fluid> tmp = HashBiMap.create(); for (Fluid fluid : fluids.values()) { if (fluid.canBePlacedInWorld() && fluid.getBlock() != null) { tmp.put(fluid.getBlock(), fluid); } } fluidBlocks = tmp; } return fluidBlocks.get(block); }
public static void loadFluidDefaults(NBTTagCompound tag) { Set<String> defaults = Sets.newHashSet(); if (tag.hasKey("DefaultFluidList",9)) { FMLLog.getLogger().log(Level.DEBUG, "Loading persistent fluid defaults from world"); NBTTagList tl = tag.getTagList("DefaultFluidList", 8); for (int i = 0; i < tl.tagCount(); i++) { defaults.add(tl.getStringTagAt(i)); } } else { FMLLog.getLogger().log(Level.DEBUG, "World is missing persistent fluid defaults - using local defaults"); } loadFluidDefaults(HashBiMap.create(fluidIDs), defaults); }
@Override public void afterPropertiesSet() throws Exception { dbEsBiMapping = HashBiMap.create(); dbEsMapping.forEach((key, value) -> { String[] keyStrings = StringUtils.split(key, "."); String[] valueStrings = StringUtils.split(value, "."); dbEsBiMapping.put(new DatabaseTableModel(keyStrings[0], keyStrings[1]), new IndexTypeModel(valueStrings[0], valueStrings[1])); }); mysqlTypeElasticsearchTypeMapping = Maps.newHashMap(); mysqlTypeElasticsearchTypeMapping.put("char", data -> data); mysqlTypeElasticsearchTypeMapping.put("text", data -> data); mysqlTypeElasticsearchTypeMapping.put("blob", data -> data); mysqlTypeElasticsearchTypeMapping.put("int", Long::valueOf); mysqlTypeElasticsearchTypeMapping.put("date", data -> LocalDateTime.parse(data, formatter)); mysqlTypeElasticsearchTypeMapping.put("time", data -> LocalDateTime.parse(data, formatter)); mysqlTypeElasticsearchTypeMapping.put("float", Double::valueOf); mysqlTypeElasticsearchTypeMapping.put("double", Double::valueOf); mysqlTypeElasticsearchTypeMapping.put("decimal", Double::valueOf); }
public static void main(String[] args) throws IOException { List<Salary> list = SalaryFileUtils.readFromFile(); long start = System.currentTimeMillis(); HashBiMap<String, LongSummaryStatistics> groupMap = list.parallelStream() .filter(s -> s.getTotalIncome() > 100000) .collect( Collectors.groupingBy( Salary::namePrefix, () -> HashBiMap.create(), Collectors.summarizingLong(Salary::getTotalIncome) ) ); groupMap.values() .parallelStream() .sorted(Comparator.comparingLong(LongSummaryStatistics::getSum).reversed()) // 默认是从小到大排序 .limit(10) .forEachOrdered(ls -> { System.out.format("[%s], count: %s, sum: %s \n", groupMap.inverse().get(ls), ls.getCount(), ls.getSum()); }); System.out.println("elapsed time : " + (System.currentTimeMillis() - start)); }
public static EurostagFakeNodes build(Network network, EurostagEchExportConfig config) { Objects.requireNonNull(network); Objects.requireNonNull(config); BiMap<String, String> fakeNodesMap = HashBiMap.create(new HashMap<>()); AtomicLongMap<String> countUsesMap = AtomicLongMap.create(); //adds 2 default fake nodes fakeNodesMap.put(EchUtil.FAKE_NODE_NAME1, EchUtil.FAKE_NODE_NAME1); countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME1); fakeNodesMap.put(EchUtil.FAKE_NODE_NAME2, EchUtil.FAKE_NODE_NAME2); countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME2); Identifiables.sort(network.getVoltageLevels()).stream().map(VoltageLevel::getId).forEach(vlId -> fakeNodesMap.put(vlId, newEsgId(fakeNodesMap, vlId))); return new EurostagFakeNodes(fakeNodesMap, countUsesMap, network); }
public static void loadFluidDefaults(NBTTagCompound tag) { Set<String> defaults = Sets.newHashSet(); if (tag.func_150297_b("DefaultFluidList",9)) { FMLLog.getLogger().log(Level.DEBUG, "Loading persistent fluid defaults from world"); NBTTagList tl = tag.func_150295_c("DefaultFluidList", 8); for (int i = 0; i < tl.func_74745_c(); i++) { defaults.add(tl.func_150307_f(i)); } } else { FMLLog.getLogger().log(Level.DEBUG, "World is missing persistent fluid defaults - using local defaults"); } loadFluidDefaults(HashBiMap.create(fluidIDs), defaults); }
public static void write(ArticlesIdsRelations articlesIds, String file, String[] header) { List<String[]> entries = new ArrayList<>(); entries.add(header); HashBiMap<String, String> titleIdMap = articlesIds.getTitleIdMap(); for (Map.Entry<String, String> e : titleIdMap.entrySet()) { String id1 = e.getValue(); String id2 = e.getKey(); String[] entry = { id1, id2 }; entries.add(entry); } write(entries, file); }
public Netlist(BDDFactory fac, StateGraph sg, Reset reset) { this.fac = fac; this.reset = reset; this.nameVarMap = new HashMap<>(); this.idVarMap = new HashMap<>(); this.terms = new TreeMap<>(new BDDComparator()); this.unmappedTerms = new HashSet<>(); this.mappedTerms = new HashMap<>(); this.quasiSignals = new HashMap<>(); this.tmpid = 0; this.sigVarMap = HashBiMap.create(); for(Signal sig : sg.getAllSignals()) { sigVarMap.put(sig, getNetlistVariableByName(sig.getName())); } initReset(); }
public static void registerRitual(IRitual ritual, String name) { if(Strings.isNullOrEmpty(name)) { throw new IllegalArgumentException("Attempted to register a ritual with no name: " + ritual); } if(ritual == null) { throw new NullPointerException("The ritual cannot be null"); } ModContainer mod = Loader.instance().activeModContainer(); if(mod == null) { name = "minecraft:" + name; } else { name = mod.getModId() + ":" + name; } HashBiMap<String, IRitualRecipe> recipes = HashBiMap.create(); NAMED_RITUALS.put(name, ritual); RITUALS_RECIPES.put(ritual, recipes); }
public SchemaBranchCache(Integer size, Long expiryInSecs, final SchemaBranchFetcher schemaBranchFetcher) { schemaBranchNameToIdMap = Maps.synchronizedBiMap(HashBiMap.create()); loadingCache = CacheBuilder.newBuilder() .maximumSize(size) .expireAfterAccess(expiryInSecs, TimeUnit.SECONDS) .build(new CacheLoader<Key, SchemaBranch>() { @Override public SchemaBranch load(Key key) throws Exception { SchemaBranch schemaBranch; Key otherKey; if (key.getSchemaBranchKey() != null) { schemaBranch = schemaBranchFetcher.getSchemaBranch(key.getSchemaBranchKey()); otherKey = Key.of(schemaBranch.getId()); schemaBranchNameToIdMap.put(key.getSchemaBranchKey(), schemaBranch.getId()); } else if (key.getId() != null) { schemaBranch = schemaBranchFetcher.getSchemaBranch(key.getId()); otherKey = Key.of(new SchemaBranchKey(schemaBranch.getName(), schemaBranch.getSchemaMetadataName())); schemaBranchNameToIdMap.put(otherKey.schemaBranchKey, schemaBranch.getId()); } else { throw new IllegalArgumentException("Given argument is not valid: " + key); } loadingCache.put(otherKey, schemaBranch); return schemaBranch; } }); }
public ConstructCache.Defrule.ECSetRule build() { if (1 != this.stack.size()) { throw new IllegalStateException("Rule can only be constructed if all existential scopes are closed!"); } final AbstractConditionProxy conditionProxy = this.stack.pop(); final Set<ECFilterSet> condition = conditionProxy.condition; final Set<SingleFactVariable> factVariableSet = conditionProxy.factVariableSet; final Set<RuleCondition.EquivalenceClass> equivalenceClasses = conditionProxy.equivalenceClasses; equivalenceClasses.addAll(this.constantToEquivalenceClass.values()); final Set<RuleCondition.EquivalenceClass> usedECs = ECCollector.collect(condition); if (usedECs.contains(this.initialFactVariable.getEqual())) { factVariableSet.add(this.initialFactVariable); equivalenceClasses.add(this.initialFactVariable.getEqual()); } final ConstructCache.Defrule defrule = new ConstructCache.Defrule(this.ruleName, "", 0, null, ImmutableList.of()); final ConstructCache.Defrule.ECSetRule ecSetRule = defrule.newECSetRule(condition, factVariableSet, equivalenceClasses, HashBiMap.create(0), 0); return ecSetRule; }
private static ImmutableMap<String, Map<CollectionAttribute, String>> generateShortNames( Collection<CollectionAttribute> collections) { // Map[version -> Map[name -> collection]] because collection name must be unique within a // given version, but likely is not unique across versions. Map<String, BiMap<String, CollectionAttribute>> versionMap = new HashMap<>(); for (CollectionAttribute collection : collections) { String version = collection.getVersionWithDefault(); if (!versionMap.containsKey(version)) { versionMap.put(version, HashBiMap.<String, CollectionAttribute>create()); } String baseName = collection.getBaseName(); String shortName = baseName.substring(baseName.lastIndexOf(".") + 1); insertOrDisambiguate(versionMap.get(version), shortName, collection); } ImmutableMap.Builder<String, Map<CollectionAttribute, String>> shortNames = new ImmutableMap.Builder<>(); for (Map.Entry<String, BiMap<String, CollectionAttribute>> entry : versionMap.entrySet()) { shortNames.put(entry.getKey(), entry.getValue().inverse()); } return shortNames.build(); }
public AsyncKeyedOperationImpl(KeyedNamespaceOperation<K> operation, KeyCreator<K> keyCreator, ClientNamespace namespace, long curTime, byte[] originator) { super(operation, namespace.getContext(), curTime, originator); this.keyedNamespaceOperation = (KeyedNamespaceOperation<K>)operation; size = keyedNamespaceOperation.size(); this.keyCreator = keyCreator; //dhtKeyToKey = new Object2ObjectOpenHashMap<>(size); //keyToDHTKey = new Object2ObjectOpenHashMap<>(size); //dhtKeyToKey = new HashMap<>(size); //keyToDHTKey = new HashMap<>(size); if (size != 1) { keyDHTKeyBiMap = HashBiMap.create(size); keyToDHTKey = keyDHTKeyBiMap; dhtKeyToKey = keyDHTKeyBiMap.inverse(); } else { keyDHTKeyBiMap = null; keyToDHTKey = new SingleKeyToDHTKeyMap<>(); dhtKeyToKey = new SingleDHTKeyToKeyMap<>(); } dhtKeys = createKeys(keyCreator); failureCausesRef = new AtomicReference<>(); resultsReceived = new AtomicInteger(); completionCheckLock = new SpinLock(); //completionCheckLock = new ReentrantLock(); }
@Override public Transformation reverse() throws NonReversibleValidationException { if (mode != Mode.MAP_OR_FAIL && mode != Mode.MAP_OR_IGNORE) { throw new NonReversibleValidationException(location, mode + " mode is not reversible"); } BiMap<String, String> mapping; try { mapping = HashBiMap.create(this.mapping); } catch (IllegalArgumentException e) { throw new NonReversibleValidationException(location, "Non-reversible mapping: " + e.getMessage()); } return new TodoReplace(location, glob, todoTags, mode, mapping.inverse(), defaultString, parallelizer); }
public void expandKeys() { keyLen++; Set<String> unusedKeysSet = new TreeSet<>(); generateKeys(keyLen, "", unusedKeysSet); ArrayList<String> newUnusedKeys = new ArrayList<>(unusedKeysSet); BiMap<String, TileInstance> newInstances = HashBiMap.create(); Map<Location, String> newMap = new HashMap<>(); Map<String, String> substitutions = new HashMap<>(); for(Map.Entry<String, TileInstance> instance : instances.entrySet()) { String newKey = newUnusedKeys.get(rand.nextInt(newUnusedKeys.size())); newUnusedKeys.remove(newKey); substitutions.put(instance.getKey(), newKey); newInstances.put(newKey, instance.getValue()); } for(Map.Entry<Location, String> mapInst : map.entrySet()) { newMap.put(mapInst.getKey(), substitutions.get(mapInst.getValue())); } diffStack.push(new DMMDiff.ExpandKeysDiff(this, map, newMap, instances, newInstances, unusedKeys, newUnusedKeys, keyLen-1, keyLen)); instances = newInstances; map = newMap; unusedKeys = newUnusedKeys; }
public void register(ItemType itemType, PluginContainer pluginContainer, Iterable<String> models, String modelDirectoryName) { models.forEach(model -> { BiMap<Integer, Identifier> durabilityToModelId = typeToDurabilityToModelId.computeIfAbsent(itemType, k -> HashBiMap.create()); Identifier modelId = new Identifier(pluginContainer.getId(), model); // Is the model already registered? If so, skip. Integer registeredDurability = durabilityToModelId.inverse().get(modelId); if(registeredDurability == null) { registeredDurability = getAvailableDurability(itemType); } DurabilityIdentifier durabilityId = new DurabilityIdentifier(itemType, registeredDurability); durabilityIdToDirectoryName.put(durabilityId, modelDirectoryName); durabilityIdToModelId.put(durabilityId, modelId); durabilityToModelId.put(registeredDurability, modelId); }); }
/** * Builds something to process a set of sql results and return them as the * same format as a GroupBy query to Druid. * * @param druidQuery The original query that was converted to a sql query. * @param apiToFieldMapper The mapping from api to physical name. * @param objectMapper The mapper for all JSON processing. * @param sqlTimeConverter The time converter used with making the query. */ public SqlResultSetProcessor( DruidAggregationQuery<?> druidQuery, ApiToFieldMapper apiToFieldMapper, ObjectMapper objectMapper, SqlTimeConverter sqlTimeConverter ) { this.druidQuery = druidQuery; this.apiToFieldMapper = apiToFieldMapper; this.objectMapper = objectMapper; this.sqlTimeConverter = sqlTimeConverter; this.sqlResults = new ArrayList<>(); this.columnToColumnName = HashBiMap.create(); this.groupByDimensionsCount = druidQuery.getDimensions().size(); }
private Map<Set<User>, NotificationMessage> createSingleNotifications( SortedSet<MessagePair> messagePairs ) { BiMap<Set<User>, NotificationMessage> singleNotificationCollection = HashBiMap.create(); for ( MessagePair messagePair : messagePairs ) { NotificationMessage notificationMessage = notificationMessageRenderer .render( messagePair.result, messagePair.template ); notificationMessage.setPriority( getPriority( messagePair.result.getValidationRule().getImportance() ) ); singleNotificationCollection.put( new HashSet<>(), notificationMessage ); resolveRecipients( messagePair ) .forEach( user -> singleNotificationCollection.inverse().get( notificationMessage ).add( user ) ); } return singleNotificationCollection; }
private static Map<Set<User>, SortedSet<MessagePair>> groupRecipientsForMessagePairs( Map<User, SortedSet<MessagePair>> messagePairsPerUser ) { BiMap<Set<User>, SortedSet<MessagePair>> grouped = HashBiMap.create(); for ( Map.Entry<User, SortedSet<MessagePair>> entry : messagePairsPerUser.entrySet() ) { User user = entry.getKey(); SortedSet<MessagePair> setOfPairs = entry.getValue(); if ( grouped.containsValue( setOfPairs ) ) { // Value exists -> Add user to the existing key set grouped.inverse().get( setOfPairs ).add( user ); } else { // Value doesn't exist -> Add the [user, set] as a new entry grouped.put( Sets.newHashSet( user ), setOfPairs ); } } return grouped; }
public P1Header() { pinConfiguration = HashBiMap.create(); pinConfiguration.put(3, RaspiPin.GPIO_08); pinConfiguration.put(5, RaspiPin.GPIO_09); pinConfiguration.put(7, RaspiPin.GPIO_07); pinConfiguration.put(8, RaspiPin.GPIO_15); pinConfiguration.put(10, RaspiPin.GPIO_16); pinConfiguration.put(11, RaspiPin.GPIO_00); pinConfiguration.put(12, RaspiPin.GPIO_01); pinConfiguration.put(13, RaspiPin.GPIO_02); pinConfiguration.put(15, RaspiPin.GPIO_03); pinConfiguration.put(16, RaspiPin.GPIO_04); pinConfiguration.put(18, RaspiPin.GPIO_05); pinConfiguration.put(19, RaspiPin.GPIO_12); pinConfiguration.put(21, RaspiPin.GPIO_13); pinConfiguration.put(22, RaspiPin.GPIO_06); pinConfiguration.put(23, RaspiPin.GPIO_14); pinConfiguration.put(24, RaspiPin.GPIO_10); pinConfiguration.put(26, RaspiPin.GPIO_11); }
public StringToIntMapper(Class<S> clazz) { this.clazz = clazz; id2num = new EnumMap<>(clazz); counter = new EnumMap<>(clazz); for (S s : clazz.getEnumConstants()) { id2num.put(s, HashBiMap.<String, Integer>create()); counter.put(s, s.getInitialValue()); } }
public synchronized void reset(S subset) { if (subset == null) { throw new IllegalArgumentException("subset is null"); } id2num.put(subset, HashBiMap.<String, Integer>create()); counter.put(subset, subset.getInitialValue()); }
private TryInfo computeTryInfo() { // Canonical map of handlers. BiMap<CatchHandlers<BasicBlock>, Integer> canonicalHandlers = HashBiMap.create(); // Compute the list of try items and their handlers. List<TryItem> tryItems = computeTryItems(canonicalHandlers); // Compute handler sets before dex items which depend on the handler index. Try[] tries = getDexTryItems(tryItems, canonicalHandlers); TryHandler[] handlers = getDexTryHandlers(canonicalHandlers.inverse()); return new TryInfo(tries, handlers); }
synchronized private void loadFullUserMap() throws IOException { BiMap<Integer, String> uMap = HashBiMap.create(); if (OS.startsWith("Mac")) { updateMapInternal(uMap, "user", MAC_GET_ALL_USERS_CMD, "\\s+", staticMapping.uidMapping); } else { updateMapInternal(uMap, "user", GET_ALL_USERS_CMD, ":", staticMapping.uidMapping); } uidNameMap = uMap; lastUpdateTime = Time.monotonicNow(); }