List of usage examples for java.util Map clear
void clear();
From source file:CTmousetrack.java
public static void main(String[] args) { String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder String srcName = "CTmousetrack"; // name of the output CT source long blockPts = 10; // points per block flush long sampInterval = 10; // time between sampling updates, msec double trimTime = 0.0; // amount of data to keep (trim time), sec boolean debug = false; // turn on debug? // Specify the CT output connection CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data String serverHost = ""; // Server (FTP or HTTP/S) host:port String serverUser = ""; // Server (FTP or HTTPS) username String serverPassword = ""; // Server (FTP or HTTPS) password // For UDP output mode DatagramSocket udpServerSocket = null; InetAddress udpServerAddress = null; String udpHost = ""; int udpPort = -1; // Concatenate all of the CTWriteMode types String possibleWriteModes = ""; for (CTWriteMode wm : CTWriteMode.values()) { possibleWriteModes = possibleWriteModes + ", " + wm.name(); }/* w w w . jav a 2s.c o m*/ // Remove ", " from start of string possibleWriteModes = possibleWriteModes.substring(2); // // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption(Option.builder("o").argName("base output dir").hasArg().desc( "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \"" + outLoc + "\".") .build()); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write data to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("b").argName("points per block").hasArg() .desc("Number of points per block; UDP output mode will use 1 point/block; default = " + Long.toString(blockPts) + ".") .build()); options.addOption(Option.builder("dt").argName("samp interval msec").hasArg() .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build()); options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc( "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption( Option.builder("w").argName("write mode").hasArg() .desc("Type of write connection; one of " + possibleWriteModes + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".") .build()); options.addOption(Option.builder("host").argName("host[:port]").hasArg() .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build()); options.addOption(Option.builder("u").argName("username,password").hasArg() .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build()); options.addOption("x", "debug", false, "Enable CloudTurbine debug output."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTmousetrack", "", options, "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port."); return; } outLoc = line.getOptionValue("o", outLoc); if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) { outLoc = outLoc + File.separator; } // Make sure the base output folder location ends in "CTdata" if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) { outLoc = outLoc + "CTdata" + File.separator; } srcName = line.getOptionValue("s", srcName); blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts))); sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval))); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); // Type of output connection String writeModeStr = line.getOptionValue("w", writeMode.name()); boolean bMatch = false; for (CTWriteMode wm : CTWriteMode.values()) { if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) { writeMode = wm; bMatch = true; } } if (!bMatch) { System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of " + possibleWriteModes); System.exit(0); } if (writeMode != CTWriteMode.LOCAL) { // User must have specified the host // If FTP or HTTPS, they may also specify username/password serverHost = line.getOptionValue("host", serverHost); if (serverHost.isEmpty()) { System.err.println( "When using write mode \"" + writeModeStr + "\", you must specify the server host."); System.exit(0); } if (writeMode == CTWriteMode.UDP) { // Force blockPts to be 1 blockPts = 1; // User must have specified both host and port int colonIdx = serverHost.indexOf(':'); if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) { System.err.println( "For UDP output mode, both the host and port (<host>:<port>)) must be specified."); System.exit(0); } udpHost = serverHost.substring(0, colonIdx); String udpPortStr = serverHost.substring(colonIdx + 1); try { udpPort = Integer.parseInt(udpPortStr); } catch (NumberFormatException nfe) { System.err.println("The UDP port must be a positive integer."); System.exit(0); } } if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) { String userpassStr = line.getOptionValue("u", ""); if (!userpassStr.isEmpty()) { // This string should be comma-delimited username and password String[] userpassCSV = userpassStr.split(","); if (userpassCSV.length != 2) { System.err.println("When specifying a username and password for write mode \"" + writeModeStr + "\", separate the username and password by a comma."); System.exit(0); } serverUser = userpassCSV[0]; serverPassword = userpassCSV[1]; } } } debug = line.hasOption("debug"); System.err.println("CTmousetrack parameters:"); System.err.println("\toutput mode = " + writeMode.name()); if (writeMode == CTWriteMode.UDP) { System.err.println("\twrite to " + udpHost + ":" + udpPort); } else { System.err.println("\tsource = " + srcName); System.err.println("\ttrim time = " + trimTime + " sec"); } System.err.println("\tpoints per block = " + blockPts); System.err.println("\tsample interval = " + sampInterval + " msec"); try { // // Setup CTwriter or UDP output // CTwriter ctw = null; CTinfo.setDebug(debug); if (writeMode == CTWriteMode.LOCAL) { ctw = new CTwriter(outLoc + srcName, trimTime); System.err.println("\tdata will be written to local folder \"" + outLoc + "\""); } else if (writeMode == CTWriteMode.FTP) { CTftp ctftp = new CTftp(srcName); try { ctftp.login(serverHost, serverUser, serverPassword); } catch (Exception e) { throw new IOException( new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage())); } ctw = ctftp; // upcast to CTWriter System.err.println("\tdata will be written to FTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTP) { // Don't send username/pw in HTTP mode since they will be unencrypted CThttp cthttp = new CThttp(srcName, "http://" + serverHost); ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTPS) { CThttp cthttp = new CThttp(srcName, "https://" + serverHost); // Username/pw are optional for HTTPS mode; only use them if username is not empty if (!serverUser.isEmpty()) { try { cthttp.login(serverUser, serverPassword); } catch (Exception e) { throw new IOException(new String( "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage())); } } ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTPS server at " + serverHost); } else if (writeMode == CTWriteMode.UDP) { try { udpServerSocket = new DatagramSocket(); } catch (SocketException se) { System.err.println("Error creating socket for UDP:\n" + se); System.exit(0); } try { udpServerAddress = InetAddress.getByName(udpHost); } catch (UnknownHostException uhe) { System.err.println("Error getting UDP server host address:\n" + uhe); System.exit(0); } } if (writeMode != CTWriteMode.UDP) { ctw.setBlockMode(blockPts > 1, blockPts > 1); ctw.autoFlush(0); // no autoflush ctw.autoSegment(1000); } // screen dims Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); // use Map for consolidated putData Map<String, Object> cmap = new LinkedHashMap<String, Object>(); // loop and write some output for (int i = 0; i < 1000000; i++) { // go until killed long currentTime = System.currentTimeMillis(); Point mousePos = MouseInfo.getPointerInfo().getLocation(); float x_pt = (float) (mousePos.getX() / width); // normalize float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0) if (writeMode != CTWriteMode.UDP) { // CT output mode ctw.setTime(currentTime); cmap.clear(); cmap.put("x", x_pt); cmap.put("y", y_pt); ctw.putData(cmap); if (((i + 1) % blockPts) == 0) { ctw.flush(); System.err.print("."); } } else { // UDP output mode // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time // Write the following data (21 bytes total): // header = "MOUSE", 5 bytes // current time, long, 8 bytes // 2 floats (x,y) 4 bytes each, 8 bytes int len = 21; ByteBuffer bb = ByteBuffer.allocate(len); String headerStr = "MOUSE"; bb.put(headerStr.getBytes("UTF-8")); bb.putLong(currentTime); bb.putFloat(x_pt); bb.putFloat(y_pt); // Might be able to use the following, but not sure: // byte[] sendData = bb.array(); byte[] sendData = new byte[len]; bb.position(0); bb.get(sendData, 0, len); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress, udpPort); try { udpServerSocket.send(sendPacket); } catch (IOException e) { System.err.println("Test server caught exception trying to send data to UDP client:\n" + e); } System.err.print("."); } try { Thread.sleep(sampInterval); } catch (Exception e) { } ; } if (writeMode != CTWriteMode.UDP) { ctw.flush(); // wrap up } } catch (Exception e) { System.err.println("CTmousetrack exception: " + e); e.printStackTrace(); } }
From source file:TweetAttributes.java
public static void main(String[] args) throws IOException, ParseException, JSONException { int k = Integer.parseInt(args[0]); String inputFile = args[1];//from w w w. ja v a 2 s. co m String initialSeedsFile = args[2]; String outputFile = args[3]; KMeansJaccard kmj = new KMeansJaccard(k); kmj.makeTweetObjects(inputFile); List<TweetAttributes> centroidPoints = kmj.getInitialCentroids(initialSeedsFile); Map<Long, List<Double>> distanceMap = new LinkedHashMap<>(); List<TweetAttributes> tweets = kmj.getTweetList(); buildDistanceMap(centroidPoints, tweets, kmj, distanceMap); for (Long i : distanceMap.keySet()) { kmj.assignClusterToTweet(i, distanceMap.get(i)); } List<TweetAttributes> tweetCopy = tweets; List<TweetAttributes> centroidCopy = centroidPoints; double cost = calculateCost(tweets, centroidPoints, kmj); Map<Integer, List<TweetAttributes>> tweetClusterMapping = getTweetCLusterMapping(tweets); for (Integer i : tweetClusterMapping.keySet()) { List<TweetAttributes> ta = tweetClusterMapping.get(i); for (TweetAttributes tweet : ta) { centroidPoints.remove(i - 1); centroidPoints.add(i - 1, tweet); distanceMap.clear(); buildDistanceMap(centroidPoints, tweets, kmj, distanceMap); for (Long id : distanceMap.keySet()) { kmj.assignClusterToTweet(id, distanceMap.get(id)); } double newCost = calculateCost(tweets, centroidPoints, kmj); if (newCost < cost) { cost = newCost; tweetCopy = kmj.getTweetList(); centroidCopy = kmj.getCentroidList(); } } } double sse = calculateSSE(tweetCopy, centroidCopy, kmj); System.out.println("COST: " + cost + " " + "SSE:" + sse); writeOutputToFile(tweetCopy, outputFile); }
From source file:Main.java
public static void main(String args[]) { Map<String, Integer> atomNums = new TreeMap<String, Integer>(); atomNums.put("A", 1); atomNums.put("B", 2); atomNums.put("C", 3); atomNums.put("D", 4); atomNums.put("E", 5); atomNums.put("F", 6); System.out.println("The map contains these " + atomNums.size() + " entries:"); Set<Map.Entry<String, Integer>> set = atomNums.entrySet(); for (Map.Entry<String, Integer> me : set) { System.out.print(me.getKey() + ", Atomic Number: "); System.out.println(me.getValue()); }//from ww w .j av a2 s . c o m TreeMap<String, Integer> atomNums2 = new TreeMap<String, Integer>(); atomNums2.put("Q", 30); atomNums2.put("W", 82); atomNums.putAll(atomNums2); set = atomNums.entrySet(); System.out.println("The map now contains these " + atomNums.size() + " entries:"); for (Map.Entry<String, Integer> me : set) { System.out.print(me.getKey() + ", Atomic Number: "); System.out.println(me.getValue()); } if (atomNums.containsKey("A")) System.out.println("A has an atomic number of " + atomNums.get("A")); if (atomNums.containsValue(82)) System.out.println("The atomic number 82 is in the map."); System.out.println(); if (atomNums.remove("A") != null) System.out.println("A has been removed.\n"); else System.out.println("Entry not found.\n"); Set<String> keys = atomNums.keySet(); for (String str : keys) System.out.println(str + " "); Collection<Integer> vals = atomNums.values(); for (Integer n : vals) System.out.println(n + " "); atomNums.clear(); if (atomNums.isEmpty()) System.out.println("The map is now empty."); }
From source file:edu.msu.cme.rdp.graph.utils.ContigMerger.java
public static void main(String[] args) throws IOException { final BufferedReader hmmgsResultReader; final IndexedSeqReader nuclContigReader; final double minBits; final int minProtLength; final Options options = new Options(); final PrintStream out; final ProfileHMM hmm; final FastaWriter protSeqOut; final FastaWriter nuclSeqOut; final boolean prot; final boolean all; final String shortSampleName; options.addOption("a", "all", false, "Generate all combinations for multiple paths, instead of just the best"); options.addOption("b", "min-bits", true, "Minimum bits score"); options.addOption("l", "min-length", true, "Minimum length"); options.addOption("s", "short_samplename", true, "short sample name, to be used as part of contig identifiers. This allow analyzing contigs together from different samples in downstream analysis "); options.addOption("o", "out", true, "Write output to file instead of stdout"); try {/*from w w w .j av a2 s .c o m*/ CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("min-bits")) { minBits = Double.valueOf(line.getOptionValue("min-bits")); } else { minBits = Double.NEGATIVE_INFINITY; } if (line.hasOption("min-length")) { minProtLength = Integer.valueOf(line.getOptionValue("min-length")); } else { minProtLength = 0; } if (line.hasOption("short_samplename")) { shortSampleName = line.getOptionValue("short_samplename") + "_"; } else { shortSampleName = ""; } if (line.hasOption("out")) { out = new PrintStream(line.getOptionValue("out")); } else { out = System.err; } all = line.hasOption("all"); args = line.getArgs(); if (args.length != 3) { throw new Exception("Unexpected number of arguments"); } hmmgsResultReader = new BufferedReader(new FileReader(new File(args[1]))); nuclContigReader = new IndexedSeqReader(new File(args[2])); hmm = HMMER3bParser.readModel(new File(args[0])); prot = (hmm.getAlphabet() == SequenceType.Protein); if (prot) { protSeqOut = new FastaWriter(new File("prot_merged.fasta")); } else { protSeqOut = null; } nuclSeqOut = new FastaWriter(new File("nucl_merged.fasta")); } catch (Exception e) { new HelpFormatter().printHelp("USAGE: ContigMerger [options] <hmm> <hmmgs_file> <nucl_contig>", options); System.err.println("Error: " + e.getMessage()); System.exit(1); throw new RuntimeException("I hate you javac"); } String line; SearchDirection lastDir = SearchDirection.left; //So this has an assumption built in //It depends on hmmgs always outputting left fragments, then right //We can't just use the kmer to figure out if we've switched to another starting point //because we allow multiple starting model pos, so two different starting //positions can have the same starting kmer Map<String, Sequence> leftContigs = new HashMap(); Map<String, Sequence> rightContigs = new HashMap(); int contigsMerged = 0; int writtenMerges = 0; long startTime = System.currentTimeMillis(); String kmer = null; String geneName = null; while ((line = hmmgsResultReader.readLine()) != null) { if (line.startsWith("#")) { continue; } String[] lexemes = line.trim().split("\t"); if (lexemes.length != 12 || lexemes[0].equals("-")) { System.err.println("Skipping line: " + line); continue; } //contig_53493 nirk 1500:6:35:16409:3561/1 ADV15048 tcggcgctctacacgttcctgcagcccggg 40 210 70 left -44.692 184 0 int index = 0; String seqid = lexemes[0]; geneName = lexemes[1]; String readid = lexemes[2]; String refid = lexemes[3]; kmer = lexemes[4]; int modelStart = Integer.valueOf(lexemes[5]); int nuclLength = Integer.valueOf(lexemes[6]); int protLength = Integer.valueOf(lexemes[7]); SearchDirection dir = SearchDirection.valueOf(lexemes[8]); if (dir != lastDir) { if (dir == SearchDirection.left) { List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm) : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm); contigsMerged++; for (MergedContig mc : mergedContigs) { String mergedId = shortSampleName + geneName + "_" + mc.leftContig + "_" + mc.rightContig; out.println(mergedId + "\t" + mc.length + "\t" + mc.score); if (mc.score > minBits && mc.length > minProtLength) { if (prot) { protSeqOut.writeSeq(mergedId, mc.protSeq); } nuclSeqOut.writeSeq(mergedId, mc.nuclSeq); writtenMerges++; } } leftContigs.clear(); rightContigs.clear(); } lastDir = dir; } Sequence seq = nuclContigReader.readSeq(seqid); if (dir == SearchDirection.left) { leftContigs.put(seqid, seq); } else if (dir == SearchDirection.right) { rightContigs.put(seqid, seq); } else { throw new IOException("Cannot handle search direction " + dir); } } if (!leftContigs.isEmpty() || !rightContigs.isEmpty()) { List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm) : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm); for (MergedContig mc : mergedContigs) { String mergedId = shortSampleName + mc.gene + "_" + mc.leftContig + "_" + mc.rightContig; out.println(mergedId + "\t" + mc.length + "\t" + mc.score); contigsMerged++; if (mc.score > minBits && mc.length > minProtLength) { if (prot) { protSeqOut.writeSeq(mergedId, mc.protSeq); } nuclSeqOut.writeSeq(mergedId, mc.nuclSeq); writtenMerges++; } } } out.close(); if (prot) { protSeqOut.close(); } nuclSeqOut.close(); System.err.println("Read in " + contigsMerged + " contigs, wrote out " + writtenMerges + " merged contigs in " + ((double) (System.currentTimeMillis() - startTime) / 1000) + "s"); }
From source file:com.px100systems.data.utility.RestoreUtility.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility " + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]"); return;/*from w w w .jav a2 s . c o m*/ } FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]); try { PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class); File directory = new File(args[2]); if (!directory.isDirectory()) { System.err.println(directory.getName() + " is not a directory"); return; } List<File> files = new ArrayList<File>(); //noinspection ConstantConditions for (File file : directory.listFiles()) if (BackupFile.isBackup(file)) files.add(file); if (files.isEmpty()) { System.err.println(directory.getName() + " directory has no backup files"); return; } if (args.length == 4 && args[3].equalsIgnoreCase("compare")) { final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>(); for (String storage : persister.storage()) { System.out.println("Storage " + storage); persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { Map<Long, RawRecord> unitList = units.get(record.getUnitName()); if (unitList == null) { unitList = new HashMap<Long, RawRecord>(); units.put(record.getUnitName(), unitList); } unitList.put(record.getId(), record); } }); for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) { BackupFile file = null; for (int i = 0, n = files.size(); i < n; i++) if (BackupFile.isBackup(files.get(i), unit.getKey())) { file = new BackupFile(files.get(i)); files.remove(i); break; } if (file == null) throw new RuntimeException("Could not find backup file for unit " + unit.getKey()); final Long[] count = new Long[] { 0L }; file.read(new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { RawRecord r = unit.getValue().get(record.getId()); if (r == null) throw new RuntimeException("Could not find persisted record " + record.getId() + " for unit " + unit.getKey()); if (!r.equals(record)) throw new RuntimeException( "Record " + record.getId() + " mismatch for unit " + unit.getKey()); count[0] = count[0] + 1; } }); if (count[0] != unit.getValue().size()) throw new RuntimeException("Extra persisted records for unit " + unit.getKey()); System.out.println(" Unit " + unit.getKey() + ": OK"); } units.clear(); } if (!files.isEmpty()) { System.err.println("Extra backups: "); for (File file : files) System.err.println(" " + file.getName()); } } else { persister.init(); for (File file : files) { InMemoryDatabase.readBackupFile(file, persister); System.out.println("Loaded " + file.getName()); } } } catch (Exception e) { throw new RuntimeException(e); } finally { ctx.close(); } }
From source file:Main.java
private static <K, V> Map<K, V> composeMapImpl(Iterable<Map.Entry<K, V>> entrySet, Map<K, V> target) { target.clear(); for (Map.Entry<K, V> entry : entrySet) { target.put(entry.getKey(), entry.getValue()); }/*from w w w . j a v a 2s. com*/ return target; }
From source file:Main.java
public static void clearMap(Map hash) { if (hash != null) { hash.clear(); } hash = null; }
From source file:Main.java
public static void clear() { Map<String, Object> map = wfThreadLocal.get(); if (map != null) { map.clear(); }/*from w w w.j a v a 2 s .com*/ }
From source file:Main.java
public static final void clear() { Map<Object, Object> cache = LOCAL_CACHE.get(); if (cache != null) { cache.clear(); LOCAL_CACHE.remove();/*w ww. j av a 2s . c om*/ } }
From source file:Main.java
public static <K, V> void clear(Map<K, V> map) { if (map == null) { map = new HashMap<K, V>(); } else {/* w w w. j a v a 2 s .c o m*/ map.clear(); } }