private void sendEntityBodyToClient(
      DataOutputStream socketOutputStream, HtmlResponse htmlResponse, boolean isChunked)
      throws IOException {

    byte[] content = htmlResponse.getEntityBody();

    if (!isChunked) {
      try {
        socketOutputStream.write(content, 0, content.length);
        socketOutputStream.flush();
      } catch (IOException e) {
        System.out.println("Writing the answer caused an error" + e.toString());
      }
    } else {

      int currentIndexStart = 0;
      int currentIndexEnd = Math.min(CHUNCKED_BYTES - 1, content.length - 1);
      int lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;

      while (currentIndexStart < content.length - 1) {
        socketOutputStream.writeBytes(Integer.toHexString(lengthOfBytesSent) + CRLF);
        socketOutputStream.write(content, currentIndexStart, lengthOfBytesSent);
        socketOutputStream.writeBytes(CRLF);
        socketOutputStream.flush();

        currentIndexStart = currentIndexEnd + 1;
        currentIndexEnd = Math.min(currentIndexStart + CHUNCKED_BYTES - 1, content.length - 1);
        lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;
      }

      socketOutputStream.writeBytes("0" + CRLF);
      socketOutputStream.writeBytes(CRLF);
      socketOutputStream.flush();
    }
  }
 private long calculateExpiry(
     URLConnection urlConnection,
     long request_time,
     UrlConnectionExpiryCalculator urlConnectionExpiryCalculator) {
   if ("no-cache".equals(urlConnection.getHeaderField("Pragma"))) {
     return 0L;
   }
   final String cacheControl = urlConnection.getHeaderField("Cache-Control");
   if (cacheControl != null) {
     if (cacheControl.indexOf("no-cache") != -1) {
       return 0L;
     }
     final int max_age = getMaxAge(cacheControl);
     if (-1 != max_age) {
       final long response_time = System.currentTimeMillis();
       final long apparent_age = Math.max(0, response_time - urlConnection.getDate());
       final long corrected_received_age =
           Math.max(apparent_age, urlConnection.getHeaderFieldInt("Age", 0) * 1000L);
       final long response_delay = response_time - request_time;
       final long corrected_initial_age = corrected_received_age + response_delay;
       final long creation_time = response_time - corrected_initial_age;
       return max_age * 1000L + creation_time;
     }
   }
   final long explicitExpiry = urlConnection.getHeaderFieldDate("Expires", -1L);
   if (explicitExpiry != -1L) {
     return explicitExpiry;
   }
   return urlConnectionExpiryCalculator == null
       ? 0L
       : urlConnectionExpiryCalculator.calculateExpiry(urlConnection);
 }
 /**
  * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>,
  * <code>nohref</code> Attribute for the specified figure and ellipse.
  *
  * @return Returns true, if the circle is inside of the image bounds.
  */
 private boolean writeCircleAttributes(IXMLElement elem, SVGFigure f, Ellipse2D.Double ellipse) {
     AffineTransform t = TRANSFORM.getClone(f);
     if (t == null) {
         t = drawingTransform;
     } else {
         t.preConcatenate(drawingTransform);
     }
     
     if ((t.getType() &
             (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) ==
             t.getType() &&
             ellipse.width == ellipse.height
             ) {
         
         Point2D.Double start = new Point2D.Double(ellipse.x, ellipse.y);
         Point2D.Double end = new Point2D.Double(ellipse.x + ellipse.width, ellipse.y + ellipse.height);
         t.transform(start, start);
         t.transform(end, end);
         ellipse.x = Math.min(start.x, end.x);
         ellipse.y = Math.min(start.y, end.y);
         ellipse.width = Math.abs(start.x - end.x);
         ellipse.height = Math.abs(start.y - end.y);
         
         elem.setAttribute("shape", "circle");
         elem.setAttribute("coords",
                 (int) (ellipse.x + ellipse.width / 2d)+","+
                 (int) (ellipse.y + ellipse.height / 2d)+","+
                 (int) (ellipse.width / 2d)
                 );
         writeHrefAttribute(elem, f);
         return bounds.intersects(ellipse.getBounds());
     } else {
         return writePolyAttributes(elem, f, (Shape) ellipse);
     }
 }
Example #4
0
  // createPageString -
  // Create list of pages for search results
  private String createPageString(
      int numberOfItems, int itemsPerPage, int currentPage, String baseUrl) {
    StringBuffer pageString = new StringBuffer();

    // Calculate the total number of pages
    int totalPages = 1;
    if (numberOfItems > itemsPerPage) {
      double pages = Math.ceil(numberOfItems / (double) itemsPerPage);
      totalPages = (int) Math.ceil(pages);
    }

    //
    if (totalPages > 1) {
      for (int i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
          pageString.append(i);
        } else {
          pageString.append("<a href=\"" + baseUrl + i + "\" title=\"" + i + "\">" + i + "</a>");
        }

        if (i != totalPages) pageString.append(" ");
      }
    } else {
      pageString.append("1");
    }

    return pageString.toString();
  }
