Example #1
1
  static void serTest(Map s, int size) throws Exception {
    if (!(s instanceof Serializable)) return;
    System.out.print("Serialize              : ");

    for (int i = 0; i < size; i++) {
      s.put(new Integer(i), Boolean.TRUE);
    }

    long startTime = System.currentTimeMillis();

    FileOutputStream fs = new FileOutputStream("MapCheck.dat");
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs));
    out.writeObject(s);
    out.close();

    FileInputStream is = new FileInputStream("MapCheck.dat");
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is));
    Map m = (Map) in.readObject();

    long endTime = System.currentTimeMillis();
    long time = endTime - startTime;

    System.out.print(time + "ms");

    if (s instanceof IdentityHashMap) return;
    reallyAssert(s.equals(m));
  }
Example #2
1
  public List<Shred> getShredsWithTagsInTagsList(List<String> tags) {
    StringBuilder shredId =
        new StringBuilder("SELECT s.Id FROM Shred s, TagsForShred tfs, Tag t  ");
    shredId.append("WHERE tfs.ShredId = s.id AND tfs.TagId = t.Id AND ");
    shredId.append("(");
    for (int i = 0; i < tags.size() - 1; i++) {
      shredId.append(" t.Label='").append(tags.get(i)).append("' OR ");
    }
    shredId.append(" t.Label='").append(tags.get(tags.size() - 1)).append("' )");
    shredId.append(" Group By ( s.id) HAVING (Count(s.id) >= ?)");

    String selectShreds =
        "SELECT "
            + ShredderDAOImpl.SHREDDER_SQL
            + ", "
            + SHRED_SQL
            + " FROM Shred s,"
            + " Rating r, Shredder sr, GuitarForShredder gs, "
            + " EquiptmentForShredder es WHERE r.ShredId = s.id AND "
            + "gs.ShredderId = sr.id AND es.ShredderId = sr.id AND s.Id IN ("
            + shredId.toString()
            + ") AND s.Owner = sr.id LIMIT "
            + NO_SHREDS_IN_RESULT_SET;

    long t1 = System.currentTimeMillis();
    List<Shred> res =
        getShredsFromSQLString(selectShreds, new Object[] {tags.size()}, new ShredMapper());
    System.out.println("Shreds by tags: " + (System.currentTimeMillis() - t1));
    logger.info("Shreds by tags: " + (System.currentTimeMillis() - t1));
    return res;
  }
Example #3
1
  public static void main(String[] args) {
    long st, dt, et;
    String plaintext1 = "Yellow and Black Border Collies";
    String keysPath = "keys.txt";
    RSA rsa;

    try {
      Scanner in = new Scanner(new FileReader(keysPath));
      BigInteger n = new BigInteger(in.nextLine().substring(3));
      BigInteger e = new BigInteger(in.nextLine().substring(3));
      BigInteger d = new BigInteger(in.nextLine().substring(3));
      in.close();

      rsa = new RSA(n, e, d);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    }

    //		rsa = new RSA(8, 1024);

    st = System.currentTimeMillis();
    String ciphertext = rsa.encrypt(plaintext1);
    dt = System.currentTimeMillis();
    String plaintext2 = rsa.decrypt(ciphertext);
    et = System.currentTimeMillis();

    System.out.println("enc time: " + (dt - st));
    System.out.println("dec time: " + (et - dt));
    System.out.println(plaintext2);

    // rsa.saveKeys(keysPath);
  }
Example #4
1
 private void loadSystemInformation() {
   lblOperatingSystem.setText(System.getProperty("os.name"));
   lblOperatingSystemVersion.setText(System.getProperty("os.version"));
   lblJavaVersion.setText(System.getProperty("java.version"));
   lblUser.setText(System.getProperty("user.name"));
   lblSystemResolution.setText(getResolutionString(Util.getScreenResolution()));
 }
Example #5
1
  /**
   * Gets shred created by shredder that is fanee of shredders that are fanee of shredder with id
   * shredderId! Limit result set is 20 shreds.
   *
   * <p>SQL string: SELECT sr.Id AS sr_id, sr.Username,sr.BirthDate, sr.Email, sr.Password,
   * sr.Description AS sr_description,sr.Country, sr.TimeCreated AS sr_timeCreated, sr.ProfileImage,
   * sr.ExperiencePoints, sr.ShredderLevel, gs.guitar, es.equiptment, s.Id as s_id,s.Description as
   * s_description, s.Owner as s_owner, s.TimeCreated as s_timeCreated, VideoPath, ShredType,
   * s.thumbnailpath, r.currentRating, r.numberOfRaters FROM Shred s,Rating r, Shredder sr,
   * GuitarForShredder gs, EquiptmentForShredder es WHERE r.ShredId = s.id AND gs.ShredderId = sr.id
   * AND es.ShredderId = sr.id AND s.Owner IN (SELECT distinct faneeid FROM Fan WHERE FanerId IN
   * (SELECT FaneeId FROM Fan WHERE FanerId = 4078) AND faneeid != 4078 ORDER BY faneeid DESC);
   */
  public List<Shred> getShredsFromShreddersShredderMightKnow(int shredderId, int page) {
    String shreddersMightKnow =
        "SELECT distinct faneeid FROM Fan WHERE FanerId IN "
            + "(SELECT FaneeId FROM Fan WHERE FanerId = ?)  AND faneeid !=  ? ORDER BY faneeid DESC";
    String sql =
        "SELECT "
            + ShredderDAOImpl.SHREDDER_SQL
            + ", "
            + SHRED_SQL
            + " FROM Shred s,"
            + " Rating r, Shredder sr, GuitarForShredder gs, "
            + " EquiptmentForShredder es  WHERE r.ShredId = s.id AND "
            + "gs.ShredderId = sr.id AND es.ShredderId = sr.id AND s.Owner IN ("
            + shreddersMightKnow
            + ") LIMIT "
            + NO_SHREDS_IN_RESULT_SET
            + " OFFSET "
            + page * 21; // Simply because it fits the view. Should be a parameter though..

    long t1 = System.currentTimeMillis();
    List<Shred> res =
        getShredsFromSQLString(sql, new Object[] {shredderId, shredderId}, new ShredMapper());
    System.out.println("Shreds shredder might know: " + (System.currentTimeMillis() - t1));
    logger.info("Shreds shredder might know: " + (System.currentTimeMillis() - t1));
    return res;
  }
  public static void main(String args[]) {

    long start = System.currentTimeMillis();

    PrintWriter outputStream = null;
    try {
      BufferedReader inputStream = new BufferedReader(new FileReader("myBinaryIntegers.dat"));
      outputStream = new PrintWriter(new FileOutputStream("myBinaryIntegers.txt"));

      System.out.println("Loading binary integers...");

      String line = inputStream.readLine();

      while (line != null) {
        // System.out.println(line);
        outputStream.print(line);
        line = inputStream.readLine();
      }

      outputStream.close();
      inputStream.close();
      System.out.println("Done with read in binary integers!");
    } catch (FileNotFoundException e) {
      System.out.println("File cannot be found when open for read.");
    } catch (IOException e) {
      System.out.println("Error reading.");
    }

    long end = System.currentTimeMillis();
    System.out.println("Took: " + ((end - start)) + "ms");
  }
Example #7
1
  public static void main(String[] args) {
    long time = System.currentTimeMillis();

    ArrayList<String> numerals = new ArrayList<String>();
    Tools.readStringListFromFile("completed/euler0054_poker.txt", numerals);

    Hand h1 = new Hand();
    Hand h2 = new Hand();
    int c1 = 0;
    int c2 = 0;

    for (String numeral : numerals) {

      String[] cards = numeral.split(" ");

      for (int i = 0; i < 5; i++) {
        h1.cards[i].setCard(cards[i]);
      }
      for (int i = 5; i < 10; i++) {
        h2.cards[i - 5].setCard(cards[i]);
      }
      h1.EvalHand();
      h2.EvalHand();
      if (isFirstHandBest(h1, h2)) {
        c1++;
      } else {
        c2++;
      }
    }
    System.out.println(c1);
    System.out.println("time: " + (System.currentTimeMillis() - time) + "ms");
  }
Example #8
1
 @Test
 public void verifySignedJar() throws Exception {
   String classpath = System.getProperty("java.class.path");
   String[] entries = classpath.split(System.getProperty("path.separator"));
   String signedJarFile = null;
   for (String entry : entries) {
     if (entry.contains("bcprov")) {
       signedJarFile = entry;
     }
   }
   assertThat(signedJarFile).isNotNull();
   java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile));
   jarFile.getManifest();
   Enumeration<JarEntry> jarEntries = jarFile.entries();
   while (jarEntries.hasMoreElements()) {
     JarEntry jarEntry = jarEntries.nextElement();
     InputStream inputStream = jarFile.getInputStream(jarEntry);
     inputStream.skip(Long.MAX_VALUE);
     inputStream.close();
     if (!jarEntry.getName().startsWith("META-INF")
         && !jarEntry.isDirectory()
         && !jarEntry.getName().endsWith("TigerDigest.class")) {
       assertThat(jarEntry.getCertificates()).isNotNull();
     }
   }
   jarFile.close();
 }
  protected void closeWebDriver(Thread thread) {
    ALL_WEB_DRIVERS_THREADS.remove(thread);
    WebDriver webdriver = THREAD_WEB_DRIVER.remove(thread.getId());

    if (webdriver != null && !holdBrowserOpen) {
      log.info("Close webdriver: " + thread.getId() + " -> " + webdriver);

      long start = System.currentTimeMillis();

      Thread t = new Thread(new CloseBrowser(webdriver));
      t.setDaemon(true);
      t.start();

      try {
        t.join(closeBrowserTimeoutMs);
      } catch (InterruptedException e) {
        log.log(FINE, "Failed to close webdriver in " + closeBrowserTimeoutMs + " milliseconds", e);
      }

      long duration = System.currentTimeMillis() - start;
      if (duration >= closeBrowserTimeoutMs) {
        log.severe("Failed to close webdriver in " + closeBrowserTimeoutMs + " milliseconds");
      } else if (duration > 200) {
        log.info("Closed webdriver in " + duration + " ms");
      } else {
        log.fine("Closed webdriver in " + duration + " ms");
      }
    }
  }
  @Test
  public void testContinueOnSomeDbDirectoriesMissing() throws Exception {
    File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());

    try {
      assertTrue(targetDir1.mkdirs());
      assertTrue(targetDir2.mkdirs());

      if (!targetDir1.setWritable(false, false)) {
        System.err.println(
            "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable");
        return;
      }

      RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI);
      rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath());

      try {
        rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE);
      } catch (Exception e) {
        e.printStackTrace();
        fail("Backend initialization failed even though some paths were available");
      }
    } finally {
      //noinspection ResultOfMethodCallIgnored
      targetDir1.setWritable(true, false);
      FileUtils.deleteDirectory(targetDir1);
      FileUtils.deleteDirectory(targetDir2);
    }
  }
 /**
  * invoke as: <CODE>
  * java -cp &lt;classpath&gt; parallel.distributed.PDBTExecSingleCltWrkInitSrv [workers_port(7890)] [client_port(7891)]
  * </CODE>
  *
  * @param args String[]
  */
 public static void main(String[] args) {
   int wport = 7890; // default port
   int cport = 7891;
   if (args.length > 0) {
     try {
       wport = Integer.parseInt(args[0]);
     } catch (Exception e) {
       e.printStackTrace();
       usage();
       System.exit(-1);
     }
     if (args.length > 1) {
       try {
         cport = Integer.parseInt(args[1]);
       } catch (Exception e) {
         e.printStackTrace();
         usage();
         System.exit(-1);
       }
     }
   }
   PDBTExecSingleCltWrkInitSrv server = new PDBTExecSingleCltWrkInitSrv(wport, cport);
   try {
     server.run();
   } catch (Exception e) {
     e.printStackTrace();
     System.err.println("Server exits due to exception.");
   }
 }
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;

    try {
      serverSocket = new ServerSocket(10008);
      System.out.println("Enroll: 130050131071");
      System.out.println("Connection Socket Created");
      try {
        while (true) {
          System.out.println("Waiting for Connection");
          new EchoServer2(serverSocket.accept());
        }
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port: 10008.");
      System.exit(1);
    } finally {
      try {
        serverSocket.close();
      } catch (IOException e) {
        System.err.println("Could not close port: 10008.");
        System.exit(1);
      }
    }
  }
  public void onDrawFrame(GL10 gl) {
    GLGameState state = null;

    synchronized (stateChanged) {
      state = this.state;
    }

    if (state == GLGameState.Running) {
      float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
      startTime = System.nanoTime();

      screen.update(deltaTime);
      screen.present(deltaTime);
    }

    if (state == GLGameState.Paused) {
      screen.pause();
      synchronized (stateChanged) {
        this.state = GLGameState.Idle;
        stateChanged.notifyAll();
      }
    }

    if (state == GLGameState.Finished) {
      screen.pause();
      screen.dispose();
      synchronized (stateChanged) {
        this.state = GLGameState.Idle;
        stateChanged.notifyAll();
      }
    }
  }
  @Test
  public void testTime() {
    int connections = 5;
    List<Integer> opIds = new ArrayList<>();
    // Build a router
    for (int i = 0; i < connections; i++) {
      opIds.add(i);
    }
    Router r = RouterFactory.buildRouterFor(opIds, false);

    // Try router
    // Try router
    int iter = 10000000;
    long start = System.nanoTime();
    for (int i = 0; i < iter; i++) {
      int opId = r.route();
    }
    long stop = System.nanoTime();
    long totalMillis = (stop - start) / 1000000;
    System.out.println(
        "Time to route: "
            + iter
            + " to "
            + connections
            + " downstreams is: "
            + totalMillis
            + " ms");
    assert (true);
  }
Example #15
0
  // Declare parameters
  @Parameters(name = "{index}: {0}")
  public static Iterable<Object[]> data() {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    File currentDir = new File(System.getProperty("user.dir"));
    String rootPath = new File(currentDir, "src/test/resources/models/sbml-test-cases").getPath();
    // Get all the SBML files
    LinkedList<String> sbmlPaths = walk(rootPath);

    int N = sbmlPaths.size();
    System.out.println("Number of SBML test cases: " + N);
    Object[][] resources = new String[N][1];
    for (int k = 0; k < N; k++) {
      String path = sbmlPaths.get(k);
      // create the resource
      String[] items = path.split("/");
      int mindex = -1;
      for (int i = 0; i < items.length; i++) {
        if (items[i].equals("models")) {
          mindex = i;
          break;
        }
      }
      String resource = StringUtils.join(ArrayUtils.subarray(items, mindex, items.length), "/");
      // System.out.println(resource);
      resources[k][0] = "/" + resource; // String.format("/models/BiGG/%s", fname);
    }
    return Arrays.asList(resources);
  }
 public void initGame() {
   String cfgname = null;
   if (isApplet()) {
     cfgname = getParameter("configfile");
   } else {
     JFileChooser chooser = new JFileChooser();
     chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
     chooser.setDialogTitle("Choose a config file");
     int returnVal = chooser.showOpenDialog(this);
     if (returnVal == JFileChooser.APPROVE_OPTION) {
       cfgname = chooser.getSelectedFile().getAbsolutePath();
     } else {
       System.exit(0);
     }
     // XXX read this as resource!
     // cfgname = "mygeneratedgame.appconfig";
   }
   gamecfg = new AppConfig("Game parameters", this, cfgname);
   gamecfg.loadFromFile();
   gamecfg.defineFields("gp_", "", "", "");
   gamecfg.saveToObject();
   initMotionPars();
   // unpause and copy settingswhen config window is closed
   gamecfg.setListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           start();
           requestGameFocus();
           initMotionPars();
         }
       });
   defineMedia("simplegeneratedgame.tbl");
   setFrameRate(35, 1);
 }
  @Override
  public boolean onTouchEvent(MotionEvent event) {

    if (!isEnable) return true;
    int y = (int) event.getY();
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        isScrolling = true;
        downY = (int) event.getY();
        downTime = System.currentTimeMillis();
        break;
      case MotionEvent.ACTION_MOVE:
        actionMove(y - downY);
        onSelectListener();
        break;
      case MotionEvent.ACTION_UP:

        // 移动距离的绝对值
        int move = (y - downY);
        move = move > 0 ? move : move * (-1);
        // 判断段时间移动的距离
        if (System.currentTimeMillis() - downTime < goonTime && move > goonDistence) {
          goonMove(y - downY);
        } else {
          actionUp(y - downY);
        }
        noEmpty();
        isScrolling = false;
        break;
      default:
        break;
    }
    return true;
  }
Example #18
0
  @SuppressWarnings("deprecation")
  @Before
  public void setUp() throws Exception {
    System.setProperty("java.security.policy", "polis.policy");
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }
    try {
      Registry registry = LocateRegistry.getRegistry("localhost");
      articoloFacade = (IArticoloMenuFacade) registry.lookup("ArticoloFacade");
      userFacade = (IUserFacade) registry.lookup("UserFacade");
    } catch (Exception e) {
      System.err.println("Exception to obtain the reference to the remote object: " + e);
      fail("Exception");
    }

    user = userFacade.login(Ruolo.TEST, "test");

    ingrediente = new Ingrediente();
    ingrediente.setNome("INGREDIENTE TEST");
    ingrediente.setScadenza(new Date(109, 4, 31));
    ingrediente.setVariante(true);

    ingrediente = articoloFacade.inserisciIngrediente(user, ingrediente);
  }
  public static void app_launched(Context context, int days, int launches) {

    SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, 0);

    // Check if app was already rated
    if (prefs.getBoolean("rated", false)) {
      return;
    }

    SharedPreferences.Editor editor = prefs.edit();

    // Increment launch counter
    long launch_count = prefs.getLong("launch_count", 0) + 1;
    editor.putLong("launch_count", launch_count);

    // Get date of first launch
    Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
    if (date_firstLaunch == 0) {
      date_firstLaunch = System.currentTimeMillis();
      editor.putLong("date_firstlaunch", date_firstLaunch);
    }

    // Wait at least n days before opening
    if (launch_count >= launches) {
      if (System.currentTimeMillis() >= date_firstLaunch + (days * 24 * 60 * 60 * 1000)) {
        showRateDialog(context, editor);
      }
    }

    editor.commit();
  }
Example #20
0
  /** @return an array of buildlets that together build a CIMTool project */
  public Buildlet[] createBuildlets() {
    Buildlet[] defaultBuildlets =
        new Buildlet[] {
          new SchemaBuildlet(),
          new ProfileChecker(),
          new XSDBuildlet(),
          new TransformBuildlet(null, "xml"),
          new TransformBuildlet("html", "html"),
          new TextBuildlet("sql", "sql"),
          new TextBuildlet("jpa", "java"),
          new TextBuildlet("scala", "scala"),
          new SimpleOWLBuildlet("RDF/XML", "simple-flat-owl", false),
          new SimpleOWLBuildlet("RDF/XML-ABBREV", "simple-owl", false),
          new LegacyRDFSBuildlet("RDF/XML", "legacy-rdfs", false),
          new SimpleOWLBuildlet("RDF/XML", "simple-flat-owl-augmented", true),
          new SimpleOWLBuildlet("RDF/XML-ABBREV", "simple-owl-augmented", true),
          new LegacyRDFSBuildlet("RDF/XML", "legacy-rdfs-augmented", true),
          new CopyBuildlet("TURTLE", "ttl"),
          new ValidationBuildlet(),
          new SplitValidationBuildlet(),
          new IncrementalValidationBuildlet(),
        };

    ProfileBuildlet[] registered = ProfileBuildletRegistry.INSTANCE.getBuildlets();
    if (registered.length > 0) {
      Buildlet[] combined = new Buildlet[defaultBuildlets.length + registered.length];
      System.arraycopy(defaultBuildlets, 0, combined, 0, defaultBuildlets.length);
      System.arraycopy(registered, 0, combined, defaultBuildlets.length, registered.length);
      return combined;
    } else return defaultBuildlets;
  }
Example #21
0
  /** Wait at most msecs millisconds for a permit. * */
  public boolean attempt(long msecs) throws InterruptedException {
    if (Thread.interrupted()) throw new InterruptedException();

    synchronized (this) {
      if (permits_ > 0) {
        --permits_;
        return true;
      } else if (msecs <= 0) return false;
      else {
        try {
          long startTime = System.currentTimeMillis();
          long waitTime = msecs;

          for (; ; ) {
            wait(waitTime);
            if (permits_ > 0) {
              --permits_;
              return true;
            } else {
              waitTime = msecs - (System.currentTimeMillis() - startTime);
              if (waitTime <= 0) return false;
            }
          }
        } catch (InterruptedException ex) {
          notify();
          throw ex;
        }
      }
    }
  }
  @SuppressWarnings("unchecked")
  @RequestMapping(
      value = "/postfriendlabledelete",
      method = RequestMethod.POST,
      produces = "text/plain;charset=UTF-8")
  @ResponseBody
  public static String put(HttpServletRequest request) throws Exception {
    String data = request.getParameter("info");
    String content = AESUtils.decrypt4AES(data, AESUtils.key);
    LogRecord.info("SolrFriendLableDelete类postfriendlabledelete接口接收的参数:" + content);
    long start = System.currentTimeMillis();
    String middletimes = "";
    String bug_one = "";
    String ccid = "";
    String ffid = "";
    String fflid = "";
    List<Map<String, FriendLabel>> lists = Transformation.friendlableLol(content);
    for (Map<String, FriendLabel> cardMap : lists) {
      for (String key : cardMap.keySet()) {
        switch (key) {
          case "cid":
            ccid = cardMap.get(key) + "";
            break;
          case "fid":
            ffid = cardMap.get(key) + "";
            break;
          case "flid":
            fflid = cardMap.get(key) + "";
            break;
          default:
            break;
        }
      }
    }
    try {
      SolrUpdateFriendLabel.solrqueryresult(fflid, ffid, ccid);
    } catch (Exception e) {
      bug_one = e.getMessage();
      LogRecord.info("Exception :" + e + ",Msg :" + e.getMessage());
    }

    long end = System.currentTimeMillis();
    middletimes = (end - start) + "";

    // 计算当前的时间,格式为"yyyy/MM/dd HH:mm:ss"可以任意修改格式
    Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // 可以方便地修改日期格式
    String messageid = dateFormat.format(now);

    ResultDelete result = new ResultDelete(true, messageid, "删除成功!", "000000", middletimes);
    ResultDelete resultfalse = new ResultDelete(true, messageid, "删除失败!", "060002", middletimes);

    String cardjsonsucess = AESUtils.encrypt4AES(JSON.toJSONString(result), AESUtils.key);
    String cardjsonfalse = AESUtils.encrypt4AES(JSON.toJSONString(resultfalse), AESUtils.key);
    String str = bug_one.length() > 0 ? cardjsonfalse : cardjsonsucess;
    LogRecord.info(
        "SolrFriendLableDelete类postfriendlabledelete接口返回的值:"
            + AESUtils.decrypt4AES(str, AESUtils.key));
    return str;
  }
Example #23
0
  public static BufferedImage blur(BufferedImage srcImage) {
    int w = srcImage.getWidth();
    int h = srcImage.getHeight();

    int[] src = srcImage.getRGB(0, 0, w, h, null, 0, w);
    int[] dst = new int[src.length];

    System.out.println("Array size is " + src.length);
    System.out.println("Threshold is " + sThreshold);

    int processors = Runtime.getRuntime().availableProcessors();
    System.out.println(
        Integer.toString(processors)
            + " processor"
            + (processors != 1 ? "s are " : " is ")
            + "available");

    ForkBlur fb = new ForkBlur(src, 0, src.length, dst);

    ForkJoinPool pool = new ForkJoinPool();

    long startTime = System.currentTimeMillis();
    pool.invoke(fb);
    long endTime = System.currentTimeMillis();

    System.out.println("Image blur took " + (endTime - startTime) + " milliseconds.");

    BufferedImage dstImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    dstImage.setRGB(0, 0, w, h, dst, 0, w);

    return dstImage;
  }
  private void waitUntilServerIsRunning(boolean reconnect)
      throws IOException, InterruptedException, TimeoutException {

    Thread.sleep(500); // this value is taken from implementation of CLI "reload"

    if (reconnect) {
      client.reconnect(timeoutInSeconds);
    }

    long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutInSeconds);
    while (System.currentTimeMillis() < endTime) {
      try {
        if (isServerRunning()) {
          break;
        }
      } catch (Throwable ignored) {
        // server is probably down, will retry
      }

      Thread.sleep(200); // this value is completely arbitrary
    }

    boolean running = false;
    try {
      running = isServerRunning();
    } catch (Throwable ignored) {
      // server probably down
    }
    if (!running) {
      throw new TimeoutException("Waiting for server timed out");
    }
  }
 @Test
 public void lengthExceedLimit() {
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           "realmId",
           StringUtils.repeat("clientId", 100),
           "userId",
           "127.0.0.1",
           "error"));
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           StringUtils.repeat("realmId", 100),
           "clientId",
           "userId",
           "127.0.0.1",
           "error"));
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           "realmId",
           "clientId",
           StringUtils.repeat("userId", 100),
           "127.0.0.1",
           "error"));
 }
 /**
  * creates a server socket listening on the port specified in the parameter of the constructor,
  * and waits for a single incoming client connection which it handles by invoking the <CODE>
  * addNewClientConnection(s)</CODE> method of the enclosing server, and then the thread exits.
  */
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(_port);
     System.out.println("Srv: Now Accepting Single Client Connection");
     // while (true) {
     try {
       Socket s = ss.accept();
       System.out.println("Srv: Client Added to the Network");
       addNewClientConnection(s);
       System.out.println("Srv: finished adding client connection");
     } catch (Exception e) {
       // e.printStackTrace();
       System.err.println("Client Connection failed, exiting...");
       System.exit(-1);
     }
     // }
   } catch (IOException e) {
     // e.printStackTrace();
     utils.Messenger.getInstance()
         .msg(
             "PDBTExecSingleCltWrkInitSrv.C2Thread.run(): "
                 + "Failed to create Server Socket, Server exiting.",
             0);
     System.exit(-1);
   }
 }
Example #27
0
  private void blur(Bitmap bg, View view) {
    long startMs = System.currentTimeMillis();

    float radius = 20;
    Bitmap overlay =
        Bitmap.createBitmap(
            view.getMeasuredWidth() / scaleFactor,
            view.getMeasuredHeight() / scaleFactor,
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(overlay);
    canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
    // scale参数为float类型
    canvas.scale(1.0f / scaleFactor, 1.0f / scaleFactor);
    // 开启双缓冲
    Paint paint = new Paint();
    paint.setFlags(Paint.FILTER_BITMAP_FLAG);

    canvas.drawBitmap(bg, 0, 0, paint);
    // Bitmap result = blurBitmap(overlay, 2);
    Bitmap result = blurBitmapStack(overlay, 2);
    view.setBackground(new BitmapDrawable(result));
    long endMs = System.currentTimeMillis();
    String time = (endMs - startMs) + "ms";
    Toast.makeText(this, time, Toast.LENGTH_SHORT).show();
  }
 private static void testJXTable(JXTable table, int iterations) {
   for (int i = 0; i < iterations; i++) {
     long time = System.currentTimeMillis();
     table.toggleSortOrder(0);
     System.err.println(System.currentTimeMillis() - time + " ms");
   }
 }
Example #29
0
  /* input defaults to reading the Fakefile, cwd to "." */
  public void make(InputStream input, File cwd, String[] args) {
    try {
      Parser parser = parse(input, cwd);

      // filter out variable definitions
      int firstArg = 0;
      while (firstArg < args.length && args[firstArg].indexOf('=') >= 0) firstArg++;

      List<String> list = null;
      if (args.length > firstArg) {
        list = new ArrayList<String>();
        for (int i = firstArg; i < args.length; i++) list.add(args[i]);
      }
      Rule all = parser.parseRules(list);

      for (int i = 0; i < firstArg; i++) {
        int equal = args[i].indexOf('=');
        parser.setVariable(args[i].substring(0, equal), args[i].substring(equal + 1));
      }

      for (Rule rule : all.getDependenciesRecursively())
        if (rule.getVarBool("rebuild")) rule.clean(false);

      String parallel = all.getVar("parallel");
      if (parallel != null) all.makeParallel(Integer.parseInt(parallel));
      else all.make();
    } catch (FakeException e) {
      System.err.println(e);
      System.exit(1);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Example #30
0
 @Override
 @After
 public void tearDown() throws Exception {
   System.gc();
   super.tearDown();
   System.gc();
 }