Exemplo n.º 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();
   }
 }
Exemplo n.º 2
0
Arquivo: vans.java Projeto: 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();
 }
Exemplo n.º 3
0
 private void redirectIO() {
   // redirect std I/O to console and problems:
   // > System.out => console
   // > System.err => problems
   // > console => System.in
   System.setOut(consoleView.getOutputStream());
   System.setErr(problemsView.getOutputStream());
   // redirect input from console to System.in
   System.setIn(consoleView.getInputStream());
 }
Exemplo n.º 4
0
 public String runApp(String[] args, String input) throws Exception {
   // Save normal System.in and System.out
   InputStream sysin = System.in;
   PrintStream sysout = System.out;
   // Replace System.in with input text
   if (input == null) {
     input = "";
   }
   System.setIn(new ByteArrayInputStream(input.getBytes("UTF-8")));
   // Replace System.out with OutputStream we can capture
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   System.setOut(new PrintStream(out));
   // Run the app with the List of arguments
   App.main(args);
   // Replace normal System.in and System.out
   System.setIn(sysin);
   System.setOut(sysout);
   // Return the captured output
   return out.toString("UTF-8").trim();
 }
Exemplo n.º 5
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();
 }
Exemplo n.º 6
0
 Quest() {
   @SuppressWarnings({"UnusedDeclaration"})
   String id = getClass().getName().toLowerCase();
   //noinspection EmptyTryBlock
   try {
     System.setIn(new FileInputStream(id + ".in"));
     System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
     //			System.setIn(new FileInputStream("input.txt"));
     //			System.setOut(new PrintStream(new FileOutputStream("output.txt")));
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   in = new InputReader(System.in);
   out = new PrintWriter(System.out);
 }
Exemplo n.º 7
0
  public static void main(String[] args) throws IOException {

    // Create a String
    StringBuilder sb = new StringBuilder();
    sb.append("Lena").append('\n');
    sb.append("Katya").append('\n');
    sb.append("Anya").append('\n');
    String data = sb.toString();

    // Wrap an InputStream
    InputStream is = new ByteArrayInputStream(data.getBytes());

    // Substitute a real InputStream
    System.setIn(is);

    readAndPrintLine();
  }
Exemplo n.º 8
0
 public static void main(String... args) {
   System.setIn(
       new ByteArrayInputStream(
           "2\n5\n0 0\n1 0\n1 1\n1 2\n0 2\n6\n1.0 1.0\n30.91 8\n4.0 7.64\n21.12 6.0\n11.39 3.0\n5.31 11.0"
               .getBytes()));
   Scanner scanner = new Scanner(System.in);
   int t = scanner.nextInt();
   for (int i = 0; i < t; i++) {
     int n = scanner.nextInt();
     Coord[] towers = new Coord[n];
     for (int j = 0; j < n; j++) {
       towers[j] = new Coord(scanner.nextDouble(), scanner.nextDouble());
     }
     Arctic arctic = new Arctic(towers);
     arctic.minPower(0, new boolean[n], new double[n - 1]);
     System.out.printf("%.2f\n", arctic.min);
   }
 }
Exemplo n.º 9
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();
  }
Exemplo n.º 10
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();
    }
  }
