示例#1
1
  /**
   * Calculates losses for the given credit portfolio using Monte-Carlo Simulation. Simulates
   * probability of default only.
   *
   * @param portfolio Credit portfolio.
   * @param horizon Forecast horizon.
   * @param num Number of Monte-Carlo iterations.
   * @return Losses array simulated by Monte Carlo method.
   */
  private double[] calculateLosses(Credit[] portfolio, int horizon, int num) {
    double[] losses = new double[num];

    // Count losses using Monte-Carlo method. We generate random probability of default,
    // if it exceeds certain credit default value we count losses - otherwise count income.
    for (int i = 0; i < num; i++)
      for (Credit crd : portfolio) {
        int remDays = Math.min(crd.getRemainingTerm(), horizon);

        if (rndGen.nextDouble() >= 1 - crd.getDefaultProbability(remDays))
          // (1 + 'r' * min(H, W) / 365) * S.
          // Where W is a horizon, H is a remaining crediting term, 'r' is an annual credit rate,
          // S is a remaining credit amount.
          losses[i] +=
              (1 + crd.getAnnualRate() * Math.min(horizon, crd.getRemainingTerm()) / 365)
                  * crd.getRemainingAmount();
        else
          // - 'r' * min(H,W) / 365 * S
          // Where W is a horizon, H is a remaining crediting term, 'r' is a annual credit rate,
          // S is a remaining credit amount.
          losses[i] -=
              crd.getAnnualRate()
                  * Math.min(horizon, crd.getRemainingTerm())
                  / 365
                  * crd.getRemainingAmount();
      }

    return losses;
  }
示例#2
0
  private double rec(int idx, double rem) {
    if (idx >= 3) {
      return rem / walkSpeed;
    }

    double ans = INF;
    double left = 0;
    double right = rem;

    for (int iter = 0; iter < 100; iter++) {
      double m1 = left + (right - left) / 3.0;
      double m2 = right - (right - left) / 3.0;

      double a1 = rec(idx + 1, rem - m1) + Math.sqrt(sq(a[idx][0]) + sq(m1)) / a[idx][1];
      ans = Math.min(ans, a1);

      double a2 = rec(idx + 1, rem - m2) + Math.sqrt(sq(a[idx][0]) + sq(m2)) / a[idx][1];
      ans = Math.min(ans, a2);

      if (a1 < a2) {
        right = m2;
      } else {
        left = m1;
      }
    }

    return ans;
  }
示例#3
0
  /** @return watches contained in this group of watches */
  public Object[] getChildren(Object parent, int from, int to) throws UnknownTypeException {
    if (parent == ROOT) {

      // 1) get Watches
      Watch[] ws = DebuggerManager.getDebuggerManager().getWatches();
      to = Math.min(ws.length, to);
      from = Math.min(ws.length, from);
      Watch[] fws = new Watch[to - from];
      System.arraycopy(ws, from, fws, 0, to - from);

      // 2) create JPDAWatches for Watches
      int i, k = fws.length;
      JPDAWatch[] jws = new JPDAWatch[k + 1];
      for (i = 0; i < k; i++) {

        JPDAWatchEvaluating jw = watchToValue.get(fws[i]);
        if (jw == null) {
          jw = new JPDAWatchEvaluating(this, fws[i], debugger);
          watchToValue.put(fws[i], jw);
        }
        jws[i] = jw;

        // The actual expressions are computed on demand in JPDAWatchEvaluating
      }
      jws[k] = EMPTY_WATCH;

      if (listener == null) listener = new Listener(this, debugger);
      return jws;
    }
    if (parent instanceof JPDAWatchImpl) {
      return getLocalsTreeModel().getChildren(parent, from, to);
    }
    return getLocalsTreeModel().getChildren(parent, from, to);
  }