Example #5
0
 protected void drawImageMosaic(Graphics2D g2) {
   // Break the image up into tiles. Draw each
   //   tile with its own transparency, allowing
   //   the background to show through to varying
   //   degrees.
   int side = 36;
   int width = mImage.getWidth();
   int height = mImage.getHeight();
   for (int y = 0; y < height; y += side) {
     for (int x = 0; x < width; x += side) {
       // Calculate an appropriate transparency value.
       float xBias = (float) x / (float) width;
       float yBias = (float) y / (float) height;
       float alpha = 1.0f - Math.abs(xBias - yBias);
       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
       // Draw the subimage.
       int w = Math.min(side, width - x);
       int h = Math.min(side, height - y);
       BufferedImage tile = mImage.getSubimage(x, y, w, h);
       g2.drawImage(tile, x, y, null);
     }
   }
   // Reset the composite.
   g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
 }
 /**
  * Write the given text string in the current font, centered on (x, y) and rotated by the
  * specified number of degrees
  *
  * @param x the center x-coordinate of the text
  * @param y the center y-coordinate of the text
  * @param s the text
  * @param degrees is the number of degrees to rotate counterclockwise
  */
 public static void text(double x, double y, String s, double degrees) {
   double xs = scaleX(x);
   double ys = scaleY(y);
   offscreen.rotate(Math.toRadians(-degrees), xs, ys);
   text(x, y, s);
   offscreen.rotate(Math.toRadians(+degrees), xs, ys);
 }
Example #7
0
  public void mouseClicked(MouseEvent e) {
    int x;
    int y;

    e.consume();

    if (mouseEventsEnabled) {

      x = Math.round(e.getX() / scale);
      y = Math.round(e.getY() / scale);

      // allow for the canvas margin
      y -= margin;

      // System.out.println("Mouse Click: (" + x + ", " + y + ")");

      if (e.getClickCount() < 2) {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }
      } else {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }

        editSelected();
        parentFTAFrame.updateFrame();
      }

      if (focusEventsEnabled) {
        // tell the main Canvas to point to this coordinate
        parentFTAFrame.setCanvasFocus(x, y);
      }
    }
  }
