@Test public void kmeans_test() throws IOException { File file = new File(filename); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; List<Vector<Double>> vectors = new ArrayList<Vector<Double>>(); List<Integer> oc = new ArrayList<Integer>(); while ((line = br.readLine()) != null) { String[] values = line.split(separator); Vector<Double> vector = new Vector<Double>(values.length - 1); for (int i = 0; i < values.length - 1; i++) { vector.add(i, Double.valueOf(values[i])); } vectors.add(vector); String clazz = values[values.length - 1]; if (clazz.equals("Iris-setosa")) { oc.add(0); } else if (clazz.equals("Iris-versicolor")) { oc.add(1); } else { oc.add(2); } } br.close(); fr.close(); Matrix matrix = new Matrix(vectors); KMeansClustering kmeans = new KMeansClustering(); int[] clusters = kmeans.cluster(matrix, 3); int[][] classMatrix = new int[3][3]; for (int i = 0; i < oc.size(); i++) { classMatrix[oc.get(i)][clusters[i]]++; } System.out.println(" setosa versicolor virginica"); System.out.println( "setosa " + classMatrix[0][0] + " " + classMatrix[0][1] + " " + classMatrix[0][2]); System.out.println( "versicolor " + classMatrix[1][0] + " " + classMatrix[1][1] + " " + classMatrix[1][2]); System.out.println( "virginica " + classMatrix[2][0] + " " + classMatrix[2][1] + " " + classMatrix[2][2]); System.out.println( "Rand index: " + new RandIndex().calculate(oc.toArray(new Integer[oc.size()]), clusters)); }
public static void coding(String resource, String target) { BufferedReader reader = null; PrintWriter writer = null; try { FileInputStream in = new FileInputStream(resource); reader = new BufferedReader(new InputStreamReader(in, "GBK")); writer = new PrintWriter(target, "UTF-8"); String line = null; while ((line = reader.readLine()) != null) { writer.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { writer.close(); if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private static void init() throws IOException { startComponentMethods = new HashMap<String, Set<String>>(); subSignatures = new HashSet<String>(); FileReader fr = null; BufferedReader br = null; String line = null; try { fr = new FileReader(IPC_FILE); br = new BufferedReader(fr); while ((line = br.readLine()) != null) { String[] tokens = line.split(":"); String className = tokens[0].substring(1); String subSignature = tokens[1].substring(1, tokens[1].length() - 1); Set<String> methods = startComponentMethods.get(className); if (methods == null) { methods = new HashSet<String>(); methods.add(subSignature); subSignatures.add(subSignature); startComponentMethods.put(className, methods); } else { methods.add(subSignature); subSignatures.add(subSignature); } } } catch (IOException ioe) { System.out.print(ioe.toString()); } finally { if (br != null) br.close(); if (fr != null) fr.close(); } }
private void load(String normalizedFilePath, String filePath) { max_weight = -1; BufferedReader br; try { if (normalize) { br = new BufferedReader(new FileReader(normalizedFilePath)); } else { br = new BufferedReader(new FileReader(filePath)); } cTran2wt.clear(); String line = ""; while ((line = br.readLine()) != null) { String[] tokens = line.split("\t"); // if (tokens[0].equals(tokens[1])) { // continue; // } if (max_weight < Double.valueOf(tokens[2])) { max_weight = Double.valueOf(tokens[2]); } Transition t = new Transition(tokens[0], tokens[1]); cTran2wt.put(t, Double.valueOf(tokens[2])); } br.close(); logger.debug("size(): " + cTran2wt.size()); logger.debug("max_weight: " + max_weight); } catch (IOException e) { logger.error("not happened", e); } }
public static void main(String arr[]) { ParseQuery pq = new ParseQuery(); // DBSystem.readConfig("/tmp/config.txt"); String configFilePath = arr[0]; DBSystem.readConfig(configFilePath); // String query = "Select distinct * from countries where id=123 and code like 'jkl' group by // continent having code like 'antartic' order by name"; String inputFile = arr[1]; try { BufferedReader br = new BufferedReader(new FileReader(inputFile)); String line; while ((line = br.readLine()) != null) { pq.queryType(line); } } catch (FileNotFoundException e) { System.out.println("Input file not found"); // e.printStackTrace(); } catch (IOException e) { System.out.println("I/O Exception"); // e.printStackTrace(); } // /String query = "create table rtyui(name varchar, age int, rollno int)"; }
public static void main(String args[]) { long start = System.currentTimeMillis(); PrintWriter outputStream = null; try { BufferedReader inputStream = new BufferedReader(new FileReader("myBinaryIntegers.dat")); outputStream = new PrintWriter(new FileOutputStream("myBinaryIntegers.txt")); System.out.println("Loading binary integers..."); String line = inputStream.readLine(); while (line != null) { // System.out.println(line); outputStream.print(line); line = inputStream.readLine(); } outputStream.close(); inputStream.close(); System.out.println("Done with read in binary integers!"); } catch (FileNotFoundException e) { System.out.println("File cannot be found when open for read."); } catch (IOException e) { System.out.println("Error reading."); } long end = System.currentTimeMillis(); System.out.println("Took: " + ((end - start)) + "ms"); }
public static void execute(String[] args) { try { String hs2mmFile = args[0]; HashMap human2mouse = human2mouse(hs2mmFile); String inputFile = args[1]; String outputFile = args[2]; FileWriter fwriter = new FileWriter(outputFile); BufferedWriter out = new BufferedWriter(fwriter); FileInputStream fstream = new FileInputStream(inputFile); DataInputStream din = new DataInputStream(fstream); BufferedReader in = new BufferedReader(new InputStreamReader(din)); while (in.ready()) { String str = in.readLine(); String[] split = str.split("\t"); out.write(split[0] + "\t" + split[1]); for (int i = 2; i < split.length; i++) { if (human2mouse.containsKey(split[i])) { out.write("\t" + (String) human2mouse.get(split[i])); } } out.write("\n"); } in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
public static String submitPostData(String pos, String data) throws IOException { Log.v("req", data); URL url = new URL(urlPre + pos); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); configConnection(connection); if (sCookie != null && sCookie.length() > 0) { connection.setRequestProperty("Cookie", sCookie); } connection.connect(); // Send data DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(data.getBytes()); output.flush(); output.close(); // check Cookie String cookie = connection.getHeaderField("set-cookie"); if (cookie != null && !cookie.equals(sCookie)) { sCookie = cookie; } // Respond BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } connection.disconnect(); String res = sb.toString(); Log.v("res", res); return res; }
public static void main(String[] args) throws Exception { /* BufferedReader br=new BufferedReader(new FileReader("input.txt")); BufferedWriter out=new BufferedWriter(new FileWriter("output.txt")); */ BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int q = Integer.parseInt(s[1]); int num[] = new int[n + 1]; int[] m = new int[3 * n + 1]; // size = 2*n+1 Arrays.fill(num, -1); s = br.readLine().split(" "); for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]); /// build tree maketree(1, 1, n, m, num); for (int qq = 1; qq <= q; qq++) { s = br.readLine().split(" "); int i = Integer.parseInt(s[0]); int j = Integer.parseInt(s[1]); int ans = query(1, 1, n, m, num, i, j); out.write("" + num[ans] + "\n"); out.flush(); } }
public String getLauncherDetails(String prefix) { try { final String javaVersionCommand = javaCommand + " -version"; Process proc = Runtime.getRuntime().exec(javaVersionCommand); try { InputStream inputStream = proc.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(prefix); buffer.append(line); buffer.append('\n'); } return buffer.toString(); } finally { proc.destroy(); } } catch (Exception e) { throw new RuntimeException(e); } }
public static void main(String[] args) throws Exception { Do_Not_Terminate.forbidExit(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o; // Must be used to hold the reference of the instance of // the class Solution.Inner.Private Inner in = new Inner(); o = in.new Private(); Class<?> clz = Class.forName(Solution3.class.getName() + "$Inner$Private"); for (Method m : clz.getDeclaredMethods()) { if (m.getName().indexOf("powerof2") > -1) { m.setAccessible(true); System.out.println(num + " is " + m.invoke(o, num)); } } // TODO System.out.println( "An instance of class: " + o.getClass().getCanonicalName() + " has been created"); } // end of try catch (Do_Not_Terminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } } // end of main
/** * 读取文件 * * @param 文件路径 * @param 字符集名称一个受支持的名称 * @return 如果文件不存在,返回null,否则返回文件的内容 * @throws RuntimeException if an error occurs while operator BufferedReader */ public static StringBuilder readFile(String filePath, String charsetName) { File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } reader.close(); return fileContent; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } } } }
/** * 从文件读取json字符串 * * @param path 目录 * @param name 文件名称 * @return 返回字符串 */ public static String readJsonFromFile(String path, String name) { if (StringUtils.isEmpty(path) || StringUtils.isEmpty(name)) { return null; } String content = ""; File file = new File(path + name); if (!file.exists()) { return null; } InputStream in = null; try { in = new FileInputStream(file); if (in != null) { InputStreamReader inputreader = new InputStreamReader(in); BufferedReader buffreader = new BufferedReader(inputreader); String line; // 分行读取 while ((line = buffreader.readLine()) != null) { content += line; } in.close(); } } catch (IOException e) { e.printStackTrace(); return null; } return content; }
/** * 读文件的字符串列表,列表的元素是一条线 * * @param 文件路径 * @param 字符集名称一个支持的名字 * @return 如果文件不存在,返回null,否则返回文件的内容 * @throws RuntimeException 如果为空责返回异常 */ public static List<String> readFileToList(String filePath, String charsetName) { File file = new File(filePath); List<String> fileContent = new ArrayList<String>(); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { fileContent.add(line); } reader.close(); return fileContent; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } } } }
public static int ramSize() { if (mRamSize == 0) { BufferedReader br = null; try { br = new BufferedReader(new FileReader("/proc/meminfo"), 1024); String line = br.readLine(); /* * # cat /proc/meminfo MemTotal: 94096 kB MemFree: 1684 kB */ if (!TextUtils.isEmpty(line)) { String[] splits = line.split("\\s+"); if (splits.length > 1) { mRamSize = Integer.valueOf(splits[1]).intValue(); } } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } return mRamSize; }
public static String cpuArch() { if (mCPUArch == null) { /** * Email from [email protected] in 2014/06/27 said their new x86 ROM modifies the * android.os.abi to make the Build.CPU_ABI to always return "armeabi-v7a" and recommended * following method to get real CPU arch. */ BufferedReader ibr = null; try { Process process = Runtime.getRuntime().exec("getprop ro.product.cpu.abi"); ibr = new BufferedReader(new InputStreamReader(process.getInputStream())); mCPUArch = ibr.readLine(); } catch (IOException e) { } finally { if (ibr != null) { try { ibr.close(); } catch (IOException e) { } } } if (TextUtils.isEmpty(mCPUArch)) { // if meet something wrong, get cpu arch from android sdk. mCPUArch = Build.CPU_ABI; } } return mCPUArch; }
public void parseFile(File file) { log.debug("Will attempt to process the file: " + file.getAbsolutePath()); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { log.error("Unable to read the input file. Error: " + e); throw new RuntimeException("Unable to read the input file."); } try { boolean done = false; int lineIndex = 0; while (!done) { String line = reader.readLine(); if (line == null) { done = true; continue; } processLine(line, lineIndex++); } } catch (IOException e) { log.error("Failed while loading the input file. Error: " + e); throw new RuntimeException("Failed while loading the input file."); } }
/** * Uses the command line arguments to authenticate the GoogleService and build the basic feed URI, * then invokes all the other methods to demonstrate how to interface with the Translator toolkit * service. * * @param args See the usage method. */ public static void main(String[] args) { try { // Connect to the Google translator toolkit service GttService service = new GttService("sample.gtt.GttClient"); // Login if there is a command line argument for it. if (args.length >= 1 && NAME_TO_COMMAND_MAP.get(args[0]) == GttCommand.LOGIN) { GttCommand.LOGIN.execute(service, args); } // Input stream to get user input BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Do some actions based on user input while (true) { // Get user input System.out.print(USER_PROMPT); System.out.flush(); String userInput = in.readLine(); System.out.println(); // Do action corresponding to user input String[] commandArgs = userInput.split("\\s+"); GttCommand command = NAME_TO_COMMAND_MAP.get(commandArgs[0]); if (command != null) { command.execute(service, commandArgs); } else { System.out.println("Sorry I did not understand that."); } } } catch (IOException ioe) { ioe.printStackTrace(); } }
private void readFreeLinks() { try { FileReader fr = new FileReader(this.linkIdFile); BufferedReader br = new BufferedReader(fr); String curr_line = br.readLine(); while ((curr_line = br.readLine()) != null) { String[] entries = curr_line.split("\t", -1); Id<Link> lId = Id.create(entries[0], Link.class); LinkRetailersImpl l = new LinkRetailersImpl( this.scenario.getNetwork().getLinks().get(lId), this.scenario.getNetwork(), Double.valueOf(0.0D), Double.valueOf(0.0D)); this.freeLinks.add(l); this.allLinks.put(l.getId(), l); } br.close(); } catch (IOException e) { } }
// This method will read synapse.xml files public String readSynapseFile() throws Exception { ESBCommon esbCommon = new ESBCommon(selenium); Properties properties = new Properties(); String conCatLines = "exact:"; try { // Open the file FileInputStream fstream = new FileInputStream(esbCommon.getCarbonHome() + "/conf/synapse.xml"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { strLine = strLine.trim(); conCatLines = conCatLines + strLine + " "; } // Close the input stream in.close(); // return conCatLines; } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } return conCatLines; }
public void run() { System.out.println("New Communication Thread Started"); try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; String[] inputTemp = new String[3]; while ((inputLine = in.readLine()) != null) { System.out.println("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
/* * メインメソッド * * @param 実行時の引数 */ public static void main(String[] args) { System.out.println("じゃんけんをしましょう!"); System.out.println("1:グー、 2:チョキ 3:パー"); int userHand = 0; Random rdm = new Random(); // ユーザの手の入力 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean isFinish = false; while (!isFinish) { try { // コンピュータの手(ランダム) int comHandNum = rdm.nextInt(3) + 1; // ユーザの手(入力) String str = br.readLine(); userHand = Integer.parseInt(str); // 正しい入力範囲かの確認 if (userHand == ROCK_NUM || userHand == PAPER_NUM || userHand == SCISSORS_NUM) { // 出した手を確認 System.out.println( "あなたは:" + getHandName(userHand) + " コンピュータは:" + getHandName(comHandNum)); // 終了と勝ち負けの判定 isFinish = isNotDraw(userHand, comHandNum); } else { System.out.println("1〜3で入力してください!"); } } catch (NumberFormatException e) { System.out.println("1〜3で入力してください!"); } catch (IOException e) { System.out.println("予期せぬエラーが発生しました"); return; } } }
// Read from file public void readFile(String fileName) { // TODO Auto-generated method stub try { FileReader frStream = new FileReader(fileName); BufferedReader brStream = new BufferedReader(frStream); String inputLine; int i = 0; Vector<Object> currentRow = new Vector<Object>(); while ((inputLine = brStream.readLine()) != null) { // Ignore the file comment if (inputLine.startsWith("#")) continue; // Extract the column name if (inputLine.startsWith("$")) { StringTokenizer st1 = new StringTokenizer(inputLine.substring(1), " "); while (st1.hasMoreTokens()) colName.addElement(st1.nextToken()); } else // Extract data and put into the row records { StringTokenizer st1 = new StringTokenizer(inputLine, " "); currentRow = new Vector<Object>(); while (st1.hasMoreTokens()) currentRow.addElement(st1.nextToken()); data.addElement(currentRow); } } brStream.close(); } catch (IOException ex) { System.out.println("Error in readFile method! " + ex); } }
@Override public ArrayList<Datum> readOneTuple() { if (buffer == null) return null; String line = null; try { line = buffer.readLine(); } catch (IOException e) { // e.printStackTrace(); return null; } if (line == null || line.isEmpty()) { try { buffer.close(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } String col[] = line.split("\\|"); ArrayList<Datum> tuples = new ArrayList<>(); for (int counter = 0; counter < col.length; counter++) { if (indexMaps.containsKey(counter)) { String type = indexMaps.get(counter); tuples.add(new Datum(type.toLowerCase(), col[counter])); } } return tuples; }
/** this void method runs the command created in the constructor. */ public void runTesseract() { LOGGER.info( "Trying to run command: " + command[0] + " " + command[1] + " " + command[2] + " " + command[3] + " " + command[4]); System.out.println("Trying to run command: " + Arrays.toString(command)); try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code " + exitVal); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
private List<Article> loadNewsFromFile(Context context) { startedLoadingNews = true; List<Article> articles = new ArrayList<>(); if (newsFile == null) newsFile = new File(context.getFilesDir(), NEWS_FILE_NAME); if (newsFile.exists()) { try { BufferedReader reader = new BufferedReader(new FileReader(newsFile)); String currentLine = reader.readLine(); if (currentLine != null) { String[] split = currentLine.split("-"); if (split.length > 1) { for (int i = 0; i < Integer.parseInt(split[1]); i++) { // TODO figure out why all lines, after i = 18, are null. currentLine = reader.readLine(); Article a = readArticle(reader); articles.add(a); Log.d("q32", "" + i + "line: " + currentLine); } } else { updateNews(context); } // if we didn't find the number of articles, the file must be corrupt. Update the file. } else updateNews(context); } catch (IOException e) { Log.d("Unit5Calendar", e.getMessage(), e); } Collections.sort(newsArticles, Utils.articlePubDateSorter); newsReady = true; } return articles; }
private void showBoundingBox() { try { BufferedReader br = new BufferedReader( new FileReader( Constants.RESULT_PATH + File.separator + "17_BTS_near_work_home_bounding_box" + File.separator + numbers.get(chainIndex))); String line; while ((line = br.readLine()) != null) { String[] tokens = line.split("\t"); float lat = Float.valueOf(tokens[1]); float lng = Float.valueOf(tokens[2]); float[] xy = this.map.getScreenPositionFromLocation(new Location(lat, lng)); stroke(0xFF5ffb32); fill(0xFF5ffb32); ellipse(xy[0], xy[1], 5, 5); } br.close(); } catch (IOException ioe) { logger.error("not happened", ioe); } }
/** * * test each position how many times it can be back calculate the LCM for all the moves of each * position */ void LCM() throws NumberFormatException, IOException { int N = Integer.parseInt(in.readLine()); p = new int[N + 1]; test = new int[N + 1]; String[] ps = in.readLine().split(" "); for (int i = 0; i < N; i++) { p[i + 1] = Integer.parseInt(ps[i]); test[i + 1] = p[i + 1]; } for (int i = 1; i <= N; i++) { int t = 1; while (test[i] != i) { test[i] = p[test[i]]; t++; } test[i] = t; // out.printf("%d ",t); } int a = test[1]; for (int i = 2; i <= N; i++) { a = calLCM(a, test[i]); } out.println(a); }
protected String getPrefix(File cwd, String path) { try { InputStream input = new FileInputStream(Util.makePath(cwd, path)); InputStreamReader inputReader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputReader); for (; ; ) { String line = reader.readLine(); if (line == null) break; else line = line.trim(); if (!line.startsWith("package ")) continue; line = line.substring(8); if (line.endsWith(";")) line = line.substring(0, line.length() - 1); line = line.replace(".", "/"); int slash = path.lastIndexOf("/"); int backslash = path.lastIndexOf("\\"); if (backslash > slash) slash = backslash; if (path.endsWith(line + path.substring(slash))) return path.substring(0, path.length() - line.length() - path.length() + slash); } int slash = path.lastIndexOf('/'); return path.substring(0, slash + 1); } catch (Exception e) { e.printStackTrace(); return null; } }
public T load(File f) throws IOException, JsonSyntaxException { if (!f.isFile()) { return null; } T doc = null; BufferedReader reader = new BufferedReader(new FileReader(f)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); doc = (T) gson.fromJson(sb.toString(), myClass); fileCache.put(doc, f); doc.setSaved(true); doc.getInternalID(); addMedia(doc); System.out.println("Loaded: " + doc.getSaveString() + " " + doc.getClass().getSimpleName()); if (MediaBase.class.isAssignableFrom(doc.getClass())) { ((MediaBase) doc).load(); } return doc; }