@Override public Map<MaterialCategory, StatValue<Integer, Double>> calculate() { List<Material> materialList = manager.getMaterials(); Map<MaterialCategory, Integer> map = new HashMap<MaterialCategory, Integer>(); for (MaterialCategory cat : MaterialCategory.values()) { map.put(cat, 0); } for (Material m : materialList) { MaterialCategory category = m.getMaterialType().getCategory(); int number = map.get(category); number++; map.put(category, number); } int sizeStock = materialList.size(); MaterialCategory[] listCategory = MaterialCategory.values(); Map<MaterialCategory, StatValue<Integer, Double>> numberAndPourcent = new HashMap<MaterialCategory, StatValue<Integer, Double>>(); for (MaterialCategory mc : listCategory) { int numberCat = map.get(mc); double pourcent = (numberCat * 1.0) / sizeStock; numberAndPourcent.put(mc, new StatValue<Integer, Double>(numberCat, pourcent)); } return numberAndPourcent; }
/** {@inheritDoc} */ public void putAll(Map<? extends Integer, ? extends Integer> map) { ensureCapacity(map.size()); // could optimize this for cases when map instanceof THashMap for (Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) { this.put(entry.getKey().intValue(), entry.getValue().intValue()); } }
static { Map<Character, AddressField> map = new HashMap<Character, AddressField>(); for (AddressField value : values()) { map.put(value.getChar(), value); } FIELD_MAPPING = Collections.unmodifiableMap(map); }
public DialogPanel(boolean canok, boolean cancancel) { super(new GridBagLayout()); actions = new LinkedHashMap<String, Action>(); keystrokes = new HashMap<KeyStroke, String>(); if (canok) { addButton( "ok", UIManager.getString("OptionPane.okButtonText"), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new AbstractAction() { public void actionPerformed(ActionEvent e) { acceptDialog(); } }); keystrokes.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_MASK), "ok"); } if (cancancel) { addButton( "cancel", UIManager.getString("OptionPane.cancelButtonText"), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction() { public void actionPerformed(ActionEvent e) { cancelDialog(); } }); keystrokes.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, InputEvent.CTRL_MASK), "cancel"); } }
private static void findIndividualPerSequenceCoverage( Calibrator calibrator, Map<String, Integer> sequenceLengths, Map<String, String> readGroupToSampleId, final Map<String, HashMap<String, CalibrationStats>> local, RegionRestriction restriction) { final Covariate rgCovariate = calibrator.getCovariate(calibrator.getCovariateIndex(CovariateEnum.READGROUP)); final Covariate seqCovariate = calibrator.getCovariate(calibrator.getCovariateIndex(CovariateEnum.SEQUENCE)); for (final Map.Entry<String, Integer> entry : sequenceLengths.entrySet()) { final String sequenceName = entry.getKey(); if (restriction != null && !sequenceName.equals(restriction.getSequenceName())) { continue; } for (final Map.Entry<String, String> e2 : readGroupToSampleId.entrySet()) { final String readGroup = e2.getKey(); final String sampleName = e2.getValue(); final int rgValue = rgCovariate.valueOf(readGroup); final int seqValue = seqCovariate.valueOf(sequenceName); if (rgValue == -1 || seqValue == -1) { add(local, sampleName, sequenceName, new CalibrationStats(null)); } else { final Calibrator.QuerySpec spec = calibrator.initQuery(); spec.setValue(CovariateEnum.READGROUP, rgValue); spec.setValue(CovariateEnum.SEQUENCE, seqValue); calibrator.processStats(new LocalStatsProcessor(local, sampleName, sequenceName), spec); } } } }
/** * Tests that an exception is thrown when the {@link Constants#USER_FILE_BUFFER_BYTES} overflows. */ @Test public void variableUserFileBufferBytesOverFlowCheckTest1() { Map<String, String> properties = new LinkedHashMap<String, String>(); properties.put(Constants.USER_FILE_BUFFER_BYTES, String.valueOf(Integer.MAX_VALUE + 1) + "B"); mThrown.expect(IllegalArgumentException.class); new Configuration(properties); }
private void load(String normalizedFilePath, String filePath) { max_weight = -1; BufferedReader br; try { if (normalize) { br = new BufferedReader(new FileReader(normalizedFilePath)); } else { br = new BufferedReader(new FileReader(filePath)); } cTran2wt.clear(); String line = ""; while ((line = br.readLine()) != null) { String[] tokens = line.split("\t"); // if (tokens[0].equals(tokens[1])) { // continue; // } if (max_weight < Double.valueOf(tokens[2])) { max_weight = Double.valueOf(tokens[2]); } Transition t = new Transition(tokens[0], tokens[1]); cTran2wt.put(t, Double.valueOf(tokens[2])); } br.close(); logger.debug("size(): " + cTran2wt.size()); logger.debug("max_weight: " + max_weight); } catch (IOException e) { logger.error("not happened", e); } }
@Test public void testChildrenRIMsDifferentEntity() { ResourceState initial = new ResourceState("Note", "initial", mockActions(), "/note/{id}"); ResourceState comment = new ResourceState("Comment", "draft", mockActions(), "/comments/{noteid}"); // example uri linkage uses 'id' from Note entity to transition to 'noteid' of comments resource Map<String, String> uriLinkageMap = new HashMap<String, String>(); uriLinkageMap.put("noteid", "id"); // create comment for note initial.addTransition( new Transition.Builder() .method("PUT") .target(comment) .uriParameters(uriLinkageMap) .build()); // update comment comment.addTransition(new Transition.Builder().method("PUT").target(comment).build()); // supply a transformer to check that this is copied into child resource BeanTransformer transformer = new BeanTransformer(); ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer); HTTPHypermediaRIM parent = new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata()); Collection<ResourceInteractionModel> resources = parent.getChildren(); assertEquals(1, resources.size()); assertEquals(comment.getPath(), resources.iterator().next().getResourcePath()); assertEquals( transformer, ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer()); }
public synchronized void start() throws Exception { if (started) { return; } for (BroadcastGroup group : broadcastGroups.values()) { if (!backup) { group.start(); } } for (ClusterConnection conn : clusterConnections.values()) { conn.start(); if (backup && configuration.isSharedStore()) { conn.informTopology(); conn.announceBackup(); } } for (BridgeConfiguration config : configuration.getBridgeConfigurations()) { deployBridge(config, !backup); } started = true; }
/** * Set the id associated with each quadrant. The quadrants are laid out: TopLeft, TopRight, Bottom * Left, Bottom Right * * @param keys */ public void setDivisionIds(List<Object> keys) { if (keys.size() > MAX_DIVISIONS) { throw new IllegalArgumentException("too many divisionIds: " + keys); } boolean needClear = getDivisionCount() != keys.size(); if (!needClear) { for (int i = 0; i < keys.size(); i++) { String divisionId = transformKeyToDivisionId(keys.get(i)); // different item or different place if (!mDivisionMap.containsKey(divisionId) || mDivisionMap.get(divisionId) != i) { needClear = true; break; } } } if (needClear) { mDivisionMap.clear(); mDivisionImages.clear(); int i = 0; for (Object key : keys) { String divisionId = transformKeyToDivisionId(key); mDivisionMap.put(divisionId, i); mDivisionImages.add(null); i++; } } }
private Map<String, String> getTypes() { Map<String, String> statuses = new LinkedHashMap<String, String>(); statuses.put(String.valueOf(SubscribeActor.TYPE_ACTIVE), getText("subscribePersonal.active")); statuses.put(String.valueOf(SubscribeActor.TYPE_PASSIVE), getText("subscribePersonal.passive")); statuses.put("", getText("bc.status.all")); return statuses; }
public void setStaticUserProperties(final Map<String, String> staticUserPropertiesMap) { // trim map staticUserProperties = new HashMap<String, String>(); for (final Entry<String, String> entry : staticUserPropertiesMap.entrySet()) { staticUserProperties.put(entry.getKey().trim(), entry.getValue().trim()); } }
public void setReqAttrs(final Map<String, String> reqAttrs) { // trim map reqAttr = new HashMap<String, String>(); for (final Entry<String, String> entry : reqAttrs.entrySet()) { reqAttr.put(entry.getKey().trim(), entry.getValue().trim()); } }
/** * Checks if defined OLAT Properties in olatextconfig.xml exist in OLAT. Configuration: LDAP * Attributes Map = olatextconfig.xml (property=reqAttrs, property=userAttributeMapper) * * @param attrs Map of OLAT Properties from of the LDAP configuration * @return true All exist OK, false Error */ private boolean checkIfOlatPropertiesExists(final Map<String, String> attrs) { final List<UserPropertyHandler> upHandler = userService.getAllUserPropertyHandlers(); for (final String ldapAttribute : attrs.keySet()) { boolean propertyExists = false; final String olatProperty = attrs.get(ldapAttribute); if (olatProperty.equals(LDAPConstants.LDAP_USER_IDENTIFYER)) { // LDAP user identifyer is not a user propery, it's the username continue; } for (final UserPropertyHandler userPropItr : upHandler) { if (olatProperty.equals(userPropItr.getName())) { // ok, this property exist, continue with next one propertyExists = true; break; } } if (!propertyExists) { log.error( "Error in checkIfOlatPropertiesExists(): configured LDAP attribute::" + ldapAttribute + " configured to map to OLAT user property::" + olatProperty + " but no such user property configured in olat_userconfig.xml"); return false; } } return true; }
@Override public void configure() { try { setName("AppWithStreamSizeSchedule"); setDescription("Sample application"); ObjectStores.createObjectStore(getConfigurer(), "input", String.class); ObjectStores.createObjectStore(getConfigurer(), "output", String.class); addWorkflow(new SampleWorkflow()); addStream(new Stream("stream")); Map<String, String> scheduleProperties = Maps.newHashMap(); scheduleProperties.put("oneKey", "oneValue"); scheduleProperties.put("anotherKey", "anotherValue"); scheduleProperties.put("someKey", "someValue"); scheduleWorkflow( Schedules.createDataSchedule("SampleSchedule1", "", Schedules.Source.STREAM, "stream", 1), "SampleWorkflow", scheduleProperties); scheduleWorkflow( Schedules.createDataSchedule("SampleSchedule2", "", Schedules.Source.STREAM, "stream", 2), "SampleWorkflow", scheduleProperties); } catch (UnsupportedTypeException e) { throw Throwables.propagate(e); } }
/** * Inserts the given <code>command</command> at the end of the <code>popupMenu</code>. * * @param popupMenu The popup menu to add the given <code>command</code> to. * @param command The command to insert. * @param manager The command manager. */ public static void insertCommandMenuItem( final JPopupMenu popupMenu, final Command command, final CommandManager manager) { Command[] commands = getCommands(popupMenu, manager, command); commands = sort(commands); final Map<String, Component> popupMenues = new HashMap<String, Component>(); int count = popupMenu.getComponentCount(); for (int i = 0; i < count; i++) { final Component component = popupMenu.getComponent(i); if (component instanceof JMenu) { popupMenues.put(component.getName(), component); } } popupMenu.removeAll(); for (Command command1 : commands) { insertCommandMenuItem(popupMenu, command1, popupMenu.getComponentCount()); } count = popupMenu.getComponentCount(); for (int i = 0; i < count; i++) { final Component component = popupMenu.getComponent(i); if (component instanceof JMenu) { final String name = component.getName(); final Object o = popupMenues.get(name); if (o != null) { popupMenu.remove(i); popupMenu.insert((Component) o, i); } } } }
private Map<Object, Object> createBooleanOptions() { Map<Object, Object> expectedOptions = new LinkedHashMap<Object, Object>(); expectedOptions.put("", "Please select"); expectedOptions.put(Boolean.TRUE, "Yes"); expectedOptions.put(Boolean.FALSE, "No"); return expectedOptions; }
// backup node becomes live public synchronized void activate() { if (backup) { backup = false; for (BroadcastGroup broadcastGroup : broadcastGroups.values()) { try { broadcastGroup.start(); broadcastGroup.activate(); } catch (Exception e) { log.warn("unable to start broadcast group " + broadcastGroup.getName(), e); } } for (ClusterConnection clusterConnection : clusterConnections.values()) { try { clusterConnection.activate(); } catch (Exception e) { log.warn("unable to start cluster connection " + clusterConnection.getName(), e); } } for (Bridge bridge : bridges.values()) { try { bridge.start(); } catch (Exception e) { log.warn("unable to start bridge " + bridge.getName(), e); } } } }
static synchronized Random getRandom(String algorithm, Double seed) throws ExpressionException { algorithm = algorithm.toLowerCase(); Random result = randoms.get(algorithm); if (result == null || !seed.isNaN()) { if (CFMXCompat.ALGORITHM_NAME.equalsIgnoreCase(algorithm)) { result = new Random(); } else { try { result = SecureRandom.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new ExpressionException( "random algorithm [" + algorithm + "] is not installed on the system", e.getMessage()); } } if (!seed.isNaN()) result.setSeed(seed.longValue()); randoms.put(algorithm, result); } return result; }
@Override public void mergeLabels(Map<String, String> srcMap, Map<String, String> destMap) { if (srcMap == null || destMap == null) { return; } for (Map.Entry<String, String> entry : srcMap.entrySet()) { String key = entry.getKey(); if (key.toLowerCase().startsWith("io.rancher")) { key = key.toLowerCase(); } String value = entry.getValue(); if (key.startsWith("io.rancher.scheduler.affinity")) { // merge labels String destValue = destMap.get(key); if (StringUtils.isEmpty(destValue)) { destMap.put(key, value); } else if (StringUtils.isEmpty(value)) { continue; } else if (!destValue.toLowerCase().contains(value.toLowerCase())) { destMap.put(key, destValue + "," + value); } } else { // overwrite label value destMap.put(key, value); } } }
/** Constructor */ Attachment(InputStream contentStream, String contentType) { this.body = contentStream; metadata = new HashMap<String, Object>(); metadata.put("content_type", contentType); metadata.put("follows", true); this.gzipped = false; }
@SuppressLint("DefaultLocale") @Override protected FilterResults performFiltering(CharSequence constraint) { constraint = constraint.toString().toLowerCase(); FilterResults results = new FilterResults(); if (constraint.length() == 0) { results.values = oriItemList; results.count = oriItemList.size(); } else { List<Map<String, Object>> filteredList = new ArrayList<Map<String, Object>>(); for (Map<String, Object> app : oriItemList) { String title = ((String) app.get("title")).toLowerCase(); if (title.indexOf((String) constraint) == 0) { filteredList.add(app); } } results.values = filteredList; results.count = filteredList.size(); } return results; }
public void showVoronoi() { voronoi = new Voronoi(); for (String btsID : BTS2Location.keySet()) { Location location = BTS2Location.get(btsID); float xy[] = this.map.getScreenPositionFromLocation(location); if (xy[0] > width * 2 || xy[0] < -(width * 2) || xy[1] > height * 2 || xy[1] < -(height * 2)) { // avoid errors in toxiclib continue; } try { voronoi.addPoint(new Vec2D(xy[0], xy[1])); } catch (Exception e) { logger.debug(e); } } noFill(); stroke(0xFF40a6dd); strokeWeight(1); for (Polygon2D polygon : voronoi.getRegions()) { gfx.polygon2D(polygon); } fill(255, 0, 255); noStroke(); for (Vec2D c : voronoi.getSites()) { ellipse(c.x, c.y, 5, 5); } }
protected Map getChannelMap(ConsoleInput ci) { Map channel_map = new HashMap(); PluginInterface[] pis = ci.azureus_core.getPluginManager().getPluginInterfaces(); for (int i = 0; i < pis.length; i++) { LoggerChannel[] logs = pis[i].getLogger().getChannels(); if (logs.length > 0) { if (logs.length == 1) { channel_map.put(pis[i].getPluginName(), logs[0]); } else { for (int j = 0; j < logs.length; j++) { channel_map.put(pis[i].getPluginName() + "." + logs[j].getName(), logs[j]); } } } } return (channel_map); }
protected boolean receiveBeacon(InetAddress sender, byte[] buffer, int length) { if (is_enabled) { try { Map<String, String> map = decodeBeacon(buffer, length); String id = map.get("identity"); if (id == null || id.equals(uid)) { return (false); } String platform = map.get("platform"); if (platform != null && platform.toLowerCase().startsWith("tcd/")) { String classification = "tivo." + platform.substring(4).toLowerCase(); foundTiVo(sender, id, classification, (String) map.get("machine")); return (true); } } catch (Throwable e) { log("Failed to decode beacon", e); } } return (false); }
/** * Check that EquipmentSetFacadeImpl when initialised with a dataset containing equipment hides * and shows the correct weapon slots. */ public void testSlotManagementOnInitWithEquipment() { PlayerCharacter pc = getCharacter(); EquipSet es = new EquipSet("0.1", "Unit Test Equip"); Equipment weapon = new Equipment(); weapon.setName("Morningstar"); addEquipToEquipSet(pc, es, weapon, 1.0f, LOC_PRIMARY); EquipmentSetFacadeImpl esfi = new EquipmentSetFacadeImpl(uiDelegate, pc, es, dataset); ListFacade<EquipNode> nodes = esfi.getNodes(); Map<String, EquipNode> nodeMap = new HashMap<String, EquipNode>(); for (EquipNode equipNode : nodes) { nodeMap.put(equipNode.toString(), equipNode); } EquipNode testNode = nodeMap.get("Morningstar"); assertNotNull("Morningstar should be present", testNode); assertEquals("Morningstar type", EquipNode.NodeType.EQUIPMENT, testNode.getNodeType()); assertEquals("Morningstar location", LOC_PRIMARY, esfi.getLocation(testNode)); // Test for removed slots String removedSlots[] = new String[] {"Primary Hand", "Double Weapon", "Both Hands"}; for (String slotName : removedSlots) { testNode = nodeMap.get(slotName); assertNull(slotName + " should not be present", testNode); } // Test for still present slots String retainedSlots[] = new String[] {"Secondary Hand", "Ring"}; for (String slotName : retainedSlots) { testNode = nodeMap.get(slotName); assertNotNull(slotName + " should be present", testNode); } }
/** * Gets the SWT resource elements. * * @param resourceComposites The resources in composite data array * @return The SWT resource elements */ private Collection<ISWTResourceElement> getSWTResourceElements( CompositeData[] resourceComposites) { Map<String, ISWTResourceElement> newResourceElements = new HashMap<String, ISWTResourceElement>(); for (CompositeData compositeData : resourceComposites) { Object name = compositeData.get(NAME); if (!(name instanceof String)) { continue; } ISWTResourceElement element = resourceElements.get(name); if (element == null) { Object stackTraceElements = compositeData.get(STACK_TRACE); if (!(stackTraceElements instanceof CompositeData[])) { continue; } element = new SWTResourceElement( (String) name, getStackTrace((CompositeData[]) stackTraceElements)); } newResourceElements.put((String) name, element); } resourceElements = newResourceElements; return resourceElements.values(); }
private static void appendSorted( final List<Command> commandsList, final CommandWrapper wrapper, final Map<String, CommandWrapper> wrappers) { if (!wrapper.afterWrappers.isEmpty()) { final List<CommandWrapper> afterWrappersList = wrapper.afterWrappers; final CommandWrapper[] afterWrappers = afterWrappersList.toArray(new CommandWrapper[afterWrappersList.size()]); for (CommandWrapper afterWrapper : afterWrappers) { for (int j = 0; j < afterWrapper.afterWrappers.size(); j++) { CommandWrapper ownAfterWrapper = afterWrapper.afterWrappers.get(j); if (afterWrappersList.contains(ownAfterWrapper)) { afterWrappersList.remove(afterWrapper); final int insertIndex = afterWrappersList.indexOf(ownAfterWrapper); afterWrappersList.add(insertIndex, afterWrapper); } } } for (CommandWrapper anAfterWrapper : afterWrappersList) { final CommandWrapper cwFromMap = wrappers.get(anAfterWrapper.getName()); if (cwFromMap != null) { commandsList.add(cwFromMap.command); wrappers.remove(cwFromMap.getName()); } } for (CommandWrapper anAfterWrapper : afterWrappersList) { appendSorted(commandsList, anAfterWrapper, wrappers); } } }
private List<BroadcastMetadata> getBroadcastMetadata( List<String> fileObjectPids, InfrastructureContext context, TranscodeRequest request) throws ProcessorException { Map<String, BroadcastMetadata> pidMap = new HashMap<String, BroadcastMetadata>(); CentralWebservice doms = CentralWebserviceFactory.getServiceInstance(context); List<BroadcastMetadata> broadcastMetadataList = new ArrayList<BroadcastMetadata>(); for (String fileObjectPid : fileObjectPids) { BroadcastMetadata broadcastMetadata = null; try { String broadcastMetadataXml = doms.getDatastreamContents(fileObjectPid, "BROADCAST_METADATA"); logger.debug("Found file metadata '" + fileObjectPid + "' :\n" + broadcastMetadataXml); broadcastMetadata = JAXBContext.newInstance(BroadcastMetadata.class) .createUnmarshaller() .unmarshal( new StreamSource(new StringReader(broadcastMetadataXml)), BroadcastMetadata.class) .getValue(); } catch (Exception e) { throw new ProcessorException( "Failed to get Broadcast Metadata for " + request.getObjectPid(), e); } broadcastMetadataList.add(broadcastMetadata); pidMap.put(fileObjectPid, broadcastMetadata); } request.setPidMap(pidMap); return broadcastMetadataList; }
public Object toJSonObject() { Map map = CommUtil.obj2mapExcept(this, new String[] {"orderInfo", "product"}); if (product != null) { map.put("product", product.toJSonObject()); } return map; }