/** * This function is used to re-run the analyser, and re-create the rows corresponding the its * results. */ private void refreshReviewTable() { reviewPanel.removeAll(); rows.clear(); GridBagLayout gbl = new GridBagLayout(); reviewPanel.setLayout(gbl); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 0; try { Map<String, Long> sums = analyser.processLogFile(config.getLogFilename(), fromDate.getDate(), toDate.getDate()); for (Entry<String, Long> entry : sums.entrySet()) { String project = entry.getKey(); double hours = 1.0 * entry.getValue() / (1000 * 3600); addRow(gbl, gbc, project, hours); } for (String project : main.getProjectsTree().getTopLevelProjects()) if (!rows.containsKey(project)) addRow(gbl, gbc, project, 0); gbc.insets = new Insets(10, 0, 0, 0); addLeftLabel(gbl, gbc, "TOTAL"); gbc.gridx = 1; gbc.weightx = 1; totalLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 3)); gbl.setConstraints(totalLabel, gbc); reviewPanel.add(totalLabel); gbc.weightx = 0; addRightLabel(gbl, gbc); } catch (IOException e) { e.printStackTrace(); } recomputeTotal(); pack(); }
/** {@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()); } }
public CloudScriptObject eval(Context context) throws CloudScriptException { CloudScriptClass clazz = context.getCurrentClass(); for (Map.Entry<String, String> entry : data.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (!clazz.hasMethod(key)) { clazz.addMethod( key, new Method() { public CloudScriptObject call( CloudScriptObject receiver, CloudScriptObject arguments[]) throws CloudScriptException { ValueObject content = new ValueObject(value); int numValue; try { numValue = Integer.parseInt(value); content = new ValueObject(numValue); } catch (NumberFormatException e) { } return content; } }); } } return new ValueObject(this.content); }
private List<String> getCurrentServerIds(boolean nag, boolean lagged) { try (Jedis jedis = pool.getResource()) { long time = getRedisTime(jedis.time()); int nagTime = 0; if (nag) { nagTime = nagAboutServers.decrementAndGet(); if (nagTime <= 0) { nagAboutServers.set(10); } } ImmutableList.Builder<String> servers = ImmutableList.builder(); Map<String, String> heartbeats = jedis.hgetAll("heartbeats"); for (Map.Entry<String, String> entry : heartbeats.entrySet()) { try { long stamp = Long.parseLong(entry.getValue()); if (lagged ? time >= stamp + 30 : time <= stamp + 30) servers.add(entry.getKey()); else if (nag && nagTime <= 0) { getLogger() .severe( entry.getKey() + " is " + (time - stamp) + " seconds behind! (Time not synchronized or server down?)"); } } catch (NumberFormatException ignored) { } } return servers.build(); } catch (JedisConnectionException e) { getLogger().log(Level.SEVERE, "Unable to fetch server IDs", e); return Collections.singletonList(configuration.getServerId()); } }
public static HttpRequestBase buildHeaders( HttpRequestBase httpRequestBase, Map<String, String> headers) { for (Entry<String, String> header : headers.entrySet()) { httpRequestBase.setHeader(header.getKey(), header.getValue()); } return httpRequestBase; }
public static void testDetermineMergeParticipantsAndMergeCoords4() { Address a = Util.createRandomAddress(), b = Util.createRandomAddress(), c = Util.createRandomAddress(), d = Util.createRandomAddress(); org.jgroups.util.UUID.add(a, "A"); org.jgroups.util.UUID.add(b, "B"); org.jgroups.util.UUID.add(c, "C"); org.jgroups.util.UUID.add(d, "D"); View v1 = View.create(a, 1, a, b); View v2 = View.create(c, 1, c, d); Map<Address, View> map = new HashMap<>(); map.put(a, v1); map.put(b, v1); map.put(d, v2); StringBuilder sb = new StringBuilder("map:\n"); for (Map.Entry<Address, View> entry : map.entrySet()) sb.append(entry.getKey() + ": " + entry.getValue() + "\n"); System.out.println(sb); Collection<Address> merge_participants = Util.determineMergeParticipants(map); System.out.println("merge_participants = " + merge_participants); assert merge_participants.size() == 3; assert merge_participants.contains(a) && merge_participants.contains(c) && merge_participants.contains(d); Collection<Address> merge_coords = Util.determineMergeCoords(map); System.out.println("merge_coords = " + merge_coords); assert merge_coords.size() == 2; assert merge_coords.contains(a) && merge_coords.contains(c); }
public void changeClassLabels() { System.out.println("Reading cluster file: " + cluserInputFile); Clusters clusters = loadClusters(cluserInputFile); if (clusters == null) { System.out.println("Not clusters found to change"); return; } Map<Integer, String> classToSector = new HashMap<Integer, String>(); for (Map.Entry<String, Integer> e : sectorToClazz.entrySet()) { classToSector.put(e.getValue(), e.getKey()); } for (Cluster c : clusters.getCluster()) { // find the cluster label // this is the label String key = classToSector.get(c.getKey()); if (key != null) { System.out.println("Setting label: " + key + " to cluster: " + c.getKey()); c.setLabel(key); } } try { System.out.println("Writing cluster file: " + clusterOutputFile); saveClusters(clusterOutputFile, clusters); } catch (FileNotFoundException | JAXBException e) { throw new RuntimeException("Failed to write clusters", e); } }
/** @return mapping from pack to row position */ public Map<Pack, Integer> getPacksToRowNumbers() { Map<Pack, Integer> packsToRowNumbers = new HashMap<Pack, Integer>(); for (Map.Entry<String, Integer> entry : nameToRow.entrySet()) { packsToRowNumbers.put(nameToPack.get(entry.getKey()), entry.getValue()); } return packsToRowNumbers; }
public void writeFoundWordsFile() throws IOException { PrintWriter pw = new PrintWriter(new FileWriter("src\\LW_5\\output2.txt")); for (Map.Entry entry : wordsNumStr.entrySet()) { pw.println("Word : " + entry.getKey() + ", String number : " + entry.getValue()); } pw.close(); }
/** * create the info string; assumes that no values are null * * @param infoFields a map of info fields * @throws IOException for writer */ private void writeInfoString(Map<String, String> infoFields) throws IOException { if (infoFields.isEmpty()) { mWriter.write(VCFConstants.EMPTY_INFO_FIELD); return; } boolean isFirst = true; for (Map.Entry<String, String> entry : infoFields.entrySet()) { if (isFirst) isFirst = false; else mWriter.write(VCFConstants.INFO_FIELD_SEPARATOR); String key = entry.getKey(); mWriter.write(key); if (!entry.getValue().equals("")) { VCFInfoHeaderLine metaData = mHeader.getInfoHeaderLine(key); if (metaData == null || metaData.getCountType() != VCFHeaderLineCount.INTEGER || metaData.getCount() != 0) { mWriter.write("="); mWriter.write(entry.getValue()); } } } }
/** * TODO: this method should be removed when find by xpath is ready, and currently works fine only * with one attribute * * @return */ @NotNull public static List<XmlTag> findTagInFile( @NotNull XmlFile xmlFile, @NotNull String nodeName, Map<String, String> attributes) { List<XmlTag> xmlTags = new ArrayList<XmlTag>(); // XmlTag rootTag = xmlFile.getRootTag(); // xmlFile.getDocument().getManager(); String xmlText = xmlFile.getText(); // final XPathSupport support = XPathSupport.getInstance(); String regex = "<" + nodeName + "[\\s>]+.*?"; if (attributes != null) { for (Map.Entry<String, String> entry : attributes.entrySet()) { String attrName = entry.getKey(); String attrValue = entry.getValue(); regex += attrName + "\\s*" + "=\\s*\"" + attrValue + "\"\\s*"; } } Pattern p = Pattern.compile(regex); Matcher m = p.matcher(xmlText); List<Integer> positions = new ArrayList<Integer>(); while (m.find()) { positions.add(m.start()); } for (Integer position : positions) { PsiElement psiElement = xmlFile.findElementAt(position); XmlTag xmlTag = XmlHelper.getParentOfType(psiElement, XmlTag.class, false); if (xmlTag != null) { xmlTags.add(xmlTag); } } return xmlTags; }
private void exportParameters() { synchronized (exported_parameters) { if (!exported_parameters_dirty) { return; } exported_parameters_dirty = false; try { TreeMap<String, String> tm = new TreeMap<String, String>(); Set<String> exported_keys = new HashSet<String>(); for (String[] entry : exported_parameters.values()) { String key = entry[0]; String value = entry[1]; exported_keys.add(key); if (value != null) { tm.put(key, value); } } for (Map.Entry<String, String> entry : imported_parameters.entrySet()) { String key = entry.getKey(); if (!exported_keys.contains(key)) { tm.put(key, entry.getValue()); } } File parent_dir = new File(SystemProperties.getUserPath()); File props = new File(parent_dir, "exported_params.properties"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(props), "UTF-8")); try { for (Map.Entry<String, String> entry : tm.entrySet()) { pw.println(entry.getKey() + "=" + entry.getValue()); } } finally { pw.close(); } } catch (Throwable e) { e.printStackTrace(); } } }
private void exportAttributes(Map<String, Object> attrMap) { for (Map.Entry<String, Object> e : attrMap.entrySet()) { if (e.getKey().equals(WikiPage.CHANGENOTE)) exportProperty("wiki:changeNote", (String) e.getValue(), STRING); else exportProperty(e.getKey(), e.getValue().toString(), STRING); } }
/** * The basic method for splitting off a clause of a tree. This modifies the tree in place. This * method addtionally follows ref edges. * * @param tree The tree to split a clause from. * @param toKeep The edge representing the clause to keep. */ @SuppressWarnings("unchecked") private void simpleClause(SemanticGraph tree, SemanticGraphEdge toKeep) { splitToChildOfEdge(tree, toKeep); // Follow 'ref' edges Map<IndexedWord, IndexedWord> refReplaceMap = new HashMap<>(); // (find replacements) for (IndexedWord vertex : tree.vertexSet()) { for (SemanticGraphEdge edge : extraEdgesByDependent.get(vertex)) { if ("ref".equals(edge.getRelation().toString()) && // it's a ref edge... !tree.containsVertex( edge.getGovernor())) { // ...that doesn't already exist in the tree. refReplaceMap.put(vertex, edge.getGovernor()); } } } // (do replacements) for (Map.Entry<IndexedWord, IndexedWord> entry : refReplaceMap.entrySet()) { Iterator<SemanticGraphEdge> iter = tree.incomingEdgeIterator(entry.getKey()); if (!iter.hasNext()) { continue; } SemanticGraphEdge incomingEdge = iter.next(); IndexedWord governor = incomingEdge.getGovernor(); tree.removeVertex(entry.getKey()); addSubtree( tree, governor, incomingEdge.getRelation().toString(), this.tree, entry.getValue(), this.tree.incomingEdgeList(tree.getFirstRoot())); } }
/** * Answer the {@linkplain ModuleRoot module roots} in the order that they are specified in the * Avail {@linkplain ModuleDescriptor module} path. * * @return The module roots. */ public Set<ModuleRoot> roots() { final Set<ModuleRoot> roots = new LinkedHashSet<>(); for (final Map.Entry<String, ModuleRoot> entry : rootMap.entrySet()) { roots.add(entry.getValue()); } return roots; }
/** {@inheritDoc} */ @Override public boolean apply(@Nullable T1 t1, @Nullable T2 t2) { lazyCompile(); if (expr != null) { JexlContext ctx = new MapContext(); ctx.set(var1, t1); ctx.set(var2, t2); for (Map.Entry<String, Object> e : map.entrySet()) { ctx.set(e.getKey(), e.getValue()); } try { Object obj = expr.evaluate(ctx); if (obj instanceof Boolean) { return (Boolean) obj; } } catch (Exception ex) { throw F.wrap(ex); } } return false; }
public static <K, V extends Comparable<? super V>> Map<K, V> getSortedMap(Map<K, V> rankTerm) { System.out.println("Started Sorting..." + "@ " + new Date()); List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(rankTerm.entrySet()); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { // return (o1.getValue()).compareTo(o2.getValue()); return Double.parseDouble(o1.getValue().toString()) > Double.parseDouble(o2.getValue().toString()) ? -1 : Double.parseDouble(o1.getValue().toString()) == Double.parseDouble(o2.getValue().toString()) ? 0 : 1; } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } System.out.println("Stopped Sorting..." + "@ " + new Date()); return result; }
private void deploy() { List startList = new ArrayList(); Iterator iter = dirMap.entrySet().iterator(); try { while (iter.hasNext() && !shutdown) { Map.Entry entry = (Map.Entry) iter.next(); File f = (File) entry.getKey(); QEntry qentry = (QEntry) entry.getValue(); long deployed = qentry.getDeployed(); if (deployed == 0) { if (deploy(f)) { if (qentry.isQBean()) startList.add(qentry.getInstance()); qentry.setDeployed(f.lastModified()); } else { // deploy failed, clean up. iter.remove(); } } else if (deployed != f.lastModified()) { undeploy(f); iter.remove(); loader.forceNewClassLoaderOnNextScan(); } } iter = startList.iterator(); while (iter.hasNext()) { start((ObjectInstance) iter.next()); } } catch (Exception e) { log.error("deploy", e); } }
/** * Select/Deselect pack(s) based on packsData mapping. This is related to the onSelect and * onDeselect attributes for packs. User is not allowed to has a required pack for onSelect and * onDeselect. * * @param packsData */ private void selectionUpdate(Map<String, String> packsData) { RulesEngine rules = installData.getRules(); for (Map.Entry<String, String> packData : packsData.entrySet()) { int value, packPos; String packName = packData.getKey(); String condition = packData.getValue(); if (condition != null && !rules.isConditionTrue(condition)) { return; // Do nothing if condition is false } Pack pack; if (packName.startsWith("!")) { packName = packName.substring(1); pack = nameToPack.get(packName); packPos = getPos(packName); value = DESELECTED; } else { pack = nameToPack.get(packName); packPos = getPos(packName); value = SELECTED; } if (!pack.isRequired() && dependenciesResolved(pack)) { checkValues[packPos] = value; } } }
/** * Send Conference POST request to API endpoint which is used for allocating new conferences in * reservation system. * * @param ownerEmail email of new conference owner * @param mucRoomName full name of MUC room that is hosting the conference. * {room_name}@{muc.server.net} * @return <tt>ApiResult</tt> that contains system response. It will contain <tt>Conference</tt> * instance filled with data from the reservation system if everything goes OK. * @throws FaultTolerantRESTRequest.RetryExhaustedException When the number of retries to submit * the request for the conference data is reached * @throws UnsupportedEncodingException When the room data have the encoding that does not play * with UTF8 standard */ public ApiResult createNewConference(String ownerEmail, String mucRoomName) throws FaultTolerantRESTRequest.RetryExhaustedException, UnsupportedEncodingException { Conference conference = new Conference(mucRoomName, ownerEmail, new Date()); HttpPost post = new HttpPost(baseUrl + "/conference"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); Map<String, Object> jsonMap = conference.createJSonMap(); for (Map.Entry<String, Object> entry : jsonMap.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF8")); logger.info("Sending post: " + jsonMap); CreateConferenceResponseParser conferenceResponseParser = new CreateConferenceResponseParser(conference); FaultTolerantRESTRequest faultTolerantRESTRequest = new FaultTolerantRESTRequest(post, conferenceResponseParser, retriesCreate, httpClient); return faultTolerantRESTRequest.submit(); }
/* * Termina a realização da Tarefa. * Retorna true se foi terminada com sucesso false caso contrário */ public boolean endTask(String id) throws InterruptedException { Map<String, Integer> objectsToSupply; String type; lock.lock(); try { if (!this.tasksRunning.containsKey(Integer.valueOf(id))) { return false; } else { type = this.tasksRunning.get(Integer.valueOf(id)); objectsToSupply = this.tasks.get(type).getObjects(); } } finally { lock.unlock(); } // Supply de todos os objetos for (Map.Entry<String, Integer> entry : objectsToSupply.entrySet()) { warehouse.supply(entry.getKey(), entry.getValue()); } lock.lock(); try { this.tasksRunning.remove(Integer.valueOf(id)); this.tasks.get(type).signalP(); } finally { lock.unlock(); } return true; }
private static InputStream generateSoundsJSON() throws IOException { OpenSecurity.logger.info( Minecraft.getMinecraft().mcDataDir + "\\mods\\OpenSecurity\\sounds\\alarms\\"); JsonObject root = new JsonObject(); for (Map.Entry<String, String> entry : sound_map.entrySet()) { JsonObject event = new JsonObject(); event.addProperty("category", "master"); // put under the "record" category for sound options JsonArray sounds = new JsonArray(); // array of sounds (will only ever be one) JsonObject sound = new JsonObject(); // sound object (instead of primitive to use 'stream' flag) sound.addProperty( "name", new File(".") + "\\mods\\OpenSecurity\\sounds\\alarms\\" + entry.getValue().substring(0, entry.getValue().lastIndexOf('.'))); // path to file sound.addProperty("stream", false); // prevents lag for large files sounds.add(sound); event.add("sounds", sounds); root.add( entry.getValue().substring(0, entry.getValue().lastIndexOf('.')), event); // event name (same as name sent to ItemCustomRecord) } // System.out.println(new Gson().toJson(root)); return new ByteArrayInputStream(new Gson().toJson(root).getBytes()); }
/** * Prints the given map with nice line breaks. * * @param out the stream to print to * @param key the key that maps to the map in some other map * @param map the map to print */ public static synchronized void debugPrint(PrintStream out, Object key, Map map) { debugPrintIndent(out); out.println(key + " = "); debugPrintIndent(out); out.println("{"); ++debugIndent; for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String childKey = (String) entry.getKey(); Object childValue = entry.getValue(); if (childValue instanceof Map) { verbosePrint(out, childKey, (Map) childValue); } else { debugPrintIndent(out); String typeName = (childValue != null) ? childValue.getClass().getName() : null; out.println(childKey + " = " + childValue + " class: " + typeName); } } --debugIndent; debugPrintIndent(out); out.println("}"); }
static void itTest4(Map s, int size, int pos) { IdentityHashMap seen = new IdentityHashMap(size); reallyAssert(s.size() == size); int sum = 0; timer.start("Iter XEntry ", size); Iterator it = s.entrySet().iterator(); Object k = null; Object v = null; for (int i = 0; i < size - pos; ++i) { Map.Entry x = (Map.Entry) (it.next()); k = x.getKey(); v = x.getValue(); seen.put(k, k); if (x != MISSING) ++sum; } reallyAssert(s.containsKey(k)); it.remove(); reallyAssert(!s.containsKey(k)); while (it.hasNext()) { Map.Entry x = (Map.Entry) (it.next()); Object k2 = x.getKey(); seen.put(k2, k2); if (x != MISSING) ++sum; } reallyAssert(s.size() == size - 1); s.put(k, v); reallyAssert(seen.size() == size); timer.finish(); reallyAssert(sum == size); reallyAssert(s.size() == size); }
public static void main(String[] args) throws Exception { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(rd.readLine()); Map<String, Integer> terms = new LinkedHashMap<String, Integer>(N * 2); for (int i = 0; i < N; i++) { String term = rd.readLine(); Integer count = terms.get(term); count = (count == null) ? 1 : count + 1; terms.put(term, count); } int K = Integer.parseInt(rd.readLine()); rd.close(); Queue<TermCount> sortedTerms = new PriorityQueue<TermCount>( K, new Comparator<TermCount>() { @Override public int compare(TermCount x, TermCount y) { return (x.count == y.count) ? x.term.compareTo(y.term) : y.count - x.count; } }); for (Map.Entry<String, Integer> entry : terms.entrySet()) { sortedTerms.add(new TermCount(entry.getKey(), entry.getValue())); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); for (int i = 0; i < K; i++) { pw.println(sortedTerms.poll().term); } pw.close(); }
private void init() { permNoToSymbol = Utils.loadMapping(originalStockFile); Map<String, Integer> symbolToPerm = new HashMap<String, Integer>(); for (Map.Entry<Integer, String> entry : permNoToSymbol.entrySet()) { symbolToPerm.put(entry.getValue(), entry.getKey()); } }
/** * Copies the key/value mappings in <tt>map</tt> into this map. Note that this will be a * <b>deep</b> copy, as storage is by primitive value. * * @param map a <code>Map</code> value */ public void putAll(Map<? extends Character, ? extends Double> map) { Iterator<? extends Entry<? extends Character, ? extends Double>> it = map.entrySet().iterator(); for (int i = map.size(); i-- > 0; ) { Entry<? extends Character, ? extends Double> e = it.next(); this.put(e.getKey(), e.getValue()); } }
/** PUBLIC: Add all of the elements. */ public void putAll(Map map) { Iterator entriesIterator = map.entrySet().iterator(); while (entriesIterator.hasNext()) { Map.Entry entry = (Map.Entry) entriesIterator.next(); put(entry.getKey(), entry.getValue()); } }
/** * {@inheritDoc} * * @param ctx */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); if (ownedVals != null) { ownedValKeys = ownedVals.keySet(); ownedValVals = ownedVals.values(); for (Map.Entry<IgniteTxKey, CacheVersionedValue> entry : ownedVals.entrySet()) { GridCacheContext cacheCtx = ctx.cacheContext(entry.getKey().cacheId()); entry.getKey().prepareMarshal(cacheCtx); entry.getValue().prepareMarshal(cacheCtx.cacheObjectContext()); } } if (retVal != null && retVal.cacheId() != 0) { GridCacheContext cctx = ctx.cacheContext(retVal.cacheId()); assert cctx != null : retVal.cacheId(); retVal.prepareMarshal(cctx); } if (filterFailedKeys != null) { for (IgniteTxKey key : filterFailedKeys) { GridCacheContext cctx = ctx.cacheContext(key.cacheId()); key.prepareMarshal(cctx); } } }
public static Map cloneMap(Map map) { if (map == null) { return (null); } Map res = new TreeMap(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); // keys must be String (or very rarely byte[]) if (key instanceof byte[]) { key = ((byte[]) key).clone(); } res.put(key, clone(value)); } return (res); }