示例#4
0
  private static void analyzeNext() {
    ArrayList previous = new ArrayList();
    String token = nextToken();
    analysis.add("", token, 0); // Insert 1st token directly.
    previous.add(token);

    while (true) {
      int nWords = Math.min(previous.size(), MAX);
      token = nextToken();
      if (token == PERIOD) break;

      for (int j = 1; j <= nWords; j++) {
        String s1 = concat(previous, j); // ({"a", "b", "c"}, 2) -> "b c"
        analysis.add(s1, token, j);
      }

      previous.add(token);
      if (previous.size() == MAX) previous.remove(0);
    }

    int nWords = Math.min(previous.size(), MAX);
    for (int j = 1; j < nWords; j++) {
      String s1 = concat(previous, j); // ({"a", "b", "c"}, 2) -> "b c"
      analysis.add(s1, PERIOD, j);
    }
  }
  public static int maxProduct(int[] A) {
    if (A.length == 0) {
      return 0;
    }
    if (A.length == 1 && A[0] < 0) {
      return A[0];
    }
    int max_product = 0;

    int current_max = 0;
    int current_min = 0;

    int prev_max = 1;
    int prev_min = 1;

    for (int i = 0; i < A.length; i++) {
      current_max = Math.max(Math.max(prev_max * A[i], prev_min * A[i]), A[i]);
      current_min = Math.min(Math.min(prev_max * A[i], prev_max * A[i]), A[i]);

      max_product = Math.max(max_product, current_max);

      prev_max = current_max;
      prev_min = current_min;
    }
    return max_product;
  }
示例#6
0
 public static void main(String[] args) {
   final int INF = 1 << 30;
   Scanner scan = new Scanner(System.in);
   int N = scan.nextInt();
   int K = scan.nextInt();
   int[] d = new int[N + 1];
   for (int i = 0; i < N; i++) d[i + 1] = scan.nextInt();
   N++;
   for (int i = N - 1; i > 0; i--) d[i] -= d[i - 1];
   int[] prev = new int[N];
   int[] dp = new int[N];
   Arrays.fill(prev, INF);
   prev[0] = 0;
   for (int k = 0; k < K; k++) {
     int best = INF;
     for (int i = 0; i < N; i++) {
       if (i >= 2) best = Math.min(best, prev[i - 2]);
       dp[i] = INF;
       if (i > 0) {
         dp[i] = Math.min(dp[i], dp[i - 1] + d[i]);
         dp[i] = Math.min(dp[i], best + d[i]);
       }
     }
     int[] temp = prev;
     prev = dp;
     dp = temp;
   }
   int min = INF;
   for (int i = 0; i < N; i++) min = Math.min(min, prev[i]);
   System.out.println(min);
 }
示例#7
0
 /**
  * Gets the minimum extent of this envelope across all three dimensions.
  *
  * @return the minimum extent of this envelope
  */
 @Override
 public double minExtent() {
   if (isNull()) {
     return 0.0;
   }
   return Math.min(getWidth(), Math.min(getHeight(), getDepth()));
 }
  private void strongConnect(SCCNode v, List<List<SCCNode>> sccs) {
    // Set the depth index for v to the smallest unused index
    v.index = index;
    v.lowlink = index++;
    stack.push(v);
    stackSet.add(v);

    // Consider successors of v
    for (Node<SCCNode> n : v.getLinks()) {
      SCCNode w = (SCCNode) n;
      if (w.index == -1) {
        // Successor w has not yet been visited; recurse on it
        strongConnect(w, sccs);
        v.lowlink = Math.min(v.lowlink, w.lowlink);
      } else if (stackSet.contains(w)) {
        // Successor w is in stack S and hence in the current SCC
        v.lowlink = Math.min(v.lowlink, w.index);
      }
    }

    // If v is a root node, pop the stack and generate an SCC
    if (v.lowlink == v.index) {
      List<SCCNode> SCC = new LinkedList<>();
      SCCNode node = null;
      do {
        node = stack.pop();
        stackSet.remove(node);
        SCC.add(node);
      } while (node != v);

      if (SCC.size() > 1) sccs.add(SCC);
    }
  }
  /**
   * Calculates the min and max boundaries of the structure after it has been transformed into its
   * canonical orientation.
   */
  private void calcBoundaries() {
    minBoundary.x = Double.MAX_VALUE;
    maxBoundary.x = Double.MIN_VALUE;
    minBoundary.y = Double.MAX_VALUE;
    maxBoundary.x = Double.MIN_VALUE;
    minBoundary.z = Double.MAX_VALUE;
    maxBoundary.z = Double.MIN_VALUE;
    xzRadiusMax = Double.MIN_VALUE;

    Point3d probe = new Point3d();

    for (Point3d[] list : subunits.getTraces()) {
      for (Point3d p : list) {
        probe.set(p);
        transformationMatrix.transform(probe);

        minBoundary.x = Math.min(minBoundary.x, probe.x);
        maxBoundary.x = Math.max(maxBoundary.x, probe.x);
        minBoundary.y = Math.min(minBoundary.y, probe.y);
        maxBoundary.y = Math.max(maxBoundary.y, probe.y);
        minBoundary.z = Math.min(minBoundary.z, probe.z);
        maxBoundary.z = Math.max(maxBoundary.z, probe.z);
        xzRadiusMax = Math.max(xzRadiusMax, Math.sqrt(probe.x * probe.x + probe.z * probe.z));
      }
    }
    //		System.out.println("MinBoundary: " + minBoundary);
    //		System.out.println("MaxBoundary: " + maxBoundary);
    //		System.out.println("zxRadius: " + xzRadiusMax);
  }
