Example #1
0
 private static void setStream(String in, String out) {
   try {
     System.setIn(new BufferedInputStream(new FileInputStream(in)));
     System.setOut(new PrintStream(out));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #2
0
File: vans.java Project: were/progs
 public static void main(String args[]) {
   try {
     System.setIn(new FileInputStream("vans.in"));
     System.setOut(new PrintStream("vans.out"));
   } catch (Throwable T_T) {
   }
   new vans().run();
 }
  /**
   * Adds an old value with a fixed timestamp to the sample.
   *
   * @param value the value to be added
   * @param timestamp the epoch timestamp of {@code value} in seconds
   */
  public void update(long value, long timestamp) {
    lockForRegularUsage();
    try {
      final double priority = weight(timestamp - startTime) / random();
      final long newCount = count.incrementAndGet();
      if (newCount <= reservoirSize) {
        values.put(priority, value);
      } else {
        Double first = values.firstKey();
        if (first < priority) {
          if (values.putIfAbsent(priority, value) == null) {
            // ensure we always remove an item
            while (values.remove(first) == null) {
              first = values.firstKey();
            }
          }
        }
      }
    } finally {
      unlockForRegularUsage();
    }

    final long now = System.nanoTime();
    final long next = nextScaleTime.get();
    if (now >= next) {
      rescale(now, next);
    }
  }
Example #4
0
 public static void main(String[] args) {
   A2 instance = new A2();
   Task solver = instance.new Task();
   solver.solve();
   instance.out.close();
   System.exit(0);
 }
Example #5
0
 public void onTick() {
   long currentTime = System.currentTimeMillis();
   long timeDiff = currentTime - lastTickTime;
   millisSinceLastDragonFrameChange += timeDiff;
   if (millisSinceLastDragonFrameChange > 500) {
     cycleDragonFrame();
     millisSinceLastDragonFrameChange = 0;
   }
   millisSinceLastFlagFrameChange += timeDiff;
   if (millisSinceLastFlagFrameChange > 500) {
     cycleFlagFrame();
     millisSinceLastFlagFrameChange = 0;
   }
   lastTickTime = currentTime;
   try {
     getWorld().onTick();
   } catch (SQLException exception) {
     client
         .getLogger()
         .log(
             WARNING,
             "Failed to update unit in database (but this is the client, so it should be fine)",
             exception);
   }
   repaint();
 }
Example #6
0
 void pln(String s) {
   try {
     bw.write(s);
     bw.write(System.lineSeparator());
   } catch (Exception ex) {
   }
 }
Example #7
0
  /* play the game */
  private void play() {
    t0 = System.currentTimeMillis(); /*Times the beginning of the game */
    currentTime = System.currentTimeMillis() - t0;
    generateRandomOrderTimes();
    System.out.println("next t1 is in " + orderTimes.get(0));
    System.out.println("next t2 is in " + orderTimes.get(1));
    System.out.println("next t3 is in " + orderTimes.get(2));

    while (System.currentTimeMillis() - t0 < ENDOFGAMETIME) {
      pause(100);
      /*Update the days label*/
      daysElapsed = (int) ((System.currentTimeMillis() - t0) / (LENGTHOFADAY * 1000));
      daysElapsedLabel.setLabel("DAYS " + daysElapsed);
      scanEquipments();
    }
  }
Example #8
0
 /*setup the game */
 private void setup() {
   t0 = System.currentTimeMillis(); /*Times the beginning of the game */
   // int size;
   Scanner in = new Scanner(System.in);
   // System.out.println("Enter the size of available");
   // size = in.nextInt();
   initiateScores();
   placeWalls();
   placeStates();
   placeLabels();
   randomizeOrderRent(); /*randomizes the order of the equipment for the On Rent state */
   System.out.println(
       "How many High Runners at price $" + EQUIPMENTCOSTS[0] + " do you want to buy?");
   int type1Equip = in.nextInt();
   System.out.println(
       "How many Medium Runners at price $" + EQUIPMENTCOSTS[1] + " do you want to buy?");
   int type2Equip = in.nextInt();
   System.out.println(
       "How many Low Runners at price $" + EQUIPMENTCOSTS[2] + " do you want to buy?");
   int type3Equip = in.nextInt();
   capitalInvested =
       EQUIPMENTCOSTS[0] * type1Equip
           + EQUIPMENTCOSTS[1] * type2Equip
           + EQUIPMENTCOSTS[2] * type3Equip;
   capitalLabel.setLabel("Capital Invested: $" + capitalInvested);
   fillAvailable(type1Equip, type2Equip, type3Equip); // fills with the proper number of equipment
   // fillStates(size,INITRENT,INITSHOP);
   placeEquipments();
 }
Example #9
0
 public static void main(String[] args) {
   InputReader in = new InputReader(System.in);
   OutputWriter out = new OutputWriter(System.out);
   A1Task solver = new A1Task();
   solver.solve(in, out);
   out.close();
   System.exit(0);
 }
 void run() throws Exception {
   in = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
   out = new PrintWriter(System.out);
   long s = System.currentTimeMillis();
   solve();
   out.flush();
   //		pr(System.currentTimeMillis() - s + "ms");
 }
Example #11
0
  public static void main(String[] args) {

    double[] sigma = {3E-4, 1E-6, 2.4E-2, 6.67E-5, 1E-6, 6E-3, 4.4E-4, 1E-2, 1E-6};
    double[] mu = {0.42E9, 2.27};
    double alpha = 0.0;
    Sampler sampler = new Sampler(mu, sigma, alpha);
    double[][] M = sampler.getCovMat();
    System.out.println("The Covirance Matrix is:");
    sampler.printMatrix(M);

    double[][] A = sampler.getCholDecompA();
    System.out.println("The decomposed Matrix A is");
    sampler.printMatrix(A);

    try {

      File file = new File("/Users/Weizheng/Documents/JavaWorkPlace/CLS_MCIntegrator/output.txt");
      // if file doesnt exists, then create it
      if (!file.exists()) {
        file.createNewFile();
      } else {
        file.delete();
        file.createNewFile();
      }

      PrintWriter fw = new PrintWriter(file);

      long startTime = System.currentTimeMillis();

      for (int i = 0; i < 1E3; i++) {
        double[] MultiNormalVector = sampler.nextMultiNormalVector();
        //				for(double a:MultiNormalVector ){
        //					fw.printf("%4.2e ", a);
        //				}
        //				fw.println("");
      }
      fw.close();
      long endTime = System.currentTimeMillis();
      System.out.println("That took " + (endTime - startTime) + " milliseconds");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #12
0
  public static void main(String[] args) {
    String sourceFile = args[0];
    int m = Integer.parseInt(args[1]);

    String format = sourceFile.substring(1 + sourceFile.lastIndexOf('.'));
    String targetBase = sourceFile.substring(0, sourceFile.lastIndexOf('.'));
    String targetFile0 = targetBase + "_" + m + "_0." + format;
    String targetFile1 = targetBase + "_" + m + "_1." + format;
    String targetFile2 = targetBase + "_" + m + "_2." + format;

    KernelJAI gaussKernel = createGaussianKernel(m);
    dumpKernelData("Gaussian", gaussKernel);
    KernelJAI distKernel = createDistancesKernel(m);
    dumpKernelData("Distances", distKernel);

    RenderedOp source = FileLoadDescriptor.create(sourceFile, null, true, null);
    source = BandSelectDescriptor.create(source, new int[1], null);
    System.out.println("Writing " + targetFile0);
    FileStoreDescriptor.create(source, targetFile0, format, null, false, null);

    long t1 = System.currentTimeMillis();
    System.out.println("Computing " + targetFile1);
    BorderExtender borderExtender = BorderExtender.createInstance(BorderExtender.BORDER_COPY);
    RenderedOp target1 =
        ConvolveDescriptor.create(
            source, gaussKernel, new RenderingHints(JAI.KEY_BORDER_EXTENDER, borderExtender));
    RenderedOp mask = ClampDescriptor.create(source, new double[] {0}, new double[] {1}, null);
    mask = MultiplyConstDescriptor.create(mask, new double[] {255}, null);
    mask = NotDescriptor.create(mask, null);
    mask = ClampDescriptor.create(mask, new double[] {0}, new double[] {1}, null);
    target1 = MultiplyDescriptor.create(target1, mask, null);
    target1 = AddDescriptor.create(target1, source, null);
    System.out.println("Writing " + targetFile1);
    FileStoreDescriptor.create(target1, targetFile1, format, null, false, null);
    System.out.println("Done in " + (System.currentTimeMillis() - t1) + " ms");

    long t2 = System.currentTimeMillis();
    System.out.println("Computing " + targetFile2);
    BufferedImage target2 = convolveICOL(source, gaussKernel, distKernel);
    System.out.println("Writing " + targetFile2);
    FileStoreDescriptor.create(target2, targetFile2, format, null, false, null);
    System.out.println("Done in " + (System.currentTimeMillis() - t2) + " ms");
  }
Example #13
0
  private void browseAction() {
    if (selectedPath == null) {
      selectedPath = System.getenv("ROPE_SOURCES_DIR");
      if (selectedPath != null) {
        File dir = new File(selectedPath);
        if (!dir.exists() || !dir.isDirectory()) {
          String message =
              String.format(
                  "The sources path set in environment variable ROPE_SOURCES_DIR is not avaliable.\n%s",
                  selectedPath);
          JOptionPane.showMessageDialog(null, message, "ROPE", JOptionPane.WARNING_MESSAGE);
          selectedPath = null;
        } else {
          System.out.println("Source folder path set from ROPE_SOURCES_DIR: " + selectedPath);
        }
      }
      if (selectedPath == null) {
        selectedPath = System.getProperty("user.dir");

        System.out.println("Source folder path set to current directory: " + selectedPath);
      }
    }

    Vector<RopeFileFilter> filters = new Vector<RopeFileFilter>();
    filters.add(
        new RopeFileFilter(
            new String[] {".a", ".asm", ".aut", ".s"}, "Assembly files (*.a *.asm *.aut *.s)"));
    filters.add(new RopeFileFilter(new String[] {".m", ".mac"}, "Macro files (*.m *.mac)"));
    filters.add(new RopeFileFilter(new String[] {".lst"}, "List files (*.lst)"));
    filters.add(new RopeFileFilter(new String[] {".txt"}, "Text files (*.txt)"));

    RopeFileChooser chooser = new RopeFileChooser(selectedPath, null, filters);
    chooser.setDialogTitle("Source document selection");
    chooser.setFileFilter(filters.firstElement());
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    File file = chooser.open(this, fileText);
    if (file != null) {
      if (loadSourceFile(file)) {
        mainFrame.showExecWindow(baseName);
      }
    }
  }
Example #14
0
  void run() {
    Scanner sc = new Scanner(System.in);
    int oo = sc.nextInt();
    for (int o = 1; o <= oo; o++) {
      que = new PriorityQueue<E>();
      int n = sc.nextInt();
      tank = new Tank();
      count = 0;
      int[] h = new int[n + 3], b = new int[n + 3];
      h[0] = 100;
      b[0] = 0;
      h[n + 1] = 50;
      b[n + 1] = 100;
      h[n + 2] = 50;
      b[n + 2] = INF;
      for (int i = 1; i <= n; i++) {
        b[i] = sc.nextInt();
        h[i] = sc.nextInt();
      }
      n += 3;
      for (int i = 1; i < n; i++) {
        tank.bs.add(new Box(b[i - 1], b[i], h[i - 1], h[i], 0, 0));
      }
      int m = sc.nextInt();
      for (int i = 0; i < m; i++) {
        int f = sc.nextInt();
        double a = sc.nextDouble() / 30;
        for (Box box : tank.bs) {
          if (box.b1 < f && f < box.b2) box.f += a;
        }
      }
      debug(tank.bs);

      int l = sc.nextInt();
      res = new double[l];
      for (int i = 0; i < l; i++) {
        que.offer(new W(sc.nextInt(), sc.nextDouble(), i));
      }
      que.offer(tank.nextEvent());
      debug(que.size());
      while (!que.isEmpty()) {
        if (res[0] < 0) System.exit(1);
        que.poll().go();
        debug(que.peek().time());
        debug(tank.bs);
        debug(res);
        debug();
        if (count == l) break;
      }
      for (double r : res) {
        System.out.println(r);
      }
    }
  }
Example #15
0
  /*compute the initial Time outs for all equipments */
  private void computeInitialTimes() {
    System.out.println("t0 is" + t0);
    double timeDiff = 0;

    /*Times for available equipment will depend on the type and position in queue as it's FIFO */
    generateRandomOrderTimes();

    /*for equipment on rent, it's simply at the end of the rental period */
    for (Equipment e : rentEquipment) {
      e.timeIn = System.currentTimeMillis() - t0;
      timeDiff = nextRandomTime(RENTALFREQUENCY[e.type - 1]);
      e.timeOut = System.currentTimeMillis() + timeDiff - t0;
      System.out.println("I am in state " + e.state + " and order " + rentEquipment.indexOf(e));
      System.out.println(
          "My time in is "
              + e.timeIn
              + " And my time out is "
              + e.timeOut
              + " and the difference between the 2 is "
              + (e.timeOut - e.timeIn));
      /*System.out.println("and nextRandomTime returns" + nextRandomTime(e.timeIn,RENTALFREQUENCY[e.type-1]) +" for type "+e.type+" for RentalFrequency "+RENTALFREQUENCY[e.type-1]);
      System.out.println("For equipment in state "+e.state+" and order "+rentEquipment.indexOf(e)+" : inter-arrival is "+(e.timeOut-e.timeIn)); */
    }

    /*for equipment in the shop, it's simply at the end of the rental period */
    for (Equipment e : shopEquipment) {
      e.timeIn = System.currentTimeMillis() - t0;
      timeDiff = nextRandomTime(SHOPFREQUENCY[e.type - 1]);
      e.timeOut = System.currentTimeMillis() + timeDiff - t0;
      System.out.println("I am in state " + e.state + " and order " + shopEquipment.indexOf(e));
      System.out.println(
          "My time in is "
              + e.timeIn
              + " And my time out is "
              + e.timeOut
              + " and the difference between the 2 is "
              + (e.timeOut - e.timeIn));
      /*System.out.println("For equipment in state "+e.state+" and order "+shopEquipment.indexOf(e)+" : inter-arrival is "+(e.timeOut-e.timeIn)); */
    }
  }
Example #16
0
  /*Scans the particular equipment and decides whether or not it shoud be moved */
  private int scan(Equipment equip) {
    double currentTime = System.currentTimeMillis() - t0;
    int orderMoved = -1;
    int or = -1;
    switch (equip.state) {
      case 1:
        or = availEquipment.indexOf(equip);
        break;
      case 2:
        or = rentEquipment.indexOf(equip);
        break;
      case 3:
        or = shopEquipment.indexOf(equip);
        break;
    }
    // System.out.println("Now looking at state "+equip.state+" and type "+equip.type+" and order"
    // +or);
    // System.out.println("Current time is "+currentTime+" while equip.timeOut time is
    // "+equip.timeOut+" and the difference is "+(equip.timeOut-currentTime));

    switch (equip.state) {
      case 1:
        break;
      case 2:
        if (equip.timeOut < System.currentTimeMillis() - t0) {
          orderMoved = rentEquipment.indexOf(equip);
          return orderMoved;
        }
        break;
      case 3:
        if (equip.timeOut < System.currentTimeMillis() - t0) {
          orderMoved = shopEquipment.indexOf(equip);
          // System.out.println("I have just moved equipment from state 3 "+equip.state+" of type
          // "+equip.type+" and of order "+shopEquipment.indexOf(equip));
          return orderMoved;
        }
        break;
    }
    return orderMoved;
  }
Example #17
0
 public CA3(float SCSymmetricDivBalance, int maxDivisions, float densityV) {
   int time = (int) System.currentTimeMillis();
   random = new MersenneTwisterFast(5); // choose a seed a number or 'time'
   asymmetricRatio = SCSymmetricDivBalance;
   maxProDivisions = maxDivisions;
   maxMatureCellAge = 1;
   // densityVasculature=densityV;
   carriedGenome = new StringBuilder[size][size];
   // tree = new Hashtable<Integer,Integer>();
   // timeTree = new Hashtable<Integer, Integer>();
   reset();
   // resetVasculature();
 }
Example #18
0
 /** @param args */
 public static void main(String[] args) throws Exception {
   File file = new File("input.txt");
   if (file.exists()) {
     System.setIn(new BufferedInputStream(new FileInputStream("input.txt")));
   }
   out = System.out;
   bw = new BufferedWriter(new PrintWriter(out));
   // sc =  new Scanner(System.in);
   br = new BufferedReader(new InputStreamReader(System.in));
   C231 t = new C231();
   t.solve();
   bw.close();
 }
Example #19
0
 public static void main(String[] args) throws IOException {
   // InputStream inputStream = new FileInputStream("replaceme.in");
   // OutputStream outputStream = new FileOutputStream("replaceme.out");
   /////////////////////////////////////////////////////////////////////
   InputStream inputStream = System.in;
   OutputStream outputStream = System.out;
   InputReader in = new InputReader(inputStream);
   OutputWriter out = new OutputWriter(outputStream);
   Task solver = new Task();
   solver.solve(1, in, out);
   out.close();
   System.exit(0);
 }
Example #20
0
  /** @param args */
  public static void main(String[] args) throws Exception {
    File file = new File("B-small-practice.in");
    if (file.exists()) {
      System.setIn(new BufferedInputStream(new FileInputStream(file)));
    }
    sc = new Scanner(System.in);
    FileWriter fw = new FileWriter(new File("output.txt"));
    out = new PrintWriter(fw);

    Bsmall b = new Bsmall();
    int T = sc.nextInt();
    int t = 1;
    while (t <= T) {
      out.print("Case #" + t + ": ");
      b.solve();
      t++;
    }
    out.close();
    fw.close();
  }
Example #21
0
  public void transform(double[] src, double[] dst) {
    if (src.length != dst.length) {
      System.err.println("not able to transform point due to dimension error.");
      System.exit(1);
    } else {

      for (int i = 0; i < src.length; i++) {
        temp[i] = src[i];
      }
      temp[src.length] = 1;

      for (int i = 0; i < this.row - 1; i++) {
        double replacement = 0;
        for (int j = 0; j < this.col; j++) {
          replacement += temp[j] * this.get(j, i);
        }
        dst[i] = replacement;
      }
    }
  }
Example #22
0
 ///////  this is to run CA without Vis ***********  end from non sensitivty analysis stuff
 public static void main(String args[]) {
   int maxTS = 1000;
   CA3 ca;
   System.err.println("# CA version:" + CA3.version);
   float SCSymmetricDivBalance = 0.2f;
   int maxDivisions = 3;
   float densityV = 0.04f;
   if (args.length == 4) {
     SCSymmetricDivBalance = Float.parseFloat(args[0]);
     maxDivisions = Integer.parseInt(args[1]);
     maxTS = Integer.parseInt(args[2]);
     densityV = Float.parseFloat(args[3]);
     System.err.println(
         "Balance: " + SCSymmetricDivBalance + " maxDiv: " + maxDivisions + " maxTS: " + maxTS);
   } else {
     System.err.println("Arguments needed: s/a maxDivisions timesteps, densityV");
     System.exit(-1);
   }
   ca = new CA3(SCSymmetricDivBalance, maxDivisions, densityV);
   for (int ts = 0; ts < maxTS; ts++) ca.nextTimeStep();
 }
Example #23
0
  /** @param args */
  public static void main(String[] args) throws Exception {
    out = System.out;
    File file = new File("input.txt");
    if (file.exists()) {
      System.setIn(new BufferedInputStream(new FileInputStream("input.txt")));
    }
    sc = new Scanner(System.in);
    POJ3109 p = new POJ3109();

    while (true) {
      try {
        N = sc.nextInt();
        if (N == 0) {
          break;
        }
      } catch (Exception ex) {
        break;
      }
      p.solve();
    }
  }
Example #24
0
  public void rightMultiply(Matrix other) {
    // this * other
    if (this.col != other.row) {
      System.err.println("attempt to multiply incompatible matrices.");
      System.exit(1);
    } else {

      tempCopy();

      for (int i = 0; i < tempElements.length; i++) {
        for (int j = 0; j < other.col; j++) {
          // multiply this row by other col to get replacement elements[i][j]
          double replacement = 0;
          for (int k = 0; k < tempElements[0].length; k++) {
            replacement += tempElements[i][k] * other.get(j, k);
          }
          this.set(j, i, replacement);
        }
      }
    }
  }
Example #25
0
  public void leftMultiply(Matrix other) {
    // other * this
    if (other.col != this.row) {
      System.err.println("attempt to multiply incompatible matrices.");
      System.exit(1);
    } else {

      tempCopy();

      for (int i = 0; i < other.row; i++) {
        for (int j = 0; j < tempElements[0].length; j++) {
          // multiply other row by this col to get replacement elements[i][j]
          double replacement = 0;
          for (int k = 0; k < other.col; k++) {
            replacement += other.get(k, i) * tempElements[k][j];
          }
          this.set(j, i, replacement);
        }
      }
    }
  }
Example #26
0
  /* Generates random order times for the orders of each type in the Available state */
  private void generateRandomOrderTimes() {
    orderTime1 = System.currentTimeMillis() + nextRandomTime(ARRIVAL1) - t0;
    orderTime2 = System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0;
    orderTime3 = System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0;

    double[] arrivalFrequencies = {ARRIVAL1, ARRIVAL2, ARRIVAL3};
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL1) - t0);
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0);
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL3) - t0);

    /*for (double counter : arrivalFrequencies) {
    	System.out.println("t0 is = "+t0+" and current time is "+currentTime);
    	currentTime=System.currentTimeMillis()-t0;
    	orderTimes.add(System.currentTimeMillis()+nextRandomTime(counter)-t0);
    }*/
  }
