示例#1
0
 public static void outputTaskDetail(int numCtrls, int partSize, int numJobsPerPart) {
   try {
     bwTaskDetail.write(
         "JobId\tStartTime\tSubmissionTime\t" + "ExecuteTime\tFinishTime\tResultBackTime\r\n");
     for (int i = 0; i < numCtrls; i++) {
       String ctrlId = "node-" + Integer.toString(i * partSize);
       for (int j = 0; j < numJobsPerPart; j++) {
         String jobId = ctrlId + " " + Integer.toString(j);
         Job job = jobMetaData.get(jobId);
         long startTime;
         long submitTime;
         long exeTime;
         long finTime;
         long backTime;
         bwTaskDetail.write(
             jobId
                 + "\t"
                 + job.startTime
                 + "\t"
                 + job.submitTime
                 + "\t"
                 + job.exeTime
                 + "\t"
                 + job.finTime
                 + "\t"
                 + job.backTime
                 + "\r\n");
       }
     }
     bwTaskDetail.flush();
     bwTaskDetail.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
示例#2
0
 void pln(String s) {
   try {
     bw.write(s);
     bw.write(System.lineSeparator());
   } catch (Exception ex) {
   }
 }
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
示例#4
0
 public static void main(String[] args) throws IOException {
   FileReader fin = new FileReader(new File("input.txt"));
   BufferedReader input = new BufferedReader(fin);
   FileWriter fout = new FileWriter(new File("output.txt"));
   BufferedWriter out = new BufferedWriter(fout);
   StringTokenizer str = new StringTokenizer(input.readLine());
   int n = Integer.parseInt(str.nextToken());
   str = new StringTokenizer(input.readLine());
   ArrayList<Integer>[] data = new ArrayList[5000];
   for (int i = 0; i < 5000; i++) data[i] = new ArrayList<Integer>();
   for (int i = 0; i < 2 * n; i++) {
     int x = Integer.parseInt(str.nextToken());
     data[x - 1].add(i + 1);
   }
   boolean okay = true;
   for (int i = 0; i < 5000; i++) if (data[i].size() % 2 == 1) okay = false;
   if (okay) {
     for (int i = 0; i < 5000; i++) {
       for (int j = 0; j < data[i].size() / 2; j++) {
         out.write(data[i].get(2 * j) + " " + data[i].get(2 * j + 1) + "\n");
       }
     }
   } else {
     out.write("-1");
   }
   out.close();
 }
  static void writeNewData(String datafile) {

    try {
      BufferedReader bufr = new BufferedReader(new FileReader(datafile));
      BufferedWriter bufw = new BufferedWriter(new FileWriter(datafile + ".nzf"));

      String line;
      String[] tokens;

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

        tokens = line.split(" ");
        bufw.write(tokens[0]);
        for (int i = 1; i < tokens.length; i++) {

          Integer index = Integer.valueOf(tokens[i].split(":")[0]);
          if (nnzFeas.contains(index)) {
            bufw.write(" " + tokens[i]);
          }
        }
        bufw.newLine();
      }
      bufw.close();
      bufr.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
示例#6
0
  /**
   * Marshalls the mgf file object to a file. If the file already exists it will be overwritten.
   *
   * @param file The file to marshall the mgf file to.
   */
  public void marshallToFile(File file) throws JMzReaderException {
    try {
      // create the object to write the file
      BufferedWriter writer = new BufferedWriter(new FileWriter(file));

      // process all additional parameters
      String parameters = marshallAdditionalParameters();

      // write the parameters
      writer.write(parameters);

      // process the pmf spectra
      for (PmfQuery q : pmfQueries) writer.write(q.toString() + "\n");

      writer.write("\n");

      // write the spectra
      for (Integer index = 0; index < 1000000; index++) {
        if (!ms2Queries.containsKey(index)) continue;

        writer.write(ms2Queries.get(index).toString() + "\n");
      }

      writer.close();

    } catch (IOException e) {
      throw new JMzReaderException("Failed to write output file", e);
    }
  }
示例#7
0
  /**
   * piirtää reitin tiedostoon ja reittikartta taulukkoon
   *
   * @param käydytsolmut
   * @throws IOException
   */
  public void piirräreitti(PriorityQueue<Solmu> käydytsolmut) throws IOException {

    String nimi = new String("uk");
    BufferedWriter reittikarttatiedosto = new BufferedWriter(new FileWriter("uk"));
    Solmu solmu = new Solmu(0, 0, null, 0);

    while (!käydytsolmut.isEmpty()) {
      solmu = käydytsolmut.poll();

      for (int n = 0; n < kartankoko; n++) {
        for (int i = 0; i < kartankoko; i++) {
          if (solmu.x == n && solmu.y == i) {
            // reittikartta[i][n] = '-';
            reittikartta[i][n] = (char) (solmu.summaamatkat(0, solmu.annavanhempi()) + 65);
            // reittikarttatiedosto.write("-");
            reittikarttatiedosto.write('-');
          } else {
            reittikarttatiedosto.write(reittikartta[i][n]);
          }
        }
        reittikarttatiedosto.newLine();
      }
    }
    reittikarttatiedosto.close();
    tulostakartta(reittikartta);
  }
示例#8
0
  /**
   * given a list of sequences, creates a db for use with blat
   *
   * @param seqList is the list of sequences to create the database with
   * @return the full path of the location of the database
   */
  private String dumpToFile(Map<String, String> seqList) {

    File tmpdir;
    BufferedWriter out;
    File seqFile = null;

    /*
    open temp file
     */
    try {
      seqFile = new File(tmpDirFile, "reads.fa");
      out = new BufferedWriter(new FileWriter(seqFile.getPath()));

      /*
      write out the sequences to file
      */
      for (String key : seqList.keySet()) {
        assert (seqList.get(key) != null);
        out.write(">" + key + "\n");
        out.write(seqList.get(key) + "\n");
      }

      /*
      close temp file
       */
      out.close();

    } catch (Exception e) {
      log.error(e);
      return null;
    }

    return seqFile.getPath();
  }
示例#9
0
  /**
   * create the info string; assumes that no values are null
   *
   * @param infoFields a map of info fields
   * @throws IOException for writer
   */
  private void writeInfoString(Map<String, String> infoFields) throws IOException {
    if (infoFields.isEmpty()) {
      mWriter.write(VCFConstants.EMPTY_INFO_FIELD);
      return;
    }

    boolean isFirst = true;
    for (Map.Entry<String, String> entry : infoFields.entrySet()) {
      if (isFirst) isFirst = false;
      else mWriter.write(VCFConstants.INFO_FIELD_SEPARATOR);

      String key = entry.getKey();
      mWriter.write(key);

      if (!entry.getValue().equals("")) {
        VCFInfoHeaderLine metaData = mHeader.getInfoHeaderLine(key);
        if (metaData == null
            || metaData.getCountType() != VCFHeaderLineCount.INTEGER
            || metaData.getCount() != 0) {
          mWriter.write("=");
          mWriter.write(entry.getValue());
        }
      }
    }
  }
示例#10
0
  // saves changes to player data. MUST be called after you're done making
  // changes, otherwise a reload will lose them
  @Override
  public synchronized void savePlayerData(String playerName, PlayerData playerData) {
    // never save data for the "administrative" account. an empty string for
    // claim owner indicates administrative account
    if (playerName.length() == 0) return;

    BufferedWriter outStream = null;
    try {
      // open the player's file
      File playerDataFile =
          new File(playerDataFolderPath + File.separator + playerName.toLowerCase());
      playerDataFile.createNewFile();
      outStream = new BufferedWriter(new FileWriter(playerDataFile));

      // first line is last login timestamp
      if (playerData.lastLogin == null) playerData.lastLogin = new Date();
      DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
      outStream.write(dateFormat.format(playerData.lastLogin));
      outStream.newLine();

      // second line is accrued claim blocks
      outStream.write(String.valueOf(playerData.accruedClaimBlocks));
      outStream.newLine();

      // third line is bonus claim blocks
      outStream.write(String.valueOf(playerData.bonusClaimBlocks));
      outStream.newLine();

      // fourth line is a double-semicolon-delimited list of claims
      /*if (playerData.claims.size() > 0) {
      	outStream.write(this.locationToString(playerData.claims.get(0).getLesserBoundaryCorner()));
      	for (int i = 1; i < playerData.claims.size(); i++) {
      		outStream.write(";;" + this.locationToString(playerData.claims.get(i).getLesserBoundaryCorner()));
      	}
      } */

      // write out wether the player's inventory needs to be cleared on join.
      outStream.newLine();
      outStream.write(String.valueOf(playerData.ClearInventoryOnJoin));
      outStream.newLine();
    }

    // if any problem, log it
    catch (Exception e) {
      GriefPrevention.AddLogEntry(
          "GriefPrevention: Unexpected exception saving data for player \""
              + playerName
              + "\": "
              + e.getMessage());
    }

    try {
      // close the file
      if (outStream != null) {
        outStream.close();
      }
    } catch (IOException exception) {
    }
  }
示例#11
0
  public void innerExecute() throws IOException, JerializerException {
    // first arg - schema dir, second arg - dest dir
    // TODO write schemas

    File schemas = new File(schemaDir);
    assert schemas.isDirectory() && schemas.canRead();

    File dest = new File(destDir);
    assert !dest.exists();
    dest.mkdir();
    assert dest.isDirectory() && dest.canWrite();

    Set<Klass> genKlasses = new TreeSet<Klass>();

    JsonParser parser = new JsonParser();
    for (File schema : schemas.listFiles()) {
      BufferedReader reader = new BufferedReader(new FileReader(schema));
      JThing thing = parser.parse(reader);
      System.out.println(thing);
      String rootString = schemas.toURI().toString();
      if (!rootString.endsWith("/")) rootString = rootString + "/";
      String klassName =
          KlassContext.capitalize(schema.toURI().toString().substring(rootString.length()));
      String packageName = basePackage + "." + klassName.toLowerCase();

      GenWritable writable = parseSchemaThing(klassName, packageName, thing);

      Map<String, String> m = writable.makeClassToTextMap();

      final File dir = new File(destDir + "/" + klassName.toLowerCase());
      dir.mkdirs();
      for (Map.Entry<String, String> entry : m.entrySet()) {
        final String fullClass = entry.getKey();
        final String contents = entry.getValue();
        final String relName = fullClass.substring(fullClass.lastIndexOf(".") + 1) + ".java";
        final File f = new File(dir, relName);
        FileWriter writer = new FileWriter(f);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(contents, 0, contents.length());
        bufferedWriter.close();
      }

      genKlasses.add(new Klass(klassName, packageName));
    }

    RegistryGen registryGen =
        new RegistryGen(new Klass("GenschemaRegistryFactory", basePackage), genKlasses);
    final File g = new File(destDir + "/GenschemaRegistryFactory.java");
    for (Map.Entry<String, String> entry : registryGen.makeClassToTextMap().entrySet()) {
      final String contents = entry.getValue();
      FileWriter writer = new FileWriter(g);
      BufferedWriter bufferedWriter = new BufferedWriter(writer);
      bufferedWriter.write(contents, 0, contents.length());
      bufferedWriter.close();
      break;
    }
  }
示例#12
0
  public void writeResults(String outputFile) {

    try {
      // Create file
      FileWriter fStream = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fStream);

      out.write(
          "Attribute Type"
              + SEPARATOR
              + "numberOfDiffValues"
              + SEPARATOR
              + "min"
              + SEPARATOR
              + "max"
              + SEPARATOR
              + "Example\n");
      for (Map.Entry<String, Set<String>> entry : attrByValue.entrySet()) {
        Set<String> attrValues = entry.getValue();
        String lineToWrite = entry.getKey();

        Collections.max(attrValues);

        String sampleValues = "";
        int maxNumberOfSampleValues = 0;

        for (String s : attrValues) {
          sampleValues = sampleValues + " " + s;
          if (maxNumberOfSampleValues > MAX_EXAMPLE_COUNT) break;
          maxNumberOfSampleValues++;
        }

        String max = Collections.max(attrValues);
        String min = Collections.min(attrValues);

        lineToWrite =
            lineToWrite
                + SEPARATOR
                + attrValues.size()
                + SEPARATOR
                + max
                + SEPARATOR
                + min
                + SEPARATOR
                + sampleValues.trim();

        out.write(lineToWrite + "\n");
      }

      out.flush();
      // Close the output stream
      out.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
示例#13
0
 private void writeUninstallerJarFileLog(UninstallData udata, JarOutputStream outJar)
     throws IOException {
   BufferedWriter logWriter;
   outJar.putNextEntry(new JarEntry("jarlocation.log"));
   logWriter = new BufferedWriter(new OutputStreamWriter(outJar));
   logWriter.write(udata.getUninstallerJarFilename());
   logWriter.newLine();
   logWriter.write(udata.getUninstallerPath());
   logWriter.flush();
   outJar.closeEntry();
 }
示例#14
0
 private static void api(String file, Option<String> out, Option<String> prepend)
     throws UserError, IOException {
   if (!isComponent(file)) {
     throw new UserError(
         "The api command needs a Fortress component file; filename "
             + file
             + " must end with .fss");
   }
   Component c = (Component) Parser.parseFileConvertExn(new File(file));
   String logFile = file + ".api.log";
   Option<Node> result = c.accept(new ApiMaker(logFile));
   File log = new File(logFile);
   if (log.length() != 0) {
     System.err.println("To generate an API, the following types are required:");
     BufferedReader reader = Useful.filenameToBufferedReader(logFile);
     String line = reader.readLine();
     while (line != null) {
       System.err.println(line);
       line = reader.readLine();
     }
     try {
       Files.rm(logFile);
     } catch (IOException e) {
     }
     throw new UserError("Missing types from the component.");
   }
   try {
     Files.rm(logFile);
   } catch (IOException e) {
   }
   if (result.isNone()) throw new UserError("The api command needs a Fortress component file.");
   Api a = (Api) result.unwrap();
   String code = a.accept(new FortressAstToConcrete());
   if (out.isSome()) {
     try {
       BufferedWriter writer = Useful.filenameToBufferedWriter(out.unwrap());
       if (prepend.isSome()) {
         BufferedReader reader = Useful.filenameToBufferedReader(prepend.unwrap());
         String line = reader.readLine();
         while (line != null) {
           writer.write(line + "\n");
           line = reader.readLine();
         }
       }
       writer.write(code);
       writer.close();
       System.out.println("Dumped code to " + out.unwrap());
     } catch (IOException e) {
       throw new IOException("IOException " + e + " while writing " + out.unwrap());
     }
   } else {
     System.out.println(code);
   }
 }
 // ------------------------------------
 // Send RTSP Response
 // ------------------------------------
 private void send_RTSP_response() {
   try {
     RTSPBufferedWriter.write("RTSP/1.0 200 OK" + CRLF);
     RTSPBufferedWriter.write("CSeq: " + RTSPSeqNb + CRLF);
     RTSPBufferedWriter.write("Session: " + RTSP_ID + CRLF);
     RTSPBufferedWriter.flush();
     // System.out.println("RTSP Server - Sent response to Client.");
   } catch (Exception ex) {
     System.out.println("Exception caught: " + ex);
     System.exit(0);
   }
 }
  public void write_in_file(
      String catch_block,
      String expr_type,
      String try_con,
      String all_catch_as_string,
      String method_content,
      int log_count,
      String method_parameter) {
    // log_count=1;
    // id++;
    BufferedWriter bw = null;
    int logged = 0;

    if (log_count != 0) {
      logged = 1;
    }

    if (logged == 1) {

      try {
        bw = new BufferedWriter(new FileWriter(logged_file_path, true));

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      try {
        bw = new BufferedWriter(new FileWriter(non_logged_file_path, true));

      } catch (IOException e) {
        e.printStackTrace();
      }
    } // else

    /* String insert_str= "insert into "+table+" values(\""+package_name+"\",\""+class_name+"\",\""+method_name+"\","+  id+",\""+method_content+"\",\""+
    log_levels_combined+"\",\""+temp_file_path+"\","+"\""+if_block+"\",\""+expr_type+"\","+log_count+",\""
    +if_train_con+"\","+logged+")";
    System.out.println("Insert str"+insert_str);
    */

    try {
      bw.write("File Path=" + temp_file_path + "\n");
      bw.write("Package Name =" + package_name + "\n");
      bw.write("class name=" + class_name + "\n");
      bw.write("Method Name=" + method_name + "\n");
      bw.write("Try Content=" + try_con + "\n");
      bw.write(" All Catch Blocks=" + all_catch_as_string + "\n");
      bw.write("method parameter = " + method_parameter + "\n");
      bw.write("method content=" + method_content + "\n");
      bw.write("--------------------\n");
      bw.close();
    } catch (IOException e) {

      e.printStackTrace();
    }
  }
  private void saveFile(File file) {
    try {
      BufferedWriter writer = new BufferedWriter(new FileWriter(file));

      for (QuizCard card : cardList) {
        writer.write(card.getQuestion() + "/");
        writer.write(card.getAnswer() + "/n");
      }
    } catch (IOException ex) {
      System.out.println("Couldn't wirite the cardList out");
      ex.printStackTrace();
    }
  }
示例#18
0
 public static void writeTransControlFile() throws IOException {
   BufferedWriter bw = new BufferedWriter(new FileWriter("trans.ctl"));
   bw.write("LOAD DATA");
   bw.newLine();
   bw.write("INFILE trans.dat");
   bw.newLine();
   bw.write("INTO TABLE trans");
   bw.newLine();
   bw.write("FIELDS TERMINATED BY ','");
   bw.newLine();
   bw.write("(transid,itemid)");
   bw.close();
 }
示例#19
0
 public static void writeItemsControlFile() throws IOException {
   BufferedWriter bw = new BufferedWriter(new FileWriter("items.ctl"));
   bw.write("LOAD DATA");
   bw.newLine();
   bw.write("INFILE items.dat");
   bw.newLine();
   bw.write("INTO TABLE items");
   bw.newLine();
   bw.write("FIELDS TERMINATED BY ',' optionally enclosed by X'27'");
   bw.newLine();
   bw.write("(itemid,itemname)");
   bw.close();
 }
示例#20
0
  public static void main(String[] args) {
    // 1. read the inchis into HashMap
    HashMap inchiDict = new HashMap();
    try {
      FileReader inchiDictionary = new FileReader(args[0]);
      BufferedReader inchiDictionaryBR = new BufferedReader(inchiDictionary);
      String line = inchiDictionaryBR.readLine();
      // While more InChIs remain
      while (line != null) {
        String[] spl = line.split("\t"); // split on tab
        inchiDict.put(spl[0], spl[2]); // add the chemkin name as key, and InChI as value
        line = inchiDictionaryBR.readLine();
      }
      inchiDictionary.close();
    } catch (FileNotFoundException e) {
      System.err.println("File was not found!\n");
    } catch (IOException eIO) {
      System.err.println("IO Exception!\n");
    }

    // 2. read the CHEMKIN file, while simultaneously writing a CHEMKIN output file with InChI
    // comments, where available
    try {
      FileReader chemkinOld = new FileReader(args[1]);
      FileWriter chemkinNew = new FileWriter(args[2]);
      BufferedReader chemkinReader = new BufferedReader(chemkinOld);
      BufferedWriter chemkinWriter = new BufferedWriter(chemkinNew);
      String line = chemkinReader.readLine();
      // While more InChIs remain
      while (line != null) {
        String[] spl = line.split(" "); // split on  space
        int len = spl.length;
        // if the last "word" is a 1 and the first word can be found in the dictionary, write a
        // comment line before copying the line; otherwise, just copy the line
        if (spl[len - 1].equals("1") && inchiDict.containsKey(spl[0])) {
          chemkinWriter.write("! [_ SMILES=\"" + inchiDict.get(spl[0]) + "\" _]\n");
        }
        chemkinWriter.write(line + "\n");

        line = chemkinReader.readLine();
      }
      chemkinOld.close();
      chemkinWriter.flush();
      chemkinWriter.close();
      chemkinNew.close();
    } catch (FileNotFoundException e) {
      System.err.println("File was not found!\n");
    } catch (IOException eIO) {
      System.err.println("IO Exception!\n");
    }
  }
示例#21
0
  public void printWeightUpdate() {

    String fileName = "WeightFile.txt";
    try {

      FileWriter fileWriter = new FileWriter(fileName);

      BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

      System.out.println(
          "printWeightUpdate, put this i trainedWeights() and set isTrained to true");
      // weights for the hidden layer
      for (Neuron n : hiddenLayer) {
        ArrayList<Connection> connections = n.getAllInConnections();
        for (Connection con : connections) {
          String w = df.format(con.getWeight());
          System.out.println(
              "weightUpdate.put(weightKey(" + n.id + ", " + con.id + "), " + w + ");");

          bufferedWriter.write(ef.format(n.id));
          bufferedWriter.write(" ");
          bufferedWriter.write(ef.format(con.id));
          bufferedWriter.write(" ");
          bufferedWriter.write(w);
          bufferedWriter.newLine();
        }
      }
      // weights for the output layer
      for (Neuron n : outputLayer) {
        ArrayList<Connection> connections = n.getAllInConnections();
        for (Connection con : connections) {
          String w = df.format(con.getWeight());
          System.out.println(
              "weightUpdate.put(weightKey(" + n.id + ", " + con.id + "), " + w + ");");

          bufferedWriter.write(ef.format(n.id));
          bufferedWriter.write(" ");
          bufferedWriter.write(ef.format(con.id));
          bufferedWriter.write(" ");
          bufferedWriter.write(w);
          bufferedWriter.newLine();
        }
      }
      System.out.println();
      bufferedWriter.close();
    } catch (IOException ex) {

      System.out.println("Error writing to file " + fileName);
    }
  }
  public void merge(String filename[]) throws NumberFormatException, IOException {

    File file[] = new File[filename.length];
    BufferedWriter out = new BufferedWriter(new FileWriter("Sol.txt"));
    ArrayList<BufferedReader> br = new ArrayList<BufferedReader>();
    int pointer[] = new int[filename.length];

    for (int i = 0; i < filename.length; i++) {
      br.add(new BufferedReader(new FileReader(filename[i])));
    }
    for (int i = 0; i < br.size(); i++) {

      pointer[i] = Integer.parseInt(br.get(i).readLine());
      // System.out.println(pointer[i]);
    }

    int chunks = pointer.length;
    boolean first = true;

    // write the final solution file using individual chunk solution files.
    while (chunks > 0) {
      int index = -1;
      int min = Integer.MAX_VALUE;
      for (int i = 0; i < pointer.length; i++) {
        int no = pointer[i];

        if (no >= 0) {
          if (no < min) {
            min = no;
            index = i;
          }
        }
      }
      for (int k = 0; k < countsMap.get(min); k++) {
        out.write(new Integer(min).toString());
        out.write("\n");
      }
      String line;
      if ((line = br.get(index).readLine()) == null) {
        pointer[index] = -1;
        chunks--;
      } else {
        pointer[index] = Integer.parseInt(line);
      }
    }

    out.close();
    System.out.println("WRITTEN TO FILE");
  }
示例#23
0
  /** Write all AIML files. Adds categories for BUILD and DEVELOPMENT ENVIRONMENT */
  public void writeAIMLFiles() {
    if (MagicBooleans.trace_mode) System.out.println("writeAIMLFiles");
    HashMap<String, BufferedWriter> fileMap = new HashMap<String, BufferedWriter>();
    Category b = new Category(0, "BRAIN BUILD", "*", "*", new Date().toString(), "update.aiml");
    brain.addCategory(b);
    // b = new Category(0, "PROGRAM VERSION", "*", "*", MagicStrings.program_name_version,
    // "update.aiml");
    // brain.addCategory(b);
    ArrayList<Category> brainCategories = brain.getCategories();
    Collections.sort(brainCategories, Category.CATEGORY_NUMBER_COMPARATOR);
    for (Category c : brainCategories) {

      if (!c.getFilename().equals(MagicStrings.null_aiml_file))
        try {
          // System.out.println("Writing "+c.getCategoryNumber()+" "+c.inputThatTopic());
          BufferedWriter bw;
          String fileName = c.getFilename();
          if (fileMap.containsKey(fileName)) bw = fileMap.get(fileName);
          else {
            String copyright = Utilities.getCopyright(this, fileName);
            bw = new BufferedWriter(new FileWriter(aiml_path + "/" + fileName));
            fileMap.put(fileName, bw);
            bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" + "<aiml>\n");
            bw.write(copyright);
            // bw.newLine();
          }
          bw.write(Category.categoryToAIML(c) + "\n");
          // bw.newLine();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
    }
    Set set = fileMap.keySet();
    for (Object aSet : set) {
      BufferedWriter bw = fileMap.get(aSet);
      // Close the bw
      try {
        if (bw != null) {
          bw.write("</aiml>\n");
          bw.flush();
          bw.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    File dir = new File(aiml_path);
    dir.setLastModified(new Date().getTime());
  }
示例#24
0
 public void write() {
   filename = "open/" + filename;
   try {
     BufferedWriter br = new BufferedWriter(new FileWriter(new File(filename)));
     br.write(precode);
     for (int i = 0; i < classes.size(); i++) {
       System.out.println("Jooifying " + (i + 1) + " out of " + classes.size() + 1);
       br.write(((Class) classes.get(i)).toString());
     }
     br.close();
     System.out.println("Written file " + filename);
   } catch (Exception e) {
     System.out.println("Exception " + e + " occured");
   }
 }
  private static void predict(WordAligner wordAligner, List<SentencePair> testSentencePairs, String path) throws IOException {
	BufferedWriter writer = new BufferedWriter(new FileWriter(path));
    for (SentencePair sentencePair : testSentencePairs) {
      Alignment proposedAlignment = wordAligner.alignSentencePair(sentencePair);
      for (int frenchPosition = 0; frenchPosition < sentencePair.getFrenchWords().size(); frenchPosition++) {
        for (int englishPosition = 0; englishPosition < sentencePair.getEnglishWords().size(); englishPosition++) {
          if (proposedAlignment.containsSureAlignment(englishPosition, frenchPosition)) {
        	writer.write(frenchPosition + "-" + englishPosition + " ");
          }
        }
      }
      writer.write("\n");
    }
    writer.close();
  }
示例#26
0
  // Save data from LinkedHashMap to file
  public void save() {
    BufferedWriter bw = null;
    try {
      // Construct the BufferedWriter object
      bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
      bw.write("# " + pName + " Properties File");
      bw.newLine();

      // Save all the properties one at a time, only if there's data to write
      if (properties.size() > 0) {
        // Grab all the entries and create an iterator to run through them all
        Set<?> set = properties.entrySet();
        Iterator<?> i = set.iterator();

        // While there's data to iterate through..
        while (i.hasNext()) {
          // Map the entry and save the key and value as variables
          Map.Entry<?, ?> me = (Map.Entry<?, ?>) i.next();
          String key = (String) me.getKey();
          String val = me.getValue().toString();

          // If it starts with "#", it's a comment so write it as such
          if (key.charAt(0) == '#') {
            // Writing a comment to the file
            bw.write("# " + val);
            bw.newLine();
          } else {
            // Otherwise write the key and value pair as key=value
            bw.write(key + '=' + val);
            bw.newLine();
          }
        }
      }
    } catch (FileNotFoundException ex) {
      log.log(Level.SEVERE, '[' + pName + "]: Couldn't find file " + filename, ex);
      return;
    } catch (IOException ex) {
      log.log(Level.SEVERE, '[' + pName + "]: Unable to save " + filename, ex);
      return;
    } finally {
      // Close the BufferedWriter
      try {
        if (bw != null) bw.close();
      } catch (IOException ex) {
        log.log(Level.SEVERE, '[' + pName + "]: Unable to save " + filename, ex);
      }
    }
  }
  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();
    }
  }
示例#28
0
  public void save() {
    BufferedWriter sourceFile = null;

    try {
      String sourceText = sourceArea.getText();

      String cleanText = cleanupSource(sourceText);

      if (cleanText.length() != sourceText.length()) {
        sourceArea.setText(cleanText);

        String message =
            String.format(
                "One or more invalid characters at the end of the source file have been removed.");
        JOptionPane.showMessageDialog(this, message, "ROPE", JOptionPane.INFORMATION_MESSAGE);
      }

      sourceFile = new BufferedWriter(new FileWriter(sourcePath, false));
      sourceFile.write(cleanText);

      setSourceChanged(false);

      setupMenus();
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (sourceFile != null) {
        try {
          sourceFile.close();
        } catch (IOException ignore) {
        }
      }
    }
  }
示例#29
0
文件: Installer.java 项目: suever/CTP
 private void setFileText(File file, String text) throws Exception {
   BufferedWriter bw =
       new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
   bw.write(text, 0, text.length());
   bw.flush();
   bw.close();
 }
示例#30
0
 /**
  * write categories to AIMLIF file
  *
  * @param cats array list of categories
  * @param filename AIMLIF filename
  */
 public void writeIFCategories(ArrayList<Category> cats, String filename) {
   // System.out.println("writeIFCategories "+filename);
   BufferedWriter bw = null;
   File existsPath = new File(aimlif_path);
   if (existsPath.exists())
     try {
       // Construct the bw object
       bw = new BufferedWriter(new FileWriter(aimlif_path + "/" + filename));
       for (Category category : cats) {
         bw.write(Category.categoryToIF(category));
         bw.newLine();
       }
     } catch (FileNotFoundException ex) {
       ex.printStackTrace();
     } catch (IOException ex) {
       ex.printStackTrace();
     } finally {
       // Close the bw
       try {
         if (bw != null) {
           bw.flush();
           bw.close();
         }
       } catch (IOException ex) {
         ex.printStackTrace();
       }
     }
 }