List of usage examples for com.google.common.io Files write
public static void write(CharSequence from, File to, Charset charset) throws IOException
From source file:org.joda.railmodel.Crossrail2SwirlNorthernSWLondonModel.java
public static void main(String[] args) throws Exception { Crossrail2SwirlNorthernSWLondonModel model = new Crossrail2SwirlNorthernSWLondonModel(); ImmutableList<Station> starts = ImmutableList.of(CSS, LHD, EPS, SNL, WCP, MOT, SHP, FLW, KNG, HMC, SUR, NEM, RAY, WIM, EAD, UMD, USW, UTB, BAL, SRH, STE); ImmutableList<Station> ends = ImmutableList.of(VIC, TCR, EUS, AGL, WAT, UGP, UOX, BDS, CHX, ULS, UGS, UWS, UBS, UWM, UTM, ZFD, UBH, LBG, UBK, MOG, UOS, UHL, UCL, USP, CWF); List<String> output = new ArrayList<>(); output.add("Modelling for SW London with Crossrail 2 Swirl plus Northern Line extension" + NEWLINE); output.add("===========================================================================" + NEWLINE); output.add(/*from w w w . ja v a 2 s .com*/ "This uses CR2 via Earlsfield based on the [Swirl plan](http://ukrail.blogspot.co.uk/2015/11/crossrail-2-swirl.html)," + " with best efforts guesses of interchange times." + NEWLINE); output.add("It then changes Chelsea to Battersea Power, and adds a Northern Line extension from " + "Battersea Power to Balham with one intermediate stop." + NEWLINE); output.add("Trains from Morden run via Battersea Power to the West End." + NEWLINE); output.add("Trains from Balham run via Stockwell to the City." + NEWLINE); output.add(NEWLINE); appendDocs(output); appendTotals(output, starts, ends, model); appendSeparator(output); for (Iterator<Station> it = starts.iterator(); it.hasNext();) { Station start = it.next(); for (Station end : ends) { String explain = model.explain(start, end); output.add(explain); output.add(NEWLINE); } if (it.hasNext()) { appendSeparator(output); } } appendStations(output); output.add(NEWLINE); output.add("Feel free to send a pull request for errors and enhancments!" + NEWLINE); File file = new File("CR2-SwirlNorthern-SWLondon.md"); String result = Joiner.on("").join(output); Files.write(result, file, StandardCharsets.UTF_8); System.out.println(result); }
From source file:com.music.tools.SongDBDownloader.java
public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); // HttpHost proxy = new HttpHost("localhost", 8888); // client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpContext ctx = new BasicHttpContext(); HttpUriRequest req = new HttpGet( "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand"); client.execute(req, ctx);/*ww w . java 2s . c o m*/ req.abort(); List<String> urls = getSongUrls( "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1", client, ctx); List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size()); for (String songUrl : urls) { paramsList.addAll(getSongParams(songUrl, client, ctx)); } int i = 0; for (List<? extends NameValuePair> params : paramsList) { HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML"); request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1"); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.setHeader("Accept-Encoding", "gzip, deflate"); request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3"); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setHeader("Origin", "http://www.hooktheory.com"); request.setHeader("Referer", URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8")); HttpEntity entity = new UrlEncodedFormEntity(params); request.setEntity(entity); try { HttpResponse response = client.execute(request, ctx); if (response.getStatusLine().getStatusCode() == 200) { InputStream is = response.getEntity().getContent(); String xml = CharStreams.toString(new InputStreamReader(is)); is.close(); Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8")); } else { System.out.println(response.getStatusLine()); System.out.println(params); } i++; request.abort(); } catch (Exception ex) { System.out.println(params); ex.printStackTrace(); } } }
From source file:org.dllearner.algorithms.qtl.experiments.Diagrams.java
public static void main(String[] args) throws Exception { File dir = new File(args[0]); dir.mkdirs();/*from ww w . j a va 2 s . c om*/ Properties config = new Properties(); config.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("org/dllearner/algorithms/qtl/qtl-eval-config.properties")); String url = config.getProperty("url"); String username = config.getProperty("username"); String password = config.getProperty("password"); Class.forName("com.mysql.jdbc.Driver").newInstance(); // url = "jdbc:mysql://address=(protocol=tcp)(host=[2001:638:902:2010:0:168:35:138])(port=3306)(user=root)/qtl"; Connection conn = DriverManager.getConnection(url, username, password); int[] nrOfExamplesIntervals = { 5, 10, // 15, 20, // 25, 30 }; double[] noiseIntervals = { 0.0, 0.1, 0.2, 0.3, // 0.4, // 0.6 }; Map<HeuristicType, String> measure2ColumnName = Maps.newHashMap(); measure2ColumnName.put(HeuristicType.FMEASURE, "avg_fscore_best_returned"); measure2ColumnName.put(HeuristicType.PRED_ACC, "avg_predacc_best_returned"); measure2ColumnName.put(HeuristicType.MATTHEWS_CORRELATION, "avg_mathcorr_best_returned"); HeuristicType[] measures = { HeuristicType.PRED_ACC, HeuristicType.FMEASURE, HeuristicType.MATTHEWS_CORRELATION }; String[] labels = { "A_1", "F_1", "MCC" }; // get distinct noise intervals // |E| vs fscore String sql = "SELECT nrOfExamples,%s from eval_overall WHERE heuristic_measure = ? && noise = ? ORDER BY nrOfExamples"; PreparedStatement ps; for (double noise : noiseIntervals) { String s = ""; s += "\t"; s += Joiner.on("\t").join(Ints.asList(nrOfExamplesIntervals)); s += "\n"; for (HeuristicType measure : measures) { ps = conn.prepareStatement(String.format(sql, measure2ColumnName.get(measure))); ps.setString(1, measure.toString()); ps.setDouble(2, noise); ResultSet rs = ps.executeQuery(); s += measure; while (rs.next()) { int nrOfExamples = rs.getInt(1); double avgFscore = rs.getDouble(2); s += "\t" + avgFscore; } s += "\n"; } Files.write(s, new File(dir, "examplesVsScore-" + noise + ".tsv"), Charsets.UTF_8); } // noise vs fscore sql = "SELECT noise,%s from eval_overall WHERE heuristic_measure = ? && nrOfExamples = ?"; NavigableMap<Integer, Map<HeuristicType, double[][]>> input = new TreeMap<>(); for (int nrOfExamples : nrOfExamplesIntervals) { String s = ""; s += "\t"; s += Joiner.on("\t").join(Doubles.asList(noiseIntervals)); s += "\n"; String gnuplot = ""; // F-score ps = conn.prepareStatement( "SELECT noise,avg_fscore_best_returned from eval_overall WHERE heuristic_measure = 'FMEASURE' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); ResultSet rs = ps.executeQuery(); gnuplot += "\"F_1\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } // precision gnuplot += "\n\n"; ps = conn.prepareStatement( "SELECT noise,avg_precision_best_returned from eval_overall WHERE heuristic_measure = 'FMEASURE' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); rs = ps.executeQuery(); gnuplot += "\"precision\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } // recall gnuplot += "\n\n"; ps = conn.prepareStatement( "SELECT noise,avg_recall_best_returned from eval_overall WHERE heuristic_measure = 'FMEASURE' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); rs = ps.executeQuery(); gnuplot += "\"recall\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } // MCC gnuplot += "\n\n"; ps = conn.prepareStatement( "SELECT noise,avg_mathcorr_best_returned from eval_overall WHERE heuristic_measure = 'MATTHEWS_CORRELATION' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); rs = ps.executeQuery(); gnuplot += "\"MCC\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } // baseline F-score gnuplot += "\n\n"; ps = conn.prepareStatement( "SELECT noise,avg_fscore_baseline from eval_overall WHERE heuristic_measure = 'FMEASURE' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); rs = ps.executeQuery(); gnuplot += "\"baseline F_1\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } // baseline MCC gnuplot += "\n\n"; ps = conn.prepareStatement( "SELECT noise,avg_mathcorr_baseline from eval_overall WHERE heuristic_measure = 'MATTHEWS_CORRELATION' && nrOfExamples = ?"); ps.setInt(1, nrOfExamples); rs = ps.executeQuery(); gnuplot += "\"baseline MCC\"\n"; while (rs.next()) { double noise = rs.getDouble(1); double avgFscore = rs.getDouble(2); gnuplot += noise + "," + avgFscore + "\n"; } Files.write(gnuplot.trim(), new File(dir, "noiseVsScore-" + nrOfExamples + ".dat"), Charsets.UTF_8); } if (!input.isEmpty()) { // plotNoiseVsFscore(input); } }
From source file:org.joda.railmodel.CurrentSWLondonModel.java
public static void main(String[] args) throws Exception { CurrentSWLondonModel model = MODEL;/*w w w . ja v a2 s . co m*/ ImmutableList<Station> starts = ImmutableList.of(CSS, LHD, EPS, SNL, WCP, MOT, SHP, FLW, KNG, HMC, SUR, NEM, RAY, WIM, EAD, UMD, USW, UTB, BAL, SRH, STE); ImmutableList<Station> ends = ImmutableList.of(VIC, TCR, EUS, AGL, WAT, UGP, UOX, BDS, CHX, ULS, UGS, UWS, UBS, UWM, UTM, ZFD, UBH, LBG, UBK, MOG, UOS, UHL, UCL, USP, CWF); List<String> output = new ArrayList<>(); output.add("Modelling for SW London without Crossrail 2" + NEWLINE); output.add("===========================================" + NEWLINE); output.add("This uses best efforts guesses of interchange times." + NEWLINE); output.add(NEWLINE); output.add( "A selection of interesting journeys is listed, together with calculated route options." + NEWLINE); output.add("A key for station codes is at the end." + NEWLINE); output.add("The route options are sorted, with the fastest first." + NEWLINE); output.add("The excess over the fastest route option is listed in brackets." + NEWLINE); output.add("If the fastest route is direct, then only limited alternatives are shown." + NEWLINE); output.add("No alternative that takes over 15 minutes longer is shown." + NEWLINE); output.add("The number of trains per hour (tph) is also shown." + NEWLINE); output.add(NEWLINE); output.add("Station entry/exit times, buses and walking times are not included." + NEWLINE); output.add("Walking may affect the faster route on occasion." + NEWLINE); output.add(NEWLINE); output.add("The 'effective time' adds some fudge factors to take into account low frequency " + "start service and an additional penalty per interchange. It is intended to be used as a rough metric " + "of what a more typical journey would be like (ie. a non-perfect one)." + NEWLINE); output.add("The 'total effective time' is the sum of all effective times modelled." + NEWLINE); output.add("It is a reasonable proxy for the total enhancement provided by the scheme." + NEWLINE); output.add(NEWLINE); output.add("Total effective times" + NEWLINE); output.add("---------------------" + NEWLINE); int totalTotal = 0; for (Iterator<Station> it = starts.iterator(); it.hasNext();) { Station start = it.next(); int totalPoints = 0; for (Station end : ends) { totalPoints += model.solve(start, end).points(); } totalTotal += totalPoints; output.add("From " + start.description() + ": " + totalPoints + NEWLINE); } output.add("TOTAL: " + totalTotal + NEWLINE); appendSeparator(output); for (Iterator<Station> it = starts.iterator(); it.hasNext();) { Station start = it.next(); for (Station end : ends) { String explain = model.explain(start, end); output.add(explain); output.add(NEWLINE); } if (it.hasNext()) { appendSeparator(output); } } appendSeparator(output); appendStations(output); output.add(NEWLINE); output.add("Feel free to send a pull request for errors and enhancments!" + NEWLINE); File file = new File("SWLondon.md"); String result = Joiner.on("").join(output); Files.write(result, file, StandardCharsets.UTF_8); System.out.println(result); }
From source file:natlab.Main.java
/** * Main method deals with command line options and execution of * desired functions.//from www.j a va2 s. c o m */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("No options given\nTry -help for usage"); return; } options = new Options(); options.parse(args); if (options.help()) { System.err.println(options.getUsage()); return; } if (options.pref()) { NatlabPreferences.modify(options); return; } if (options.show_pref()) { System.out.println("Preferences:"); System.out.println( Joiner.on('\n').withKeyValueSeparator(" = ").join(NatlabPreferences.getAllPreferences())); } if (options.version()) { System.out.println("The version of this release is: " + VersionInfo.getVersion()); return; } if (options.quiet()) { AbstractDepthFirstAnalysis.DEBUG = false; AbstractStructuralAnalysis.DEBUG = false; } if (options.tamer()) { //TODO - the parsing of the options should probably not be done by the tamer tool BasicTamerTool.main(options); return; } if (options.tamerplus()) { TamerPlusMain.main(options); } if (options.mclint()) { McLint.main(options); return; } if (options.server()) { NatlabServer.create(options).start(); return; } if (options.mix10c()) { Mix10.compile(options); } // Mc2For options if (options.codegen() || options.nocheck()) { Main_readable.compile(options); } if (options.getFiles().isEmpty()) { System.err.println("No files provided, must have at least one file."); return; } List<String> files = options.getFiles(); log("Parsing " + Joiner.on(", ").join(files)); List<CompilationProblem> errors = Lists.newArrayList(); CompilationUnits cu; if (!options.natlab()) { cu = Parse.parseMatlabFiles(files, errors); } else { cu = Parse.parseNatlabFiles(files, errors); } if (!errors.isEmpty()) { System.err.println(CompilationProblem.toStringAll(errors)); return; } if (options.simplify()) { Simplifier.simplify(cu, FullSimplification.class); } if (options.json()) { System.out.println(cu.getJsonString()); return; } if (options.xml()) { System.out.print(cu.XMLtoString(cu.ASTtoXML())); return; } if (options.pretty()) { log("Pretty printing"); if (options.od().length() == 0) { System.out.println(cu.getPrettyPrinted()); } else { File outputDir = new File(options.od()); for (Program program : cu.getPrograms()) { File outputFile = new File(outputDir, program.getFile().getName()); Files.createParentDirs(outputFile); Files.write(program.getPrettyPrinted(), outputFile, Charsets.UTF_8); } } return; } }
From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineTestService.java
/** Entry point * @param args/*from w w w. j av a 2 s . com*/ * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 3) { System.out .println("ARGS: <script-file> <input-file> <output-prefix> [{[len: <LEN>], [group: <GROUP>]}]"); } // STEP 1: load script file final String user_script = Files.toString(new File(args[0]), Charsets.UTF_8); // STEP 2: get a stream for the JSON file final InputStream io_stream = new FileInputStream(new File(args[1])); // STEP 3: set up control if applicable Optional<JsonNode> json = Optional.of("").filter(__ -> args.length > 3).map(__ -> args[3]) .map(Lambdas.wrap_u(j -> _mapper.readTree(j))); // STEP 4: set up the various objects final DataBucketBean bucket = Mockito.mock(DataBucketBean.class); final JsScriptEngineService service_under_test = new JsScriptEngineService(); final LinkedList<ObjectNode> emitted = new LinkedList<>(); final LinkedList<JsonNode> grouped = new LinkedList<>(); final LinkedList<JsonNode> externally_emitted = new LinkedList<>(); final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class, new Answer<Void>() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) { try { Object[] args = invocation.getArguments(); if (invocation.getMethod().getName().equals("emitMutableObject")) { final Optional<JsonNode> grouping = (Optional<JsonNode>) args[3]; if (grouping.isPresent()) { grouped.add(grouping.get()); } emitted.add((ObjectNode) args[1]); } else if (invocation.getMethod().getName().equals("externalEmit")) { final DataBucketBean to = (DataBucketBean) args[0]; final Either<JsonNode, Map<String, Object>> out = (Either<JsonNode, Map<String, Object>>) args[1]; externally_emitted .add(((ObjectNode) out.left().value()).put("__a2_bucket", to.full_name())); } } catch (Exception e) { e.printStackTrace(); } return null; } }); final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class) .with(EnrichmentControlMetadataBean::config, new LinkedHashMap<String, Object>( ImmutableMap.<String, Object>builder().put("script", user_script).build())) .done().get(); service_under_test.onStageInitialize(context, bucket, control, Tuples._2T(ProcessingStage.batch, ProcessingStage.grouping), Optional.empty()); final BeJsonParser json_parser = new BeJsonParser(); // Run the file through final Stream<Tuple2<Long, IBatchRecord>> json_stream = StreamUtils .takeUntil(Stream.generate(() -> json_parser.getNextRecord(io_stream)), i -> null == i) .map(j -> Tuples._2T(0L, new BatchRecord(j))); service_under_test.onObjectBatch(json_stream, json.map(j -> j.get("len")).map(j -> (int) j.asLong(0L)), json.map(j -> j.get("group"))); System.out.println("RESULTS: "); System.out.println("emitted: " + emitted.size()); System.out.println("grouped: " + grouped.size()); System.out.println("externally emitted: " + externally_emitted.size()); Files.write(emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "emit.json"), Charsets.UTF_8); Files.write(grouped.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "group.json"), Charsets.UTF_8); Files.write(externally_emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "external_emit.json"), Charsets.UTF_8); }
From source file:org.eqaula.glue.util.Lists.java
public static void main(String args[]) throws IOException { String aFileName = "/home/jlgranda/iaenvirtual/selenium/CrearCurso"; int MAX = 114; String content = null;//from www.ja v a2s .co m File file = null; for (int i = 1; i <= MAX; i++) { content = buildContent(i); aFileName = aFileName + i; file = new File(aFileName); Files.write(content, file, ENCODING); System.out.println(aFileName + " created!"); aFileName = "/home/jlgranda/iaenvirtual/selenium/CrearCurso"; } }
From source file:edu.byu.nlp.data.app.AnnotationStream2Csv.java
public static void main(String[] args) throws IOException { // parse CLI arguments new ArgumentParser(AnnotationStream2Csv.class).parseArgs(args); Preconditions.checkNotNull(jsonStream, "You must provide a valid --json-stream!"); Dataset data = readData(jsonStream); // optionally aggregate by instance String header = "annotator,start,end,annotation,label,source,num_correct_annotations,num_annotations,cum_num_annotations,num_annotators,cum_num_annotators\n"; // iterate over instances and (optionally) annotations final StringBuilder bld = new StringBuilder(); switch (row) { case ANNOTATION: // sort all annotations by end time Map<FlatInstance<SparseFeatureVector, Integer>, DatasetInstance> ann2InstMap = Maps .newIdentityHashMap();/*from w w w .j a v a 2 s . c o m*/ List<FlatInstance<SparseFeatureVector, Integer>> annotationList = Lists.newArrayList(); for (DatasetInstance inst : data) { for (FlatInstance<SparseFeatureVector, Integer> ann : inst.getAnnotations().getRawAnnotations()) { ann2InstMap.put(ann, inst); // record instance of each annotations annotationList.add(ann); } } Collections.sort(annotationList, new Comparator<FlatInstance<SparseFeatureVector, Integer>>() { @Override public int compare(FlatInstance<SparseFeatureVector, Integer> o1, FlatInstance<SparseFeatureVector, Integer> o2) { // no null checking since we want to fail if annotation time is not set. return Long.compare(o1.getEndTimestamp(), o2.getEndTimestamp()); } }); Set<Integer> annotators = Sets.newHashSet(); for (Enumeration<FlatInstance<SparseFeatureVector, Integer>> item : Iterables2 .enumerate(annotationList)) { FlatInstance<SparseFeatureVector, Integer> ann = item.getElement(); DatasetInstance inst = ann2InstMap.get(ann); annotators.add(ann.getAnnotator()); bld.append(ann.getAnnotator() + ","); bld.append(ann.getStartTimestamp() + ","); bld.append(ann.getEndTimestamp() + ","); bld.append(ann.getAnnotation() + ","); bld.append(inst.getLabel() + ","); bld.append( data.getInfo().getIndexers().getInstanceIdIndexer().get(inst.getInfo().getSource()) + ","); bld.append((!inst.hasLabel() ? "NA" : ann.getAnnotation() == inst.getLabel() ? 1 : 0) + ","); // num correct bld.append(1 + ","); // num annotations bld.append((item.getIndex() + 1) + ","); // cumulative num annotations bld.append(1 + ","); // num annotators bld.append(annotators.size() + ""); // cumulative num annotators bld.append("\n"); } break; case INSTANCE: int cumNumAnnotations = 0; for (DatasetInstance inst : data) { cumNumAnnotations += inst.getInfo().getNumAnnotations(); int numCorrectAnnotations = 0; // sum over all the annotators who put the correct answer (if available) if (inst.hasLabel()) { Integer correctLabel = inst.getLabel(); for (int j = 0; j < data.getInfo().getNumAnnotators(); j++) { numCorrectAnnotations += inst.getAnnotations().getLabelAnnotations() .getRow(j)[correctLabel]; } } bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append(inst.getLabel() + ","); bld.append(inst.getInfo().getSource() + ","); bld.append(numCorrectAnnotations + ","); bld.append(inst.getInfo().getNumAnnotations() + ","); bld.append(cumNumAnnotations + ","); bld.append(inst.getInfo().getNumAnnotators() + ","); bld.append("NA"); // cumulative num annotators bld.append("\n"); } break; case ANNOTATOR: Multiset<Integer> perAnnotatorAnnotationCounts = HashMultiset.create(); Multiset<Integer> perAnnotatorCorrectAnnotationCounts = HashMultiset.create(); for (DatasetInstance inst : data) { for (FlatInstance<SparseFeatureVector, Integer> ann : inst.getAnnotations().getRawAnnotations()) { int annotatorId = ann.getAnnotator(); perAnnotatorAnnotationCounts.add(annotatorId); if (inst.getLabel() == ann.getAnnotation()) { perAnnotatorCorrectAnnotationCounts.add(annotatorId); } } } for (String annotatorId : data.getInfo().getAnnotatorIdIndexer()) { bld.append(annotatorId + ","); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append("NA,"); bld.append(perAnnotatorCorrectAnnotationCounts.count(annotatorId) + ","); bld.append(perAnnotatorAnnotationCounts.count(annotatorId) + ","); bld.append("NA,"); bld.append("1,"); // num annotators bld.append("NA"); // cumulative num annotators bld.append("\n"); } break; default: Preconditions.checkArgument(false, "unknown row type: " + row); break; } // output to console if (out == null) { System.out.println(header); System.out.println(bld.toString()); } else { File outfile = new File(out); Files.write(header, outfile, Charsets.UTF_8); Files.append(bld, outfile, Charsets.UTF_8); } }
From source file:com.google.dart.java2dart.engine.MainAnalysisServer.java
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java2dart <services-target-src-folder> <server-target-src-folder>"); System.exit(0);/*from w ww . j av a 2 s . co m*/ } String targetFolderServices = args[0]; String targetFolderServer = args[1]; System.out.println("Generating files into\n\t" + targetFolderServices + "\n\t" + targetFolderServer); new File(targetFolderServer).mkdirs(); // engineFolder = new File("../../../tools/plugins/com.google.dart.engine/src"); serviceFolder = new File("../../../tools/plugins/com.google.dart.engine.services/src"); serverFolder = new File("../../../tools/plugins/com.google.dart.server/src"); engineFolder = engineFolder.getCanonicalFile(); // configure Context context.addClasspathFile(new File("../../../../third_party/guava/r13/guava-13.0.1.jar")); context.addClasspathFile(new File("../../../../third_party/commons-lang/3.2.1/commons-lang3-3.2.1.jar")); context.addClasspathFile(new File("../../../../third_party/junit/v4_8_2/junit.jar")); context.addSourceFolder(engineFolder); context.addSourceFolder(serviceFolder); context.addSourceFolder(serverFolder); context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/")); context.addSourceFiles(new File(serverFolder, "com/google/dart/server/")); context.removeSourceFiles(new File(serverFolder, "com/google/dart/server/internal/remote/")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/assist")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/change")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/completion")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/correction")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/internal/completion")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/internal/correction")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/internal/refactoring")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/internal/util")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/refactoring")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/status")); context.addSourceFiles(new File(serviceFolder, "com/google/dart/engine/services/util")); // translate into single CompilationUnit dartUnit = context.translate(); // run processors { List<SemanticProcessor> PROCESSORS = ImmutableList.of(new TypeSemanticProcessor(context), new ObjectSemanticProcessor(context), new CollectionSemanticProcessor(context), new IOSemanticProcessor(context), new PropertySemanticProcessor(context), new GuavaSemanticProcessor(context), new JUnitSemanticProcessor(context), new EngineAnnotationProcessor(context), new UniqueMemberNamesSemanticProcessor(context), new RenameConstructorsSemanticProcessor(context), new EngineSemanticProcessor(context), new EngineInstanceOfProcessor(context), new BeautifySemanticProcessor(context)); for (SemanticProcessor processor : PROCESSORS) { processor.process(dartUnit); } } // run this again, because we may introduce conflicts when convert methods to getters/setters context.ensureUniqueClassMemberNames(); context.applyLocalVariableSemanticChanges(dartUnit); { CompilationUnit library = buildServiceInterfacesLibrary(); Files.write(getFormattedSource(library), new File(targetFolderServer + "/service_interfaces.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServiceComputersLibrary(); Files.write(getFormattedSource(library), new File(targetFolderServer + "/service_computers.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServicesLibrary_change(); Files.write(getFormattedSource(library), new File(targetFolderServices + "/change.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServicesLibrary_completion(); String source = getFormattedSource(library); // TODO(scheglov) improve java2dart to make this translated correctly source = replaceSourceFragment(source, "new CompletionEngine_CommentReferenceCompleter(this, _completionNode)", "new CompletionEngine_CommentReferenceCompleter(CompletionEngine_this, _completionNode)"); source = replaceSourceFragment(source, "new CompletionEngine_TypeNameCompleter(this, _completionNode, node)", "new CompletionEngine_TypeNameCompleter(CompletionEngine_this, _completionNode, node)"); // source = replaceSourceFragment( // source, // "new CompletionEngine_NameCollector(this)", // "new CompletionEngine_NameCollector(CompletionEngine_this)"); source = replaceSourceFragment(source, "new CompletionEngine_IdentifierCompleter(this, node)", "new CompletionEngine_IdentifierCompleter(CompletionEngine_this, node)"); source = replaceSourceFragment(source, "new CompletionEngine_StringCompleter(this, node)", "new CompletionEngine_StringCompleter(CompletionEngine_this, node)"); Files.write(source, new File(targetFolderServices + "/completion.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServicesLibrary_status(); Files.write(getFormattedSource(library), new File(targetFolderServices + "/status.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServicesLibrary_proposal(); Files.write(getFormattedSource(library), new File(targetFolderServices + "/proposal.dart"), Charsets.UTF_8); } { CompilationUnit library = buildServicesLibrary_util(); Files.write(getFormattedSource(library), new File(targetFolderServices + "/util.dart"), Charsets.UTF_8); } // TODO(scheglov) restore to translate more // { // CompilationUnit library = buildServicesLibrary_assist(); // Files.write(getFormattedSource(library), new File(targetFolder2 // + "/service_correction.dart"), Charsets.UTF_8); // } { CompilationUnit library = buildServicesLibrary_refactoring(); Files.write(getFormattedSource(library), new File(targetFolderServices + "/refactoring.dart"), Charsets.UTF_8); } { String projectFolder = new File(targetFolderServices).getParentFile().getParentFile().getParent(); fixUnnecessaryCastHints(projectFolder); } { String projectFolder = new File(targetFolderServer).getParentFile().getParentFile().getParent(); fixUnnecessaryCastHints(projectFolder); } System.out.println("Translation complete"); }
From source file:waffle.util.WaffleInfo.java
/** * Print system information./* w ww .j a v a 2 s . co m*/ * * @param args * variable arguments to pass to main. Valid values are "-show" and "-lookup". */ public static void main(final String[] args) { boolean show = false; final List<String> lookup = new ArrayList<>(); if (args != null) { String arg; for (int i = 0; i < args.length; i++) { arg = args[i]; if (null != arg) { switch (arg) { case "-show": show = true; break; case "-lookup": lookup.add(args[++i]); break; default: WaffleInfo.LOGGER.error("Unknown Argument: {}", arg); throw new RuntimeException("Unknown Argument: " + arg); } } } } final WaffleInfo helper = new WaffleInfo(); try { final Document info = helper.getWaffleInfo(); for (final String name : lookup) { info.getDocumentElement().appendChild(helper.getLookupInfo(info, name)); } final String xml = WaffleInfo.toPrettyXML(info); final File f; if (show) { f = File.createTempFile("waffle-info-", ".xml"); Files.write(xml, f, StandardCharsets.UTF_8); Desktop.getDesktop().open(f); } else { WaffleInfo.LOGGER.info(xml); } } catch (final IOException | TransformerException | ParserConfigurationException e) { WaffleInfo.LOGGER.error(e.getMessage()); WaffleInfo.LOGGER.trace("", e); } }