Example #27
0
  /** @param args */
  public static void main(String[] args) {
    FileChannel fc = null;
    RandomAccessFile raf = null;
    // StringBuilder sb;

    if (args.length != 1) {
      System.out.println("Usage: Ntfs filename");
      System.exit(1);
    }
    /*
    sb = new StringBuilder();
    int[] foo = {129,4,229,33};
    for (int b: foo) {
        sb.insert(0,String.format("%02X", b));
    }
    System.out.println(sb.toString());
    System.exit(0);
    */
    try {
      raf = new RandomAccessFile(args[0], "r");
      fc = raf.getChannel();
      Filesystem fs = new Filesystem(fc);

      fs.demo();
      // fs.displayFs();
    } catch (FileNotFoundException x) {
      System.out.println("FNF exp: " + x.getMessage());
    } catch (IOException x) {
      System.out.println("IO exp: " + x.getMessage());
    } finally {
      if (raf != null)
        try {
          raf.close();
        } catch (IOException e) {
          e.printStackTrace(); // To change body of catch statement use File | Settings | File
          // Templates.
        }
    }
  }
public class _336_D_Bear_Vasily_and_Beautiful_Strings {
  // ->solution screencast http://youtu.be/oHg5SJYRHA0
  public void solve() {
    int n = ni();
    long res = 0;

    out.println(res);
  }