示例#10
0
 public String getResult() {
   ProfilerFrame[] f = (ProfilerFrame[]) frames.values().toArray(new ProfilerFrame[0]);
   Arrays.sort(
       f,
       new Comparator() {
         public int compare(Object o1, Object o2) {
           return ((ProfilerFrame) o2).runtime - ((ProfilerFrame) o1).runtime;
         }
       });
   int length = Math.min(100, f.length);
   int prefixLength = length < 2 ? 0 : Integer.MAX_VALUE;
   int maxLength = 0;
   for (int i = 0; i < length; i++) {
     maxLength = Math.max(maxLength, f[i].name.length());
     if (i < length - 1) {
       prefixLength =
           Math.min(prefixLength, StringUtils.getCommonPrefix(f[i].name, f[i + 1].name).length());
     }
   }
   maxLength = maxLength + 30 - prefixLength;
   StringBuffer buffer = new StringBuffer("     total  average  calls    path\n");
   for (int i = 0; i < maxLength; i++) {
     buffer.append('-');
   }
   buffer.append('\n');
   for (int i = 0; i < length; i++) {
     buffer.append(f[i].renderLine(prefixLength));
   }
   return buffer.toString();
 }
示例#11
0
 public int minimumMoves(String[] boardString) {
   n = boardString.length;
   m = boardString[0].length();
   board = new int[n];
   for (int i = 0; i < n; ++i) {
     for (int j = 0; j < m; ++j) {
       if (boardString[i].charAt(j) == 'W') {
         board[i] |= 1 << j;
       }
     }
   }
   int answer = Integer.MAX_VALUE;
   all = (1 << m) - 1;
   for (int type = 0; type < 1 << m; ++type) {
     answer = Math.min(answer, solve(type, 0));
     for (int first = type; first > 0; first = (first - 1) & type) {
       answer = Math.min(answer, solve(type, first));
     }
     answer = Math.min(answer, solve(type, all ^ type));
     for (int first = all ^ type; first > 0; first = (first - 1) & (all ^ type)) {
       answer = Math.min(answer, solve(type, first));
     }
   }
   return answer == Integer.MAX_VALUE ? -1 : answer;
 }
