private int initialSeparatorPosition(List<Line> lines) {
   int i = 0;
   for (Line line : lines) {
     i = Math.max(i, line.currentTokenLength());
   }
   return i;
 }
 public int maxArea(int[] height) {
   // Start typing your Java solution below
   // DO NOT write main() function
   if (height == null || height.length == 0) {
     return 0;
   }
   Line[] lines = new Line[height.length];
   for (int i = 0; i < height.length; i++) {
     Line line = new Line();
     line.h = height[i];
     line.p = i;
     lines[i] = line;
   }
   Arrays.sort(lines);
   int area;
   int min = lines[0].p;
   int max = lines[0].p;
   area = 0;
   for (int i = 1; i < lines.length; i++) {
     if (lines[i].p < min) {
       min = lines[i].p;
     } else if (lines[i].p > max) {
       max = lines[i].p;
     }
     int a = (max - min) * lines[i].h;
     if (a > area) {
       area = a;
     }
   }
   return area;
 }
示例#3
0
文件: PHPMode.java 项目: gnooth/j
 public boolean isInQuote(Buffer buffer, Position pos) {
   if (buffer.getMode() != this) Debug.bug();
   if (buffer.needsParsing()) buffer.getFormatter().parseBuffer();
   Line line = pos.getLine();
   int offset = pos.getOffset();
   boolean inQuote = false;
   char quoteChar = '\0';
   int state = PHPFormatter.getState(line.flags());
   if (state == STATE_QUOTE) {
     inQuote = true;
     quoteChar = '"';
   } else if (state == STATE_SINGLEQUOTE) {
     inQuote = true;
     quoteChar = '\'';
   }
   for (int i = 0; i < offset; i++) {
     char c = line.charAt(i);
     if (c == '\\') {
       // Escape.
       ++i;
     } else if (inQuote && c == quoteChar) {
       inQuote = false;
     } else if (c == '"' || c == '\'') {
       inQuote = true;
       quoteChar = c;
     }
   }
   return inQuote;
 }
示例#4
0
文件: Position.java 项目: gnooth/j
 public boolean atEnd() {
   if (line != null) {
     if (offset < line.length()) return false;
     if (line.next() != null) return false;
   }
   return true;
 }
