/**
  * Parses a textual representation of an object ID as dotted string (e.g. "1.3.6.1.2.1.1") and
  * returns its raw value.
  *
  * @param text a textual representation of an OID.
  * @return the raw OID value.
  * @throws ParseException if the OID cannot be parsed successfully.
  */
 public int[] parse(String text) throws ParseException {
   StringTokenizer st = new StringTokenizer(text, ".", true);
   int size = st.countTokens();
   int[] value = new int[size];
   size = 0;
   StringBuffer buf = null;
   while (st.hasMoreTokens()) {
     String t = st.nextToken();
     if ((buf == null) && t.startsWith("'")) {
       buf = new StringBuffer();
       t = t.substring(1);
     }
     if ((buf != null) && (t.endsWith("'"))) {
       buf.append(t.substring(0, t.length() - 1));
       OID o = new OctetString(buf.toString()).toSubIndex(true);
       int[] h = value;
       value = new int[st.countTokens() + h.length + o.size()];
       System.arraycopy(h, 0, value, 0, size);
       System.arraycopy(o.getValue(), 0, value, size, o.size());
       size += o.size();
       buf = null;
     } else if (buf != null) {
       buf.append(t);
     } else if (!".".equals(t)) {
       value[size++] = (int) Long.parseLong(t.trim());
     }
   }
   if (size < value.length) {
     int[] h = value;
     value = new int[size];
     System.arraycopy(h, 0, value, 0, size);
   }
   return value;
 }