Example #8
0
 public int rate() {
   int score = 0;
   int cur = 1;
   for (int i = 0; i < properties.values.size(); i++) {
     score += 10000 - Math.min(10000, Math.abs((1 << i) - properties.values.get(i)));
   }
   return score;
 }
 public void run() {
   while (running) {
     if (!paused) {
       if (mode == 0) {
         for (double i = 0; i < 3.14f; i = i + 0.1f) {
           for (int j = 0; j < 12; j++) {
             double osc = Math.sin(i) * 127;
             int value = (int) osc;
             MIDILight(j, value);
           }
           delay(30);
         }
         for (double i = 3.14f; i >= 0; i = i - 0.1f) {
           for (int j = 0; j < 12; j++) {
             double osc = Math.sin(i) * 127;
             int value = (int) osc;
             MIDILight(j, value);
           }
           delay(30);
         }
       } else if (mode == 1) {
         for (int j = 0; j < 12; j++) {
           MIDILight(j, 127);
         }
         mode = 1000;
       } else if (mode == 2) {
         for (int j = 0; j < 12; j++) {
           MIDILight(j, 0);
         }
         mode = 1000;
       } else if (mode == 3) {
         int controller = (int) random(12);
         int randomValue = (int) random(127);
         MIDILight(controller, randomValue);
         delay(30);
       } else if (mode == 4) {
         for (int i = 0; i < 64; i++) {
           for (int j = 0; j < 12; j++) {
             MIDILight(j, i * 2);
           }
           delay(20);
         }
         for (int i = 63; i >= 0; i--) {
           for (int j = 0; j < 12; j++) {
             MIDILight(j, i * 2);
           }
           delay(20);
         }
       } else {
         delay(10);
         // FIX THIS. WITHOUT THIS THE CPU USE GOES THROUGH THE ROOF. NEED A WAY
         // TO SLEEP THIS THREAD WHEN IT'S NOT IN USE.
       }
     }
   }
   System.out.println(id + " thread is done!");
 }
 public void nudge(int i) {
   x[i] += (double) rand.nextInt(1000) / 8756;
   y[i] += (double) rand.nextInt(1000) / 5432;
   int tmpScale = (int) (Math.abs(Math.sin(x[i])) * 10);
   scale[i] = (double) tmpScale / 10;
   int nudgeX = (int) (((double) getWidth() / 2) * .8);
   int nudgeY = (int) (((double) getHeight() / 2) * .60);
   xh[i] = (int) (Math.sin(x[i]) * nudgeX) + nudgeX;
   yh[i] = (int) (Math.sin(y[i]) * nudgeY) + nudgeY;
 }
Example #11
0
  /**
   * Draw picture (gif, jpg, or png) centered on (x, y).
   *
   * @param x the center x-coordinate of the image
   * @param y the center y-coordinate of the image
   * @param s the name of the image/picture, e.g., "ball.gif"
   * @throws RuntimeException if the image is corrupt
   */
  public static void picture(double x, double y, String s) {
    Image image = getImage(s);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");

    offscreen.drawImage(
        image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    draw();
  }
Example #12
0
 FoundItem getFoundItem(Node n, String text) {
   String s = n.getNodeValue();
   if (s == null) s = n.getNodeName();
   String string;
   if (text != null) {
     int index = s.indexOf(text);
     int left = Math.max(0, index - 5);
     int right = Math.min(s.length(), index + text.length() + 20);
     string = s.substring(left, right);
   } else string = s;
   TreeNode tn = jtree.getTreeNode(n);
   TreePath tp = getTreePath(tn);
   return new FoundItem(string, tp);
 }
Example #13
0
  /* move the ball */
  public void move(ArrayList movingObjects, int objectCounter) {
    // EFFECT OF GRAVITY
    gravityEffect(movingObjects);

    // MOVE
    pos_x += Math.round(x_speed);
    pos_y += Math.round(y_speed);

    // IS BALL OUT OF BOUNDS?
    isOut();

    // HAS BALL COLLIDED WITH ANYTHING?
    objectCollision(movingObjects);
  }
Example #14
0
  private void loadHint(TTGlyph a_glyph, EContourPoint a_point, int a_index) {
    double x = a_point.getX();
    double y = a_point.getY();

    XHint[] hints = a_point.getHint();

    for (int i = 0; i < hints.length; i++) {
      EHint hint = (EHint) hints[i];
      double xHint = hint.getX();
      double yHint = hint.getY();

      if (x == xHint && y == yHint) {
        continue;
      } // if

      double xDelta = xHint - x;
      double yDelta = yHint - y;
      int instruction = TTGlyph.DELTAP1;
      double deltaStep = ((double) Engine.getEm()) / hint.getPpem() / 8;
      int xShift = (int) Math.round(xDelta / deltaStep);
      int yShift = (int) Math.round(yDelta / deltaStep);

      if (xShift == 0 && yShift == 0) {
        continue;
      } // if

      a_glyph.addInstruction(TTGlyph.PUSHB000);
      a_glyph.addInstruction((int) hint.getPpem());
      a_glyph.addInstruction(TTGlyph.SDB);

      if (xShift != 0) {
        a_glyph.addInstruction(TTGlyph.SVTCA1);
        a_glyph.addInstruction(TTGlyph.PUSHB010);
        a_glyph.addInstruction(TTGlyph.toDeltaArg(0, xShift));
        a_glyph.addInstruction(a_index);
        a_glyph.addInstruction(1);
        a_glyph.addInstruction(TTGlyph.DELTAP1);
      } // if

      if (yShift != 0) {
        a_glyph.addInstruction(TTGlyph.SVTCA0);
        a_glyph.addInstruction(TTGlyph.PUSHB010);
        a_glyph.addInstruction(TTGlyph.toDeltaArg(0, yShift));
        a_glyph.addInstruction(a_index);
        a_glyph.addInstruction(1);
        a_glyph.addInstruction(TTGlyph.DELTAP1);
      } // if
    } // for i
  }
Example #15
0
  public String createUID() {
    Long num;
    String uid;

    uid = "";
    num = new Date().getTime();
    while (num > 0) {
      uid += UIDMap[(int) (num % 62)];
      num /= 62;
    }

    uid += Math.round(Math.random() * 9.0);

    return uid;
  }
Example #16
0
  /**
   * Draw picture (gif, jpg, or png) centered on (x, y), rotated given number of degrees
   *
   * @param x the center x-coordinate of the image
   * @param y the center y-coordinate of the image
   * @param s the name of the image/picture, e.g., "ball.gif"
   * @param degrees is the number of degrees to rotate counterclockwise
   * @throws IllegalArgumentException if the image is corrupt
   */
  public static void picture(double x, double y, String s, double degrees) {
    Image image = getImage(s);
    double xs = scaleX(x);
    double ys = scaleY(y);
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt");

    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    offscreen.drawImage(
        image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), null);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);

    draw();
  }