示例#12
0
  /**
   * Get the bounding rectangle
   *
   * @return minimum bounding rectangle
   */
  public BoundingRectangle2D getBounds() {
    if (boundsChanged == true) {
      boolean first = true;
      double minX = 0;
      double maxX = 0;
      double minY = 0;
      double maxY = 0;

      for (Enumeration e = vertices.elements(); e.hasMoreElements(); ) {
        Vector2D vertex = (Vector2D) e.nextElement();
        if (first) {
          minX = vertex.getX();
          maxX = vertex.getX();
          minY = vertex.getY();
          maxY = vertex.getY();
          first = false;
        } else {
          minX = Math.min(minX, vertex.getX());
          maxX = Math.max(maxX, vertex.getX());
          minY = Math.min(minY, vertex.getY());
          maxY = Math.max(maxY, vertex.getY());
        }
      }

      bounds.set(minX, minY, Math.abs(maxX - minX), Math.abs(maxY - minY));

      boundsChanged = false;
    }

    return bounds;
  }
示例#13
0
 public static ItemStack insertItem(
     IInventory inventory, ItemStack itemStack, boolean test, boolean force) {
   if (test) {
     itemStack = itemStack.copy();
   }
   int size = inventory.getSizeInventory();
   for (int i = 0; i < size; i++) {
     if (inventory.isItemValidForSlot(i, itemStack) || force) {
       ItemStack storedItem = inventory.getStackInSlot(i);
       if (storedItem != null) {
         if (equalItemAndNBT(storedItem, itemStack)) {
           int maxStackSize =
               Math.min(itemStack.getMaxStackSize(), inventory.getInventoryStackLimit());
           int add = Math.min(itemStack.stackSize, maxStackSize - storedItem.stackSize);
           if (!test) {
             storedItem.stackSize += add;
           }
           itemStack.stackSize -= add;
           inventory.setInventorySlotContents(i, storedItem);
         }
       } else {
         storedItem = itemStack.copy();
         storedItem.stackSize = Math.min(itemStack.stackSize, itemStack.getMaxStackSize());
         if (!test) {
           inventory.setInventorySlotContents(i, storedItem);
         }
         itemStack.stackSize -= storedItem.stackSize;
       }
       if (itemStack.stackSize <= 0) {
         return null;
       }
     }
   }
   return itemStack;
 }
 public void addCrossArgumentSemanticSimilarity(
     Counter<String> features, final NumericMentionExpression e) {
   List<NumericTuple> args = e.expression.arguments();
   double sim = 0.;
   double minSim = 0.;
   double maxSim = 0.;
   if (args.size() > 1) {
     sim =
         semanticSimilarityVW(features, "12-", args.get(0).subjSentence, args.get(1).subjSentence);
     maxSim = Math.max(maxSim, sim);
     minSim = Math.min(minSim, sim);
   }
   if (args.size() > 2) {
     sim =
         semanticSimilarityVW(features, "13-", args.get(0).subjSentence, args.get(2).subjSentence);
     maxSim = Math.max(maxSim, sim);
     minSim = Math.min(minSim, sim);
     sim =
         semanticSimilarityVW(features, "23-", args.get(1).subjSentence, args.get(2).subjSentence);
     maxSim = Math.max(maxSim, sim);
     minSim = Math.min(minSim, sim);
   }
   features.incrementCount("max-cross-semantic-similarity", maxSim);
   features.incrementCount("min-cross-semantic-similarity", minSim);
 }
  /** get the profiling results for "name" from this database. */
  public ProfilerResults(ProfilerDB db, String name) {
    this.name = name;
    this.db = db;

    // XXX: if "name" is non existing, an empty data will be created
    ProfiledData data = db.getDataset(name);

    this.count = data.getSize();
    this.memories = data.memories;
    this.ids = data.ids;
    this.times = data.times;

    this.current = -1;

    // calc min/max:
    min_times = Integer.MAX_VALUE;
    max_times = Integer.MIN_VALUE;
    min_mems = Long.MAX_VALUE;
    max_mems = Long.MIN_VALUE;

    for (int i = 0; i < count; i++) {
      min_mems = Math.min(min_mems, memories[i]);
      max_mems = Math.max(max_mems, memories[i]);
      min_times = Math.min(min_times, times[i]);
      max_times = Math.max(max_times, times[i]);
    }
  }
