/** * Saves value to raster * * @param dLat Latitude. * @param dLon Longitude. * @param dValue Value to be written */ public void put(double dLat, double dLon, double dValue) { // ico1 = indices IndexCoordinate ico1; // checking mask // if(plyMask!=null && !plyMask.contains(dLat, dLon)){ // return; // } // updating index maps if (!mapDate.containsKey(tim1)) { mapDate.put(tim1, iDateIndex); iDateIndex++; } if (!mapVert.containsKey(dVert)) { mapVert.put(dVert, iVertIndex); iVertIndex++; } // saving value ico1 = convertGeoCoordinateToIndexCoordinate(new GeoCoordinate(dLat, dLon, tim1, dVert)); this.put(ico1.iLat, ico1.iLon, ico1.iTime, ico1.iVert, dValue); // updating list of coordinates lstCoords.add(new GeoCoordinate(mapLat.floorKey(dLat), mapLon.floorKey(dLon), tim1, dVert)); }
private void extractVocabulary(String directoryPath, int classID) throws IOException { File dir = new File(directoryPath); File[] directoryListing = dir.listFiles(); numDocs += directoryListing.length; numDocsOfEachClass[classID] = directoryListing.length; TreeMap<String, Integer> thisClassVocab = new TreeMap<String, Integer>(); if (directoryListing != null) { for (File child : directoryListing) { System.out.print("."); FileInputStream fis = new FileInputStream(child); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String wholeFile = ""; String line = ""; while (line != null) { line = br.readLine(); wholeFile += line + " "; } for (String term : Utils.tokenizeString(wholeFile)) { if (!term.matches(".*\\d+.*")) { if (!vocabulary.contains(term)) vocabulary.add(term); if (!thisClassVocab.containsKey(term)) { thisClassVocab.put(term, 1); } else if (thisClassVocab.containsKey(term)) { int temp = thisClassVocab.get(term) + 1; thisClassVocab.put(term, new Integer(temp)); } } } br.close(); } } vocabOfClasses.add(thisClassVocab); }
public static void findMoreCiteds(String text) { String[] words = text.split(" "); TreeMap<String, Integer> calculatedsMap = new TreeMap<>(); for (int i = 0; i < words.length; i++) { String word = words[i]; if (!calculatedsMap.containsKey(word)) { calculatedsMap.put(word, 1); } else { calculatedsMap.put(word, calculatedsMap.get(word) + 1); } } // TODO otimizar System.out.println("Termos mais utilizados:"); String bigger = calculatedsMap.firstKey(); int i = 0; while (i < 10) { for (String s : calculatedsMap.keySet()) { if ((calculatedsMap.containsKey(bigger) && calculatedsMap.containsKey(s)) && calculatedsMap.get(bigger) < calculatedsMap.get(s)) { bigger = s; } } // TODO verificar se podemos ignorar caracteres aleatórios if (bigger.length() > 2) { System.out.println((++i) + ": " + bigger + " - " + calculatedsMap.get(bigger)); } calculatedsMap.remove(bigger); bigger = calculatedsMap.firstKey(); } }
@Override public void doGet(TreeMap<String, Integer> treeMap, String gId, String from, String to) { // TODO Auto-generated method stub FacebookManager facebookManager = new FacebookManager(); List<models.Post> posts = facebookManager.getPostsFQL(gId, from, to); for (models.Post post : posts) { String userId = post.actor_id; int count = post.likes.findValue("count").asInt(); if (!treeMap.containsKey(userId)) { treeMap.put(userId, count); } else { int value = (int) treeMap.get(userId) + count; treeMap.put(userId, value); } } List<models.Comment> comments = facebookManager.getPostsCommentsFQL(gId, from, to); for (models.Comment comment : comments) { String userId = comment.fromid; int count = comment.likes; if (!treeMap.containsKey(userId)) { treeMap.put(userId, count); } else { int value = (int) treeMap.get(userId) + count; treeMap.put(userId, value); } } }
private void addStartEndKeysForTest(TreeMap<byte[], Integer> map, byte[] first, byte[] last) { Integer value = map.containsKey(first) ? map.get(first) : 0; map.put(first, value + 1); value = map.containsKey(last) ? map.get(last) : 0; map.put(last, value - 1); }
public void restore() { _listByIndex.clear(); _listByClassId.clear(); List<SubClass> subclasses = CharacterSubclassDAO.getInstance().restore(_owner); int lastFreeIndex = 2; for (SubClass sub : subclasses) { if (sub == null) // Невозможно, но хай будет. continue; if (size() >= MAX_SUB_COUNT) { _log.warn( "SubClassList:restore: Limit is subclass! Player: " + _owner.getName() + "(" + _owner.getObjectId() + ")"); break; } if (sub.isActive()) { _activeSubClass = sub; } if (sub.isBase()) { _baseSubClass = sub; sub.setIndex(1); } else { sub.setIndex(lastFreeIndex); lastFreeIndex++; } if (_listByIndex.containsKey(sub.getIndex())) _log.warn( "SubClassList:restore: Duplicate index in player subclasses! Player: " + _owner.getName() + "(" + _owner.getObjectId() + ")"); _listByIndex.put(sub.getIndex(), sub); if (_listByClassId.containsKey(sub.getClassId())) _log.warn( "SubClassList:restore: Duplicate class_id in player subclasses! Player: " + _owner.getName() + "(" + _owner.getObjectId() + ")"); _listByClassId.put(sub.getClassId(), sub); } _lastFreeIndex = lastFreeIndex; if (_listByIndex.size() != _listByClassId.size()) // Невозможно, но хай будет. _log.warn( "SubClassList:restore: The size of the lists do not match! Player: " + _owner.getName() + "(" + _owner.getObjectId() + ")"); }
/** 获取TOKEN,一天最多获取200次,需要所有用户共享值 */ public String GetToken() { String requestUrl = tokenUrl + "?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret; TenpayHttpClient httpClient = new TenpayHttpClient(); httpClient.setReqContent(requestUrl); if (httpClient.call()) { String res = httpClient.getResContent(); Gson gson = new Gson(); TreeMap map = gson.fromJson(res, TreeMap.class); // 在有效期内直接返回access_token if (map.containsKey("access_token")) { String s = map.get("access_token").toString(); } // 如果请求成功 if (null != map) { try { if (map.containsKey("access_token")) { Token = map.get("access_token").toString(); return this.Token; } } catch (Exception e) { // 获取token失败 System.out.println("失败:" + map.get("errmsg")); } } } return ""; }
/** * Checks if the class contains the given element. * * @param element A Method or Field * @return */ public boolean contains(FSTModelElement element) { if (element instanceof FSTMethod) { return methods.containsKey(((FSTMethod) element).getIdentifier()); } else if (element instanceof FSTField) { return fields.containsKey(((FSTField) element).getIdentifier()); } return false; }
@Override public List<Span> getSpansInRange(long start, long end) { /* * We first find the book-end files (first and last) whose Spans may * or may not fit in the the range. Intermediary files can be directly * passed, since they are completely within the time range. * * [ ] <-- Time range * * |-----++|+++++++|+++++++|+++++++|+++----|-------|---> * \ / \ / * start end * file file * */ List<Span> out = new ArrayList<Span>(); List<Long> middleFiles = new LinkedList<Long>(); long startSecond = start / SpanStorage.NANOS_PER_SECOND; long endSecond = end / SpanStorage.NANOS_PER_SECOND; int numFiles = (int) (endSecond - startSecond) / secondsPerFile; for (int i = 1; i < (numFiles); i++) { middleFiles.add(startSecond + i * secondsPerFile); } synchronized (this.files) { for (Long l : middleFiles) { if (files.containsKey(l)) { try { readFileSpans(files.get(l), out); } catch (IOException e) { LOG.warn("Error reading file: " + files.get(l).getAbsolutePath()); } } } // Start file if (files.containsKey(startSecond)) { try { readFileSpans(files.get(startSecond), out, start, end); } catch (IOException e) { LOG.warn("Error reading file: " + files.get(startSecond).getAbsolutePath()); } } // End file if (files.containsKey(endSecond)) { try { readFileSpans(files.get(endSecond), out, start, end); } catch (IOException e) { LOG.warn("Error reading file: " + files.get(endSecond).getAbsolutePath()); } } } return out; }
private void addFamixPackage(FamixObject famixObject) { if (!packages.containsKey(((FamixEntity) famixObject).uniqueName)) { packages.put(((FamixEntity) famixObject).uniqueName, (FamixPackage) famixObject); String parentUniqueName = ((FamixPackage) famixObject).belongsToPackage; FamixPackage parent = null; if (!parentUniqueName.equals("") && (packages.containsKey(parentUniqueName))) { parent = packages.get(parentUniqueName); parent.children.add(((FamixEntity) famixObject).uniqueName); } } }
public boolean changeSubClassId(int oldClassId, int newClassId) { if (!_listByClassId.containsKey(oldClassId)) return false; if (_listByClassId.containsKey(newClassId)) return false; SubClass sub = _listByClassId.get(oldClassId); sub.setClassId(newClassId); _listByClassId.remove(oldClassId); _listByClassId.put(sub.getClassId(), sub); return true; }
protected String fixSpelling(String turn) { String split[] = turn.split(" "); String result = ""; for (int i = 0; i < split.length; i++) { String w = split[i]; String lowerCase = w.toLowerCase(); Pattern p = Pattern.compile( "([\\\\/\\.\\?!,;\\(\\)]*)([^\\\\/\\.\\?!,;\\(\\)]+)([\\\\/\\.\\?!,;\\(\\)]*)"); Pattern p1 = Pattern.compile( "([\\\\/\\.\\?!,;\\(\\)]*)([^\\\\/\\.\\?!,;\\(\\)]+)([\\\\/\\.\\?!,;\\(\\)]+)([^\\\\/\\.\\?!,;\\(\\)]+)([\\\\/\\.\\?!,;\\(\\)]*)"); Matcher m = p.matcher(lowerCase); Matcher m1 = p1.matcher(lowerCase); if (m.matches()) { if (misspellings.containsKey(m.group(2))) { String replacement = misspellings.get(m.group(2)); result += m.group(1) + replacement + m.group(3) + " "; } else { result += m.group(1) + m.group(2) + m.group(3) + " "; } } else if (m1.matches()) { result += m1.group(1) + (misspellings.containsKey(m1.group(2)) ? misspellings.get(m1.group(2)) : m1.group(2)) + m1.group(3) + (misspellings.containsKey(m1.group(4)) ? misspellings.get(m1.group(4)) : m1.group(4)) + m1.group(5) + " "; } else { if (misspellings.containsKey(lowerCase)) { String replacement = misspellings.get(lowerCase); result += replacement + " "; } else { if (!w.matches("[A-Z][a-z]*")) result += lowerCase + " "; else result += w + " "; } } } return result.trim(); }
/** * Checks to see if this property has a match in the Lazy list to return if enabled or disabled. * * @param state * @return t/f */ private boolean isXToXLazyEnabledByConfig(TreeMap<String, Boolean> state) { String classPackage = this.getClazz().getClassPackage(); String className = this.getClazz().getClassName(); boolean match = state.containsKey("*.*.*") || state.containsKey("*." + className + ".*") || state.containsKey("*." + className + "." + propertyName) || state.containsKey(classPackage + ".*." + propertyName) || state.containsKey(classPackage + ".*.*") || state.containsKey(classPackage + "." + className + ".*") || state.containsKey("*.*." + propertyName) || state.containsKey(classPackage + "." + className + "." + propertyName); // get the default boolean enableLazy = state.get("*"); if (match) { // we're using: default... EXCEPT enableLazy = !enableLazy; } return enableLazy; }
private void sync() { // note that sometimes the tuples active may be less than max_spout_pending, e.g. // max_spout_pending = 3 // tx 1, 2, 3 active, tx 2 is acked. there won't be a commit for tx 2 (because tx 1 isn't // committed yet), // and there won't be a batch for tx 4 because there's max_spout_pending tx active TransactionStatus maybeCommit = _activeTx.get(_currTransaction); if (maybeCommit != null && maybeCommit.status == AttemptStatus.PROCESSED) { maybeCommit.status = AttemptStatus.COMMITTING; _collector.emit( TRANSACTION_COMMIT_STREAM_ID, new Values(maybeCommit.attempt), maybeCommit.attempt); } try { if (_activeTx.size() < _maxTransactionActive) { BigInteger curr = _currTransaction; for (int i = 0; i < _maxTransactionActive; i++) { if ((_coordinatorState.hasCache(curr) || _coordinator.isReady()) && !_activeTx.containsKey(curr)) { TransactionAttempt attempt = new TransactionAttempt(curr, _rand.nextLong()); Object state = _coordinatorState.getState(curr, _initializer); _activeTx.put(curr, new TransactionStatus(attempt)); _collector.emit( TRANSACTION_BATCH_STREAM_ID, new Values(attempt, state, previousTransactionId(_currTransaction)), attempt); } curr = nextTransactionId(curr); } } } catch (FailedException e) { LOG.warn("Failed to get metadata for a transaction", e); } }
public StreamElement(TreeMap<String, Serializable> output, DataField[] fields) { int nbFields = output.keySet().size(); if (output.containsKey("timed")) nbFields--; String fieldNames[] = new String[nbFields]; Byte fieldTypes[] = new Byte[nbFields]; Serializable fieldValues[] = new Serializable[nbFields]; TreeMap<String, Integer> indexedFieldNames = new TreeMap<String, Integer>(new CaseInsensitiveComparator()); int idx = 0; long timestamp = System.currentTimeMillis(); for (String key : output.keySet()) { Serializable value = output.get(key); if (key.equalsIgnoreCase("timed")) timestamp = (Long) value; else { fieldNames[idx] = key; fieldValues[idx] = value; for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equalsIgnoreCase(key)) fieldTypes[idx] = fields[i].getDataTypeID(); } indexedFieldNames.put(key, idx); idx++; } } this.fieldNames = fieldNames; this.fieldTypes = fieldTypes; this.fieldValues = fieldValues; this.indexedFieldNames = indexedFieldNames; this.timeStamp = timestamp; }
public void addNeighbour(String neighbour) { if (!addNeighbours) return; if (!instanceNeighbourMap.containsKey(neighbour)) return; this.instanceNeighbourMap.put(neighbour, "1"); if (stripEmpty) neighbourMap.put(neighbour, "1"); logger.debug(name + ": has neighbours: " + instanceNeighbourMap.toString()); }
/** * Compute which element should be quizzed next from the given set of elements UID, according to * the statistics of each elements. * * @param elementsUID Set of elementsUID from which to found the next element. * @return String Element Unique ID */ public String getNextElement(Vector<String> elementsUID) { String currentElementUID = null; float bestScore = Float.NEGATIVE_INFINITY; float currentScore = bestScore; Vector<String> bestsUIDs = new Vector<String>(); Iterator<String> itElements = elementsUID.iterator(); while (itElements.hasNext()) { currentElementUID = itElements.next(); if (!statistics.containsKey(currentElementUID)) { KanjiNoSensei.log( Level.WARNING, Messages.getString("LearningProfile.LearningProfile.WarningNeverSeenElement") + " : \"" + currentElementUID + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return currentElementUID; } currentScore = statistics.get(currentElementUID).getNeedScore(); if (currentScore > bestScore) { bestsUIDs.removeAllElements(); bestsUIDs.add(currentElementUID); bestScore = currentScore; } else if (currentScore == bestScore) { bestsUIDs.add(currentElementUID); } } return bestsUIDs.get(random.nextInt(bestsUIDs.size())); }
public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pr = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("in.txt")); // pr = new PrintWriter(new FileWriter("out.txt")); int n = readInt(); int k = readInt(); int[] boy = new int[n]; TreeMap<Integer, Integer> girl = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; i++) { boy[i] = readInt(); } for (int i = 0; i < n; i++) { int in = readInt(); if (!girl.containsKey(in)) girl.put(in, 0); girl.put(in, girl.get(in) + 1); } Arrays.sort(boy); int ans = 0; for (int i = 0; i < n; i++) { Integer next = girl.ceilingKey(boy[i] - k); if (next != null && Math.abs(next - boy[i]) <= k) { ans++; girl.put(next, girl.get(next) - 1); if (girl.get(next) == 0) girl.remove(next); } } System.out.println(ans); pr.close(); }
/** * this method draws a sample of size endPercent-startPercent and returns the size of this sample * which corresponds to the number of content items */ public static double drawSample(int forumID, int startPercent, int endPercent) { if (!distributionsPerForumMap.containsKey( String.valueOf(forumID) + String.valueOf(startPercent) + String.valueOf(endPercent))) { ForumDistribution sampledForumDistribution = new ForumDistribution(); ArrayList<Integer> threadLengths = threadsPerForumMap.get(forumID); Integer numberOfThreads = threadLengths.size(); Integer startIndex; if (startPercent == 0.0) { startIndex = 0; } else { startIndex = (int) Math.round((startPercent / (double) 100) * numberOfThreads) - 1; } Integer endIndex = (int) Math.round((endPercent / (double) 100) * numberOfThreads) - 1; for (int i = startIndex; i <= endIndex; i++) { sampledForumDistribution.addThread(threadLengths.get(i)); } distributionsPerForumMap.put( String.valueOf(forumID) + String.valueOf(startPercent) + String.valueOf(endPercent), sampledForumDistribution); dumpDistributionToFile(sampledForumDistribution, forumID, startPercent, endPercent); return (double) sampledForumDistribution.getNumberOfContentItems(); } else { return (double) distributionsPerForumMap .get( String.valueOf(forumID) + String.valueOf(startPercent) + String.valueOf(endPercent)) .getNumberOfContentItems(); } }
public TreeMap<String, Integer> getOccurrencesOfTagsAfterTurnLength(int min) throws IOException { TreeMap<String, Integer> occurrences = new TreeMap<String, Integer>(); File[] files = inputDir.listFiles(); int totalTurns = 0; for (File curFile : files) { if (!curFile.getName().endsWith(datafileExtension)) continue; System.out.print("Processing file: " + curFile + " ..."); BufferedReader in = new BufferedReader(new FileReader(curFile)); String line = in.readLine(); while ((line = in.readLine()) != null) { String[] values = line.split("\\|", -1); if (values[0].equalsIgnoreCase("server") || values[1].equalsIgnoreCase("server") || values[2].equalsIgnoreCase("server") || values[9].isEmpty()) continue; String curTurn = values[8]; String spellingCorrected = fixSpelling(curTurn); float distance = 0.0f; if (spellingCorrected.trim().isEmpty()) { // System.out.println("EMPTY. SKIPPING THIS."); continue; } List<ArrayList<? extends HasWord>> sentences = MaxentTagger.tokenizeText(new StringReader(spellingCorrected)); if (sentences.isEmpty()) { continue; } totalTurns++; for (ArrayList<? extends HasWord> sent : sentences) { ArrayList<TaggedWord> taggedSentence = tagger.tagSentence(sent); boolean lastSentence = (sent == sentences.get(sentences.size() - 1)); if (lastSentence) { taggedSentence.add(new TaggedWord("", "EOT")); } for (int i = 0; i < taggedSentence.size(); i++) { TaggedWord cur = taggedSentence.get(i); distance++; if (distance >= min) { if (occurrences.containsKey(cur.tag())) { occurrences.put(cur.tag(), occurrences.get(cur.tag()) + 1); } else { occurrences.put(cur.tag(), 1); } } } } } } System.out.println("there were " + totalTurns + " turns in total."); return occurrences; }
/** * Get a message from out I18n data file. * * @param message - message title. Such as 'noPlayer' * @return - What the set message really is */ public String getColoredMessage(final String message) { if (messageCache.containsKey(message)) { return messageCache.get(message); } try { try { final String translatedMessage = ChatColor.translateAlternateColorCodes(colorCode, customMessages.getString(message)); messageCache.put(message, translatedMessage); return translatedMessage; } catch (final MissingResourceException ex) { final String translatedMessage = ChatColor.translateAlternateColorCodes(colorCode, messages.getString(message)); messageCache.put(message, translatedMessage); return translatedMessage; } } catch (final MissingResourceException ex) { return defaultBundle.getString(message); } }
public SymbolTableEntry addSymbol(String theSymbol) { if (!table.containsKey(theSymbol)) { return table.put(theSymbol, new SymbolTableEntry(theSymbol)); } return null; }
public void removeByClassId(int classId) { if (!_listByClassId.containsKey(classId)) return; int index = _listByClassId.get(classId).getIndex(); _listByIndex.remove(index); _listByClassId.remove(classId); }
public String getNextAddress() { if (nodes.containsKey(this.nextId)) { return nodes.get(this.nextId); } else { return "255.255.255.255"; } }
// TODO private void update(File[] files) throws IOException { InputStream in; TarInputStream tin; TarEntry entry; TreeMap<String, Long> entries = new TreeMap<String, Long>(); if ((in = openFileRead(archive)) == null) { fatal(" ", 1); } if (decompress != 0) { in = wrapInputStream(in); } tin = new TarInputStream(in); while ((entry = tin.getNextEntry()) != null) { entries.put(entry.getName(), entry.getModTime().getTime()); } tin.close(); long etime, ftime; ArrayList<File> list = new ArrayList<File>(); for (File file : files) { if (entries.containsKey(file.getPath())) { etime = entries.get(file.getPath()); ftime = file.lastModified(); if (etime >= ftime) { continue; } } list.add(file); } insert(list.toArray(files)); }
public void insert(String s) { // Start from root TrieNode current = root; int i = 0; // Till end of string while (i < s.length()) { // Get the next character char c = s.charAt(i++); TreeMap<Character, TrieNode> childrenMap = (TreeMap) current.getChildren(); // Check if the current node has it in its children if (childrenMap.containsKey((Character) c)) { // Get the child node matching the current character current = childrenMap.get((Character) c); } else { // Create a temporary node and add it to current nodes children TrieNode n = new TrieNode(c); childrenMap.put((Character) c, n); current = n; } } current.setEnd(true); }
/** * Read callback implementation * * @param rc return code * @param ledgerId Ledger identifier * @param entryId Entry identifier * @param bb Data * @param ctx Control object */ public void readEntryComplete(int rc, long ledgerId, long entryId, ByteBuffer bb, Object ctx) { if (rc == 0) { bb.rewind(); /* * Collect new vote */ if (!votes.containsKey(entryId)) { votes.put(entryId, new ArrayList<ByteBuffer>()); } votes.get(entryId).add(bb); /* * Extract hint */ bb.position(16); long hint = bb.getLong(); LOG.info("Received a response: " + rc + ", " + entryId + ", " + hint); if (!hints.containsKey(hint)) { hints.put(hint, 0); } hints.put(hint, hints.get(hint) + 1); synchronized (counter) { if (counter.incrementAndGet() >= minimum) ; counter.notify(); } } else { LOG.debug("rc != 0"); } }
/* (non-Javadoc) * @see org.exist.xquery.Module#resolveVariable(org.exist.dom.QName) */ public Variable resolveVariable(QName qname) throws XPathException { VariableDeclaration decl = (VariableDeclaration) mGlobalVariables.get(qname); if (decl != null && !mStaticVariables.containsKey(qname)) { decl.eval(null); } return (Variable) mStaticVariables.get(qname); }
public String longestPrefix(String s) { if (root == null) return ""; TrieNode current = root; String p = new String(""); int prevWordEnd = 0; for (int i = 0; i < s.length(); i++) { TreeMap<Character, TrieNode> childrenMap = (TreeMap<Character, TrieNode>) current.getChildren(); char c = s.charAt(i); if (childrenMap.containsKey((Character) c)) { p += c; current = childrenMap.get((Character) c); if (current.isEnd()) { prevWordEnd = i + 1; } } else { break; } } if (current.isEnd()) { return p; } else { return s.substring(0, prevWordEnd); } }
public void addContainer(UMOContainerContext container) { if (containers.containsKey(container.getName())) { throw new IllegalArgumentException( CoreMessages.containerAlreadyRegistered(container.getName()).toString()); } containers.put(container.getName(), container); }