Example #17
0
  /** Setzt alle Spielparameter zurück und verteilt die Spieler entlang der Main-Ebene */
  public void restartGame() {
    for (int c = 1; c < player.length; c++) {
      if (player[c] != null) {
        player[c].x = (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]);
        player[c].y = 0;
        player[c].health = 100;
        player[c].jumpheigth = 200;
        player[c].speed = 5;
        player[c].sperrzeit = 40;
        player[c].freezeControls = false;
        gamerunner.neu = false;
        gamerunner.schonneu = true;
        player[c].amstartwarten = 42;
        player[c].perkzählerjump = -1;
        player[c].perkzählerrun = -1;
        player[c].perkzählershoot = -1;
        player[c].boomRight = 0;
        player[c].boomUp = 0;
        player[c].boomLeft = 0;
        gamerunner.wellenModus.wAnzeige = -1;
        gamerunner.wellenModus.wNeu = false;
        gamerunner.wellenModus.nNeu = false;
        gamerunner.storyModus.amanfang = true;
        gamerunner.wellenModus.amanfang = true;
      } // end of if
    } // end of for

    for (int c = 0; c < gamerunner.shot.length; c++) {
      gamerunner.shot[c] = null;
      DamageLogig.shot[c] = null;
    } // end of for
    DamageLogig.counter = 0;
  }
Example #18
0
  public void LevelContinue() {
    short i;
    int dx = 1;
    int random;

    try {
      int blocksize = game.getBlocksize();
      int[] ghosty = game.getGhosty();
      int[] ghostx = game.getGhostx();
      int nrofghosts = game.getNrofghosts();

      for (i = 0; i < nrofghosts; i++) {
        ghosty[i] = 4 * blocksize;
        ghostx[i] = 4 * blocksize;
        ghostdy[i] = 0;
        ghostdx[i] = dx;
        dx = -dx;
        random = (int) (Math.random() * (currentspeed + 1));
        if (random > currentspeed) random = currentspeed;
        ghostspeed[i] = validspeeds[random];
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #19
0
  /* -------------------------------------------------------------*/
  private void gravityEffect(ArrayList movingObjects) {
    // find effect of gravity on this objects from all other objects
    for (int i = 0; i < movingObjects.size(); i++) {
      // reset variables
      double add_vx = 0.0;
      double add_vy = 0.0;

      SpaceObject object = (SpaceObject) movingObjects.get(i);

      if (object.getObjCount() != objectNum
          && // ignore yourself (distance = 0!)
          !object.isBullet()
          && // ignore bullets
          !object.isSpaceShip()) // ignore spaceships
      {

        // find distance vector between planet and ball
        int x = pos_x - object.getXPos();
        int y = pos_y - object.getYPos();

        double distance = Math.sqrt(x * x + y * y);

        // find effect of planet on velocity
        double add_vec = (SpaceObject.G * k * object.getMass() * ballMass) / (distance * distance);

        add_vx = -(x / distance) * add_vec;
        add_vy = -(y / distance) * add_vec;

        // add objects speeds onto spaceship speed (clip speed if too large)
        x_speed += add_vx;
        y_speed += add_vy;
      }
    }
  }
Example #20
0
  /* -------------------------------------------------------------*/
  private void objectCollision(ArrayList movingObjects) {
    for (int i = 0; i < movingObjects.size(); i++) {
      // make sure not testing if collided with yourself :P
      if (((SpaceObject) movingObjects.get(i)).getObjCount() != objectNum) {
        SpaceObject object = (SpaceObject) movingObjects.get(i);

        // find distance vector between two objects
        int x = pos_x - object.getXPos();
        int y = pos_y - object.getYPos();

        double distance = Math.sqrt(x * x + y * y);

        // has it collided with the object?
        if (distance < (radius + object.getRadius())) {
          // has it collided with a BULLET (or MISSILE)?
          if (object.isBullet()) {
            // do nothing
          }
          // is it another SPACESHIP? (INSTANT DEATH)
          else if (object.isSpaceShip()) {
            // do nothing
          }
          // collided with anything else (e.g PLANET): (INSTANT DEATH)
          else {
            collision.play();
            kill(movingObjects); // object has died
          }
        }
      }
    } // end for loop
  }
Example #21
0
  /** @param args the command line arguments */
  public static void main(String[] args) {

    try {
      int randomNum = (int) ((Math.random() * 100) + 1);
      Socket server = new Socket("127.0.0.1", 8888);
      BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream()));
      PrintWriter output = new PrintWriter(server.getOutputStream(), true);
      String leggi;
      int total = 0;
      output.println(randomNum);
      while ((leggi = input.readLine()) != null) {
        System.out.println("Valore letto: " + leggi);
        total += Integer.parseInt(leggi);
      }
      System.out.println("Somma dei valori ricevuti dal Server: " + total);
      if (total % 2 == 0) {
        System.out.println("PARI");
      } else {
        System.out.println("DISPARI");
      }

    } catch (UnknownHostException ex) {
      System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage());
    } catch (IOException ex) {
      System.out.println(ex);
    }
  }
  public WebCustomRequest map(FilterableRequestSpecification requestSpec, FilterContext ctx) {
    try {
      URL url = new URL(ctx.getCompleteRequestPath());
      String method = String.valueOf(ctx.getRequestMethod());

      WebCustomRequest request = new WebCustomRequest();
      request.setName(method + " to " + url.toString());
      request.setUrl(url.toString());
      request.setMethod(method);
      request.setResource("0");
      request.setSnapshot(
          String.format("t%d.inf", (long) (System.currentTimeMillis() % Math.pow(10, 10))));
      request.setMode(url.getProtocol());
      request.setBody((String) requestSpec.getBody());

      request.getBeforeFunctions().add(new WebRequestSaveParam());

      for (Header header : requestSpec.getHeaders()) {
        request.getBeforeFunctions().add(headerMapper.map(header));
      }

      return request;
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }
Example #23
0
 /**
  * Create a note (sine wave) of the given frequency (Hz), for the given duration (seconds) scaled
  * to the given volume (amplitude).
  */
 public static double[] note(double hz, double duration, double amplitude) {
   int N = (int) (StdAudio.SAMPLE_RATE * duration);
   double[] a = new double[N + 1];
   for (int i = 0; i <= N; i++)
     a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
   return a;
 }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
  /**
   * @param replica
   * @param externalizable
   * @param tcpReplicatorBuilder
   * @param maxEntrySizeBytes used to check that the last entry will fit into the buffer, it can not
   *     be smaller than the size of and entry, if it is set smaller the buffer will over flow, it
   *     can be larger then the entry, but setting it too large reduces the workable space in the
   *     buffer.
   * @throws IOException
   */
  TcpReplicator(
      @NotNull final Replica replica,
      @NotNull final EntryExternalizable externalizable,
      @NotNull final TcpReplicatorBuilder tcpReplicatorBuilder,
      final int maxEntrySizeBytes)
      throws IOException {

    super("TcpSocketReplicator-" + replica.identifier(), tcpReplicatorBuilder, maxEntrySizeBytes);

    serverInetSocketAddress = tcpReplicatorBuilder.serverInetSocketAddress();

    heartBeatInterval = tcpReplicatorBuilder.heartBeatInterval(MILLISECONDS);

    long throttleBucketInterval = tcpReplicatorBuilder.throttleBucketInterval(MILLISECONDS);
    selectorTimeout = Math.min(heartBeatInterval, throttleBucketInterval);

    packetSize = tcpReplicatorBuilder.packetSize();
    endpoints = tcpReplicatorBuilder.endpoints();

    this.replica = replica;
    this.localIdentifier = replica.identifier();
    this.maxEntrySizeBytes = maxEntrySizeBytes;
    this.externalizable = externalizable;

    start();
  }
Example #26
0
  /**
   * 返回想要的随机数,Nub代表随机数的位数 比如 Nub为3,则返回的字符串可能为 254
   *
   * @param Nub
   * @return
   */
  public static String getRandomNub(int Nub) {

    String num = "";
    for (int i = 0; i < Nub; i++) {
      num += String.valueOf((int) (10 * Math.random()));
    }
    return num;
  }
Example #27
0
  // ------------------------------------------------------------------
  // the UserCanvas constructor
  UserCanvas(
      ForcesMaster f,
      int p,
      int m,
      int pM,
      String w,
      String an,
      String ac,
      String cS,
      ProblemCanvas v) {

    problemNo = p;
    maxTriesEachForce = m;
    problemMode = pM;
    cgiScript = cS;
    problemCanvas = v;
    forcesMaster = f;
    weightIn = w;
    angleIn = an;
    accelerationIn = ac;
    problemSelector = new ProblemSelector(problemNo, angleIn, weightIn, accelerationIn);
    problemCanvas.setProblemSelectorHandle(problemSelector);

    numForces = problemSelector.getNumForces();
    matchForceComps = problemSelector.getMatchForceComps();
    numEquations = problemSelector.getNumEquations();
    units = problemSelector.getUnits();
    scale = problemSelector.getScale();
    // if (!weightIn.equals("none")) {scale = 18 * scale /(double)(Integer.parseInt(weightIn));}
    forceTolerance = (int) Math.round(scale * userTolerance);
    resultsSpacingStrings = problemSelector.getResultsSpacingStrings();
    blinkerStrings = problemSelector.getBlinkerStrings();
    messageStrings = problemSelector.getMessageStrings();
    forceNames = problemSelector.getForceNames();
    truAnsX = problemSelector.getTruAnsX();
    truAnsY = problemSelector.getTruAnsY();
    tailPosX = problemSelector.getTailPosX();
    tailPosY = problemSelector.getTailPosY();
    cosSin = problemSelector.getCosSin();
    truHdsX = problemSelector.getTruHdsX();
    truHdsY = problemSelector.getTruHdsY();
    cost = cosSin[0];
    sint = cosSin[1];

    // initialize the force variables
    maxForceNumber = numForces - 1;
    mouseUpsString = "";
    for (int n = 0; n <= numForces; n++) {
      mouseUpsString += "0";
    }

    ifBrowserPaint = false;

    // initialize to the "see data" message
    ifDataMessage = true;
    forceNumber = -1;
    fInit = mUp = mDown = mDrag = false;
  }
  /**
   * Read block from file.
   *
   * @param file - File to read.
   * @param off - Marker position in file to start read from if {@code -1} read last blockSz bytes.
   * @param blockSz - Maximum number of chars to read.
   * @param lastModified - File last modification time.
   * @return Read file block.
   * @throws IOException In case of error.
   */
  public static VisorFileBlock readBlock(File file, long off, int blockSz, long lastModified)
      throws IOException {
    RandomAccessFile raf = null;

    try {
      long fSz = file.length();
      long fLastModified = file.lastModified();

      long pos = off >= 0 ? off : Math.max(fSz - blockSz, 0);

      // Try read more that file length.
      if (fLastModified == lastModified && fSz != 0 && pos >= fSz)
        throw new IOException(
            "Trying to read file block with wrong offset: " + pos + " while file size: " + fSz);

      if (fSz == 0)
        return new VisorFileBlock(file.getPath(), pos, fLastModified, 0, false, EMPTY_FILE_BUF);
      else {
        int toRead = Math.min(blockSz, (int) (fSz - pos));

        byte[] buf = new byte[toRead];

        raf = new RandomAccessFile(file, "r");

        raf.seek(pos);

        int cntRead = raf.read(buf, 0, toRead);

        if (cntRead != toRead)
          throw new IOException(
              "Count of requested and actually read bytes does not match [cntRead="
                  + cntRead
                  + ", toRead="
                  + toRead
                  + ']');

        boolean zipped = buf.length > 512;

        return new VisorFileBlock(
            file.getPath(), pos, fSz, fLastModified, zipped, zipped ? zipBytes(buf) : buf);
      }
    } finally {
      U.close(raf, null);
    }
  }
Example #29
0
  private void updateLoader() {
    if (NavigineApp.Navigation == null) return;

    // Log.d(TAG, String.format(Locale.ENGLISH, "Update loader: %d", mLoader));

    long timeNow = DateTimeUtils.currentTimeMillis();
    if (mLoader < 0) return;

    int status = LocationLoader.checkLocationLoader(mLoader);
    if (status < 100) {
      if ((Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT / 3 && status == 0)
          || (Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT)) {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Loading timeout!\nPlease, check your internet connection!");
        Log.d(TAG, String.format(Locale.ENGLISH, "Load stopped on timeout!"));
        LocationLoader.stopLocationLoader(mLoader);
        mLoader = -1;
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText(String.format(Locale.ENGLISH, "Loading content (%d%%)", status));
      }
    } else {
      Log.d(TAG, String.format(Locale.ENGLISH, "Load finished with result: %d", status));
      LocationLoader.stopLocationLoader(mLoader);
      mLoader = -1;

      if (status == 100) {
        parseMapsXml();
        if (mInfoList.isEmpty()) {
          mListView.setVisibility(View.GONE);
          mStatusLabel.setVisibility(View.VISIBLE);
          mStatusLabel.setText("No locations available");
        } else {
          mListView.setVisibility(View.VISIBLE);
          mStatusLabel.setVisibility(View.GONE);
        }
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Error loading!\nPlease, check your ID!");
      }
    }
  }
  /**
   * Computes CPU usage (fraction of 1.0) between <code>start[1]</code> and <code>end[1]</code> time
   * points [1.0 corresponds to 100% utilization of all processors].
   *
   * @throws IllegalArgumentException if start and end time points are less than #MIN_ELAPSED_TIME
   *     ms apart.
   * @throws IllegalArgumentException if either argument is null
   * @param start,end long[2]: [0] system time stamp, [1] process CPU time (as returned by
   *     makeCPUUsageSnapshot()).
   */
  public static double getProcessCPUUsage(long[] start, long[] end) {
    if (start == null) throw new IllegalArgumentException("null input: start");
    if (end == null) throw new IllegalArgumentException("null input: end");
    // if (end[0] < start[0] + MIN_ELAPSED_TIME) throw new IllegalArgumentException("end time must
    // be at least " + MIN_ELAPSED_TIME + " ms later than start time");
    end[0] = Math.max(end[0], start[0] + MIN_ELAPSED_TIME);

    return ((double) (end[1] - start[1])) / (double) (end[0] - start[0]);
  }