  // IO methods

  void run() throws Exception {
    long s = System.currentTimeMillis();
    solve();
    out.flush();
    pr(System.currentTimeMillis() - s + "ms");
  }

  public static void main(String[] args) throws Exception {
    new _336_D_Bear_Vasily_and_Beautiful_Strings().run();
  }

  InputStream in = System.in;
  PrintWriter out = new PrintWriter(System.out);

  private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
  private byte[] inbuf = new byte[1024];
  private int lenbuf = 0, ptrbuf = 0;

  private int readByte() {
    if (lenbuf == -1) throw new InputMismatchException();
    if (ptrbuf >= lenbuf) {
      ptrbuf = 0;
      try {
        lenbuf = in.read(inbuf);
      } catch (IOException e) {
        throw new InputMismatchException();
      }
      if (lenbuf <= 0) return -1;
    }
    return inbuf[ptrbuf++];
  }

  private boolean isSpaceChar(int c) {
    return !(c >= 33 && c <= 126);
  }

  private int skip() {
    int b;
    while ((b = readByte()) != -1 && isSpaceChar(b)) ;
    return b;
  }

  public String ns() {
    int b = skip();
    StringBuilder sb = new StringBuilder();
    while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ')
      sb.appendCodePoint(b);
      b = readByte();
    }
    return sb.toString();
  }

  public char[] ns(int n) {
    char[] buf = new char[n];
    int b = skip(), p = 0;
    while (p < n && !(isSpaceChar(b))) {
      buf[p++] = (char) b;
      b = readByte();
    }
    return n == p ? buf : Arrays.copyOf(buf, p);
  }

  public char[][] nm(int n, int m) {
    char[][] map = new char[n][];
    for (int i = 0; i < n; i++) map[i] = ns(m);
    return map;
  }

  public int[] na(int n) {
    int[] a = new int[n];
    for (int i = 0; i < n; i++) a[i] = ni();
    return a;
  }

  public int ni() {
    int num = 0, b;
    boolean minus = false;
    while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
    if (b == '-') {
      minus = true;
      b = readByte();
    }

    while (true) {
      if (b >= '0' && b <= '9') {
        num = num * 10 + (b - '0');
      } else {
        return minus ? -num : num;
      }
      b = readByte();
    }
  }

  public long nl() {
    long num = 0;
    int b;
    boolean minus = false;
    while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
    if (b == '-') {
      minus = true;
      b = readByte();
    }
    while (true) {
      if (b >= '0' && b <= '9') {
        num = num * 10 + (b - '0');
      } else {
        return minus ? -num : num;
      }
      b = readByte();
    }
  }

  void pr(Object... ob) {
    if (!oj) System.out.println(Arrays.deepToString(ob).replace("],", "],\n"));
  }
}
 void run() throws Exception {
   long s = System.currentTimeMillis();
   solve();
   out.flush();
   pr(System.currentTimeMillis() - s + "ms");
 }