示例#5
0
  public static boolean isValid(GardenModel mod) {
    for (Garden g : mod.gardens) {
      if (g.getTreeCount() > mod.trees) return false;
      if (g.getUnknownCount() + g.getTreeCount() < mod.trees) return false;
    }
    for (Iterator<Line> it = mod.grid.iterateColumns(); it.hasNext(); ) {
      Line col = it.next();
      if (col.getTreeCount() > mod.trees) return false;
      if (col.getUnknownCount() + col.getTreeCount() < mod.trees) return false;
    }
    for (Iterator<Line> it = mod.grid.iterateRows(); it.hasNext(); ) {
      Line row = it.next();
      if (row.getTreeCount() > mod.trees) return false;
      if (row.getUnknownCount() + row.getTreeCount() < mod.trees) return false;
    }

    for (Cell c : mod.grid) {
      if (c.getState() == State.Tree) {
        for (Iterator<Cell> it = mod.grid.iterateAdjacent(c); it.hasNext(); ) {
          if (it.next().getState() == State.Tree) return false;
        }
      }
    }

    for (Garden g : mod.gardens) {
      if (!g.areThereEnoughFreeNonAdjacentCells()) return false;
    }
    for (Line l : mod.grid.getColumnsAndRows()) {
      if (!l.areThereEnoughFreeNonAdjacentCells(mod.trees)) return false;
    }

    return checkBalance(mod);
  }
  // cf. Steven Eker. Faster "Pixel-Perfect" Line Clipping. Graphics Gems V:
  // 314-322.
  // - Pixels are not missed at the ends of a clipped segment.
  // - Visible pixels are the same as if there was no clipping.
  private boolean clipLine(Rectangle r, final Line sl, Line dl) {
    int code1 = 0, code2 = 0;

    dl.x0 = sl.x0;
    dl.y0 = sl.y0;
    dl.x1 = sl.x1;
    dl.y1 = sl.y1;

    if (sl.x0 < r.xmin) code1 |= CLIP_LEFT;
    if (sl.x0 > r.xmax) code1 |= CLIP_RIGHT;
    if (sl.y0 < r.ymin) code1 |= CLIP_BOTTOM;
    if (sl.y0 > r.ymax) code1 |= CLIP_TOP;

    if (sl.x1 < r.xmin) code2 |= CLIP_LEFT;
    if (sl.x1 > r.xmax) code2 |= CLIP_RIGHT;
    if (sl.y1 < r.ymin) code2 |= CLIP_BOTTOM;
    if (sl.y1 > r.ymax) code2 |= CLIP_TOP;

    if ((code1 | code2) == 0) return false; // Trivial accept.
    if ((code1 & code2) != 0) return true; // Trivial reject.

    // Clip first end point.
    if (code1 != 0) if (clipEndPoint(r, sl, dl, code1, false)) return true;
    // Clip second end point.
    if (code2 != 0) if (clipEndPoint(r, sl, dl, code2, true)) return true;

    return false;
  }
  public void run() {
    RAM memory = Emulator.computer.memory;
    Emulator.computer.pause();
    int pos = memory.readWordRaw(startingAddressPointer);
    for (Line line : lines) {
      int nextPos = pos + line.getLength() + 1;
      memory.write(pos++, (byte) (nextPos & 0x0ff), false, true);
      memory.write(pos++, (byte) (nextPos >> 8 & 0x0ff), false, true);
      memory.write(pos++, (byte) (line.getNumber() & 0x0ff), false, true);
      memory.write(pos++, (byte) (line.getNumber() >> 8 & 0x0ff), false, true);
      boolean isFirst = true;
      for (Command command : line.getCommands()) {
        if (!isFirst) {
          memory.write(pos++, (byte) ':', false, true);
        }
        isFirst = false;
        for (Command.ByteOrToken part : command.parts) {
          memory.write(pos++, part.getByte(), false, true);
        }
      }
      memory.write(pos++, (byte) 0, false, true);
    }
    memory.write(pos++, (byte) 0, false, true);
    memory.write(pos++, (byte) 0, false, true);
    memory.write(pos++, (byte) 0, false, true);
    memory.write(pos++, (byte) 0, false, true);

    //        Emulator.computer.cpu.setProgramCounter(BASIC_RUN);
    Emulator.computer.resume();
  }
  public static Header consumeHeaders(List<Line> remainingMessage) {
    final int headerLineNumber =
        remainingMessage.size() != 0 ? remainingMessage.get(0).getLineNumber() : 0;
    final Header headers = new Header(headerLineNumber);
    final Iterator<Line> iter = remainingMessage.iterator();
    Line currentLine;
    boolean isHeader = true;

    while (iter.hasNext() && isHeader) {
      currentLine = iter.next();
      final Matcher headerMatcher = PATTERN_HEADER_LINE.matcher(currentLine.toString());

      if (headerMatcher.matches() && headerMatcher.groupCount() == 2) {
        iter.remove();

        String headerName = headerMatcher.group(1).trim();
        String headerValue = headerMatcher.group(2).trim();

        headers.addHeader(
            headerName, Header.splitValuesByComma(headerValue), currentLine.getLineNumber());
      } else {
        isHeader = false;
      }
    }

    return headers;
  }