示例#16
0
 /**
  * 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);
     }
 }
    private Pair<MutableTextRange, StringBuffer> getFragmentByRange(int start, final int length) {
      final StringBuffer fragmentBuffer = new StringBuffer();
      int end = start + length;

      // restoring buffer and remove all subfragments from the list
      int documentOffset = 0;
      int effectiveOffset = 0;

      Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
      while (iterator.hasNext() && effectiveOffset <= end) {
        final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
        final MutableTextRange range = pair.getFirst();
        final StringBuffer buffer = pair.getSecond();
        int effectiveFragmentEnd = range.getStartOffset() + buffer.length();

        if (range.getStartOffset() <= start && effectiveFragmentEnd >= end) return pair;

        if (effectiveFragmentEnd >= start) {
          final int effectiveStart = Math.max(effectiveOffset, start);
          if (range.getStartOffset() > start) {
            fragmentBuffer.append(
                myDocument.getCharsSequence(),
                effectiveStart - effectiveOffset + documentOffset,
                Math.min(range.getStartOffset(), end) - effectiveOffset + documentOffset);
          }
          if (end >= range.getStartOffset()) {
            fragmentBuffer.append(buffer);
            end =
                end > effectiveFragmentEnd
                    ? end - (buffer.length() - range.getLength())
                    : range.getEndOffset();
            effectiveFragmentEnd = range.getEndOffset();
            start = Math.min(start, range.getStartOffset());
            iterator.remove();
          }
        }

        documentOffset += range.getEndOffset() - effectiveOffset;
        effectiveOffset = effectiveFragmentEnd;
      }

      if (effectiveOffset < end) {
        final int effectiveStart = Math.max(effectiveOffset, start);
        fragmentBuffer.append(
            myDocument.getCharsSequence(),
            effectiveStart - effectiveOffset + documentOffset,
            end - effectiveOffset + documentOffset);
      }

      MutableTextRange newRange = new MutableTextRange(start, end);
      final Pair<MutableTextRange, StringBuffer> pair =
          new Pair<MutableTextRange, StringBuffer>(newRange, fragmentBuffer);
      for (Pair<MutableTextRange, StringBuffer> affectedFragment : myAffectedFragments) {
        MutableTextRange range = affectedFragment.getFirst();
        assert end <= range.getStartOffset() || range.getEndOffset() <= start
            : "Range :" + range + "; Added: " + newRange;
      }
      myAffectedFragments.add(pair);
      return pair;
    }
示例#18
0
  /**
   * Algorithm of Tarjan for computing the strongly connected components of a graph.
   *
   * @param v current node
   * @throws QueryException if a variable directly calls itself
   */
  private void tarjan(final int v) throws QueryException {
    final int ixv = 2 * v, llv = ixv + 1, idx = next++;
    while (list.size() <= llv) list.add(-1);
    list.set(ixv, idx);
    list.set(llv, idx);

    stack.push(v);

    for (final int w : adjacentTo(v)) {
      final int ixw = 2 * w, llw = ixw + 1;
      if (list.size() <= ixw || list.get(ixw) < 0) {
        // Successor w has not yet been visited; recurse on it
        tarjan(w);
        list.set(llv, Math.min(list.get(llv), list.get(llw)));
      } else if (stack.contains(w)) {
        // Successor w is in stack S and hence in the current SCC
        list.set(llv, Math.min(list.get(llv), list.get(ixw)));
      }
    }

    // If v is a root node, pop the stack and generate an SCC
    if (list.get(llv) == list.get(ixv)) {
      int w;
      Scope[] out = null;
      do {
        w = stack.pop();
        final Scope scp = scopes.get(w);
        out = out == null ? new Scope[] {scp} : Array.add(out, scp);
      } while (w != v);
      result.add(out);
    }
  }
    private static <T> int strongConnect(
        InferenceGraphNode<T> currentNode,
        int index,
        Stack<InferenceGraphNode<T>> currentStack,
        ArrayList<List<InferenceGraphNode<T>>> result) {
      currentNode.index = index;
      currentNode.lowlink = index;
      index++;

      currentStack.push(currentNode);

      for (InferenceGraphNode<T> dependantNode : currentNode.getDependencies()) {
        if (dependantNode.index == -1) {
          strongConnect(dependantNode, index, currentStack, result);
          currentNode.lowlink = Math.min(currentNode.lowlink, dependantNode.lowlink);
        } else if (currentStack.contains(dependantNode)) {
          currentNode.lowlink = Math.min(currentNode.lowlink, dependantNode.index);
        }
      }

      if (currentNode.lowlink == currentNode.index) {
        final ArrayList<InferenceGraphNode<T>> arrayList = new ArrayList<InferenceGraphNode<T>>();
        InferenceGraphNode<T> cyclicNode;
        do {
          cyclicNode = currentStack.pop();
          arrayList.add(cyclicNode);
        } while (cyclicNode != currentNode);
        result.add(arrayList);
      }
      return index;
    }
  private static void solve(int[][] points) {
    int N = points.length;
    int W = (1 << N);
    int[][] dp = new int[N][W];
    int[][] masks = new int[N][N];
    int[][] areas = new int[N][N];
    makeMasksAndAreas(points, masks, areas);

    for (int i = 0; i < N; i++) {
      Arrays.fill(dp[i], Integer.MAX_VALUE);
    }

    dp[0][0] = 0;

    for (int i = 1; i < N; i++) {
      for (int state = 0; state < W; state++) {
        if (dp[i - 1][state] == Integer.MAX_VALUE) continue;
        for (int a = 0; a < N; a++) {
          for (int b = a + 1; b < N; b++) {
            int mask = masks[a][b];
            if ((mask | state) == state) continue;

            dp[i][mask | state] = Math.min(dp[i][mask | state], dp[i - 1][state] + areas[a][b]);
          }
        }
      }
    }

    int res = Integer.MAX_VALUE;
    for (int i = 0; i < N; i++) {
      res = Math.min(res, dp[i][W - 1]);
    }

    System.out.println(res);
  }
 private int wrapPositionForTabbedTextWithOptimization(
     @NotNull CharSequence text,
     int tabSize,
     int startLineOffset,
     int endLineOffset,
     int targetRangeEndOffset) {
   int width = 0;
   int symbolWidth;
   int result = Integer.MAX_VALUE;
   boolean wrapLine = false;
   for (int i = startLineOffset; i < Math.min(endLineOffset, targetRangeEndOffset); i++) {
     char c = text.charAt(i);
     switch (c) {
       case '\t':
         symbolWidth = tabSize - (width % tabSize);
         break;
       default:
         symbolWidth = 1;
     }
     if (width + symbolWidth + FormatConstants.RESERVED_LINE_WRAP_WIDTH_IN_COLUMNS
             >= mySettings.RIGHT_MARGIN
         && (Math.min(endLineOffset, targetRangeEndOffset) - i)
             >= FormatConstants.RESERVED_LINE_WRAP_WIDTH_IN_COLUMNS) {
       // Remember preferred position.
       result = i - 1;
     }
     if (width + symbolWidth >= mySettings.RIGHT_MARGIN) {
       wrapLine = true;
       break;
     }
     width += symbolWidth;
   }
   return wrapLine ? result : -1;
 }
