예제 #1
0
  // trained data
  void trainedWeights() {

    weightUpdate.clear();

    try {

      String line;

      FileReader fileReader = new FileReader("WeightFile.txt");

      BufferedReader bufferedReader = new BufferedReader(fileReader);

      while ((line = bufferedReader.readLine()) != null) {

        String[] lineSplit = line.split(" ");

        weightUpdate.put(
            weightKey(Integer.parseInt(lineSplit[0]), Integer.parseInt(lineSplit[1])),
            Double.parseDouble(lineSplit[2]));
      }

      bufferedReader.close();

    } catch (FileNotFoundException ex) {
      System.out.println("File Reading Error");
    } catch (IOException ex) {

      System.out.println("Error reading to file ");
    }
  }
예제 #2
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
예제 #3
0
  public CryoBay reconnectServer(ORB o, ReconnectThread rct) {

    BufferedReader reader;
    File file;
    ORB orb;
    org.omg.CORBA.Object obj;

    orb = o;

    obj = null;
    cryoB = null;

    try {
      // instantiate ModuleAccessor
      file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
      if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        obj = orb.string_to_object(reader.readLine());
      }

      if (obj != null) {
        cryoB = CryoBayHelper.narrow(obj);
      }

      if (cryoB != null) {
        if (!(cryoB._non_existent())) {
          // System.out.println("reconnected!!!!");
          rct.reconnected = true;
        }
      }
    } catch (Exception e) {
      // System.out.println("Got error: " + e);
    }
    return cryoB;
  }
예제 #4
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
예제 #5
0
파일: Chart.java 프로젝트: feihugis/NetCDF
  public Chart(String filename) {
    try {
      // Get Stock Symbol
      this.stockSymbol = filename.substring(0, filename.indexOf('.'));

      // Create time series
      TimeSeries open = new TimeSeries("Open Price", Day.class);
      TimeSeries close = new TimeSeries("Close Price", Day.class);
      TimeSeries high = new TimeSeries("High", Day.class);
      TimeSeries low = new TimeSeries("Low", Day.class);
      TimeSeries volume = new TimeSeries("Volume", Day.class);

      BufferedReader br = new BufferedReader(new FileReader(filename));
      String key = br.readLine();
      String line = br.readLine();
      while (line != null && !line.startsWith("<!--")) {
        StringTokenizer st = new StringTokenizer(line, ",", false);
        Day day = getDay(st.nextToken());
        double openValue = Double.parseDouble(st.nextToken());
        double highValue = Double.parseDouble(st.nextToken());
        double lowValue = Double.parseDouble(st.nextToken());
        double closeValue = Double.parseDouble(st.nextToken());
        long volumeValue = Long.parseLong(st.nextToken());

        // Add this value to our series'
        open.add(day, openValue);
        close.add(day, closeValue);
        high.add(day, highValue);
        low.add(day, lowValue);

        // Read the next day
        line = br.readLine();
      }

      // Build the datasets
      dataset.addSeries(open);
      dataset.addSeries(close);
      dataset.addSeries(low);
      dataset.addSeries(high);
      datasetOpenClose.addSeries(open);
      datasetOpenClose.addSeries(close);
      datasetHighLow.addSeries(high);
      datasetHighLow.addSeries(low);

      JFreeChart summaryChart = buildChart(dataset, "Summary", true);
      JFreeChart openCloseChart = buildChart(datasetOpenClose, "Open/Close Data", false);
      JFreeChart highLowChart = buildChart(datasetHighLow, "High/Low Data", true);
      JFreeChart highLowDifChart =
          buildDifferenceChart(datasetHighLow, "High/Low Difference Chart");

      // Create this panel
      this.setLayout(new GridLayout(2, 2));
      this.add(new ChartPanel(summaryChart));
      this.add(new ChartPanel(openCloseChart));
      this.add(new ChartPanel(highLowChart));
      this.add(new ChartPanel(highLowDifChart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  static int doTest(BufferedReader in, PrintWriter out, boolean writeNewFile) throws Exception {
    int errorCount = 0;

    String key = null;
    String expectedValue = null;
    String line = in.readLine();
    while (line != null) {
      if (line.startsWith("#") || line.length() == 0) {
        if (writeNewFile) out.println(line);
      } else {
        int index = line.indexOf("=");
        if (index == -1) {
          key = line;
          expectedValue = "";
        } else {
          key = line.substring(0, index);
          if (index + 1 == line.length()) expectedValue = "";
          else expectedValue = line.substring(index + 1);
        }
        if (!processLine(key, expectedValue, out, writeNewFile)) ++errorCount;
      }
      line = in.readLine();
    }
    return errorCount;
  }
예제 #7
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
예제 #8
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int a[] = new int[n];
    int c[] = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = Integer.parseInt(br.readLine());
    }

    for (int i = 0; i < n; i++) {
      c[i] = 1;
    }

    for (int j = 1; j < n; j++) {
      if (a[j] > a[j - 1]) c[j] = c[j - 1] + 1;
    }

    for (int k = n - 2; k >= 0; k--) {
      if (a[k] > a[k + 1]) c[k] = Math.max(c[k + 1] + 1, c[k]);
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
      count += c[i];
    }

    System.out.println(count);
  }
예제 #9
0
파일: Model.java 프로젝트: Jankish/GRAB
 private void extractInfo(File filename) {
   checkpoint = false;
   String line;
   try {
     ArrayList<String> order = new ArrayList<String>();
     BufferedReader input =
         new BufferedReader(new InputStreamReader(new FileInputStream(filename), "iso-8859-1"));
     while ((line = input.readLine()) != null) {
       if (line.equalsIgnoreCase("hämtas")) checkpoint = true;
       if (checkpoint) order.add(new String(line));
     }
     //	printList(order);
     int quant = Integer.parseInt(order.get(2));
     int rows = 9;
     int outer = (quant * rows);
     double price;
     double total;
     // DecimalFormat decimal = (DecimalFormat) format;
     Number number;
     for (int i = 4; i <= outer; i += 9) {
       Data d =
           new Data(
               order.get(i + 1),
               order.get(i + 3),
               order.get(i + 4),
               order.get(i + 5),
               order.get(i + 7));
       dataList.add(d);
       /*	try {
       System.out.println(order.get(i+5));
       number = format.parse(order.get(i+5));
       System.out.println("Number is " + number);
       price = number.doubleValue();
       System.out.println("Price is " + price);
       number = format.parse(order.get(i+7));
       total = number.doubleValue();
       Data d = new Data(order.get(i), Integer.parseInt(order.get(i+1)), Integer.parseInt(order.get(i+2)), order.get(i+3), order.get(i+4), price, total);
       dataList.add(d);
       } catch (ParseException numExcep) {
       numExcep.printStackTrace();
       System.exit(1);
       }
       **/
     }
     //	printDataList(dataList);
   } catch (FileNotFoundException found) {
     found.printStackTrace();
     System.exit(1);
   } catch (UnsupportedEncodingException encode) {
     encode.printStackTrace();
     System.exit(1);
   } catch (IOException ioexcep) {
     ioexcep.printStackTrace();
     System.exit(1);
   }
 }
예제 #10
0
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
      int tIndex = 0;
      int pIndex = 0;

      // This will probably change soon (name and implementation)
      NgramParser tnp = new NgramParser(args[1]);

      ArrayList<String> triplet = tnp.getTriplet();
      ArrayList<String> polarity = tnp.getPolarity();

      FileWriter sw = new FileWriter(args[2]);
      String line = null;

      while (((line = br.readLine()) != null)
          && (tIndex < triplet.size())
          && (pIndex < polarity.size())) {
        if (line.matches("^[\\d]*:")) {
          // System.out.println(line);
          sw.write(line + "\n");
        } else {
          Scanner sc = new Scanner(line);
          String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*"));
          // if (trip != null && trip.equals(triplet.get(tIndex))) {
          System.out.println(trip);
          if (trip != null && !trip.toLowerCase().contains("no#cl")) {
            // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex));
            String pol = polarity.get(pIndex);
            sw.write(line + " " + pol + "\n");
            sc.close();
            tIndex++;
            pIndex++;
          } else {
            String pol = "neg";
            sw.write("no#a#1" + " " + pol + "\n");
            sc.close();
          }
        }

        // sw.flush();
      }

      sw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #12
0
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }
예제 #13
0
  protected void load() throws IOException {

    BufferedReader is = new BufferedReader(new FileReader("ReminderService.txt"));
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd hh mm");
    String aLine;
    while ((aLine = is.readLine()) != null) {
      ParsePosition pp = new ParsePosition(0);
      Date date = formatter.parse(aLine, pp);
      if (date == null) {
        message("Invalid date in " + aLine);
        continue;
      }
      String mesg = aLine.substring(pp.getIndex());
      l.add(new Item(date, mesg));
    }
  }
예제 #14
0
 public String readword() throws IOException {
   StringBuilder b = new StringBuilder();
   int c;
   c = in.read();
   while (c >= 0 && c <= ' ') {
     c = in.read();
   }
   if (c < 0) {
     return "";
   }
   while (c > ' ') {
     b.append((char) c);
     c = in.read();
   }
   return b.toString();
 }
예제 #15
0
 public static String ping(String address) {
   String reply = "Request timed out";
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (line.trim().startsWith("Reply ")) {
         reply = line;
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return reply;
 }
예제 #16
0
  private static void readLinkFile(boolean isHighway) {
    System.out.println("read link file...");
    int debug = 0;
    try {
      FileInputStream fstream =
          new FileInputStream(root + "/" + (isHighway ? highwayLinkFile : arterialLinkFile));
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        debug++;
        String[] nodes = strLine.split(";");
        int linkId = Integer.parseInt(nodes[0]);
        String allDir = nodes[1];
        String streetName = nodes[2];
        int funcClass = Integer.parseInt(nodes[3]);
        ArrayList<PairInfo> nodeList = getPairListFromStr(nodes[4]);
        int speedCat = Integer.parseInt(nodes[5]);
        String dirTravel = nodes[6];
        int startNode = Integer.parseInt(nodes[7]);
        int endNode = Integer.parseInt(nodes[8]);

        LinkInfo linkInfo =
            new LinkInfo(
                linkId,
                funcClass,
                streetName,
                startNode,
                endNode,
                nodeList,
                dirTravel,
                speedCat,
                allDir);

        if (isHighway) highwayLinkList.add(linkInfo);
        else arterialLinkList.add(linkInfo);

        if (debug % 100000 == 0) System.out.println("record " + debug + " finish!");
      }
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      System.err.println("Error Code: " + debug);
    }
    System.out.println("read link file finish!");
  }
  /**
   * Gets the value of the specified environment variable.
   *
   * @param ses SSH session.
   * @param cmd environment variable name.
   * @return environment variable value.
   * @throws JSchException In case of SSH error.
   * @throws IOException If failed.
   */
  private String exec(Session ses, String cmd) throws JSchException, IOException {
    ChannelExec ch = null;

    try {
      ch = (ChannelExec) ses.openChannel("exec");

      ch.setCommand(cmd);

      ch.connect();

      try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream()))) {
        return reader.readLine();
      }
    } finally {
      if (ch != null && ch.isConnected()) ch.disconnect();
    }
  }