示例#9
0
 /** Sets <code>hlDepth</code> and takes care of '#' chars. */
 public void transfromHeadline() {
   if (this.hlDepth > 0) {
     return;
   }
   int level = 0;
   final Line line = this.lines;
   if (line.isEmpty) {
     return;
   }
   int start = line.leading;
   while (start < line.value.length() && line.value.charAt(start) == '#') {
     level++;
     start++;
   }
   while (start < line.value.length() && line.value.charAt(start) == ' ') {
     start++;
   }
   if (start >= line.value.length()) {
     line.setEmpty();
   } else {
     int end = line.value.length() - line.trailing - 1;
     while (line.value.charAt(end) == '#') {
       end--;
     }
     while (line.value.charAt(end) == ' ') {
       end--;
     }
     line.value = line.value.substring(start, end + 1);
     line.leading = line.trailing = 0;
   }
   this.hlDepth = Math.min(level, 6);
 }
示例#10
0
 private TextMeshData createQuadVertices(GUIText text, List<Line> lines) {
   text.setNumberOfLines(lines.size());
   double curserX = 0f;
   double curserY = 0f;
   List<Float> vertices = new ArrayList<Float>();
   List<Float> textureCoords = new ArrayList<Float>();
   for (Line line : lines) {
     if (text.isCentered()) {
       curserX = (line.getMaxLength() - line.getLineLength()) / 2;
     }
     for (Word word : line.getWords()) {
       for (Character letter : word.getCharacters()) {
         addVerticesForCharacter(curserX, curserY, letter, text.getFontSize(), vertices);
         addTexCoords(
             textureCoords,
             letter.getxTextureCoord(),
             letter.getyTextureCoord(),
             letter.getXMaxTextureCoord(),
             letter.getYMaxTextureCoord());
         curserX += letter.getxAdvance() * text.getFontSize();
       }
       curserX += metaData.getSpaceWidth() * text.getFontSize();
     }
     curserX = 0;
     curserY += LINE_HEIGHT * text.getFontSize();
   }
   return new TextMeshData(listToArray(vertices), listToArray(textureCoords));
 }
示例#11
0
 @Test
 public void testToString() {
   final Point start = Point.valueOf(5, 6);
   final Point end = Point.valueOf(50, 60);
   final Line sut = Line.valueOf(start, end);
   assertEquals(String.format("Line{start=%s, end=%s}", start, end), sut.toString());
 }
示例#12
0
 /**
  * This method finds the average distances between the partitions and parses those to the
  * validation object for the calculation of the column confidence.
  */
 private void setClusterCertainties() {
   method:
   while (true) {
     ArrayList<Integer> totalDistances = data.get(0).getDistances();
     for (Line line : data) {
       if (data.indexOf(line) > 0) {
         for (int x = 0; x < line.getDistances().size(); x++) {
           if (!(x >= totalDistances.size() || x >= line.getDistances().size())) {
             int totalDistance = totalDistances.get(x) + line.getDistances().get(x);
             totalDistances.set(x, totalDistance);
           } else {
             LOGGER.info(
                 "Found a problem during the cluster certainties. I've given the table a very low confidence");
             ArrayList<Integer> lowValidation = new ArrayList<Integer>();
             for (int o : line.getDistances()) {
               lowValidation.add(0);
             }
             validation.setClusterCertainty(lowValidation, data.get(0).getDistanceThreshold());
             validation.setLineThreshold(data.get(0).getDistanceThreshold());
             break method;
           }
         }
       }
     }
     ArrayList<Integer> averageDistances = new ArrayList<Integer>();
     for (int distance : totalDistances) {
       averageDistances.add(distance / data.size());
     }
     validation.setClusterCertainty(averageDistances, data.get(0).getDistanceThreshold());
     validation.setLineThreshold(data.get(0).getDistanceThreshold());
     break method;
   }
 }