Example #2
1
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("Usage: java MyParser [file] [file] ...");
      System.exit(1);
    }

    /* Initialize parser. */
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(false);
      factory.setIgnoringElementContentWhitespace(true);
      builder = factory.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      userList = new Hashtable<String, String[]>();
      bothSellerAndBuyer = new Vector<String>();
    } catch (FactoryConfigurationError e) {
      System.out.println("unable to get a document builder factory");
      System.exit(2);
    } catch (ParserConfigurationException e) {
      System.out.println("parser was unable to be configured");
      System.exit(2);
    }

    /* Process all files listed on command line. */
    for (int i = 0; i < args.length; i++) {
      File currentFile = new File(args[i]);
      processFile(currentFile);
    }
    writeUsersToFile();
  }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit-pf 2.3.0
 private static boolean KawigiEdit_RunTest(int testNum, int p0, boolean hasAnswer, int p1) {
   System.out.print("Test " + testNum + ": [" + p0);
   System.out.println("]");
   EmoticonsDiv1 obj;
   int answer;
   obj = new EmoticonsDiv1();
   long startTime = System.currentTimeMillis();
   answer = obj.printSmiles(p0);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p1);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == p1;
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit 2.1.8 (beta) modified by pivanof
 private static boolean KawigiEdit_RunTest(
     int testNum, int p0, int p1, boolean hasAnswer, String p2) {
   System.out.print("Test " + testNum + ": [" + p0 + "," + p1);
   System.out.println("]");
   KLastNonZeroDigits obj;
   String answer;
   obj = new KLastNonZeroDigits();
   long startTime = System.currentTimeMillis();
   answer = obj.getKDigits(p0, p1);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + "\"" + p2 + "\"");
   }
   System.out.println("Your answer:");
   System.out.println("\t" + "\"" + answer + "\"");
   if (hasAnswer) {
     res = answer.equals(p2);
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
Example #6
0
  /**
   * Returns JPicEdt's install directory w/o trailing "/", provided the command line looks like :
   *
   * <p><code>java -classpath other-class-paths:jpicedt-install-dir/lib/jpicedt.jar jpicedt.JPicEdt
   * </code> (where <code>/</code> may be replaced by the actual respective separator for files on
   * the underlying platform).
   *
   * <p>For Windows platform, the install directory is tried to be detected 1st with the MSWindows
   * file-separator (<code>\</code>), and if this does not work, a subsequent trial is made with
   * <code>/</code>.
   *
   * <p>That is, the old way (java -jar jpicedt.jar) won't work. However, classpath can contain
   * relative pathname (then user.dir get prepended).
   *
   * <p>Code snippet was adapted from jEdit/JEdit.java (http://www.jedit.org).
   *
   * @return the value of the "user.dir" Java property if "lib/jpicedt.jar" wasn't found in the
   *     command line.
   */
  public static String getJPicEdtHome() {

    String classpath = System.getProperty("java.class.path"); // e.g.
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/lib/jpicedt.jar"
    // File.separator = "/" on Unix, "\\" on Windows,...
    String fileSeparator = File.separator;
    int index;
    // File.pathSeparator = ":" on Unix/MacOS-X platforms, ";" on Windows
    // search ":" backward starting from
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/^lib/jpicedt.jar"

    String homeDir = null;
    int trials = 2;
    do {
      index = classpath.toLowerCase().indexOf("lib" + fileSeparator + "jpicedt.jar");
      int start = classpath.lastIndexOf(File.pathSeparator, index);
      if (start == -1)
        start =
            0; // File.pathSeparator not found => lib/jpicedt.jar probably at beginning of classpath
      else start += File.pathSeparator.length(); // e.g. ":^/home..."

      if (index >= start) {
        homeDir = classpath.substring(start, index);
        if (homeDir.endsWith(fileSeparator)) homeDir = homeDir.substring(0, homeDir.length() - 1);
      }
      switch (trials) {
        case 2:
          if (File.pathSeparator.equals(";") && homeDir == null) {
            // MS-Windows case, this must work both with / and \
            trials = 1;
            fileSeparator = "/";
          } else trials = 0;
          break;
        case 1:
          if (homeDir != null && !fileSeparator.equals(File.separator)) {
            homeDir.replace(fileSeparator, File.separator);
          }
          trials = 0;
          break;

        default:
          trials = 0;
          break;
      }
    } while (trials != 0);

    if (homeDir != null) {
      if (homeDir.equals("")) homeDir = System.getProperty("user.dir");
      else if (!new File(homeDir).isAbsolute())
        homeDir = System.getProperty("user.dir") + File.separator + homeDir;
    } else {
      homeDir = System.getProperty("user.dir");
      if (homeDir.endsWith(
          "lib")) // this is the case if jpicedt run as "java -jar jpicedt.jar" from inside lib/ dir
      homeDir = homeDir.substring(0, homeDir.lastIndexOf("lib"));
    }

    // System.out.println("JPicEdt's home = " + homeDir);
    return homeDir;
  }
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
  public static void main(String args[]) throws Exception {
    long begin, end;

    begin = System.currentTimeMillis();

    String logConfig = System.getProperty("log-config");
    if (logConfig == null) logConfig = "log-config.txt";

    PropertyConfigurator.configure(logConfig);

    if (args.length != 6) {
      System.err.println(
          "java -mx512M org.itc.irst.tcc.sre.util.StatisticalSignificance gold baseline preferred iterations confidence-level stat");
      System.exit(0);
    }

    String g = args[0];
    String b = args[1];
    String p = args[2];
    int n = Integer.parseInt(args[3]);
    double c = Double.parseDouble(args[4]);
    String s = args[5];
    new StatisticalSignificance(new File(g), new File(b), new File(p), n, c, s);

    //
    end = System.currentTimeMillis();
    logger.info("evaluation done in " + (end - begin) + " ms");
  } // end main
Example #9
0
  public static void main(String[] args) {
    if (args.length < 5) {
      System.out.println(
          "\n  Usage: java prob.mdp.MDPSim prob_file " + "spudd_vfun trials steps rand_seed\n");
      System.exit(1);
    }

    MDPSim mdpsim = new MDPSim(args[0], args[1]);

    ArrayList vals = null;
    int trials = -1, steps = -1;
    long seed = -1;
    try {
      trials = Integer.parseInt(args[2]);
      steps = Integer.parseInt(args[3]);
      seed = Long.parseLong(args[4]);
      vals = mdpsim.simulate(trials, steps, seed);
    } catch (NumberFormatException nfe) {
      System.out.println(nfe);
      System.exit(1);
    }

    System.out.println("\n Problem:  " + args[0]);
    System.out.println(" VFun:     " + args[1]);
    System.out.println(" Trials:   " + trials);
    System.out.println(" Steps:    " + steps);
    System.out.println(" Seed:     " + seed);
    System.out.println(" Data:     " + PrintList(vals));
    System.out.println(" Average:  " + MDP._df.format(Average(vals)) + "\n");
  }
Example #10
0
 public static void main(String[] args) {
   try {
     if (args.length != 1) throw new IllegalArgumentException("Wrong number of arguments");
     FileReader in = new FileReader(args[0]);
     HardcopyWriter out = null;
     Frame f = new Frame("PrintFile: " + args[0]);
     f.setSize(200, 50);
     f.show();
     try {
       out = new HardcopyWriter(f, args[0], 10, .75, .75, .75, .75);
     } catch (HardcopyWriter.PrintCanceledException e) {
       System.exit(0);
     }
     f.setVisible(false);
     char[] buffer = new char[4096];
     int numchars;
     while ((numchars = in.read(buffer)) != -1) out.write(buffer, 0, numchars);
     out.close();
   } catch (Exception e) {
     System.err.println(e);
     System.err.println("Usage: java HardcopyWriter$PrintFile <filename>");
     System.exit(1);
   }
   System.exit(0);
 }
Example #11
0
 /**
  * Concatenates two tokens.
  *
  * @param token1 first token
  * @param token2 second token
  * @return resulting array
  */
 public static byte[] concat(final byte[] token1, final byte[] token2) {
   final int t1 = token1.length;
   final int t2 = token2.length;
   final byte[] tmp = new byte[t1 + t2];
   System.arraycopy(token1, 0, tmp, 0, t1);
   System.arraycopy(token2, 0, tmp, t1, t2);
   return tmp;
 }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
 private static boolean KawigiEdit_RunTest(
     int testNum, int[] p0, int[] p1, int[] p2, boolean hasAnswer, int p3) {
   System.out.print("Test " + testNum + ": [" + "{");
   for (int i = 0; p0.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p0[i]);
   }
   System.out.print("}" + "," + "{");
   for (int i = 0; p1.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p1[i]);
   }
   System.out.print("}" + "," + "{");
   for (int i = 0; p2.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p2[i]);
   }
   System.out.print("}");
   System.out.println("]");
   KeyDungeonDiv2 obj;
   int answer;
   obj = new KeyDungeonDiv2();
   long startTime = System.currentTimeMillis();
   answer = obj.countDoors(p0, p1, p2);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p3);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == p3;
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
Example #13
0
 private void extractInfo(File filename) {
   checkpoint = false;
   String line;
   try {
     ArrayList<String> order = new ArrayList<String>();
     BufferedReader input =
         new BufferedReader(new InputStreamReader(new FileInputStream(filename), "iso-8859-1"));
     while ((line = input.readLine()) != null) {
       if (line.equalsIgnoreCase("hämtas")) checkpoint = true;
       if (checkpoint) order.add(new String(line));
     }
     //	printList(order);
     int quant = Integer.parseInt(order.get(2));
     int rows = 9;
     int outer = (quant * rows);
     double price;
     double total;
     // DecimalFormat decimal = (DecimalFormat) format;
     Number number;
     for (int i = 4; i <= outer; i += 9) {
       Data d =
           new Data(
               order.get(i + 1),
               order.get(i + 3),
               order.get(i + 4),
               order.get(i + 5),
               order.get(i + 7));
       dataList.add(d);
       /*	try {
       System.out.println(order.get(i+5));
       number = format.parse(order.get(i+5));
       System.out.println("Number is " + number);
       price = number.doubleValue();
       System.out.println("Price is " + price);
       number = format.parse(order.get(i+7));
       total = number.doubleValue();
       Data d = new Data(order.get(i), Integer.parseInt(order.get(i+1)), Integer.parseInt(order.get(i+2)), order.get(i+3), order.get(i+4), price, total);
       dataList.add(d);
       } catch (ParseException numExcep) {
       numExcep.printStackTrace();
       System.exit(1);
       }
       **/
     }
     //	printDataList(dataList);
   } catch (FileNotFoundException found) {
     found.printStackTrace();
     System.exit(1);
   } catch (UnsupportedEncodingException encode) {
     encode.printStackTrace();
     System.exit(1);
   } catch (IOException ioexcep) {
     ioexcep.printStackTrace();
     System.exit(1);
   }
 }
