List of usage examples for java.util HashMap get
public V get(Object key)
From source file:Main.java
public static void main(String[] args) throws IllegalAccessException { Class clazz = Color.class; Field[] colorFields = clazz.getDeclaredFields(); HashMap<String, Color> singleColors = new HashMap<String, Color>(); for (Field cf : colorFields) { int modifiers = cf.getModifiers(); if (!Modifier.isPublic(modifiers)) continue; Color c = (Color) cf.get(null); if (!singleColors.values().contains(c)) singleColors.put(cf.getName(), c); }// w ww. j ava 2 s . c om for (String k : singleColors.keySet()) { System.out.println(k + ": " + singleColors.get(k)); } }
From source file:edu.illinois.cs.cogcomp.nlp.tokenizer.HashCollisionReport.java
/** * Read each test file in the directory, tokenize and create the token view. Then check for * collisions./* w ww . j a v a2s. com*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length == 0) error("Must pass in the name of a directory with files to test against."); File dir = new File(args[0]); if (!dir.exists()) { error("The directory did not exist : " + dir); } if (!dir.isDirectory()) { error("The path was not a directory : " + dir); } File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { String normal = FileUtils.readFileToString(file); TextAnnotationBuilder tabldr = new TokenizerTextAnnotationBuilder(new StatefulTokenizer()); TextAnnotation taNormal = tabldr.createTextAnnotation("test", "normal", normal); List<Constituent> normalToks = taNormal.getView(ViewNames.TOKENS).getConstituents(); HashMap<Integer, Constituent> hashmap = new HashMap<>(); // add each constituent to the map keyed by it's hashcode. Check first to see if the hashcode // is already used, if it is report it. for (Constituent c : normalToks) { int code = c.hashCode(); if (hashmap.containsKey(code)) { Constituent dup = hashmap.get(code); System.err.println(c + " == " + dup); } else { hashmap.put(code, c); } } } } }
From source file:HashMapDemo.java
public static void main(String args[]) { HashMap<String, Double> hm = new HashMap<String, Double>(); hm.put("A", new Double(3.34)); hm.put("B", new Double(1.22)); hm.put("C", new Double(1.00)); hm.put("D", new Double(9.22)); hm.put("E", new Double(-19.08)); Set<Map.Entry<String, Double>> set = hm.entrySet(); for (Map.Entry<String, Double> me : set) { System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); }//from w ww .j a va 2 s. c o m double balance = hm.get("A"); hm.put("A", balance + 1000); System.out.println(hm.get("A")); }
From source file:ISMAGS.CommandLineInterface.java
public static void main(String[] args) throws IOException { String folder = null, files = null, motifspec = null, output = null; Options opts = new Options(); opts.addOption("folder", true, "Folder name"); opts.addOption("linkfiles", true, "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)"); opts.addOption("motif", true, "Motif description by two strings (format: linktypes)"); opts.addOption("output", true, "Output file name"); CommandLineParser parser = new PosixParser(); try {// ww w . j a va 2 s.c om CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("folder")) { folder = cmd.getOptionValue("folder"); } if (cmd.hasOption("linkfiles")) { files = cmd.getOptionValue("linkfiles"); } if (cmd.hasOption("motif")) { motifspec = cmd.getOptionValue("motif"); } if (cmd.hasOption("output")) { output = cmd.getOptionValue("output"); } } catch (ParseException e) { Die("Error: Parsing error"); } if (print) { printBanner(folder, files, motifspec, output); } if (folder == null || files == null || motifspec == null || output == null) { Die("Error: not all options are provided"); } else { ArrayList<String> linkfiles = new ArrayList<String>(); ArrayList<String> linkTypes = new ArrayList<String>(); ArrayList<String> sourcenetworks = new ArrayList<String>(); ArrayList<String> destinationnetworks = new ArrayList<String>(); ArrayList<Boolean> directed = new ArrayList<Boolean>(); StringTokenizer st = new StringTokenizer(files, " "); while (st.hasMoreTokens()) { linkTypes.add(st.nextToken()); directed.add(st.nextToken().equals("d")); sourcenetworks.add(st.nextToken()); destinationnetworks.add(st.nextToken()); linkfiles.add(folder + st.nextToken()); } ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>(); HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>(); for (int i = 0; i < linkTypes.size(); i++) { String n = linkTypes.get(i); char nn = n.charAt(0); LinkType t = typeTranslation.get(nn); if (t == null) { t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i)); } allLinkTypes.add(t); typeTranslation.put(nn, t); } if (print) { System.out.println("Reading network.."); } Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes); Motif motif = getMotif(motifspec, typeTranslation); if (print) { System.out.println("Starting the search.."); } MotifFinder mf = new MotifFinder(network); long tijd = System.nanoTime(); Set<MotifInstance> motifs = mf.findMotif(motif, false); tijd = System.nanoTime() - tijd; if (print) { System.out.println("Completed search in " + tijd / 1000000 + " milliseconds"); } if (print) { System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif"); } if (print) { System.out.println("Writing instances to file: " + output); } printMotifs(motifs, output); if (print) { System.out.println("Done."); } // Set<MotifInstance> motifs=null; // MotifFinder mf=null; // System.out.println("Starting the search.."); // long tstart = System.nanoTime(); // for (int i = 0; i < it; i++) { // // mf = new MotifFinder(network, allLinkTypes, true); // motifs = mf.findMotif(motif); // } // // long tend = System.nanoTime(); // double time_in_ms = (tend - tstart) / 1000000.0; // System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms"); //// System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes"); //// System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms"); // printMotifs(motifs, output); } }
From source file:edu.usc.squash.Main.java
public static void main(String[] args) { Stack<Module> modulesStack; Module module;//from w ww.j av a2s . com if (parseInputs(args) == false) { System.exit(-1); //The input files do not exist } String separator = "----------------------------------------------"; System.out.println("Squash v2.0"); System.out.println(separator); long start = System.currentTimeMillis(); // Parsing the input library Library library = QLib.readLib(libraryPath); library.setCurrentECC(currentECC); HashMap<String, Module> modules = parseQASMHF(library); Module mainModule = modules.get("main"); //Finding max{A_L_i} int childModulesLogicalAncillaReq; int moduleAncillaReq; modulesStack = new Stack<Module>(); modulesStack.add(mainModule); while (!modulesStack.isEmpty()) { module = modulesStack.peek(); if (!module.isVisited() && module.isChildrenVisited()) { //Finding the maximum childModulesLogicalAncillaReq = 0; for (Module child : module.getDFG().getModules()) { childModulesLogicalAncillaReq = Math.max(childModulesLogicalAncillaReq, child.getAncillaReq()); } moduleAncillaReq = module.getAncillaQubitNo() + childModulesLogicalAncillaReq; module.setAncillaReq(moduleAncillaReq); // System.out.println("Module "+module.getName()+" requires "+moduleAncillaReq+" ancilla."); modulesStack.pop(); module.setVisited(); } else if (module.isVisited()) { modulesStack.pop(); } else if (!module.isChildrenVisited()) { modulesStack.addAll(module.getDFG().getModules()); module.setChildrenVisited(); } } int totalLogicalAncilla = mainModule.getAncillaReq(); System.out.println("A_L_i_max: " + totalLogicalAncilla); final int Q_L = mainModule.getDataQubitNo(); /* * In order traversal of modules */ //Making sure all of the modules are unvisited for (Module m : modules.values()) { m.setUnvisited(); } modulesStack = new Stack<Module>(); modulesStack.add(mainModule); while (!modulesStack.isEmpty()) { module = modulesStack.peek(); if (!module.isVisited() && module.isChildrenVisited()) { System.out.println(separator); mapModule(module, k, physicalAncillaBudget, totalLogicalAncilla, Q_L, beta_pmd, alpha_int, gamma_memory, library); modulesStack.pop(); module.setVisited(); } else if (module.isVisited()) { modulesStack.pop(); } else if (!module.isChildrenVisited()) { modulesStack.addAll(module.getDFG().getModules()); module.setChildrenVisited(); } } System.out.println(separator); double runtime = (System.currentTimeMillis() - start) / 1000.0; System.out.println("B_P: " + B_P); System.out.println("Total Runtime:\t" + runtime + " sec"); }
From source file:ch.cyclops.gatekeeper.Main.java
public static void main(String[] args) throws Exception { CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); if (args.length > 0) config.addConfiguration(new PropertiesConfiguration(args[args.length - 1])); //setting up the logging framework now Logger.getRootLogger().getLoggerRepository().resetConfiguration(); ConsoleAppender console = new ConsoleAppender(); //create appender //configure the appender String PATTERN = "%d [%p|%C{1}|%M|%L] %m%n"; console.setLayout(new PatternLayout(PATTERN)); String logConsoleLevel = config.getProperty("log.level.console").toString(); switch (logConsoleLevel) { case ("INFO"): console.setThreshold(Level.INFO); break;//from ww w . j a v a 2s .c om case ("DEBUG"): console.setThreshold(Level.DEBUG); break; case ("WARN"): console.setThreshold(Level.WARN); break; case ("ERROR"): console.setThreshold(Level.ERROR); break; case ("FATAL"): console.setThreshold(Level.FATAL); break; case ("OFF"): console.setThreshold(Level.OFF); break; default: console.setThreshold(Level.ALL); } console.activateOptions(); //add appender to any Logger (here is root) Logger.getRootLogger().addAppender(console); String logFileLevel = config.getProperty("log.level.file").toString(); String logFile = config.getProperty("log.file").toString(); if (logFile != null && logFile.length() > 0) { FileAppender fa = new FileAppender(); fa.setName("FileLogger"); fa.setFile(logFile); fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n")); switch (logFileLevel) { case ("INFO"): fa.setThreshold(Level.INFO); break; case ("DEBUG"): fa.setThreshold(Level.DEBUG); break; case ("WARN"): fa.setThreshold(Level.WARN); break; case ("ERROR"): fa.setThreshold(Level.ERROR); break; case ("FATAL"): fa.setThreshold(Level.FATAL); break; case ("OFF"): fa.setThreshold(Level.OFF); break; default: fa.setThreshold(Level.ALL); } fa.setAppend(true); fa.activateOptions(); //add appender to any Logger (here is root) Logger.getRootLogger().addAppender(fa); } //now logger configuration is done, we can start using it. Logger mainLogger = Logger.getLogger("gatekeeper-driver.Main"); mainLogger.debug("Driver loaded properly"); if (args.length > 0) { GKDriver gkDriver = new GKDriver(args[args.length - 1], 1, "Eq7K8h9gpg"); System.out.println("testing if admin: " + gkDriver.isAdmin(1, 0)); ArrayList<String> uList = gkDriver.getUserList(0); //the argument is the starting count of number of allowed //internal attempts. if (uList != null) { mainLogger.info("Received user list from Gatekeeper! Count: " + uList.size()); for (int i = 0; i < uList.size(); i++) mainLogger.info(uList.get(i)); } boolean authResponse = gkDriver.simpleAuthentication(1, "Eq7K8h9gpg"); if (authResponse) mainLogger.info("Authentication attempt was successful."); else mainLogger.warn("Authentication attempt failed!"); String sName = "myservice-" + System.currentTimeMillis(); HashMap<String, String> newService = gkDriver.registerService(sName, "this is my new cool service", 0); String sKey = ""; if (newService != null) { mainLogger.info("Service registration was successful! Got:" + newService.get("uri") + ", Key=" + newService.get("key")); sKey = newService.get("key"); } else { mainLogger.warn("Service registration failed!"); } int newUserId = gkDriver.registerUser("user-" + System.currentTimeMillis(), "pass1234", false, sName, 0); if (newUserId != -1) mainLogger.info("User registration was successful. Received new id: " + newUserId); else mainLogger.warn("User registration failed!"); String token = gkDriver.generateToken(newUserId, "pass1234"); boolean isValidToken = gkDriver.validateToken(token, newUserId); if (isValidToken) mainLogger.info("The token: " + token + " is successfully validated for user-id: " + newUserId); else mainLogger.warn("Token validation was unsuccessful! Token: " + token + ", user-id: " + newUserId); ArrayList<String> sList = gkDriver.getServiceList(0); //the argument is the starting count of number of allowed //internal attempts. if (sList != null) { mainLogger.info("Received service list from Gatekeeper! Count: " + sList.size()); for (int i = 0; i < sList.size(); i++) mainLogger.info(sList.get(i)); } isValidToken = gkDriver.validateToken(token, sKey); if (isValidToken) mainLogger.info("The token: " + token + " is successfully validated for user-id: " + newUserId + " against s-key:" + sKey); else mainLogger.warn("Token validation was unsuccessful! Token: " + token + ", user-id: " + newUserId + ", s-key: " + sKey); boolean deleteResult = gkDriver.deleteUser(newUserId, 0); if (deleteResult) mainLogger.info("User with id: " + newUserId + " was deleted successfully."); else mainLogger.warn("User with id: " + newUserId + " could not be deleted successfully!"); } }
From source file:MainClass.java
public static void main(String args[]) { HashMap<String, Double> hm = new HashMap<String, Double>(); hm.put("A", new Double(3434.34)); hm.put("B", new Double(123.22)); hm.put("C", new Double(1378.00)); hm.put("D", new Double(99.22)); hm.put("E", new Double(-19.08)); Set<Map.Entry<String, Double>> set = hm.entrySet(); for (Map.Entry<String, Double> me : set) { System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); }//from www . j a v a2 s . co m System.out.println(); double balance = hm.get("B"); hm.put("B", balance + 1000); System.out.println("B's new balance: " + hm.get("B")); }
From source file:com.appeligo.epg.EpgIndexer.java
public static void main(String[] args) throws Exception { HessianProxyFactory factory = new HessianProxyFactory(); EPGProvider epg = (EPGProvider) factory.create(EPGProvider.class, "http://localhost/epg/channel.epg"); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -5);//w w w .j a va 2 s.co m cal.set(Calendar.DATE, 1); String[] lineups = new String[] { "SDTW-C", "P-C", "P-DC", "P-S", "M-C", "M-DC", "M-S", "E-C", "E-DC", "E-S", "H-C", "H-DC", "H-S" }; List<String> ids = epg.getModifiedProgramIds(cal.getTime()); int count = 0; long average = 0; int counter = 0; int added = 0; while (count < ids.size()) { System.err.println("in loop: " + counter + ", " + count + "," + ids.size()); int subsetSize = (ids.size() < 100 ? ids.size() : 100); counter++; if (count % 1000 == 0) { log.debug("Index programs into the Lucene Index. Current have processed " + count + " programs out of " + ids.size()); } int endIndex = (count + subsetSize > ids.size() ? ids.size() : count + subsetSize); List<String> subset = ids.subList(count, endIndex); count += subsetSize; long time = System.currentTimeMillis(); HashMap<String, List<ScheduledProgram>> schedules = new HashMap<String, List<ScheduledProgram>>(); for (String lineup : lineups) { ScheduledProgram[] programs = epg.getNextShowingList(lineup, subset); for (ScheduledProgram program : programs) { if (program != null) { List<ScheduledProgram> schedule = schedules.get(program.getProgramId()); if (schedule == null) { schedule = new ArrayList<ScheduledProgram>(); schedules.put(program.getProgramId(), schedule); } schedule.add(program); added++; } } } long after = System.currentTimeMillis(); long diff = after - time; average += diff; System.err.println(diff + " - " + (average / counter) + " added: " + added); } // EpgIndexer indexer = new EpgIndexer(programIndex, epg, lineup); // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.DAY_OF_MONTH, 24); // cal.set(Calendar.HOUR_OF_DAY, 0); // indexer.updateEpgIndex(cal.getTime()); }
From source file:com.zenoss.zenpacks.zenjmx.ZenJmxMain.java
/** * @param args/* w w w . j ava2s .com*/ */ public static void main(String[] args) throws Exception { HashMap<String, Level> loggingLevel = new HashMap<String, Level>(); loggingLevel.put(ERROR, Level.ERROR); loggingLevel.put(WARNING, Level.WARN); loggingLevel.put(INFO, Level.INFO); loggingLevel.put(DEBUG, Level.DEBUG); Configuration config = Configuration.instance(); parseArguments(config, args); if (config.propertyExists(OptionsFactory.LOG_SEVERITY)) { String levelOpt = config.getProperty(OptionsFactory.LOG_SEVERITY); Level level = loggingLevel.get(levelOpt); if (level != null) { _logger.info("setting root logger to " + level); Logger.getRootLogger().setLevel(level); } else { _logger.warn("Ignoring unknown log severity " + levelOpt); } } String port = config.getProperty(OptionsFactory.LISTEN_PORT, OptionsFactory.DEFAULT_LISTENPORT); Server server = new Server(); Connector connector = new SocketConnector(); connector.setPort(Integer.parseInt(port)); server.setConnectors(new Connector[] { connector }); ServletHandler handler = new ServletHandler(); ServletHolder holder = new ServletHolder(new XmlRpcServlet()); handler.addServletWithMapping(holder, "/"); // handler.start(); handler.initialize(); server.setHandler(handler); try { server.start(); } catch (Exception e) { System.exit(10); } server.join(); }
From source file:at.tlphotography.jAbuseReport.Reporter.java
/** * The main method./* w w w . j a va2 s.c o m*/ * * @param args * the arguments */ public static void main(String[] args) { parseArguments(args); File[] directory = new File(logDir).listFiles(); // get the files in the dir for (File file : directory) // iterate over the file { if (!file.isDirectory() && file.getName().contains(logNames)) // if the file is not a dir and the name contains the logName string { if (file.getName().endsWith(".gz")) // is it zipped? { content.putAll(readGZFile(file)); } else { content.putAll(readLogFile(file)); } } } // save the mails to the log lines HashMap<String, ArrayList<LogObject>> finalContent = new HashMap<>(); Iterator<Entry<String, String>> it = content.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); String mail = whoIsLookUp(pair.getKey()); if (finalContent.containsKey(mail)) { finalContent.get(mail).add(new LogObject(pair.getValue())); } else { ArrayList<LogObject> temp = new ArrayList<LogObject>(); temp.add(new LogObject(pair.getValue())); finalContent.put(mail, temp); } it.remove(); } // sort them Iterator<Entry<String, ArrayList<LogObject>>> it2 = finalContent.entrySet().iterator(); while (it2.hasNext()) { Entry<String, ArrayList<LogObject>> pair = it2.next(); Collections.sort(pair.getValue()); println(pair.getKey() + " ="); for (LogObject obj : pair.getValue()) { println(obj.logContent); } println("\n"); it2.remove(); } }