示例#13
0
文件: Triangle.java 项目: JaiKB/APCS
  /**
   * Calculates and returns an altitude of the triangle
   *
   * @return An altitude of the triangle
   */
  public Line getAltitude() {
    Line base = new Line(pointB, pointC);
    double altitudeSlope = base.getPerpSlope();
    // D is a point on BC such that AD perp BC
    double ax = pointA.getX();
    double bx = pointB.getX();
    double cx = pointC.getX();
    double ay = pointA.getY();
    double by = pointB.getY();
    double cy = pointC.getY();
    // Vertical case:
    if (Double.isInfinite(base.getSlope())) return new Line(pointA, new Point(ax, by));
    // There has to be an easier way...
    // This sorcery brought to you by Wolfram Alpha
    double dx =
        (ax * bx / (by - cy)
                - ax * cx / (by - cy)
                - ay * cy / (by - cy)
                + ay * by / (by - cy)
                + cx * (by - cy) / (bx - cx)
                - cy)
            / ((by - cy) / (bx - cx) + bx / (by - cy) - cx / (by - cy));
    double dy = base.getSlope() * (dx - cx) + cy;

    return new Line(pointA, new Point(dx, dy));
  }
示例#14
0
 protected boolean isTemplateLine(Line line) {
   ProcessedRichString string = line.getRichString();
   if (string.getLines().size() == 1) {
     return false;
   }
   boolean firstOrLast = string.getLines().get(0) == line;
   if (!firstOrLast) {
     if (string.getLines().get(string.getLines().size() - 1) == line) {
       if (!(line.getParts().get(line.getParts().size() - 1) instanceof LineBreak))
         firstOrLast = true;
     }
   }
   boolean onlyLiterals = true;
   for (LinePart part : line.getParts()) {
     if (part instanceof PrintedExpression) return false;
     if (part instanceof Literal) {
       Literal literal = (Literal) part;
       if (literal instanceof LineBreak) {
         if (firstOrLast) return onlyLiterals;
         return !onlyLiterals;
       }
       if (!(new TextLine(
               literal.getLiteral().getValue(), literal.getOffset(), literal.getLength(), 0)
           .containsOnlyWhitespace())) return false;
     } else if (firstOrLast) {
       return false;
     } else {
       onlyLiterals = false;
     }
   }
   if (firstOrLast) return onlyLiterals;
   return !onlyLiterals;
 }
示例#15
0
文件: Line.java 项目: vojta001/Zelda
 public static Line constructFromTwoPoints(Point A, Point B) {
   Line l = new Line();
   l.A = A;
   l.B = B;
   l.refreshCoefs();
   return l;
 }
示例#16
0
 public void drawTo(Graphics g, Line line) {
   if (!calc.tileOnMap(t1) || !calc.tileOnMap(t2)) return;
   if (calc.tileOnMap(line.getTile1()) && calc.tileOnMap(line.getTile2())) {
     Point p1 = calc.tileToMinimap(t1);
     Point p2 = calc.tileToMinimap(t2);
     Point p3 = calc.tileToMinimap(line.getTile2());
     Point p4 = calc.tileToMinimap(line.getTile1());
     GeneralPath path = new GeneralPath();
     path.moveTo(p1.x, p1.y);
     path.lineTo(p2.x, p2.y);
     path.lineTo(p3.x, p3.y);
     path.lineTo(p4.x, p4.y);
     path.closePath();
     g.setColor(POLY_FILL);
     ((Graphics2D) g).fill(path);
     ((Graphics2D) g).draw(path);
   }
   Point last = null, p;
   g.setColor(Color.ORANGE);
   for (RSTile t : pathList) {
     if (calc.tileOnMap(t)) {
       p = calc.tileToMinimap(t);
       g.fillOval(p.x - 2, p.y - 2, 5, 5);
       if (last != null) g.drawLine(p.x, p.y, last.x, last.y);
       last = p;
     } else last = null;
   }
 }