示例#22
0
  public int[] solve(String[] edgeStrings) {

    ArrayList<Integer> oddPoints = new ArrayList<Integer>();

    int min = Integer.MAX_VALUE;
    for (String s : edgeStrings) {
      StringTokenizer st = new StringTokenizer(s);
      int from = Integer.parseInt(st.nextToken());
      int to = Integer.parseInt(st.nextToken());
      edges.add(new Edge(from, to));

      min = Math.min(min, from);
      min = Math.min(min, to);
      oddPoint(oddPoints, from);
      oddPoint(oddPoints, to);
    }

    assert (oddPoints.size() < 3);

    if (oddPoints.size() > 0) {
      dfs(min(oddPoints));
      return toArray(circuit);
    } else {
      dfs(min);
      return toArray(circuit);
    }
  }
示例#23
0
 private void scroll_area_set(int y0, int y1) {
   y0 = Math.max(0, Math.min(height - 1, y0));
   y1 = Math.max(1, Math.min(height, y1));
   if (y1 > y0) {
     scroll_area_y0 = y0;
     scroll_area_y1 = y1;
   }
 }
示例#24
0
 public static Color gradientColor(double value) {
   if (value < 0.0) return Color.gray;
   if (value > 1.0) value = 1.0;
   int red = Math.min(255, (int) (512.0 - (value * 512.0)));
   int green = Math.min(255, (int) (value * 512.0));
   int blue = 0;
   return new Color(red, green, blue);
 }