Example #30
0
  public boolean loadSourceFile(File file) {
    boolean result = false;

    selectedPath = file.getParent();

    BufferedReader sourceFile = null;

    String directoryPath = file.getParent();
    String sourceName = file.getName();

    int idx = sourceName.lastIndexOf(".");
    fileExt = idx == -1 ? "" : sourceName.substring(idx + 1);
    baseName = idx == -1 ? sourceName.substring(0) : sourceName.substring(0, idx);
    String basePath = directoryPath + File.separator + baseName;

    DataOptions.directoryPath = directoryPath;

    sourcePath = file.getPath();

    AssemblerOptions.sourcePath = sourcePath;
    AssemblerOptions.listingPath = basePath + ".lst";
    AssemblerOptions.objectPath = basePath + ".cd";

    String var = System.getenv("ROPE_MACROS_DIR");
    if (var != null && !var.isEmpty()) {
      File dir = new File(var);
      if (dir.exists() && dir.isDirectory()) {
        AssemblerOptions.macroPath = var;
      } else {
        AssemblerOptions.macroPath = directoryPath;
      }
    } else {
      AssemblerOptions.macroPath = directoryPath;
    }

    DataOptions.inputPath = AssemblerOptions.objectPath;
    DataOptions.outputPath = basePath + ".out";
    DataOptions.readerPath = null;
    DataOptions.punchPath = basePath + ".pch";
    DataOptions.tape1Path = basePath + ".mt1";
    DataOptions.tape2Path = basePath + ".mt2";
    DataOptions.tape3Path = basePath + ".mt3";
    DataOptions.tape4Path = basePath + ".mt4";
    DataOptions.tape5Path = basePath + ".mt5";
    DataOptions.tape6Path = basePath + ".mt6";

    this.setTitle("EDIT: " + sourceName);
    fileText.setText(sourcePath);

    if (dialog == null) {
      dialog = new AssemblerDialog(mainFrame, "Assembler options");

      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      Dimension dialogSize = dialog.getSize();
      dialog.setLocation(
          (screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2);
    }

    dialog.initialize();

    AssemblerOptions.command = dialog.buildCommand();

    sourceArea.setText(null);

    try {
      sourceFile = new BufferedReader(new FileReader(file));
      String line;

      while ((line = sourceFile.readLine()) != null) {
        sourceArea.append(line + "\n");
      }

      sourceArea.setCaretPosition(0);
      optionsButton.setEnabled(true);
      assembleButton.setEnabled(true);
      saveButton.setEnabled(true);

      setSourceChanged(false);
      undoMgr.discardAllEdits();

      result = true;
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        if (sourceFile != null) {
          sourceFile.close();
        }
      } catch (IOException ignore) {
      }
    }

    return result;
  }