Example #14
0
  /** Sets up configuration based on params */
  private static boolean setup(Hashtable<String, String> curConf, Configuration argConf) {

    if (argConf.get("file") == null) {
      logger.fatal("Missing file parameter");
      System.exit(1);
    }

    if (argConf.get("hdfs_base_path") == null) {
      logger.fatal("Missing HDFS base path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("hdfs_temp_path") == null) {
      logger.fatal("Missing HDFS temp path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("local_temp_path") == null) {
      logger.fatal("Missing local temp path, check gestore-conf.xml");
      System.exit(1);
    }

    // Input paramaters
    curConf.put("run_id", argConf.get("run", ""));
    curConf.put("task_id", argConf.get("task", ""));
    curConf.put("file_id", argConf.get("file"));
    curConf.put("local_path", argConf.get("path", ""));
    curConf.put("type", argConf.get("type", "l2r"));
    curConf.put("timestamp_start", argConf.get("timestamp_start", "1"));
    curConf.put(
        "timestamp_stop", argConf.get("timestamp_stop", Integer.toString(Integer.MAX_VALUE)));
    curConf.put("delimiter", argConf.get("regex", "ID=.*"));
    curConf.put("taxon", argConf.get("taxon", "all"));
    curConf.put("intermediate", argConf.get("full_run", "false"));
    curConf.put("quick_add", argConf.get("quick_add", "false"));
    Boolean full_run = curConf.get("intermediate").matches("(?i).*true.*");
    curConf.put("format", argConf.get("format", "unknown"));
    curConf.put("split", argConf.get("split", "1"));
    curConf.put("copy", argConf.get("copy", "true"));

    // Constants
    curConf.put("base_path", argConf.get("hdfs_base_path"));
    curConf.put("temp_path", argConf.get("hdfs_temp_path"));
    curConf.put("local_temp_path", argConf.get("local_temp_path"));
    curConf.put("db_name_files", argConf.get("hbase_file_table"));
    curConf.put("db_name_runs", argConf.get("hbase_run_table"));
    curConf.put("db_name_updates", argConf.get("hbase_db_update_table"));

    // Timestamps
    Date currentTime = new Date();
    Date endDate = new Date(new Long(curConf.get("timestamp_stop")));
    curConf.put("timestamp_real", Long.toString(currentTime.getTime()));

    return true;
  }
Example #15
0
 private void setTick(Info info, String time) {
   int addon = 0;
   try {
     addon = Integer.parseInt(time);
   } catch (NumberFormatException e) {
     info.sendMessage(
         "Format exception.  Command should be !setTick # where # is the number of minutes till the next tick.");
   }
   tickSetter = info.getSender();
   tickTime = System.currentTimeMillis();
   OFFSET = (Utils.getRealMinutes(info) + addon) % 15;
   info.sendMessage("Tick set to " + OFFSET + " minutes off.");
 }
  /* Process one items-???.xml file.
   */
  static void processFile(File xmlFile) {
    Document doc = null;
    try {
      doc = builder.parse(xmlFile);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(3);
    } catch (SAXException e) {
      System.out.println("Parsing error on file " + xmlFile);
      System.out.println("  (not supposed to happen with supplied XML files)");
      e.printStackTrace();
      System.exit(3);
    }

    /* At this point 'doc' contains a DOM representation of an 'Items' XML
     * file. Use doc.getDocumentElement() to get the root Element. */
    System.out.println("Successfully parsed - " + xmlFile);

    /* Fill in code here (you will probably need to write auxiliary
    methods). */

    // open each CSV file (creates it if it doesn't exist)
    System.out.println("creating dat file");
    itemWriter = createCSVFile("Items.dat");
    itemCategoriesWriter = createCSVFile("ItemCategories.dat");
    bidWriter = createCSVFile("Bids.dat");

    Element itemsElem = doc.getDocumentElement();
    Element[] itemList = getElementsByTagNameNR(itemsElem, "Item");
    System.out.println("There are " + itemList.length + " <item> tags");

    for (Element curItem : itemList) {
      processItem(curItem);
    }

    // close the dat files
    try {
      itemWriter.flush();
      itemWriter.close();

      itemCategoriesWriter.flush();
      itemCategoriesWriter.close();

      bidWriter.flush();
      bidWriter.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    /** *********************************************************** */
  }
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    Scanner input = new Scanner(System.in);
    int numberOfTestCases = input.nextInt();
    ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases);
    int previousKey = -1;
    int previousValue = 0;
    int cycleNumber = 0;

    Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>();

    for (int i = 0; i < numberOfTestCases; i++) {
      int numberOfCycles = input.nextInt();
      testCases.put(numberOfCycles, 1);
      order.add(numberOfCycles);
    }

    for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) {
      int numberOfCycles;
      int initialHeight;

      if (previousKey == -1) {
        numberOfCycles = entry.getKey();
        initialHeight = entry.getValue();
      } else {
        numberOfCycles = entry.getKey() - previousKey;
        initialHeight = previousValue;
      }

      for (int i = 0; i < numberOfCycles; i++) {
        if (cycleNumber % 2 == 0) {
          initialHeight *= 2;
        } else {
          initialHeight += 1;
        }
        cycleNumber++;
      }

      entry.setValue(initialHeight);
      previousKey = entry.getKey();
      previousValue = initialHeight;
    }

    for (Integer element : order) {
      System.out.println(testCases.get(element));
    }

    long elapsed = System.currentTimeMillis() - start;
    System.out.println("time: " + elapsed);
  }
Example #18
0
 private void chkFPS() {
   if (fpsCount == 0) {
     fpsTime = System.currentTimeMillis() / 1000;
     fpsCount++;
     return;
   }
   fpsCount++;
   long time = System.currentTimeMillis() / 1000;
   if (time != fpsTime) {
     lastFPS = fpsCount;
     fpsCount = 1;
     fpsTime = time;
   }
 }
Example #19
0
  /**
   * Statically analyze a query for various properties.
   *
   * @param query the query to analyze
   * @param params parameters for the query; if necessary parameters are left out they will be
   *     listed as required variables in the analysis
   * @return a query analysis facet
   */
  public QueryAnalysis analyze(String query, Object... params) {
    if (presub) query = presub(query, params);

    long t1 = System.currentTimeMillis(), t2 = 0, t3 = 0;
    DBBroker broker = null;
    try {
      broker = db.acquireBroker();
      prepareContext(broker);
      final org.exist.source.Source source = buildQuerySource(query, params, "analyze");
      final XQuery xquery = broker.getXQueryService();
      final XQueryPool pool = xquery.getXQueryPool();
      CompiledXQuery compiledQuery = pool.borrowCompiledXQuery(broker, source);
      try {
        AnalysisXQueryContext context;
        if (compiledQuery == null) {
          context = new AnalysisXQueryContext(broker, AccessContext.INTERNAL_PREFIX_LOOKUP);
          buildXQueryStaticContext(context, false);
          buildXQueryDynamicContext(context, params, null, false);
          t2 = System.currentTimeMillis();
          compiledQuery = xquery.compile(context, source);
          t3 = System.currentTimeMillis();
        } else {
          context = (AnalysisXQueryContext) compiledQuery.getContext();
          t2 = System.currentTimeMillis();
        }
        return new QueryAnalysis(
            compiledQuery,
            Collections.unmodifiableSet(context.requiredVariables),
            Collections.unmodifiableSet(context.requiredFunctions));
      } finally {
        if (compiledQuery != null) pool.returnCompiledXQuery(source, compiledQuery);
      }
    } catch (XPathException e) {
      LOG.warn(
          "query compilation failed --  "
              + query
              + "  -- "
              + (params == null ? "" : " with params " + Arrays.asList(params))
              + (bindings.isEmpty() ? "" : " and bindings " + bindings));
      throw new DatabaseException("failed to compile query", e);
    } catch (IOException e) {
      throw new DatabaseException("unexpected exception", e);
    } catch (PermissionDeniedException e) {
      throw new DatabaseException("permission denied", e);
    } finally {
      db.releaseBroker(broker);
      STATS.update(query, t1, t2, t3, 0, System.currentTimeMillis());
    }
  }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit-pf 2.3.0
 private static boolean KawigiEdit_RunTest(
     int testNum, int[] p0, int[] p1, boolean hasAnswer, double p2) {
   System.out.print("Test " + testNum + ": [" + "{");
   for (int i = 0; p0.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p0[i]);
   }
   System.out.print("}" + "," + "{");
   for (int i = 0; p1.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p1[i]);
   }
   System.out.print("}");
   System.out.println("]");
   GreaterGame obj;
   double answer;
   obj = new GreaterGame();
   long startTime = System.currentTimeMillis();
   answer = obj.calc(p0, p1);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p2);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == answer && Math.abs(p2 - answer) <= 1e-9 * Math.max(1.0, Math.abs(p2));
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
Example #21
0
  @Before
  public void init() {
    alist.add(a1);
    alist.add(a2);
    alist.add(a3);
    alist.add(a4);
    alist.add(a5);
    alist.add(a6);
    alist.add(a7);
    alist.add(a8);
    alist.add(a9);

    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
  }
Example #22
0
 public static void main(String[] args) {
   ORB orb = null;
   orb = ORB.init(args, null);
   if (orb != null) {
     try {
       new ClientGui(orb);
     } catch (Exception e) {
       System.err.println(e);
       System.exit(-1);
     }
   } else {
     System.err.println("can't initiate orb");
     System.exit(-1);
   }
 } /*end of main*/
Example #23
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

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

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Example #24
0
 public String getTimeElapsed() {
   long time = (System.currentTimeMillis() - starttime) / 1000l;
   if (time - 60l >= 0) {
     if (time % 60 >= 10) return time / 60 + ":" + (time % 60) + "m";
     else return time / 60 + ":0" + (time % 60) + "m";
   } else return time < 10 ? "0" + time + "s" : time + "s";
 }
Example #25
0
 public String getUprate() {
   long time = System.currentTimeMillis() - starttime;
   if (time != 0) {
     long uprate = currSize * 1000 / time;
     return convertFileSize(uprate) + "/s";
   } else return "n/a";
 }
Example #26
0
  public void run() {

    // setup advertisement message
    advMsg.set_sourceAddr(TOS_UART_ADDR);

    if (reboot) {
      advMsg.set_summary_vNum(0x0);
      advMsg.set_runningVNum(0xffff);
    } else {
      advMsg.set_summary_vNum(0xffff);
      advMsg.set_runningVNum(0x0);
    }
    advMsg.set_summary_numPgsComplete((byte) numPgs);

    while (true) {
      try {
        // send an advertisement message every second
        if (printAllMsgs) System.out.print(advMsg);
        send(advMsg);
        Thread.currentThread().sleep(1000);
        if (reboot) {
          System.exit(0);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #27
0
 private static void usage() {
   System.err.println(
       "\nUsage: java EDU.purdue.cs.bloat.optimize.Main"
           + "\n            [-options] classes dir"
           + "\n"
           + "\nwhere options include:"
           + "\n    -help             print out this message"
           + "\n    -v -verbose       turn on verbose mode"
           + "\n    -debug            display a hideous amount of debug info"
           + "\n    -classpath <directories separated by colons>"
           + "\n                      list directories in which to look for classes"
           + "\n    -f                optimize files even if up-to-date"
           + "\n    -closure          recursively optimize referenced classes"
           + "\n    -relax-loading    don't report errors if a class is not found"
           + "\n    -skip <class|package.*>"
           + "\n                      skip the given class or package"
           + "\n    -only <class|package.*>"
           + "\n                      skip all but the given class or package"
           + "\n    -preserve-debug   try to preserve debug information"
           + "\n    -[no]anno         insert an annotation in the contant pool"
           + "\n    -[no]stack-alloc  try to push locals onto the operand stack"
           + "\n    -peel-loops <n|all>"
           + "\n                      peel innermost loops to enable code hoisting"
           + "\n                      (n >= 0 is the maximum loop level to peel)"
           + "\n    -[no]pre          perform partial redundency elimination"
           + "\n    -[no]dce          perform dead code elimination"
           + "\n    -diva             perform demand-driven induction variable analysis"
           + "\n    -[no]prop         perform copy and constant propagation"
           + "");
   System.exit(0);
 }
  /**
   * Sets the time in milliseconds of the last activity related to this <tt>Conference</tt> to the
   * current system time.
   */
  public void touch() {
    long now = System.currentTimeMillis();

    synchronized (this) {
      if (getLastActivityTime() < now) lastActivityTime = now;
    }
  }
Example #29
0
 /** Return the platform standard tmp dir, or null if none is standardly defined. */
 public static File getOSTmpDir() {
   // Note : default tmp dir can be obtained through :
   // System.getProperty("java.io.tmp")
   String tmp = System.getProperty("java.io.tmp");
   if (tmp == null) return null;
   else return new File(tmp);
 }
 public void windowClosing(WindowEvent e) // write file on finish
     {
   FileOutputStream out = null;
   ObjectOutputStream data = null;
   try {
     // open file for output
     out = new FileOutputStream(DB);
     data = new ObjectOutputStream(out);
     // write Person objects to file using iterator class
     Iterator<Person> itr = persons.iterator();
     while (itr.hasNext()) {
       data.writeObject((Person) itr.next());
     }
     data.flush();
     data.close();
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         objUpdate.this,
         "Error processing output file" + "\n" + ex.toString(),
         "Output Error",
         JOptionPane.ERROR_MESSAGE);
   } finally {
     System.exit(0);
   }
 }