List of usage examples for java.util List size
int size();
From source file:io.cloudslang.lang.tools.build.SlangBuildMain.java
public static void main(String[] args) { loadUserProperties();/*from w ww .java 2s. c o m*/ configureLog4j(); ApplicationArgs appArgs = new ApplicationArgs(); parseArgs(args, appArgs); String projectPath = parseProjectPathArg(appArgs); final String contentPath = defaultIfEmpty(appArgs.getContentRoot(), projectPath + CONTENT_DIR); final String testsPath = defaultIfEmpty(appArgs.getTestRoot(), projectPath + TEST_DIR); List<String> testSuites = parseTestSuites(appArgs); boolean shouldPrintCoverageData = appArgs.shouldOutputCoverage(); boolean runTestsInParallel = appArgs.isParallel(); int threadCount = parseThreadCountArg(appArgs, runTestsInParallel); String testCaseTimeout = parseTestTimeout(appArgs); setProperty(TEST_CASE_TIMEOUT_IN_MINUTES_KEY, valueOf(testCaseTimeout)); final boolean shouldValidateDescription = appArgs.shouldValidateDescription(); final boolean shouldValidateCheckstyle = appArgs.shouldValidateCheckstyle(); String runConfigPath = FilenameUtils.normalize(appArgs.getRunConfigPath()); BuildMode buildMode = null; Set<String> changedFiles = null; try { String smartModePath = appArgs.getChangesOnlyConfigPath(); if (StringUtils.isEmpty(smartModePath)) { buildMode = BuildMode.BASIC; changedFiles = new HashSet<>(); printBuildModeInfo(buildMode); } else { buildMode = BuildMode.CHANGED; changedFiles = readChangedFilesFromSource(smartModePath); printBuildModeInfo(buildMode); } } catch (Exception ex) { log.error("Exception: " + ex.getMessage()); System.exit(1); } // Override with the values from the file if configured List<String> testSuitesParallel = new ArrayList<>(); List<String> testSuitesSequential = new ArrayList<>(); BulkRunMode bulkRunMode = runTestsInParallel ? ALL_PARALLEL : ALL_SEQUENTIAL; TestCaseRunMode unspecifiedTestSuiteRunMode = runTestsInParallel ? TestCaseRunMode.PARALLEL : TestCaseRunMode.SEQUENTIAL; if (get(runConfigPath).isAbsolute() && isRegularFile(get(runConfigPath), NOFOLLOW_LINKS) && equalsIgnoreCase(PROPERTIES_FILE_EXTENSION, FilenameUtils.getExtension(runConfigPath))) { Properties runConfigurationProperties = ArgumentProcessorUtils.getPropertiesFromFile(runConfigPath); shouldPrintCoverageData = getBooleanFromPropertiesWithDefault(TEST_COVERAGE, shouldPrintCoverageData, runConfigurationProperties); threadCount = getIntFromPropertiesWithDefaultAndRange(TEST_PARALLEL_THREAD_COUNT, Runtime.getRuntime().availableProcessors(), runConfigurationProperties, 1, MAX_THREADS_TEST_RUNNER + 1); testSuites = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_TO_RUN); testSuitesParallel = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_PARALLEL); testSuitesSequential = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_SEQUENTIAL); addErrorIfSameTestSuiteIsInBothParallelOrSequential(testSuitesParallel, testSuitesSequential); unspecifiedTestSuiteRunMode = getEnumInstanceFromPropertiesWithDefault(TEST_SUITES_RUN_UNSPECIFIED, unspecifiedTestSuiteRunMode, runConfigurationProperties); addWarningsForMisconfiguredTestSuites(unspecifiedTestSuiteRunMode, testSuites, testSuitesSequential, testSuitesParallel); bulkRunMode = POSSIBLY_MIXED; } else { // Warn when file is misconfigured, relative path, file does not exist or is not a properties file log.info(format(DID_NOT_DETECT_RUN_CONFIGURATION_PROPERTIES_FILE, runConfigPath)); } String testCaseReportLocation = getProperty(TEST_CASE_REPORT_LOCATION); if (StringUtils.isBlank(testCaseReportLocation)) { log.info("Test case report location property [" + TEST_CASE_REPORT_LOCATION + "] is not defined. Report will be skipped."); } // Setting thread count for visibility in ParallelTestCaseExecutorService setProperty(SLANG_TEST_RUNNER_THREAD_COUNT, valueOf(threadCount)); log.info(NEW_LINE + "------------------------------------------------------------"); log.info("Building project: " + projectPath); log.info("Content root is at: " + contentPath); log.info("Test root is at: " + testsPath); log.info("Active test suites are: " + getListForPrint(testSuites)); log.info("Parallel run mode is configured for test suites: " + getListForPrint(testSuitesParallel)); log.info("Sequential run mode is configured for test suites: " + getListForPrint(testSuitesSequential)); log.info("Default run mode '" + unspecifiedTestSuiteRunMode.name().toLowerCase() + "' is configured for test suites: " + getListForPrint( getDefaultRunModeTestSuites(testSuites, testSuitesParallel, testSuitesSequential))); log.info("Bulk run mode for tests: " + getBulkModeForPrint(bulkRunMode)); log.info("Print coverage data: " + valueOf(shouldPrintCoverageData)); log.info("Validate description: " + valueOf(shouldValidateDescription)); log.info("Validate checkstyle: " + valueOf(shouldValidateCheckstyle)); log.info("Thread count: " + threadCount); log.info("Test case timeout in minutes: " + (isEmpty(testCaseTimeout) ? valueOf(MAX_TIME_PER_TESTCASE_IN_MINUTES) : testCaseTimeout)); log.info(NEW_LINE + "Loading..."); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/testRunnerContext.xml"); context.registerShutdownHook(); SlangBuilder slangBuilder = context.getBean(SlangBuilder.class); LoggingService loggingService = context.getBean(LoggingServiceImpl.class); Slang slang = context.getBean(Slang.class); try { updateTestSuiteMappings(context.getBean(TestRunInfoService.class), testSuitesParallel, testSuitesSequential, testSuites, unspecifiedTestSuiteRunMode); registerEventHandlers(slang); List<RuntimeException> exceptions = new ArrayList<>(); SlangBuildResults buildResults = slangBuilder.buildSlangContent(projectPath, contentPath, testsPath, testSuites, shouldValidateDescription, shouldValidateCheckstyle, bulkRunMode, buildMode, changedFiles); exceptions.addAll(buildResults.getCompilationExceptions()); if (exceptions.size() > 0) { logErrors(exceptions, projectPath, loggingService); } IRunTestResults runTestsResults = buildResults.getRunTestsResults(); Map<String, TestRun> skippedTests = runTestsResults.getSkippedTests(); if (isNotEmpty(skippedTests)) { printSkippedTestsSummary(skippedTests, loggingService); } printPassedTests(runTestsResults, loggingService); if (shouldPrintCoverageData) { printTestCoverageData(runTestsResults, loggingService); } if (isNotEmpty(runTestsResults.getFailedTests())) { printBuildFailureSummary(projectPath, runTestsResults, loggingService); } else { printBuildSuccessSummary(contentPath, buildResults, runTestsResults, loggingService); } loggingService.waitForAllLogTasksToFinish(); generateTestCaseReport(context.getBean(SlangTestCaseRunReportGeneratorService.class), runTestsResults, testCaseReportLocation); System.exit(isNotEmpty(runTestsResults.getFailedTests()) ? 1 : 0); } catch (Throwable e) { logErrorsPrefix(loggingService); loggingService.logEvent(Level.ERROR, "Exception: " + e.getMessage()); logErrorsSuffix(projectPath, loggingService); loggingService.waitForAllLogTasksToFinish(); System.exit(1); } }
From source file:Utilities.java
public static void main(String[] args) { List list = Arrays.asList("one Two three Four five six one".split(" ")); System.out.println(list);/* w w w. j a v a2 s .c o m*/ System.out.println("max: " + Collections.max(list)); System.out.println("min: " + Collections.min(list)); AlphabeticComparator comp = new AlphabeticComparator(); System.out.println("max w/ comparator: " + Collections.max(list, comp)); System.out.println("min w/ comparator: " + Collections.min(list, comp)); List sublist = Arrays.asList("Four five six".split(" ")); System.out.println("indexOfSubList: " + Collections.indexOfSubList(list, sublist)); System.out.println("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist)); Collections.replaceAll(list, "one", "Yo"); System.out.println("replaceAll: " + list); Collections.reverse(list); System.out.println("reverse: " + list); Collections.rotate(list, 3); System.out.println("rotate: " + list); List source = Arrays.asList("in the matrix".split(" ")); Collections.copy(list, source); System.out.println("copy: " + list); Collections.swap(list, 0, list.size() - 1); System.out.println("swap: " + list); Collections.fill(list, "pop"); System.out.println("fill: " + list); List dups = Collections.nCopies(3, "snap"); System.out.println("dups: " + dups); // Getting an old-style Enumeration: Enumeration e = Collections.enumeration(dups); Vector v = new Vector(); while (e.hasMoreElements()) v.addElement(e.nextElement()); // Converting an old-style Vector // to a List via an Enumeration: ArrayList arrayList = Collections.list(v.elements()); System.out.println("arrayList: " + arrayList); }
From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file") .withDescription("Path to a single file").create('f'); Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir") .withDescription("A directory with image files in it").create('d'); Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h'); Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile") .withDescription(//from ww w.j av a2 s. com "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt") .create('p'); Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg() .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o'); Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json") .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j'); Option similarityFromFeatureVectorsOpt = OptionBuilder .withArgName("similarity from FeatureVectors directory") .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg() .withDescription("calculate similarity matrix from given directory of feature vectors").create('s'); Options options = new Options(); options.addOption(dirOpt); options.addOption(pathFileOpt); options.addOption(fileOpt); options.addOption(helpOpt); options.addOption(outputFileOpt); options.addOption(jsonOutputFlag); options.addOption(similarityFromFeatureVectorsOpt); // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String directoryPath = null; String pathFile = null; String singleFilePath = null; String similarityFromFeatureVectorsDirectory = null; ArrayList<Path> videoFiles = null; if (line.hasOption("dir")) { directoryPath = line.getOptionValue("dir"); } if (line.hasOption("pathfile")) { pathFile = line.getOptionValue("pathfile"); } if (line.hasOption("file")) { singleFilePath = line.getOptionValue("file"); } if (line.hasOption("outputfile")) { outputFile = line.getOptionValue("outputfile"); } if (line.hasOption("json")) { outputFormat = OUTPUT_FORMATS.JSON; } if (line.hasOption("similarityFromFeatureVectorsDirectory")) { similarityFromFeatureVectorsDirectory = line .getOptionValue("similarityFromFeatureVectorsDirectory"); } if (line.hasOption("help") || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0)) || (directoryPath != null && pathFile != null && !directoryPath.equals("") && !pathFile.equals(""))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pooled_time_series", options); System.exit(1); } if (directoryPath != null) { File dir = new File(directoryPath); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // When given a directory to load videos from we need to ensure that we // don't try to load the of.txt and hog.txt intermediate result files // that results from previous processing runs. if (!filePath.contains(".txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath); } if (pathFile != null) { Path list_file = Paths.get(pathFile); videoFiles = loadFiles(list_file); LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile); } if (singleFilePath != null) { Path singleFile = Paths.get(singleFilePath); LOG.info("Loaded file: " + singleFile); videoFiles = new ArrayList<Path>(1); videoFiles.add(singleFile); } if (similarityFromFeatureVectorsDirectory != null) { File dir = new File(similarityFromFeatureVectorsDirectory); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // We need to load only the *.of.txt and *.hog.txt values if (filePath.endsWith(".of.txt")) { videoFiles.add(file.toPath()); } if (filePath.endsWith(".hog.txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " feature vectors from " + similarityFromFeatureVectorsDirectory); evaluateSimilarity(videoFiles, 1); } else { evaluateSimilarity(videoFiles, 1); } LOG.info("done."); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } }
From source file:amie.keys.CSAKey.java
public static void main(String[] args) throws IOException, InterruptedException { final Triple<MiningAssistant, Float, String> parsedArgs = parseArguments(args); final Set<Rule> output = new LinkedHashSet<>(); // Helper object that contains the implementation for the calculation // of confidence and support // The file with the non-keys, one per line long timea = System.currentTimeMillis(); List<List<String>> inputNonKeys = Utilities.parseNonKeysFile(parsedArgs.third); System.out.println(inputNonKeys.size() + " input non-keys"); final List<List<String>> nonKeys = pruneBySupport(inputNonKeys, parsedArgs.second, parsedArgs.first.getKb());/* ww w . j a v a 2 s . co m*/ Collections.sort(nonKeys, new Comparator<List<String>>() { @Override public int compare(List<String> o1, List<String> o2) { int r = Integer.compare(o2.size(), o1.size()); if (r == 0) { return Integer.compare(o2.hashCode(), o1.hashCode()); } return r; } }); System.out.println(nonKeys.size() + " non-keys after pruning"); int totalLoad = computeLoad(nonKeys); System.out.println(totalLoad + " is the total load"); int nThreads = Runtime.getRuntime().availableProcessors(); //int batchSize = Math.max(Math.min(maxBatchSize, totalLoad / nThreads), minBatchSize); int batchSize = Math.max(Math.min(maxLoad, totalLoad / nThreads), minLoad); final Queue<int[]> chunks = new PriorityQueue(50, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o2[2], o1[2]); } }); final HashSet<HashSet<Integer>> nonKeysInt = new HashSet<>(); final HashMap<String, Integer> property2Id = new HashMap<>(); final HashMap<Integer, String> id2Property = new HashMap<>(); final List<Integer> propertiesList = new ArrayList<>(); int support = (int) parsedArgs.second.floatValue(); KB kb = parsedArgs.first.getKb(); buildDictionaries(nonKeys, nonKeysInt, property2Id, id2Property, propertiesList, support, kb); final List<HashSet<Integer>> nonKeysIntList = new ArrayList<>(nonKeysInt); int start = 0; int[] nextIdx = nextIndex(nonKeysIntList, 0, batchSize); int end = nextIdx[0]; int load = nextIdx[1]; while (start < nonKeysIntList.size()) { int[] chunk = new int[] { start, end, load }; chunks.add(chunk); start = end; nextIdx = nextIndex(nonKeysIntList, end, batchSize); end = nextIdx[0]; load = nextIdx[1]; } Thread[] threads = new Thread[Math.min(Runtime.getRuntime().availableProcessors(), chunks.size())]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(new Runnable() { @Override public void run() { while (true) { int[] chunk = null; synchronized (chunks) { if (!chunks.isEmpty()) { chunk = chunks.poll(); } else { break; } } System.out.println("Processing chunk " + Arrays.toString(chunk)); mine(parsedArgs, nonKeysIntList, property2Id, id2Property, propertiesList, chunk[0], chunk[1], output); } } }); threads[i].start(); } for (int i = 0; i < threads.length; ++i) { threads[i].join(); } long timeb = System.currentTimeMillis(); System.out.println("==== Unique C-keys ====="); for (Rule r : output) { System.out.println(Utilities.formatKey(r)); } System.out.println( "VICKEY found " + output.size() + " unique conditional keys in " + (timeb - timea) + " ms"); }
From source file:com.serena.rlc.provider.servicenow.client.ServiceNowClient.java
static public void main(String[] args) { ServiceNowClient snow = new ServiceNowClient(null, "http://localhost:9999", "v1", "itil", "itil"); ChangeRequest firstChangeRequest = null; ChangeTask firstChangeTask = null;// w w w . java 2 s . com Incident firstIncident = null; String titleFilter = "Java"; String query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE" + titleFilter; System.out.println("Retrieving ServiceNow Change Requests..."); List<ChangeRequest> changeRequests = null; try { changeRequests = snow.getChangeRequests(query, "New", 1); System.out.println("Found " + changeRequests.size() + " Change Requests"); for (ChangeRequest cr : changeRequests) { if (firstChangeRequest == null) firstChangeRequest = cr; System.out.println("Found Change Request: " + cr.getNumber()); System.out.println("Title: " + cr.getTitle()); System.out.println("Description: " + cr.getDescription()); System.out.println("State: " + cr.getState()); System.out.println("URL: " + cr.getUrl()); } } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { ChangeRequest cr = snow.getChangeRequestById(firstChangeRequest.getId()); System.out.println("Found Change Request: " + cr.getNumber()); System.out.println("Title: " + cr.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { ChangeRequest cr = snow.getChangeRequestByNumber(firstChangeRequest.getNumber()); System.out.println("Found Change Request: " + cr.getNumber()); System.out.println("Title: " + cr.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } System.out.println("Retrieving ServiceNow Change Tasks..."); titleFilter = "Install"; query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE" + titleFilter; List<ChangeTask> changeTasks = null; try { changeTasks = snow.getChangeTasks(query, firstChangeRequest.getNumber(), "Open", 10); System.out.println("Found " + changeTasks.size() + " Change Tasks"); for (ChangeTask ct : changeTasks) { if (firstChangeTask == null) firstChangeTask = ct; System.out.println("Found Change Task: " + ct.getNumber()); System.out.println("Title: " + ct.getTitle()); System.out.println("Description: " + ct.getDescription()); System.out.println("State: " + ct.getState()); System.out.println("URL: " + ct.getUrl()); } } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { ChangeTask ct = snow.getChangeTaskById(firstChangeTask.getId()); System.out.println("Found Change Task: " + ct.getNumber()); System.out.println("Title: " + ct.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { ChangeTask ct = snow.getChangeTaskByNumber(firstChangeTask.getNumber()); System.out.println("Found Change Task: " + ct.getNumber()); System.out.println("Title: " + ct.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } System.out.println("Retrieving ServiceNow Incidents..."); titleFilter = "password"; query = "short_descriptionLIKE" + titleFilter + "^ORdescriptionLIKE" + titleFilter + "^ORnumberLIKE" + titleFilter; List<Incident> incidents = null; try { incidents = snow.getIncidents(query, "Closed", 10); System.out.println("Found " + incidents.size() + " Incidents"); for (Incident i : incidents) { if (firstIncident == null) firstIncident = i; System.out.println("Found Incident: " + i.getNumber()); System.out.println("Title: " + i.getTitle()); System.out.println("Description: " + i.getDescription()); System.out.println("State: " + i.getState()); System.out.println("Type: " + i.getType()); System.out.println("URL: " + i.getUrl()); } } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { Incident inc = snow.getIncidentById(firstIncident.getId()); System.out.println("Found Incident: " + inc.getNumber()); System.out.println("Title: " + inc.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } try { Incident inc = snow.getIncidentByNumber(firstIncident.getNumber()); System.out.println("Found Incident: " + inc.getNumber()); System.out.println("Title: " + inc.getTitle()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } System.out.println("Creating Change Request"); String changeNumber = ""; String changeId = ""; try { ChangeRequest cr = snow.createChangeRequest("my cr", "its description", "Normal", "Software", "3 - Moderate", "High", "3 - Low"); System.out.println("Created Change Request: " + cr.getNumber()); System.out.println("Title: " + cr.getTitle()); System.out.println("Description: " + cr.getDescription()); System.out.println("State: " + cr.getState()); System.out.println("URL: " + cr.getUrl()); changeId = cr.getId(); changeNumber = cr.getNumber(); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } String approvalStatus = null; System.out.println("Checking Approval State of " + changeNumber); int pollCount = 0; while (pollCount < 100) { try { approvalStatus = snow.getChangeRequestApproval(changeNumber); System.out.println("Approval Status = " + approvalStatus); } catch (ServiceNowClientException e) { logger.debug("Error checking approval status ({}) - {}", changeNumber, e.getMessage()); } if (approvalStatus != null && (approvalStatus.equals("Approved") || approvalStatus.equals("Rejected"))) { break; } else { try { Thread.sleep(6000); } catch (InterruptedException e) { } } pollCount++; } if (approvalStatus != null && approvalStatus.equals("Approved")) { System.out.println("Change Request " + changeNumber + " has been approved"); } else { System.out.println( "Change Request " + changeNumber + " has been rejected or its status cannot be retrieved."); } System.out.println("Checking State of " + changeNumber); try { ChangeRequest cr = snow.getChangeRequestByNumber(changeNumber); System.out.println("Status = " + cr.getState()); cr = snow.setChangeRequestStatus(cr.getId(), "Closed"); System.out.println("Status = " + cr.getState()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } System.out.println("Creating Change Task"); String changeTaskNumber = ""; String changeTaskId = ""; try { ChangeTask ct = snow.createChangeTask(firstChangeRequest.getId(), "my ct", "its description", "1 - Critical", "3 - Low"); System.out.println("Created Change Task: " + ct.getNumber()); System.out.println("Title: " + ct.getTitle()); System.out.println("Description: " + ct.getDescription()); System.out.println("State: " + ct.getState()); System.out.println("URL: " + ct.getUrl()); changeTaskId = ct.getId(); changeTaskNumber = ct.getNumber(); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } System.out.println("Checking State of " + changeTaskNumber); try { ChangeTask ct = snow.getChangeTaskById(changeTaskId); System.out.println("Status = " + ct.getState()); ct = snow.setChangeTaskStatus(ct.getId(), "Closed Complete"); System.out.println("Status = " + ct.getState()); } catch (ServiceNowClientException e) { System.out.print(e.toString()); } }
From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java
/** * @param cmdArgs Arguments.// www . j ava 2s. com */ public static void main(String[] cmdArgs) { try { JFreeChartGraphPlotterArguments args = new JFreeChartGraphPlotterArguments(); JCommander jCommander = jcommander(cmdArgs, args, "<graph-plotter>"); if (args.help()) { jCommander.usage(); return; } if (args.inputFolders().isEmpty()) { errorHelp("Input folders are not defined."); return; } List<String> inFoldersAsString = args.inputFolders(); List<File> inFolders = new ArrayList<>(inFoldersAsString.size()); for (String folderAsString : inFoldersAsString) inFolders.add(new File(folderAsString).getAbsoluteFile()); for (File inFolder : inFolders) { if (!inFolder.exists()) { errorHelp("Folder does not exist: " + inFolder.getAbsolutePath()); return; } } List<List<List<File>>> benchFolders = new ArrayList<>(); for (File inFolder : inFolders) { File[] dirs0 = inFolder.listFiles(); if (dirs0 == null || dirs0.length == 0) continue; List<File> dirs = new ArrayList<>(Arrays.asList(dirs0)); Collections.sort(dirs, FILE_NAME_COMP); boolean multipleDrivers = false; for (File f : dirs) { if (f.isFile() && MULTIPLE_DRIVERS_MARKER_FILE.equals(f.getName())) { multipleDrivers = true; break; } } List<List<File>> mulDrvFiles = new ArrayList<>(); if (multipleDrivers) { for (File f : dirs) { List<File> files = getFiles(f); if (files != null) mulDrvFiles.add(files); } } else { List<File> files = getFiles(inFolder); if (files != null) mulDrvFiles.add(files); } benchFolders.add(mergeMultipleDriverLists(mulDrvFiles)); } if (benchFolders.isEmpty()) { errorHelp("Input folders are empty or have invalid structure: " + inFoldersAsString); return; } String outputFolder = outputFolder(inFolders); JFreeChartGenerationMode mode = args.generationMode(); if (mode == COMPOUND) processCompoundMode(outputFolder, benchFolders, args); else if (mode == COMPARISON) processComparisonMode(outputFolder, benchFolders, args); else if (mode == STANDARD) processStandardMode(benchFolders, args); else errorHelp("Unknown generation mode: " + args.generationMode()); } catch (ParameterException e) { errorHelp("Invalid parameter.", e); } catch (Exception e) { errorHelp("Failed to execute graph generator.", e); } }
From source file:org.openimaj.demos.sandbox.flickr.geo.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { final File inputcsv = new File("/Volumes/SSD/training_latlng"); final List<double[]> data = new ArrayList<double[]>(10000000); // read in images final BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line;/* w w w .j a v a2s. co m*/ int i = 0; br.readLine(); while ((line = br.readLine()) != null) { final String[] parts = line.split(" "); final double longitude = Double.parseDouble(parts[2]); final double latitude = Double.parseDouble(parts[1]); data.add(new double[] { longitude, latitude }); if (longitude >= -0.1 && longitude < 0 && latitude > 50 && latitude < 54) System.out.println(parts[0] + " " + latitude + " " + longitude); // if (i++ % 10000 == 0) // System.out.println(i); } br.close(); System.out.println("Done reading"); final float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = (float) data.get(i)[0]; dataArr[1][i] = (float) data.get(i)[1]; } final NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); final NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); final FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); final JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final ApplicationFrame frame = new ApplicationFrame("Title"); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); }
From source file:com.genentech.struchk.oeStruchk.OEStruchk.java
/** * Command line interface to {@link OEStruchk}. *//*from ww w. j a v a 2 s . com*/ public static void main(String[] args) throws ParseException, JDOMException, IOException { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion()); // create command line Options object Options options = new Options(); Option opt = new Option("f", true, "specify the configuration file name"); opt.setRequired(false); options.addOption(opt); opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file"); options.addOption(opt); opt = new Option("printRules", true, "Print HTML listing all the rules to filename."); options.addOption(opt); opt = new Option("errorsAsWarnings", false, "Treat errors as warnings."); options.addOption(opt); opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger."); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } URL confFile; if (cmd.hasOption("f")) { confFile = new File(cmd.getOptionValue("f")).toURI().toURL(); } else { confFile = getResourceURL(OEStruchk.class, "Struchk.xml"); } boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings"); if (cmd.hasOption("printRules")) { String fName = cmd.getOptionValue("printRules"); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName))); OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); structFlagAssigner.printRules(out); out.close(); return; } if (args.length < 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("oeStruck", options); throw new Error("missing input file\n"); } BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); StringBuilder mol = new StringBuilder(); StringBuilder data = new StringBuilder(); PrintStream out = System.out; if (args.length > 1) out = new PrintStream(args[1]); // create OEStruchk from config file OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings); Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)"); String line; boolean inMolFile = true; boolean atEnd = false; while (!atEnd) { if ((line = in.readLine()) == null) { if ("".equals(mol.toString().trim())) break; if (!inMolFile) throw new Error("Invalid end of sd file!"); line = "$$$$"; atEnd = true; } if (line.startsWith("$$$$")) { OEStruchk oeStruchk; StructureFlag sFlag = null; Matcher mat = sFlagPat.matcher(data); if (!mat.find()) { oeStruchk = structFlagAssigner; } else { oeStruchk = structFlagChecker; sFlag = StructureFlag.fromString(mat.group(1)); } if (!oeStruchk.applyRules(mol.toString(), null, sFlag)) nErrors++; out.print(oeStruchk.getTransformedMolfile(null)); out.print(data); if (!cmd.hasOption("noMsg")) { List<Message> msgs = oeStruchk.getStructureMessages(null); if (msgs.size() > 0) { nMessages += msgs.size(); out.println("> <errors_oe2>"); for (Message msg : msgs) out.printf("%s: %s\n", msg.getLevel(), msg.getText()); out.println(); } //System.err.println(oeStruchk.getTransformedMolfile("substance")); out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName()); out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null)); out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null)); out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent")); out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode()); out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(), oeStruchk.countStereoDBondStr()); } out.println(line); nStruct++; mol.setLength(0); data.setLength(0); inMolFile = true; } else if (!inMolFile || line.startsWith(">")) { inMolFile = false; data.append(line).append("\n"); } else { mol.append(line).append("\n"); } } structFlagAssigner.delete(); structFlagChecker.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); if (in != null) in.close(); } if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } }
From source file:edu.monash.merc.system.parser.xml.GPMWSXmlParser.java
public static void main(String[] art) throws Exception { GPMWSXmlParser parser = new GPMWSXmlParser(); String gpmFileName = "./testData/2012.9.23.gpm2tpb.xml"; List<GPMEntryBean> gpmEntryBeans = parser.parseGPMXml(gpmFileName, WSXmlInputFactory.getInputFactoryConfiguredForXmlConformance()); for (GPMEntryBean gpmEntryBean : gpmEntryBeans) { System.out.println("Db name: " + gpmEntryBean.getPrimaryDbSourceBean().getDbName() + " - ensg: " + gpmEntryBean.getGeneBean().getEnsgAccession()); PEEvidenceBean pemsProbEvidence = gpmEntryBean.getPeMsProbEvidenceBean(); System.out.println("PE MS Prob evidence: " + pemsProbEvidence.getEvidenceValue() + " color level: " + pemsProbEvidence.getColorLevel()); PEEvidenceBean pemsSamplesEvidence = gpmEntryBean.getPeMsSamplesEvidenceBean(); System.out.println("PE MS Samples Evidence: " + pemsSamplesEvidence.getEvidenceValue() + " color level: " + pemsSamplesEvidence.getColorLevel()); }/*from w w w . j a v a 2s . c o m*/ System.out.println("================== total size: " + gpmEntryBeans.size()); }
From source file:com.yobidrive.diskmap.DiskMapManager.java
public static void main(String[] args) { try {/*from w ww.j a v a2s. c om*/ BasicConfigurator.configure(); // (String storeName, String logPath, String keyPath, long ckeckPointPeriod, long logSize, int keySize, // long mapSize, int packInterval, int readThreads, long needleCachedEntries, long bucketCachedBytes, short nodeId) /* String path = "/Users/david/Documents/NEEDLES"; if ( args.length > 0) { path = args[0]; } System.out.println("Using directory:" + path); */ DiskMapManager dmm = new DiskMapManager("TestStore", "/drive_hd1", "/drive_ssd/storage_indexes", 1000, // Synching period 60000 * 5, // Checkpointing period 2000000000L, // Log file size 100, // Key max size 2048, // Nb of buffers 32768, // Nb of entries (buckets) per buffer 60, // Compact interval 8, // Read threads TEST_COUNT / 3 * 2 * 140, // NeedleHeaderCachedEntries (1/20 in cache, 1/2 of typical data set) TEST_COUNT / 3 * 2 * 140, // NeedleCachedBytes (3% of Map, weights 120 bytes/entry) true, // Use needle average age instead of needle yougest age (short) 0, (short) 0, 0, new TokenSynchronizer(1), new TokenSynchronizer(1), null); // dmm.getBtm().getCheckPoint().copyFrom(new NeedlePointer()) ; // Removes checkpoint // System.out.println("Start read for "+TEST_COUNT+" pointers") ; Date startDate = new Date(); Date lapDate = new Date(); System.out.println("Start read test for " + TEST_COUNT + " pointers"); long counter = 0; long lapCounter = 0; startDate = new Date(); lapDate = new Date(); long failCount = 0; counter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; List<Versioned<byte[]>> values = dmm.get(key.getBytes("UTF-8")); if (values.size() <= 0) { failCount++; } else { // Gets previous version byte[] value = values.get(0).getValue(); if (value == null) failCount++; else if (value[0] != (byte) ((short) counter % 128)) failCount++; } counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print(".") ; } else // System.out.print("*") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } long timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n" + "\tBad results: " + failCount); startDate = new Date(); lapDate = new Date(); System.out.println("Start write test for " + TEST_COUNT + " pointers"); counter = 0; lapCounter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; byte[] value = new byte[128000]; value[0] = (byte) ((short) counter % 128); long chaseDurer = new Date().getTime(); List<Versioned<byte[]>> previousValues = dmm.get(key.getBytes("UTF-8")); long chaseDurer2 = new Date().getTime(); // System.out.println("Get in "+(chaseDurer2 -chaseDurer)+"ms") ; chaseDurer = chaseDurer2; Version newVersion = null; if (previousValues.size() <= 0) { newVersion = new VectorClock(); } else { // Gets previous version newVersion = previousValues.get(0).cloneVersioned().getVersion(); } // Increment version before writing ((VectorClock) newVersion).incrementVersion(dmm.getNodeId(), new Date().getTime()); dmm.put(key.getBytes("UTF-8"), value, newVersion); chaseDurer2 = new Date().getTime(); // System.out.println("Put in "+(chaseDurer2 -chaseDurer)+"ms") ; // dmm.putValue(key.getBytes("UTF-8"), value) ; counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPS)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print("("+counter+")") ; } else // System.out.print("["+counter+"]") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nWriting before cache commit of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps"); System.out.println("Start read for " + TEST_COUNT + " pointers"); startDate = new Date(); lapDate = new Date(); failCount = 0; counter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; List<Versioned<byte[]>> values = dmm.get(key.getBytes("UTF-8")); if (values.size() <= 0) { failCount++; } else { // Gets previous version byte[] value = values.get(0).getValue(); if (value == null) failCount++; else if (value[0] != (byte) ((short) counter % 128)) failCount++; } counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print(".") ; } else // System.out.print("*") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n" + "\tBad results: " + failCount); dmm.stopService(); System.out.println("Max cycle time = " + (dmm.getBtm().getMaxCycleTimePass1() + dmm.getBtm().getMaxCycleTimePass2())); } catch (Throwable th) { th.printStackTrace(); } }