示例#25
0
 private static int DFS(int si, int sj, int countdown) {
   if (countdown == 0) return -1;
   int i = si, j = sj;
   int step = Integer.MAX_VALUE;
   // search up
   while (i > 0 && map[i - 1][j] == 0) i--;
   if (i != 0) {
     if (map[i - 1][j] == 3) return 1;
     else if (i != si && map[i - 1][j] == 1) {
       map[i - 1][j] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i - 1][j] = 1;
     }
   }
   // search down
   i = si;
   j = sj;
   while (i < H - 1 && map[i + 1][j] == 0) i++;
   if (i != H - 1) {
     if (map[i + 1][j] == 3) return 1;
     if (i != si && map[i + 1][j] == 1) {
       map[i + 1][j] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i + 1][j] = 1;
     }
   }
   // search left
   i = si;
   j = sj;
   while (j > 0 && map[i][j - 1] == 0) j--;
   if (j != 0) {
     if (map[i][j - 1] == 3) return 1;
     if (j != sj && map[i][j - 1] == 1) {
       map[i][j - 1] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i][j - 1] = 1;
     }
   }
   // search right
   i = si;
   j = sj;
   while (j < W - 1 && map[i][j + 1] == 0) j++;
   if (j != W - 1) {
     if (map[i][j + 1] == 3) return 1;
     if (j != sj && map[i][j + 1] == 1) {
       map[i][j + 1] = 0;
       int ret = DFS(i, j, countdown - 1);
       if (ret != -1) step = Math.min(step, ret + 1);
       map[i][j + 1] = 1;
     }
   }
   if (step == Integer.MAX_VALUE) return -1;
   return step;
 }
示例#26
0
  // ParserListener methods
  public void noteEvent(Note note) {
    if (layer >= staves) {
      return;
    }
    // System.out.println(note.getMusicString() + " " + note.getMillisDuration() + " " +
    // note.getDecimalDuration());
    Vector<Chord> currChords = chords[layer];
    Iterator<NotePanel> currNote = currNotes[layer];

    if (!currNote.hasNext()) {
      System.err.println("Received noteEvent, but no PostScript notes are left");
      return;
    }

    if (note.getMillisDuration() > 0) {
      NotePanel notePanel = currNote.next();
      // time the last chord ended
      long tempTime = 0;
      for (int i = currChords.size() - 1; i >= 0; --i) {
        if (!currChords.get(i).isTie()) {
          tempTime = currChords.get(i).getTime() + currChords.get(i).getDuration();
          break;
        }
      }

      if (notePanel.isTie) {
        Chord chord = new Chord();
        // for each note in the last chord, set the next note as a tied note
        for (int i = 0; i < currChords.lastElement().size(); ++i) {
          notePanel.setTie(true).setTime(Math.min(tempTime, time - 1)).setTempo(tempo);
          chord.addNote(notePanel);
          notePanel = currNote.next();
        }
        currChords.add(chord);
      }

      while (notePanel.isRest) {
        notePanel
            .setTime(Math.min(tempTime, time - 1)) // hack, in case the rest should be trimmed
            .setTempo(tempo);
        tempTime += notePanel.getDuration();
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
        // System.out.println("REST: " + notePanel.getMusicString() + " " +
        // notePanel.getDuration());
        notePanel = currNote.next();
      }

      notePanel.setNote(note).setTime(time).setTempo(tempo);
      if (currChords.isEmpty() || currChords.lastElement().getTime() != time) {
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
      } else {
        currChords.lastElement().addNote(notePanel);
      }
    }
  }
