List of usage examples for java.util Collections sort
@SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> void sort(List<T> list)
From source file:ws.moor.bt.grapher.Grapher.java
public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Please specify a tab-separated values file"); System.exit(1);// w w w . j a v a 2 s .com } File file = new File(args[0]); final CSVMapCollector collector = new CSVMapCollector( new CSVSkipFilter(new CSVInputStream(new FileInputStream(file)), 0 * 1000)); JFrame window = new JFrame("Grapher"); window.setSize(1100, 800); window.setLayout(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(null); List<String> possibleNames = collector.getAvailableStreams(); Collections.sort(possibleNames); TreeNode root = convertToTree(possibleNames); final JTree tree = new JTree(root); tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { List<String> names = new ArrayList<String>(); final TreePath[] paths = tree.getSelectionModel().getSelectionPaths(); if (paths == null) { chartPanel.setChart(null); return; } for (TreePath path : paths) { Object lastPath = path.getLastPathComponent(); if (lastPath instanceof DefaultMutableTreeNode) { Object value = ((DefaultMutableTreeNode) lastPath).getUserObject(); if (value instanceof NodeValue) { names.add(value.toString()); } } } chartPanel.setChart(createChart(collector, names.toArray(new String[names.size()]))); } }); Font font = tree.getFont(); tree.setFont(font.deriveFont(10.0f)); JScrollPane scrollPane = new JScrollPane(tree); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(scrollPane); splitPane.setRightComponent(chartPanel); splitPane.setDividerLocation(200); window.setContentPane(splitPane); window.setVisible(true); }
From source file:com.buddycloud.channeldirectory.cli.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE)); JsonArray rootArray = rootElement.getAsJsonArray(); Map<String, Query> queries = new HashMap<String, Query>(); for (int i = 0; i < rootArray.size(); i++) { JsonObject queryElement = rootArray.get(i).getAsJsonObject(); String queryName = queryElement.get("name").getAsString(); String type = queryElement.get("type").getAsString(); Query query = null;//from w ww . j a v a 2 s . c o m if (type.equals("solr")) { query = new QueryToSolr(queryElement.get("agg").getAsString(), queryElement.get("core").getAsString(), queryElement.get("q").getAsString()); } else if (type.equals("dbms")) { query = new QueryToDBMS(queryElement.get("q").getAsString()); } queries.put(queryName, query); } LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet()); Collections.sort(queriesNames); Options options = new Options(); options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true) .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q')); options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true) .withDescription("Arguments for the query").create('a')); options.addOption(new Option("?", "help", false, "Print this message")); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit(options); } if (cmd.hasOption("help")) { printHelpAndExit(options); } String queryName = cmd.getOptionValue("q"); String argsCmd = cmd.getOptionValue("a"); Properties configuration = ConfigurationUtils.loadConfiguration(); Query query = queries.get(queryName); if (query == null) { printHelpAndExit(options); } System.out.println(query.exec(argsCmd, configuration)); }
From source file:jrrombaldo.pset.PSETMain.java
public static void main(String[] args) { Options options = prepareOptions();// w w w. j a va 2 s . co m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); String domain = line.getOptionValue("d"); // print help if (line.hasOption("h")) { printHelp(options); return; } // start gui e do nothing else if (!line.hasOption("c")) { startGuiVersion(domain); return; } // start gui e do nothing else if (!line.hasOption("d")) { System.out.println("a target domain is required, none was specified!"); printHelp(options); return; } if (!line.hasOption("g") && !line.hasOption("b")) { System.out.println("No search engine selected, at least one should be present"); printHelp(options); return; } if (line.hasOption("p")) { String proxy = line.getOptionValue("p"); System.out.println(proxy); } Set<String> results = new HashSet<>(); if (line.hasOption("g")) { results.addAll(new GoogleSearch(domain).listSubdomains()); } if (line.hasOption("b")) { results.addAll(new BingSearch(domain).listSubdomains()); } List<String> sortedResult = new ArrayList<String>(results); Collections.sort(sortedResult); int q = 1; for (String subDomain : sortedResult) { if (q == 1) { System.out.println("\nResults:"); } System.out.println(q + ": " + subDomain); q++; } } catch (ParseException exp) { System.out.println(exp.getLocalizedMessage()); printHelp(options); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.turn.ttorrent.client.main.TorrentMain.java
/** * Torrent creator./*from ww w . ja va 2 s . c om*/ * * <p> * You can use the {@code main()} function of this class to create * torrent files. See usage for details. * </p> */ public static void main(String[] args) throws Exception { // BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); OptionParser parser = new OptionParser(); OptionSpec<Void> helpOption = parser.accepts("help").forHelp(); OptionSpec<File> inputOption = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input file or directory for the torrent."); OptionSpec<File> outputOption = parser.accepts("output").withRequiredArg().ofType(File.class).required() .describedAs("The output torrent file."); OptionSpec<URI> announceOption = parser.accepts("announce").withRequiredArg().ofType(URI.class).required() .describedAs("The announce URL for the torrent."); parser.nonOptions().ofType(File.class).describedAs("Files to include in the torrent."); OptionSet options = parser.parse(args); List<?> otherArgs = options.nonOptionArguments(); // Display help and exit if requested if (options.has(helpOption)) { System.out.println("Usage: Torrent [<options>] <torrent-file>"); parser.printHelpOn(System.err); System.exit(0); } List<File> files = new ArrayList<File>(); for (Object o : otherArgs) files.add((File) o); Collections.sort(files); TorrentCreator creator = new TorrentCreator(options.valueOf(inputOption)); if (!files.isEmpty()) creator.setFiles(files); creator.setAnnounceList(options.valuesOf(announceOption)); Torrent torrent = creator.create(); File file = options.valueOf(outputOption); OutputStream fos = FileUtils.openOutputStream(file); try { torrent.save(fos); } finally { IOUtils.closeQuietly(fos); } }
From source file:org.test.LookupSVNUsers.java
/** * @param args/* w w w. j a va2s . c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length != 2) { log.error("USAGE: <svn users file(input)> <git authors file (output)>"); System.exit(-1); } Set<String> unmatchedNameSet = new LinkedHashSet<String>(); Map<String, GitUser> gitUserMap = new LinkedHashMap<String, GitUser>(); String svnAuthorsFile = args[0]; List<String> lines = FileUtils.readLines(new File(svnAuthorsFile)); for (String line : lines) { // intentionally handle both upper and lower case varients of the same name. String svnUserName = line.trim(); if (svnUserName.contains("(")) continue; // skip over this line as we can't use it on the url if (gitUserMap.keySet().contains(svnUserName)) continue; // skip this duplicate. log.info("starting on user = " + svnUserName); String gitName = extractFullName(svnUserName); if (gitName == null) { gitName = extractFullName(svnUserName.toLowerCase()); } if (gitName == null) { unmatchedNameSet.add(svnUserName); } else { gitUserMap.put(svnUserName, new GitUser(svnUserName, gitName)); log.info("mapped user (" + svnUserName + ") to: " + gitName); } } List<String> mergedList = new ArrayList<String>(); mergedList.add("# GENERATED "); List<String> userNameList = new ArrayList<String>(); userNameList.addAll(gitUserMap.keySet()); Collections.sort(userNameList); for (String userName : userNameList) { GitUser gUser = gitUserMap.get(userName); mergedList.add(gUser.getSvnAuthor() + " = " + gUser.getGitUser() + " <" + gUser.getSvnAuthor() + "@users.sourceforge.net>"); } for (String username : unmatchedNameSet) { log.warn("failed to match SVN User = " + username); // add in the unmatched entries as is. mergedList.add(username + " = " + username + " <" + username + "@users.sourceforge.net>"); } FileUtils.writeLines(new File(args[1]), "UTF-8", mergedList); }
From source file:at.tlphotography.jAbuseReport.Reporter.java
/** * The main method.//from w w w . j a v a2 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(); } }
From source file:movierecommend.MovieRecommend.java
public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:sqlserver://localhost;databaseName=MovieDB;integratedSecurity=true"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(url); Statement stm = conn.createStatement(); ResultSet rsRecnik = stm.executeQuery("SELECT Recnik FROM Recnik WHERE (ID_Zanra = 1)"); //citam recnik iz baze za odredjeni zanr String recnik[] = null;// w w w. j ava2 s .c o m while (rsRecnik.next()) { recnik = rsRecnik.getString("Recnik").split(","); //delim recnik na reci } ResultSet rsFilmovi = stm.executeQuery( "SELECT TOP (200) Naziv_Filma, LemmaPlots, " + "ID_Filma FROM Film WHERE (ID_Zanra = 1)"); List<Film> listaFilmova = new ArrayList<>(); Film f = null; int rb = 0; while (rsFilmovi.next()) { f = new Film(rb, Integer.parseInt(rsFilmovi.getString("ID_Filma")), rsFilmovi.getString("Naziv_Filma"), rsFilmovi.getString("LemmaPlots")); listaFilmova.add(f); rb++; } //kreiranje vektorskog modela M = MatrixUtils.createRealMatrix(recnik.length, listaFilmova.size()); System.out.println("Prva tezinska matrica"); for (int i = 0; i < recnik.length; i++) { String recBaza = recnik[i]; for (Film film : listaFilmova) { for (String lemmaRec : film.getPlotLema()) { if (recBaza.equals(lemmaRec)) { M.setEntry(i, film.getRb(), M.getEntry(i, film.getRb()) + 1); } } } } //racunanje tf-idf System.out.println("td-idf"); M = LSA.calculateTfIdf(M); System.out.println("SVD"); //SVD SingularValueDecomposition svd = new SingularValueDecomposition(M); RealMatrix V = svd.getV(); RealMatrix Vk = V.getSubMatrix(0, V.getRowDimension() - 1, 0, brojDimenzija - 1); //dimenzija je poslednji argument //kosinusna slicnost System.out.println("Cosin simmilarity"); CallableStatement stmTop = conn.prepareCall("{call Dodaj_TopList(?,?,?)}"); for (int j = 0; j < listaFilmova.size(); j++) { Film fl = listaFilmova.get(j); List<Film> lFilmova1 = new ArrayList<>(); lFilmova1.add(listaFilmova.get(j)); double sim = 0.0; for (int k = 0; k < listaFilmova.size(); k++) { // System.out.println(listaFilmova.size()); sim = LSA.cosinSim(j, k, Vk.transpose()); listaFilmova.get(k).setSimilarity(sim); lFilmova1.add(listaFilmova.get(k)); } Collections.sort(lFilmova1); for (int k = 2; k < 13; k++) { stmTop.setString(1, fl.getID() + ""); stmTop.setString(2, lFilmova1.get(k).getID() + ""); stmTop.setString(3, lFilmova1.get(k).getSimilarity() + ""); stmTop.execute(); } } stm.close(); rsRecnik.close(); rsFilmovi.close(); conn.close(); }
From source file:com.music.tools.ScaleTester.java
public static void main(String[] args) { System.out.println(// ww w .ja va 2s.co m "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>"); final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true); try { fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class); int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class); List<Double> harmonicFrequencies = new ArrayList<>(); List<String> ratios = new ArrayList<>(); Set<Double> frequencies = new HashSet<Double>(); frequencies.add(fundamentalFreq); int octaveMultiplier = 2; for (int i = 2; i < 100; i++) { // Exclude the 7th harmonic TODO exclude the 11th as well? // http://www.phy.mtu.edu/~suits/badnote.html if (i % 7 == 0) { continue; } double actualFreq = fundamentalFreq * i; double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier); if (closestTonicRatio < 1 || closestTonicRatio > 2) { octaveMultiplier *= 2; } double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier); double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic); harmonicFrequencies.add(actualFreq); frequencies.add(normalizedFreq); if (frequencies.size() == pitchesInChromaticScale) { break; } } System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies); System.out.println("Transposed harmonic frequencies: " + frequencies); List<Double> chromaticScale = new ArrayList<>(frequencies); Collections.sort(chromaticScale); // find the "perfect" interval (e.g. perfect fifth) int perfectIntervalIndex = 0; int idx = 0; for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) { Double noteFreq = it.next(); long[] fraction = findCommonFraction(noteFreq / fundamentalFreq); fractionCache.put(noteFreq, fraction); if (fraction[0] == 3 && fraction[1] == 2) { perfectIntervalIndex = idx; System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex); } idx++; ratios.add(Arrays.toString(fraction)); } System.out.println("Ratios to fundemental frequency: " + ratios); if (getBooleanArgument(args, 4, USE_ET)) { chromaticScale = temper(chromaticScale); } System.out.println(); System.out.println("Chromatic scale: " + chromaticScale); Set<Double> scaleSet = new HashSet<Double>(); scaleSet.add(chromaticScale.get(0)); idx = 0; List<Double> orderedInCircle = new ArrayList<>(); // now go around the circle of perfect intervals and put the notes // in order while (orderedInCircle.size() < chromaticScale.size()) { orderedInCircle.add(chromaticScale.get(idx)); idx += perfectIntervalIndex; idx = idx % chromaticScale.size(); } System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle); List<Double> scale = new ArrayList<Double>(scaleSet); int currentIdxInCircle = orderedInCircle.size() - 1; // start with // the last // note in the // circle int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class); while (scale.size() < scaleSize) { double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size()); if (!scale.contains(pitch)) { scale.add(pitch); } currentIdxInCircle++; } Collections.sort(scale); System.out.println("Scale: " + scale); SourceDataLine line = AudioSystem.getSourceDataLine(af); line.open(af); line.start(); Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]); // first play the whole scale WaveMelodyGenerator.playScale(line, scaleFrequencies); // then generate a random melody in the scale WaveMelodyGenerator.playMelody(line, scaleFrequencies); line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:br.com.autonomiccs.cloudTraces.main.CloudTracesSimulator.java
public static void main(String[] args) { validateInputFile(args);//from w w w . j a v a2 s . com String cloudTracesFile = args[0]; Collection<VirtualMachine> virtualMachines = getAllVirtualMachinesFromCloudTraces(cloudTracesFile); logger.info(String.format("#VirtualMachines [%d] found on [%s].", virtualMachines.size(), cloudTracesFile)); Map<Integer, List<VirtualMachine>> mapVirtualMachinesTaskExecutionByTime = createMapVirtualMachinesTaskExecutionByTime( virtualMachines); logger.info(String.format("#Times [%d] that have tasks being executed by VMs ", mapVirtualMachinesTaskExecutionByTime.size())); Cloud cloud = createCloudEnvirtonmentToStartsimulation(); logger.info("Cloud configuration: " + cloud); List<Integer> timesToExecuteTasks = new ArrayList<>(mapVirtualMachinesTaskExecutionByTime.keySet()); Collections.sort(timesToExecuteTasks); Integer firstTimeInTimeUnitOfUsedCloudData = timesToExecuteTasks.get(0); Integer lastTimeInTimeUnitOfUserCloudData = timesToExecuteTasks.get(timesToExecuteTasks.size() - 1); logger.info("First time: " + firstTimeInTimeUnitOfUsedCloudData); logger.info("Last time: " + lastTimeInTimeUnitOfUserCloudData); double timeUnitPerLoopIteration = getTimeUnitPerLoopIteration(firstTimeInTimeUnitOfUsedCloudData, lastTimeInTimeUnitOfUserCloudData); logger.info("The time unit converted to trace time: " + timeUnitPerLoopIteration); double currentTime = firstTimeInTimeUnitOfUsedCloudData; long highetResourceAllocation = Long.MIN_VALUE; String cloudStateHighestMemoryAllocation = ""; while (currentTime < lastTimeInTimeUnitOfUserCloudData + 2 * timeUnitPerLoopIteration) { logger.debug("Current time of iteration: " + currentTime); if (cloud.getMemoryAllocatedInBytes() > highetResourceAllocation) { highetResourceAllocation = cloud.getMemoryAllocatedInBytes(); cloudStateHighestMemoryAllocation = cloud.toString(); } applyLoadOnCloudForCurrentTime(mapVirtualMachinesTaskExecutionByTime, cloud, currentTime); destroyVirtualMachinesIfNeeded(cloud, currentTime); logger.info(String.format("Time [%.3f], cloud state [%s] ", currentTime, cloud)); executeManagement(cloud, currentTime); logClustersConfigurationsAndStdAtTime(cloud.getClusters(), currentTime); currentTime += timeUnitPerLoopIteration; } logger.info("Cloud configuration after simulation: " + cloud); logger.info("Cloud highestResourceUsage: " + cloudStateHighestMemoryAllocation); }
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host// ww w. jav a2s .c o m String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }