Beispiel #1
0
 /**
  * It draws the population to a file. A character allele is drawn as 1 o 0. Otherwise, a real
  * allele is drawn in ten points, that represent the interval [0..1] divided in ten fragments. In
  * each fragment, three types of symbol are possible: . --> The fragment is not covered by the
  * classifier. o --> The fragment is partially covered by the classifier. O --> The fragment is
  * totally covered by the classifier.
  *
  * <p>This notation has been obtained from Wilson2000 XCSR
  *
  * @param fout is the file where the population has to be drawn.
  */
 public void draw(PrintWriter fout) {
   double lower = 0, upper = 0;
   if (Config.ternaryRep) {
     fout.print(" " + ((char) rep[0].getAllele()) + " ");
     for (int i = 1; i < rep.length; i++) {
       fout.print("| " + ((char) rep[i].getAllele()) + " ");
     }
   } else {
     if (Config.typeOfAttributes[0].equals("character")) {
       fout.print(" " + ((char) rep[0].getAllele()) + " ");
     } else {
       printInterval(fout, rep[0].getLowerAllele(), rep[0].getUpperAllele());
     }
     for (int i = 1; i < rep.length; i++) {
       if (Config.typeOfAttributes[i].equals("character")) {
         fout.print("| " + ((char) rep[i].getAllele()) + " ");
       } else if (Config.typeOfAttributes[i].equals("integer")) {
         printInterval(i, fout, ((int) rep[i].getLowerAllele()), ((int) rep[i].getUpperAllele()));
       } else {
         printInterval(fout, rep[i].getLowerAllele(), rep[i].getUpperAllele());
       }
     }
   }
   fout.print("\t " + action);
 } // end draw
Beispiel #2
0
 /**
  * It draws the population to a file. A character allele is drawn as 1 o 0. Otherwise, a real
  * allele is drawn in ten points, which represent the interval [0..1] divided in ten fragments. In
  * each fragment, it can be three types of symbols: . --> The fragment is not covered by the
  * classifier. o --> The fragment is partially covered by the classifier. O --> The fragment is
  * totally covered by the classifier.
  *
  * <p>This notation is obtained from Wilson-2000 XCSR
  *
  * @param fout is the file where the population has to be drawn.
  */
 public void drawPopulationToFile(PrintWriter fout) {
   fout.println(macroClSum); // We write the number of macro classifiers.
   fout.println(microClSum); // We write the number of micro classifiers.
   for (int i = 0; i < macroClSum; i++) {
     set[i].draw(fout);
     fout.println("");
   }
 } // end drawPopulationToFile
Beispiel #3
0
 /**
  * Prints the classifier to the specified file.
  *
  * @param fout is the file output where the classifier has to be printed.
  */
 public void print(PrintWriter fout) {
   fout.print(" ");
   for (int i = 0; i < rep.length; i++) {
     rep[i].print(fout);
   }
   fout.print("  " + action + "  ");
   if (parameters != null) parameters.print(fout);
 }
Beispiel #4
0
  /**
   * Prints the classifier to the specified file.
   *
   * @param fout is the output file.
   */
  public void print(PrintWriter fout) {

    fout.print(" ");
    for (int i = 0; i < rep.length; i++) {
      rep[i].print(fout);
    }

    fout.print("\t " + action);
  } // end print
Beispiel #5
0
 public static void make_output(float Sk[])
     throws FileNotFoundException, UnsupportedEncodingException {
   PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
   float temp = (float) 10.0;
   for (int i = 0; i < Sk.length; i++) {
     writer.println(String.valueOf(Sk[i]));
   }
   writer.close();
 }
Beispiel #6
0
 /**
  * Prints the desnormalized population into the specified file.
  *
  * @param fout is the file where the population has to be printed.
  */
 public void printNotNormPopToFile(PrintWriter fout) {
   fout.println(macroClSum); // We write the number of macro classifiers.
   fout.println(microClSum); // We write the number of micro classifiers.
   fout.println(
       "Cond - Action     - prediction - predError - fitness - Numerosity - Experience - aSetSize - Generality - timeStamp");
   for (int i = 0; i < macroClSum; i++) {
     set[i].printNotNorm(fout);
     fout.println("");
   }
 }
Beispiel #7
0
 /**
  * ** Encodes the specified DBRecordKyes into XML and writes it to ** a specified PrintWriter
  * ** @param out The PrintWriter ** @param dbrk The list of DBRecordKeys
  */
 public static void printXML(PrintWriter out, DBRecordKey... dbrk) {
   if (out != null) {
     out.write("<" + DBFactory.TAG_RecordKeys + ">\n");
     for (int i = 0; i < dbrk.length; i++) {
       dbrk[i].printXML(out, 4);
     }
     out.write("</" + DBFactory.TAG_RecordKeys + ">\n");
     out.flush();
   }
 }
  public static void main(String[] args) throws java.lang.Exception {
    // let_me_start

    String s = s();
    String t = s();
    int c[] = new int[150];
    int d[] = new int[150];
    String S = s.toUpperCase();
    String T = t.toUpperCase();
    int C[] = new int[150];
    int D[] = new int[150];

    int n = s.length();
    int m = t.length();

    // int arr[] = is((int)n);

    long ans = 0;
    for (int i = 1; i <= n; i++) {
      c[s.charAt(i - 1)]++;
    }

    for (int i = 1; i <= m; i++) {
      d[t.charAt(i - 1)]++;
    }
    for (int i = 1; i <= n; i++) {
      C[S.charAt(i - 1)]++;
    }

    for (int i = 1; i <= m; i++) {
      D[T.charAt(i - 1)]++;
    }

    int b = 0;
    int min = 1000000000;
    for (int i = 1; i <= 149; i++) {
      b += Math.min(c[i], d[i]);
      d[i] -= Math.min(c[i], d[i]);
    }
    int a = 0;
    min = 1000000000;
    for (int i = 1; i <= 149; i++) {
      a += Math.min(C[i], D[i]);
      D[i] -= Math.min(C[i], D[i]);
    }
    a = a - b;
    out.write("" + b + " " + a + "\n");
    out.flush();
    return;
  }
Beispiel #9
0
 /**
  * It draws an integer interval
  *
  * @param fout is a reference to the file where the classifier has to be drawn.
  * @param numInterval is the position of the interval in the classifier.
  * @param lower is the lower value of the interval
  * @param upper is the upper value of the interval.
  */
 private void printInterval(int numInterval, PrintWriter fout, int lower, int upper) {
   double aux = 0.0;
   int points = Config.realDrawnPrecision;
   int inc =
       ((int) Config.attBounds[numInterval][1] - (int) Config.attBounds[numInterval][0] + 1)
           / points;
   for (int i = 0; i < points; i++) {
     if (i * inc >= lower && i * inc <= upper) {
       fout.print("O");
     } else {
       fout.print(".");
     }
   }
   fout.print(" | ");
 }
  // **********************************************************************************
  //
  // 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);
    }
  }
  void run() throws Exception {
    // for this PS3, you can alter this method as you see fit

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    int TC = Integer.parseInt(br.readLine()); // there will be several test cases
    while (TC-- > 0) {
      br.readLine(); // ignore dummy blank line
      V = Integer.parseInt(br.readLine());

      StringTokenizer st = new StringTokenizer(br.readLine());
      // read rating scores, A (index 0), B (index 1), C (index 2), ..., until the V-th index
      RatingScore = new int[V];
      for (int i = 0; i < V; i++) {
        RatingScore[i] = Integer.parseInt(st.nextToken());
      }

      // clear the graph and read in a new graph as Adjacency Matrix
      AdjMatrix = new TreeMap<Integer, TreeMap<Integer, Boolean>>();
      for (int i = 0; i < V; i++) {
        st = new StringTokenizer(br.readLine());
        int k = Integer.parseInt(st.nextToken());

        TreeMap<Integer, Boolean> g = AdjMatrix.get(i);
        if (g == null) {
          g = new TreeMap<Integer, Boolean>();
          AdjMatrix.put(i, g);
        }

        while (k-- > 0) {
          int j = Integer.parseInt(st.nextToken());

          g.put(j, true);
          TreeMap<Integer, Boolean> gCon = AdjMatrix.get(j);
          if (gCon == null) {
            gCon = new TreeMap<Integer, Boolean>();
            AdjMatrix.put(j, gCon);
          }

          gCon.put(i, true);
        }
      }

      pr.println(Query());
    }
    pr.close();
  }
Beispiel #12
0
  /**
   * Prints the population into the specified file.
   *
   * @param fileName is the file name where the classifiers have to be printed.
   */
  public void printPopulationToFile(String fileName) {

    try {
      PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
      fout.println(macroClSum); // We write the number of macro classifiers.
      fout.println(microClSum); // We write the number of micro classifiers.
      fout.println(
          "Cond - Action  - prediction - predError - fitness - Numerosity - Experience - aSetSize - Generality - timeStamp");
      for (int i = 0; i < macroClSum; i++) {
        set[i].print(fout);
        fout.println("");
      }
      fout.close();
    } catch (IOException eio) {
      System.out.println("ERROR when writing the population to a out file. ");
    }
  } // end printPopulationToFile
Beispiel #13
0
  public static void main(String args[]) {

    wmatrix wmatrix = new wmatrix();
    wmatrix.start();
    try {
      PrintWriter profilefout =
          new PrintWriter(
              new BufferedWriter(
                  new FileWriter(
                      "profile_"
                          + Data.kinease
                          + "_"
                          + Data.code
                          + "_"
                          + Data.windows_size
                          + ".csv")));

      profilefout.print("Position=");
      for (int j = 0; j < Data.windows_size; j++) {
        profilefout.print("," + (j - Data.windows_size / 2));
      }
      profilefout.println();

      for (int i = 0; i < 20; i++) {
        for (int j = 0; j < Data.windows_size; j++) {
          profilefout.print("," + wm[i][j]);
        }
        profilefout.println();
      }
      profilefout.close();

    } catch (IOException ex) {

    }
  }
Beispiel #14
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader("numtri.in"));
    PrintWriter out = new PrintWriter(new FileWriter("numtri.out"));

    int r = Integer.parseInt(in.readLine());
    final int LEN = r;
    int[] weights = new int[LEN];

    weights[0] = Integer.parseInt(in.readLine());

    search(weights, in, 1);
    insertionSort(weights, r);

    out.println(weights[r - 1]);
    in.close();
    out.close();
    System.exit(0);
  }
  public static void main(String[] args) throws java.lang.Exception {
    // let_me_start
    /*  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out));
     BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */

    int n = i();
    int m = i();
    // int arr[] = is((int)n);
    // String ans = "NO";
    long ans = 0;
    for (int i = 1; i <= n; i++) {}

    out.write("" + ans + "\n");
    out.flush();
    return;
  }
Beispiel #16
0
 /**
  * Prints the classifier to the specified file.
  *
  * @param fout is the output file.
  */
 public void printNotNorm(PrintWriter fout) {
   int i = 0;
   fout.print(" ");
   try {
     for (i = 0; i < rep.length; i++) {
       if (Config.typeOfAttributes[i].equals("enumerate")) {
         rep[i].printNotNorm(fout, Config.enumConv[i]);
       } else if (Config.typeOfAttributes[i].equals("integer")) {
         if (Config.enumConv[i].size() > 0) rep[i].printNotNorm(fout, Config.enumConv[i]);
         else rep[i].printNotNorm(fout, (int) Config.attBounds[i][0]);
       } else if (Config.typeOfAttributes[i].equals("real")) {
         rep[i].printNotNorm(fout, Config.attBounds[i][0], Config.attBounds[i][1]);
       }
     }
   } catch (Exception e) {
     System.out.println("Exception when printing the attribute: " + i);
     e.printStackTrace();
   }
   fout.print("\t " + (String) Config.classConv.elementAt(action));
 } // end print
Beispiel #17
0
  /**
   * Prints the desnormalized classifier to the specified file.
   *
   * @param fout is the file output where the classifier has to be printed.
   */
  public void printNotNorm(PrintWriter fout) {
    int i = 0;
    fout.print(" ");
    try {
      for (i = 0; i < rep.length; i++) {
        if (Config.typeOfAttributes[i].equals("ternary")) {
          rep[i].print(fout);
        } else if (Config.typeOfAttributes[i].equals("integer")) {
          rep[i].printNotNorm(fout, Config.attBounds[i][0]);
        } else if (Config.typeOfAttributes[i].equals("real")) {
          rep[i].printNotNorm(fout, Config.attBounds[i][0], Config.attBounds[i][1]);
        }
      }
    } catch (Exception e) {
      System.out.println("Exception when printing the attribute: " + i);
      e.printStackTrace();
    }
    fout.print("\t " + (String) Config.classConv.elementAt(action));

    if (parameters != null) parameters.print(fout);
  }
  // You shouldn't need to modify this function
  public void act() {
    int a = selectAction();

    // visit the node if it has positive utility
    String buf;
    int destination = world[currentNode].links[a];
    if (currentUtilitiesforVisitingNodes[destination] > 0) buf = a + " Y\n";
    else buf = a + " N\n";

    System.out.print("Sent: " + buf);
    sout.println(buf);
  }
  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>");
    }
  }
  public Duder(String args[]) {

    getConnected(args);

    play();

    try {
      sin.close();
      sout.close();
      s.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Beispiel #21
0
  /**
   * Log all test case results to file. Depend on 'log' configuration details will be log or not.
   *
   * @throws IOException
   */
  public void logToFile() throws IOException {
    /*
    // Generate file name
    String DATE_FORMAT_NOW = "yyyyMMddHHmmssmm";
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

    //String fileName = "report-" + sdf.format(cal.getTime())+ "-" + ran.nextInt(100);
    //System.out.println("File Name is : " + oi.reportFilePath + fileName);
     *
     */

    String fileName = init.defaultReportFileName;

    // Create new file
    File reportFile = new File("C:\\" + fileName + ".csv");
    if (reportFile.exists() == false) {
      reportFile.createNewFile();
    }

    // Write log to reportFile
    FileWriter outFile = new FileWriter(reportFile, true);
    PrintWriter out = new PrintWriter(outFile, true);

    Iterator<?> stepper = oi.logList.iterator();

    while (stepper.hasNext()) {
      out.println(stepper.next());
    }

    out.close();

    System.out.println("File Name is : " + reportFile);

    // Clear logList
    oi.logList = new ArrayList<String>();
  }
Beispiel #22
0
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("treasure.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("treasure.out")));
   StringTokenizer st = new StringTokenizer(f.readLine());
   int N = Integer.parseInt(st.nextToken());
   int[] coins = new int[N];
   for (int i = 0; i < N; i++) {
     st = new StringTokenizer(f.readLine());
     coins[i] = Integer.parseInt(st.nextToken());
   }
   int min = 0;
   int max = N - 1;
   int ans = 0;
   int other = 0;
   int counter = 0;
   while (min < max) {
     if (coins[min] > coins[max]) {
       if (counter % 2 == 0) {
         ans += coins[min];
       } else {
         other += coins[min];
       }
       min++;
     } else {
       if (counter % 2 == 0) {
         ans += coins[max];
       } else {
         other += coins[max];
       }
       max--;
     }
     counter++;
   }
   out.println(ans);
   out.close();
   System.exit(0);
 }
Beispiel #23
0
 /**
  * It draws a real interval
  *
  * @param fout is a reference to the file where the classifier has to be drawn.
  * @param lower is the lower value of the interval
  * @param upper is the upper value of the interval.
  */
 private void printInterval(PrintWriter fout, double lower, double upper) {
   double aux = 0.0;
   int points = Config.realDrawnPrecision;
   double inc = 1. / (double) points;
   for (double i = 0.; i < (double) points; i++) {
     if (i * inc < lower && (i * inc + inc) <= lower) {
       fout.print(".");
     } else if (i * inc < lower && (i * inc + inc) > lower) {
       fout.print("o");
     } // In the next if, the value is bigger than the lower
     else if (i * inc < upper && (i * inc + inc) <= upper) {
       fout.print("O");
     } else if (i * inc < upper && (i * inc + inc) > upper) {
       fout.print("o");
     } else if (i * inc >= lower) {
       fout.print(".");
     } else {
       fout.print("ERR. Case not covered!!");
     }
   }
   fout.print(" | ");
 }
  /**
   * Add a quiz to a course if not already so. Also write the menu file for the course. Throws
   * InvalidDBRequestException if quiz already in the course, error occured during insertion, or
   * other exception occured. Throws FileFailureException if fail to append quiz to the menu.
   *
   * @param quizname the quiz name
   * @param courseID the course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void addQuiz(String quizName, String courseID)
      throws InvalidDBRequestException, FileFailureException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      Statement cstmt = db.createStatement();
      ResultSet rs, courseRS;

      int count = 0;

      // get quiz info
      courseRS =
          cstmt.executeQuery(
              "select menu_text, script_type, visual_type from test where name = '"
                  + quizName
                  + "'");

      // check if quiz in the database
      if (!courseRS.next())
        throw new InvalidDBRequestException("Quiz is not registered in the database");
      else {
        // check if quiz already in the course
        rs =
            stmt.executeQuery(
                "select test_name from courseTest where test_name = '"
                    + quizName
                    + "' and course_id = '"
                    + courseID
                    + "'");
        if (rs.next()) throw new InvalidDBRequestException("Quiz is already added for the course");
        else {
          count =
              stmt.executeUpdate(
                  "insert into courseTest (course_id, test_name) values ('"
                      + courseID
                      + "', '"
                      + quizName
                      + "')");
          if (count != 1) throw new InvalidDBRequestException("Error occured during insertion");
          else {
            // append quiz info to the course menu
            try {
              PrintWriter fileOStream =
                  new PrintWriter(
                      new FileOutputStream("./html_root/cat/" + courseID + ".list", true));
              if (debug)
                System.out.println(
                    courseRS.getString(1).trim()
                        + "\n"
                        + quizName
                        + " "
                        + courseRS.getString(2).trim()
                        + " "
                        + courseRS.getString(3).trim().toLowerCase()
                        + "\n****\n");
              fileOStream.print(
                  courseRS.getString(1).trim()
                      + "\n"
                      + quizName
                      + " "
                      + courseRS.getString(2).trim()
                      + " "
                      + courseRS.getString(3).trim().toLowerCase()
                      + "\n****\n");
              fileOStream.flush();
              fileOStream.close();
            } catch (Exception e) {
              System.err.println("Error in creating the menu: " + e.getMessage());
              throw new FileFailureException("Error in creating the menu: " + e.getMessage());
            }
          }
        }
      }

      courseRS.close();
      rs.close();
      stmt.close();
      cstmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addQuiz: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Beispiel #25
0
  public static void exporter(LinkedList<profile> usr, MatlabProxy proxy)
      throws MatlabConnectionException, MatlabInvocationException {

    String file = "/Users/richarddavies/NetBeansProjects/typ_MatlabGraph/rotCmp_2012.txt";
    int i = 0;

    try {

      double result;
      int index_a = 0;
      int index_b = 0;
      int item;

      FileWriter fw = new FileWriter(file);
      BufferedWriter bw = new BufferedWriter(fw);
      PrintWriter outFile = new PrintWriter(bw);

      outFile.println("nodedef>name VARCHAR,label VARCHAR,sex VARCHAR,locale VARCHAR");

      for (i = 0; i < usr.size(); i++) {

        outFile.println(
            usr.get(i).idProf
                + ","
                + usr.get(i).firstName
                + ","
                + usr.get(i).gender
                + ","
                + usr.get(i).nat);
      }

      outFile.println("edgedef>node1 VARCHAR,node2 VARCHAR");

      for (i = 0; i < usr.size(); i++) {

        System.out.println(usr.get(i).firstName + ": ");

        for (int j = 0; j < usr.size(); j++) {

          index_a = i + 1;
          index_b = j + 1;

          // result = proxy.getVariable("adjMatrix("+index_a+","+index_b+");");

          result = ((double[]) proxy.getVariable("adjMatrix(" + index_a + "," + index_b + ");"))[0];

          item = (int) result;

          // item = ((Integer)result).intValue();
          // System.out.println(result);
          if (item == 1) {

            System.out.print(" (" + usr.get(j).firstName + ") ");

            outFile.println(usr.get(i).idProf + "," + usr.get(j).idProf);
          }
        }

        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
      }

      outFile.close();
    } catch (IOException ex) {
      System.out.println(" error : " + ex);
    }
  }
Beispiel #26
0
 /**
  * ** Encodes this DBRecordKey into XML and writes it to a specified PrintWriter ** @param out The
  * PrintWriter ** @param indent The number of spaces to indent ** @param sequence Optional
  * sequence value ** @param soapXML True for SOAP XML
  */
 public void printXML(PrintWriter out, int indent, int sequence, boolean soapXML) {
   if (out != null) {
     out.write(this.toXML(null, indent, sequence, soapXML).toString());
     out.flush();
   }
 }
Beispiel #27
0
  public static void default_fn() throws IOException {
    // Declaring Socket for sending and receiving data
    DatagramSocket skt = null;
    // declaring the fields to be used
    String client_name, movie_name, time, cost, password, reply_string;
    int i, j;
    // assigning the socket a port number
    skt = new DatagramSocket(6789);
    // defining the buffer and its size
    byte[] buffer = new byte[1000];
    while (true) {
      // defining the packet to be received from client
      DatagramPacket request = new DatagramPacket(buffer, buffer.length);

      // receiving the packet
      skt.receive(request);

      // comment on the console
      System.out.println("Data received from client");

      // Thread.sleep(5000);//for error check

      // converting the message to string and then splitting it into fields divided by newline
      // character
      String[] arrayMsg = (new String(request.getData())).split("\n");
      client_name = arrayMsg[1];
      movie_name = arrayMsg[2];
      time = arrayMsg[3];
      cost = "$12";
      password = "******";

      // Composing the reply message by appending start time,cost and password
      reply_string = client_name + "\n" + movie_name + "\n" + time + "\n" + cost + "\n" + password;
      System.out.println(reply_string);
      // Thread.sleep(5000); for error check

      // converting string message to byte
      byte[] sendMsg = (reply_string).getBytes();

      // composing the data packet and sending it to the client's address and the same port the
      // client used
      DatagramPacket reply =
          new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

      System.out.println("sending confirmation");

      // Thread.sleep(5000);//for error check

      // writing server log file
      PrintWriter writer = new PrintWriter("server_log.txt", "UTF-8");
      writer.println(client_name);
      writer.println(movie_name);
      writer.println(time);
      writer.close();

      // sending the data packet
      skt.send(reply);
      // Closing the server socket
      skt.close();
    }
  }
  public void service(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    Connection con = null;

    String bnm[] = req.getParameterValues("Comics");

    String qty[] = new String[bnm.length];
    ArrayList al1 = new ArrayList();
    ArrayList al2 = new ArrayList();
    for (int i = 0; i < bnm.length; i++) {
      qty[i] = req.getParameter(bnm[i]);
      al1.add(bnm[i]);
      al2.add(qty[i]);
    }

    HttpSession HSession = req.getSession(true);

    ArrayList alo1 = (ArrayList) HSession.getValue("bNames");
    ArrayList alo2 = (ArrayList) HSession.getValue("bQty");

    al1.addAll(alo1);
    al2.addAll(alo2);

    HSession.putValue("bNames", al1);
    HSession.putValue("bQty", al2);

    out.println("<html>");
    out.println("<title>Categories..</title>");
    out.println("<body bgcolor=gold >");

    out.println("<b><font face=\"Papyrus\" size=36 color= #806F7E><center>");
    out.println("<big>Category</big></center>");

    out.println("<ul type=disc>");
    out.println("<font face=\"Maiandra GD\" color=black size=4>");
    out.println("<li type=square>Choose your category..");
    out.println("</li></font><br>");

    out.println(
        "<A href=\"FictionClick\"><font face=\"Mistral\" size=8 color=#208234><b>Fiction</b></A><br>");

    out.println(
        "<A href=\"NonFictionClick\"><font face=\"Mistral\" size=8 color=#208234><b>Non-Fiction</b></A><br>");

    out.println(
        "<A href=\"AutobiographyClick\"><font face=\"Mistral\" size=8 color=#208234><b>Autobiography</b></A><br>");

    out.println(
        "<A href=\"HistoryClick\"><font face=\"Mistral\" size=8 color=#208234><b>History</b></A><br>");

    out.println(
        "<A href=\"ComicsClick\"><font face=\"Mistral\" size=8 color=#208234><b>Comics</b></A></font><br><br>");

    out.println("<center><form action=\"http://localhost:8080/servlet/FinalList\">");
    out.println("<input type=submit value=\" Finalize List >>\"></form>");

    out.println("<font face=\"Maiandra GD\" color=black size=4>");
    out.println("Moves to final List..</center>");

    out.println("</font></body>");
    out.println("</html>");
  } // service
Beispiel #29
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
  /**
   * Remove a quiz from a course. Also deletes all the quiz visualization files from the students'
   * folder who is registered in the course. Caution: vizualisation file will be deleted eventhough
   * it also relates to anther course if the student is also registered to that course. (FIX ME!)
   * Throws InvalidDBRequestException if the quiz is not registered in the course, error occured
   * during deletion, or other exception occured.
   *
   * @param quizName quiz name
   * @param courseID course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void deleteQuiz(String quizName, String courseID)
      throws InvalidDBRequestException, FileFailureException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if quiz is used in the course
      rs =
          stmt.executeQuery(
              "select test_name from courseTest where test_name = '"
                  + quizName
                  + "' and course_id = '"
                  + courseID
                  + "'");
      if (!rs.next()) throw new InvalidDBRequestException("Quiz is not registered for the course");
      else {
        // remove quiz from course
        count =
            stmt.executeUpdate(
                "delete from courseTest where course_id = '"
                    + courseID
                    + "' and test_name = '"
                    + quizName
                    + "'");
        if (count != 1) throw new InvalidDBRequestException("Error occured during deletion");
        else {
          // delete quiz visualization files
          rs =
              stmt.executeQuery(
                  "select distinct unique_id, scores.user_login from scores, courseRoster "
                      + "where courseRoster.user_login = scores.user_login "
                      + "and course_id = '"
                      + courseID
                      + "' "
                      + "and test_name = '"
                      + quizName
                      + "'");
          while (rs.next()) {
            deleteVisualization(rs.getString(1), rs.getString(2), quizName);
            count =
                stmt.executeUpdate(
                    "delete from scores where unique_id = " + rs.getString(1).trim());
          }

          // rewrite the menu for the course
          rs =
              stmt.executeQuery(
                  "select distinct menu_text, name, script_type, visual_type from test t, courseTest c "
                      + "where t.name = c.test_name "
                      + "and course_id = '"
                      + courseID
                      + "'");
          PrintWriter fileOStream =
              new PrintWriter(new FileOutputStream("./html_root/cat/" + courseID + ".list"));
          while (rs.next()) {
            if (debug)
              System.out.println(
                  rs.getString(1).trim()
                      + "\n"
                      + rs.getString(2).trim()
                      + " "
                      + rs.getString(3).trim()
                      + " "
                      + rs.getString(4).trim().toLowerCase()
                      + "\n****\n");
            fileOStream.print(
                rs.getString(1).trim()
                    + "\n"
                    + rs.getString(2).trim()
                    + " "
                    + rs.getString(3).trim()
                    + " "
                    + rs.getString(4).trim().toLowerCase()
                    + "\n****\n");
          }
          fileOStream.flush();
          fileOStream.close();
        }
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addQuiz: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    } catch (Exception e) {
      System.err.println("Error in recreating menu for course: " + courseID);
      System.err.println(e.getMessage());
      throw new FileFailureException();
    }
  }