Exemplo n.º 11
0
  /*
   * Accepts a new request from the HTTP server and creates
   * a conventional execution environment for the request.
   * If the application was invoked as a FastCGI server,
   * the first call to FCGIaccept indicates that the application
   * has completed its initialization and is ready to accept
   * a request.  Subsequent calls to FCGI_accept indicate that
   * the application has completed its processing of the
   * current request and is ready to accept a new request.
   * If the application was invoked as a CGI program, the first
   * call to FCGIaccept is essentially a no-op and the second
   * call returns EOF (-1) as does an error. Application should exit.
   *
   * If the application was invoked as a FastCGI server,
   * and this is not the first call to this procedure,
   * FCGIaccept first flushes any buffered output to the HTTP server.
   *
   * On every call, FCGIaccept accepts the new request and
   * reads the FCGI_PARAMS stream into System.props. It also creates
   * streams that understand FastCGI protocol and take input from
   * the HTTP server send output and error output to the HTTP server,
   * and assigns these new streams to System.in, System.out and
   * System.err respectively.
   *
   * For now, we will just return an int to the caller, which is why
   * this method catches, but doen't throw Exceptions.
   *
   */
  public int FCGIaccept() {
    int acceptResult = 0;

    /*
     * If first call, mark it and if fcgi save original system properties,
     * If not first call, and  we are cgi, we should be gone.
     */
    if (!acceptCalled) {
      isFCGI = System.getenv("FCGI_PORT") != null;
      acceptCalled = true;
      if (isFCGI) {
        /*
         * save original system properties (nonrequest)
         * and get a server socket
         */
        startupProps = new Properties(System.getProperties());
        String str = new String(System.getenv("FCGI_PORT"));
        if (str.length() <= 0) {
          return -1;
        }
        int portNum = Integer.parseInt(str);

        try {
          srvSocket = new ServerSocket(portNum);
        } catch (IOException e) {
          if (request != null) {
            request.socket = null;
          }
          srvSocket = null;
          request = null;
          return -1;
        }
      }
    } else {
      if (!isFCGI) {
        return -1;
      }
    }
    /*
     * If we are cgi, just leave everything as is, otherwise set up env
     */
    if (isFCGI) {
      try {
        acceptResult = FCGIAccept();
      } catch (IOException e) {
        return -1;
      }
      if (acceptResult < 0) {
        return -1;
      }

      /*
       * redirect stdin, stdout and stderr to fcgi socket
       */
      System.setIn(new BufferedInputStream(request.inStream, 8192));
      System.setOut(new PrintStream(new BufferedOutputStream(request.outStream, 8192)));
      System.setErr(new PrintStream(new BufferedOutputStream(request.errStream, 512)));
      System.setProperties(request.params);
    }
    return 0;
  }
Exemplo n.º 12
0
 public static void main(String[] args) throws Exception {
   System.setIn(new BufferedInputStream(new FileInputStream("E.txt")));
   new E().run();
 }
Exemplo n.º 13
0
  /**
   * Executes the requested Grails target. The "targetName" must match a known Grails script
   * provided by grails-scripts.
   *
   * @param targetName The name of the Grails target to execute.
   * @param args String of arguments to be passed to the executed Grails target.
   * @throws MojoExecutionException if an error occurs while attempting to execute the target.
   */
  protected void runGrails(final String targetName, String args) throws MojoExecutionException {
    if (((lastArgs != null && lastArgs.equals(args)) || (lastArgs == null && args == null))
        && lastTargetName != null
        && lastTargetName.equals(targetName)) return;

    lastArgs = args;
    lastTargetName = targetName;

    if (!alreadyLoaderClasspathForArtifact()) doOncePerArtifact();
    else if (targetName.equals("War")) resolveClasspath(); // we have to get rid of the test rubbish

    getLog()
        .info(
            "Grails target: "
                + targetName
                + " raw args:"
                + args
                + " (pom says Grails Version is "
                + grailsVersion
                + ")");

    InputStream currentIn = System.in;
    PrintStream currentOutput = System.out;

    try {
      RootLoader rootLoader = new RootLoader(addBinaryPluginWorkaround(classpath));

      // see if log4j is there and if so, initialize it
      try {
        Class cls = rootLoader.loadClass("org.springframework.util.Log4jConfigurer");
        invokeStaticMethod(
            cls, "initLogging", new Object[] {"classpath:grails-maven/log4j.properties"});
      } catch (Exception ex) {
        getLog().info("No log4j available, good!");
      }

      try {
        final DecentGrailsLauncher launcher =
            new DecentGrailsLauncher(rootLoader, grailsHomePath, basedir.getAbsolutePath());
        launcher.setPlainOutput(true);

        /**
         * this collects the different dependency levels (compile, runtime, test) and puts them into
         * the correct arrays to pass through to the Grails script launcher. If using Maven, you
         * should *never* see an Ivy message and if you do, immediately stop your build, figure out
         * the incorrect dependency, delete the ~/.ivy2 directory and try again.
         */
        Field settingsField = launcher.getClass().getDeclaredField("settings");
        settingsField.setAccessible(true);

        configureBuildSettings(
            launcher,
            resolvedArtifacts,
            settingsField,
            rootLoader.loadClass("grails.util.BuildSettings"),
            args);

        syncAppVersion();

        installGrailsPlugins(
            pluginDirectories,
            launcher,
            settingsField,
            rootLoader.loadClass("grails.util.AbstractBuildSettings"));

        // If the command is running in non-interactive mode, we
        // need to pass on the relevant argument.
        if (this.nonInteractive) {
          args = (args != null) ? "--non-interactive " + args : "--non-interactive ";
        }

        // consuming the standard output after execution via Maven.
        args = (args != null) ? "--plain-output " + args : "--plain-output";
        args = (args != null) ? "--stacktrace " + args : "--stacktrace";
        args = (args != null) ? "--verboseCompile " + args : "--verboseCompile";

        if (env == null) System.clearProperty("grails.env");
        else System.setProperty("grails.env", env);

        getLog()
            .info(
                "grails -Dgrails.env="
                    + (env == null ? "dev" : env)
                    + " "
                    + targetName.toLowerCase()
                    + " "
                    + args);
        int retval;

        if ("true".equals(System.getProperty("print.grails.settings"))
            || "ideaprintprojectsettings".equalsIgnoreCase(targetName)) {
          printIntellijIDEASettings(launcher, settingsField, pluginArtifacts);
        } else {

          if ("interactive".equals(targetName)) retval = launcher.launch("", "", env);
          else retval = launcher.launch(targetName, args, env);

          if (retval != 0) {
            throw new MojoExecutionException("Grails returned non-zero value: " + retval);
          }
        }
      } catch (final MojoExecutionException ex) {
        // Simply rethrow it.
        throw ex;
      } catch (final Exception ex) {
        getLog().error(ex);

        throw new MojoExecutionException("Unable to start Grails", ex);
      }

      rootLoader = null;
    } catch (MalformedURLException mfe) {
      throw new MojoExecutionException("Unable to start Grails", mfe);
    } finally {
      System.setIn(currentIn);
      System.setOut(currentOutput);
    }

    System.gc(); // try and help with memory issues
  }
Exemplo n.º 14
0
  public static void main(String[] args) {
    log = Logger.getLogger(Main.class.getName());
    try {
      // Setting up logging

      Logger packageLog = Logger.getLogger(ChatBot.class.getPackage().getName());
      File logFile = new File(LOGFILE + ".log");
      if (logFile.exists()) {
        Calendar cal = Calendar.getInstance();
        File backup =
            new File(
                String.format(
                    "%s_%d_%d_%d.log",
                    LOGFILE,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH) + 1,
                    cal.get(Calendar.DAY_OF_MONTH)));
        if (backup.exists())
          try (BufferedReader reader = new BufferedReader(new FileReader(logFile));
              PrintWriter writer = new PrintWriter(new FileWriter(backup, true))) {
            char buff[] = new char[1024];
            int n;
            while ((n = reader.read(buff)) > 0) {
              writer.write(buff, 0, n);
            }
            log.info("Appened log to backup " + backup.getName());
          } catch (IOException e) {
            log.log(Level.SEVERE, "Couldn't append log to " + backup.getName(), e);
          }
        else {
          try {
            FileUtils.moveFile(logFile, backup);
            log.info("Moved log to backup " + backup.getName());
          } catch (IOException e) {
            log.log(Level.SEVERE, "Couldn't move log to " + backup.getName(), e);
          }
        }
      }

      //noinspection ResultOfMethodCallIgnored
      // logFile.delete();
      Handler handler = new FileHandler(LOGFILE + ".log");
      handler.setFormatter(new SimpleFormatter());
      packageLog.setLevel(Level.FINE);
      packageLog.addHandler(handler);

      // Starting up XMPPCraft
      Main main = new Main();
      PipeInputStream stdinPipe = new PipeInputStream(1048576);
      PipeOutputStream stdoutPipe = new PipeOutputStream();
      main.init(
          System.in, new PipeOutputStream(stdinPipe), new PipeInputStream(stdoutPipe, 1048576));
      System.setIn(stdinPipe);
      System.setOut(new PrintStream(new TeeOutputStream(System.out, stdoutPipe)));
      main.start();
      // Starting up Minecraft
      MinecraftServer.main(args);
      // DummyMinecraftServer.main(args);
    } catch (KeyManagementException
        | NoSuchAlgorithmException
        | SmackException
        | XMPPException
        | IOException e) {
      String filename =
          String.format(
              "crashreport_%s_%s.log",
              e.getClass().getSimpleName(), new SimpleDateFormat("MM_dd.HH_mm").format(new Date()));
      File f = new File(filename);
      try {
        if (f.createNewFile()) {
          PrintWriter out = new PrintWriter(f);
          out.println("Error on startup :");
          out.printf(
              "JVM: %s %s on %s\n",
              System.getProperty("java.vm.name"),
              System.getProperty("java.runtime.version"),
              System.getProperty("os.name"));
          e.printStackTrace(out);
          out.flush();
          out.close();
        }
      } catch (IOException ignore) {
      } // lol what can you do
      log.severe("Crash detected. Generating report.");
    }
  }