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); }
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); }
private static int shortestPath(TreeNode t) { if (t == null) { return 0; } else { return 1 + Math.min(shortestPath(t.left), shortestPath(t.right)); } }
public synchronized void run() { byte[] buffer = new byte[BUFFER_SIZE]; for (; ; ) { try { this.wait(100); } catch (InterruptedException ie) { } int len = 0; try { int noBytes = pin.available(); if (noBytes > 0) { len = pin.read(buffer, 0, Math.min(noBytes, BUFFER_SIZE)); if (len > 0) { jTextArea.append(new String(buffer, 0, len)); jTextArea.setCaretPosition(jTextArea.getText().length()); } } } catch (IOException ioe) { throw new UIError("Unable to read from input stream! " + ioe.getMessage()); } } }
/** * Formats the specified value and enters it in the text field. * * @param value the value to be entered */ public void setValue(double value) { if (!isVisible()) return; if (minValue != null) value = Math.max(value, minValue.doubleValue()); if (maxValue != null) value = Math.min(value, maxValue.doubleValue()); setFormatFor(value); setText(format.format(value)); prevValue = value; }
/** * Called by the paint method to draw the graph and its graph items. * * @param g the graphics context. */ public void paintComponent(Graphics g) { Dimension dim = getSize(); Insets insets = getInsets(); dataArea = new Rectangle( insets.left, insets.top, dim.width - insets.left - insets.right - 1, dim.height - insets.top - insets.bottom - 1); // background if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, dim.width, dim.height); } g.setColor(getForeground()); // get axis tickmarks double xticks[] = xAxis.getTicks(); double yticks[] = yAxis.getTicks(); int yb = dataArea.y + dataArea.height; // draw grid if (showGrid) { g.setColor(gridColor != null ? gridColor : getBackground().darker()); // vertical x grid lines for (int i = 0; i < xticks.length; i += 2) { int x = dataArea.x + (int) Math.round(xticks[i]); g.drawLine(x, dataArea.y, x, dataArea.y + dataArea.height); } // horizontal y grid lines for (int i = 0; i < yticks.length; i += 2) { int y = yb - (int) Math.round(yticks[i]); g.drawLine(dataArea.x, y, dataArea.x + dataArea.width, y); } } for (int i = 0; i < graphItems.size(); i++) { ((GraphItem) graphItems.elementAt(i)).draw(this, g, dataArea, xAxis, yAxis); } if (sPt != null && ePt != null) { g.setColor(getForeground()); g.drawRect( Math.min(sPt.x, ePt.x), Math.min(sPt.y, ePt.y), Math.abs(ePt.x - sPt.x), Math.abs(ePt.y - sPt.y)); } }
/** * Compares two tokens lexicographically. * * @param token first token * @param compare token to be compared * @return 0 if tokens are equal, negative if first token is smaller, positive if first token is * bigger */ public static int diff(final byte[] token, final byte[] compare) { final int tl = token.length; final int cl = compare.length; final int l = Math.min(tl, cl); for (int i = 0; i < l; ++i) { final int c = (token[i] & 0xFF) - (compare[i] & 0xFF); if (c != 0) return c; } return tl - cl; }
public ScientificRenderer(int sigfigs) { sigfigs = Math.min(sigfigs, 6); if (format instanceof DecimalFormat) { String pattern = "0.0"; // $NON-NLS-1$ for (int i = 0; i < sigfigs - 1; i++) { pattern += "0"; // $NON-NLS-1$ } pattern += "E0"; // $NON-NLS-1$ ((DecimalFormat) format).applyPattern(pattern); } }
/** * Return a string that describes the statistics for the top n entries, sorted by descending * order of total time spent dealing with the query. This will always include the totals entry * in the first position. * * @param n the desired number of entries to describe * @return a string describing the statistics for the top n entries */ public synchronized String toStringTop(int n) { StringBuilder out = new StringBuilder(); List<Entry> list = entries(); if (list.isEmpty()) return "<no queries executed>"; Collections.sort(list, TOTAL_TIME_DESCENDING); int maxCountLength = COUNT_FORMAT.format(list.get(0).numQueries).length(); double totalDuration = list.get(0).queryTime; for (Entry entry : list.subList(0, Math.min(n, list.size()))) out.append(entry.toString(maxCountLength, totalDuration)).append('\n'); return out.toString(); }
/** * Returns a partial token. * * @param token input text * @param start start position * @param end end position * @return resulting text */ public static byte[] subtoken(final byte[] token, final int start, final int end) { int s = Math.max(0, start); final int e = Math.min(end, token.length); if (s == 0 && e == token.length) return token; if (s >= e) return EMPTY; int t = Math.max(0, s - 4); for (; t != s && t < e; t += cl(token, t)) { if (t >= s) s = t; } for (; t < e; t += cl(token, t)) ; return Arrays.copyOfRange(token, s, t); }
void animate() { dim = getSize(); size = (int) (Math.min(dim.height, dim.width) / 2.2); timer.tell_time(); if (timer.time_diff == 0) return; // not enought time has passed, dont animate-crach fix dragged_speed = dragged_vec.sub(last_dragged_vec).div(timer.time_diff); last_dragged_vec = dragged_vec; if (dragged_ball != -1) { balls.get2(dragged_ball).pos = dragged_vec.add(find_offset).trim(-1, 1); balls.get2(dragged_ball).speed = dragged_speed; } balls = new WorldAnimate().calc_new_frame(balls, springs, RADIUS, timer); }
void perm(long[] r, int index) { if (index == r.length) { min = Math.min(min, dist(r)); return; } for (int i = index; i < r.length; i++) { long x = r[index]; r[index] = r[i]; r[i] = x; perm(r, index + 1); x = r[index]; r[index] = r[i]; r[i] = x; } }
private int[] getWidths(TableModel tableModel) { int[] widths = new int[tableModel.getColumnCount()]; for (int r = 0; r < Math.min(tableModel.getRowCount(), 500); r++) { // 500 is not for performance, but for using only a sample of data with huge table for (int c = 0; c < tableModel.getColumnCount(); c++) { Object o = tableModel.getValueAt(r, c); if (o instanceof String) { String s = ((String) o).trim(); if (s.length() > widths[c]) widths[c] = s.length(); } } } return widths; }
public CachedProbe(AffyProbe ap, Vector<AffyExperiment> expts) { probe = ap; min = max = 0.0; color = Color.lightGray; stroke = new BasicStroke((float) 2.0); values = new Vector<Double>(); for (AffyExperiment e : expts) { AffyMeasurement am = e.getMeasurement(probe); if (am != null) { values.add(am.getValue()); min = Math.min(am.getValue(), min); max = Math.max(am.getValue(), max); } else { values.add(null); } } }
/** * 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); } }
/** * Returns a string of the specified UTF8 token. * * @param token token * @param start start position * @param length length * @return string */ private static String utf8(final byte[] token, final int start, final int length) { // input is assumed to be correct UTF8. if input contains codepoints // larger than Character.MAX_CODE_POINT, results might be unexpected. final StringBuilder sb = new StringBuilder(length << 1); final int il = Math.min(start + length, token.length); for (int i = start; i < il; i += cl(token, i)) { final int cp = cp(token, i); if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) { sb.append((char) cp); } else { final int o = cp - Character.MIN_SUPPLEMENTARY_CODE_POINT; sb.append((char) ((o >>> 10) + Character.MIN_HIGH_SURROGATE)); sb.append((char) ((o & 0x3ff) + Character.MIN_LOW_SURROGATE)); } } return sb.toString(); }
public void updateCPUInfo(Result result) { if (prevUpTime > 0L && result.upTime > prevUpTime) { // elapsedCpu is in ns and elapsedTime is in ms. long elapsedCpu = result.processCpuTime - prevProcessCpuTime; long elapsedTime = result.upTime - prevUpTime; // cpuUsage could go higher than 100% because elapsedTime // and elapsedCpu are not fetched simultaneously. Limit to // 99% to avoid Plotter showing a scale from 0% to 200%. float cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * result.nCPUs)); getPlotter() .addValues(result.timeStamp, Math.round(cpuUsage * Math.pow(10.0, CPU_DECIMALS))); getInfoLabel() .setText( Resources.format( Messages.CPU_USAGE_FORMAT, String.format("%." + CPU_DECIMALS + "f", cpuUsage))); } this.prevUpTime = result.upTime; this.prevProcessCpuTime = result.processCpuTime; }
/** * Calculates statistical values for a data array. * * @param data the data array * @return the max, min, mean, SD, SE and non-NaN data count */ private double[] getStatistics(double[] data) { double max = -Double.MAX_VALUE; double min = Double.MAX_VALUE; double sum = 0.0; double squareSum = 0.0; int count = 0; for (int i = 0; i < data.length; i++) { if (Double.isNaN(data[i])) { continue; } count++; max = Math.max(max, data[i]); min = Math.min(min, data[i]); sum += data[i]; squareSum += data[i] * data[i]; } double mean = sum / count; double sd = count < 2 ? Double.NaN : Math.sqrt((squareSum - count * mean * mean) / (count - 1)); if (max == -Double.MAX_VALUE) max = Double.NaN; if (min == Double.MAX_VALUE) min = Double.NaN; return new double[] {max, min, mean, sd, sd / Math.sqrt(count), count}; }
public static void drawValueBar( int x, int y, String labelhead, double value, double percentage, int colorindex, Graphics g) { g.setColor(GetColor(colorindex)); g.drawRect(x, y, VALUE_BAR_WIDTH, VALUE_BAR_HEIGHT); int barwidth; if (percentage < 0.0) { // Unknown value barwidth = VALUE_BAR_WIDTH - 1; } else { barwidth = (int) ((VALUE_BAR_WIDTH - 1) * Math.min(1.0, percentage)); } // g.setColor(gradientColor(percentage)); g.fillRect(x + 1, y + 1, barwidth, VALUE_BAR_HEIGHT - 1); if (labelhead != null) { g.setFont(MainFrame.defaultFont); // g.setColor(MainFrame.labelColor); int off = 2; g.drawString(labelhead, x + VALUE_BAR_WIDTH + 2, y + VALUE_BAR_HEIGHT); // off += (labelhead.length()+1) * 4; // Just a guess String maxStr = new String("DateRate [/sec]:"); off += (int) ((maxStr.length() + 1) * 5.5); if (value < 0.0) { g.drawString("?", x + VALUE_BAR_WIDTH + off, y + VALUE_BAR_HEIGHT); } else { if (percentage < 0.0) { g.drawString(format(value), x + VALUE_BAR_WIDTH + off, y + VALUE_BAR_HEIGHT); } else { g.drawString( format(value) + " (" + format(percentage * 100) + "%)", x + VALUE_BAR_WIDTH + off, y + VALUE_BAR_HEIGHT); } } } }
void tell_time() { double time = system_time() - epoch_time; time_diff = Math.min(time - cur_time, .05); cur_time = time; }
/** * Returns a substring of the specified token. Note that this method does not correctly split UTF8 * character; use {@link #subtoken} instead. * * @param token input token * @param start start position * @param end end position * @return substring */ public static byte[] substring(final byte[] token, final int start, final int end) { final int s = Math.max(0, start); final int e = Math.min(end, token.length); if (s == 0 && e == token.length) return token; return s >= e ? EMPTY : Arrays.copyOfRange(token, s, e); }
/** * Sets the size of the shell to it's "packed" size, unless that makes it larger than the monitor * it is being displayed on, in which case just set the shell size to be slightly smaller than the * monitor. */ static void setShellSize(ControlExample instance, Shell shell) { Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); Rectangle monitorArea = shell.getMonitor().getClientArea(); shell.setSize(Math.min(size.x, monitorArea.width), Math.min(size.y, monitorArea.height)); }
/** * Calculates a hash code for the specified token. * * @param token specified token * @return hash code */ public static int hash(final byte[] token) { int h = 0; final int l = Math.min(token.length, MAXLENGTH); for (int i = 0; i != l; ++i) h = (h << 5) - h + token[i]; return h; }
public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); // Draws a white arrow and the principal axis g.drawLine(0, 200, 700, 200); g.drawLine(arrow_x, 200, arrow_x, arrow_y2); // Show coordinates of arrow tip arrowCoordinate_x = arrow_x - startingPosition; arrowCoordinate_x /= 10; arrowCoordinate_y = 200 - arrow_y2; arrowCoordinate_y /= 10; // Coordinates Optics.lbl_arrowCoordinates.setText( "<html>(d<sub>o</sub>, h<sub>o</sub>) = (" + arrowCoordinate_x + ", " + arrowCoordinate_y + ")</html>"); if (arrow_y2 < 200) // if arrow is above principal axis { g.drawLine(arrow_x, arrow_y2, arrow_x - 7, arrow_y2 + 7); g.drawLine(arrow_x, arrow_y2, arrow_x + 7, arrow_y2 + 7); } else if (arrow_y2 > 200) // if arrow is below principal axis { g.drawLine(arrow_x, arrow_y2, arrow_x - 7, arrow_y2 - 7); g.drawLine(arrow_x, arrow_y2, arrow_x + 7, arrow_y2 - 7); } // Draws lines for the grid if (lenses) startingPosition = 350; else { radiusOfCurvature = 20 * focalLength; if (type == 0) startingPosition = 500; else startingPosition = 350; } { for (int i = startingPosition; i <= 700; i += 10) { if ((i - startingPosition) % (10 * focalLength) == 0) { g.setColor(Color.ORANGE); g.drawLine(i, 195, i, 205); } else { g.setColor(Color.WHITE); g.drawLine(i, 197, i, 203); } } for (int i = startingPosition; i >= 0; i -= 10) { if ((i - startingPosition) % (10 * focalLength) == 0 && i != 0) { g.setColor(Color.ORANGE); g.drawLine(i, 195, i, 205); } else { g.setColor(Color.WHITE); g.drawLine(i, 197, i, 203); } } } g.setColor(Color.WHITE); if (lenses) { if (type == 0) // If Converging { // Draws a converging lens g.drawArc(340, 50, 40, 300, 120, 120); g.drawArc(320, 50, 40, 300, 60, -120); // draws horizontal line from the tip of the arrow to the lens (line 1/3) g.setColor(Color.RED); g.drawLine(arrow_x, arrow_y2, 350, arrow_y2); // calculates necessary information to form equation of line from lens to focal point (line // 2/3) dy_1 = 200 - arrow_y2; if (arrow_x > 350) dx_1 = -10 * focalLength; else dx_1 = 10 * focalLength; slope_1 = dy_1 / dx_1; if (arrow_x > 350) y_intercept_1 = 200 - slope_1 * (350 - 10 * focalLength); else y_intercept_1 = 200 - slope_1 * (10 * focalLength + 350); // Calculates coordinates of points on the edge of screen (endpoints) if (arrow_x <= 350) y_screenIntersection_1 = (int) (Math.round(slope_1 * 700 + y_intercept_1)); else y_screenIntersection_1 = (int) (Math.round(y_intercept_1)); if (slope_1 != 0) if (arrow_y2 <= 200) x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1)); else x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1)); if (x_screenIntersection_1 >= 0 && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge if (arrow_y2 <= 200) g.drawLine(350, arrow_y2, x_screenIntersection_1, 400); else g.drawLine(350, arrow_y2, x_screenIntersection_1, 0); else if (arrow_x > 350) g.drawLine(350, arrow_y2, 0, y_screenIntersection_1); else g.drawLine(350, arrow_y2, 700, y_screenIntersection_1); // Else: endpoint is on the y-edge } else // Else: Diverging { // Draws a diverging lens g.drawArc(360, 50, 40, 300, 120, 120); g.drawArc(300, 50, 40, 300, 60, -120); g.drawLine(330, 68, 370, 68); g.drawLine(330, 330, 370, 330); // draws horizontal line from the tip of the arrow to the lens (line 1/3) g.setColor(Color.RED); g.drawLine(arrow_x, arrow_y2, 350, arrow_y2); // calculates necessary information to form equation of line from lens to focal point (line // 2/3) dy_1 = arrow_y2 - 200; if (arrow_x > 350) dx_1 = -10 * focalLength; else dx_1 = 10 * focalLength; slope_1 = dy_1 / dx_1; if (arrow_x > 350) y_intercept_1 = 200 - slope_1 * (10 * focalLength + 350); else y_intercept_1 = 200 - slope_1 * (350 - 10 * focalLength); // Calculates coordinates of points on the edge of screen (endpoints) if (arrow_x <= 350) y_screenIntersection_1 = (int) (Math.round(slope_1 * 700 + y_intercept_1)); else y_screenIntersection_1 = (int) (Math.round(y_intercept_1)); if (slope_1 != 0) if (arrow_y2 <= 200) x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1)); else x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1)); if (x_screenIntersection_1 >= 0 && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge if (arrow_y2 <= 200) g.drawLine(350, arrow_y2, x_screenIntersection_1, 0); else g.drawLine(350, arrow_y2, x_screenIntersection_1, 400); else // Else: endpoint is on the y-edge if (arrow_x > 350) g.drawLine(350, arrow_y2, 0, y_screenIntersection_1); else g.drawLine(350, arrow_y2, 700, y_screenIntersection_1); } // Line 3/3 dy_2 = 200 - arrow_y2; dx_2 = 350 - arrow_x; slope_2 = dy_2 / dx_2; y_intercept_2 = 200 - slope_2 * 350; if (arrow_x <= 350) y_screenIntersection_2 = (int) (Math.round(slope_2 * 700 + y_intercept_2)); else y_screenIntersection_2 = (int) (Math.round(y_intercept_2)); if (slope_2 != 0) if (arrow_y2 <= 200) x_screenIntersection_2 = (int) (Math.round((400 - y_intercept_2) / slope_2)); else x_screenIntersection_2 = (int) (Math.round(-y_intercept_2 / slope_2)); if (x_screenIntersection_2 >= 0 && x_screenIntersection_2 <= 700) // If endpoint is on the x-edge if (arrow_y2 <= 200) g.drawLine(arrow_x, arrow_y2, x_screenIntersection_2, 400); else g.drawLine(arrow_x, arrow_y2, x_screenIntersection_2, 0); else if (arrow_x <= 350) g.drawLine( arrow_x, arrow_y2, 700, y_screenIntersection_2); // Else: endpoint is on the y-edge else g.drawLine(arrow_x, arrow_y2, 0, y_screenIntersection_2); // POI between Line 2 & Line 3 x_pointOfIntersection = (int) ((y_intercept_2 - y_intercept_1) / (slope_1 - slope_2)); y_pointOfIntersection = (int) (slope_1 * x_pointOfIntersection + y_intercept_1); // Draw image g.setColor(Color.ORANGE); g.drawLine(x_pointOfIntersection, 200, x_pointOfIntersection, y_pointOfIntersection); if (y_pointOfIntersection < 200) { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection + 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection + 7); } else { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection - 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection - 7); } // Same side image line continuation if (((x_pointOfIntersection > 350 && arrow_x > 350) || (x_pointOfIntersection < 350 && arrow_x < 350)) && (arrow_x != 350 - 10 * focalLength && arrow_x != 350 + 10 * focalLength || type == 1)) { g.setColor(Color.YELLOW); g.drawLine(x_pointOfIntersection, y_pointOfIntersection, 350, arrow_y2); if (type == 0) g.drawLine(x_pointOfIntersection, y_pointOfIntersection, arrow_x, arrow_y2); } // Mag calculations height_image = 200 - y_pointOfIntersection; height_object = 200 - arrow_y2; if (height_object != 0) magnification = height_image / height_object; if (magnification <= 9999 && magnification >= -9999) Optics.txt_magnification.setText("" + roundTwoDecimals(magnification)); else if (magnification > 9999) { magnification = Double.POSITIVE_INFINITY; Optics.txt_magnification.setText("N/A"); } else { magnification = Double.NEGATIVE_INFINITY; Optics.txt_magnification.setText("N/A"); } // Characteristics g.setColor(Color.ORANGE); g.drawString("Image Characteristics:", 20, 300); if (type == 0) { if ((Math.abs(magnification) > 1 && Math.abs(magnification) < 9999)) g.drawString("Magnification: Enlarged", 20, 320); else if (arrow_x == 350 - 20 * focalLength || arrow_x == 350 + 20 * focalLength || (int) (Math.abs(magnification)) == 1) g.drawString("Magnification: None", 20, 320); else if (Math.abs(magnification) < 1 && Math.abs(magnification) > 0) g.drawString("Magnification: Diminished", 20, 320); else g.drawString("Magnification: N/A", 20, 320); if (arrow_x == 350 - 10 * focalLength || arrow_x == 350 + 10 * focalLength) g.drawString("Orientation: N/A", 20, 335); else if ((arrow_y2 < 200 && y_pointOfIntersection < 200) || (arrow_y2 > 200 && y_pointOfIntersection > 200)) g.drawString("Orientation: Upright", 20, 335); else g.drawString("Orientation: Inverted", 20, 335); if (arrow_x == 350 - 10 * focalLength || arrow_x == 350 + 10 * focalLength) g.drawString("Type: N/A", 20, 350); else if ((x_pointOfIntersection < 350 && arrow_x < 350) || (x_pointOfIntersection > 350 && arrow_x > 350)) g.drawString("Type: Virtual", 20, 350); else g.drawString("Type: Real", 20, 350); } else { g.drawString("Magnification: Diminished", 20, 320); g.drawString("Orientation: Upright", 20, 335); g.drawString("Type: Virtual", 20, 350); } height_image /= 10; if (height_image > 9999 || height_image < -9999) Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>"); else Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= " + height_image + "</html>"); distance_image = x_pointOfIntersection - 350; distance_image /= 10; if (distance_image > 9999 || distance_image < -9999) Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>"); else Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= " + distance_image + "</html>"); } else // Else: mirrors { if (type == 0) // If converging { // draws converging mirror g.drawArc( 500 - 2 * radiusOfCurvature, 200 - radiusOfCurvature, 2 * radiusOfCurvature, 2 * radiusOfCurvature, 60, -120); // draws horizontal line from the tip of the arrow to the lens (line 1/4) g.setColor(Color.RED); x_arcIntersection_1 = (int) ((Math.sqrt(Math.abs(Math.pow(radiusOfCurvature, 2) - Math.pow(arrow_y2 - 200, 2)))) + (500 - radiusOfCurvature)); g.drawLine(arrow_x, arrow_y2, x_arcIntersection_1, arrow_y2); // line 2/4 dy_1 = arrow_y2 - 200; dx_1 = x_arcIntersection_1 - (500 - focalLength * 10); slope_1 = dy_1 / dx_1; y_intercept_1 = 200 - slope_1 * (500 - focalLength * 10); // Calculates coordinates of points on the edge of screen (endpoints) y_screenIntersection_1 = (int) (Math.round(y_intercept_1)); if (slope_1 != 0) if (arrow_y2 <= 200) x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1)); else x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1)); if (x_screenIntersection_1 >= 0 && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge if (arrow_y2 <= 200) g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 400); else g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 0); else g.drawLine( x_arcIntersection_1, arrow_y2, 0, y_screenIntersection_1); // Else: endpoint is on the y-edge // line 3/4 if (!(arrow_x > 495 - focalLength * 10 && arrow_x < 505 - focalLength * 10)) { dy_2 = 200 - arrow_y2; dx_2 = (500 - 10 * focalLength) - arrow_x; slope_2 = dy_2 / dx_2; y_intercept_2 = arrow_y2 - slope_2 * arrow_x; quadratic_a = (float) (Math.pow(slope_2, 2) + 1); quadratic_b = (float) (((2 * slope_2 * y_intercept_2) - (400 * slope_2) + ((radiusOfCurvature - 500) * 2))); quadratic_c = (float) ((Math.pow(y_intercept_2, 2) - Math.pow(radiusOfCurvature, 2) - (400 * y_intercept_2) + 40000 + Math.pow((radiusOfCurvature - 500), 2))); discriminant = (float) (Math.pow(quadratic_b, 2) - (4 * quadratic_a * quadratic_c)); if (discriminant >= 0) x_arcIntersection_2 = (int) (Math.max( ((-quadratic_b + Math.sqrt(discriminant)) / (2 * quadratic_a)), ((-quadratic_b - Math.sqrt(discriminant)) / (2 * quadratic_a)))); else System.out.println("Error, imaginary root!"); y_arcIntersection_2 = (int) (slope_2 * x_arcIntersection_2 + y_intercept_2); g.drawLine(arrow_x, arrow_y2, x_arcIntersection_2, y_arcIntersection_2); // System.out.println ("slope: " + slope_2 + "\n yintercept: " + y_intercept_2 + "\n // quadratic-a: " + quadratic_a + "\n quadratic-b: " + quadratic_b + "\n quadratic_c: " + // quadratic_c + "\n discriminant: " + discriminant + "\n xarcintersection2: " + // x_arcIntersection_2 + "\n yarcintersection2: " + y_arcIntersection_2); // line 4/4 g.drawLine(x_arcIntersection_2, y_arcIntersection_2, 0, y_arcIntersection_2); // POI between line 2 and line 4 x_pointOfIntersection = (int) ((y_arcIntersection_2 - y_intercept_1) / slope_1); y_pointOfIntersection = y_arcIntersection_2; g.setColor(Color.ORANGE); g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection, 200); if (y_pointOfIntersection < 200) { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection + 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection + 7); } else { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection - 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection - 7); } // Same side image line continuation if (arrow_x > 500 - 10 * focalLength) { g.setColor(Color.YELLOW); g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_1, arrow_y2); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_2, y_arcIntersection_2); } } } else // Diverging { // draws converging mirror g.drawArc( 350, 200 - radiusOfCurvature, 2 * radiusOfCurvature, 2 * radiusOfCurvature, 120, 120); // draws horizontal line from the tip of the arrow to the lens (line 1/4) g.setColor(Color.RED); x_arcIntersection_1 = (int) (-(Math.sqrt(Math.pow(radiusOfCurvature, 2) - Math.pow(arrow_y2 - 200, 2))) + (350 + radiusOfCurvature)); g.drawLine(arrow_x, arrow_y2, x_arcIntersection_1, arrow_y2); // line 2/4 dy_1 = arrow_y2 - 200; dx_1 = x_arcIntersection_1 - (350 + focalLength * 10); slope_1 = dy_1 / dx_1; y_intercept_1 = 200 - slope_1 * (350 + focalLength * 10); // Calculates coordinates of points on the edge of screen (endpoints) y_screenIntersection_1 = (int) (Math.round(y_intercept_1)); if (slope_1 != 0) if (arrow_y2 <= 200) x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1)); else if (arrow_y2 > 200) x_screenIntersection_1 = (int) (Math.round(400 - y_intercept_1 / slope_1)); if (x_screenIntersection_1 >= 0 && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge if (arrow_y2 <= 200) g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 0); else g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 400); else g.drawLine( x_arcIntersection_1, arrow_y2, 0, y_screenIntersection_1); // Else: endpoint is on the y-edge // line 3/4 dy_2 = 200 - arrow_y2; dx_2 = (350 + 10 * focalLength) - arrow_x; slope_2 = dy_2 / dx_2; y_intercept_2 = arrow_y2 - slope_2 * arrow_x; quadratic_a = (float) (Math.pow(slope_2, 2) + 1); quadratic_b = (float) ((2 * slope_2 * y_intercept_2) - (400 * slope_2) - (2 * radiusOfCurvature + 700)); quadratic_c = (float) ((Math.pow(y_intercept_2, 2) - Math.pow(radiusOfCurvature, 2) - (400 * y_intercept_2) + 40000 + Math.pow((radiusOfCurvature + 350), 2))); discriminant = (float) (Math.pow(quadratic_b, 2) - (4 * quadratic_a * quadratic_c)); if (discriminant >= 0) x_arcIntersection_2 = (int) (Math.min( ((-quadratic_b + Math.sqrt(discriminant)) / (2 * quadratic_a)), ((-quadratic_b - Math.sqrt(discriminant)) / (2 * quadratic_a)))); else System.out.println("Error, imaginary root!"); y_arcIntersection_2 = (int) (slope_2 * x_arcIntersection_2 + y_intercept_2); g.drawLine(arrow_x, arrow_y2, x_arcIntersection_2, y_arcIntersection_2); // System.out.println ("slope: " + slope_2 + "\n yintercept: " + y_intercept_2 + "\n // quadratic-a: " + quadratic_a + "\n quadratic-b: " + quadratic_b + "\n quadratic_c: " + // quadratic_c + "\n discriminant: " + discriminant + "\n xarcintersection2: " + // x_arcIntersection_2 + "\n yarcintersection2: " + y_arcIntersection_2); // line 4/4 g.drawLine(x_arcIntersection_2, y_arcIntersection_2, 0, y_arcIntersection_2); // POI between line 2 and line 4 x_pointOfIntersection = (int) ((y_arcIntersection_2 - y_intercept_1) / slope_1); y_pointOfIntersection = y_arcIntersection_2; g.setColor(Color.ORANGE); g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection, 200); if (y_pointOfIntersection < 200) { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection + 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection + 7); } else { g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection - 7, y_pointOfIntersection - 7); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection + 7, y_pointOfIntersection - 7); } // Same side image line continuation g.setColor(Color.YELLOW); g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_1, arrow_y2); g.drawLine( x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_2, y_arcIntersection_2); } // Mag calculations height_image = 200 - y_pointOfIntersection; height_object = 200 - arrow_y2; if (height_object != 0) magnification = height_image / height_object; if (magnification <= 9999 && magnification >= -9999) Optics.txt_magnification.setText("" + roundTwoDecimals(magnification)); else if (magnification > 9999) { magnification = Double.POSITIVE_INFINITY; Optics.txt_magnification.setText("N/A"); } else { magnification = Double.NEGATIVE_INFINITY; Optics.txt_magnification.setText("N/A"); } // Characteristics g.setColor(Color.ORANGE); g.drawString("Image Characteristics:", 20, 300); if (type == 0) { if ((Math.abs(magnification) > 1 && Math.abs(magnification) < 9999) && arrow_x != 500 - 10 * focalLength) g.drawString("Magnification: Enlarged", 20, 320); else if ((int) (Math.abs(magnification)) == 1) g.drawString("Magnification: None", 20, 320); else if (Math.abs(magnification) < 1 && Math.abs(magnification) > 0) g.drawString("Magnification: Diminished", 20, 320); else { g.drawString("Magnification: N/A", 20, 320); Optics.txt_magnification.setText("N/A"); Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>"); Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>"); } if (arrow_x == 500 - 10 * focalLength) g.drawString("Orientation: N/A", 20, 335); else if ((arrow_y2 < 200 && y_pointOfIntersection < 200) || (arrow_y2 > 200 && y_pointOfIntersection > 200)) g.drawString("Orientation: Upright", 20, 335); else g.drawString("Orientation: Inverted", 20, 335); if (arrow_x == 500 - 10 * focalLength) g.drawString("Type: N/A", 20, 350); else if (x_pointOfIntersection < 500 && arrow_x < 500) g.drawString("Type: Real", 20, 350); else if (x_pointOfIntersection > 500 && arrow_x < 500) g.drawString("Type: Virtual", 20, 350); } else { g.drawString("Magnification: Diminished", 20, 320); g.drawString("Orientation: Upright", 20, 335); g.drawString("Type: Virtual", 20, 350); } height_image /= 10; if (height_image > 9999 || height_image < -9999 || arrow_x == 500 - 10 * focalLength) Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>"); else Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= " + height_image + "</html>"); if (type == 0) distance_image = x_pointOfIntersection - 500; else distance_image = x_pointOfIntersection - 350; distance_image /= 10; if (distance_image > 9999 || distance_image < -9999 || arrow_x == 500 - 10 * focalLength) Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>"); else Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= " + distance_image + "</html>"); } }
public Main() { try { in = new BufferedReader(new InputStreamReader(System.in)); // minimum distance from D to K int numCities = nextInt(); int tradeRoutes = nextInt(); int[][] adjacencyMatrix = new int[numCities][numCities]; int[] minDistance = new int[numCities]; Arrays.fill(minDistance, 100000000); // Arrays.fill(adjacencyMatrix, -1); // int [] pencilCosts = new int[ Node[] cities = new Node[numCities]; for (int x = 0; x < tradeRoutes; x++) { int cityA = nextInt() - 1; int cityB = nextInt() - 1; int cost = nextInt(); if (cities[cityA] == null) cities[cityA] = new Node(cityA); if (cities[cityB] == null) cities[cityB] = new Node(cityB); adjacencyMatrix[cityA][cityB] = cost; adjacencyMatrix[cityB][cityA] = cost; // cities[cityA].routes.add(new Edge(cost, cities[cityB])); // cities[cityB].routes.add(new Edge(cost, cities[cityA])); } int numStores = nextInt(); int[] pencilCosts = new int[numCities]; Arrays.fill(pencilCosts, -1); for (int x = 0; x < numStores; x++) { int ID = nextInt() - 1; int cost = nextInt(); pencilCosts[ID] = cost; } int destination = nextInt() - 1; // if (isGood[destination]){ // } int minCost = 100000000; Queue<Node> Q = new LinkedList<Node>(); // PriorityQueue<Node> Q = new PriorityQueue<Node>(); minDistance[destination] = 0; // cities[destination].distance = 0; Q.offer(cities[destination]); while (!Q.isEmpty()) { Node temp = Q.poll(); for (int x = 0; x < numCities; x++) { if (adjacencyMatrix[temp.ID][x] != 0 && (minDistance[x] == 100000000 || minDistance[x] > minDistance[temp.ID] + adjacencyMatrix[temp.ID][x])) { minDistance[x] = minDistance[temp.ID] + adjacencyMatrix[temp.ID][x]; if (pencilCosts[x] != -1 && minDistance[x] < minCost) { // System.out.println(minCost); minCost = Math.min(minDistance[x] + pencilCosts[x], minCost); Q.offer(cities[x]); } else { if (pencilCosts[x] == -1) { // why> Q.offer(cities[x]); } } // Q.offer(temp.routes.get(x).destination); } } } for (int x = 0; x < numCities; x++) { if (pencilCosts[x] != -1 && pencilCosts[x] + minDistance[x] < minCost && minDistance[x] != 100000000) { minCost = minDistance[x] + pencilCosts[x]; } } System.out.println(minCost); } catch (IOException e) { System.out.println("IO: General"); } }
static ItemResult extractItemInfo(Element curItem) { ItemResult item = new ItemResult(); // get the item columns String itemId = getAttributeText(curItem, "ItemID"); String name = getElementTextByTagNameNR(curItem, "Name"); String currently = getElementTextByTagNameNR(curItem, "Currently"); // get Buy_Price, just put in the "" if it doesn't exist. String buyPrice = getElementTextByTagNameNR(curItem, "Buy_Price"); // get First_Bid, just put in the "" if it doesn't exist. String firstBid = getElementTextByTagNameNR(curItem, "First_Bid"); String numberOfBids = getElementTextByTagNameNR(curItem, "Number_of_Bids"); String started = convertToSQLTime(getElementTextByTagNameNR(curItem, "Started")); String ends = convertToSQLTime(getElementTextByTagNameNR(curItem, "Ends")); Element locationElem = getElementByTagNameNR(curItem, "Location"); String latitude = getAttributeText(locationElem, "Latitude"); String longitude = getAttributeText(locationElem, "Longitude"); String location = getElementText(locationElem); String country = getElementTextByTagNameNR(curItem, "Country"); String description = getElementTextByTagNameNR(curItem, "Description"); description = description.substring(0, Math.min(description.length(), 4000)); Element sellerElem = getElementByTagNameNR(curItem, "Seller"); String sellerId = getAttributeText(sellerElem, "UserID"); String sellerRating = getAttributeText(sellerElem, "Rating"); // for each itemCategory Element[] categoriesElem = getElementsByTagNameNR(curItem, "Category"); ArrayList<String> categoriesArrayList = new ArrayList<String>(); for (Element category : categoriesElem) { categoriesArrayList.add(getElementText(category)); } String[] categories = new String[categoriesArrayList.size()]; categories = categoriesArrayList.toArray(categories); // for each bid Element bidsElem = getElementByTagNameNR(curItem, "Bids"); Element[] bidElemList = getElementsByTagNameNR(bidsElem, "Bid"); ArrayList<BidResult> bidsArrayList = new ArrayList<BidResult>(); for (Element bid : bidElemList) { // process the user (bidder) first Element bidderElem = getElementByTagNameNR(bid, "Bidder"); String bidderId = getAttributeText(bidderElem, "UserID"); String bidderRating = getAttributeText(bidderElem, "Rating"); String bidderLocation = getElementTextByTagNameNR(bidderElem, "Location"); String bidderCountry = getElementTextByTagNameNR(bidderElem, "Country"); String bidTime = getElementTextByTagNameNR(bid, "Time"); String amount = getElementTextByTagNameNR(bid, "Amount"); BidResult bidResult = new BidResult(bidderId, bidderRating, bidderLocation, bidderCountry, amount, bidTime); bidsArrayList.add(bidResult); } BidResult[] bidResults = new BidResult[bidsArrayList.size()]; bidResults = bidsArrayList.toArray(bidResults); return new ItemResult( itemId, name, categories, currently, buyPrice, firstBid, numberOfBids, bidResults, longitude, latitude, location, country, started, ends, sellerId, sellerRating, description); }
double trim(double x, double min_value, double max_value) { return Math.min(Math.max(x, min_value), max_value); }
static void processItem(Element curItem) { String itemRow = ""; // get the item columns String itemID = getAttributeText(curItem, "ItemID"); itemRow += itemID + ","; String name = getElementTextByTagNameNR(curItem, "Name"); itemRow += wrapQuotations(name) + ","; // get Buy_Price, just put in the "" if it doesn't exist. String buyPrice = strip(getElementTextByTagNameNR(curItem, "Buy_Price")); if (!buyPrice.equals("")) itemRow += buyPrice + ","; else itemRow += "NULL,"; // get First_Bid, just put in the "" if it doesn't exist. String firstBid = strip(getElementTextByTagNameNR(curItem, "First_Bid")); itemRow += firstBid + ","; String started = convertToSQLTime(getElementTextByTagNameNR(curItem, "Started")); itemRow += wrapQuotations(started) + ","; String ends = convertToSQLTime(getElementTextByTagNameNR(curItem, "Ends")); itemRow += wrapQuotations(ends) + ","; Element locationElem = getElementByTagNameNR(curItem, "Location"); String latitude = getAttributeText(locationElem, "Latitude"); itemRow += wrapQuotations(latitude) + ","; String longitude = getAttributeText(locationElem, "Longitude"); itemRow += wrapQuotations(longitude) + ","; String location = getElementText(locationElem); itemRow += wrapQuotations(location) + ","; String country = getElementTextByTagNameNR(curItem, "Country"); itemRow += wrapQuotations(country) + ","; String description = getElementTextByTagNameNR(curItem, "Description"); description = description.substring(0, Math.min(description.length(), 4000)); itemRow += wrapQuotations(description) + ","; Element sellerElem = getElementByTagNameNR(curItem, "Seller"); String sellerID = getAttributeText(sellerElem, "UserID"); itemRow += wrapQuotations(sellerID); String sellerRating = getAttributeText(sellerElem, "Rating"); // check if this seller already exists in our hashtable String sellerRow[] = userList.get(sellerID); if (sellerRow == null) { sellerRow = new String[5]; sellerRow[0] = sellerID; sellerRow[1] = "NULL"; sellerRow[2] = sellerRating; sellerRow[3] = "NULL"; sellerRow[4] = "NULL"; userList.put(sellerID, sellerRow); } else { sellerRow[2] = sellerRating; // if(sellerRow[1] != null) // bothSellerAndBuyer.add(sellerID); } // String sellerRow = wrapQuotations(seller) + "," + wrapQuotations(sellerRating); // System.out.println("itemid: " + itemID); // System.out.println("name: " + name); // System.out.println("buy_Price: " + buyPrice); // System.out.println("started: " + started); // System.out.println("ends: " + ends); // System.out.println("location: " + location); // System.out.println("latitude: " + latitude); // System.out.println("longitude: " + longitude); // System.out.println("country: " + country); // System.out.println("description: " + description); // System.out.println("seller ID: " + seller); // System.out.println("SQL line: " + itemRow); // System.out.println("seller rating: " + sellerRating); // for each itemCategory Element[] categories = getElementsByTagNameNR(curItem, "Category"); for (Element category : categories) { String categoryName = getElementText(category); String categoryRow = wrapQuotations(itemID) + "," + wrapQuotations(categoryName); writeLine(itemCategoriesWriter, categoryRow); } // for each bid Element bidsElem = getElementByTagNameNR(curItem, "Bids"); Element[] bids = getElementsByTagNameNR(bidsElem, "Bid"); for (Element bid : bids) { // process the user (bidder) first Element bidderElem = getElementByTagNameNR(bid, "Bidder"); String bidderID = getAttributeText(bidderElem, "UserID"); String bidderRating = getAttributeText(bidderElem, "Rating"); String bidderLocation = getElementTextByTagNameNR(bidderElem, "Location"); String bidderCountry = getElementTextByTagNameNR(bidderElem, "Country"); String bidderRow[] = userList.get(bidderID); if (bidderRow == null) { bidderRow = new String[5]; bidderRow[0] = bidderID; bidderRow[1] = bidderRating; bidderRow[2] = "NULL"; bidderRow[3] = bidderLocation; bidderRow[4] = bidderCountry; userList.put(bidderID, bidderRow); } else { bidderRow[1] = bidderRating; bidderRow[3] = bidderLocation; bidderRow[4] = bidderCountry; // if(!bidderRow[2].equals("NULL")) // bothSellerAndBuyer.add(bidderID); } String bidTime = convertToSQLTime(getElementTextByTagNameNR(bid, "Time")); String amount = strip(getElementTextByTagNameNR(bid, "Amount")); String bidRow = wrapQuotations(bidderID) + "," + itemID + "," + wrapQuotations(bidTime) + "," + wrapQuotations(amount); writeLine(bidWriter, bidRow); } writeLine(itemWriter, itemRow); // System.out.println("--------END ITEM PROCESS---------"); }
/** * Sets the default point index. This defines the index of the points array used to get the point * initially selected when the step is created. * * @param index the index */ public void setDefaultPointIndex(int index) { index = Math.min(index, points.length - 1); defaultIndex = Math.max(0, index); }