List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:edu.cmu.lti.oaqa.knn4qa.apps.FilterTranTable.java
public static void main(String[] args) { Options options = new Options(); options.addOption(INPUT_PARAM, null, true, INPUT_DESC); options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC); options.addOption(CommonParams.MEM_FWD_INDEX_PARAM, null, true, CommonParams.MEM_FWD_INDEX_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_PARAM); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_PARAM); options.addOption(CommonParams.MIN_PROB_PARAM, null, true, CommonParams.MIN_PROB_DESC); options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from www. j a v a2 s . c om CommandLine cmd = parser.parse(options, args); String outputFile = null; outputFile = cmd.getOptionValue(OUTPUT_PARAM); if (null == outputFile) { Usage("Specify 'A name of the output file'", options); } String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); if (null == gizaRootDir) { Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_DESC + "'", options); } String gizaIterQty = cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM); if (null == gizaIterQty) { Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options); } float minProb = 0; String tmpf = cmd.getOptionValue(CommonParams.MIN_PROB_PARAM); if (tmpf != null) { minProb = Float.parseFloat(tmpf); } int maxWordQty = Integer.MAX_VALUE; String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM); if (null != tmpi) { maxWordQty = Integer.parseInt(tmpi); } String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM); if (null == memFwdIndxName) { Usage("Specify '" + CommonParams.MEM_FWD_INDEX_DESC + "'", options); } System.out.println("Filtering index: " + memFwdIndxName + " max # of frequent words: " + maxWordQty + " min. probability:" + minProb); VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty); String srcVocFile = CompressUtils.findFileVariant(gizaRootDir + "/source.vcb"); System.out.println("Source vocabulary file: " + srcVocFile); GizaVocabularyReader srcVoc = new GizaVocabularyReader(srcVocFile, filter); String dstVocFile = CompressUtils.findFileVariant(gizaRootDir + "/target.vcb"); System.out.println("Target vocabulary file: " + dstVocFile); GizaVocabularyReader dstVoc = new GizaVocabularyReader(CompressUtils.findFileVariant(dstVocFile), filter); String inputFile = CompressUtils.findFileVariant(gizaRootDir + "/output.t1." + gizaIterQty); BufferedReader finp = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); BufferedWriter fout = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFile))); try { String line; int prevSrcId = -1; int wordQty = 0; long addedQty = 0; long totalQty = 0; boolean isNotFiltered = false; for (totalQty = 0; (line = finp.readLine()) != null;) { ++totalQty; // Skip empty lines line = line.trim(); if (line.isEmpty()) continue; GizaTranRec rec = new GizaTranRec(line); if (rec.mSrcId != prevSrcId) { ++wordQty; } if (totalQty % REPORT_INTERVAL_QTY == 0) { System.out.println(String.format( "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } // isNotFiltered should be set after procOneWord if (rec.mSrcId != prevSrcId) { if (rec.mSrcId == 0) isNotFiltered = true; else { String wordSrc = srcVoc.getWord(rec.mSrcId); isNotFiltered = filter == null || (wordSrc != null && filter.checkWord(wordSrc)); } } prevSrcId = rec.mSrcId; if (rec.mProb >= minProb && isNotFiltered) { String wordDst = dstVoc.getWord(rec.mDstId); if (filter == null || (wordDst != null && filter.checkWord(wordDst))) { fout.write(String.format(rec.mSrcId + " " + rec.mDstId + " " + rec.mProb)); fout.newLine(); addedQty++; } } } System.out.println( String.format("Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty, wordQty, inputFile, addedQty)); } finally { finp.close(); fout.close(); } } catch (ParseException e) { Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:com.yahoo.semsearch.fastlinking.EntityContextFastEntityLinker.java
/** * Context-aware command line entity linker * @param args arguments (see -help for further info) * @throws Exception/*from ww w. ja va 2 s . com*/ */ public static void main(String args[]) throws Exception { SimpleJSAP jsap = new SimpleJSAP(EntityContextFastEntityLinker.class.getName(), "Interactive mode for entity linking", new Parameter[] { new FlaggedOption("hash", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'h', "hash", "quasi succint hash"), new FlaggedOption("vectors", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'v', "vectors", "Word vectors file"), new FlaggedOption("labels", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'l', "labels", "File containing query2entity labels"), new FlaggedOption("id2type", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'i', "id2type", "File with the id2type mapping"), new Switch("centroid", 'c', "centroid", "Use centroid-based distances and not LR"), new FlaggedOption("map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'm', "map", "Entity 2 type mapping "), new FlaggedOption("threshold", JSAP.STRING_PARSER, "-20", JSAP.NOT_REQUIRED, 'd', "threshold", "Score threshold value "), new FlaggedOption("entities", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'e', "entities", "Entities word vectors file"), }); JSAPResult jsapResult = jsap.parse(args); if (jsap.messagePrinted()) return; double threshold = Double.parseDouble(jsapResult.getString("threshold")); QuasiSuccinctEntityHash hash = (QuasiSuccinctEntityHash) BinIO.loadObject(jsapResult.getString("hash")); EntityContext queryContext; if (!jsapResult.getBoolean("centroid")) { queryContext = new LREntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"), hash); } else { queryContext = new CentroidEntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"), hash); } HashMap<String, ArrayList<EntityRelevanceJudgment>> labels = null; if (jsapResult.getString("labels") != null) { labels = readTrainingData(jsapResult.getString("labels")); } String map = jsapResult.getString("map"); HashMap<String, String> entities2Type = null; if (map != null) entities2Type = readEntity2IdFile(map); EntityContextFastEntityLinker linker = new EntityContextFastEntityLinker(hash, queryContext); final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String q; for (;;) { System.out.print(">"); q = br.readLine(); if (q == null) { System.err.println(); break; // CTRL-D } if (q.length() == 0) continue; long time = -System.nanoTime(); try { List<EntityResult> results = linker.getResults(q, threshold); //List<EntityResult> results = linker.getResultsGreedy( q, 5 ); //int rank = 0; for (EntityResult er : results) { if (entities2Type != null) { String name = er.text.toString().trim(); String newType = entities2Type.get(name); if (newType == null) newType = "NF"; System.out.println(q + "\t span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + newType + ")" + " score: " + er.score + " ( " + er.s.span + " ) "); //System.out.println( newType + "\t" + q + "\t" + StringUtils.remove( q, er.s.span.toString() ) + " \t " + er.text ); break; /* } else { System.out.print( "[" + er.text + "(" + String.format("%.2f",er.score) +")] "); System.out.println( "span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + typeMapping.get( hash.getEntity( er.id ).type ) + " score: " + er.score + " ( " + er.s.span + " ) " ); } rank++; */ } else { if (labels == null) { System.out.println(q + "\t" + er.text + "\t" + er.score); } else { ArrayList<EntityRelevanceJudgment> jds = labels.get(q); String label = "NF"; if (jds != null) { EntityRelevanceJudgment relevanceOfEntity = relevanceOfEntity(er.text, jds); label = relevanceOfEntity.label; } System.out.println(q + "\t" + er.text + "\t" + label + "\t" + er.score); break; } } System.out.println(); } time += System.nanoTime(); System.out.println("Time to rank and print the candidates:" + time / 1000000. + " ms"); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java
public static void main(String[] args) throws Exception { //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%BC%D0%B0%D1%87%D0%BE%D0%B2%D0%B5%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE/ //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE-%D0%B8-%D0%B2-%D0%BF%D0%B5%D1%82/ //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%B8-%D0%B2-%D1%87%D0%B5%D1%82%D0%B2%D1%8A%D1%80%D1%82%D0%B8%D1%8F/ builder = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerAdapter()) .registerTypeAdapter(String.class, new StringAdapter()) .registerTypeAdapter(Action.class, new ActionAdapter()).setPrettyPrinting(); BufferedReader reader = new BufferedReader( new InputStreamReader(FIBAJsonParser.class.getResourceAsStream("/games.txt"))); String location = null;//from ww w . j a va 2 s . c o m while ((location = reader.readLine()) != null) { location = location.trim(); try { readLocation(location); } catch (Exception ex) { ex.printStackTrace(); } } /* readLocation("48965/13/13/23/68uR30BQLmzJM"); readLocation("48965/13/15/86/78CJrCjRx5mh6"); readLocation("48965/13/13/18/12pOKqzKs5nE"); readLocation("48965/13/29/11/33upB2PIPn3MI"); readLocation("48965/13/13/21/38Gqht27dPT1"); readLocation("48965/13/15/84/999JtqK7Eao"); readLocation("48965/13/29/07/66ODts76QU17A"); */ }
From source file:OpenDataExtractor.java
public static void main(String[] args) { System.out.println("\nSeleziona in che campo fare la ricerca: "); System.out.println("Elenco completo delle gare in formato (1)"); // cc16106a-1a65-4c34-af13-cc045d181452 System.out.println("Composizione delle commissioni giudicatrici (2)"); // c90f1ffb-c315-4f59-b0e3-b0f2f8709127 System.out.println("Registro delle imprese escluse dalle gare (3)"); // 2ea798cc-1f52-4fc8-a28e-f92a6f409cb8 System.out.println("Registro delle imprese invitate alle gare (4)"); // a124b6af-ae31-428a-8ac5-bb341feb3c46 System.out.println("Registro delle imprese che hanno partecipato alle gare (5)");// e58396cf-1145-4cb1-84a4-34311238a0c6 System.out.println("Anagrafica completa dei contratti per l'acquisizione di beni e servizi (6)"); // aa6a8664-5ef5-43eb-a563-910e25161798 System.out.println("Fornitori (7)"); // 253c8ac9-8335-4425-84c5-4a90be863c00 System.out.println("Autorizzazioni subappalti per i lavori (8)"); // 4f9ba542-5768-4b39-a92a-450c45eabd5d System.out.println("Aggiudicazioni delle gare per i lavori (9)"); // 34e298ad-3a99-4feb-9614-b9c4071b9d8e System.out.println("Dati cruscotto lavori per area (10)"); // 1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8 System.out.println("Dati cruscotto lavori per lotto (11)"); // cbededce-269f-48d2-8c25-2359bf246f42 int count = 0; int scelta;/*from w w w . j a v a 2 s . c o m*/ String id_ref = ""; Scanner scanner; try { do { scanner = new Scanner(System.in); scelta = scanner.nextInt(); switch (scelta) { case 1: id_ref = "cc16106a-1a65-4c34-af13-cc045d181452&q="; break; case 2: id_ref = "c90f1ffb-c315-4f59-b0e3-b0f2f8709127&q="; break; case 3: id_ref = "2ea798cc-1f52-4fc8-a28e-f92a6f409cb8&q="; break; case 4: id_ref = "a124b6af-ae31-428a-8ac5-bb341feb3c46&q="; break; case 5: id_ref = "e58396cf-1145-4cb1-84a4-34311238a0c6&q="; break; case 6: id_ref = "aa6a8664-5ef5-43eb-a563-910e25161798&q="; break; case 7: id_ref = "253c8ac9-8335-4425-84c5-4a90be863c00&q="; break; case 8: id_ref = "4f9ba542-5768-4b39-a92a-450c45eabd5d&q="; break; case 9: id_ref = "34e298ad-3a99-4feb-9614-b9c4071b9d8e&q="; break; case 10: id_ref = "1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8&q="; break; case 11: id_ref = "cbededce-269f-48d2-8c25-2359bf246f42&q="; break; default: System.out.println("Numero non selezionabile"); System.out.println("Reinserisci"); break; } } while (scelta <= 0 || scelta > 11); scanner = new Scanner(System.in); System.out.println("Inserisci un parametro di ricerca: "); String record = scanner.nextLine(); String limit = "&limit=10000"; System.out.println("id di riferimento: " + id_ref); System.out.println("___________________________"); String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id=" + id_ref + record + limit; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(requestString); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = ""; String resline = ""; while ((resline = rd.readLine()) != null) { result += resline; } if (result != null) { JSONObject jsonObject = new JSONObject(result); JSONObject resultJson = (JSONObject) jsonObject.get("result"); JSONArray resultJsonFields = (JSONArray) resultJson.get("fields"); ArrayList<TypeFields> type = new ArrayList<TypeFields>(); TypeFields type1; JSONObject temp; while (count < resultJsonFields.length()) { temp = (JSONObject) resultJsonFields.get(count); type1 = new TypeFields(temp.getString("id"), temp.getString("type")); type.add(type1); count++; } JSONArray arr = (JSONArray) resultJson.get("records"); count = 0; while (count < arr.length()) { System.out.println("Entry numero: " + count); temp = (JSONObject) arr.get(count); for (TypeFields temp2 : type) { System.out.println(temp2.nameType + ": " + temp.get(temp2.nameType)); } count++; System.out.println("--------------------------"); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:lapispaste.Main.java
public static void main(String[] args) throws Exception { // create Options object Options options = new Options(); String version;/*from w ww . j av a 2 s . com*/ version = "0.1"; // populate Options with.. well options :P options.addOption("v", false, "Display version"); options.addOption("f", true, "File to paste"); // non-critical options options.addOption("t", true, "Code language"); options.addOption("p", false, "Read from pipe"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); // assemble a map of values final Map<String, String> pastemap = new HashMap<String, String>(); if (cmd.hasOption("t")) pastemap.put("format", cmd.getOptionValue("t").toString()); else pastemap.put("format", "text"); // critical options if (cmd.hasOption("v")) System.out.println("lapispaste version " + version); else if (cmd.hasOption("f")) { File file = new File(cmd.getOptionValue("f")); StringBuffer pdata = readData(new FileReader(file)); paster(pastemap, pdata); } else if (cmd.hasOption("p")) { StringBuffer pdata = readData(new InputStreamReader(System.in)); paster(pastemap, pdata); } else { // Did not recieve what was expected HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("lapispaste [OPTIONS] [FILE]", options); } }
From source file:drmaas.sandbox.http.LoginTest.java
public static void main(String[] args) throws Exception { //1. For SSL//from ww w. j a v a 2 s . com DefaultHttpClient base = new DefaultHttpClient(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; X509HostnameVerifier verifier = new X509HostnameVerifier() { @Override public void verify(String string, SSLSocket ssls) throws IOException { } @Override public void verify(String string, X509Certificate xc) throws SSLException { } @Override public void verify(String string, String[] strings, String[] strings1) throws SSLException { } @Override public boolean verify(String string, SSLSession ssls) { return true; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, base.getParams()); httpclient.setRedirectStrategy(new LaxRedirectStrategy()); try { HttpPost httpost; HttpResponse response; HttpEntity entity; List<Cookie> cookies; BufferedReader rd; String line; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); //log in httpost = new HttpPost("myloginurl"); nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("login", "Log In")); nvps.add(new BasicNameValuePair("os_username", "foo")); nvps.add(new BasicNameValuePair("os_password", "foobar")); nvps.add(new BasicNameValuePair("os_cookie", "true")); nvps.add(new BasicNameValuePair("os_destination", "")); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = httpclient.execute(httpost); System.out.println(response.toString()); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroupsAndBuffering.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println(String.format("%s <output-file>", GradleDependenciesWithGroupsAndBuffering.class.getSimpleName())); System.exit(1);//from www . j av a 2 s . co m } final File file = new File(args[0]); System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ..."); FileWriter fileWriter = null; Reader reader = null; LineNumberReader lineReader = null; try { fileWriter = new FileWriter(file); final com.github.fritaly.graphml4j.datastructure.Graph graph = new Graph(); // The dependency graph has been generated by Gradle with the // command "gradle dependencies". The output of this command has // been saved to a text file which will be parsed to rebuild the // dependency graph reader = new InputStreamReader( GradleDependenciesWithGroupsAndBuffering.class.getResourceAsStream("gradle-dependencies.txt")); lineReader = new LineNumberReader(reader); String line = null; // Stack containing the nodes per depth inside the dependency graph // (the topmost dependency is the first one in the stack) final Stack<Node> parentNodes = new Stack<Node>(); while ((line = lineReader.readLine()) != null) { // Determine the depth of the current dependency inside the // graph. The depth can be inferred from the indentation used by // Gradle. Each level of depth adds 5 more characters of // indentation final int initialLength = line.length(); // Remove the strings used by Gradle to indent dependencies line = StringUtils.replace(line, "+--- ", ""); line = StringUtils.replace(line, "| ", ""); line = StringUtils.replace(line, "\\--- ", ""); line = StringUtils.replace(line, " ", ""); // The depth can easily be inferred now final int depth = (initialLength - line.length()) / 5; // Remove unnecessary node ids while (depth <= parentNodes.size()) { parentNodes.pop(); } final Artifact artifact = createArtifact(line); Node node = graph.getNodeByData(artifact); // Has this dependency already been added to the graph ? if (node == null) { // No, add the node node = graph.addNode(artifact); } parentNodes.push(node); if (parentNodes.size() > 1) { // Generate an edge between the current node and its parent graph.addEdge("Depends on", parentNodes.get(parentNodes.size() - 2), node); } } // Create the groups after creating the nodes & edges for (Node node : graph.getNodes()) { final Artifact artifact = (Artifact) node.getData(); final String groupId = artifact.group; Node groupNode = graph.getNodeByData(groupId); if (groupNode == null) { groupNode = graph.addNode(groupId); } // add the node to the group node.setParent(groupNode); } graph.toGraphML(fileWriter, new Renderer() { @Override public String getNodeLabel(Node node) { return node.isGroup() ? node.getData().toString() : ((Artifact) node.getData()).getLabel(); } @Override public boolean isGroupOpen(Node node) { return true; } @Override public NodeStyle getNodeStyle(Node node) { // Customize the rendering of nodes final NodeStyle nodeStyle = new NodeStyle(); nodeStyle.setWidth(250.0f); return nodeStyle; } @Override public GroupStyles getGroupStyles(Node node) { return new GroupStyles(); } @Override public EdgeStyle getEdgeStyle(Edge edge) { return new EdgeStyle(); } }); System.out.println("Done"); } finally { // Calling GraphMLWriter.close() is necessary to dispose the underlying resources fileWriter.close(); lineReader.close(); reader.close(); } }
From source file:ch.admin.hermes.etl.load.HermesETLApplication.java
/** * Hauptprogramm//ww w . j a v a 2 s . c o m * @param args Commandline Argumente */ public static void main(String[] args) { JFrame frame = null; try { // Crawler fuer Zugriff auf HERMES 5 Online Loesung initialiseren */ crawler = new HermesOnlineCrawler(); // CommandLine Argumente aufbereiten parseCommandLine(args); // Methoden Export (Variante Zuehlke) extrahieren System.out.println("load library " + model); ModelExtract root = new ModelExtract(); root.extract(model); frame = createProgressDialog(); // wird das XML Model von HERMES Online geholt - URL der Templates korrigieren if (scenario != null) { List<Workproduct> workproducts = (List<Workproduct>) root.getObjects().get("workproducts"); for (Workproduct wp : workproducts) for (Template t : wp.getTemplate()) { // Template beinhaltet kompletten URL - keine Aenderung if (t.getUrl().toLowerCase().startsWith("http") || t.getUrl().toLowerCase().startsWith("file")) continue; // Model wird ab Website geholte if (model.startsWith("http")) t.setUrl(crawler.getTemplateURL(scenario, t.getUrl())); // Model ist lokal - Path aus model und relativem Path Template zusammenstellen else { File m = new File(model); t.setUrl(m.getParentFile() + "/" + t.getUrl()); } } } // JavaScript - fuer Import in Fremdsystem if (script.endsWith(".js")) { final JavaScriptEngine js = new JavaScriptEngine(); js.setObjects(root.getObjects()); js.put("progress", progress); js.eval("function log( x ) { println( x ); progress.setString( x ); }"); progress.setString("call main() in " + script); js.put(ScriptEngine.FILENAME, script); js.call(new InputStreamReader(new FileInputStream(script)), "main", new Object[] { site, user, passwd }); } // FreeMarker - fuer Umwandlungen nach HTML else if (script.endsWith(".ftl")) { FileOutputStream out = new FileOutputStream( new File(script.substring(0, script.length() - 3) + "html ")); int i = script.indexOf("templates"); if (i >= 0) script = script.substring(i + "templates".length()); MethodTransform transform = new MethodTransform(); transform.transform(root.getObjects(), script, out); out.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString(), "Fehlerhafte Verarbeitung", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } if (frame != null) { frame.setVisible(false); frame.dispose(); } System.exit(0); }
From source file:Messenger.TorLib.java
public static void main(String[] args) { String req = "-r"; String targetHostname = "tor.eff.org"; String targetDir = "index.html"; int targetPort = 80; if (args.length > 0 && args[0].equals("-h")) { System.out.println("Tinfoil/TorLib - interface for using Tor from Java\n" + "By Joe Foley<foley@mit.edu>\n" + "Usage: java Tinfoil.TorLib <cmd> <args>\n" + "<cmd> can be: -h for help\n" + " -r for resolve\n" + " -w for wget\n" + "For -r, the arg is:\n" + " <hostname> Hostname to DNS resolve\n" + "For -w, the args are:\n" + " <host> <path> <optional port>\n" + " for example, http://tor.eff.org:80/index.html would be\n" + " tor.eff.org index.html 80\n" + " Since this is a demo, the default is the tor website.\n"); System.exit(2);//from w w w . j ava 2 s .com } if (args.length >= 4) targetPort = new Integer(args[2]).intValue(); if (args.length >= 3) targetDir = args[2]; if (args.length >= 2) targetHostname = args[1]; if (args.length >= 1) req = args[0]; if (req.equals("-r")) { System.out.println(TorResolve(targetHostname)); } else if (req.equals("-w")) { try { Socket s = TorSocket(targetHostname, targetPort); DataInputStream is = new DataInputStream(s.getInputStream()); PrintStream out = new java.io.PrintStream(s.getOutputStream()); //Construct an HTTP request out.print("GET /" + targetDir + " HTTP/1.0\r\n"); out.print("Host: " + targetHostname + ":" + targetPort + "\r\n"); out.print("Accept: */*\r\n"); out.print("Connection: Keep-Aliv\r\n"); out.print("Pragma: no-cache\r\n"); out.print("\r\n"); out.flush(); // this is from Java Examples In a Nutshell final InputStreamReader from_server = new InputStreamReader(is); char[] buffer = new char[1024]; int chars_read; // read until stream closes while ((chars_read = from_server.read(buffer)) != -1) { // loop through array of chars // change \n to local platform terminator // this is a nieve implementation for (int j = 0; j < chars_read; j++) { if (buffer[j] == '\n') System.out.println(); else System.out.print(buffer[j]); } System.out.flush(); } s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:edu.oregonstate.eecs.mcplan.domains.tetris.TetrisVisualization.java
/** * @param args//from w ww . j ava 2s .c o m * @throws IOException * @throws NumberFormatException */ public static void main(final String[] args) throws NumberFormatException, IOException { // final int[][] cells = new int[][] { // new int[] { 1, 2, 3, 0, 4, 5, 0, 0, 0, 6 }, // new int[] { 0, 7, 0, 0, 8, 9, 0, 0, 0, 1 }, // new int[] { 2, 3, 4, 5, 0, 0, 0, 0, 4, 3 }, // new int[] { 0, 0, 0, 0, 1, 2, 0, 0, 2, 9 }, // new int[] { 0, 0, 0, 0, 3, 4, 0, 0, 8, 7 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 } // }; // This one tests cascading block falls // final int[][] cells = new int[][] { // new int[] { 2, 2, 2, 2, 2, 2, 0, 2, 2, 2 }, // new int[] { 3, 0, 0, 1, 8, 9, 1, 1, 1, 1 }, // new int[] { 0, 0, 0, 0, 0, 0, 1, 0, 1, 3 }, // new int[] { 0, 4, 4, 0, 0, 0, 1, 0, 1, 9 }, // new int[] { 0, 0, 4, 0, 0, 0, 0, 1, 8, 7 }, // new int[] { 0, 0, 4, 0, 0, 0, 0, 0, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } // }; // for( int y = 0; y < cells.length; ++y ) { // for( int x = 0; x < TetrisState.Ncolumns; ++x ) { // s.cells[y][x] = cells[y][x]; // } // } final int T = 50; final int Nrows = 10; final RandomGenerator rng = new MersenneTwister(43); final TetrisParameters params = new TetrisParameters(T, Nrows); final TetrisFsssModel model = new TetrisFsssModel(rng, params, new TetrisBertsekasRepresenter(params)); TetrisState s = model.initialState(); // for( final TetrominoType type : TetrominoType.values() ) { // final Tetromino t = type.create(); // for( int r = 0; r < 4; ++r ) { // for( int x = 0; x < TetrisState.Ncolumns; ++x ) { // s = model.initialState(); //// Fn.assign( s.cells, 0 ); // s.queued_tetro = t; // // System.out.println( "" + type + ", " + x + ", " + r ); // // final TetrisAction a = new TetrisAction( x, r ); // a.doAction( s ); // //// try { //// t.setCells( s, 1 ); //// } //// catch( final TetrisGameOver ex ) { //// // TODO Auto-generated catch block //// ex.printStackTrace(); //// } // System.out.println( s ); // } // } // } int steps = 0; while (!s.isTerminal()) { System.out.println(s); System.out.println(model.base_repr().encode(s)); // final int t = rng.nextInt( TetrominoType.values().length ); // final int r = rng.nextInt( 4 ); // final Tetromino tetro = TetrominoType.values()[t].create(); // tetro.setRotation( r ); // System.out.println( "Next:" ); // System.out.println( tetro ); // final int input_position = rng.nextInt( params.Ncolumns ); // final int input_rotation = rng.nextInt( 4 ); // This move sequence produces a cascading clear for seed=43: // 00 41 21 60 91 73 41 01 01 61 83 53 23 31 System.out.print(">>> "); final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); final int choice = Integer.parseInt(cin.readLine()); final int input_position = choice / 10; final int input_rotation = choice - (input_position * 10); final TetrisAction a = new TetrisAction(input_position, input_rotation); System.out.println("Input: " + a); final TetrisState sprime = model.sampleTransition(s, a); s = sprime; // tetro.setPosition( input_position, TetrisState.Nrows - 1 - tetro.getBoundingBox().top ); // tetro.setRotation( input_rotation ); // s.createTetromino( tetro ); ++steps; if (s.isTerminal()) { break; } // System.out.println( s ); // System.out.println(); // final int clears = s.drop(); // if( clears > 0 ) { // System.out.println( "\tCleared " + clears ); // } } System.out.println("Steps: " + steps); }