예제 #18
0
 private CIJob getJob(ApplicationInfo appInfo) throws PhrescoException {
   Gson gson = new Gson();
   try {
     BufferedReader br = new BufferedReader(new FileReader(getCIJobPath(appInfo)));
     CIJob job = gson.fromJson(br, CIJob.class);
     br.close();
     return job;
   } catch (FileNotFoundException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   } catch (com.google.gson.JsonParseException e) {
     S_LOGGER.debug("it is already adpted project !!!!! " + e.getLocalizedMessage());
     return null;
   } catch (IOException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   }
 }
예제 #19
0
 public static Properties getEnvironmentVariables() {
   synchronized (cygstartPath) {
     if (envVars != null) return envVars;
     envVars = new Properties();
     try (BufferedReader br =
         new BufferedReader(
             new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) {
       for (String line = null; (line = br.readLine()) != null; ) {
         // if (debug) System.out.println("getEnvironmentVariables(): line=" + line);
         int idx = line.indexOf('=');
         if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1));
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
     return envVars;
   }
 }
  public static void main(String[] args) throws Exception {

    // set up our flags and our input and output streams based on the
    // command-line arguments (exceptions generated here will propagate out
    // to the environment)
    BufferedReader in = null;
    PrintWriter out = null;
    boolean writeNewFile = false;
    boolean doThrow = true;

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-w")) {
        writeNewFile = true;
        doThrow = false;
      } else if (args[i].equals("-nothrow")) doThrow = false;
      else if (args[i].equals("-s") && in == null)
        in = new BufferedReader(new EscapeReader(new InputStreamReader(System.in, "ISO8859_1")));
      else if (!args[i].startsWith("-") && in == null)
        in =
            new BufferedReader(
                new EscapeReader(new InputStreamReader(new FileInputStream(args[i]), "ISO8859_1")));
    }
    if (in == null) {
      File localeData = new File(System.getProperty("test.src", "."), "LocaleData");
      in =
          new BufferedReader(
              new EscapeReader(
                  new InputStreamReader(new FileInputStream(localeData), "ISO8859_1")));
    }
    out = new PrintWriter(new EscapeWriter(new OutputStreamWriter(System.out, "ISO8859_1")), true);

    // perform the actual test
    int errorCount = doTest(in, out, writeNewFile);

    // write out the error count, and throw an exception out into the environment
    // if there were any errors
    if (errorCount != 0) {
      if (!writeNewFile) out.println("Test failed.  " + errorCount + " errors.");
      if (doThrow) throw new Exception("Test failed.  " + errorCount + " errors.");
    } else if (!writeNewFile) out.println("Test passed.");

    in.close();
    out.close();
  }
예제 #21
0
  // You shouldn't modify this function
  // This function gets an update from the server each time your car reaches a new node
  // The server supplies you with the following information:
  //      1. Reward/cost information: travelCost: the cost (measured in happiness units) you
  // incurred for traveling over the last link
  //                               payout: the number of happiness units you got for arriving at the
  // current node
  //                               tollCharge: the amount of toll charge you incurred for traveling
  // the latest link
  //      2. currentNode: the current node position your car is at in the world (value between 0-3)
  //      3. currentUtilitiesforVisitingNode [array of 4]: The number of happiness units you will
  // get in the future for arriving at each of the 4 nodes
  public boolean readStatusMessage() {
    try {
      //            System.out.println(sin.readLine());
      String[] buf = sin.readLine().split(" ");

      if (buf[0].equals("quit")) return false;

      travelCost = Double.valueOf(buf[1]);
      payout = Double.valueOf(buf[2]);
      tollCharge = Double.valueOf(buf[3]);
      System.out.println("Results: " + travelCost + " " + payout + " " + tollCharge);

      // parse my current position in the world
      String[] buf2 = sin.readLine().split(" ");
      currentNode = Integer.valueOf(buf2[1]);
      System.out.println("Position: " + currentNode);

      // parse my utilities for visiting each node
      String[] buf3 = sin.readLine().split(" ");
      int i;
      for (i = 0; i < numNodes; i++)
        currentUtilitiesforVisitingNodes[i] = Double.valueOf(buf3[i + 1]);
      System.out.println(
          "Utilities: "
              + currentUtilitiesforVisitingNodes[0]
              + " "
              + currentUtilitiesforVisitingNodes[1]
              + " "
              + currentUtilitiesforVisitingNodes[2]
              + " "
              + currentUtilitiesforVisitingNodes[3]);

      // parse linkState stuff
      String[] buf4 = sin.readLine().split(" ");
      aveOnLink = Double.valueOf(buf4[1]);
      capacity = Integer.parseInt(buf4[2]);
      System.out.println("linkState: " + aveOnLink + " " + capacity);
    } catch (IOException e) {
      System.out.println(e);
      return false;
    }

    return true;
  }
예제 #22
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
예제 #23
0
 public List<CIJob> getJobs(ApplicationInfo appInfo) throws PhrescoException {
   S_LOGGER.debug("GetJobs Called!");
   try {
     boolean adaptedProject = adaptExistingJobs(appInfo);
     S_LOGGER.debug("Project adapted for new feature => " + adaptedProject);
     Gson gson = new Gson();
     BufferedReader br = new BufferedReader(new FileReader(getCIJobPath(appInfo)));
     Type type = new TypeToken<List<CIJob>>() {}.getType();
     List<CIJob> jobs = gson.fromJson(br, type);
     br.close();
     return jobs;
   } catch (FileNotFoundException e) {
     S_LOGGER.debug("FileNotFoundException");
     return null;
   } catch (IOException e) {
     S_LOGGER.debug("IOException");
     throw new PhrescoException(e);
   }
 }
예제 #24
0
  public ClientGui(ORB o) throws Exception {
    ShutdownFrame sf;
    BufferedReader reader;
    boolean modulePresent;
    File file;
    CryoThread update;

    orb = o;

    obj = null;
    cryoBay = null;

    // System.out.println("running test client.");

    // instantiate ModuleAccessor
    file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
    if (file.exists()) {
      reader = new BufferedReader(new FileReader(file));
      obj = orb.string_to_object(reader.readLine());
    }

    if (obj == null) {
      throw new Exception("string_to_object is null: cryoBay.CORBAref");
    }

    // System.out.println("Got object.");

    cryoBay = CryoBayHelper.narrow(obj);

    if (cryoBay == null) {
      throw new Exception("cryoBay is null");
    }

    if (cryoBay._non_existent()) {
      throw new Exception("cryoBay is not running");
    }

    sf = new ShutdownFrame(cryoBay);
    update = new CryoThread(cryoBay, sf, this);
    sf.show();
    update.start();
  } /*end of constructor*/
  public List<MarketSnapshot> load(ProgressListener progressListener) throws JBookTraderException {
    String line = "";
    int lineSeparatorSize = System.getProperty("line.separator").length();
    long sizeRead = 0, lineNumber = 0;

    List<MarketSnapshot> snapshots = new ArrayList<MarketSnapshot>();

    try {
      while ((line = reader.readLine()) != null) {
        if (lineNumber % 50000 == 0) {
          progressListener.setProgress(sizeRead, fileSize, "Loading historical data file");
          if (progressListener.isCancelled()) {
            break;
          }
        }
        lineNumber++;
        sizeRead += line.length() + lineSeparatorSize;
        boolean isComment = line.startsWith("#");
        boolean isProperty = line.contains("=");
        boolean isBlankLine = (line.trim().length() == 0);
        boolean isMarketDepthLine = !(isComment || isProperty || isBlankLine);
        if (isMarketDepthLine) {
          MarketSnapshot marketSnapshot = toMarketDepth(line);
          if (filter == null || filter.contains(time)) {
            snapshots.add(marketSnapshot);
          }
          previousTime = time;
        } else if (isProperty) {
          if (line.startsWith("timeZone")) {
            setTimeZone(line);
          }
        }
      }

      if (sdf == null) {
        String msg = "Property " + "\"timeZone\"" + " is not defined in the data file." + LINE_SEP;
        throw new JBookTraderException(msg);
      }

    } catch (IOException ioe) {
      throw new JBookTraderException("Could not read data file");
    } catch (Exception e) {
      String errorMsg = "Problem parsing line #" + lineNumber + ": " + line + LINE_SEP;
      String description = e.getMessage();
      if (description == null) {
        description = e.toString();
      }
      errorMsg += description;
      throw new RuntimeException(errorMsg);
    }

    return snapshots;
  }
