List of usage examples for java.lang String split
public String[] split(String regex)
From source file:TestReadCustData.java
public static void main(String[] args) { AgentLoader.loadAgentFromClasspath("avaje-ebeanorm-agent", "debug=1"); List<Customer> lCust = new ArrayList<>(); try {//w w w . j a va2 s . co m List<String> s = Files.readAllLines(Paths.get("customer.txt"), Charsets.ISO_8859_1); for (String s1 : s) { if (!s1.startsWith("GRUP")) { Customer c = new Customer(); try { c.setId(Long.parseLong(s1.split("~")[3])); } catch (ArrayIndexOutOfBoundsException arrex) { c.setId(Long.parseLong(s1.split("~")[3])); } try { c.setNama(s1.split("~")[4]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setNama(""); } try { c.setShipto(s1.split("~")[9]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setShipto(""); } try { c.setKota(s1.split("~")[12]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setKota(""); } try { c.setProvinsi(s1.split("~")[13]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setProvinsi(""); } try { c.setKodePos(s1.split("~")[14]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setKodePos(""); } try { c.setNamaArea(s1.split("~")[2]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setNamaArea(""); } try { c.setDKLK(s1.split("~")[15]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setDKLK(""); } try { c.setCreditLimit(Long.parseLong(s1.split("~")[16])); } catch (ArrayIndexOutOfBoundsException arrex) { c.setCreditLimit(new Long(0)); } try { c.setNpwp(s1.split("~")[11]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setNpwp(""); } try { c.setNamaWajibPajak(s1.split("~")[10]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setNamaWajibPajak(""); } try { c.setCreationDate(s1.split("~")[6]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setCreationDate(""); } try { c.setLastUpdateBy(s1.split("~")[17]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setLastUpdateBy(""); } try { c.setLastUpdateDate(s1.split("~")[18]); } catch (ArrayIndexOutOfBoundsException arrex) { c.setLastUpdateDate(""); } lCust.add(c); } } for (Customer c : lCust) { Customer cc = Ebean.find(Customer.class, c.getId()); if (cc != null) { cc = c; Ebean.update(cc); } System.out.print(c.getId()); System.out.print(" | "); System.out.print(c.getNama()); System.out.print(" | "); System.out.print(c.getShipto()); System.out.print(" | "); System.out.print(c.getNpwp()); System.out.print(" | "); System.out.print(c.getNamaWajibPajak()); System.out.println(); } } catch (IOException ex) { Logger.getLogger(TestReadCustData.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.openimaj.demos.sandbox.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { File inputcsv = new File("/Users/jsh2/Desktop/world-geo.csv"); List<float[]> data = new ArrayList<float[]>(10000000); //read in images BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line; int i = 0;//from w w w.j a va2 s. c om while ((line = br.readLine()) != null) { String[] parts = line.split(","); float longitude = Float.parseFloat(parts[0]); float latitude = Float.parseFloat(parts[1]); data.add(new float[] { longitude, latitude }); if (i++ % 10000 == 0) System.out.println(i); } System.out.println("Done reading"); float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = data.get(i)[0]; dataArr[1][i] = data.get(i)[1]; } NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 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.joliciel.talismane.TalismaneMain.java
public static void main(String[] args) throws Exception { Map<String, String> argsMap = StringUtils.convertArgs(args); OtherCommand otherCommand = null;/*from w w w.j av a 2s. c o m*/ if (argsMap.containsKey("command")) { try { otherCommand = OtherCommand.valueOf(argsMap.get("command")); argsMap.remove("command"); } catch (IllegalArgumentException e) { // not anotherCommand } } String sessionId = ""; TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId); TalismaneService talismaneService = locator.getTalismaneService(); TalismaneSession talismaneSession = talismaneService.getTalismaneSession(); if (otherCommand == null) { // regular command TalismaneConfig config = talismaneService.getTalismaneConfig(argsMap, sessionId); if (config.getCommand() == null) return; Talismane talismane = config.getTalismane(); talismane.process(); } else { // other command String logConfigPath = argsMap.get("logConfigFile"); if (logConfigPath != null) { argsMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } switch (otherCommand) { case serializeLexicon: { LexiconSerializer serializer = new LexiconSerializer(); serializer.serializeLexicons(argsMap); break; } case testLexicon: { String lexiconFilePath = null; String[] wordList = null; for (String argName : argsMap.keySet()) { String argValue = argsMap.get(argName); if (argName.equals("lexicon")) { lexiconFilePath = argValue; } else if (argName.equals("words")) { wordList = argValue.split(","); } else { throw new TalismaneException("Unknown argument: " + argName); } } File lexiconFile = new File(lexiconFilePath); LexiconDeserializer lexiconDeserializer = new LexiconDeserializer(talismaneSession); List<PosTaggerLexicon> lexicons = lexiconDeserializer.deserializeLexicons(lexiconFile); for (PosTaggerLexicon lexicon : lexicons) talismaneSession.addLexicon(lexicon); PosTaggerLexicon mergedLexicon = talismaneSession.getMergedLexicon(); for (String word : wordList) { LOG.info("################"); LOG.info("Word: " + word); List<LexicalEntry> entries = mergedLexicon.getEntries(word); for (LexicalEntry entry : entries) { LOG.info(entry + ", Full morph: " + entry.getMorphologyForCoNLL()); } } break; } } } }
From source file:com.github.projectflink.testPlan.KryoTest.java
public static void main(String[] args) throws Exception { // set up the execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); // get input data DataSet<String> text = env.readTextFile(args[0]); boolean kryoMode = false; if (args[1].equals("kryo")) { kryoMode = true;// w ww .j a va 2s .c o m DataSet<KryoType> ds = text.map(new MapFunction<String, KryoType>() { @Override public KryoType map(String s) throws Exception { KryoType kt = new KryoType(); kt.elements = new ArrayList<Object>(); String[] splits = s.split(" "); for (String split : splits) { if (split == null || split.length() == 0) continue; if (StringUtils.isNumeric(split)) { try { kt.elements.add(Integer.valueOf(split)); } catch (Throwable t) { kt.elements.add(Integer.valueOf(0)); } } else { kt.elements.add(split); } } return kt; } }); DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance() .map(new MapFunction<KryoType, Tuple2<Object, Integer>>() { @Override public Tuple2<Object, Integer> map(KryoType valueType) throws Exception { return new Tuple2<Object, Integer>(valueType.elements.iterator().next(), valueType.elements.size()); } }); ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>()); } else { DataSet<ValueType> ds = text.map(new MapFunction<String, ValueType>() { @Override public ValueType map(String s) throws Exception { ValueType vt = new ValueType(); vt.elements = new ArrayList<Object>(); String[] splits = s.split(" "); for (String split : splits) { if (split == null || split.length() == 0) continue; if (StringUtils.isNumeric(split)) { try { vt.elements.add(Integer.valueOf(split)); } catch (Throwable t) { vt.elements.add(Integer.valueOf(0)); } } else { vt.elements.add(split); } } return vt; } }); DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance() .map(new MapFunction<ValueType, Tuple2<Object, Integer>>() { @Override public Tuple2<Object, Integer> map(ValueType valueType) throws Exception { return new Tuple2<Object, Integer>(valueType.elements.iterator().next(), valueType.elements.size()); } }); ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>()); } // execute program env.execute("KryoTest kryoMode=" + kryoMode); }
From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalWriter.java
public static void main(String[] args) throws SOMToolboxException, IOException { // register and parse all options JSAPResult config = OptionFactory.parseResults(args, OPTIONS); File inputVectorFile = config.getFile("inputVectorFile"); String outputDirStr = AbstractOptionFactory.getFilePath(config, "outputDirectory"); File outputDirBase = new File(outputDirStr); outputDirBase.mkdirs();/* ww w . jav a 2 s . co m*/ String metricName = config.getString("metric"); DistanceMetric metric = AbstractMetric.instantiateNice(metricName); int neighbours = config.getInt("numberNeighbours"); int startIndex = config.getInt("startIndex"); int numberItems = config.getInt("numberItems", -1); try { SOMLibSparseInputData data = new SOMLibSparseInputData(inputVectorFile.getAbsolutePath()); int endIndex = data.numVectors(); if (numberItems != -1) { if (startIndex + numberItems > endIndex) { System.out.println("Specified number of items (" + numberItems + ") exceeds maximum (" + data.numVectors() + "), limiting to " + (endIndex - startIndex) + "."); } else { endIndex = startIndex + numberItems; } } StdErrProgressWriter progress = new StdErrProgressWriter(endIndex - startIndex, "processing vector "); // SortedSet<InputDistance> distances; for (int inputDatumIndex = startIndex; inputDatumIndex < endIndex; inputDatumIndex++) { InputDatum inputDatum = data.getInputDatum(inputDatumIndex); String inputLabel = inputDatum.getLabel(); if (inputDatumIndex == -1) { throw new IllegalArgumentException( "Input with label '" + inputLabel + "' not found in vector file '" + inputVectorFile + "'; possible labels are: " + StringUtils.toString(data.getLabels(), 15)); } File outputDir = new File(outputDirBase, inputLabel.charAt(2) + "/" + inputLabel.charAt(3) + "/" + inputLabel.charAt(4)); outputDir.mkdirs(); File outputFile = new File(outputDir, inputLabel + ".txt"); boolean fileExistsAndValid = false; if (outputFile.exists()) { // check if it the valid data String linesInvalid = ""; int validLineCount = 0; ArrayList<String> lines = FileUtils.readLinesAsList(outputFile.getAbsolutePath()); for (String string : lines) { if (string.trim().length() == 0) { continue; } String[] parts = string.split("\t"); if (parts.length != 2) { linesInvalid += "Line '" + string + "' invalid - contains " + parts.length + " elements.\n"; } else if (!NumberUtils.isNumber(parts[1])) { linesInvalid = "Line '" + string + "' invalid - 2nd part is not a number.\n"; } else { validLineCount++; } } if (validLineCount != neighbours) { linesInvalid = "Not enough valid lines; expected " + neighbours + ", found " + validLineCount + ".\n"; } fileExistsAndValid = true; if (org.apache.commons.lang.StringUtils.isNotBlank(linesInvalid)) { System.out.println("File " + outputFile.getAbsolutePath() + " exists, but is not valid:\n" + linesInvalid); } } if (fileExistsAndValid) { Logger.getLogger("at.tuwien.ifs.feature.evaluation").finer( "File " + outputFile.getAbsolutePath() + " exists and is valid; not recomputing"); } else { PrintWriter p = new PrintWriter(outputFile); SmallestElementSet<InputDistance> distances = data.getNearestDistances(inputDatumIndex, neighbours, metric); for (InputDistance inputDistance : distances) { p.println(inputDistance.getInput().getLabel() + "\t" + inputDistance.getDistance()); } p.close(); } progress.progress(); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage() + ". Aborting."); System.exit(-1); } }
From source file:Split.java
public static void main(String args[]) { String statement = "I will not compromise. I will not " + "cooperate. There will be no concession, no conciliation, no " + "finding the middle group, and no give and take."; String tokens[] = null;//from ww w. j a va 2s . c o m String splitPattern = "compromise|cooperate|concession|" + "conciliation|(finding the middle group)|(give and take)"; tokens = statement.split(splitPattern); System.out.println("REGEX PATTERN:\n" + splitPattern + "\n"); System.out.println("STATEMENT:\n" + statement + "\n"); System.out.println("\nTOKENS"); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } }
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args/*w w w . j a v a 2s. c o m*/ */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }
From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java
public static void main(String args[]) throws IOException { CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger(); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a")); commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file") .isRequired().withLongOpt("output").create("o")); CommandLine commandLine = null;//from w ww .j a v a2 s . c om try { commandLine = commandLineWithLogger.getCommandLine(args); PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps()); } catch (Exception e) { System.exit(1); } String wikiIDFileName = commandLine.getOptionValue("wikidata-id"); String airpediaFileName = commandLine.getOptionValue("airpedia"); String outputFileName = commandLine.getOptionValue("output"); HashMap<Integer, String> wikiIDs = new HashMap<>(); HashSet<Integer> airpediaClasses = new HashSet<>(); List<String> strings; logger.info("Loading file " + wikiIDFileName); strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } wikiIDs.put(id, parts[1]); } logger.info("Loading file " + airpediaFileName); strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8); for (String line : strings) { line = line.trim(); if (line.length() == 0) { continue; } if (line.startsWith("#")) { continue; } String[] parts = line.split("\t"); if (parts.length < 2) { continue; } int id; try { id = Integer.parseInt(parts[0]); } catch (Exception e) { continue; } airpediaClasses.add(id); } logger.info("Saving information"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); for (int i : wikiIDs.keySet()) { if (!airpediaClasses.contains(i)) { continue; } writer.append(wikiIDs.get(i)).append("\n"); } writer.close(); }
From source file:EVT.java
/** * @param args//from w w w . j a va2 s . c om */ public static void main(final String[] args) throws MalformedURLException { try { URL url = new EVT().getClass().getClassLoader().getResource("general.properties"); config = new PropertiesConfiguration(url); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } final Map parameters = parseParameters(args); if (parameters.containsKey("-v")) verboseMode = 1; if (parameters.containsKey("-V") || parameters.containsKey("-vv")) verboseMode = 2; //the from version and the to version must be put in property file String supportedVersions = PropertiesUtil.concatenatePropsValues(config, ALFRESCO_VERSION, ","); List<String> supportedVersionsList = Arrays.asList(supportedVersions.split(",")); String alfrescoVersion = (String) parameters.get(ALFRESCO_VERSION); boolean supportedVersion = (alfrescoVersion != null) && supportedVersionsList.contains(alfrescoVersion); System.out.println( "\nAlfresco Environment Validation Tool (for Alfresco Enterprise " + supportedVersions + ")"); System.out.println("------------------------------------------------------------------"); if (parameters.isEmpty() || parameters.containsKey("-?") || parameters.containsKey("--help") || parameters.containsKey("/?") || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_TYPE) || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_HOSTNAME) || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_LOGIN) || !parameters.containsKey(ALFRESCO_VERSION) || !parameters.containsKey(IndexDiskSpeedValidator.PARAMETER_DISK_LOCATION)) { System.out.println(""); System.out.println("usage: evt[.sh|.cmd] [-?|--help] [-v] [-V|-vv]"); System.out.println(" -a alfrescoversion -t databaseType -h databaseHost [-r databasePort]"); System.out.println( " [-d databaseName] -l databaseLogin [-p databasePassword] -i indexlocation"); System.out.println(""); System.out.println("where: -?|--help - display this help"); System.out.println(" -v - produce verbose output"); System.out.println(" -V|-vv - produce super-verbose output (stack traces)"); System.out.println( " alfrescoversion - Version for which the verification is made . May be one of:"); System.out.println( " 4.0.0,4.0.1,4.0.2,4.1.1,4.1.2,4.1.3,4.1.4,4.1.5,4.1.6,4.2"); System.out.println(" databaseType - the type of database. May be one of:"); System.out.println(" mysql, postgresql, oracle, mssqlserver, db2"); System.out.println(" databaseHost - the hostname of the database server"); System.out.println(" databasePort - the port the database is listening on (optional -"); System.out.println(" defaults to default for the database type)"); System.out.println(" databaseName - the name of the Alfresco database (optional -"); System.out.println(" defaults to 'alfresco')"); System.out.println(" databaseLogin - the login Alfresco will use to connect to the"); System.out.println(" database"); System.out.println(" databasePassword - the password for that user (optional)"); System.out.println( " indexlocation - a path to a folder that will contain Alfresco indexes"); System.out.println(""); System.out.println("The tool must be run as the OS user that Alfreso will run as. In particular"); System.out.println("it will report erroneous results if run as \"root\" (or equivalent on other"); System.out.println("OSes) if Alfresco is not intended to be run as that user."); System.out.println(""); } else if (!supportedVersion) { System.out.println(""); System.out.println("Version " + alfrescoVersion + " is not in the list of the Alfresco versions supported by this tool."); System.out.println("Please specify one of the following versions: " + supportedVersions); } else { final StdoutValidatorCallback callback = new StdoutValidatorCallback(); (new AllValidators()).validate(parameters, callback); System.out.println("\n\n **** FINAL GRADE: " + TestResult.typeToString(callback.worstResult) + " ****\n"); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];//from w ww.j a va 2s . c o m File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // we will process only a subset first List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); for (File file : files) { allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file)); } // collect turkers and csv List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs); String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs); // save CSV and run MACE Path tmpDir = Files.createTempDirectory("mace"); File maceInputFile = new File(tmpDir.toFile(), "input.csv"); FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8"); File outputPredictions = new File(tmpDir.toFile(), "predictions.txt"); File outputCompetence = new File(tmpDir.toFile(), "competence.txt"); // run MACE MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts", "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence", outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() }); // read back the predictions and competence List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8"); // check the output if (predictions.size() != allArgumentPairs.size()) { throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size() + " lines but was " + predictions.size()); } String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8"); String[] competence = competenceRaw.split("\t"); if (competence.length != turkerIDs.size()) { throw new IllegalStateException( "Expected " + turkerIDs.size() + " competence number, got " + competence.length); } // rank turkers by competence Map<String, Double> turkerIDCompetenceMap = new TreeMap<>(); for (int i = 0; i < turkerIDs.size(); i++) { turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i])); } // sort by value descending Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false); System.out.println("Sorted turker competences: " + sortedCompetences); // assign the gold label and competence for (int i = 0; i < allArgumentPairs.size(); i++) { AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i); String goldLabel = predictions.get(i).trim(); // might be empty if (!goldLabel.isEmpty()) { // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only the gold label annotatedArgumentPair.setGoldLabel(goldLabel); } // update turker competence for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String turkID = assignment.getTurkID(); int turkRank = getTurkerRank(turkID, sortedCompetences); assignment.setTurkRank(turkRank); double turkCompetence = turkerIDCompetenceMap.get(turkID); assignment.setTurkCompetence(turkCompetence); } } // now sort the data back according to their original file name Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>(); for (AnnotatedArgumentPair argumentPair : allArgumentPairs) { String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(), argumentPair.getArg1().getStance()); if (!fileNameAnnotatedPairsMap.containsKey(fileName)) { fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>()); } fileNameAnnotatedPairsMap.get(fileName).add(argumentPair); } // and save them to the output file for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) { String fileName = entry.getKey(); List<AnnotatedArgumentPair> argumentPairs = entry.getValue(); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); } }