示例#27
0
  public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2 = (Graphics2D) g;
    int size =
        Math.min(
            MAX_SIZE,
            Math.min(
                getWidth() - imagePadding.left - imagePadding.right,
                getHeight() - imagePadding.top - imagePadding.bottom));

    g2.translate(getWidth() / 2 - size / 2, getHeight() / 2 - size / 2);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Shape shape;

    if (mode == ColorPicker.SAT || mode == ColorPicker.BRI) {
      shape = new Ellipse2D.Float(0, 0, size, size);
    } else {
      Rectangle r = new Rectangle(0, 0, size, size);
      shape = r;
    }

    if (hasFocus()) {
      PaintUtils.paintFocus(g2, shape, 5);
    }

    if (!(shape instanceof Rectangle)) {
      // paint a circular shadow
      g2.translate(2, 2);
      g2.setColor(new Color(0, 0, 0, 20));
      g2.fill(new Ellipse2D.Float(-2, -2, size + 4, size + 4));
      g2.setColor(new Color(0, 0, 0, 40));
      g2.fill(new Ellipse2D.Float(-1, -1, size + 2, size + 2));
      g2.setColor(new Color(0, 0, 0, 80));
      g2.fill(new Ellipse2D.Float(0, 0, size, size));
      g2.translate(-2, -2);
    }

    g2.drawImage(image, 0, 0, size, size, 0, 0, size, size, null);

    if (shape instanceof Rectangle) {
      Rectangle r = (Rectangle) shape;
      PaintUtils.drawBevel(g2, r);
    } else {
      g2.setColor(new Color(0, 0, 0, 120));
      g2.draw(shape);
    }

    g2.setColor(Color.white);
    g2.setStroke(new BasicStroke(1));
    g2.draw(new Ellipse2D.Float(point.x - 3, point.y - 3, 6, 6));
    g2.setColor(Color.black);
    g2.draw(new Ellipse2D.Float(point.x - 4, point.y - 4, 8, 8));

    g.translate(-imagePadding.left, -imagePadding.top);
  }
示例#28
0
 private void setHoverLocation(
     org.eclipse.swt.widgets.Shell shell, org.eclipse.swt.graphics.Point position) {
   org.eclipse.swt.graphics.Rectangle displayBounds = shell.getDisplay().getBounds();
   org.eclipse.swt.graphics.Rectangle shellBounds = shell.getBounds();
   shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
   shellBounds.y =
       Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0);
   shell.setBounds(shellBounds);
 }
示例#29
0
 {
   final int dpi = ZLibrary.Instance().getDisplayDPI();
   final int x = ZLibrary.Instance().getPixelWidth();
   final int y = ZLibrary.Instance().getPixelHeight();
   final int horMargin = Math.min(dpi / 5, Math.min(x, y) / 30);
   LeftMarginOption = new ZLIntegerRangeOption("Options", "LeftMargin", 0, 100, horMargin);
   RightMarginOption = new ZLIntegerRangeOption("Options", "RightMargin", 0, 100, horMargin);
   TopMarginOption = new ZLIntegerRangeOption("Options", "TopMargin", 0, 100, 0);
   BottomMarginOption = new ZLIntegerRangeOption("Options", "BottomMargin", 0, 100, 4);
 }
示例#30
0
  private void renderDirectionArrow(Graphics g) {
    if (widthArrow < 0) g.setColor(new Color(0, 0, 255, 150));
    else g.setColor(new Color(255, 0, 0, 150));

    g.fillPolygon(
        xPositionsArrow, yPositionsArrow, Math.min(xPositionsArrow.length, yPositionsArrow.length));
    g.setColor(new Color(0, 0, 0, 255));
    g.drawPolygon(
        xPositionsArrow, yPositionsArrow, Math.min(xPositionsArrow.length, yPositionsArrow.length));
  }