예제 #26
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int i, j;
    String amount = req.getParameter("amount");
    String from = req.getParameter("from");
    String to = req.getParameter("to");
    String ch = req.getParameter("choice");
    String answer, answer1, answer2, answer3;

    if ("INFO".equals(ch)) {
      Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect");
      res.sendRedirect(newurl.getUrl());
    } else {
      out.println("<html>");
      out.println("<title>Currency Converter</title>");
      String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to;
      URL convert = new URL(addr);
      BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream()));
      answer = in.readLine();
      answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7");
      from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7");
      to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7");
      amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7");

      in.close();
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(i + 1);
      i = answer.indexOf('"');
      answer = answer.substring(0, i);
      out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>");
      out.println("</body>");
      out.println("</html>");
    }
  }
예제 #27
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    int T = 0;
    int N = 0;
    int answer = 1;
    int temp = 0;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    s = in.readLine();
    while ((s = in.readLine()) != null && s.length() != 0) {
      temp = Integer.parseInt(s);
      for (int j = 0; j < temp / 2; j++) {
        answer = (int) (answer * 2 + 1);
      }

      if (temp % 2 != 0) {
        answer *= 2;
      }
      System.out.println(answer);
      answer = 1;
    }
  }
예제 #28
0
파일: STRQ.java 프로젝트: jmankhan/ACM
  public void solve() throws Exception {
    String str = in.readLine();
    int n = str.length();

    int t = Integer.parseInt(in.readLine());

    int[][] dp = new int[26][n];

    dp[str.charAt(0) - 'a'][0] = 1;

    for (int i = 1; i < n; i++) {
      for (int j = 0; j < 26; j++) {
        if (str.charAt(i) == 'a' + j) {
          dp[j][i] = dp[j][i - 1] + 1;
        } else {
          dp[j][i] = dp[j][i - 1];
        }
      }
    }

    while (t-- > 0) {
      st = new StringTokenizer(in.readLine());
      char a = st.nextToken().toCharArray()[0];
      char b = st.nextToken().toCharArray()[0];

      int l = parseInt(st.nextToken()) - 1;
      int r = parseInt(st.nextToken()) - 1;

      int ans = 0;
      for (int i = l; i <= r; i++) {
        if (str.charAt(i) == a) {
          ans += dp[b - 'a'][r] - dp[b - 'a'][i];
        }
      }

      out.println(ans);
    }
  }
 public static void main(String[] args) throws Exception {
   BufferedReader st = new BufferedReader(new InputStreamReader(System.in));
   StringTokenizer s;
   s = new StringTokenizer(st.readLine());
   int n = Integer.parseInt(s.nextToken());
   int r = Integer.parseInt(s.nextToken()) - 1;
   visited = new int[n];
   int i, a, b;
   for (i = 0; i < n; i++) {
     adjList.add(new ArrayList<Integer>());
   }
   for (i = 0; i < n - 1; i++) {
     s = new StringTokenizer(st.readLine());
     a = Integer.parseInt(s.nextToken());
     b = Integer.parseInt(s.nextToken());
     adjList.get(a - 1).add(b - 1);
     adjList.get(b - 1).add(a - 1);
     visited[a - 1] = 0;
     visited[b - 1] = 0;
   }
   dfs(r, 0);
   System.out.println(maxh + " " + minh);
 }
예제 #30
0
  public Duder(String args[]) {

    getConnected(args);

    play();

    try {
      sin.close();
      sout.close();
      s.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }