/** Implementation of Runnable interface. DO NOT access this method directly. */
 public void run() {
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       true); // animated frames are updated by this thread so no need to repaint
   long sleepTime = delayTime;
   while (animationThread == Thread.currentThread()) {
     long currentTime = System.currentTimeMillis();
     for (int i = 0; i < stepsPerDisplay; i++) {
       doStep();
       stepCounter++;
       if (animationThread != Thread.currentThread()) {
         break; // check for stop condition
       } else {
         Thread.yield(); // give other threads a chance to run if needed
       }
     }
     org.opensourcephysics.display.GUIUtils.renderAnimatedFrames();
     // adjust the sleep time to try and achieve a constant animation rate
     // some VMs will hang if sleep time is less than 10
     sleepTime = Math.max(10, delayTime - (System.currentTimeMillis() - currentTime));
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException ie) {
     }
   }
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       false); // animated frames are updated by this thread so no need to repaint
 }
    protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }
    public synchronized void paint(Graphics g) {
      if (needToStartThread) {
        totalDrawTime = 0;
        counter = 0;
        needToStartThread = false;
        startThread(beginAngle, endAngle);
        if (firstImage == null) {
          firstImage = createImageFromComponent(component1);
        }
        if (secondImage == null) {
          secondImage = createImageFromComponent(component2);
        }
      }
      if (firstImage == null || secondImage == null) return;
      Graphics2D g2d = (Graphics2D) g;
      int ww = firstImage.getWidth();
      int hh = firstImage.getHeight();
      {
        BufferedImage currImage = null;
        int[] currPixels = null;
        int w = firstImage.getWidth();
        int offset = (int) (w * angle / 180);
        if (offset < 0) offset = 0;
        if (offset > w) offset = w;

        long beforeDraw = System.currentTimeMillis();
        g2d.drawImage(firstImage, null, 0, 0);
        g2d.drawImage(secondImage, null, w - offset, 0);
        totalDrawTime += (System.currentTimeMillis() - beforeDraw);
        counter++;
      }
    }
Example #4
0
  /** Execute the specified number of Gameboy instructions. Use '-1' to execute forever */
  public final void execute(int numInstr) {
    terminate = false;
    running = true;
    graphicsChip.startTime = System.currentTimeMillis();
    int b1, b2, b3, offset;

    long t;
    for (int r = 0; (r != numInstr) && (!terminate); r++) {
      t = System.currentTimeMillis();

      instrCount++;

      b1 = JavaBoy.unsign(addressRead(pc));
      offset = addressRead(pc + 1);
      b3 = JavaBoy.unsign(addressRead(pc + 2));
      b2 = JavaBoy.unsign((short) offset);

      // stats.addExecution(b1);
      instructionManager.execute(b1, b2, b3, offset);

      if (ieDelay != -1) {
        if (ieDelay > 0) {
          ieDelay--;
        } else {
          interruptsEnabled = true;
          ieDelay = -1;
        }
      }

      if (interruptsEnabled) {
        checkInterrupts();
      }
      cartridge.update();
      initiateInterrupts();

      if ((t - initialTime) > checkpointTime) {
        initialTime = t;
        saveCheckpointInterrupt = true;
      }

      if (saveInterrupt) {
        saveState(".stsv");
        saveInterrupt = false;
      }
      if (loadStateInterrupt) {
        loadState(".stsv");
        loadStateInterrupt = false;
      }
      if (saveCheckpointInterrupt) {
        saveState(".cksv");
        saveCheckpointInterrupt = false;
      }
      if (loadCheckpointInterrupt) {
        loadState(".cksv");
        loadCheckpointInterrupt = false;
      }
    }
    running = false;
    terminate = false;
  }
 /**
  * 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;
 }
Example #6
0
  public boolean updateState(Landscape scape) {
    // this method has an added on season change every 1/4 minute

    // first 1/4 minute:
    if ((System.currentTimeMillis() / 15000) % 2 == 0) {
      if ((this.y > scape.getHeight() / 2)
          && (this.x > scape.getWidth() / 2)) { // if this is in the southeast ish
        if (quantity < MAX_QUANTITY) {
          quantity += 2; // grow by 2
        }
      } else { // else grow by 1 each time
        if (quantity < MAX_QUANTITY) {
          quantity++;
        }
      }
    }

    // second 1/4 minute:
    else if ((System.currentTimeMillis() / 15000) % 2 != 0) {
      if ((this.y < (scape.getHeight() / 2))
          && (this.x < scape.getWidth() / 2)) { // if this is in the northwest ish
        if (quantity < MAX_QUANTITY) {
          quantity += 2; // grows by 2
        }
      } else { // else grow by 1 each time
        if (quantity < MAX_QUANTITY) {
          quantity++;
        }
      }
    }

    // System.out.print(this.quantity+",");
    return true; // it can be assumed that this always returns true since peas never die
  }
  public static void checkSanity() {
    long t = System.currentTimeMillis();

    try {
      r.lock();
      final int fileLength = (int) getRecords().length();
      assert fileLength % RECORD_SIZE == 0;
      int recordCount = fileLength / RECORD_SIZE;

      IntArrayList usedAttributeRecordIds = new IntArrayList();
      IntArrayList validAttributeIds = new IntArrayList();
      for (int id = 2; id < recordCount; id++) {
        int flags = getFlags(id);
        LOG.assertTrue(
            (flags & ~ALL_VALID_FLAGS) == 0,
            "Invalid flags: 0x" + Integer.toHexString(flags) + ", id: " + id);
        if ((flags & FREE_RECORD_FLAG) != 0) {
          LOG.assertTrue(
              DbConnection.myFreeRecords.contains(id),
              "Record, marked free, not in free list: " + id);
        } else {
          LOG.assertTrue(
              !DbConnection.myFreeRecords.contains(id),
              "Record, not marked free, in free list: " + id);
          checkRecordSanity(id, recordCount, usedAttributeRecordIds, validAttributeIds);
        }
      }
    } finally {
      r.unlock();
    }

    t = System.currentTimeMillis() - t;
    LOG.info("Sanity check took " + t + " ms");
  }
Example #8
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
Example #9
0
 public static void release(int x, int y, int button) {
   int buttonModifiers = getButtonModifiers(button);
   Component target = getTarget();
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_RELEASED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
   isPressed = false;
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_CLICKED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
 }
  public void run() {
    // Create and add sprites to the
    // sprite manager
    spriteManager = new SpriteManager(new BackgroundImage(this, backGroundImage));
    // Create 15 sprites from 6 gif
    // files.
    for (int cnt = 0; cnt < 15; cnt++) {
      Point position =
          spriteManager.getEmptyPosition(
              new Dimension(gifImages[0].getWidth(this), gifImages[0].getHeight(this)));
      spriteManager.addSprite(makeSprite(position, cnt % 6));
    } // end for loop

    // Loop, sleep, and update sprite
    // positions once each 83
    // milliseconds
    long time = System.currentTimeMillis();
    while (true) { // infinite loop
      spriteManager.update();
      repaint();
      try {
        time += animationDelay;
        Thread.sleep(Math.max(0, time - System.currentTimeMillis()));
      } catch (InterruptedException e) {
        System.out.println(e);
      } // end catch
    } // end while loop
  } // end run method
  public final void runMovement() {
    if (!isShowing()) {
      return;
    }
    final int distance;
    final Rectangle bounds = getBounds();
    if (myAnchor == ToolWindowAnchor.LEFT || myAnchor == ToolWindowAnchor.RIGHT) {
      distance = bounds.width;
    } else {
      distance = bounds.height;
    }
    int count = 0;
    myOffset = 0;
    paintImmediately(
        0, 0, getWidth(), getHeight()); // first paint requires more time than next ones
    final long startTime = System.currentTimeMillis();

    while (true) {
      paintImmediately(0, 0, getWidth(), getHeight());
      final long timeSpent = System.currentTimeMillis() - startTime;
      count++;
      if (timeSpent >= myDesiredTimeToComplete) break;
      final double onePaintTime = (double) timeSpent / count;
      int iterations = (int) ((myDesiredTimeToComplete - timeSpent) / onePaintTime);
      iterations = Math.max(1, iterations);
      myOffset += (distance - myOffset) / iterations;
    }
  }
  private JComponent createLabelsPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(0, 2, 10, 1));

    // Creates a StyledLabel to warn up so that we don't include class loading time into the
    // performance test.
    // This is the same for all three cases.
    new JLabel("Bold Italic Underlined");

    long start = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
      JLabel label = new JLabel("Bold Italic Underlined");
      panel.add(label);
    }
    panel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(
                new PartialLineBorder(Color.gray, 1, true),
                " JLabel (Plain) Examples - use " + (System.currentTimeMillis() - start) + " ms ",
                TitledBorder.CENTER,
                TitledBorder.CENTER,
                null,
                Color.RED),
            BorderFactory.createEmptyBorder(6, 4, 4, 4)));
    return panel;
  }
Example #13
0
  public void run() {

    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;
    int frames = 0;
    int updates = 0;
    //		setFocusable(true);
    requestFocus();

    while (running) {
      long now = System.nanoTime();
      delta += (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        update();
        updates++;
        delta--;
      }
      // Renderiza tudo na tela
      render();
      // Calcula FPS
      frames++;

      if ((System.currentTimeMillis() - timer) > 1000) {
        timer += 1000;
        // T�tulo do jogo
        frame.setTitle(title + "  |  " + updates + " ups / " + frames + " fps ");
        updates = 0;
        frames = 0;
      }
    }
    stop();
  }
Example #14
0
 void addToRoiManager(ImagePlus imp) {
   if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager())
     IJ.error("run(\"Add to Manager\") may not work in batch mode macros");
   Frame frame = WindowManager.getFrame("ROI Manager");
   if (frame == null) IJ.run("ROI Manager...");
   if (imp == null) return;
   Roi roi = imp.getRoi();
   if (roi == null) return;
   frame = WindowManager.getFrame("ROI Manager");
   if (frame == null || !(frame instanceof RoiManager)) IJ.error("ROI Manager not found");
   RoiManager rm = (RoiManager) frame;
   boolean altDown = IJ.altKeyDown();
   IJ.setKeyUp(IJ.ALL_KEYS);
   if (altDown && !IJ.macroRunning()) IJ.setKeyDown(KeyEvent.VK_SHIFT);
   if (roi.getState() == Roi.CONSTRUCTING) { // wait (up to 2 sec.) until ROI finished
     long start = System.currentTimeMillis();
     while (true) {
       IJ.wait(10);
       if (roi.getState() != Roi.CONSTRUCTING) break;
       if ((System.currentTimeMillis() - start) > 2000) {
         IJ.beep();
         IJ.error("Add to Manager", "Selection is not complete");
         return;
       }
     }
   }
   rm.runCommand("add");
   IJ.setKeyUp(IJ.ALL_KEYS);
 }
Example #15
0
  public void make(File source, DataSet header, DataSet master) throws Exception {
    this.header = header;
    this.master = master;

    if (header == null || master == null) throw new Exception("Dataset is empty");

    long t = System.currentTimeMillis();

    InputStream inp = new FileInputStream(source);
    Workbook oldBook = WorkbookFactory.create(inp);
    Sheet oldSheet = oldBook.getSheetAt(0);

    Workbook newBook = new HSSFWorkbook();
    Sheet newSheet = newBook.createSheet(oldSheet.getSheetName());

    init(newBook);
    process(oldSheet, newSheet);

    File target = File.createTempFile("libra", ".xls");
    target.deleteOnExit();
    FileOutputStream fileOut = new FileOutputStream(target);

    newBook.write(fileOut);
    fileOut.close();
    oldBook.close();
    inp.close();

    Desktop.getDesktop().open(target);

    System.out.println(System.currentTimeMillis() - t);
  }
  private void tryToInitialize(int counter) {
    boolean existsCompatibleBrowser = getComponent() != null && isCompatible();
    synchronized (this) {
      initialized = existsCompatibleBrowser;
    }
    log.info(System.currentTimeMillis() + " initialized map: " + initialized);

    if (isInitialized()) {
      log.fine(System.currentTimeMillis() + " compatible, further initializing map");
      initializeAfterLoading();
      initializeBrowserInteraction();
      initializeCallbackListener();
      checkLocalhostResolution();
      checkCallback();
    } else {
      if (counter++ < 50) {
        log.info(System.currentTimeMillis() + " WAITING " + counter * 100 + " milliseconds");
        try {
          Thread.sleep(counter * 100);
        } catch (InterruptedException e) {
          // intentionally left empty
        }

        tryToInitialize(counter);
      }
    }
  }
  @Override
  public void onPaint(Graphics2D graphics2D) {
    this.runtimeMillis = System.currentTimeMillis() - this.startTimeMillis;
    graphics2D.setColor(new Color(0, 0, 100, 120));
    graphics2D.fillRect(25, 240, 350, 82);

    graphics2D.setColor(Color.GREEN);
    graphics2D.fillRect(25, 240, 3 * this.expTracker.getPercentageToNextLevel(Skill.HERBLORE), 9);

    graphics2D.setColor(Color.WHITE);
    graphics2D.drawRect(25, 240, 350, 9);
    graphics2D.drawRect(25, 240, 350, 82);

    int cleanedPerHour =
        (int)
            (3600000.0
                / (double) (System.currentTimeMillis() - this.startTimeMillis)
                * (double) this.herbsCleaned);
    String profitsPerHour =
        String.valueOf(cleanedPerHour * this.profitPerClean)
            .replaceAll("(\\d)(?=(\\d{3})+$)", "$1,");

    graphics2D.setFont(new Font("Monospaced", 0, 12));
    graphics2D.drawString(
        "Herbs cleaned: " + this.herbsCleaned + " | (" + cleanedPerHour + ")", 28, 260);
    graphics2D.drawString("Current State: " + this.textualState, 28, 270);
    graphics2D.drawString("Time running: " + Core.formatElapsedTime(this.runtimeMillis), 28, 280);
    graphics2D.drawString(
        "XP Gained: "
            + this.expTracker.getExperienceGained(Skill.HERBLORE)
            + (" | (" + this.expTracker.getLevelsGained(Skill.HERBLORE) + ")"),
        28,
        290);
    graphics2D.drawString(
        "XP/hr: "
            + this.expTracker.gainedPerHour(Skill.HERBLORE)
            + " | Profit/hr: "
            + profitsPerHour,
        28,
        300);
    graphics2D.drawString(
        "Time till next level: "
            + Core.formatElapsedTime(this.expTracker.timeUntilNextLevel(Skill.HERBLORE)),
        28,
        310);

    graphics2D.drawLine(
        (int) this.getMouse().getPosition().getX(),
        (int) this.getMouse().getPosition().getY() + 10,
        (int) this.getMouse().getPosition().getX(),
        (int) this.getMouse().getPosition().getY() - 10);
    graphics2D.drawLine(
        (int) this.getMouse().getPosition().getX() + 10,
        (int) this.getMouse().getPosition().getY(),
        (int) this.getMouse().getPosition().getX() - 10,
        (int) this.getMouse().getPosition().getY());

    graphics2D.setColor(Color.RED);
    graphics2D.drawString("by Chicken Wing      v1.0", 70, 320);
  }
Example #18
0
 private void repaintPanels(Iterable<TilePanel> panels) {
   long start = System.currentTimeMillis();
   for (TilePanel panel : panels) {
     game.notifyGameObservers(panel.getTile().getPosition());
   }
   long stop = System.currentTimeMillis();
   Logger.getLogger(BoardPanel.class).debug("Repaint time: " + (stop - start) / 1000.0);
 }
Example #19
0
 /**
  * Wait until a key is pressed within the time indicated This method reads only keys that are used
  * to edit text (letters, digits, space, enter, etc.).
  *
  * @param timeout Maximum time to wait in milliseconds. If is 0 wait forever
  * @return The key pressed or NO_CHAR ((char) 0) if no key was pressed in the timeout
  */
 public static char waitChar(long timeout) {
   // while( getChar()!=NO_CHAR ) ;
   if (timeout < 0) timeout = 0;
   if (timeout > 0) timeout += System.currentTimeMillis();
   char c = 0;
   while ((c = getChar()) == NO_CHAR && (timeout <= 0 || System.currentTimeMillis() < timeout)) ;
   return c;
 }
Example #20
0
 /**
  * Wait until any key is pressed within the time indicated This method also checks action keys
  * (Cursor arrows, Home, etc.).
  *
  * @param timeout Maximum time to wait in milliseconds. If is 0 wait forever
  * @return The key pressed or a negative value if no key was pressed (NO_KEY or MOUSE_CLICK).
  * @see #getKeyPressedUntil(long)
  * @see #getKeyPressed()
  * @see #getMouseEvent()
  */
 public static int waitKeyPressed(long timeout) {
   if (timeout < 0) timeout = 0;
   if (timeout > 0) timeout += System.currentTimeMillis();
   int k;
   while ((k = frame.getKeyPressed()) == NO_KEY
       && (timeout <= 0 || System.currentTimeMillis() < timeout)) ;
   return k;
 }
Example #21
0
 /**
  * Creates a new unique ID for retrieving panels in the card layout.
  *
  * @return A new unique ID
  */
 public static String createNewID() {
   String name = "gdms" + System.currentTimeMillis();
   while (name.equals(lastUID)) {
     name = "" + System.currentTimeMillis();
   }
   lastUID = name;
   return name;
 }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
Example #23
0
 private void measureThrougput(long size) {
   if ((System.currentTimeMillis() - startTimeThroughput) > oneSecond) {
     control.throughput.setText("" + (throughput / 1024) + " KB/sec");
     startTimeThroughput = System.currentTimeMillis();
     throughput = 0;
   } else {
     throughput += size;
   }
 }
Example #24
0
  public void shoot() {

    if (System.currentTimeMillis() - lastFire < Constants.ShotInterval) {
      return;
    }
    lastFire = System.currentTimeMillis();
    Shot shot = new Shot(this, "sprites/FB.gif", ship.getX() + 17, ship.getY() - 5, 1);
    Objects.add(shot);
    fireball.song.play();
  }
    @Override
    protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
      ProgressMonitorList.instance().add(pm); // NESTMOD
      saveTime = 0L;
      Product product = null;
      try {
        // free cache	// NESTMOD
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        executeStartTime = Calendar.getInstance().getTime();
        long t0 = System.currentTimeMillis();
        Operator operator = null;
        if (targetProduct.getProductReader() instanceof OperatorProductReader) {
          final OperatorProductReader opReader =
              (OperatorProductReader) targetProduct.getProductReader();
          if (opReader.getOperatorContext().getOperator() instanceof Output) {
            operator = opReader.getOperatorContext().getOperator();
          }
        }
        if (operator == null) {
          WriteOp writeOp =
              new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
          writeOp.setDeleteOutputOnFailure(true);
          writeOp.setWriteEntireTileRows(true);
          writeOp.setClearCacheAfterRowWrite(false);
          operator = writeOp;
        }
        final OperatorExecutor executor = OperatorExecutor.create(operator);
        executor.execute(SubProgressMonitor.create(pm, 95));

        saveTime = System.currentTimeMillis() - t0;
        File targetFile = model.getProductFile();
        if (model.isOpenInAppSelected() && targetFile.exists()) {
          product = ProductIO.readProduct(targetFile);
          if (product == null) {
            product = targetProduct; // todo - check - this cannot be ok!!! (nf)
          }
          pm.worked(5);
        }
      } finally {
        // free cache
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        pm.done();
        ProgressMonitorList.instance().remove(pm); // NESTMOD
        if (product != targetProduct) {
          targetProduct.dispose();
        }
      }
      return product;
    }
Example #26
0
  /**
   * This method is the access point to the planning procedure. Initially, it adds all variables
   * from axioms to the set of found vars, then does the linear planning. If lp does not solve the
   * problem and there are subtasks, goal-driven recursive planning with backtracking is invoked.
   * Planning is performed until no new variables are introduced into the algorithm.
   */
  public EvaluationAlgorithm invokePlaning(Problem problem, boolean _computeAll) {
    long startTime = System.currentTimeMillis();

    computeAll = _computeAll;
    EvaluationAlgorithm algorithm = new EvaluationAlgorithm();

    PlanningContext context = problem.getCurrentContext();

    // add all axioms at the beginning of an algorithm
    Collection<Var> flattened = new HashSet<Var>();
    for (Iterator<Rel> axiomIter = problem.getAxioms().iterator(); axiomIter.hasNext(); ) {
      Rel rel = axiomIter.next();

      unfoldVarsToSet(rel.getOutputs(), flattened);

      // do not overwrite values of variables that come via args of compute() or as inputs of
      // independent subtasks
      if (!problem.getAssumptions().containsAll(flattened)
      // do not overwrite values of already known variables.
      // typically this is the case when a value of a variable
      // is given in a scheme via a properties window
      //                    && !problem.getKnownVars().containsAll( flattened )
      ) {
        algorithm.addRel(rel);
      }
      axiomIter.remove();
      context.getKnownVars().addAll(flattened);
      flattened.clear();
    }

    context.getFoundVars().addAll(context.getKnownVars());

    // remove all known vars with no relations
    for (Iterator<Var> varIter = context.getKnownVars().iterator(); varIter.hasNext(); ) {
      if (varIter.next().getRels().isEmpty()) {
        varIter.remove();
      }
    }

    // start planning
    if (problem.getRelsWithSubtasks().isEmpty()
        && linearForwardSearch(context, algorithm, computeAll)) {
      if (isLinearLoggingOn()) logger.debug("Problem solved without subtasks");
    } else if (!problem.getRelsWithSubtasks().isEmpty() && subtaskPlanning(problem, algorithm)) {
      if (isLinearLoggingOn()) logger.debug("Problem solved with subtasks");
    } else if (!computeAll) {
      if (isLinearLoggingOn()) logger.debug("Problem not solved");
    }

    if (!nested) {
      logger.info("Planning time: " + (System.currentTimeMillis() - startTime) + "ms.");
    }
    return algorithm;
  }
    @Test
    public void testGetContentLengthFTP() {
        long contLength = ParsingUtils.getContentLength(TestUtils.AVAILABLE_FTP_URL);
        assertTrue("Error retrieving content length: " + contLength, contLength > 0);

        long start_time = System.currentTimeMillis();
        assertTrue(ParsingUtils.getContentLength(TestUtils.UNAVAILABLE_FTP_URL) == -1);
        long end_time = System.currentTimeMillis();
        assertTrue(end_time - start_time < Globals.CONNECT_TIMEOUT + 1000);
        assertTrue(end_time - start_time < Globals.CONNECT_TIMEOUT + 1000);
    }
Example #28
0
 /**
  * With segmented selections, ignore first mouse up and finalize when user double-clicks,
  * control-clicks or clicks in start box.
  */
 protected void handleMouseUp(int sx, int sy) {
   if (state == MOVING) {
     state = NORMAL;
     return;
   }
   if (state == MOVING_HANDLE) {
     cachedMask = null; // mask is no longer valid
     state = NORMAL;
     updateClipRect();
     oldX = x;
     oldY = y;
     oldWidth = width;
     oldHeight = height;
     return;
   }
   if (state != CONSTRUCTING) return;
   if (IJ.spaceBarDown()) // is user scrolling image?
   return;
   boolean samePoint = false;
   if (xpf != null)
     samePoint = (xpf[nPoints - 2] == xpf[nPoints - 1] && ypf[nPoints - 2] == ypf[nPoints - 1]);
   else samePoint = (xp[nPoints - 2] == xp[nPoints - 1] && yp[nPoints - 2] == yp[nPoints - 1]);
   Rectangle biggerStartBox =
       new Rectangle(ic.screenXD(startXD) - 5, ic.screenYD(startYD) - 5, 10, 10);
   if (nPoints > 2
       && (biggerStartBox.contains(sx, sy)
           || (ic.offScreenXD(sx) == startXD && ic.offScreenYD(sy) == startYD)
           || (samePoint && (System.currentTimeMillis() - mouseUpTime) <= 500))) {
     nPoints--;
     addOffset();
     finishPolygon();
     return;
   } else if (!samePoint) {
     mouseUpTime = System.currentTimeMillis();
     if (type == ANGLE && nPoints == 3) {
       addOffset();
       finishPolygon();
       return;
     }
     // add point to polygon
     if (xpf != null) {
       xpf[nPoints] = xpf[nPoints - 1];
       ypf[nPoints] = ypf[nPoints - 1];
       nPoints++;
       if (nPoints == xpf.length) enlargeArrays();
     } else {
       xp[nPoints] = xp[nPoints - 1];
       yp[nPoints] = yp[nPoints - 1];
       nPoints++;
       if (nPoints == xp.length) enlargeArrays();
     }
     // if (lineWidth>1) fitSpline();
   }
 }
Example #29
0
  public void testQuickSort() {
    long before, after;
    System.out.println("Testing quick sort.");
    for (int i = 0; i < 5; i++) {
      before = System.currentTimeMillis();
      sort.quicksort(lists[i]);
      after = System.currentTimeMillis();

      System.out.println(after - before);
    }
  }
Example #30
0
  public final String readCommand(byte[] b)
      throws IOException, InterruptedException, MessagingNetworkException {
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;
      boolean d = false;
      for (; ; ) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int by = is.read();
        if (by == -1) throw new IOException("unexpected EOF");
        if (by == 10 && d) break;
        d = (by == 13);
        if (ofs < b.length) {
          b[ofs++] = (byte) by;
        }
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }
      if (b[ofs - 1] == 13) --ofs;

      String line = new String(b, 0, ofs, "ASCII");

      if (StringUtil.startsWith(line, "MSG")) {
        StringTokenizer st = new StringTokenizer(line);
        String len_s = null;
        while (st.hasMoreTokens()) {
          len_s = st.nextToken();
        }
        if (len_s == null) throw new AssertException("len_s is null");
        int len;
        try {
          len = Integer.parseInt(len_s);
        } catch (NumberFormatException ex) {
          ServerConnection.throwProtocolViolated("MSG length must be int");
          len = 0;
        }
        String msg = readMSG(len);
        line = line + "\r\n" + msg;
      }
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line);
      return line;
    }
  }