示例#17
0
  private void mapRegistersToVariables() {
    Hashtable<String, String> prevMapRegToVar = null;

    for (int i = 0; i < getLines().getNumItems(); i++) {
      Line line = getLines().getItemAtIndex(i);

      if (Line.Type.INSTRUCTION == line.getType()) {
        Instruction instr = (Instruction) line;

        // Copy previous map, if available
        if (null != prevMapRegToVar)
          copyHashStringToString(instr.getMapRegToValue(), prevMapRegToVar);

        // On a load word, map the register to the variable
        if (0 == instr.getInstruction().compareTo("lw")
            || 0 == instr.getInstruction().compareTo("li")) {
          instr
              .getMapRegToValue()
              .put(instr.getArgument1().getName(), instr.getArgument2().getName());
        }
        // On a store word, remove the register mapping
        else if (0 == instr.getInstruction().compareTo("sw")) {
          // instr.getMapRegToValue().remove(instr.getArgument1().getName());
          // instr.getMapRegToValue().put(instr.getArgument1().getName(),
          // instr.getArgument2().getName());
        }

        prevMapRegToVar = instr.getMapRegToValue();
      }
    }
  }
示例#18
0
 private List<Line> createStructure(GUIText text) {
   char[] chars = text.getTextString().toCharArray();
   List<Line> lines = new ArrayList<Line>();
   Line currentLine =
       new Line(metaData.getSpaceWidth(), text.getFontSize(), text.getMaxLineSize());
   Word currentWord = new Word(text.getFontSize());
   for (char c : chars) {
     int ascii = (int) c;
     if (ascii == SPACE_ASCII) {
       boolean added = currentLine.attemptToAddWord(currentWord);
       if (!added) {
         lines.add(currentLine);
         currentLine =
             new Line(metaData.getSpaceWidth(), text.getFontSize(), text.getMaxLineSize());
         currentLine.attemptToAddWord(currentWord);
       }
       currentWord = new Word(text.getFontSize());
       continue;
     }
     Character character = metaData.getCharacter(ascii);
     currentWord.addCharacter(character);
   }
   completeStructure(lines, currentLine, currentWord, text);
   return lines;
 }
示例#19
0
  public void flush() throws IOException {
    if (!dirty) return;

    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    try {
      fos = new FileOutputStream(filePath);
      osw = new OutputStreamWriter(fos, charset);

      // 全局数据
      for (Line l : globalLines) {
        osw.write(l.toString());
        osw.write('\n');
      }

      // 各个块
      for (Sector s : sectors) {
        osw.write(s.toString());
      }

      dirty = false;
    } finally {
      // XXX 因为stream之间有一定的依赖顺序,必须按照一定的顺序关闭流
      if (osw != null) osw.close();
      if (fos != null) fos.close();
    }
  }
示例#20
0
  /** By Dingding */
  private Set<Line.Segment> getRemovableLineSegments(
      Map<Position, Piece> pieceMap, PieceColor pieceColor) {
    Set<Line.Segment> removableLines = new HashSet<>();
    Set<Line> linesOnTheBoard =
        Line.getLinesOnTheBoard(
            this); // Get all the possible lines on the board. Positions don't need to be occupied.

    for (Line line : linesOnTheBoard) {
      Position currentPosition = line.getStartPosition();
      Position startOfSegment = null;
      Position endOfSegment = null;
      Direction direction = line.getDirection();
      int consecutivePieces =
          0; // We start at a dot position, so we can assume that we don't start in a set of
             // consecutive pieces
      boolean isInLineSegment = false;

      // Break the for-loop if an endOfSegment has been found (because the largest lines only have 7
      // positions on the board, there
      // can't be more than one set of four pieces of the same color (requiring at least 9
      // positions) on the board.
      for (;
          endOfSegment == null && isPositionOnPlayAreaOrOuterDots(currentPosition);
          currentPosition = currentPosition.next(direction)) {
        PieceColor currentPieceColor =
            pieceMap.containsKey(currentPosition)
                ? pieceMap.get(currentPosition).getPieceColor()
                : null;

        // Update the consecutivePieces
        if (currentPieceColor == pieceColor) consecutivePieces++;
        if (consecutivePieces == 4) isInLineSegment = true;
        if (currentPieceColor != pieceColor) consecutivePieces = 0;

        if (isInLineSegment) {
          if (isDotPosition(currentPosition) || currentPieceColor == null) {
            endOfSegment = currentPosition.previous(direction);
          }
        }

        // Update the startOfSegment if necessary
        if (startOfSegment == null) {
          if (currentPieceColor != null) {
            startOfSegment = currentPosition;
          }
        }
        if (currentPieceColor == null && endOfSegment == null) {
          startOfSegment = null;
        }

        // Add a line segment to the list if we have found one
        if (endOfSegment != null) {
          removableLines.add(new Line.Segment(this, startOfSegment, endOfSegment, direction));
        }
      }
    }

    return removableLines;
  }
示例#21
0
文件: Line.java 项目: vojta001/Zelda
 /**
  * Vytvoří obraz réro přímky souměrný přes osu danou přímkou
  *
  * @param mirror osa souměrnosti
  * @return obraz přes osu souměrnosti mirror
  */
 public Line mirrorReflection(Line mirror) {
   Point intersect = this.intersectPoint(mirror);
   Line lineNormal = constructFromPointAndVector(intersect, mirror.a, mirror.b);
   Line lineParalell = constructFromPointAndNormal(A, mirror.a, mirror.b);
   Point S = lineParalell.intersectPoint(lineNormal);
   Point reflectedA = new Point(2 * S.x - A.x, 2 * S.y - A.y);
   return Line.constructFromTwoPoints(intersect, reflectedA);
 }
示例#22
0
文件: Position.java 项目: gnooth/j
 public char getChar() {
   if (offset < 0 || offset > line.length()) {
     Log.error("Position.getChar() offset = " + offset + " line.length() = " + line.length());
     Debug.assertTrue(false);
   }
   if (offset == line.length()) return EOL;
   return line.charAt(offset);
 }
示例#23
0
文件: Position.java 项目: gnooth/j
 public boolean nextLine() {
   if (line.next() != null) {
     line = line.next();
     offset = 0;
     return true;
   }
   return false;
 }
示例#24
0
 @Test
 public void create() {
   final Point start = Point.valueOf(5, 6);
   final Point end = Point.valueOf(50, 60);
   final Line sut = Line.valueOf(start, end);
   assertEquals(start, sut.getStart());
   assertEquals(end, sut.getEnd());
 }
示例#25
0
文件: Triangle.java 项目: JaiKB/APCS
 /**
  * Calculates and returns the perimeter of the triangle
  *
  * @return the triangle's perimeter
  */
 public double getPerimeter() {
   double perimeter = 0;
   Line[] sides = getSides();
   for (Line l : sides) {
     perimeter += l.getLength();
   }
   return perimeter;
 }
示例#26
0
文件: Triangle.java 项目: JaiKB/APCS
 public double getArea3() {
   double s = getPerimeter() / 2;
   double product = s;
   for (Line side : getSides()) {
     product *= s - side.getLength();
   }
   return Math.sqrt(product);
 }
 public static Line removeEndingCRLF(final Line line) {
   Matcher matcher = PATTERN_LAST_CRLF.matcher(line.toString());
   if (matcher.matches()) {
     return new Line(matcher.group(1), line.getLineNumber());
   } else {
     return line;
   }
 }
示例#28
0
 /**
  * Draws a Line object on the GrapherPanel as a 1 pixel wide line ending on the points defining
  * the Line object.
  *
  * @param The Line to paint.
  */
 private void paintLine(Line l) {
   g.setColor(Color.YELLOW);
   g.drawLine(
       250 + (int) (l.getPointA().getX() * 25),
       250 - (int) (l.getPointA().getY() * 25),
       250 + (int) (l.getPointB().getX() * 25),
       250 - (int) (l.getPointB().getY() * 25));
 }
示例#29
0
 public Line findByUri(String uri) {
   for (Line l : getLines()) {
     String candidate = l.getUri();
     if (candidate.equals(uri)) {
       return l;
     }
   }
   return null;
 }
示例#30
0
 public Line findByUsername(String username) {
   for (Line l : getLines()) {
     User user = l.getUser();
     if (user != null && user.getUserName().equals(username)) {
       return l;
     }
   }
   return null;
 }