file_id
int64 1
250k
| content
stringlengths 0
562k
| repo
stringlengths 6
115
| path
stringlengths 1
147
|
---|---|---|---|
247,609 | //----------------------------------------------------------------------------
// SortedABPriQ.java by Dale/Joyce/Weems Chapter 9
// Priority Queue using a Sorted Array
//
// Two constructors are provided: one that use the natural order of the
// elements as defined by their compareTo method and one that uses an
// ordering based on a comparator argument.
//
// Null elements are not allowed. Duplicate elements are allowed.
//----------------------------------------------------------------------------
import java.util.Comparator;
public class SortedABPriQ<T> implements PriQueueInterface<T>
{
protected final int DEFCAP = 100; // default capacity
protected T[] elements; // array to hold priority queue�s elements
protected int numElements = 0; // number of elements in this priority queue
protected Comparator<T> comp;
public SortedABPriQ()
// Precondition: T implements Comparable
{
elements = (T[]) new Object[DEFCAP];
comp = new Comparator<T>()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public SortedABPriQ(Comparator<T> comp)
{
elements = (T[]) new Object[DEFCAP];
this.comp = comp;
}
protected void enlarge()
// Increments the capacity of the priority queue by an amount
// equal to the original capacity.
{
// Create the larger array.
T[] larger = (T[]) new Object[elements.length + DEFCAP];
// Copy the contents from the smaller array into the larger array.
for (int i = 0; i < numElements; i++)
{
larger[i] = elements[i];
}
// Reassign priority queue reference.
elements = larger;
}
public void enqueue(T element)
// Adds element to this priority queue.
{
if (numElements == elements.length)
enlarge();
int index = numElements;
while ((index > 0) && (comp.compare(elements[index - 1], element) > 0))
{
elements[index] = elements[index - 1];
index--;
}
elements[index] = element;
numElements++;
}
public T dequeue()
// Throws PriQUnderflowException if this priority queue is empty;
// otherwise, removes element with highest priority from this
// priority queue and returns it.
{
if (!isEmpty())
{
T temp = elements[numElements - 1];
elements[numElements - 1] = null;
numElements--;
return temp;
}
else
throw new PriQUnderflowException("dequeue attempted on an empty priority queue.");
}
public int size()
// Returns the number of elements on this priority queue.
{
return numElements;
}
public boolean isEmpty()
// Returns true if this priority queue is empty; otherwise, returns false.
{
return (numElements == 0);
}
public boolean isFull()
// This priority queue is unbounded so always returns false.
{
return false;
}
public String toString()
// Returns a nicely formatted string that represents this priority queue.
{
String temp = "\nPriority Queue: ";
for (int i = 0; i < numElements; i++)
temp = temp + " " + elements[i];
temp = temp + "\n";
return temp;
}
}
| Faizaan790/Flight_Path | src/SortedABPriQ.java |
247,610 | package Lecture19;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
class CirclePane extends StackPane {
private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge() {
circle.setRadius(circle.getRadius() + 2);
}
public void shrink() {
circle.setRadius(circle.getRadius() > 2 ?
circle.getRadius() - 2 : circle.getRadius());
}
} | AhmadAlzhrani/OOP | Motion/circlePane.java |
247,611 | package map;
import java.util.Arrays;
import java.util.Random;
import util.Vector2f;
public strictfp class BinaryMask {
private boolean[][] mask;
private final Random random;
private final Symmetry symmetry = Symmetry.POINT;
public BinaryMask(int size, long seed) {
mask = new boolean[size][size];
random = new Random(seed);
}
public BinaryMask(BinaryMask mask, long seed) {
this.mask = new boolean[mask.getSize()][mask.getSize()];
for (int y = 0; y < mask.getSize(); y++) {
for (int x = 0; x < mask.getSize(); x++) {
this.mask[x][y] = mask.get(x, y);
}
}
random = new Random(seed);
}
public BinaryMask(boolean[][] mask, long seed) {
this.mask = mask;
random = new Random(seed);
}
public int getSize() {
return mask[0].length;
}
public boolean get(int x, int y) {
return mask[x][y];
}
private void applySymmetry() {
switch (symmetry) {
case POINT:
for (int y = 0; y < getSize() / 2; y++) {
for (int x = 0; x < getSize(); x++) {
mask[getSize() - x - 1][getSize() - y - 1] = mask[x][y];
}
}
break;
default:
break;
}
}
public BinaryMask randomize(float density) {
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
mask[x][y] = random.nextFloat() < density;
}
}
applySymmetry();
return this;
}
public BinaryMask invert() {
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
mask[x][y] = !mask[x][y];
}
}
return this;
}
public BinaryMask enlarge(int size) {
boolean[][] largeMask = new boolean[size][size];
int smallX;
int smallY;
for (int y = 0; y < size; y++) {
smallY = StrictMath.min(y / (size / getSize()), getSize() - 1);
for (int x = 0; x < size; x++) {
smallX = StrictMath.min(x / (size / getSize()), getSize() - 1);
largeMask[x][y] = mask[smallX][smallY];
}
}
mask = largeMask;
return this;
}
public BinaryMask shrink(int size) {
boolean[][] smallMask = new boolean[size][size];
int largeX;
int largeY;
for (int y = 0; y < size; y++) {
largeY = (y * getSize()) / size + (getSize() / size / 2);
if (largeY >= getSize())
largeY = getSize() - 1;
for (int x = 0; x < size; x++) {
largeX = (x * getSize()) / size + (getSize() / size / 2);
if (largeX >= getSize())
largeX = getSize() - 1;
smallMask[x][y] = mask[largeX][largeY];
}
}
mask = smallMask;
return this;
}
public BinaryMask inflate(float radius) {
return deflate(-radius);
}
public BinaryMask deflate(float radius) {
boolean[][] maskCopy = new boolean[getSize()][getSize()];
boolean inverted = radius <= 0;
Thread[] threads = new Thread[4];
threads[0] = new Thread(() -> deflateRegion(inverted, StrictMath.abs(radius), maskCopy, 0, (getSize() / 4)));
threads[1] = new Thread(() -> deflateRegion(inverted, StrictMath.abs(radius), maskCopy, (getSize() / 4), (getSize() / 2)));
threads[2] = new Thread(() -> deflateRegion(inverted, StrictMath.abs(radius), maskCopy, (getSize() / 2), (getSize() / 4) * 3));
threads[3] = new Thread(() -> deflateRegion(inverted, StrictMath.abs(radius), maskCopy, (getSize() / 4) * 3, getSize()));
Arrays.stream(threads).forEach(Thread::start);
for (Thread f : threads) {
try {
f.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mask = maskCopy;
return this;
}
private void deflateRegion(boolean inverted, float radius, boolean[][] maskCopy, int startY, int endY) {
float radius2 = (radius + 0.5f) * (radius + 0.5f);
for (int y = startY; y < endY; y++) {
for (int x = 0; x < getSize(); x++) {
maskCopy[x][y] = !inverted;
l: for (int y2 = (int) (y - radius); y2 < y + radius + 1; y2++) {
for (int x2 = (int) (x - radius); x2 < x + radius + 1; x2++) {
if (x2 >= 0 && y2 >= 0 && x2 < getSize() && y2 < getSize() && (x - x2) * (x - x2) + (y - y2) * (y - y2) <= radius2 && inverted ^ !mask[x2][y2]) {
maskCopy[x][y] = inverted;
break l;
}
}
}
}
}
}
public BinaryMask cutCorners() {
int size = mask[0].length;
boolean[][] maskCopy = new boolean[size][size];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
int count = 0;
if (x > 0 && !mask[x - 1][y])
count++;
if (y > 0 && !mask[x][y - 1])
count++;
if (x < size - 1 && !mask[x + 1][y])
count++;
if (y < size - 1 && !mask[x][y + 1])
count++;
if (count > 1)
maskCopy[x][y] = false;
else
maskCopy[x][y] = mask[x][y];
}
}
mask = maskCopy;
return this;
}
public BinaryMask acid(float strength) {
boolean[][] maskCopy = new boolean[getSize()][getSize()];
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
if (((x > 0 && !mask[x - 1][y]) || (y > 0 && !mask[x][y - 1]) || (x < getSize() - 1 && !mask[x + 1][y]) || (y < getSize() - 1 && !mask[x][y + 1])) && random.nextFloat() < strength)
maskCopy[x][y] = false;
else
maskCopy[x][y] = mask[x][y];
}
}
mask = maskCopy;
applySymmetry();
return this;
}
public BinaryMask outline() {
boolean[][] maskCopy = new boolean[getSize()][getSize()];
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
maskCopy[x][y] = ((x > 0 && !mask[x - 1][y])
|| (y > 0 && !mask[x][y - 1])
|| (x < getSize() - 1 && !mask[x + 1][y])
|| (y < getSize() - 1 && !mask[x][y + 1]))
&& ((x > 0 && mask[x - 1][y])
|| (y > 0 && mask[x][y - 1])
|| (x < getSize() - 1 && mask[x + 1][y])
|| (y < getSize() - 1 && mask[x][y + 1]));
}
}
mask = maskCopy;
applySymmetry();
return this;
}
public BinaryMask smooth(float radius) {
boolean[][] maskCopy = new boolean[getSize()][getSize()];
Thread[] threads = new Thread[4];
threads[0] = new Thread(() -> smoothRegion(radius, maskCopy, 0, (getSize() / 4)));
threads[1] = new Thread(() -> smoothRegion(radius, maskCopy, (getSize() / 4), (getSize() / 2)));
threads[2] = new Thread(() -> smoothRegion(radius, maskCopy, (getSize() / 2), (getSize() / 4) * 3));
threads[3] = new Thread(() -> smoothRegion(radius, maskCopy, (getSize() / 4) * 3, getSize()));
Arrays.stream(threads).forEach(Thread::start);
for (Thread f : threads) {
try {
f.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mask = maskCopy;
return this;
}
private void smoothRegion(float radius, boolean[][] maskCopy, int startY, int endY) {
float radius2 = (radius + 0.5f) * (radius + 0.5f);
for (int y = startY; y < endY; y++) {
for (int x = 0; x < getSize(); x++) {
int count = 0;
int count2 = 0;
for (int y2 = (int) (y - radius); y2 <= y + radius; y2++) {
for (int x2 = (int) (x - radius); x2 <= x + radius; x2++) {
if (x2 > 0 && y2 > 0 && x2 < getSize() && y2 < getSize() && (x - x2) * (x - x2) + (y - y2) * (y - y2) <= radius2) {
count++;
if (mask[x2][y2])
count2++;
}
}
}
if (count2 > count / 2) {
maskCopy[x][y] = true;
}
}
}
}
public BinaryMask combine(BinaryMask other) {
int size = Math.max(getSize(), other.getSize());
if (getSize() != size)
enlarge(size);
if (other.getSize() != size)
other.enlarge(size);
boolean[][] maskCopy = new boolean[getSize()][getSize()];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
maskCopy[x][y] = get(x, y) || other.get(x, y);
}
}
mask = maskCopy;
return this;
}
public BinaryMask intersect(BinaryMask other) {
int size = Math.max(getSize(), other.getSize());
if (getSize() != size)
enlarge(size);
if (other.getSize() != size)
other.enlarge(size);
boolean[][] maskCopy = new boolean[getSize()][getSize()];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
maskCopy[x][y] = get(x, y) && other.get(x, y);
}
}
mask = maskCopy;
return this;
}
public BinaryMask minus(BinaryMask other) {
int size = Math.max(getSize(), other.getSize());
if (getSize() != size)
enlarge(size);
if (other.getSize() != size)
other.enlarge(size);
boolean[][] maskCopy = new boolean[getSize()][getSize()];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
maskCopy[x][y] = get(x, y) && !other.get(x, y);
}
}
mask = maskCopy;
return this;
}
public BinaryMask fillCircle(float x, float y, float radius, boolean value) {
int ex = (int) StrictMath.min(getSize(), x + radius);
int ey = (int) StrictMath.min(getSize(), y + radius);
float dx;
float dy;
float radius2 = radius * radius;
for (int cy = (int) StrictMath.max(0, y - radius); cy < ey; cy++) {
for (int cx = (int) StrictMath.max(0, x - radius); cx < ex; cx++) {
dx = x - cx;
dy = y - cy;
if (dx * dx + dy * dy <= radius2) {
mask[cx][cy] = value;
}
}
}
return this;
}
public BinaryMask trimEdge(int rimWidth) {
for (int a = 0; a < rimWidth; a++) {
for (int b = 0; b < getSize() - rimWidth; b++) {
mask[a][b] = false;
mask[getSize() - 1 - a][getSize() - 1 - b] = false;
mask[b][getSize() - 1 - a] = false;
mask[getSize() - 1 - b][a] = false;
}
}
return this;
}
public Vector2f getRandomPosition(){
int cellCount = 0;
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
if(mask[x][y])
cellCount++;
}
}
if(cellCount == 0)
return null;
int cell = random.nextInt(cellCount) + 1;
cellCount = 0;
for (int y = 0; y < getSize(); y++) {
for (int x = 0; x < getSize(); x++) {
if(mask[x][y])
cellCount++;
if(cellCount == cell)
return new Vector2f(x,y);
}
}
return null;
}
}
| muellni/Neroxis-Map-Generator | src/map/BinaryMask.java |
247,612 |
class Text implements Resizable
{
private final Double DEFAULT_SIZE = 10.0;
private Colour colour;
private Double fontSize;
private String text;
public Text(String text) {
this.text = text;
fontSize = DEFAULT_SIZE;
}
public Double getFontSize(){
return fontSize;
}
public void setColour(String s){
colour = new Colour(s);
}
public void setText(String newText){
text = newText;
}
public String getText(){
return text ;
}
@Override
public String toString() {
return (text);
}
public void shrink(double n) throws SizeFactorException {
if (n < LIMIT) {
throw new SizeFactorException();
}
fontSize /= n;
}
public void enlarge(double n) throws SizeFactorException {
if (n < LIMIT) {
throw new SizeFactorException();
}
fontSize *= n;
}
}
| DeflateAwning/ENSF-409-Labs | Lab5/Lab5Ex2/src/Text.java |
247,613 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ControlBall extends JFrame {
private JButton jbtEnlarge = new JButton("Enlarge");
private JButton jbtShrink = new JButton("Shrink");
private BallCanvas canvas = new BallCanvas();
public ControlBall() {
JPanel panel = new JPanel(); // Use the panel to group buttons
panel.add(jbtEnlarge);
panel.add(jbtShrink);
this.add(canvas, BorderLayout.CENTER); // Add canvas to center
this.add(panel, BorderLayout.SOUTH); // Add buttons to the frame
jbtEnlarge.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
canvas.enlarge();
}
});
jbtShrink.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
canvas.shrink();
}
});
}
/** Main method */
public static void main(String[] args) {
JFrame frame = new ControlBall();
frame.setTitle("ControlBall");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static class BallCanvas extends JPanel {
private int radius = 5; // Default ball radius
/** Enlarge the ball */
public void enlarge() {
radius += 1;
repaint();
}
/** Shrink the ball */
public void shrink() {
radius -= 1;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
2 * radius, 2 * radius);
}
}
}
| rdejong/LiangJava | ControlBall.java |
247,614 | 404: Not Found | Katharsas/Neroxis-Map-Generator | src/java/map/Mask.java |
247,617 | package pf.utils;
import java.io.Serializable;
public class Rectangle implements Serializable{
// private static final String TAG = "Rectangle";
public double left, right, top, bottom;
private Line leftSide, rightSide, topSide, bottomSide;
public Rectangle() {
left = Double.POSITIVE_INFINITY;
right = Double.NEGATIVE_INFINITY;
top = Double.POSITIVE_INFINITY;
bottom = Double.NEGATIVE_INFINITY;
}
public Rectangle(double x1, double y1, double x2, double y2) {
set(x1, y1, x2, y2);
}
public void set(Rectangle other) {
set(other.left, other.top, other.right, other.bottom);
}
public void set(double x1, double y1, double x2, double y2) {
this.left = Math.min(x1, x2);
this.top = Math.min(y1, y2);
this.right = Math.max(x1, x2);
this.bottom = Math.max(y1, y2);
leftSide = new Line(left, top, left, bottom);
rightSide = new Line(right, top, right, bottom);
topSide = new Line(left, top, right, top);
bottomSide = new Line(left, bottom, right, bottom);
}
public void consolidate() {
this.left = Math.min(left, right);
this.top = Math.min(top, bottom);
this.right = Math.max(left, right);
this.bottom = Math.max(top, bottom);
leftSide = new Line(left, top, left, bottom);
rightSide = new Line(right, top, right, bottom);
topSide = new Line(left, top, right, top);
bottomSide = new Line(left, bottom, right, bottom);
}
public double getX1() {
return left;
}
public double getX2() {
return right;
}
public double getY1() {
return top;
}
public double getY2() {
return bottom;
}
public void enlarge(double length) {
set(left - length, top - length, right + length, bottom + length);
/*
left -= length;
top -= length;
right += length;
bottom += length;
*/
}
/**
* Enlarges the rectangle to contain the point
* Must call consolidate after all points are inserted!!!
* @param point inserted point
*/
public void enlargeToFit(Point2D point) {
this.left = Math.min(left, point.x);
this.top = Math.min(top, point.y);
this.right = Math.max(right, point.x);
this.bottom = Math.max(bottom, point.y);
}
public boolean hasIntersection(double x, double y) {
return left <= x && x <= right && top <= y && y <= bottom;
/*
return Math.min(left, right) <= x && x <= Math.max(left, right)
&& Math.min(top, bottom) <= y && y <= Math.max(top, bottom);
*/
}
public boolean hasIntersection(Point2D point) {
return hasIntersection(point.x, point.y);
}
public boolean hasIntersection(Line line) {
/*
boolean b1 = hasIntersection(line.getX1(), line.getY1());
boolean b2 = hasIntersection(line.getX2(), line.getY2());
boolean b3 = (leftSide != null && line.intersect(leftSide));
boolean b4 = (rightSide != null && line.intersect(rightSide));
Log.d(TAG, "topSide = " + topSide);
boolean b5 = (topSide != null && line.intersect(topSide));
Log.d(TAG, "bottomSide = " + bottomSide);
boolean b6 = (bottomSide != null && line.intersect(bottomSide));
Log.d(TAG, "intersection of " + this);
Log.d(TAG, "with = " + line);
Log.d(TAG, "b1 = " + b1 + ", b2 = " + b2 + ", b3 = " + b3 +
", b4 = " + b4 + ", b5 = " + b5 + ", b6 = " + b6);
return b1 || b2 || b3 || b4 || b5 || b6;
*/
return hasIntersection(line.getX1(), line.getY1())
|| hasIntersection(line.getX2(), line.getY2())
|| (leftSide != null && line.intersect(leftSide))
|| (rightSide != null && line.intersect(rightSide))
|| (topSide != null && line.intersect(topSide))
|| (bottomSide != null && line.intersect(bottomSide));
}
public boolean hasIntersection(Rectangle other) {
return left <= other.right && right >= other.left
&& top <= other.bottom && bottom >= other.top;
}
public void intersect(Rectangle other) {
if (hasIntersection(other)) {
left = Math.max(left, other.left);
top = Math.max(top, other.top);
right = Math.min(right, other.right);
bottom = Math.min(bottom, other.bottom);
} else {
left = Double.POSITIVE_INFINITY;
right = Double.NEGATIVE_INFINITY;
top = Double.POSITIVE_INFINITY;
bottom = Double.NEGATIVE_INFINITY;
}
}
public Rectangle intersection(Rectangle other) {
if (hasIntersection(other)) {
return new Rectangle(Math.max(left, other.left), Math.max(top,
other.top), Math.min(right, other.right), Math.min(bottom,
other.bottom));
} else {
return null;
}
}
public String toString() {
return "rect(" + left + " " + top + " " + right + " " + bottom + ")";
}
}
| yuchaoran2011/Particle-Filtering | utils/Rectangle.java |
247,618 | /*
* $Id$
*
* JSDAI(TM), a way to implement STEP, ISO 10303
* Copyright (C) 1997-2008, LKSoftWare GmbH, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation (AGPL v3).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* JSDAI is a registered trademark of LKSoftWare GmbH, Germany
* This software is also available under commercial licenses.
* See also http://www.jsdai.net/
*/
package jsdai.lang; import jsdai.dictionary.*;
class Token
{
int type;
int integer;
double real;
byte[] string;
int length;
int line;
int column;
static final int LENGTH_OF_STRING_TOKEN = 128;
Token() {
string = new byte[LENGTH_OF_STRING_TOKEN];
}
void enlarge() {
int new_length = string.length * 2;
byte new_string[] = new byte[new_length];
System.arraycopy(string, 0, new_string, 0, string.length);
string = new_string;
}
void PrintToken() {
int i;
String str_type;
switch (type) {
case PhFileReader.EOF:
str_type = "eof";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.ERROR:
str_type = "error";
System.out.println("SCANNER> " + str_type + " error_index=" + integer +
" line=" + line + " column=" + column);
break;
case PhFileReader.BINARY:
str_type = "BINARY";
System.out.print("SCANNER> " + str_type + " value=");
for (i = 0; i < length; i++) {
System.out.print( (char)string[i]);
}
System.out.println(" line=" + line + " column=" + column);
break;
case PhFileReader.COMMA:
str_type = "COMMA";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.DATA:
str_type = "DATA";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.ENDSCOPE:
str_type = "ENDSCOPE";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.ENDSEC:
str_type = "ENDSEC";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.ISO_END:
str_type = "END_ISO_10303_21";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.ENTITY_NAME:
str_type = "ENTITY_NAME";
System.out.print("SCANNER> " + str_type + " name=");
for (i = 0; i < length; i++) {
System.out.print( (char)string[i]);
}
System.out.println(" line=" + line + " column=" + column);
break;
case PhFileReader.ENUM:
str_type = "ENUM";
System.out.print("SCANNER> " + str_type + " value=");
for (i = 0; i < length; i++) {
System.out.print( (char)string[i]);
}
System.out.println(" line=" + line + " column=" + column);
break;
case PhFileReader.EQUALS:
str_type = "EQUALS";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.HEADER:
str_type = "HEADER";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.INSTANCE_NAME:
str_type = "INSTANCE_NAME";
System.out.println("SCANNER> " + str_type + " instance=" + integer +
" line=" + line + " column=" + column);
break;
case PhFileReader.INTEGER:
str_type = "INTEGER";
System.out.println("SCANNER> " + str_type + " value=" + integer +
" line=" + line + " column=" + column);
break;
case PhFileReader.ISO_BEGIN:
str_type = "ISO_10303_21";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.LPAREN:
str_type = "LEFT_PAREN";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.LOGICAL:
str_type = "LOGICAL";
System.out.println("SCANNER> " + str_type + " value=" + integer +
" line=" + line + " column=" + column);
break;
case PhFileReader.MISSING:
str_type = "MISSING";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.REAL:
str_type = "REAL";
System.out.println("SCANNER> " + str_type + " value=" + real +
" line=" + line + " column=" + column);
break;
case PhFileReader.REDEFINE:
str_type = "REDEFINE";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.RPAREN:
str_type = "RIGHT_PAREN";
System.out.println("SCANNER> " + str_type +" line=" + line + " column=" + column);
break;
case PhFileReader.SCOPE:
str_type = "SCOPE";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.SEMICOLON:
str_type = "SEMICOLON";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.SLASH:
str_type = "SLASH";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
case PhFileReader.STRING:
str_type = "STRING";
System.out.print("SCANNER> " + str_type + " value=");
for (i = 0; i < length; i++) {
System.out.print( (char)string[i]);
}
System.out.println(" line=" + line + " column=" + column);
break;
case PhFileReader.USER_DEFINED_KEYWORD:
str_type = "USER_DEFINED_KEYWORD";
System.out.print("SCANNER> " + str_type + " name=");
for (i = 0; i < length; i++) {
System.out.print( (char)string[i]);
}
System.out.println(" line=" + line + " column=" + column);
break;
default: str_type = "Unknown token";
System.out.println("SCANNER> " + str_type + " line=" + line + " column=" + column);
break;
}
}
}
| math85360/jsdai | jsdai-core/src/jsdai/lang/Token.java |
247,619 | package jp.jaxa.iss.kibo.rpc.uae;
import java.util.ArrayList;
import java.util.List;
public class Obstacle {
private Point3D topLeft;
private Point3D bottomRight;
public Obstacle(Point3D topLeft, Point3D bottomRight) {
this.topLeft = topLeft;
this.bottomRight = bottomRight;
}
public Point3D[] getVerticesAABB() {
// We assume that topLeft and bottomRight are the minimum and maximum corners respectively.
// That is, topLeft has the smallest x, y, z coordinates and bottomRight has the largest x, y, z coordinates.
Point3D[] points = new Point3D[] {topLeft, bottomRight};
return points;
}
public List<Point3D> getVertices() {
List<Point3D> vertices = new ArrayList<>();
double x1 = topLeft.getX();
double y1 = topLeft.getY();
double z1 = topLeft.getZ();
double x2 = bottomRight.getX();
double y2 = bottomRight.getY();
double z2 = bottomRight.getZ();
vertices.add(new Point3D(x1, y1, z1)); // top-left
vertices.add(new Point3D(x1, y2, z1)); // bottom-left
vertices.add(new Point3D(x2, y1, z1)); // top-right
vertices.add(new Point3D(x2, y2, z1)); // bottom-right
vertices.add(new Point3D(x1, y1, z2)); // top-left (other face)
vertices.add(new Point3D(x1, y2, z2)); // bottom-left (other face)
vertices.add(new Point3D(x2, y1, z2)); // top-right (other face)
vertices.add(new Point3D(x2, y2, z2)); // bottom-right (other face)
return vertices;
}
public Obstacle enlarge(float size) {
// Assumes size is added equally in all directions.
return new Obstacle(
new Point3D(topLeft.getX() - size, topLeft.getY() - size, topLeft.getZ() - size),
new Point3D(bottomRight.getX() + size, bottomRight.getY() + size, bottomRight.getZ() + size)
);
}
}
| TaufiqSyed/kibo-rpc-2023 | Obstacle.java |
247,621 | package opencascade;
/**
* Describes a bounding box in 3D space.
* A bounding box is parallel to the axes of the coordinates
* system. If it is finite, it is defined by the three intervals:
* - [ Xmin,Xmax ],
* - [ Ymin,Ymax ],
* - [ Zmin,Zmax ].
* A bounding box may be infinite (i.e. open) in one or more
* directions. It is said to be:
* - OpenXmin if it is infinite on the negative side of the "X Direction";
* - OpenXmax if it is infinite on the positive side of the "X Direction";
* - OpenYmin if it is infinite on the negative side of the "Y Direction";
* - OpenYmax if it is infinite on the positive side of the "Y Direction";
* - OpenZmin if it is infinite on the negative side of the "Z Direction";
* - OpenZmax if it is infinite on the positive side of the "Z Direction";
* - WholeSpace if it is infinite in all six directions. In this
* case, any point of the space is inside the box;
* - Void if it is empty. In this case, there is no point included in the box.
* A bounding box is defined by:
* - six bounds (Xmin, Xmax, Ymin, Ymax, Zmin and
* Zmax) which limit the bounding box if it is finite,
* - eight flags (OpenXmin, OpenXmax, OpenYmin,
* OpenYmax, OpenZmin, OpenZmax,
* WholeSpace and Void) which describe the
* bounding box if it is infinite or empty, and
* - a gap, which is included on both sides in any direction
* when consulting the finite bounds of the box.
*/
public class Bnd_Box {
protected long swigCPtr;
protected boolean swigCMemOwn;
protected Object swigParent;
Bnd_Box(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
Bnd_Box(long cPtr, boolean cMemoryOwn, Object Parent) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
if ( ! cMemoryOwn ) swigParent = Parent; // keep reference to assumed parent object
}
static long getCPtr(Bnd_Box obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
// Auxiliary structure for holding wrapped C reference to object
// requiring explicit decision to use it either as reference or a copy
/*public class CRef {
public CRef (Bnd_Box ptr) { Ptr = ptr; }
public Bnd_Box AsReference () { return Ptr; }
public Bnd_Box AsCopy () { return Ptr.MakeCopy(); }
public Bnd_Box Ptr;
}*/
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
OCCwrapJavaJNI.delete_Bnd_Box(swigCPtr);
}
swigCPtr = 0;
}
}
/**
* Creates an empty Box.
* The constructed box is qualified Void. Its gap is null.
*/
public Bnd_Box() {
this(OCCwrapJavaJNI.new_Bnd_Box(), true);
}
/**
* Sets this bounding box so that it covers the whole of 3D space.
* It is infinitely long in all directions.
*/
public void SetWhole() {
OCCwrapJavaJNI.Bnd_Box_SetWhole(swigCPtr, this);
}
/**
* Sets this bounding box so that it is empty. All points are outside a void box.
*/
public void SetVoid() {
OCCwrapJavaJNI.Bnd_Box_SetVoid(swigCPtr, this);
}
/**
* Sets this bounding box so that it bounds
* - the point P. This involves first setting this bounding box
* to be void and then adding the point P.
*/
public void Set( gp_Pnt P) {
OCCwrapJavaJNI.Bnd_Box_Set__SWIG_0(swigCPtr, this, gp_Pnt.getCPtr(P), P);
}
/**
* Sets this bounding box so that it bounds
* the half-line defined by point P and direction D, i.e. all
* points M defined by M=P+u*D, where u is greater than
* or equal to 0, are inside the bounding volume. This
* involves first setting this box to be void and then adding the half-line.
*/
public void Set( gp_Pnt P, gp_Dir D) {
OCCwrapJavaJNI.Bnd_Box_Set__SWIG_1(swigCPtr, this, gp_Pnt.getCPtr(P), P, gp_Dir.getCPtr(D), D);
}
/**
* Enlarges this bounding box, if required, so that it
* contains at least:
* - interval [ aXmin,aXmax ] in the "X Direction",
* - interval [ aYmin,aYmax ] in the "Y Direction",
* - interval [ aZmin,aZmax ] in the "Z Direction";
*/
public void Update(double aXmin, double aYmin, double aZmin, double aXmax, double aYmax, double aZmax) {
OCCwrapJavaJNI.Bnd_Box_Update__SWIG_0(swigCPtr, this, aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
}
/**
* Adds a point of coordinates (X,Y,Z) to this bounding box.
*/
public void Update(double X, double Y, double Z) {
OCCwrapJavaJNI.Bnd_Box_Update__SWIG_1(swigCPtr, this, X, Y, Z);
}
/**
* Returns the gap of this bounding box.
*/
public double GetGap() {
return OCCwrapJavaJNI.Bnd_Box_GetGap(swigCPtr, this);
}
/**
* Set the gap of this bounding box to abs(Tol).
*/
public void SetGap(double Tol) {
OCCwrapJavaJNI.Bnd_Box_SetGap(swigCPtr, this, Tol);
}
/**
* Enlarges the box with a tolerance value.
* (minvalues-Abs(<tol>) and maxvalues+Abs(<tol>))
* This means that the minimum values of its X, Y and Z
* intervals of definition, when they are finite, are reduced by
* the absolute value of Tol, while the maximum values are
* increased by the same amount.
*/
public void Enlarge(double Tol) {
OCCwrapJavaJNI.Bnd_Box_Enlarge(swigCPtr, this, Tol);
}
/**
* Returns the bounds of this bounding box. The gap is included.
* If this bounding box is infinite (i.e. "open"), returned values
* may be equal to +/- Precision::Infinite().
* Standard_ConstructionError exception will be thrown if the box is void.
* if IsVoid()
*/
public void Get(double[] theXmin, double[] theYmin, double[] theZmin, double[] theXmax, double[] theYmax, double[] theZmax) {
OCCwrapJavaJNI.Bnd_Box_Get(swigCPtr, this, theXmin, theYmin, theZmin, theXmax, theYmax, theZmax);
}
/**
* Returns the lower corner of this bounding box. The gap is included.
* If this bounding box is infinite (i.e. "open"), returned values
* may be equal to +/- Precision::Infinite().
* Standard_ConstructionError exception will be thrown if the box is void.
* if IsVoid()
*/
public gp_Pnt CornerMin() {
return new gp_Pnt(OCCwrapJavaJNI.Bnd_Box_CornerMin(swigCPtr, this), true);
}
/**
* Returns the upper corner of this bounding box. The gap is included.
* If this bounding box is infinite (i.e. "open"), returned values
* may be equal to +/- Precision::Infinite().
* Standard_ConstructionError exception will be thrown if the box is void.
* if IsVoid()
*/
public gp_Pnt CornerMax() {
return new gp_Pnt(OCCwrapJavaJNI.Bnd_Box_CornerMax(swigCPtr, this), true);
}
/**
* The Box will be infinitely long in the Xmin
* direction.
*/
public void OpenXmin() {
OCCwrapJavaJNI.Bnd_Box_OpenXmin(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Xmax
* direction.
*/
public void OpenXmax() {
OCCwrapJavaJNI.Bnd_Box_OpenXmax(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Ymin
* direction.
*/
public void OpenYmin() {
OCCwrapJavaJNI.Bnd_Box_OpenYmin(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Ymax
* direction.
*/
public void OpenYmax() {
OCCwrapJavaJNI.Bnd_Box_OpenYmax(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Zmin
* direction.
*/
public void OpenZmin() {
OCCwrapJavaJNI.Bnd_Box_OpenZmin(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Zmax
* direction.
*/
public void OpenZmax() {
OCCwrapJavaJNI.Bnd_Box_OpenZmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Xmin direction.
*/
public long IsOpenXmin() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenXmin(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Xmax direction.
*/
public long IsOpenXmax() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenXmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Ymix direction.
*/
public long IsOpenYmin() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenYmin(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Ymax direction.
*/
public long IsOpenYmax() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenYmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Zmin direction.
*/
public long IsOpenZmin() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenZmin(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Zmax direction.
*/
public long IsOpenZmax() {
return OCCwrapJavaJNI.Bnd_Box_IsOpenZmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is infinite in all 6 directions (WholeSpace flag).
*/
public long IsWhole() {
return OCCwrapJavaJNI.Bnd_Box_IsWhole(swigCPtr, this);
}
/**
* Returns true if this bounding box is empty (Void flag).
*/
public long IsVoid() {
return OCCwrapJavaJNI.Bnd_Box_IsVoid(swigCPtr, this);
}
/**
* true if xmax-xmin < tol.
*/
public long IsXThin(double tol) {
return OCCwrapJavaJNI.Bnd_Box_IsXThin(swigCPtr, this, tol);
}
/**
* true if ymax-ymin < tol.
*/
public long IsYThin(double tol) {
return OCCwrapJavaJNI.Bnd_Box_IsYThin(swigCPtr, this, tol);
}
/**
* true if zmax-zmin < tol.
*/
public long IsZThin(double tol) {
return OCCwrapJavaJNI.Bnd_Box_IsZThin(swigCPtr, this, tol);
}
/**
* Returns true if IsXThin, IsYThin and IsZThin are all true,
* i.e. if the box is thin in all three dimensions.
*/
public long IsThin(double tol) {
return OCCwrapJavaJNI.Bnd_Box_IsThin(swigCPtr, this, tol);
}
/**
* Returns a bounding box which is the result of applying the
* transformation T to this bounding box.
* Warning
* Applying a geometric transformation (for example, a
* rotation) to a bounding box generally increases its
* dimensions. This is not optimal for algorithms which use it.
*/
public Bnd_Box Transformed( gp_Trsf T) {
return new Bnd_Box(OCCwrapJavaJNI.Bnd_Box_Transformed(swigCPtr, this, gp_Trsf.getCPtr(T), T), true);
}
/**
* Adds the box <Other> to <me>.
*/
public void Add( Bnd_Box Other) {
OCCwrapJavaJNI.Bnd_Box_Add__SWIG_0(swigCPtr, this, Bnd_Box.getCPtr(Other), Other);
}
/**
* Adds a Pnt to the box.
*/
public void Add( gp_Pnt P) {
OCCwrapJavaJNI.Bnd_Box_Add__SWIG_1(swigCPtr, this, gp_Pnt.getCPtr(P), P);
}
/**
* Extends <me> from the Pnt <P> in the direction <D>.
*/
public void Add( gp_Pnt P, gp_Dir D) {
OCCwrapJavaJNI.Bnd_Box_Add__SWIG_2(swigCPtr, this, gp_Pnt.getCPtr(P), P, gp_Dir.getCPtr(D), D);
}
/**
* Extends the Box in the given Direction, i.e. adds
* an half-line. The box may become infinite in
* 1,2 or 3 directions.
*/
public void Add( gp_Dir D) {
OCCwrapJavaJNI.Bnd_Box_Add__SWIG_3(swigCPtr, this, gp_Dir.getCPtr(D), D);
}
/**
* Returns True if the Pnt is out the box.
*/
public long IsOut( gp_Pnt P) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_0(swigCPtr, this, gp_Pnt.getCPtr(P), P);
}
/**
* Returns False if the line intersects the box.
*/
public long IsOut( gp_Lin L) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_1(swigCPtr, this, gp_Lin.getCPtr(L), L);
}
/**
* Returns False if the plane intersects the box.
*/
public long IsOut( gp_Pln P) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_2(swigCPtr, this, gp_Pln.getCPtr(P), P);
}
/**
* Returns False if the <Box> intersects or is inside <me>.
*/
public long IsOut( Bnd_Box Other) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_3(swigCPtr, this, Bnd_Box.getCPtr(Other), Other);
}
/**
* Returns False if the transformed <Box> intersects
* or is inside <me>.
*/
public long IsOut( Bnd_Box Other, gp_Trsf T) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_4(swigCPtr, this, Bnd_Box.getCPtr(Other), Other, gp_Trsf.getCPtr(T), T);
}
/**
* Returns False if the transformed <Box> intersects
* or is inside the transformed box <me>.
*/
public long IsOut( gp_Trsf T1, Bnd_Box Other, gp_Trsf T2) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_5(swigCPtr, this, gp_Trsf.getCPtr(T1), T1, Bnd_Box.getCPtr(Other), Other, gp_Trsf.getCPtr(T2), T2);
}
/**
* Returns False if the flat band lying between two parallel
* lines represented by their reference points <P1>, <P2> and
* direction <D> intersects the box.
*/
public long IsOut( gp_Pnt P1, gp_Pnt P2, gp_Dir D) {
return OCCwrapJavaJNI.Bnd_Box_IsOut__SWIG_6(swigCPtr, this, gp_Pnt.getCPtr(P1), P1, gp_Pnt.getCPtr(P2), P2, gp_Dir.getCPtr(D), D);
}
/**
* Computes the minimum distance between two boxes.
*/
public double Distance( Bnd_Box Other) {
return OCCwrapJavaJNI.Bnd_Box_Distance(swigCPtr, this, Bnd_Box.getCPtr(Other), Other);
}
public void Dump() {
OCCwrapJavaJNI.Bnd_Box_Dump(swigCPtr, this);
}
/**
* Computes the squared diagonal of me.
*/
public double SquareExtent() {
return OCCwrapJavaJNI.Bnd_Box_SquareExtent(swigCPtr, this);
}
}
| Aircraft-Design-UniNa/jpad-occt | OCCJava/Bnd_Box.java |
247,624 | /*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package sun.awt.geom;
import java.awt.geom.Rectangle2D;
import java.awt.geom.PathIterator;
import java.awt.geom.QuadCurve2D;
import java.util.Vector;
final class Order2 extends Curve {
private double x0;
private double y0;
private double cx0;
private double cy0;
private double x1;
private double y1;
private double xmin;
private double xmax;
private double xcoeff0;
private double xcoeff1;
private double xcoeff2;
private double ycoeff0;
private double ycoeff1;
private double ycoeff2;
public static void insert(Vector curves, double tmp[],
double x0, double y0,
double cx0, double cy0,
double x1, double y1,
int direction)
{
int numparams = getHorizontalParams(y0, cy0, y1, tmp);
if (numparams == 0) {
// We are using addInstance here to avoid inserting horisontal
// segments
addInstance(curves, x0, y0, cx0, cy0, x1, y1, direction);
return;
}
// assert(numparams == 1);
double t = tmp[0];
tmp[0] = x0; tmp[1] = y0;
tmp[2] = cx0; tmp[3] = cy0;
tmp[4] = x1; tmp[5] = y1;
split(tmp, 0, t);
int i0 = (direction == INCREASING)? 0 : 4;
int i1 = 4 - i0;
addInstance(curves, tmp[i0], tmp[i0 + 1], tmp[i0 + 2], tmp[i0 + 3],
tmp[i0 + 4], tmp[i0 + 5], direction);
addInstance(curves, tmp[i1], tmp[i1 + 1], tmp[i1 + 2], tmp[i1 + 3],
tmp[i1 + 4], tmp[i1 + 5], direction);
}
public static void addInstance(Vector curves,
double x0, double y0,
double cx0, double cy0,
double x1, double y1,
int direction) {
if (y0 > y1) {
curves.add(new Order2(x1, y1, cx0, cy0, x0, y0, -direction));
} else if (y1 > y0) {
curves.add(new Order2(x0, y0, cx0, cy0, x1, y1, direction));
}
}
/*
* Return the count of the number of horizontal sections of the
* specified quadratic Bezier curve. Put the parameters for the
* horizontal sections into the specified <code>ret</code> array.
* <p>
* If we examine the parametric equation in t, we have:
* Py(t) = C0*(1-t)^2 + 2*CP*t*(1-t) + C1*t^2
* = C0 - 2*C0*t + C0*t^2 + 2*CP*t - 2*CP*t^2 + C1*t^2
* = C0 + (2*CP - 2*C0)*t + (C0 - 2*CP + C1)*t^2
* Py(t) = (C0 - 2*CP + C1)*t^2 + (2*CP - 2*C0)*t + (C0)
* If we take the derivative, we get:
* Py(t) = At^2 + Bt + C
* dPy(t) = 2At + B = 0
* 2*(C0 - 2*CP + C1)t + 2*(CP - C0) = 0
* 2*(C0 - 2*CP + C1)t = 2*(C0 - CP)
* t = 2*(C0 - CP) / 2*(C0 - 2*CP + C1)
* t = (C0 - CP) / (C0 - CP + C1 - CP)
* Note that this method will return 0 if the equation is a line,
* which is either always horizontal or never horizontal.
* Completely horizontal curves need to be eliminated by other
* means outside of this method.
*/
public static int getHorizontalParams(double c0, double cp, double c1,
double ret[]) {
if (c0 <= cp && cp <= c1) {
return 0;
}
c0 -= cp;
c1 -= cp;
double denom = c0 + c1;
// If denom == 0 then cp == (c0+c1)/2 and we have a line.
if (denom == 0) {
return 0;
}
double t = c0 / denom;
// No splits at t==0 and t==1
if (t <= 0 || t >= 1) {
return 0;
}
ret[0] = t;
return 1;
}
/*
* Split the quadratic Bezier stored at coords[pos...pos+5] representing
* the paramtric range [0..1] into two subcurves representing the
* parametric subranges [0..t] and [t..1]. Store the results back
* into the array at coords[pos...pos+5] and coords[pos+4...pos+9].
*/
public static void split(double coords[], int pos, double t) {
double x0, y0, cx, cy, x1, y1;
coords[pos+8] = x1 = coords[pos+4];
coords[pos+9] = y1 = coords[pos+5];
cx = coords[pos+2];
cy = coords[pos+3];
x1 = cx + (x1 - cx) * t;
y1 = cy + (y1 - cy) * t;
x0 = coords[pos+0];
y0 = coords[pos+1];
x0 = x0 + (cx - x0) * t;
y0 = y0 + (cy - y0) * t;
cx = x0 + (x1 - x0) * t;
cy = y0 + (y1 - y0) * t;
coords[pos+2] = x0;
coords[pos+3] = y0;
coords[pos+4] = cx;
coords[pos+5] = cy;
coords[pos+6] = x1;
coords[pos+7] = y1;
}
public Order2(double x0, double y0,
double cx0, double cy0,
double x1, double y1,
int direction)
{
super(direction);
// REMIND: Better accuracy in the root finding methods would
// ensure that cy0 is in range. As it stands, it is never
// more than "1 mantissa bit" out of range...
if (cy0 < y0) {
cy0 = y0;
} else if (cy0 > y1) {
cy0 = y1;
}
this.x0 = x0;
this.y0 = y0;
this.cx0 = cx0;
this.cy0 = cy0;
this.x1 = x1;
this.y1 = y1;
xmin = Math.min(Math.min(x0, x1), cx0);
xmax = Math.max(Math.max(x0, x1), cx0);
xcoeff0 = x0;
xcoeff1 = cx0 + cx0 - x0 - x0;
xcoeff2 = x0 - cx0 - cx0 + x1;
ycoeff0 = y0;
ycoeff1 = cy0 + cy0 - y0 - y0;
ycoeff2 = y0 - cy0 - cy0 + y1;
}
public int getOrder() {
return 2;
}
public double getXTop() {
return x0;
}
public double getYTop() {
return y0;
}
public double getXBot() {
return x1;
}
public double getYBot() {
return y1;
}
public double getXMin() {
return xmin;
}
public double getXMax() {
return xmax;
}
public double getX0() {
return (direction == INCREASING) ? x0 : x1;
}
public double getY0() {
return (direction == INCREASING) ? y0 : y1;
}
public double getCX0() {
return cx0;
}
public double getCY0() {
return cy0;
}
public double getX1() {
return (direction == DECREASING) ? x0 : x1;
}
public double getY1() {
return (direction == DECREASING) ? y0 : y1;
}
public double XforY(double y) {
if (y <= y0) {
return x0;
}
if (y >= y1) {
return x1;
}
return XforT(TforY(y));
}
public double TforY(double y) {
if (y <= y0) {
return 0;
}
if (y >= y1) {
return 1;
}
return TforY(y, ycoeff0, ycoeff1, ycoeff2);
}
public static double TforY(double y,
double ycoeff0, double ycoeff1, double ycoeff2)
{
// The caller should have already eliminated y values
// outside of the y0 to y1 range.
ycoeff0 -= y;
if (ycoeff2 == 0.0) {
// The quadratic parabola has degenerated to a line.
// ycoeff1 should not be 0.0 since we have already eliminated
// totally horizontal lines, but if it is, then we will generate
// infinity here for the root, which will not be in the [0,1]
// range so we will pass to the failure code below.
double root = -ycoeff0 / ycoeff1;
if (root >= 0 && root <= 1) {
return root;
}
} else {
// From Numerical Recipes, 5.6, Quadratic and Cubic Equations
double d = ycoeff1 * ycoeff1 - 4.0 * ycoeff2 * ycoeff0;
// If d < 0.0, then there are no roots
if (d >= 0.0) {
d = Math.sqrt(d);
// For accuracy, calculate one root using:
// (-ycoeff1 +/- d) / 2ycoeff2
// and the other using:
// 2ycoeff0 / (-ycoeff1 +/- d)
// Choose the sign of the +/- so that ycoeff1+d
// gets larger in magnitude
if (ycoeff1 < 0.0) {
d = -d;
}
double q = (ycoeff1 + d) / -2.0;
// We already tested ycoeff2 for being 0 above
double root = q / ycoeff2;
if (root >= 0 && root <= 1) {
return root;
}
if (q != 0.0) {
root = ycoeff0 / q;
if (root >= 0 && root <= 1) {
return root;
}
}
}
}
/* We failed to find a root in [0,1]. What could have gone wrong?
* First, remember that these curves are constructed to be monotonic
* in Y and totally horizontal curves have already been eliminated.
* Now keep in mind that the Y coefficients of the polynomial form
* of the curve are calculated from the Y coordinates which define
* our curve. They should theoretically define the same curve,
* but they can be off by a couple of bits of precision after the
* math is done and so can represent a slightly modified curve.
* This is normally not an issue except when we have solutions near
* the endpoints. Since the answers we get from solving the polynomial
* may be off by a few bits that means that they could lie just a
* few bits of precision outside the [0,1] range.
*
* Another problem could be that while the parametric curve defined
* by the Y coordinates has a local minima or maxima at or just
* outside of the endpoints, the polynomial form might express
* that same min/max just inside of and just shy of the Y coordinate
* of that endpoint. In that case, if we solve for a Y coordinate
* at or near that endpoint, we may be solving for a Y coordinate
* that is below that minima or above that maxima and we would find
* no solutions at all.
*
* In either case, we can assume that y is so near one of the
* endpoints that we can just collapse it onto the nearest endpoint
* without losing more than a couple of bits of precision.
*/
// First calculate the midpoint between y0 and y1 and choose to
// return either 0.0 or 1.0 depending on whether y is above
// or below the midpoint...
// Note that we subtracted y from ycoeff0 above so both y0 and y1
// will be "relative to y" so we are really just looking at where
// zero falls with respect to the "relative midpoint" here.
double y0 = ycoeff0;
double y1 = ycoeff0 + ycoeff1 + ycoeff2;
return (0 < (y0 + y1) / 2) ? 0.0 : 1.0;
}
public double XforT(double t) {
return (xcoeff2 * t + xcoeff1) * t + xcoeff0;
}
public double YforT(double t) {
return (ycoeff2 * t + ycoeff1) * t + ycoeff0;
}
public double dXforT(double t, int deriv) {
switch (deriv) {
case 0:
return (xcoeff2 * t + xcoeff1) * t + xcoeff0;
case 1:
return 2 * xcoeff2 * t + xcoeff1;
case 2:
return 2 * xcoeff2;
default:
return 0;
}
}
public double dYforT(double t, int deriv) {
switch (deriv) {
case 0:
return (ycoeff2 * t + ycoeff1) * t + ycoeff0;
case 1:
return 2 * ycoeff2 * t + ycoeff1;
case 2:
return 2 * ycoeff2;
default:
return 0;
}
}
public double nextVertical(double t0, double t1) {
double t = -xcoeff1 / (2 * xcoeff2);
if (t > t0 && t < t1) {
return t;
}
return t1;
}
public void enlarge(Rectangle2D r) {
r.add(x0, y0);
double t = -xcoeff1 / (2 * xcoeff2);
if (t > 0 && t < 1) {
r.add(XforT(t), YforT(t));
}
r.add(x1, y1);
}
public Curve getSubCurve(double ystart, double yend, int dir) {
double t0, t1;
if (ystart <= y0) {
if (yend >= y1) {
return getWithDirection(dir);
}
t0 = 0;
} else {
t0 = TforY(ystart, ycoeff0, ycoeff1, ycoeff2);
}
if (yend >= y1) {
t1 = 1;
} else {
t1 = TforY(yend, ycoeff0, ycoeff1, ycoeff2);
}
double eqn[] = new double[10];
eqn[0] = x0;
eqn[1] = y0;
eqn[2] = cx0;
eqn[3] = cy0;
eqn[4] = x1;
eqn[5] = y1;
if (t1 < 1) {
split(eqn, 0, t1);
}
int i;
if (t0 <= 0) {
i = 0;
} else {
split(eqn, 0, t0 / t1);
i = 4;
}
return new Order2(eqn[i+0], ystart,
eqn[i+2], eqn[i+3],
eqn[i+4], yend,
dir);
}
public Curve getReversedCurve() {
return new Order2(x0, y0, cx0, cy0, x1, y1, -direction);
}
public int getSegment(double coords[]) {
coords[0] = cx0;
coords[1] = cy0;
if (direction == INCREASING) {
coords[2] = x1;
coords[3] = y1;
} else {
coords[2] = x0;
coords[3] = y0;
}
return PathIterator.SEG_QUADTO;
}
public String controlPointString() {
return ("("+round(cx0)+", "+round(cy0)+"), ");
}
}
| bigjoehuang/JDK1.7-source-study | sun/awt/geom/Order2.java |
247,625 | package Homework3;
public class ArrayCollection<T> {
protected static final int DEFAULT_CAPACITY = 100;
protected T[] elements;
protected int numberOfElements;
public ArrayCollection() {
this(DEFAULT_CAPACITY);
}
public ArrayCollection(int size) {
elements = (T[]) new Object[size];
numberOfElements = 0;
}
public boolean isEmpty() {
return numberOfElements == 0;
}
public boolean isFull() {
return numberOfElements == elements.length;
}
public int size() {
return numberOfElements;
}
public String toString() {
String collection = "";
for (int i = 0; i < numberOfElements; i++)
collection += elements[i] + "\n";
return collection;
}
public boolean add(T element) {
if(!isFull()) {
elements[numberOfElements++]=element;// Complete your code here
return true;
}
return false;
}
public boolean remove(T target) {
// if(elements.length==0)return false;
// int i=0;
// while(elements[i]!=target) {
// i++;
// }
// for(int k=i;k<=elements.length;k++) {
// elements[k]=elements[k+1];
// }
// elements[elements.length-1]=null;
// numberOfElements--;
// for(int index=0;index<numberOfElements;index++) {
// if(elements[index].equals(target)) {
// while(elements[numberOfElements-1].equals(target))numberOfElements--;
// elements[index]=elements[numberOfElements-1];
// numberOfElements--;
// }
// }
if(!contains(target))return false;
elements[findIndex(target)]=elements[numberOfElements-1];
numberOfElements--;
return true;
}
public boolean removeAll(T target) {
// Complete your code here
do {
remove(target);
}
while(contains(target));
return true;
}
public void removeDuplicate() {
// Remove any duplicated elements
}
public boolean equals(ArrayCollection that) {
// Return true if ArrayCollection are identical.
boolean result = true;
for(int index=0;index<this.numberOfElements;index++) {
if (!this.elements[index].equals(that.elements[index]))
result=false;
}
// Complete your code here.
return result && this.size() == that.size();
}
public int count(T target) {
// Return count of target occurrences
int c = 0;
for (int index=0; index<numberOfElements;index++)
// Complete your code here
if(elements[index].equals(target))
c++;
return c;
}
public void merge(ArrayCollection that) {
// Merge that ArrayCollection into this ArrayCollection
// Complete your code here
}
public void enlarge(int size) {
// Enlarge elements[] with additional size
// Complete your code here
}
public void clear() {
// Remove all elements in the collection
numberOfElements=0;
}
//Note: Different from textbook, this implementation has no 'found' and 'location' attributes.
// There is no find() method.
// There is a new methods findIndex().
public boolean contains(T target) {
// Return true if target is found
boolean found = false;
for(int index=0;index<numberOfElements;index++) {
if (elements[index].equals(target)) found=true;
}
// Complete your code here
return found;
}
public int findIndex(T target) {
// Return index of target
int index = -1;
for(int i=0;i<numberOfElements;i++) {
if(elements[i].equals(target))return i;
}
// Complete your code here
return index;
}
}
| mattcat12/hello-world | ArrayCollection.java |
247,627 | /*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package sun.awt.geom;
import java.awt.geom.Rectangle2D;
import java.awt.geom.PathIterator;
import java.awt.geom.QuadCurve2D;
import java.util.Vector;
final class Order3 extends Curve {
private double x0;
private double y0;
private double cx0;
private double cy0;
private double cx1;
private double cy1;
private double x1;
private double y1;
private double xmin;
private double xmax;
private double xcoeff0;
private double xcoeff1;
private double xcoeff2;
private double xcoeff3;
private double ycoeff0;
private double ycoeff1;
private double ycoeff2;
private double ycoeff3;
public static void insert(Vector curves, double tmp[],
double x0, double y0,
double cx0, double cy0,
double cx1, double cy1,
double x1, double y1,
int direction)
{
int numparams = getHorizontalParams(y0, cy0, cy1, y1, tmp);
if (numparams == 0) {
// We are using addInstance here to avoid inserting horisontal
// segments
addInstance(curves, x0, y0, cx0, cy0, cx1, cy1, x1, y1, direction);
return;
}
// Store coordinates for splitting at tmp[3..10]
tmp[3] = x0; tmp[4] = y0;
tmp[5] = cx0; tmp[6] = cy0;
tmp[7] = cx1; tmp[8] = cy1;
tmp[9] = x1; tmp[10] = y1;
double t = tmp[0];
if (numparams > 1 && t > tmp[1]) {
// Perform a "2 element sort"...
tmp[0] = tmp[1];
tmp[1] = t;
t = tmp[0];
}
split(tmp, 3, t);
if (numparams > 1) {
// Recalculate tmp[1] relative to the range [tmp[0]...1]
t = (tmp[1] - t) / (1 - t);
split(tmp, 9, t);
}
int index = 3;
if (direction == DECREASING) {
index += numparams * 6;
}
while (numparams >= 0) {
addInstance(curves,
tmp[index + 0], tmp[index + 1],
tmp[index + 2], tmp[index + 3],
tmp[index + 4], tmp[index + 5],
tmp[index + 6], tmp[index + 7],
direction);
numparams--;
if (direction == INCREASING) {
index += 6;
} else {
index -= 6;
}
}
}
public static void addInstance(Vector curves,
double x0, double y0,
double cx0, double cy0,
double cx1, double cy1,
double x1, double y1,
int direction) {
if (y0 > y1) {
curves.add(new Order3(x1, y1, cx1, cy1, cx0, cy0, x0, y0,
-direction));
} else if (y1 > y0) {
curves.add(new Order3(x0, y0, cx0, cy0, cx1, cy1, x1, y1,
direction));
}
}
/*
* Return the count of the number of horizontal sections of the
* specified cubic Bezier curve. Put the parameters for the
* horizontal sections into the specified <code>ret</code> array.
* <p>
* If we examine the parametric equation in t, we have:
* Py(t) = C0(1-t)^3 + 3CP0 t(1-t)^2 + 3CP1 t^2(1-t) + C1 t^3
* = C0 - 3C0t + 3C0t^2 - C0t^3 +
* 3CP0t - 6CP0t^2 + 3CP0t^3 +
* 3CP1t^2 - 3CP1t^3 +
* C1t^3
* Py(t) = (C1 - 3CP1 + 3CP0 - C0) t^3 +
* (3C0 - 6CP0 + 3CP1) t^2 +
* (3CP0 - 3C0) t +
* (C0)
* If we take the derivative, we get:
* Py(t) = Dt^3 + At^2 + Bt + C
* dPy(t) = 3Dt^2 + 2At + B = 0
* 0 = 3*(C1 - 3*CP1 + 3*CP0 - C0)t^2
* + 2*(3*CP1 - 6*CP0 + 3*C0)t
* + (3*CP0 - 3*C0)
* 0 = 3*(C1 - 3*CP1 + 3*CP0 - C0)t^2
* + 3*2*(CP1 - 2*CP0 + C0)t
* + 3*(CP0 - C0)
* 0 = (C1 - CP1 - CP1 - CP1 + CP0 + CP0 + CP0 - C0)t^2
* + 2*(CP1 - CP0 - CP0 + C0)t
* + (CP0 - C0)
* 0 = (C1 - CP1 + CP0 - CP1 + CP0 - CP1 + CP0 - C0)t^2
* + 2*(CP1 - CP0 - CP0 + C0)t
* + (CP0 - C0)
* 0 = ((C1 - CP1) - (CP1 - CP0) - (CP1 - CP0) + (CP0 - C0))t^2
* + 2*((CP1 - CP0) - (CP0 - C0))t
* + (CP0 - C0)
* Note that this method will return 0 if the equation is a line,
* which is either always horizontal or never horizontal.
* Completely horizontal curves need to be eliminated by other
* means outside of this method.
*/
public static int getHorizontalParams(double c0, double cp0,
double cp1, double c1,
double ret[]) {
if (c0 <= cp0 && cp0 <= cp1 && cp1 <= c1) {
return 0;
}
c1 -= cp1;
cp1 -= cp0;
cp0 -= c0;
ret[0] = cp0;
ret[1] = (cp1 - cp0) * 2;
ret[2] = (c1 - cp1 - cp1 + cp0);
int numroots = QuadCurve2D.solveQuadratic(ret, ret);
int j = 0;
for (int i = 0; i < numroots; i++) {
double t = ret[i];
// No splits at t==0 and t==1
if (t > 0 && t < 1) {
if (j < i) {
ret[j] = t;
}
j++;
}
}
return j;
}
/*
* Split the cubic Bezier stored at coords[pos...pos+7] representing
* the parametric range [0..1] into two subcurves representing the
* parametric subranges [0..t] and [t..1]. Store the results back
* into the array at coords[pos...pos+7] and coords[pos+6...pos+13].
*/
public static void split(double coords[], int pos, double t) {
double x0, y0, cx0, cy0, cx1, cy1, x1, y1;
coords[pos+12] = x1 = coords[pos+6];
coords[pos+13] = y1 = coords[pos+7];
cx1 = coords[pos+4];
cy1 = coords[pos+5];
x1 = cx1 + (x1 - cx1) * t;
y1 = cy1 + (y1 - cy1) * t;
x0 = coords[pos+0];
y0 = coords[pos+1];
cx0 = coords[pos+2];
cy0 = coords[pos+3];
x0 = x0 + (cx0 - x0) * t;
y0 = y0 + (cy0 - y0) * t;
cx0 = cx0 + (cx1 - cx0) * t;
cy0 = cy0 + (cy1 - cy0) * t;
cx1 = cx0 + (x1 - cx0) * t;
cy1 = cy0 + (y1 - cy0) * t;
cx0 = x0 + (cx0 - x0) * t;
cy0 = y0 + (cy0 - y0) * t;
coords[pos+2] = x0;
coords[pos+3] = y0;
coords[pos+4] = cx0;
coords[pos+5] = cy0;
coords[pos+6] = cx0 + (cx1 - cx0) * t;
coords[pos+7] = cy0 + (cy1 - cy0) * t;
coords[pos+8] = cx1;
coords[pos+9] = cy1;
coords[pos+10] = x1;
coords[pos+11] = y1;
}
public Order3(double x0, double y0,
double cx0, double cy0,
double cx1, double cy1,
double x1, double y1,
int direction)
{
super(direction);
// REMIND: Better accuracy in the root finding methods would
// ensure that cys are in range. As it stands, they are never
// more than "1 mantissa bit" out of range...
if (cy0 < y0) cy0 = y0;
if (cy1 > y1) cy1 = y1;
this.x0 = x0;
this.y0 = y0;
this.cx0 = cx0;
this.cy0 = cy0;
this.cx1 = cx1;
this.cy1 = cy1;
this.x1 = x1;
this.y1 = y1;
xmin = Math.min(Math.min(x0, x1), Math.min(cx0, cx1));
xmax = Math.max(Math.max(x0, x1), Math.max(cx0, cx1));
xcoeff0 = x0;
xcoeff1 = (cx0 - x0) * 3.0;
xcoeff2 = (cx1 - cx0 - cx0 + x0) * 3.0;
xcoeff3 = x1 - (cx1 - cx0) * 3.0 - x0;
ycoeff0 = y0;
ycoeff1 = (cy0 - y0) * 3.0;
ycoeff2 = (cy1 - cy0 - cy0 + y0) * 3.0;
ycoeff3 = y1 - (cy1 - cy0) * 3.0 - y0;
YforT1 = YforT2 = YforT3 = y0;
}
public int getOrder() {
return 3;
}
public double getXTop() {
return x0;
}
public double getYTop() {
return y0;
}
public double getXBot() {
return x1;
}
public double getYBot() {
return y1;
}
public double getXMin() {
return xmin;
}
public double getXMax() {
return xmax;
}
public double getX0() {
return (direction == INCREASING) ? x0 : x1;
}
public double getY0() {
return (direction == INCREASING) ? y0 : y1;
}
public double getCX0() {
return (direction == INCREASING) ? cx0 : cx1;
}
public double getCY0() {
return (direction == INCREASING) ? cy0 : cy1;
}
public double getCX1() {
return (direction == DECREASING) ? cx0 : cx1;
}
public double getCY1() {
return (direction == DECREASING) ? cy0 : cy1;
}
public double getX1() {
return (direction == DECREASING) ? x0 : x1;
}
public double getY1() {
return (direction == DECREASING) ? y0 : y1;
}
private double TforY1;
private double YforT1;
private double TforY2;
private double YforT2;
private double TforY3;
private double YforT3;
/*
* Solve the cubic whose coefficients are in the a,b,c,d fields and
* return the first root in the range [0, 1].
* The cubic solved is represented by the equation:
* x^3 + (ycoeff2)x^2 + (ycoeff1)x + (ycoeff0) = y
* @return the first valid root (in the range [0, 1])
*/
public double TforY(double y) {
if (y <= y0) return 0;
if (y >= y1) return 1;
if (y == YforT1) return TforY1;
if (y == YforT2) return TforY2;
if (y == YforT3) return TforY3;
// From Numerical Recipes, 5.6, Quadratic and Cubic Equations
if (ycoeff3 == 0.0) {
// The cubic degenerated to quadratic (or line or ...).
return Order2.TforY(y, ycoeff0, ycoeff1, ycoeff2);
}
double a = ycoeff2 / ycoeff3;
double b = ycoeff1 / ycoeff3;
double c = (ycoeff0 - y) / ycoeff3;
int roots = 0;
double Q = (a * a - 3.0 * b) / 9.0;
double R = (2.0 * a * a * a - 9.0 * a * b + 27.0 * c) / 54.0;
double R2 = R * R;
double Q3 = Q * Q * Q;
double a_3 = a / 3.0;
double t;
if (R2 < Q3) {
double theta = Math.acos(R / Math.sqrt(Q3));
Q = -2.0 * Math.sqrt(Q);
t = refine(a, b, c, y, Q * Math.cos(theta / 3.0) - a_3);
if (t < 0) {
t = refine(a, b, c, y,
Q * Math.cos((theta + Math.PI * 2.0)/ 3.0) - a_3);
}
if (t < 0) {
t = refine(a, b, c, y,
Q * Math.cos((theta - Math.PI * 2.0)/ 3.0) - a_3);
}
} else {
boolean neg = (R < 0.0);
double S = Math.sqrt(R2 - Q3);
if (neg) {
R = -R;
}
double A = Math.pow(R + S, 1.0 / 3.0);
if (!neg) {
A = -A;
}
double B = (A == 0.0) ? 0.0 : (Q / A);
t = refine(a, b, c, y, (A + B) - a_3);
}
if (t < 0) {
//throw new InternalError("bad t");
double t0 = 0;
double t1 = 1;
while (true) {
t = (t0 + t1) / 2;
if (t == t0 || t == t1) {
break;
}
double yt = YforT(t);
if (yt < y) {
t0 = t;
} else if (yt > y) {
t1 = t;
} else {
break;
}
}
}
if (t >= 0) {
TforY3 = TforY2;
YforT3 = YforT2;
TforY2 = TforY1;
YforT2 = YforT1;
TforY1 = t;
YforT1 = y;
}
return t;
}
public double refine(double a, double b, double c,
double target, double t)
{
if (t < -0.1 || t > 1.1) {
return -1;
}
double y = YforT(t);
double t0, t1;
if (y < target) {
t0 = t;
t1 = 1;
} else {
t0 = 0;
t1 = t;
}
double origt = t;
double origy = y;
boolean useslope = true;
while (y != target) {
if (!useslope) {
double t2 = (t0 + t1) / 2;
if (t2 == t0 || t2 == t1) {
break;
}
t = t2;
} else {
double slope = dYforT(t, 1);
if (slope == 0) {
useslope = false;
continue;
}
double t2 = t + ((target - y) / slope);
if (t2 == t || t2 <= t0 || t2 >= t1) {
useslope = false;
continue;
}
t = t2;
}
y = YforT(t);
if (y < target) {
t0 = t;
} else if (y > target) {
t1 = t;
} else {
break;
}
}
boolean verbose = false;
if (false && t >= 0 && t <= 1) {
y = YforT(t);
long tdiff = diffbits(t, origt);
long ydiff = diffbits(y, origy);
long yerr = diffbits(y, target);
if (yerr > 0 || (verbose && tdiff > 0)) {
System.out.println("target was y = "+target);
System.out.println("original was y = "+origy+", t = "+origt);
System.out.println("final was y = "+y+", t = "+t);
System.out.println("t diff is "+tdiff);
System.out.println("y diff is "+ydiff);
System.out.println("y error is "+yerr);
double tlow = prev(t);
double ylow = YforT(tlow);
double thi = next(t);
double yhi = YforT(thi);
if (Math.abs(target - ylow) < Math.abs(target - y) ||
Math.abs(target - yhi) < Math.abs(target - y))
{
System.out.println("adjacent y's = ["+ylow+", "+yhi+"]");
}
}
}
return (t > 1) ? -1 : t;
}
public double XforY(double y) {
if (y <= y0) {
return x0;
}
if (y >= y1) {
return x1;
}
return XforT(TforY(y));
}
public double XforT(double t) {
return (((xcoeff3 * t) + xcoeff2) * t + xcoeff1) * t + xcoeff0;
}
public double YforT(double t) {
return (((ycoeff3 * t) + ycoeff2) * t + ycoeff1) * t + ycoeff0;
}
public double dXforT(double t, int deriv) {
switch (deriv) {
case 0:
return (((xcoeff3 * t) + xcoeff2) * t + xcoeff1) * t + xcoeff0;
case 1:
return ((3 * xcoeff3 * t) + 2 * xcoeff2) * t + xcoeff1;
case 2:
return (6 * xcoeff3 * t) + 2 * xcoeff2;
case 3:
return 6 * xcoeff3;
default:
return 0;
}
}
public double dYforT(double t, int deriv) {
switch (deriv) {
case 0:
return (((ycoeff3 * t) + ycoeff2) * t + ycoeff1) * t + ycoeff0;
case 1:
return ((3 * ycoeff3 * t) + 2 * ycoeff2) * t + ycoeff1;
case 2:
return (6 * ycoeff3 * t) + 2 * ycoeff2;
case 3:
return 6 * ycoeff3;
default:
return 0;
}
}
public double nextVertical(double t0, double t1) {
double eqn[] = {xcoeff1, 2 * xcoeff2, 3 * xcoeff3};
int numroots = QuadCurve2D.solveQuadratic(eqn, eqn);
for (int i = 0; i < numroots; i++) {
if (eqn[i] > t0 && eqn[i] < t1) {
t1 = eqn[i];
}
}
return t1;
}
public void enlarge(Rectangle2D r) {
r.add(x0, y0);
double eqn[] = {xcoeff1, 2 * xcoeff2, 3 * xcoeff3};
int numroots = QuadCurve2D.solveQuadratic(eqn, eqn);
for (int i = 0; i < numroots; i++) {
double t = eqn[i];
if (t > 0 && t < 1) {
r.add(XforT(t), YforT(t));
}
}
r.add(x1, y1);
}
public Curve getSubCurve(double ystart, double yend, int dir) {
if (ystart <= y0 && yend >= y1) {
return getWithDirection(dir);
}
double eqn[] = new double[14];
double t0, t1;
t0 = TforY(ystart);
t1 = TforY(yend);
eqn[0] = x0;
eqn[1] = y0;
eqn[2] = cx0;
eqn[3] = cy0;
eqn[4] = cx1;
eqn[5] = cy1;
eqn[6] = x1;
eqn[7] = y1;
if (t0 > t1) {
/* This happens in only rare cases where ystart is
* very near yend and solving for the yend root ends
* up stepping slightly lower in t than solving for
* the ystart root.
* Ideally we might want to skip this tiny little
* segment and just fudge the surrounding coordinates
* to bridge the gap left behind, but there is no way
* to do that from here. Higher levels could
* potentially eliminate these tiny "fixup" segments,
* but not without a lot of extra work on the code that
* coalesces chains of curves into subpaths. The
* simplest solution for now is to just reorder the t
* values and chop out a miniscule curve piece.
*/
double t = t0;
t0 = t1;
t1 = t;
}
if (t1 < 1) {
split(eqn, 0, t1);
}
int i;
if (t0 <= 0) {
i = 0;
} else {
split(eqn, 0, t0 / t1);
i = 6;
}
return new Order3(eqn[i+0], ystart,
eqn[i+2], eqn[i+3],
eqn[i+4], eqn[i+5],
eqn[i+6], yend,
dir);
}
public Curve getReversedCurve() {
return new Order3(x0, y0, cx0, cy0, cx1, cy1, x1, y1, -direction);
}
public int getSegment(double coords[]) {
if (direction == INCREASING) {
coords[0] = cx0;
coords[1] = cy0;
coords[2] = cx1;
coords[3] = cy1;
coords[4] = x1;
coords[5] = y1;
} else {
coords[0] = cx1;
coords[1] = cy1;
coords[2] = cx0;
coords[3] = cy0;
coords[4] = x0;
coords[5] = y0;
}
return PathIterator.SEG_CUBICTO;
}
public String controlPointString() {
return (("("+round(getCX0())+", "+round(getCY0())+"), ")+
("("+round(getCX1())+", "+round(getCY1())+"), "));
}
}
| bigjoehuang/JDK1.7-source-study | sun/awt/geom/Order3.java |
247,628 | //---------------------------------------------------------------------------
// HMap.java by Dale/Joyce/Weems Chapter 8
//
// Implements a map using an array-based hash table, linear probing collision
// resolution.
//
// The remove operation is not supported. Invoking it will result in the
// unchecked UnsupportedOperationException being thrown.
//
// A map provides (K = key, V = value) pairs, mapping the key onto the value.
// Keys are unique. Keys cannot be null.
//
// Methods throw IllegalArgumentException if passed a null key argument.
//
// Values can be null, so a null value returned by put or get does
// not necessarily mean that an entry did not exist.
//---------------------------------------------------------------------------
package ch08.maps;
import java.util.Iterator;
public class HMap<K, V> implements MapInterface<K,V>
{
protected MapEntry[] map;
protected final int DEFCAP = 1000; // default capacity
protected final double DEFLOAD = 0.75; // default load
protected int origCap; // original capacity
protected int currCap; // current capacity
protected double load;
protected int numPairs = 0; // number of pairs in this map
public HMap()
{
map = new MapEntry[DEFCAP];
origCap = DEFCAP;
currCap = DEFCAP;
load = DEFLOAD;
}
public HMap(int initCap, double initLoad)
{
map = new MapEntry[initCap];
origCap = initCap;
currCap = initCap;
load = initLoad;
}
private void enlarge()
// Increments the capacity of the map by an amount
// equal to the original capacity.
{
// create a snapshot iterator of the map and save current size
Iterator<MapEntry<K,V>> i = iterator();
int count = numPairs;
// create the larger array and reset variables
map = new MapEntry[currCap + origCap];
currCap = currCap + origCap;
numPairs = 0;
// put the contents of the current map into the larger array
MapEntry entry;
for (int n = 1; n <= count; n++)
{
entry = i.next();
this.put((K)entry.getKey(), (V)entry.getValue());
}
}
public V put(K k, V v)
// If an entry in this map with key k already exists then the value
// associated with that entry is replaced by value v and the original
// value is returned; otherwise, adds the (k, v) pair to the map and
// returns null.
{
if (k == null)
throw new IllegalArgumentException("Maps do not allow null keys.");
MapEntry<K, V> entry = new MapEntry<K, V>(k, v);
int location = Math.abs(k.hashCode()) % currCap;
while ((map[location] != null) && !(map[location].getKey().equals(k)))
location = (location + 1) % currCap;
if (map[location] == null) // k was not in map
{
map[location] = entry;
numPairs++;
if ((float)numPairs/currCap > load)
enlarge();
return null;
}
else // k already in map
{
V temp = (V)map[location].getValue();
map[location] = entry;
return temp;
}
}
public V get(K k)
// If an entry in this map with a key k exists then the value associated
// with that entry is returned; otherwise null is returned.
{
if (k == null)
throw new IllegalArgumentException("Maps do not allow null keys.");
int location = Math.abs(k.hashCode()) % currCap;
while ((map[location] != null) && !(map[location].getKey().equals(k)))
location = (location + 1) % currCap;
if (map[location] == null) // k was not in map
return null;
else // k in map
return (V)map[location].getValue();
}
public V remove(K k)
// Throws UnsupportedOperationException.
{
throw new UnsupportedOperationException("HMap does not allow remove.");
}
public boolean contains(K k)
// Returns true if an entry in this map with key k exists;
// Returns false otherwise.
{
if (k == null)
throw new IllegalArgumentException("Maps do not allow null keys.");
int location = Math.abs(k.hashCode()) % currCap;
while (map[location] != null)
if (map[location].getKey().equals(k))
return true;
else
location = (location + 1) % currCap;
// if get this far then no current entry is associated with k
return false;
}
public boolean isEmpty()
// Returns true if this map is empty; otherwise, returns false.
{
return (numPairs == 0);
}
public boolean isFull()
// Returns true if this map is full; otherwise, returns false.
{
return false; // An HMap is never full
}
public int size()
// Returns the number of entries in this map.
{
return numPairs;
}
private class MapIterator implements Iterator<MapEntry<K,V>>
// Provides a snapshot Iterator over this map.
// Remove is not supported and throws UnsupportedOperationException.
{
int listSize = size();
private MapEntry[] list = new MapEntry[listSize];
private int previousPos = -1; // previous position returned from list
public MapIterator()
{
int next = -1;
for (int i = 0; i < listSize; i++)
{
next++;
while (map[next] == null)
next++;
list[i] = map[next];
}
}
public boolean hasNext()
// Returns true if the iteration has more entries; otherwise returns false.
{
return (previousPos < (listSize - 1)) ;
}
public MapEntry<K,V> next()
// Returns the next entry in the iteration.
// Throws NoSuchElementException - if the iteration has no more entries
{
if (!hasNext())
throw new IndexOutOfBoundsException("illegal invocation of next " +
" in HMap iterator.\n");
previousPos++;
return list[previousPos];
}
public void remove()
// Throws UnsupportedOperationException.
// Not supported. Removal from snapshot iteration is meaningless.
{
throw new UnsupportedOperationException("Unsupported remove attempted on "
+ "HMap iterator.\n");
}
}
public Iterator<MapEntry<K,V>> iterator()
// Returns a snapshot Iterator over this map.
// Remove is not supported and throws UnsupportedOperationException.
{
return new MapIterator();
}
}
| mikeyamato/Java_CS20B_In_Class_Wk6 | src/ch08/maps/HMap.java |
247,629 | 404: Not Found | Sheikah45/Neroxis-Map-Generator | src/java/map/Mask.java |
247,631 |
class Text implements Resizable
{
private final Double DEFAULT_SIZE = 10.0;
private Colour colour;
private Double fontSize;
private String text;
public Text() {
fontSize = DEFAULT_SIZE;
}
public Text(String text) {
this.text = text;
fontSize = DEFAULT_SIZE;
}
public Double getFontSize(){
return fontSize;
}
public void setColour(String s){
colour = new Colour(s);
}
public void setText(String newText){
text = newText;
}
public String getText(){
return text ;
}
@Override
public String toString(){
return (text);
}
@Override
public void shrink(Double divisor) throws SizeFactorException {
// TODO Auto-generated method stub
if (divisor < LIMIT) {
throw new SizeFactorException();
}
fontSize = fontSize/divisor;
}
@Override
public void enlarge(Double multiplier) throws SizeFactorException {
// TODO Auto-generated method stub
if (multiplier < LIMIT) {
throw new SizeFactorException();
}
fontSize = fontSize*multiplier;
}
}
| hoxirious/ENSF409_Assignments | Lab5/Exercise_2/Text4.java |
247,632 | public class ArrayDeque<Item> implements Deque<Item> {
private int front;
private int back;
// private int nextFront;
//private int nextBack;
private Item[] arr;
private int size;
private boolean frontAdded;
private boolean backAdded;
public ArrayDeque(){
arr = (Item[]) new Object[8];
this.front=arr.length/2;
this.back=front+1;
// this.nextFront=front;
//this.nextBack=front;
this.size=0;
this.frontAdded=false;
this.backAdded=false;
}
public void addFirst(Item item){
if(size==arr.length){
enlarge();
}
if(frontAdded==false){
arr[front]=item;
frontAdded=true;
}else{
front=minusOne(front);
arr[front]=item;
}
size++;
if(size==arr.length && backAdded==false){
back=minusOne(back);
backAdded=true;
}
}
public void addLast(Item item){
if(size==arr.length){
enlarge();
}
if(backAdded==false){
arr[back]=item;
backAdded=true;
}else{
back=addOne(back);
arr[back]=item;
}
size++;
if(size==arr.length && frontAdded==false){
front=addOne(front);
frontAdded=true;
}
}
public boolean isFull(){
return size==arr.length;
}
public int addOne(int index){
index=index+1;
return index%arr.length;
}
public int minusOne(int index){
index=index-1;
if(index<0){
index=arr.length-1;
}
return index;
}
public boolean isEmpty(){
return size==0;
}
public Item removeFirst(){
//to remove,testing only
//arr[front]=null;
if(size==0){
return null;
}
Item result=null;
if(size==1){
if(frontAdded==true){
frontAdded=false;
size--;
return arr[front];
}else{
backAdded=false;
size--;
return arr[back];
}
}else{
if(frontAdded==false){
front=addOne(front);
frontAdded=true;
}
result=arr[front];
size--;
if(size!=1){
front=addOne(front);
}else{
frontAdded=false;
}
}
return result;
}
public Item removeLast(){
//to remove,testing only
//arr[back]=null;
if(size==0){
return null;
}
Item result=null;
if(size==1){
if(frontAdded==true){
frontAdded=false;
size--;
return arr[front];
}else{
backAdded=false;
size--;
return arr[back];
}
}else{
if(backAdded==false){
back=minusOne(back);
backAdded=true;
}
result=arr[back];
size--;
if(size!=1){
back=minusOne(back);
}else{
backAdded=false;
}
}
return result;
}
public void printDeque(){
int n=size;
int start=-1;
if(frontAdded==false){
start=addOne(front);
}else{
start=front;
}
while(n!=0){
System.out.print(arr[start%size].toString()+" ");
n--;
start=addOne(start);
}
}
public void enlarge(){
Item[] temp=(Item[]) new Object[size*2];
int index=front;
int i=0;
int count=size;
while(count!=0){
temp[i]=arr[index];
index=addOne(index);
i=addOne(i);
count--;
}
arr=temp;
front=0;
back=size-1;
}
public int size(){
return size;
}
public Item get(int index){
if(index<0 ||index>=size){
return null;
}
int fakeFront=-1;
if(frontAdded==false){
fakeFront=addOne(front);
}else{
fakeFront=front;
}
return arr[(fakeFront+index)%size];
}
}
| cqiu32/Deque_Implementation | ArrayDeque.java |
247,633 | import be.kuleuven.cs.som.annotate.*;
import java.sql.Array;
import java.util.Arrays;
import java.util.Date;
/**
* A class representing a single file that has a name, a size, a creation time, a modification time and a writeability.
*
* @version 2.0
* @author Vincent Van Schependom
* @author Flor De Meulemeester
* @author Arne Claerhout
* @invar The size of a file is always greater than or equal to 0 and less than or equal to the defined maximum size.
* | isValidSize(getSize())
*/
public class File {
/**
* Constructs an object with a given (legal) name, size and writeability.
*
* @param name
* The name of the file.
* @param size
* The size of the file.
* @param writeable
* The writeability of the file; either true or false.
* @pre The size must be a legal size, i.e. a positive number, smaller than or equal to the maximum size.
* | canHaveAsSize(size)
* @post The name of the file is set to the parameter name.
* | this.getName() == name
* @post The size of the file is set to the parameter size.
* | this.getSize() == size
* @post The creation time of the file is set to the current time.
* | this.getCreationTime() == new Date()
* @post The writeability of the file is set to the parameter writeable.
* | this.isWriteable() == writeable
*/
@Raw
public File(String name, int size, boolean writeable) {
setName(name);
setSize(size);
setWriteable(writeable);
this.creationTime = new Date();
}
/**
* Constructs an object with a given name, a size of 0 and writeable set to true.
*
* @param name
* The name of the file.
* @effect A new object of the class File is created with the given parameter name,
* the size is set to 0 and the writeability is set to true.
* | this(name, 0, true)
*/
@Raw
public File(String name) {
this(name, 0, true);
}
/**
* The size of the file, represented in bytes. A file can be empty, meaning the size equals 0.
*/
private int size;
/**
* For now, the max size of all files is equal to the biggest possible value of the class Integer.
*/
private static final int MAX_SIZE = Integer.MAX_VALUE;
/**
* The name must only contain letters, digits, periods (.), dashes (-) and underscores (_) and must not be empty.
*/
private String name;
/**
* The creation time is initially set to be NULL and is instantiated when the file is created, in the constructor, after which it isn't changed.
*/
private final Date creationTime;
/**
* The modification time is initially set to be NULL and is instantiated when the file is modified for the first time.
* The modification time is updated every time the file is modified.
* Changing the writeability of the file doesn't change the modification time.
*/
private Date modificationTime;
/**
* Describes if the file is writeable.
*/
private boolean writeable;
/**
* A method for checking if the file is writeable.
*
* @return True if the file is writeable.
* @return False if the file is not writeable.
*/
@Basic
public boolean isWriteable() {
return writeable;
}
/**
* A method for checking if a size is legal.
*
* @param size
* The size to check
* @return True if the size is legal
* @return False if the size is not legal
*/
@Model
private boolean canHaveAsSize(int size) {
return size >= 0 && size < MAX_SIZE;
}
/**
* A method for setting the writeability of the file.
*
* @param writeable
* The writeability to be set, either true or false.
* @post The writeability of the file is set to the parameter writeable.
* | new.isWriteable() == writeable
*/
public void setWriteable(boolean writeable) {
this.writeable = writeable;
}
/**
* A method for getting the file size.
*
* @return The size of the file.
*/
@Basic
public int getSize() {
return this.size;
}
/**
* A method for setting the file size equal to a given positive number of bits, smaller than or equal to the maximum size.
*
* @param size
* The size to be set.
* @pre The size must be a legal size, i.e. a positive number that is smaller than the maximum size.
* | canHaveAsSize(getSize())
* @post The file size is changed to equal the parameter size.
* | new.getSize() == size
*/
private void setSize(int size) {
this.size = size;
}
/**
* A method for increasing the file size with a given positive amount of bits.
*
* @param amountOfBits
* The amount of bits we want to increase the file size with.
* @pre The amountOfBits must be a positive number.
* | amountOfBits > 0
* @pre The writeability of the file must be true.
* | isWriteable()
* @pre The current size of the file, increased with the positive amountOfBits, must not cause overflow.
* | getSize() <= Integer.MAX_VALUE - amountOfBits
* @pre The current size of the file, increased with the positive amountOfBits, must be a legal size.
* | canHaveAsSize(getSize() + amountOfBits)
* @effect The new size of the file is set to the old size of the file, incremented with the parameter amountOfBits.
* | new.getSize() == this.getSize() + amountOfBits
* @throws NotAuthorizedException
* An exception is thrown if the file is not writeable.
* | !isWriteable()
*/
public void enlarge(int amountOfBits) throws NotAuthorizedException {
if (!isWriteable()) {
throw new NotAuthorizedException(this);
}
setSize(getSize() + amountOfBits);
setModificationTime(new Date());
}
/**
* A method for decreasing the file size with a given positive amount of bits.
*
* @param amountOfBits
* The amount of bits we want to decrease the file size with.
* @pre The writeability of the file must be true.
* | isWriteable()
* @pre The amountOfBits must be a positive number.
* | amountOfBits > 0
* @pre The current size of the file, decreased with the positive amountOfBits parameter must be a legal size.
* | canHaveAsSize(getSize() - amountOfBits)
* @effect The new size of the file is set to the old size of the file, decremented with the parameter amountOfBits.
* | new.getSize() == this.getSize() - amountOfBits
* @throws NotAuthorizedException
* An exception is thrown if the file is not writeable.
* | !isWriteable()
*/
public void shorten(int amountOfBits) throws NotAuthorizedException{
if (!isWriteable()) {
throw new NotAuthorizedException(this);
}
setSize(getSize() - amountOfBits);
this.setModificationTime(new Date());
}
/**
* A method for getting the name of the file.
*
* @return The name of the file.
*/
@Basic
public String getName() {
return this.name;
}
/**
* A method for setting the name of the file.
*
* @param name
* The name to be set.
* @post The name of the file is changed to equal the parameter name, only if the name is
* not empty and only contains letters, digits, periods (.), dashes (-) and underscores (_).
*/
// (because of the inertia axioma, the name is not changed if the name is not valid)
private void setName(String name) {
// check the validity of the string with a regex
if (name.matches("[a-zA-Z0-9._-]+"))
this.name = name;
}
/**
* A method for changing the name of the file.
*
* @param newName
* The new name for the file.
* @post The name of the file is changed to the parameter newName, only if it follows the guidelines.
* The name cannot be empty and must only contain letters, digits, periods (.), dashes (-) and underscores (_)
* and the file has to be writeable.
* @post The modification time of the file is set to the current time, if the name is changed.
*/
public void changeName(String newName) throws NotAuthorizedException {
if (!isWriteable()) {
throw new NotAuthorizedException(this);
}
if (!newName.equals(this.name)) {
setName(newName);
// the name was valid and has been changed
if (getName().equals(newName)) {
setModificationTime(new Date());
}
}
}
/**
* A method for getting the creation time of the file.
*
* @return The creation time of the file.
*/
@Basic @Immutable
public Date getCreationTime() {
return this.creationTime;
}
/**
* A method for getting the modification time of the file.
*
* @return The modification time of the file is returned, possibly null.
*/
@Basic
public Date getModificationTime() {
return this.modificationTime;
}
/**
* A method for setting the modification time of the file.
* The modification time shouldn't be changed when the file is created, or when the write authorization is changed.
*
* @param modificationTime
* The modification time to be set.
* @post The modification time of the file is set to the parameter modificationTime.
*/
private void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
/**
* A method for checking if the file has an overlapping usage period with another file.
*
* @param other
* The file to be checked for overlapping usage period.
* @return False if either one of the files doesn't have a modification time.
* @return True if the usage periods of the two files overlap.
*/
public boolean hasOverlappingUsagePeriod(File other) {
// Unchanged files don't have overlapping usage periods.
if (this.modificationTime == null || other.getModificationTime() == null) {
return false;
} else {
if (getCreationTime().before(other.getCreationTime())) {
// The file was created before the other file
return getModificationTime().after(other.getCreationTime());
} else {
// The other file was created before this file
return other.getCreationTime().before(getModificationTime());
}
}
}
}
| FlorDM7/OGP | Practicum1/src/File.java |
247,634 | package opencascade;
/**
* Describes a bounding box in 2D space.
* A bounding box is parallel to the axes of the coordinates
* system. If it is finite, it is defined by the two intervals:
* - [ Xmin,Xmax ], and
* - [ Ymin,Ymax ].
* A bounding box may be infinite (i.e. open) in one or more
* directions. It is said to be:
* - OpenXmin if it is infinite on the negative side of the "X Direction";
* - OpenXmax if it is infinite on the positive side of the "X Direction";
* - OpenYmin if it is infinite on the negative side of the "Y Direction";
* - OpenYmax if it is infinite on the positive side of the "Y Direction";
* - WholeSpace if it is infinite in all four directions. In
* this case, any point of the space is inside the box;
* - Void if it is empty. In this case, there is no point included in the box.
* A bounding box is defined by four bounds (Xmin, Xmax, Ymin and Ymax) which
* limit the bounding box if it is finite, six flags (OpenXmin, OpenXmax, OpenYmin,
* OpenYmax, WholeSpace and Void) which describe the bounding box if it is infinite or empty, and
* - a gap, which is included on both sides in any direction when consulting the finite bounds of the box.
*/
public class Bnd_Box2d {
protected long swigCPtr;
protected boolean swigCMemOwn;
protected Object swigParent;
Bnd_Box2d(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
Bnd_Box2d(long cPtr, boolean cMemoryOwn, Object Parent) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
if ( ! cMemoryOwn ) swigParent = Parent; // keep reference to assumed parent object
}
static long getCPtr(Bnd_Box2d obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
// Auxiliary structure for holding wrapped C reference to object
// requiring explicit decision to use it either as reference or a copy
/*public class CRef {
public CRef (Bnd_Box2d ptr) { Ptr = ptr; }
public Bnd_Box2d AsReference () { return Ptr; }
public Bnd_Box2d AsCopy () { return Ptr.MakeCopy(); }
public Bnd_Box2d Ptr;
}*/
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
OCCwrapJavaJNI.delete_Bnd_Box2d(swigCPtr);
}
swigCPtr = 0;
}
}
/**
* Creates an empty 2D bounding box.
* The constructed box is qualified Void. Its gap is null.
*/
public Bnd_Box2d() {
this(OCCwrapJavaJNI.new_Bnd_Box2d(), true);
}
/**
* Sets this bounding box so that it covers the whole 2D
* space, i.e. it is infinite in all directions.
*/
public void SetWhole() {
OCCwrapJavaJNI.Bnd_Box2d_SetWhole(swigCPtr, this);
}
/**
* Sets this 2D bounding box so that it is empty. All points are outside a void box.
*/
public void SetVoid() {
OCCwrapJavaJNI.Bnd_Box2d_SetVoid(swigCPtr, this);
}
/**
* Sets this 2D bounding box so that it bounds
* the point P. This involves first setting this bounding box
* to be void and then adding the point PThe rectangle bounds the point <P>.
*/
public void Set( gp_Pnt2d thePnt) {
OCCwrapJavaJNI.Bnd_Box2d_Set__SWIG_0(swigCPtr, this, gp_Pnt2d.getCPtr(thePnt), thePnt);
}
/**
* Sets this 2D bounding box so that it bounds
* the half-line defined by point P and direction D, i.e. all
* points M defined by M=P+u*D, where u is greater than
* or equal to 0, are inside the bounding area. This involves
* first setting this 2D box to be void and then adding the half-line.
*/
public void Set( gp_Pnt2d thePnt, gp_Dir2d theDir) {
OCCwrapJavaJNI.Bnd_Box2d_Set__SWIG_1(swigCPtr, this, gp_Pnt2d.getCPtr(thePnt), thePnt, gp_Dir2d.getCPtr(theDir), theDir);
}
/**
* Enlarges this 2D bounding box, if required, so that it
* contains at least:
* - interval [ aXmin,aXmax ] in the "X Direction",
* - interval [ aYmin,aYmax ] in the "Y Direction"
*/
public void Update(double aXmin, double aYmin, double aXmax, double aYmax) {
OCCwrapJavaJNI.Bnd_Box2d_Update__SWIG_0(swigCPtr, this, aXmin, aYmin, aXmax, aYmax);
}
/**
* Adds a point of coordinates (X,Y) to this bounding box.
*/
public void Update(double X, double Y) {
OCCwrapJavaJNI.Bnd_Box2d_Update__SWIG_1(swigCPtr, this, X, Y);
}
/**
* Returns the gap of this 2D bounding box.
*/
public double GetGap() {
return OCCwrapJavaJNI.Bnd_Box2d_GetGap(swigCPtr, this);
}
/**
* Set the gap of this 2D bounding box to abs(Tol).
*/
public void SetGap(double Tol) {
OCCwrapJavaJNI.Bnd_Box2d_SetGap(swigCPtr, this, Tol);
}
/**
* Enlarges the box with a tolerance value.
* This means that the minimum values of its X and Y
* intervals of definition, when they are finite, are reduced by
* the absolute value of Tol, while the maximum values are
* increased by the same amount.
*/
public void Enlarge(double theTol) {
OCCwrapJavaJNI.Bnd_Box2d_Enlarge(swigCPtr, this, theTol);
}
/**
* Returns the bounds of this 2D bounding box.
* The gap is included. If this bounding box is infinite (i.e. "open"), returned values
* may be equal to +/- Precision::Infinite().
* if IsVoid()
*/
public void Get(double[] aXmin, double[] aYmin, double[] aXmax, double[] aYmax) {
OCCwrapJavaJNI.Bnd_Box2d_Get(swigCPtr, this, aXmin, aYmin, aXmax, aYmax);
}
/**
* The Box will be infinitely long in the Xmin direction.
*/
public void OpenXmin() {
OCCwrapJavaJNI.Bnd_Box2d_OpenXmin(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Xmax direction.
*/
public void OpenXmax() {
OCCwrapJavaJNI.Bnd_Box2d_OpenXmax(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Ymin direction.
*/
public void OpenYmin() {
OCCwrapJavaJNI.Bnd_Box2d_OpenYmin(swigCPtr, this);
}
/**
* The Box will be infinitely long in the Ymax direction.
*/
public void OpenYmax() {
OCCwrapJavaJNI.Bnd_Box2d_OpenYmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Xmin direction.
*/
public long IsOpenXmin() {
return OCCwrapJavaJNI.Bnd_Box2d_IsOpenXmin(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Xmax direction.
*/
public long IsOpenXmax() {
return OCCwrapJavaJNI.Bnd_Box2d_IsOpenXmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Ymin direction.
*/
public long IsOpenYmin() {
return OCCwrapJavaJNI.Bnd_Box2d_IsOpenYmin(swigCPtr, this);
}
/**
* Returns true if this bounding box is open in the Ymax direction.
*/
public long IsOpenYmax() {
return OCCwrapJavaJNI.Bnd_Box2d_IsOpenYmax(swigCPtr, this);
}
/**
* Returns true if this bounding box is infinite in all 4
* directions (Whole Space flag).
*/
public long IsWhole() {
return OCCwrapJavaJNI.Bnd_Box2d_IsWhole(swigCPtr, this);
}
/**
* Returns true if this 2D bounding box is empty (Void flag).
*/
public long IsVoid() {
return OCCwrapJavaJNI.Bnd_Box2d_IsVoid(swigCPtr, this);
}
/**
* Returns a bounding box which is the result of applying the
* transformation T to this bounding box.
* Warning
* Applying a geometric transformation (for example, a
* rotation) to a bounding box generally increases its
* dimensions. This is not optimal for algorithms which use it.
*/
public Bnd_Box2d Transformed( gp_Trsf2d T) {
return new Bnd_Box2d(OCCwrapJavaJNI.Bnd_Box2d_Transformed(swigCPtr, this, gp_Trsf2d.getCPtr(T), T), true);
}
public void Add( Bnd_Box2d Other) {
OCCwrapJavaJNI.Bnd_Box2d_Add__SWIG_0(swigCPtr, this, Bnd_Box2d.getCPtr(Other), Other);
}
public void Add( gp_Pnt2d thePnt) {
OCCwrapJavaJNI.Bnd_Box2d_Add__SWIG_1(swigCPtr, this, gp_Pnt2d.getCPtr(thePnt), thePnt);
}
/**
* Adds the 2d box <Other> to <me>.
*/
public void Add( gp_Pnt2d thePnt, gp_Dir2d theDir) {
OCCwrapJavaJNI.Bnd_Box2d_Add__SWIG_2(swigCPtr, this, gp_Pnt2d.getCPtr(thePnt), thePnt, gp_Dir2d.getCPtr(theDir), theDir);
}
/**
* Adds the 2d point.
*/
public void Add( gp_Dir2d D) {
OCCwrapJavaJNI.Bnd_Box2d_Add__SWIG_3(swigCPtr, this, gp_Dir2d.getCPtr(D), D);
}
/**
* Returns True if the 2d pnt <P> is out <me>.
*/
public long IsOut( gp_Pnt2d P) {
return OCCwrapJavaJNI.Bnd_Box2d_IsOut__SWIG_0(swigCPtr, this, gp_Pnt2d.getCPtr(P), P);
}
/**
* Returns True if <Box2d> is out <me>.
*/
public long IsOut( Bnd_Box2d Other) {
return OCCwrapJavaJNI.Bnd_Box2d_IsOut__SWIG_1(swigCPtr, this, Bnd_Box2d.getCPtr(Other), Other);
}
/**
* Returns True if transformed <Box2d> is out <me>.
*/
public long IsOut( Bnd_Box2d theOther, gp_Trsf2d theTrsf) {
return OCCwrapJavaJNI.Bnd_Box2d_IsOut__SWIG_2(swigCPtr, this, Bnd_Box2d.getCPtr(theOther), theOther, gp_Trsf2d.getCPtr(theTrsf), theTrsf);
}
public long IsOut( gp_Trsf2d T1, Bnd_Box2d Other, gp_Trsf2d T2) {
return OCCwrapJavaJNI.Bnd_Box2d_IsOut__SWIG_3(swigCPtr, this, gp_Trsf2d.getCPtr(T1), T1, Bnd_Box2d.getCPtr(Other), Other, gp_Trsf2d.getCPtr(T2), T2);
}
public void Dump() {
OCCwrapJavaJNI.Bnd_Box2d_Dump(swigCPtr, this);
}
/**
* Computes the squared diagonal of me.
*/
public double SquareExtent() {
return OCCwrapJavaJNI.Bnd_Box2d_SquareExtent(swigCPtr, this);
}
}
| Aircraft-Design-UniNa/jpad-occt | OCCJava/Bnd_Box2d.java |
247,635 | // @(#)BitSet.java 9/2002
// Copyright (c) 1998-2002, Distributed Real-time Computing Lab (DRCL)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of "DRCL" nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package drcl.data;
import java.io.*;
/**
* This class implements a set of bits that grows as needed. Each
* bit of the set has a <code>boolean</code> value. The
* bits of a <code>BitSet</code> are indexed by nonnegative integers.
* Individual indexed bit can be examined, set, or cleared. One
* <code>BitSet</code> may be used to modify the contents of another
* <code>BitSet</code> through logical AND, logical inclusive OR, and
* logical exclusive OR operations.
* <p>
* By default, all bits in the set initially have the value
* <code>false</code>.
* <p>
* Every bit set has a size, which is the number of bits in use
* by the bit set. Note that the actual size is the actual number of bits
* that the bit set is able to represent. The size as well as the actual
* size is changed when the bit index of an operation exceeds the sizes.
* Also the size can be set explicitly with <code>setSize(int)</code>.
* The most significant bits are truncated when a smaller size is set.
*
* Bits are packed into arrays of subsets(<code>long</code>s). Each subset
* is indexed with nonnegative integers. Index 0 refers to the subset
* containing
* the first 64 least significant bits. BitSet operations also apply to subsets.
*/
public class BitSet extends drcl.DrclObj
{
/*
*/
//private final static int ADDRESS_BITS_PER_UNIT = 6;
//private final static int BITS_PER_UNIT = 1 << ADDRESS_BITS_PER_UNIT;
//private final static int BIT_INDEX_MASK = BITS_PER_UNIT - 1;
/**
* The subset in this BitSet. The ith bit is stored in subset[i/64] at
* bit position i % 64 (where bit position 0 refers to the least
* significant bit and 63 refers to the most significant bit).
*
* @serial
*/
protected long subset[];
protected int nb; // # of bits in use (user-defined)
protected int nsubsets; //# of subsets in use (from nb)
protected int nbset; // # of set bits
int[] indices; // indices of set bits
int[] uindices; // indices of unset bits
public BitSet (int size_, long value_)
{
this(size_);
set(0, value_);
}
/**
* Creates and returns a bit set of the specified size given an array
* of long integers. Bit 0 of <code>values_[0]</code> is stored
* as the least significant bit, and bit 63 of <code>values_[size-1]</code>
* as the most significant bit.
*/
public BitSet (int size_, long[] values_)
{
this(size_);
if (values_ != null)
for (int i=0; i<values_.length; i++)
set(i, values_[i]);
}
/**
* Creates and returns a bit set in which the bits of the positions
* specified in <code>set_</code> are set to 1's.
* The length of the bit set is set to the maximum value in
* <code>set_</code>.
*/
public BitSet (int[] set_)
{
this(0);
if (set_ != null) {
int maxIndex_ = -1;
for (int i=0; i<set_.length; i++)
if (set_[i] > maxIndex_) maxIndex_ = set_[i];
setSize(maxIndex_ + 1);
set(set_);
}
}
/**
* Creates a new bit set. All subset are initially <code>false</code>.
*/
public BitSet()
{this(64); }
/**
* Creates a bit set whose initial size is large enough to explicitly
* represent subset with indices in the range <code>0</code> through
* <code>nbits-1</code>. All subset are initially <code>false</code>.
*
* @param nbits the initial size of the bit set.
* @exception NegativeArraySizeException if the specified initial size
* is negative.
*/
public BitSet(int nbits_)
{
/* nbits can't be negative; size 0 is OK */
if (nbits_ < 0)
throw new NegativeArraySizeException(Integer.toString(nbits_));
nb = nbits_;
nsubsets = (nb + 63) >> 6;
subset = new long[nsubsets];
}
/**
* Returns the "logical size" of this <code>BitSet</code>.
*
* @return the logical size of this <code>BitSet</code>.
*/
public int getSize() { return nb; }
/**
* If <code>size_</code> is larger than the current size,
* the bit set expands from the most significant bit and
* the new bits are cleared (set to false).
*/
public void setSize(int size_)
{
int nb_, nsubsets_;
if (size_ > nb) {
nb_ = nb;
nsubsets_ = nsubsets;
nb = size_;
nsubsets = (nb + 63) >> 6;
/*
if (debug)
System.out.println("old nb=" + nb_ + ",old nsubsets=" + nsubsets_
+ ", nb=" + nb + ",nsubsets=" + nsubsets
+ "subset.length=" + subset.length);
*/
if (nsubsets > subset.length) enlarge(nsubsets);
// clear the new bits
for (int i=nsubsets_; i<nsubsets; i++) set(i, 0L);
/*
int nbits_ = nb_ % 64;
if (nbits_ > 0) {
long k = 1L;
for (int i=1; i<nbits_; i++) k = (k << 1) | 1L;
subset[nsubsets_ - 1] &= k;
}
*/
}
else {
nb = nb_ = size_;
nsubsets = nsubsets_ = (nb + 63) >> 6;
//nbset();
nbset = -1;
}
// clear the new/unused bits
int nbits_ = nb_ % 64;
if (nbits_ > 0)
subset[nsubsets_ - 1] &= (1L << nbits_) - 1;
}
/**
* Returns the number of bits that are set true in this bit set.
*/
public int getNumSetBits()
{
if (nbset < 0) nbset(); // update it
return nbset;
}
// XXX: this could speed up getSetBitIndices() and getUnsetBitIndices...
// unfinished
static int[][] INDICES = {
{},
{0},
{1},
{0,1},
{2},
{0,2},
{1,2},
{0,1,2},
{3},
{0,3},
{1,3},
{0,1,3},
{2,3},
{0,2,3},
{1,2,3},
{0,1,2,3},
{4},
{0,4},
{1,4},
{0,1,4},
{2,4},
{0,2,4},
{1,2,4},
{0,1,2,4},
{3,4},
{0,3,4},
{1,3,4},
{0,1,3,4},
{2,3,4},
{0,2,3,4},
{1,2,3,4},
{0,1,2,3,4},
{5},
{0,5},
{1,5},
{0,1,5},
{2,5},
{0,2,5},
{1,2,5},
{0,1,2,5},
{3,5},
{0,3,5},
{1,3,5},
{0,1,3,5},
{2,3,5},
{0,2,3,5},
{1,2,3,5},
{0,1,2,3,5},
{4,5},
{0,4,5},
{1,4,5},
{0,1,4,5},
{2,4,5},
{0,2,4,5},
{1,2,4,5},
{0,1,2,4,5},
{3,4,5},
{0,3,4,5},
{1,3,4,5},
{0,1,3,4,5},
{2,3,4,5},
{0,2,3,4,5},
{1,2,3,4,5},
{0,1,2,3,4,5},
{6},
{0,6},
{1,6},
{0,1,6},
{2,6},
{0,2,6},
{1,2,6},
{0,1,2,6},
{3,6},
{0,3,6},
{1,3,6},
{0,1,3,6},
{2,3,6},
{0,2,3,6},
{1,2,3,6},
{0,1,2,3,6},
{4,6},
{0,4,6},
{1,4,6},
{0,1,4,6},
{2,4,6},
{0,2,4,6},
{1,2,4,6},
{0,1,2,4,6},
{3,4,6},
{0,3,4,6},
{1,3,4,6},
{0,1,3,4,6},
{2,3,4,6},
{0,2,3,4,6},
{1,2,3,4,6},
{0,1,2,3,4,6},
{5,6},
{0,5,6},
{1,5,6},
{0,1,5,6},
{2,5,6},
{0,2,5,6},
{1,2,5,6},
{0,1,2,5,6},
{3,5,6},
{0,3,5,6},
{1,3,5,6},
{0,1,3,5,6},
{2,3,5,6},
{0,2,3,5,6},
{1,2,3,5,6},
{0,1,2,3,5,6},
{4,5,6},
{0,4,5,6},
{1,4,5,6},
{0,1,4,5,6},
{2,4,5,6},
{0,2,4,5,6},
{1,2,4,5,6},
{0,1,2,4,5,6},
{3,4,5,6},
{0,3,4,5,6},
{1,3,4,5,6},
{0,1,3,4,5,6},
{2,3,4,5,6},
{0,2,3,4,5,6},
{1,2,3,4,5,6},
{0,1,2,3,4,5,6},
{7},
{0,7},
{1,7},
{0,1,7},
{2,7},
{0,2,7},
{1,2,7},
{0,1,2,7},
{3,7},
{0,3,7},
{1,3,7},
{0,1,3,7},
{2,3,7},
{0,2,3,7},
{1,2,3,7},
{0,1,2,3,7},
{4,7},
{0,4,7},
{1,4,7},
{0,1,4,7},
{2,4,7},
{0,2,4,7},
{1,2,4,7},
{0,1,2,4,7},
{3,4,7},
{0,3,4,7},
{1,3,4,7},
{0,1,3,4,7},
{2,3,4,7},
{0,2,3,4,7},
{1,2,3,4,7},
{0,1,2,3,4,7},
{5,7},
{0,5,7},
{1,5,7},
{0,1,5,7},
{2,5,7},
{0,2,5,7},
{1,2,5,7},
{0,1,2,5,7},
{3,5,7},
{0,3,5,7},
{1,3,5,7},
{0,1,3,5,7},
{2,3,5,7},
{0,2,3,5,7},
{1,2,3,5,7},
{0,1,2,3,5,7},
{4,5,7},
{0,4,5,7},
{1,4,5,7},
{0,1,4,5,7},
{2,4,5,7},
{0,2,4,5,7},
{1,2,4,5,7},
{0,1,2,4,5,7},
{3,4,5,7},
{0,3,4,5,7},
{1,3,4,5,7},
{0,1,3,4,5,7},
{2,3,4,5,7},
{0,2,3,4,5,7},
{1,2,3,4,5,7},
{0,1,2,3,4,5,7},
{6,7},
{0,6,7},
{1,6,7},
{0,1,6,7},
{2,6,7},
{0,2,6,7},
{1,2,6,7},
{0,1,2,6,7},
{3,6,7},
{0,3,6,7},
{1,3,6,7},
{0,1,3,6,7},
{2,3,6,7},
{0,2,3,6,7},
{1,2,3,6,7},
{0,1,2,3,6,7},
{4,6,7},
{0,4,6,7},
{1,4,6,7},
{0,1,4,6,7},
{2,4,6,7},
{0,2,4,6,7},
{1,2,4,6,7},
{0,1,2,4,6,7},
{3,4,6,7},
{0,3,4,6,7},
{1,3,4,6,7},
{0,1,3,4,6,7},
{2,3,4,6,7},
{0,2,3,4,6,7},
{1,2,3,4,6,7},
{0,1,2,3,4,6,7},
{5,6,7},
{0,5,6,7},
{1,5,6,7},
{0,1,5,6,7},
{2,5,6,7},
{0,2,5,6,7},
{1,2,5,6,7},
{0,1,2,5,6,7},
{3,5,6,7},
{0,3,5,6,7},
{1,3,5,6,7},
{0,1,3,5,6,7},
{2,3,5,6,7},
{0,2,3,5,6,7},
{1,2,3,5,6,7},
{0,1,2,3,5,6,7},
{4,5,6,7},
{0,4,5,6,7},
{1,4,5,6,7},
{0,1,4,5,6,7},
{2,4,5,6,7},
{0,2,4,5,6,7},
{1,2,4,5,6,7},
{0,1,2,4,5,6,7},
{3,4,5,6,7},
{0,3,4,5,6,7},
{1,3,4,5,6,7},
{0,1,3,4,5,6,7},
{2,3,4,5,6,7},
{0,2,3,4,5,6,7},
{1,2,3,4,5,6,7},
{0,1,2,3,4,5,6,7},
/*
{},
{0},
{1},
{0,1},
{2},
{0,2},
{1,2},
{0,1,2},
{3},
{0,3},
{1,3},
{0,1,3},
{2,3},
{0,2,3},
{1,2,3},
{0,1,2,3},
*/
};
/**
* Returns the array of indices of the bits that are set true in this bit
* set.
*
* @return the array of indices of the set bits.
*/
public int[] getSetBitIndices()
{
if (nbset < 0) nbset(); // update it
if (indices != null) {
int[] indices_ = new int[nbset];
System.arraycopy(indices, 0, indices_, 0, nbset);
return indices_;
}
int[] indices_ = new int[nbset];
/* use get(i)
int j = 0;
for (int i=0; i<nb; i++)
if (get(i)) indices_[j++] = i;
*/
/* moves get() code here and simplifies it, not much improvement
int j = 0;
int index_ = 0;
for (int i=0; i<subset.length; i++) {
for (long mask_ = 1L; mask_ != 0; mask_ <<= 1) {
if ((subset[i] & mask_) != 0) indices_[j++] = index_;
index_++;
}
}
*/
// this is much better, use only 1/8 of the time for the above
int j = 0, shift_ = 0;
//if (debug) System.out.println("nsubsets = " + nsubsets);
for (int i=0; i<nsubsets; i++) {
long subset_ = subset[i];
for (int k=0; k<64; k+=8) {
int[] tmp_ = INDICES[(int)((subset_ >> k) & 0x0FFL)];
if (tmp_.length > 0) {
/*
if (debug)
System.out.println(shift_ + " >> "
+ drcl.util.StringUtil.toString(
tmp_, ",", Integer.MAX_VALUE));
*/
try {
System.arraycopy(tmp_, 0, indices_, j, tmp_.length);
}
catch (ArrayIndexOutOfBoundsException e_) {
e_.printStackTrace();
System.out.println("subset_=" + subset_ + ", " + shift_ + " >> "
+ drcl.util.StringUtil.toString(
tmp_, ",", Integer.MAX_VALUE));
System.out.println("nb=" + nb + ", j=" + j + ", nbset=" + nbset);
}
int m = j;
j += tmp_.length;
for (; m < j; m++) indices_[m] += shift_;
/*
if (debug)
System.out.println(drcl.util.StringUtil.toString(
indices_, ",", Integer.MAX_VALUE));
*/
}
shift_ += 8;
}
}
indices = new int[nbset];
System.arraycopy(indices_, 0, indices, 0, nbset);
return indices_;
}
//public static boolean debug = false;
/**
* Returns the array of indices of the bits that are set false in this bit
* set.
*
* @return the array of indices of the unset bits.
*/
public int[] getUnsetBitIndices()
{
/*
if (nbset < 0) nbset(); // update it
int[] indices_ = new int[getSize() - nbset];
int j = 0;
for (int i=0; i<nb; i++)
if (!get(i)) indices_[j++] = i;
return indices_;
*/
/*
BitSet clone_ = (BitSet)clone();
clone_.not();
return clone_.getSetBitIndices();
*/
if (nbset < 0) nbset(); // update it
if (uindices != null) {
int[] indices_ = new int[uindices.length];
System.arraycopy(uindices, 0, indices_, 0, uindices.length);
return indices_;
}
BitSet clone_ = (BitSet)clone();
clone_.not();
int[] indices_ = clone_.getSetBitIndices();
uindices = new int[indices_.length];
System.arraycopy(indices_, 0, uindices, 0, indices_.length);
return indices_;
}
/**
* Returns the number of bits actually used by this
* <code>BitSet</code> to represent bit values.
* The maximum element in the set is the size - 1st element.
*
* @return the number of bits currently in this <code>BitSet</code>.
*/
public int getActualSize() { return subset.length << 6; }
//
void ___BIT_OP___() {}
//
/**
* Sets all the bits.
*/
public void set()
{
for (int i=0; i<nsubsets; i++)
subset[i] |= -1L;
nbset = nb;
indices = null;
uindices = null;
}
/**
* Sets the bit specified by the index to <code>true</code>.
*
* @param bitIndex_ a bit index.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public void set(int bitIndex_)
{
if (bitIndex_ < 0)
throw new IndexOutOfBoundsException(Integer.toString(bitIndex_));
int subsetIndex_ = bitIndex_ >> 6;
if (bitIndex_ >= nb) {
setSize(bitIndex_ + 1);
/*
nb = bitIndex_ + 1;
if (nsubsets <= subsetIndex_) {
nsubsets = subsetIndex_ + 1;
enlarge(nsubsets);
}
*/
}
long mask_ = 1L << (bitIndex_ & 63);
if ((subset[subsetIndex_] & mask_) == 0) {
subset[subsetIndex_] |= mask_;
if (nbset >= 0) nbset ++;
indices = null;
uindices = null;
}
}
/**
* Sets the bits specified by the indices to <code>true</code>.
*
* @param bitIndices_ array of bit indices.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public void set(int[] bitIndices_)
{
for (int i=0; i<bitIndices_.length; i++) {
int bitIndex_ = bitIndices_[i];
if (bitIndex_ < 0)
throw new IndexOutOfBoundsException(Integer.toString(bitIndex_));
int subsetIndex_ = bitIndex_ >> 6;
if (bitIndex_ >= nb) {
setSize(bitIndex_ + 1);
/*
nb = bitIndex_ + 1;
if (nsubsets <= subsetIndex_) {
nsubsets = subsetIndex_ + 1;
enlarge(nsubsets);
}
*/
}
long mask_ = 1L << (bitIndex_ & 63);
if ((subset[subsetIndex_] & mask_) == 0) {
subset[subsetIndex_] |= mask_;
if (nbset >= 0) nbset ++;
indices = null;
uindices = null;
}
}
}
/**
* Sets the subset specified by the index to the argument subset.
* This operation does not change the size of the bit set.
*
* @param subsetIndex_ the subset index.
* @param subset_ the subset with which to mask the corresponding
* subset in this <code>BitSet</code>.
*/
public void set(int subsetIndex_, long subset_)
{
if (subsetIndex_ >= subset.length) {
setSize((subsetIndex_ + 1) << 6);
//enlarge(subsetIndex_ + 1);
}
subset[subsetIndex_] = subset_;
//nbset();
nbset = -1;
}
/**
* Clears all the bits.
*/
public void clear()
{
for (int i=0; i<nsubsets; i++)
subset[i] = 0;
nbset = 0;
indices = null;
uindices = null;
}
/**
* Sets the bit specified by the index to <code>false</code>.
*
* @param bitIndex_ the index of the bit to be cleared.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public void clear(int bitIndex_)
{
if (bitIndex_ < 0)
throw new IndexOutOfBoundsException(Integer.toString(bitIndex_));
if (bitIndex_ >= nb) return;
int subsetIndex_ = bitIndex_ >> 6;
long mask_ = 1L << (bitIndex_ & 63);
if ((subset[subsetIndex_] & mask_) != 0) {
subset[subsetIndex_] &= ~mask_;
if (nbset >= 0) nbset --;
indices = null;
uindices = null;
}
}
/**
* Sets the bits specified by the indices to <code>false</code>.
*
* @param bitIndices_ array of bit indices.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public void clear(int[] bitIndices_)
{
for (int i=0; i<bitIndices_.length; i++) {
int bitIndex_ = bitIndices_[i];
if (bitIndex_ < 0)
throw new IndexOutOfBoundsException(
Integer.toString(bitIndex_));
if (bitIndex_ >= nb) return;
int subsetIndex_ = bitIndex_ >> 6;
long mask_ = 1L << (bitIndex_ & 63);
if ((subset[subsetIndex_] & mask_) != 0) {
subset[subsetIndex_] &= ~mask_;
if (nbset >= 0) nbset --;
indices = null;
uindices = null;
}
}
}
/**
* Clears all of the subset in this <code>BitSet</code> whose corresponding
* bit is set in the specified <code>BitSet</code>.
*
* @param set_ the <code>BitSet</code> with which to mask this
* <code>BitSet</code>.
*/
public void clearBy(BitSet set_)
{
int nsubsets_ = nsubsets > set_.nsubsets? set_.nsubsets: nsubsets;
// perform logical (a & !b) on subset in common
for (int i=0; i<nsubsets_; i++)
subset[i] &= ~set_.subset[i];
//nbset();
nbset = -1;
}
/**
* Clears the subset in this <code>BitSet</code> whose corresponding
* bit is set in the specified subset.
* This operation does not change the size of the bit set.
*
* @param subsetIndex_ the subset index.
* @param subset_ the subset with which to mask the corresponding
* subset in this <code>BitSet</code>.
*/
public void clearBy(int subsetIndex_, long subset_)
{
if (subsetIndex_ >= subset.length) enlarge(subsetIndex_ + 1);
// perform logical (a & !b) on subset in common
subset[subsetIndex_] &= ~subset_;
//nbset();
nbset = -1;
}
/**
* Returns the value of the bit with the specified index. The value
* is <code>true</code> if the bit with the index <code>bitIndex_</code>
* is currently set in this <code>BitSet</code>; otherwise, the result
* is <code>false</code>.
*
* @param bitIndex_ the bit index.
* @return the value of the bit with the specified index.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public boolean get(int bitIndex_)
{
if (bitIndex_ < 0)
throw new IndexOutOfBoundsException(Integer.toString(bitIndex_));
if (bitIndex_ >= nb) return false;
int subsetIndex_ = bitIndex_ >> 6;
return ((subset[subsetIndex_] & (1L << (bitIndex_ & 63))) != 0);
}
/**
* Returns the subset specified by the index to the argument subset.
*
* @param subsetIndex_ the subset index.
* @return the subset withe the specified index.
* @exception IndexOutOfBoundsException if the specified index is negative.
*/
public long getSubset(int subsetIndex_)
{
if (subsetIndex_ < 0)
throw new IndexOutOfBoundsException(Integer.toString(subsetIndex_));
if (subsetIndex_ >= subset.length) return 0;
else return subset[subsetIndex_];
}
/**
* Performs a logical <b>AND</b> of this target bit set with the
* argument bit set. This bit set is modified so that each bit in it
* has the value <code>true</code> if and only if it both initially
* had the value <code>true</code> and the corresponding bit in the
* bit set argument also had the value <code>true</code>.
*
* @param set_ a bit set.
*/
public void and(BitSet set_)
{
if (set_ == this) return;
int nsubsets_ = nsubsets > set_.nsubsets? set_.nsubsets: nsubsets;
int i;
for(i=0; i<nsubsets_; i++) subset[i] &= set_.subset[i];
for (; i<nsubsets; i++) subset[i] = 0;
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>AND</b> of the target subset with the
* argument subset. This subset is modified so that each bit in it
* has the value <code>true</code> if and only if it both initially
* had the value <code>true</code> and the corresponding bit in the
* subset argument also had the value <code>true</code>.
* This operation does not change the size of the bit set.
*
* @param subsetIndex_ the subset index.
* @param subset_ the subset with which to mask the corresponding
* subset in this <code>BitSet</code>.
*/
public void and(int subsetIndex_, long subset_)
{
if (subsetIndex_ >= subset.length) enlarge(subsetIndex_ + 1);
// perform logical (a & !b) on subset in common
subset[subsetIndex_] &= subset_;
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>OR</b> of this bit set with the bit set
* argument. This bit set is modified so that a bit in it has the
* value <code>true</code> if and only if it either already had the
* value <code>true</code> or the corresponding bit in the bit set
* argument has the value <code>true</code>.
* This operation does not change the size of the bit set.
*
* @param set_ a bit set.
*/
public void or(BitSet set_)
{
if (set_ == this) return;
int nsubsets_ = nsubsets > set_.nsubsets? set_.nsubsets: nsubsets;
if (nb < set_.nb) {
nb = set_.nb;
nsubsets = (nb + 63) >> 6;
if (nsubsets > subset.length) enlarge(nsubsets);
}
int i;
for(i=0; i<nsubsets_; i++) subset[i] |= set_.subset[i];
if (i < set_.nsubsets)
for (; i<nsubsets; i++) subset[i] = set_.subset[i];
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>OR</b> of the target subset with the
* argument subset. This subset is modified so that each bit in it
* has the value <code>true</code> if and only if it both initially
* had the value <code>true</code> or the corresponding bit in the
* subset argument also had the value <code>true</code>.
*
* @param subsetIndex_ the subset index.
* @param subset_ the subset with which to mask the corresponding
* subset in this <code>BitSet</code>.
*/
public void or(int subsetIndex_, long subset_)
{
if (subsetIndex_ >= subset.length) enlarge(subsetIndex_ + 1);
// perform logical (a & !b) on subset in common
subset[subsetIndex_] |= subset_;
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>XOR</b> of this bit set with the bit set
* argument. This bit set is modified so that a bit in it has the
* value <code>true</code> if and only if one of the following
* statements holds:
* <ul>
* <li>The bit initially has the value <code>true</code>, and the
* corresponding bit in the argument has the value <code>false</code>.
* <li>The bit initially has the value <code>false</code>, and the
* corresponding bit in the argument has the value <code>true</code>.
* </ul>
*
* @param set_ a bit set.
*/
public void xor(BitSet set_)
{
if (set_ == this) {
for (int i=0; i<nsubsets; i++) subset[i] = 0;
return;
}
int nsubsets_ = nsubsets > set_.nsubsets? set_.nsubsets: nsubsets;
if (nb < set_.nb) {
nb = set_.nb;
nsubsets = (nb + 63) >> 6;
if (nsubsets > subset.length) enlarge(nsubsets);
}
int i;
for(i=0; i<nsubsets_; i++) subset[i] ^= set_.subset[i];
if (i < set_.nsubsets)
for (; i<nsubsets; i++) subset[i] = set_.subset[i];
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>XOR</b> of the target subset with the
* argument subset. This subset is modified so that a bit in it has the
* value <code>true</code> if and only if one of the following
* statements holds:
* <ul>
* <li>The bit initially has the value <code>true</code>, and the
* corresponding bit in the argument has the value <code>false</code>.
* <li>The bit initially has the value <code>false</code>, and the
* corresponding bit in the argument has the value <code>true</code>.
* </ul>
* This operation does not change the size of the bit set.
*
* @param subsetIndex_ the subset index.
* @param subset_ the subset with which to mask the corresponding
* subset in this <code>BitSet</code>.
*/
public void xor(int subsetIndex_, long subset_)
{
if (subsetIndex_ >= subset.length) enlarge(subsetIndex_ + 1);
// perform logical (a & !b) on subset in common
subset[subsetIndex_] ^= subset_;
//nbset();
nbset = -1;
}
/**
* Performs a logical <b>NOT</b> of the this bitset.
* This operation does not change the size of the bit set.
*/
public void not()
{
for(int i=0; i<nsubsets; i++) subset[i] ^= -1L;
if (nbset >= 0) nbset = nb - nbset;
int nbits_ = nb % 64;
if (nbits_ > 0)
subset[nsubsets - 1] &= (1L << nbits_) - 1;
indices = null;
uindices = null;
}
//
void ___MISC___() {}
//
static int[] NUM_SET_BITS = {
};
/**
* Recalculates the number of set bits.
*/
private void nbset()
{
indices = uindices = null;
nbset = 0;
int i;
for (i=0; i<nsubsets - 1; i++) {
long k = 1L;
for (int j=0; j<64; j++) {
if ((subset[i] & k) != 0) nbset ++;
k = k << 1;
}
}
int remaining_ = nb - ((nsubsets - 1) << 6);
long k = 1L;
for (int j=0; j<remaining_; j++) {
if ((subset[i] & k) != 0) nbset ++;
k = k << 1;
}
}
private static int nbset(long subset_)
{
int nbset_ = 0;
long k = 1L;
for (int j=0; j<64; j++) {
if ((subset_ & k) != 0) nbset_ ++;
k = k << 1;
}
return nbset_;
}
/**
* Enlarges the bitset to the size required.
* @param required_ the required number of subsets.
*/
private void enlarge(int required_)
{
if (subset == null || subset.length < required_) {
long[] new_ = new long[required_];
if (subset != null)
System.arraycopy(subset, 0, new_, 0, subset.length);
subset = new_;
}
}
/**
* Returns a hash code value for this bit set. The has code
* depends only on which subset have been set within this
* <code>BitSet</code>. The algorithm used to compute it may
* be described as follows.<p>
* Suppose the subset in the <code>BitSet</code> were to be stored
* in an array of <code>long</code> integers called, say,
* <code>subset</code>, in such a manner that bit <code>k</code> is
* set in the <code>BitSet</code> (for nonnegative values of
* <code>k</code>) if and only if the expression
* <pre>((k>>6) < subset.length) && ((subset[k>>6] & (1L << (bit & 0x3F))) != 0)</pre>
* is true. Then the following definition of the <code>hashCode</code>
* method would be a correct implementation of the actual algorithm:
* <pre>
* public synchronized int hashCode() {
* long h = 1234;
* for (int i = subset.length; --i >= 0; ) {
* h ^= subset[i] * (i + 1);
* }
* return (int)((h >> 32) ^ h);
* }</pre>
* Note that the hash code values change if the set of subset is altered.
* <p>Overrides the <code>hashCode</code> method of <code>Object</code>.
*
* @return a hash code value for this bit set.
*/
public int hashCode()
{
long h = 1234;
for (int i = subset.length; --i >= 0; )
h ^= subset[i] * (i + 1);
return (int)((h >> 32) ^ h);
}
/**
* Compares this object against the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a <code>Bitset</code> object that has
* exactly the same set of subset set to <code>true</code> as this bit
* set. That is, for every nonnegative <code>int</code> index
* <code>k</code>,
* <pre>((BitSet)obj).get(k) == this.get(k)</pre>
* must be true. The current sizes of the two bit sets are not compared.
* <p>Overrides the <code>equals</code> method of <code>Object</code>.
*
* @param that_ the object to compare with.
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
*/
public boolean equals(Object that_)
{
if (this == that_) return true;
if (!(that_ instanceof drcl.data.BitSet)) return false;
BitSet set_ = (BitSet) that_;
int nsubsets_ = nsubsets > set_.nsubsets? set_.nsubsets: nsubsets;
// Check subsets in use by both BitSets
for (int i = 0; i < nsubsets_; i++)
if (subset[i] != set_.subset[i]) return false;
// Check any subsets in use by only one BitSet (must be 0 in other)
if (nsubsets > nsubsets_) {
for (int i = nsubsets_; i<nsubsets; i++)
if (subset[i] != 0) return false;
}
else
for (int i = nsubsets_; i<set_.nsubsets; i++)
if (set_.subset[i] != 0) return false;
return true;
}
/**
*/
public void duplicate(Object source_)
{
BitSet that_ = (BitSet)source_;
if (that_.subset == null) subset = null;
else {
if (subset == null || subset.length < that_.subset.length)
enlarge(that_.subset.length);
else clear();
nsubsets = that_.nsubsets;
System.arraycopy(that_.subset, 0, subset, 0, nsubsets);
}
nb = that_.nb;
nbset = that_.nbset;
}
public Object clone()
{
BitSet that_ = new BitSet();
that_.nb = nb;
that_.nsubsets = nsubsets;
that_.nbset = nbset;
that_.subset = new long[nsubsets];
System.arraycopy(subset, 0, that_.subset, 0, nsubsets);
that_.indices = indices;
return that_;
}
/**
* Prints out this bit set by the set of indices of 1's in this bit set.
* Overrides the <code>toString</code> method of <code>Object</code>.
* <p>Example:
* <pre>
* BitSet bs_ = new BitSet();</pre>
* Now <code>bs_.toString()</code> returns "<code>-0-</code>"
* (empty set).<p>
* <pre>
* bs_.set(2);</pre>
* Now <code>bs_.toString()</code> returns "<code>2</code>".<p>
* <pre>
* bs_.set(4);
* bs_.set(10);</pre>
* Now <code>bs_.toString()</code> returns "<code>2,4,10</code>".
*
* @return a string representation of this bit set.
*/
public String toString()
{
if (nb == 0) return "-0-";
StringBuffer sb_ = new StringBuffer(8*nb + 2);
String separator = "";
for (int i = 0 ; i < nb; i++)
if (get(i)) {
sb_.append(separator + i);
separator = ",";
}
return sb_.toString();
}
/**
* Returns the long integer representation of this bit set.
*/
public String numberRepresentation()
{
if (nb == 0) return "-0-";
StringBuffer sb_ = new StringBuffer();
if (subset != null && subset.length > 0) {
// print from most significant subset
for (int i=subset.length-1; i>0; i--)
sb_.append(subset[i] + ",");
sb_.append(subset[0]);
}
return sb_.toString();
}
/** Returns the binary representation of this bit set. */
public String binaryRepresentation()
{ return binaryRepresentation(false); }
/**
* Returns the binary representation of this bit set.
* @param skipLeadingZeros_ if true, the leading zeros in the resulting
* binary represenation is not printed.
*/
public String binaryRepresentation(boolean skipLeadingZeros_)
{
if (nb == 0) return "-0-";
StringBuffer sb_ = new StringBuffer(nb);
int len_ = nb;
int pos_ = len_%64;
if (pos_ == 0) pos_ = 64;
pos_ --;
boolean hasOne_ = false;
for (int i=subset.length-1; i>=0; i--) {
long v_ = subset[i];
long probe_ = 1L << pos_;
for (int j=pos_; j>=0; j--) {
if ((v_ & probe_) != 0) {
sb_.append('1');
hasOne_ = true;
}
else {
if (!skipLeadingZeros_ || hasOne_)
sb_.append('0');
}
if (j == 63)
// probe_ = 1000... (a negative long),
// shift right makes it 11000...
probe_ = (probe_ >> 1) - probe_;
else
probe_ >>= 1;
}
pos_ = 63;
}
//for (int i = 0 ; i < nb; i++)
// sb_.append(get(i)? '1': '0');
if (sb_.length() == 0) return "0";
else return sb_.toString();
}
/**
* Returns the binary representation of the bit set in the specified
* number of binary characters.
* It stuffs zeros if the bit set is not large enough.
* The length of the result may exceed the specified length if the bit set
* is too large.
* @param length_ expected number of binary characters.
*/
public String binaryRepresentation(int length_)
{
String result_ = binaryRepresentation(false);
if (result_.length() == length_) return result_;
if (result_.length() > length_) {
int len_ = result_.length() - length_;
for (int i=0; i<len_; i++)
if (result_.charAt(i) != '0') return result_.substring(i);
return result_.substring(len_);
}
else {
int len_ = length_ - result_.length();
// stuff leading zeros
StringBuffer sb_ = new StringBuffer(len_);
for (int i=0; i<len_; i++) sb_.append('0');
return sb_ + result_;
}
}
static char[] HEX = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/** Returns the hex representation of this bit set. */
public String hexRepresentation()
{ return hexRepresentation(false); }
/**
* Returns the hex representation of this bit set.
* @param skipLeadingZeros_ if true, the leading zeros in the resulting
* binary represenation is not printed.
*/
public String hexRepresentation(boolean skipLeadingZeros_)
{
try {
if (nb == 0) return "-0-";
StringBuffer sb_ = new StringBuffer(nb/4);
int len_ = nb;
long mask_ = 0x0f;
for (int i=0; i<subset.length; i++) {
long v_ = subset[i];
int len2_ = len_ >= 64? 64: len_;
len_ -= len2_;
for (int j=0; j<len2_; j+=4) {
int maskedV_ = (int) (v_ & mask_);
if (len2_ - j < 4) {
// last hex
maskedV_ = (int) (v_ & ((1 << (len2_ - j)) - 1));
}
sb_.append(HEX[maskedV_]);
v_ >>= 4;
}
}
if (skipLeadingZeros_) {
int i=sb_.length()-1;
for (; i>=0; i--)
if (sb_.charAt(i) != '0') break;
if (i < 0) return "0";
sb_.reverse();
return sb_.substring(sb_.length() - i - 1);
}
sb_.reverse();
return sb_.toString();
}
catch (Exception e_) {
e_.printStackTrace();
return null;
}
}
/**
* Returns the hex representation of the bit set in the specified number
* of hex characters.
* It stuffs zeros if the bit set is not large enough.
* The length of the result may exceed the specified length if the bit set
* is too large.
* @param length_ expected number of hex characters.
*/
public String hexRepresentation(int length_)
{
String result_ = hexRepresentation(false);
if (result_.length() == length_) return result_;
if (result_.length() > length_) {
int len_ = result_.length() - length_;
for (int i=0; i<len_; i++)
if (result_.charAt(i) != '0') return result_.substring(i);
return result_.substring(len_);
}
else {
int len_ = length_ - result_.length();
// stuff leading zeros
StringBuffer sb_ = new StringBuffer(len_);
for (int i=0; i<len_; i++) sb_.append('0');
return sb_ + result_;
}
}
}
| kaist-dmlab/MTA | TaskAllocationSim/src/drcl/data/BitSet.java |
247,636 | /* */ package sun.awt.geom;
/* */
/* */ import java.awt.geom.Rectangle2D;
/* */
/* */ final class Order0 extends Curve
/* */ {
/* */ private double x;
/* */ private double y;
/* */
/* */ public Order0(double paramDouble1, double paramDouble2)
/* */ {
/* 37 */ super(1);
/* 38 */ this.x = paramDouble1;
/* 39 */ this.y = paramDouble2;
/* */ }
/* */
/* */ public int getOrder() {
/* 43 */ return 0;
/* */ }
/* */
/* */ public double getXTop() {
/* 47 */ return this.x;
/* */ }
/* */
/* */ public double getYTop() {
/* 51 */ return this.y;
/* */ }
/* */
/* */ public double getXBot() {
/* 55 */ return this.x;
/* */ }
/* */
/* */ public double getYBot() {
/* 59 */ return this.y;
/* */ }
/* */
/* */ public double getXMin() {
/* 63 */ return this.x;
/* */ }
/* */
/* */ public double getXMax() {
/* 67 */ return this.x;
/* */ }
/* */
/* */ public double getX0() {
/* 71 */ return this.x;
/* */ }
/* */
/* */ public double getY0() {
/* 75 */ return this.y;
/* */ }
/* */
/* */ public double getX1() {
/* 79 */ return this.x;
/* */ }
/* */
/* */ public double getY1() {
/* 83 */ return this.y;
/* */ }
/* */
/* */ public double XforY(double paramDouble) {
/* 87 */ return paramDouble;
/* */ }
/* */
/* */ public double TforY(double paramDouble) {
/* 91 */ return 0.0D;
/* */ }
/* */
/* */ public double XforT(double paramDouble) {
/* 95 */ return this.x;
/* */ }
/* */
/* */ public double YforT(double paramDouble) {
/* 99 */ return this.y;
/* */ }
/* */
/* */ public double dXforT(double paramDouble, int paramInt) {
/* 103 */ return 0.0D;
/* */ }
/* */
/* */ public double dYforT(double paramDouble, int paramInt) {
/* 107 */ return 0.0D;
/* */ }
/* */
/* */ public double nextVertical(double paramDouble1, double paramDouble2) {
/* 111 */ return paramDouble2;
/* */ }
/* */
/* */ public int crossingsFor(double paramDouble1, double paramDouble2) {
/* 115 */ return 0;
/* */ }
/* */
/* */ public boolean accumulateCrossings(Crossings paramCrossings) {
/* 119 */ return (this.x > paramCrossings.getXLo()) && (this.x < paramCrossings.getXHi()) && (this.y > paramCrossings.getYLo()) && (this.y < paramCrossings.getYHi());
/* */ }
/* */
/* */ public void enlarge(Rectangle2D paramRectangle2D)
/* */ {
/* 126 */ paramRectangle2D.add(this.x, this.y);
/* */ }
/* */
/* */ public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt) {
/* 130 */ return this;
/* */ }
/* */
/* */ public Curve getReversedCurve() {
/* 134 */ return this;
/* */ }
/* */
/* */ public int getSegment(double[] paramArrayOfDouble) {
/* 138 */ paramArrayOfDouble[0] = this.x;
/* 139 */ paramArrayOfDouble[1] = this.y;
/* 140 */ return 0;
/* */ }
/* */ }
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: sun.awt.geom.Order0
* JD-Core Version: 0.6.2
*/ | yuexiahandao/RT-JAR-CODE | sun/awt/geom/Order0.java |
247,637 | /* Datei ScaleView.java
*
* date 28.06.99
*@author Daniel Jonietz
*/
package visual;
import java.applet.*;
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.geom.*;
import basis.*;
/**
* Zeigt Skalen an und sorgt fuer ihre richtige Unterteilung.
* Es gilt : Skalierungsfaktor = (maximale Elementezahl) durch Skalenlaenge.
**/
public class ScaleView extends Component {
/* Konstanten fuer die Lage */
public static final int HORIZONTAL = 1;
public static final int VERTICAL = 0;
/* Konstanten fuer die Richtung */
public static final int LEFT_TO_RIGHT = 1;
public static final int RIGHT_TO_LEFT = -1;
public static final int UPWARDS = -1;
public static final int DOWN = 1;
/* Nullpunkt */
private int nullx = 0;
private int nully = 0;
/* Laenge der Skala */
private int length = 0;
/* Ausrichtung vertikal, horizontal */
private int align = HORIZONTAL;
private int direction = LEFT_TO_RIGHT;
/* tickfactor = Einheiten pro Teilstrich */
private int tickfactor = 10;
/* Skalierungsfaktor */
private double scaler = 1;
/* Maximal in dieser Skalierung darstellbar */
private int max = length;
/* Die groesten und kleinsten auftretenden Elemente werden gemerkt */
private int maximum = 0;
private int minimum = 10000; // !!! //
/* Setzt die Lage */
public void Align (int al) {
align = al;
}
/* Liest die Lage */
public int getAlign() {
return align;
}
/* Setzt die Richtung, d.h. ist die Zunahme von links nach rechts oder von rechts nach links,
von oben nach unten oder von unten nach oben */
public void Direction (int dir) {
direction = dir;
}
/* Gibt die Ausrichtung zurueck */
public int getDirection() {
return direction;
}
/* Setzt die x-Koordinate des Nullpunktes der Skala */
public void X (int x) {
nullx = x;
}
/* Liest die x-Koordinate des Nullpunktes der Skala */
public int getX () {
return nullx;
}
/* Setzt die y-Koordinate des Nullpunktes der Skala */
public void Y (int y) {
nully = y;
}
/* Liest die x-Koordinate des Nullpunktes der Skala */
public int getY () {
return nully;
}
/* Setzt die Laenge einer Skala */
// Wird die Laenge einer Achse geaendert, so muessen einige Dinge angepasst werden.
public void Length (int l) {
scaler *= (double)length / (double)l;
length = l;
resizeTicks();
}
/* Aendert Nullpunkt und Laenge der Skala */
public void setDimension(int x, int y, int l) {
X(x);
Y(y);
Length(l);
}
public void XY(int x, int y) {
X(x);
Y(y);
}
/* Sorgt dafuer, dass die Abstande der Teilstriche immer einigermassen sinnvoll sind.*/
private void resizeTicks() {
// Hier entstand das Problem einer Endlosschleife, dadurch dass tickfactor unbeabsichtigterweise
// ziemlich schnell die int Grenzen verlassen hat bzw. auf 1 gesetzt wurde,
// was so nicht gewollt war. Abhilfe sollte die Eingrenzung schaffen.
if ((Scale(tickfactor) < 10) && (tickfactor < 4096)) {
tickfactor *= 2;
}
else
if ((Scale(tickfactor) > 50) && (tickfactor >= 2)) {
tickfactor /= 2;
}
}
/* Gibt die Laenge der Skala zurueck */
public int getLength () {
return length;
}
/* Gibt die Groesse des in dieser Skalierung groessten darstellbaren Datenelementes zurueck */
public int getMax () {
return max;
}
/* Gibt desn Skalierungsfaktor zurueck */
public double getScale() {
return scaler;
}
/* Setzt den Faktor, mit dem die Teilstriche skaliert werden */
public void Tickfactor(int t) {
tickfactor = t;
}
/* Gibt den Faktor zurueck, mit dem die Teilstriche skaliert werden */
public int getTick() {
return tickfactor;
}
/* Merkt sich Maximum und Minimum
wird im Moment nicht unbedingt gebraucht */
/* private void marker(int z) {
if (z < minimum) {minimum=z;}
if (z > maximum) {maximum=z;}
}
*/
/* Wendet eine Skalierungsvorschrift auf x an
ist z.B. der Wert x=400, scaler = 2, so wird
200 (Pixel) zurueckgegeben. */
public int Scale(int x) {
return (int)((double) x / scaler);
}
/* Wird eine Zahl von darzustellenden Elementen count gegeben,
so wird die Skala angepasst, fallse noetig.*/
public void Enlarge(int count) {
//marker(count);
if (count > max) {
if (scaler <= 1.8) {
scaler *= 1.5;
}
else {
scaler = ((double)count / (double)(length));
}
}
max = (int)(scaler*length);
resizeTicks();
}
/**
* Konstruktor. Parameter: Nullpunktskoordinaten, Laenge der Skala.
**/
public ScaleView(int x, int y, int l) {
this.X(x);
this.Y(y);
length=l;
max=l;
}
/**
* malt die Skala, ihre Spitzen und Teilstriche.
**/
public void paintScale(Graphics g) {
g.setColor(Color.black);
int tick = Scale(tickfactor);
// Liegt die Achse ?
if (align==HORIZONTAL) {
// Achse
g.drawLine(nullx, nully, nullx + direction*(length + 10), nully);
// Pfeilspitzen
g.drawLine(nullx + direction*(length + 10), nully, nullx + direction*(length + 5), nully +3);
g.drawLine(nullx + direction*(length + 10), nully, nullx + direction*(length + 5), nully -3);
// Teilstriche
for (int i=0; i*tick < length; i++) {
//System.err.println("i"+i);
//System.err.println("t"+tick); //Problem: tick=0 !!
//System.err.println("it"+i*tick);
//System.err.flush();
g.drawLine(nullx + direction*i*tick, nully-5, nullx + direction*i*tick, nully + 5);
}
// Beschriftung
String str = new String().valueOf(max);
g.drawString(str, nullx + direction*length-(g.getFontMetrics().stringWidth(str)), nully-10);
}
// oder steht sie ?
else {//vertical
// Achse
g.drawLine(nullx, nully, nullx, nully + direction*(length + 10));
// Pfeilspitzen
g.drawLine(nullx, nully+direction*(length+10), nullx - 3, nully + direction*(length + 5));
g.drawLine(nullx, nully+direction*(length+10), nullx + 3, nully + direction*(length + 5));
// Teilstriche
for (int i=0; i*tick <= length; i++) {
g.drawLine(nullx - 5, nully + direction*i*tick, nullx + 5, nully + direction*i*tick );
}
// Beschriftung
String str = new String().valueOf(max);
g.drawString(str, nullx+10, nully+direction*(length-10));
}
}
/**
* malt alles
**/
public void paint(Graphics g) {
paintScale(g);
}
}
| falsewasnottrue/oberfoerster | visual/ScaleView.java |
247,638 | import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import javax.swing.JLayeredPane;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Board extends JComponent{
private State model;
private Font bk = new Font("Baby Kruffy", Font.PLAIN, 28);
private Font bkLarge = new Font("Baby Kruffy", Font.PLAIN, 40);
private BufferedImage img;
public JButton[] snakeBody = new JButton[300];
public JLabel score = new JLabel();
public JLabel FPS = new JLabel();
public JLabel speed = new JLabel();
public JLabel pause = new JLabel("Hold on!");
public JLabel die = new JLabel("Game Over :(");
public ImageIcon food = new ImageIcon(Board.class.getResource("Apple-20.png"));
public ImageIcon head = new ImageIcon(Board.class.getResource("head.png"));
public ImageIcon body = new ImageIcon(Board.class.getResource("body.png"));
public JButton foodButton = new JButton(food);
public ImageIcon poison = new ImageIcon(Board.class.getResource("poison.png"));
public ImageIcon bomb = new ImageIcon(Board.class.getResource("bomb.png"));
public JButton poisonButton = new JButton(poison);
public JButton bombButton = new JButton(bomb);
public JLayeredPane area = new JLayeredPane();
public Board(State aModel) {
super();
model = aModel;
area.setLayout(null);
area.setSize(new Dimension(522,522));
area.setBorder(BorderFactory.createEmptyBorder());
area.setBackground(Color.white);
area.setLocation(new Point(27,27));
for(int i = 0;i < 300;i++){
if(i==0) {
snakeBody[i] = new JButton(head);
snakeBody[i].setDisabledIcon(head);
}else{
snakeBody[i] = new JButton(body);
snakeBody[i].setDisabledIcon(body);
}
snakeBody[i].setEnabled(false);
snakeBody[i].setSize(20, 20);
snakeBody[i].setBorder(BorderFactory.createEmptyBorder());
}
this.add(area);
setSize(new Dimension(800,600));
try {
img = ImageIO.read(Board.class.getResource("/background.jpg"));
} catch(IOException e) {
e.printStackTrace();
}
setVisible(true);
requestFocusInWindow();
setFocusable(true);
initViews();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 27, 27, 522, 522, this.area);
}
void drawSnakeBody(){
// System.out.println("drawSnakeBody");
if(model.snakeBody.isEmpty()) return;
// System.out.println("size: "+model.snakeBody.size());
for(int i=0;i<model.snakeBody.size();++i){
try{
snakeBody[i].setLocation(enlarge((Point)model.snakeBody.toArray()[i]));
area.add(snakeBody[i], new Integer(0), 0);
} catch (Exception e){
// System.out.println("Error occurs: "+ i+" , "+e.toString());
}
}
}
void updateFood(){
foodButton.setEnabled(false);
// System.out.println("Foodx:"+model.food.getX());
// System.out.println("Foody:"+model.food.getY());
foodButton.setLocation(enlarge(model.food));
foodButton.setSize(20, 20);
foodButton.setDisabledIcon(food);
foodButton.setBorder(BorderFactory.createEmptyBorder());
area.add(foodButton,new Integer(0), 0);
}
void updatePosion(){
poisonButton.setEnabled(false);
poisonButton.setLocation(enlarge(model.poison));
poisonButton.setSize(20, 20);
poisonButton.setDisabledIcon(poison);
poisonButton.setBorder(BorderFactory.createEmptyBorder());
area.add(poisonButton,new Integer(0), 0);
}
void updateBomb(){
bombButton.setEnabled(false);
bombButton.setLocation(enlarge(model.bomb));
bombButton.setSize(20, 20);
bombButton.setDisabledIcon(bomb);
bombButton.setBorder(BorderFactory.createEmptyBorder());
area.add(bombButton,new Integer(0), 0);
}
void printScore(){
score.setFont(bk);
score.setLocation(new Point(600,140));
score.setForeground(Color.DARK_GRAY);
score.setSize(200, 30);
score.setText("Score : "+model.score);
this.add(score);
score.repaint();
}
void printSpeed(){
speed.setFont(bk);
speed.setLocation(new Point(600,100));
speed.setForeground(Color.DARK_GRAY);
speed.setSize(200, 30);
speed.setText("Speed : "+model.speed);
this.add(speed);
speed.repaint();
}
void printFPS(){
FPS.setFont(bk);
FPS.setLocation(new Point(600,60));
FPS.setForeground(Color.DARK_GRAY);
FPS.setSize(200, 30);
FPS.setText("FPS : "+ model.FPS);
this.add(FPS);
FPS.repaint();
}
void printDie(){
die.setFont(bkLarge);
die.setLocation(new Point(150,160));
die.setForeground(new Color(247,18,60));
die.setSize(300, 200);
die.setVisible(false);
area.add(die, new Integer(1), 0);
}
void printPause(){
pause.setFont(bkLarge);
pause.setLocation(new Point(150,160));
pause.setForeground(new Color(17,153,250));
pause.setSize(300, 200);
pause.setVisible(false);
area.add(pause,new Integer(1), 0);
}
void initViews(){
printScore();
printSpeed();
printFPS();
updateFood();
printPause();
printDie();
drawSnakeBody();
//restart
}
Point enlarge (Point p){
// System.out.println("x:"+p.getX());
// System.out.println("y:"+p.getY());
double newX = p.getX()*20+1;
double newY = p.getY()*20+1;
Point newP = new Point((int)newX,(int)newY);
return newP;
}
}
| lynnegithub/snake | Board.java |
247,639 | package Hw3HashMap;
import java.util.*;
import java.util.function.Function;
//Naomi Serkez
// 3.2024
//this is a combination of the book, sonfoundry and my own work
public class ArrayMap<K, V> implements MapInterface<K, V> {
//variables
private MapEntry<K, V>[] map;
private final int DEFCAP = 5000;
private final double DEFLOAD = 0.75;
private int origCap;
private int currCap;
private double load;
private int numPairs = 0;
Function<K, Integer> currHash; //stores the users choice of hash as a lambda
//simple hash
Function<K, Integer> hash1 = key -> key.hashCode() % currCap < 0 ? key.hashCode() % currCap + currCap : key.hashCode() % currCap;
// 'complex' hash, for the sake of lambdas. I did not have a second function before, so I just repeated
Function<K, Integer> hash2 = key -> key.hashCode() % currCap < 0 ? key.hashCode() % currCap + currCap : key.hashCode() % currCap;
Map<String, Function<K, Integer>> functionMap = new HashMap<>(); //will store the hashes, needs to be in a function so done in constructor
//default constructor
public ArrayMap() {
map = new MapEntry[DEFCAP];
origCap = DEFCAP;
currCap = DEFCAP;
load = DEFLOAD;
functionMap.put("1", hash1);
functionMap.put("2", hash2);
}
//overloaded constructor
public ArrayMap(int initCapacity, double initLoad, String hash) {
map = new MapEntry[initCapacity];
origCap = initCapacity;
currCap = initCapacity;
load = initLoad;
functionMap.put("1", hash1);
functionMap.put("2", hash2);
setHash(hash);
}
//allows user to set the hash function
public void setHash(String h){
currHash = functionMap.get(h);
}
//make array bigger
private void enlarge() {
Iterator<MapEntry<K, V>> i = iterator();
int count = numPairs;
map = new MapEntry[currCap + origCap];
currCap = currCap + origCap;
numPairs = 0;
MapEntry entry;
for (int n = 1; n <= count; n++) {
entry = i.next();
this.put((K) entry.getKey(), (V) entry.getValue());
}
}
//function to put a pair in the hashMap
public void put(K k, V v) {
if (k == null) return; //doesn't accept null keys
int location = currHash.apply(k) % currCap; //decides location based on hash function and size of array
if (map[location] == null) { //if nothing is there, put this key value pair
map[location] = new MapEntry<>(k, v);
numPairs++;
} else { //if it is occupied...
MapEntry<K, V> entry = map[location];
//traverse down the linked list until either the key is null or the key is the same sa teh one you are inserting
while (entry.next != null && !entry.key.equals(k)) {
entry = entry.next;
}
if (entry.key.equals(k)) { //if key is the same, update value
entry.value = v;
} else { //if null, place new key value pair
entry.next = new MapEntry<>(k, v);
numPairs++;
}
}
}
//returns the value that is paired to a specified key
public V get(K k) {
if (k == null) throw new IllegalArgumentException("Maps do not allow null keys.");
for (MapEntry<K, V> temp : map) {
if (temp != null) {
if (temp.getKey().equals(k)) return temp.getValue();
}
}
return null;
}
//removes a key value pair (not used)
public V remove(K k) {
if (k == null) throw new IllegalArgumentException("Maps do not allow null keys.");
MapEntry<K, V> temp;
Iterator<MapEntry<K, V>> search = iterator();
while (search.hasNext()) {
temp = search.next();
if (temp != null) {
if (temp.getKey().equals(k)) {
search.remove();
return temp.getValue();
}
}
}
return null;
}
//checks if a key exists in the map, returns true/false
public boolean contains(K k) {
if (k == null) throw new IllegalArgumentException("Maps do not allow null keys.");
for (MapEntry<K, V> temp : map) {
if (temp != null) {
if (temp.getKey().equals(k)) return true;
}
}
return false;
}
//checks if the map is empty
public boolean isEmpty() {
return (map == null);
}
//checks if map is full, not relevent here becasue we use linked lists that cant get full
public boolean isFull() {
return false;
}
//returns the number of pairs in the map
public int size() {
return numPairs;
}
//returns number of unused slots
public int unused() {
int unusedSlots = 0;
for (MapEntry<K, V> temp : map) {
if (temp == null) {
unusedSlots++;
}
}
return unusedSlots;
}
//hash method. I know its not ideal, but its what I had time for
/* private int hashMethod(K key) {
int hashVal = key.hashCode();
hashVal %= currCap;
if (hashVal < 0) hashVal += currCap;
return hashVal;
}*/
public int sizeArray() {
return currCap;
}
// Function to print hash table
public void printHashTable() {
for (int i = 0; i < currCap; i++) {
System.out.print("\nBucket " + (i + 1) + " : ");
MapEntry<K, V> entry = map[i];
while (entry != null) {
System.out.print(entry.key + " ");
System.out.print(entry.value + " ");
entry = entry.next;
}
}
}
public void sizeLinkedList() {
for (int i = 0; i < currCap; i++) {
System.out.print("\nBucket " + (i + 1) + " size of linked list: ");
MapEntry<K, V> entry = map[i];
int counter =0;
while (entry != null) {
counter++;
entry = entry.next;
}
System.out.print(counter);
}
}
private class MapIterator implements Iterator<MapEntry<K, V>> {
int listSize = size();
private MapEntry[] list = new MapEntry[listSize];
private int previousPos = -1; // previous position returned from list
public MapIterator() {
int next = -1;
for (int i = 0; i < listSize; i++) {
next++;
while (map[next] == null) next++;
list[i] = map[next];
}
}
public boolean hasNext() {
return (previousPos < (listSize - 1));
}
public MapEntry<K, V> next() {
if (!hasNext()) throw new IndexOutOfBoundsException("illegal invocation of next " + " in HMap iterator.\n");
previousPos++;
return list[previousPos];
}
public void remove() {
throw new UnsupportedOperationException("Unsupported remove attempted " + "on HMap iterator.\n");
}
}
public Iterator<MapEntry<K, V>> iterator() {
return new MapIterator();
}
}
| serkez/MCON364 | Hw3HashMap/ArrayMap.java |
247,640 | package Spiderweb;
import shapes.Canvas;
import shapes.Circle;
import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.JOptionPane;
import java.lang.String;
/**
* Clase que representa una red de telaraña con puentes y puntos de referencia.
* Esta clase permite agregar, eliminar y reubicar puentes y puntos de referencia,
* así como también mover una araña a lo largo de los puentes.
* <p>
* La red de telaraña está formada por una serie de líneas que representan los brazos
* de la telaraña, y puentes que conectan estos brazos. Los puentes pueden ser de diferentes
* colores y se pueden agregar a una posición específica de un brazo.
* <p>
* Los puntos de referencia son también líneas, y se pueden agregar a un brazo para indicar
* un punto de interés.
*
* @author Andres Serrato-Zayra Gutierrez
* @version 18/02/2024
*/
public class SpiderWeb {
public int radio;
private int strands;
private float angle;
private final float xStard;
private final float yStard;
private float xBridge;
private float yBridge;
private float x2Bridge;
private float y2Bridge;
private float angleFirstStrand;
private float angleSecondStrand;
private float strand;
private boolean isVisible;
private boolean isBridges;
boolean isSpot = true;
private angles list;
private List<Pair<Float, Float>> lists;
private ArrayList<Strands> lineList;
private ArrayList<Spot> lineListSpot;
final Spider spider;
private final ArrayList<String> colorBridges = new ArrayList<String>();
private final ArrayList<String> colorSports = new ArrayList<String>();
private final ArrayList<Bridges> bridgesUsed = new ArrayList<Bridges>();
private final Map<String, Bridges> bridgesColor;
private final Map<String, Integer> bridgeStrand = new HashMap<>();
private final Map<String, Tuple> spotColor;
private Map<Bridges, List<Object>> bridgesType = new HashMap<>();
private final Map<Integer, ArrayList<Bridges>> bridgesByStrand = new HashMap<Integer, ArrayList<Bridges>>();
private final ArrayList<String> bridgesNoUsed = new ArrayList<String>();
private List<Integer> hilosTomados;
private boolean isOk;
private ArrayList<Line> recorrido = new ArrayList<Line>();
private final ArrayList<Bridges> used = new ArrayList<Bridges>();
private int strandFinish;
private final Canvas canvas = new Canvas("SpiderWeb Canvas", 700, 700, Color.white);
private String tipeSpot = "";
private String tipeBridge = "";
private String colorTipeBridge;
private boolean showmensage = true;
private Map<Spot, ArrayList<Circle>> spotype = new HashMap<>();
private Map<String, String> bridgesTypes = new HashMap<>();
/**
* Constructor de la clase spiderWeb.
* Crea una nueva red de telaraña con el radio y la cantidad de brazos especificados.
*
* @param radio El radio de la telaraña.
* @param strands La cantidad de brazos de la telaraña.
*/
public SpiderWeb(int radio, int strands) {
this.list = new angles(radio, strands);
this.radio = radio;
this.strands = strands;
this.angle = list.getCant();
this.lists = list.getList();
this.bridgesColor = new HashMap<>();
this.spotColor = new HashMap<>();
isVisible = false;
isBridges = false;
this.lineList = new ArrayList<Strands>();
this.lineListSpot = new ArrayList<Spot>();
xStard = 300;
yStard = 300;
spider = new Spider((int) xStard, (int) yStard + 5);
for (int i = 0; i < strands; i++) {
bridgesByStrand.put(i, new ArrayList<>());
}
cordenates();
isOk = true;
}
/**
* This is a constructor for the SpiderWeb class.
* It creates a new SpiderWeb object with a specified number of strands, a favorite strand, and an array of bridge data.
* Each bridge is represented by an array of two integers, where the first integer is the distance of the bridge from the center of the web,
* and the second integer is the strand number where the bridge starts.
* The constructor also adds a spot at the favorite strand.
*
* @param strand The number of strands in the spider web.
* @param favoritestrand The strand number where a spot will be added.
* @param bridgesData A 2D array containing the data for each bridge to be added to the spider web.
*/
public SpiderWeb(int strand, int favoritestrand, int[][] bridgesData) {
radio = 200;
this.strands = strand;
this.list = new angles(radio, strands);
this.angle = list.getCant();
this.lists = list.getList();
this.bridgesColor = new HashMap<>();
this.spotColor = new HashMap<>();
isVisible = false;
isBridges = false;
this.lineList = new ArrayList<Strands>();
this.lineListSpot = new ArrayList<Spot>();
xStard = 300;
yStard = 300;
spider = new Spider((int) xStard, (int) yStard + 5);
for (int i = 0; i < strands; i++) {
bridgesByStrand.put(i, new ArrayList<>());
}
for (int[] bridgeData : bridgesData) {
int firststrand = bridgeData[1];
int distance = bridgeData[0];
String color = canvas.generateRandomColor();
addBridge(color, distance, firststrand);
}
cordenates();
addSpot("yellow", favoritestrand);
isOk = true;
}
/**
* Calcula las coordenadas de los brazos de la telaraña y crea líneas para representarlos.
*/
private void cordenates() {
for (Pair<Float, Float> pair : lists) {
float x;
float y;
x = pair.getFirst();
y = pair.getSecond();
Strands arm = new Strands(xStard, yStard, x + xStard, yStard - y);
Spot arm1 = new Spot(xStard, yStard, x + xStard, yStard - y);
lineList.add(arm);
lineListSpot.add(arm1);
}
}
/**
* Hace visible la red de telaraña y todos los elementos.
* Si la red no ha sido visible antes, muestra las líneas de los brazos
* y una araña en el centro. Si ya ha sido visible, simplemente hace visible
* nuevamente los elementos.
*/
public void makeVisible() {
isSpot = false;
if (!isVisible && !isSpot) {
for (Bridges bridge : bridgesType.keySet()) {
bridge.makeVisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
for (Circle circle : circles) {
circle.makeVisible();
}
}
for (Strands arms : lineList) {
arms.makeVisible();
}
ArrayList<Spot> reversedLineList = new ArrayList<>();
for (int i = lineListSpot.size() - 1; i >= 0; i--) {
reversedLineList.add(lineListSpot.get(i));
}
for (Spot arms : reversedLineList) {
arms.makeVisible();
if (spotype.containsKey(arms)) {
ArrayList<Circle> circles = spotype.get(arms);
for (Circle circle : circles) {
circle.makeVisible();
}
}
}
if(spider.isLive){
spider.makeVisible();
}
isBridges = true;
isVisible = true;
for (Line l : recorrido) {
l.makeVisible();
}
}
}
/**
* Hace invisible la red de telaraña y todos los elementos.
* Oculta todas las líneas y los puentes de la red de telaraña.
*/
public void makeInvisible() {
for (Strands arms : lineList) {
arms.makeInvisible();
}
for (Spot arms : lineListSpot) {
arms.makeInvisible();
}
for (Bridges bridge : bridgesType.keySet()) {
bridge.makeInvisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
for (Circle circle : circles) {
circle.makeInvisible();
}
}
spider.makeInvisible();
isBridges = false;
isSpot = true;
isVisible = false;
for (Line l : recorrido) {
l.makeInvisible();
}
}
/**
* Agrega un puente a la red de telaraña.
*
* @param color El color del puente.
* @param distance La distancia desde el centro hasta el punto donde comienza el puente.
* @param firstStrand El número del brazo donde se conectará el puente.
*/
public void addBridge(String color, int distance, int firstStrand) {
if (!verifyBridge(color, distance, firstStrand, true)) {
isOk = false;
return;
}
if(Objects.equals(tipeBridge, "")){
tipeBridge = "normal";
}
angleFirstStrand = (firstStrand - 1) * angle;
angleSecondStrand = firstStrand * angle;
xBridge = distance * (float) Math.cos(Math.toRadians(angleFirstStrand));
yBridge = distance * (float) Math.sin(Math.toRadians(angleFirstStrand));
x2Bridge = distance * (float) Math.cos(Math.toRadians(angleSecondStrand));
y2Bridge = distance * (float) Math.sin(Math.toRadians(angleSecondStrand));
int endStrand = (firstStrand == strands) ? 0 : firstStrand;
Bridges bridge = null;
if (Objects.equals(tipeBridge, "fixed")) {
bridge = new Fixed(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, firstStrand - 1, endStrand, distance, color, firstStrand);
} else if (Objects.equals(tipeBridge, "transformer")){
bridge = new Transformer(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, firstStrand - 1, endStrand, distance, color, firstStrand);
} else if (Objects.equals(tipeBridge, "weak")){
bridge = new Weak(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, firstStrand - 1, endStrand, distance, color, firstStrand);
} else if (Objects.equals(tipeBridge, "mobile")) {
bridge = new Mobile(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, firstStrand - 1, endStrand, distance, color, firstStrand);
}else if (Objects.equals(tipeBridge,"normal")){
bridge = new Bridges(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, firstStrand - 1, endStrand, distance);
}
bridge.changeColor(color);
bridgesColor.put(color, bridge);
colorBridges.add(color);
bridgesNoUsed.add(color);
bridgesByStrand.get(firstStrand - 1).add(bridge);
bridgesByStrand.get(endStrand).add(bridge);
bridgeStrand.put(color, firstStrand);
bridgesTypes.put(color, tipeBridge);
isOk = true;
distintive(bridge, color);
if (isBridges) {
bridge.makeVisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
for (Circle circle : circles) {
circle.makeVisible();
}
}
}
/**
* This method is used to add a bridge to the spider web.
* It first sets the type of the bridge, then verifies if the bridge can be added.
* If the bridge can be added, it adds the bridge and sets the status to true.
* If the bridge cannot be added, it sets the status to false.
* After the operation, it resets the type of the bridge to an empty string.
*
* @param type The type of the bridge to be added.
* @param color The color of the bridge to be added.
* @param distance The distance from the center of the web to the start of the bridge.
* @param firstStrand The strand number where the bridge starts.
*/
public void addBridge(String type, String color, int distance, int firstStrand) {
this.tipeBridge = type;
if(verifyBridge(color, distance, firstStrand, true)) {
addBridge(color, distance, firstStrand);
isOk = true;
}else {
isOk = false;
}
this.tipeBridge = "";
}
/**
* This method is used to add distinctive features to a bridge based on its type.
* It creates a number of circles on the bridge based on the bridge type.
* The circles are added to an ArrayList and stored in a map with the bridge as the key.
* The value in the map is a List of Objects, where the first object is the bridge type and the second object is the ArrayList of circles.
*
* @param bridge The bridge to which the distinctive features are to be added.
* @param color The color of the distinctive features.
*/
private void distintive(Bridges bridge, String color){
ArrayList<Integer> midPoint = bridge.getMidPoint();
int circleCount = bridgesTypes.get(color).equals("fixed") ? 1 : bridgesTypes.get(color).equals("transformer") ? 2 : bridgesTypes.get(color).equals("weak") ? 3 : bridgesTypes.get(color).equals("mobile") ? 4: 0;
ArrayList<Circle> circles = new ArrayList<>();
for (int i = 0; i < circleCount * 2; i += 2) {
Circle circle = new Circle(5, midPoint.get(i), midPoint.get(i + 1));
circle.changeColor(color);
circles.add(circle);
}
List<Object> value = new ArrayList<>();
value.add(tipeBridge);
value.add(circles);
bridgesType.put(bridge, value);
}
/**
* This method is used to handle different types of bridges in the spider web.
* Depending on the type of the bridge, it performs different actions.
* For a "transformer" bridge, it adds a spot at the start of the bridge.
* For a "weak" bridge, it deletes the bridge.
* For a "mobile" bridge, it moves the bridge to a new location.
*
* @param istypebridge A boolean flag indicating if the bridge is of a specific type.
*/
private void TypeBridge(boolean istypebridge){
String color = colorTipeBridge;
if(Objects.equals(tipeBridge, "transformer") && istypebridge){
showmensage = false;
int[] strands = bridge(color);
showmensage = true;
int Strand = strands[0];
addSpot(color, Strand);
}else if (Objects.equals(tipeBridge,"weak")){
delBridge(color);
}else if (Objects.equals(tipeBridge,"mobile")){
Bridges bridge = null;
System.out.println(bridgesTypes);
for (Bridges bridges : bridgesType.keySet()) {
if (bridges.getColor().equals(color)) {
bridge = bridges;
}
}
float newDistance = bridge.getDistance()* 1.2f;
int newStrand = (bridge.hiloInicial == strands - 1) ? 0 : bridge.hiloInicial + 2;
delBridge(color);
tipeBridge = "";
addBridge(color, (int) newDistance, newStrand);
}
}
/**
* This method is used to verify if a bridge can be added to the spider web.
* It checks if the color of the bridge already exists, if the strand number is valid, and if the distance is valid.
* It also checks if there is already a bridge at the same distance on the current, previous, and next strand.
* If any of these checks fail, the method returns false, indicating that the bridge cannot be added.
* If all checks pass, the method returns true, indicating that the bridge can be added.
*
* @param color The color of the bridge to be added.
* @param distance The distance from the center of the web to the start of the bridge.
* @param firstStrand The strand number where the bridge starts.
* @param showMessage A boolean flag indicating if a message should be shown when a check fails.
* @return A boolean value indicating if the bridge can be added (true) or not (false).
*/
public boolean verifyBridge(String color, int distance, int firstStrand, boolean showMessage) {
if (isColorExists(color, showMessage) || !isStrandValid(firstStrand, showMessage) || !isDistanceValid(distance, showMessage)) {
return false;
}
int previousStrand = (firstStrand == 1) ? strands - 1 : firstStrand - 2;
int nextStrand = (firstStrand == strands) ? 0 : firstStrand;
return !(isBridgeExistsAtDistance(firstStrand-1, distance, showMessage) ||
isBridgeExistsAtDistance(previousStrand, distance, showMessage) ||
isBridgeExistsAtDistance(nextStrand, distance, showMessage));
}
/**
* This method checks if a bridge of a certain color already exists in the spider web.
* If a bridge of the same color exists, it shows a message and returns true.
* If no bridge of the same color exists, it returns false.
*
* @param color The color of the bridge to be checked.
* @param showMessage A boolean flag indicating if a message should be shown when a bridge of the same color exists.
* @return A boolean value indicating if a bridge of the same color exists (true) or not (false).
*/
private boolean isColorExists(String color, boolean showMessage) {
if (colorBridges.contains(color)) {
showMessage("No se puede añadir puente del mismo color.", showMessage);
return true;
}
return false;
}
/**
* This method checks if a strand number is valid.
* If the strand number is not within the range of existing strands, it shows a message and returns false.
* If the strand number is valid, it returns true.
*
* @param strand The strand number to be checked.
* @param showMessage A boolean flag indicating if a message should be shown when the strand number is not valid.
* @return A boolean value indicating if the strand number is valid (true) or not (false).
*/
private boolean isStrandValid(int strand, boolean showMessage) {
if (strand > strands || strand < 1) {
showMessage("El strand no existe.", showMessage);
return false;
}
return true;
}
/**
* This method checks if a distance value is valid.
* If the distance is not within the range of the spider web's radius, it shows a message and returns false.
* If the distance is valid, it returns true.
*
* @param distance The distance to be checked.
* @param showMessage A boolean flag indicating if a message should be shown when the distance is not valid.
* @return A boolean value indicating if the distance is valid (true) or not (false).
*/
private boolean isDistanceValid(int distance, boolean showMessage) {
if (distance > radio || distance <= 0) {
showMessage("La distancia no puede ser mayor al radio.", showMessage);
return false;
}
return true;
}
/**
* This method checks if a bridge already exists at a certain distance on a certain strand.
* If a bridge exists at the same distance on the strand, it shows a message and returns true.
* If no bridge exists at the same distance on the strand, it returns false.
*
* @param strand The strand number to be checked.
* @param distance The distance to be checked.
* @param showMessage A boolean flag indicating if a message should be shown when a bridge exists at the same distance on the strand.
* @return A boolean value indicating if a bridge exists at the same distance on the strand (true) or not (false).
*/
private boolean isBridgeExistsAtDistance(int strand, int distance, boolean showMessage) {
for (Bridges bridge : bridgesByStrand.get(strand)) {
if (bridge.getDistance() == distance) {
showMessage("Ya existe un puente en este strand a la misma distancia.", showMessage);
return true;
}
}
return false;
}
private void showMessage(String message, boolean showMessage) {
if (isVisible && showMessage) {
JOptionPane.showMessageDialog(null, message);
}
}
/**
* Relocaliza un puente existente en la red de telaraña.
*
* @param color El color del puente que se desea relocalizar.
* @param distance La nueva distancia desde el centro hasta el punto donde comienza el puente.
*/
public void relocateBridge(String color, float distance) {
if (distance < 0 || distance > radio ) {
if (isVisible) {
JOptionPane.showMessageDialog(null, "No se puede reubicar el puente con una distancia negativa o mayor a la del radio.");
}
isOk = false;
}else if(!colorBridges.contains(color)){
if (isVisible) {
JOptionPane.showMessageDialog(null, "El puente no existe.");
}
isOk = false;
}else{
angleFirstStrand = (bridgeStrand.get(color) - 1) * angle;
angleSecondStrand = bridgeStrand.get(color) * angle;
xBridge = distance * (float) Math.cos(Math.toRadians(angleFirstStrand));
yBridge = distance * (float) Math.sin(Math.toRadians(angleFirstStrand));
x2Bridge = distance * (float) Math.cos(Math.toRadians(angleSecondStrand));
y2Bridge = distance * (float) Math.sin(Math.toRadians(angleSecondStrand));
Bridges bridge = new Bridges(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, bridgesColor.get(color).hiloInicial, bridgesColor.get(color).hiloFinal, distance);
bridge.changeColor(color);
hideBridges();
bridgesType.remove(bridgesColor.get(color));
distintive(bridge, color);
bridgesColor.put(color, bridge);
if (!isSpot) {
showBridges();
}
int index = 0;
for (int i = 0; i < strands; i++) {
ArrayList<Bridges> listBridge = bridgesByStrand.get(i);
for (Bridges l : listBridge) {
if (Objects.equals(l.getColor(), color)) {
bridgesByStrand.get(i).set(index, bridge);
}
index += 1;
}
index = 0;
}
isOk = true;
}
}
/**
* Relocaliza automáticamente un puente en un brazo específico de la red de telaraña.
*/
private void relocateBridgeAutomatico(String color, float distance) {
angleFirstStrand = (bridgeStrand.get(color) - 1) * angle;
angleSecondStrand = bridgeStrand.get(color) * angle;
xBridge = distance * (float) Math.cos(Math.toRadians(angleFirstStrand));
yBridge = distance * (float) Math.sin(Math.toRadians(angleFirstStrand));
x2Bridge = distance * (float) Math.cos(Math.toRadians(angleSecondStrand));
y2Bridge = distance * (float) Math.sin(Math.toRadians(angleSecondStrand));
Bridges bridge = new Bridges(xStard + xBridge, yStard - yBridge, xStard + x2Bridge, yStard - y2Bridge, bridgesColor.get(color).hiloInicial, bridgesColor.get(color).hiloFinal, distance);
bridge.changeColor(color);
distintive(bridge, color);
bridgesColor.put(color, bridge);
int index = 0;
for (int i = 0; i < strands; i++) {
ArrayList<Bridges> listBridge = bridgesByStrand.get(i);
for (Bridges l : listBridge) {
if (Objects.equals(l.getColor(), color)) {
bridgesByStrand.get(i).set(index, bridge);
}
index += 1;
}
index = 0;
}
if (isVisible) {
System.out.println("hola");
showBridges();
}
}
/**
* Elimina un puente de la red de telaraña.
*
* @param color El color del puente que se desea eliminar.
*/
public boolean delBridge(String color) {
this.colorTipeBridge = color;
Bridges delbridge = bridgesColor.get(color);
if (delbridge == null) {
if (isVisible) {
JOptionPane.showMessageDialog(null, "El puente no existe.");
}
isOk = false;
return isOk;
}
String type = bridgesTypes.get(color);
if(!Objects.equals(type, "fixed")){
for (Bridges bridge : bridgesType.keySet()) {
if (bridge.getColor().equals(color)) {
bridge.makeInvisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
for (Circle circle : circles) {
circle.makeInvisible();
}
}
}
if(Objects.equals(type, "transformer")){
this.tipeBridge = type;
TypeBridge(true);
this.tipeBridge = "";
}
bridgesColor.remove(color);
bridgesType.remove(delbridge);
colorBridges.remove(color);
bridgesNoUsed.remove(color);
bridgesByStrand.get(delbridge.hiloInicial).remove(delbridge);
bridgesByStrand.get(delbridge.hiloFinal).remove(delbridge);
isOk = true;
return isOk;
}else{
if(isVisible) {
JOptionPane.showMessageDialog(null, "No se puede eliminar un puente fixed.");
isOk = false;
return isOk;
}
}
return false;
}
/**
* Agrega un spot a la red de telaraña.
*
* @param color El color del punto de referencia.
* @param strand El número del brazo donde se agregará el punto de referencia.
*/
public void addSpot(String color, int strand) {
String type = tipeSpot;
if(Objects.equals(type, "")){
type = "normal";
}
if (!verifySpot(color, strand, true)) {
isOk = false;
return;
}
Spot arm = lineListSpot.get(strand - 1);
Spot arm1 = lineListSpot.get(strand - 1);
if (Objects.equals(tipeSpot, "bouncy")){
arm1 = new Bouncy(xStard, yStard, lineListSpot.get(strand - 1).getX1(), lineListSpot.get(strand - 1).getY1());
}else if (Objects.equals(tipeSpot, "killer")){
arm1 = new Killer(xStard, yStard, lineListSpot.get(strand - 1).getX1(), lineListSpot.get(strand - 1).getY1());
}else if (Objects.equals(tipeSpot, "Break")){
arm1 = new Break(xStard, yStard, lineListSpot.get(strand - 1).getX1(), lineListSpot.get(strand - 1).getY1());
}
arm.changeColor(color);
lineListSpot.set(strand - 1, arm);
distintive1(arm, color, type);
if (!isSpot) {
arm.makeVisible();
ArrayList<Circle> circles = spotype.get(arm);
for (Circle circle : circles) {
circle.makeVisible();
}
}
Tuple tuple = new Tuple(strand, type);
spotColor.put(color, tuple);
colorSports.add(color);
isOk = true;
}
private void distintive1(Spot spot, String color, String type){
ArrayList<Integer> midPoint = spot.getMidPointSpot();
int circleCount = type.equals("bouncy") ? 1 : type.equals("killer") ? 2 : type.equals("break") ? 3 : 0;
ArrayList<Circle> circles = new ArrayList<>();
for (int i = 0; i < circleCount * 2; i += 2) {
Circle circle = new Circle(5, midPoint.get(i), midPoint.get(i + 1));
circle.changeColor(color);
circles.add(circle);
}
spotype.put(spot, circles);
}
/**
* Agrega un tipo spot a la red de telaraña.
*
* @param color El color del punto de referencia.
* @param strand El número del brazo donde se agregará el punto de referencia.
* @param type El tipo de spot que se desea agregar.
*/
public void addSpot(String type, String color, int strand) {
this.tipeSpot = type;
addSpot(color, strand);
this.tipeSpot = "";
}
/**
* This method is used to verify if a spot can be added to the spider web.
* It checks if a spot of the same color already exists, if the strand number is valid, and if there is already a spot on the same strand.
* If any of these checks fail, the method returns false, indicating that the spot cannot be added.
* If all checks pass, the method returns true, indicating that the spot can be added.
*
* @param color The color of the spot to be added.
* @param strand The strand number where the spot will be added.
* @param showMessage A boolean flag indicating if a message should be shown when a check fails.
* @return A boolean value indicating if the spot can be added (true) or not (false).
*/
public boolean verifySpot(String color, int strand, boolean showMessage) {
if (spotColor.containsKey(color)) {
if (isVisible && showMessage) {
JOptionPane.showMessageDialog(null, "No se puede añadir spot del mismo color.");
}
return false;
}
for(Tuple tuple : spotColor.values()){
if(tuple.getNumber() == strand){
if (isVisible && showMessage) {
JOptionPane.showMessageDialog(null, "Ya existe un spot en este strand.");
}
return false;
}
}
if (strand > strands || strand < 1) {
if (isVisible && showMessage) {
JOptionPane.showMessageDialog(null, "El strand no existe.");
}
return false;
}
return true;
}
/**
* This method is used to handle different types of spots in the spider web.
* Depending on the type of the spot, it performs different actions.
* For a "bouncy" spot, it moves the spider to the next strand and recursively calls the method until a non-bouncy spot is encountered.
* For a "killer" spot, it kills the spider and makes it invisible.
* For a "break" spot, it deletes the spot and makes all the lines in the path visible.
*/
private void typeSpot() {
String tipo = "";
String colorTipeSpot = null;
for (Map.Entry<String, Tuple> entry : spotColor.entrySet()) {
if (entry.getValue().getNumber() == strandFinish + 1 ){
tipo = entry.getValue().getType();
colorTipeSpot = entry.getKey();
}
}
if(Objects.equals(tipo, "bouncy")) {
Strands nextStrand = lineList.get((int) strandFinish + 1);
spider.moveTo(nextStrand.getX2(), nextStrand.getY2());
strandFinish = strandFinish + 1;
strandFinish = (strandFinish > strands-1) ? 0 : strandFinish;
typeSpot();
}
if(Objects.equals(tipo, "killer")) {
spider.isLive = false;
spider.makeInvisible();
}
if(Objects.equals(tipo, "break")) {
delSpot(colorTipeSpot);
if (isVisible) {
for (Line l : recorrido) {
l.makeVisible();
}
}
}
}
/**
* Elimina un punto de referencia de la red de telaraña.
*
* @param color El color del punto de referencia que se desea eliminar.
*/
public void delSpot(String color) {
if (!spotColor.containsKey(color)) {
if (isVisible) {
JOptionPane.showMessageDialog(null, "El spot no existe.");
}
this.isOk = false;
} else {
int strand = spotColor.get(color).getNumber();
Spot arm = lineListSpot.get(strand-1);
arm.changeColor("black");
lineListSpot.set(strand, arm);
if (!isSpot) {
arm.makeVisible();
ArrayList<Circle> circles = spotype.get(arm);
for (Circle circle : circles) {
circle.makeInvisible();
}
}
spotype.remove(arm);
spotColor.remove(color);
colorSports.remove(color);
isOk = true;
}
}
/**
* Oculta todos los puentes de la red de telaraña.
*/
private void hideBridges() {
for (Bridges bridge : bridgesType.keySet()) {
bridge.makeInvisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
for (Circle circle : circles) {
circle.makeInvisible();
}
}
}
/**
* Muestra todos los puentes de la red de telaraña.
*/
private void showBridges() {
for (Bridges bridge : bridgesType.keySet()) {
bridge.makeVisible();
ArrayList<Circle> circles = (ArrayList<Circle>) bridgesType.get(bridge).get(1);
System.out.println(circles+"a");
for (Circle circle : circles) {
circle.makeVisible();
}
}
}
/**
* Hace que la araña se siente en un brazo específico de la telaraña.
*
* @param strand El número del brazo donde se desea que la araña se siente.
*/
public void spiderSit(int strand) {
eraseRecorrido();
if (strand > 0 && strand <= strands) {
this.strand = strand;
spider.spiderSit();
if(!spider.isLive) {
spider.moveTo(xStard, yStard);
spider.makeVisible();
spider.isLive = true;
spider.spiderSit();
}
isOk = true;
} else {
if (isVisible) {
JOptionPane.showMessageDialog(null, "El strand no existe para sentar a la araña.");
}
isOk = false;
}
}
/**
* Hace que la araña camine a lo largo del brazo de la telaraña.
*
* @param advance Indica si la araña debe avanzar en el brazo o retroceder.
*/
public void spiderWalk(boolean advance) {
bridgesUsed.clear();
if (this.spider.isSpiderSitting()) {
if (advance) {
ArrayList<ArrayList<Float>> walk = isPosible((int) strand - 1);
typeSpot();
} else {
strandFinish = (strandFinish > strands-1) ? 0 : strandFinish;
ArrayList<ArrayList<Float>> walk = isPosible1((int) strandFinish);
float xAnterior = spider.getXPosition();
float yAnterior = spider.getYPosition();
for (ArrayList<Float> point : walk) {
spider.moveTo(point.get(0), point.get(1));
Line l = new Line(xAnterior, yAnterior, point.get(0), point.get(1));
l.changeColor("green");
if(isVisible) {
l.makeVisible();
}
recorrido.add(l);
xAnterior = point.get(0);
yAnterior = point.get(1);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
eraseRecorrido();
spider.isSitting = false;
}
} else {
if (isVisible) {
JOptionPane.showMessageDialog(null, "La araña no puede caminar pues no esta sentada sobre ningún Strand", "Error al caminar", JOptionPane.INFORMATION_MESSAGE);
}
isOk = false;
}
}
/**
* This method is used to move the spider along a path in the spider web.
* It iterates over a list of points that represent the path, and for each point, it creates a line from the previous point to the current point.
* It then changes the color of the line to blue and makes it visible if the spider web is visible.
* The line is added to the 'recorrido' list which keeps track of the path that the spider has taken.
* After each iteration, the current point becomes the previous point for the next iteration.
*
* @param walk An ArrayList of ArrayLists of Floats, where each inner ArrayList represents a point on the path and contains the x and y coordinates of the point.
* @param xAnterior The x coordinate of the previous point on the path.
* @param yAnterior The y coordinate of the previous point on the path.
*/
private void spidermove(ArrayList<ArrayList<Float>> walk, float xAnterior, float yAnterior) {
for (ArrayList<Float> point : walk) {
Line l = new Line(xAnterior, yAnterior, point.get(0), point.get(1));
l.changeColor("blue");
if (isVisible) {
l.makeVisible();
}
recorrido.add(l);
xAnterior = point.get(0);
yAnterior = point.get(1);
}
}
private void eraseRecorrido() {
for (Line l : recorrido) {
l.makeInvisible();
}
recorrido = new ArrayList<Line>();
}
/**
* This method is used to find the next bridge on a given strand that the spider can move to.
* It iterates over a list of bridges on the strand, and for each bridge, it calculates the distance from the center of the web to the bridge.
* If the distance to the bridge is greater than the current distance of the spider and the difference between the two distances is less than the minimum difference found so far,
* it updates the minimum difference and sets the bridge as the next bridge to move to.
* After iterating over all bridges, it adds a key-value pair to a map where the key is a boolean indicating if a next bridge was found and the value is the next bridge.
* If no next bridge was found, the value is a default bridge with no properties.
*
* @param listBrigde An ArrayList of Bridges representing the bridges on the strand.
* @param strand The strand number where the spider is currently located.
* @param xSpiderActual The current x coordinate of the spider.
* @param ySpiderActual The current y coordinate of the spider.
* @return A Map where the key is a Boolean indicating if a next bridge was found and the value is the next bridge (if found) or a default bridge (if not found).
*/
private Map<Boolean, Bridges> nextBridge(ArrayList<Bridges> listBrigde, int strand, float xSpiderActual, float ySpiderActual) {
float distanceMinSB = 3000;
float distanceSpider = (float) Math.sqrt(Math.pow(xSpiderActual - xStard, 2) + Math.pow(ySpiderActual - yStard, 2));
Bridges bridges = new Bridges(0, 0, 0, 0, 1, 2, 0);
Map<Boolean, Bridges> brigdeMap = new HashMap<Boolean, Bridges>();
boolean foundBridge = false;
for (Bridges b : listBrigde) {
ArrayList<Float> points = b.returnPoint(strand);
float distance = (float) Math.sqrt(Math.pow(points.get(0) - xStard, 2) + Math.pow(points.get(1) - yStard, 2));
if (distance > distanceSpider && distance - distanceSpider < distanceMinSB) {
foundBridge = true;
distanceMinSB = b.distance - distanceSpider;
bridges = b;
bridgesUsed.add(bridges);
}
}
brigdeMap.put(foundBridge, bridges);
return brigdeMap;
}
private Map<Boolean, Bridges> nextBridge1(ArrayList<Bridges> listBrigde, int strand, float xSpiderActual, float ySpiderActual) {
float distanceMinSB = 3000;
float distanceSpider = (float) Math.sqrt(Math.pow(xSpiderActual - xStard, 2) + Math.pow(ySpiderActual - yStard, 2));
Bridges bridges = new Bridges(0, 0, 0, 0, 1, 2, 0);
Map<Boolean, Bridges> brigdeMap = new HashMap<Boolean, Bridges>();
boolean foundBridge = false;
for (Bridges b : listBrigde) {
ArrayList<Float> points = b.returnPoint(strand);
float distance = (float) Math.sqrt(Math.pow(points.get(0) - xStard, 2) + Math.pow(points.get(1) - yStard, 2));
if (distance < distanceSpider && distanceSpider - distance < distanceMinSB) {
foundBridge = true;
distanceMinSB = distanceSpider - b.distance;
bridges = b;
bridgesUsed.add(bridges);
}
}
brigdeMap.put(foundBridge, bridges);
return brigdeMap;
}
private ArrayList<ArrayList<Float>> isPosible(int strand) {
hilosTomados = new ArrayList<>();
float xSpiderActual = spider.getXPosition();
float ySpiderActual = spider.getYPosition();
float xAnterior = 300;
float yAnterior = 300;
ArrayList<ArrayList<Float>> walk = new ArrayList<>();
while (true) {
Map<Boolean, Bridges> bridgeMap = nextBridge(bridgesByStrand.get(strand), strand, xSpiderActual, ySpiderActual);
boolean bridgeExists = new ArrayList<>(bridgeMap.keySet()).get(0);
if (bridgesByStrand.get(strand).size() > 0 && bridgeExists) {
hilosTomados.add(strand + 1);
Bridges bridge = bridgeMap.get(bridgeExists);
ArrayList<Float> points = bridge.returnPointAcomodados(strand);
ArrayList<Float> firstPoint = new ArrayList<>(Arrays.asList(points.get(0), points.get(1)));
ArrayList<Float> secondPoint = new ArrayList<>(Arrays.asList(points.get(2), points.get(3)));
spider.moveTo(points.get(0), points.get(1));
spider.moveTo(points.get(2), points.get(3));
xSpiderActual = points.get(2);
ySpiderActual = points.get(3);
walk.addAll(Arrays.asList(firstPoint, secondPoint));
strand = (bridge.hiloInicial == strand) ? (strand == strands - 1 ? 0 : strand + 1) : (strand == 0 ? strands - 1 : strand - 1);
colorTipeBridge = bridge.getColor();
tipeBridge = bridgesTypes.get(colorTipeBridge);
spidermove(walk, xAnterior, yAnterior);
if(Objects.equals(tipeBridge, "mobile") || Objects.equals(tipeBridge, "weak")){
TypeBridge(false);
}
tipeBridge = "";
} else {
hilosTomados.add(strand + 1);
Strands arm = lineList.get(strand);
ArrayList<Float> finishPoint = new ArrayList<>(Arrays.asList(arm.getX2(), arm.getY2()));
spider.moveTo(arm.getX2(), arm.getY2());
walk.add(finishPoint);
spidermove(walk, xAnterior, yAnterior);
break;
}
}
this.strandFinish = strand;
return walk;
}
private ArrayList<ArrayList<Float>> isPosible1(int strand) {
ArrayList<ArrayList<Float>> walk = new ArrayList<>();
hilosTomados = new ArrayList<>();
float xSpiderActual = spider.getXPosition();
float ySpiderActual = spider.getYPosition();
boolean foundBridge = false;
while (!foundBridge) {
Map<Boolean, Bridges> bridgeMap = nextBridge1(bridgesByStrand.get(strand), strand, xSpiderActual, ySpiderActual);
boolean bridgeExists = new ArrayList<>(bridgeMap.keySet()).get(0);
if (bridgesByStrand.get(strand).size() > 0 && bridgeExists) {
hilosTomados.add(strand + 1);
Bridges bridge = bridgeMap.get(bridgeExists);
ArrayList<Float> points = bridge.returnPointAcomodados(strand);
ArrayList<Float> firstPoint = new ArrayList<>(Arrays.asList(points.get(0), points.get(1)));
ArrayList<Float> secondPoint = new ArrayList<>(Arrays.asList(points.get(2), points.get(3)));
xSpiderActual = points.get(2);
ySpiderActual = points.get(3);
walk.addAll(Arrays.asList(firstPoint, secondPoint));
strand = (bridge.hiloInicial == strand) ? (strand == strands - 1 ? 0 : strand + 1) : (strand == 0 ? strands - 1 : strand - 1);
} else {
hilosTomados.add(strand + 1);
ArrayList<Float> finishPoint = new ArrayList<>(Arrays.asList(xStard, yStard)); // Modificado aquí
walk.add(finishPoint);
break;
}
}
this.strandFinish = 0;
return walk;
}
/**
* Devuelve una lista de colores de los spots que son alcanzables desde la posición actual de la araña en la telaraña.
*
* @return Una lista de cadenas que representan los colores de los spots alcanzables desde la posición actual de la araña.
*/
public ArrayList<String> reachableSpot() {
boolean finishWalk = true;
ArrayList<String> spots = new ArrayList<String>();
for (String color : colorSports) {
int hilos = (int) this.strand;
while (finishWalk) {
if (spotColor.get(color).getNumber() == hilos - 1 && lineList.get(hilos - 1).getColor() == color) {
finishWalk = false;
spots.add(color);
} else if (bridgesByStrand.get(hilos - 1).size() > 0) {
hilos += 1;
} else {
finishWalk = false;
}
}
finishWalk = true;
}
return spots;
}
/**
* Devuelve una lista de los colores de los puentes en la red de telaraña.
*
* @return Una lista de los colores de los puentes.
*/
public String[] bridges() {
StringBuilder message = new StringBuilder();
for (String color : colorBridges) {
message.append(color).append("\n");
}
if (isVisible) {
JOptionPane.showMessageDialog(null, message.toString(), "Colores de Puentes", JOptionPane.INFORMATION_MESSAGE);
}
return colorBridges.toArray(new String[0]);
}
/**
* Devuelve una lista de los colores de los spots en la red de telaraña.
*
* @return Una lista de los colores de los spots.
*/
public String[] spots() {
StringBuilder spotColorsMessage = new StringBuilder("Colores de los spots:\n");
for (String color : colorSports) {
spotColorsMessage.append(color).append("\n");
}
if (isVisible) {
JOptionPane.showMessageDialog(null, spotColorsMessage.toString(), "Colores de los spots", JOptionPane.INFORMATION_MESSAGE);
}
return colorSports.toArray(new String[0]);
}
/**
* Devuelve el número del brazo donde se encuentra un punto de referencia dado su color.
*
* @param color El color del punto de referencia.
* @return El número del brazo donde se encuentra el punto de referencia,
*/
public int spot(String color) {
if (!spotColor.containsKey(color)) {
if (isVisible) {
JOptionPane.showMessageDialog(null, "El spot de color " + color + " no existe en la telaraña.");
}
isOk = false;
return -1;
} else {
isOk = true;
return spotColor.get(color).getNumber();
}
}
/**
* Retorna una lista de hilos (strands) en los cuales se encuentra un puente dado su color.
*
* @param color El color del puente.
* @return Una lista de enteros que representan los hilos donde se encuentra el puente.
*/
public int[] bridge(String color) {
ArrayList<Integer> strandsWithBridge = new ArrayList<>();
for (int i = 0; i < strands; i++) {
ArrayList<Bridges> bridges = bridgesByStrand.get(i);
for (Bridges bridge : bridges) {
if (Objects.equals(bridge.getColor(), color)) {
strandsWithBridge.add(i + 1);
break;
}
}
}
StringBuilder strandsMessage = new StringBuilder("Strand por los que atraviesa el puente:\n");
for (int i = 0; i < strandsWithBridge.size(); i++) {
strandsMessage.append(strandsWithBridge.get(i));
if (i < strandsWithBridge.size() - 1) {
strandsMessage.append(", ");
}
}
if (isVisible && showmensage) {
JOptionPane.showMessageDialog(null, strandsMessage.toString(), "Strand", JOptionPane.INFORMATION_MESSAGE);
}
int[] array = new int[strandsWithBridge.size()];
for (int i = 0; i < strandsWithBridge.size(); i++) {
array[i] = strandsWithBridge.get(i);
}
return array;
}
/**
* Agrega un nuevo brazo a la red de telaraña.
* <p>
* Este método incrementa el número de brazos en la red de telaraña, recalcula las coordenadas
* de los brazos con el nuevo número de brazos y hace visible nuevamente la red de telaraña.
*/
public void addStrand() {
boolean wasVisible = isVisible;
makeInvisible();
strands += 1;
list = new angles(radio, strands);
this.angle = list.getCant();
this.lists = list.getList();
this.lineList = new ArrayList<>();
this.lineListSpot = new ArrayList<>();
cordenates();
bridgesByStrand.put(strands - 1, new ArrayList<>());
hideBridges();
bridgesType.clear();
for (int strand : bridgesByStrand.keySet()) {
for (Bridges l : bridgesByStrand.get(strand)) {
float distance = l.distance;
l.makeInvisible();
relocateBridgeAutomatico(l.getColor(), distance);
}
}
for (String color : spotColor.keySet()) {
int strand = spotColor.get(color).getNumber();
Spot arm = lineListSpot.get(strand-1);
arm.changeColor(color);
lineListSpot.set(strand-1, arm);
}
eraseRecorrido();
if (wasVisible && !isVisible) {
makeVisible();
}
}
/**
* Aumenta el tamaño de la red de telaraña según un porcentaje dado.
*
* @param porcentage El porcentaje por el cual se aumentará el tamaño de la red.
*/
public boolean enlarge(int porcentage) {
if (porcentage < 0) {
if (isVisible) {
JOptionPane.showMessageDialog(null, "No se puede agrandar con numeros negativos.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
isOk = false;
} else {
boolean wasVisible = isVisible;
makeInvisible();
this.radio = radio * (100 + porcentage) / 100;
list = new angles(radio, strands);
this.angle = list.getCant();
this.lists = list.getList();
this.lineList = new ArrayList<>();
cordenates();
for (String color : spotColor.keySet()) {
int strand = spotColor.get(color).getNumber();
Strands arm = lineList.get(strand);
arm.changeColor(color);
lineList.set(strand, arm);
}
if (wasVisible && !isVisible) {
makeVisible();
}
isOk = true;
}
return isOk;
}
/**
* Devuelve una lista de puentes sin usar en la red de telaraña.
*
* @return Una lista de cadenas que representan los colores de los puentes sin usar.
*/
public String[] unUsedBridges() {
ArrayList<String> unUsedBridgesColors = new ArrayList<>(colorBridges);
for (Bridges usedBridge : bridgesUsed) {
String usedBridgeColor = usedBridge.getColor();
unUsedBridgesColors.remove(usedBridgeColor);
}
return unUsedBridgesColors.toArray(new String[0]);
}
/**
* Obtiene el listado de los hilos tomados por la araña la última vez que caminó.
*
* @return Una lista de enteros que representan los números de los brazos tomados por la araña.
*/
public int[] spiderLastPath() {
int[] array = new int[hilosTomados.size()];
for (int i = 0; i < hilosTomados.size(); i++) {
array[i] = hilosTomados.get(i);
}
return array;
}
/**
* Finaliza la clase y realiza las operaciones necesarias para limpiar los datos y hacer invisible la telaraña y la araña.
* Cierra la ventana.
*/
public void finish() {
System.exit(0);
}
private class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getFirst() {
return key;
}
public V getSecond() {
return value;
}
}
private class angles {
private final List<Pair<Float, Float>> list;
private final float cant;
/**
* Crea una nueva instancia de la clase angles.
*
* @param radio El radio del círculo.
* @param count La cantidad de pares de coordenadas a generar.
*/
public angles(int radio, int count) {
this.list = new ArrayList<>();
float totalAngle;
float angle;
angle = 0;
totalAngle = 360;
this.cant = totalAngle / count;
while (angle < totalAngle) {
list.add(new Pair<>((float) Math.round((radio * Math.cos(Math.toRadians(angle)))), (float) Math.round((radio * Math.sin(Math.toRadians(angle))))));
angle += cant;
}
}
/**
* Obtiene la lista de pares de coordenadas generada.
*
* @return La lista de pares de coordenadas.
*/
public List<Pair<Float, Float>> getList() {
return list;
}
/**
* Obtiene la cantidad de ángulo entre los pares de coordenadas.
*
* @return La cantidad de ángulo entre los pares de coordenadas.
*/
public float getCant() {
return cant;
}
}
private class Tuple {
private final int number;
private final String text;
public Tuple(int number, String text) {
this.number = number;
this.text = text;
}
public int getNumber() {
return number;
}
public String getType() {
return text;
}
}
/**
* Devuelve el estado de los metodos.
*
* @return {@code true} si la araña está en un estado válido para continuar con las operaciones,
* {@code false} de lo contrario.
*/
public boolean ok() {
return isOk;
}
/**
* This method is used to get the radius of the spider web.
* The radius is the distance from the center of the web to the outermost strand.
*
* @return The radius of the spider web.
*/
public int getRadio() {
return radio;
}
/**
* This method is used to check if the spider is alive.
* If the spider is alive, it can move along the strands and bridges of the spider web.
* If the spider is not alive, it cannot move.
*
* @return A boolean value indicating if the spider is alive (true) or not (false).
*/
public boolean isSpiderLive() {
return spider.isLive;
}
/**
* This method is used to get the strand number where the spider finished its last move.
* The strand number is incremented by 1 before being returned because the internal representation of strands starts from 0,
* but for the user, strands are numbered starting from 1.
*
* @return The strand number where the spider finished its last move, incremented by 1.
*/
public int getStrandFinish() {
return strandFinish+1;
}
}
| andresserrato2004/spiderweb | Spiderweb/SpiderWeb.java |
247,641 | import java.util.Arrays;
public class DynamicArray<T> {
private int size;
private Object[] elements;
public DynamicArray(Class<T> val){
this.size = 0;
this.elements = new Object[0];
}
public int size(){
return this.size;
}
public void add(T val){
size++;
elements = Arrays.copyOf(elements, size);
elements[size-1] = val;
}
public T remove(int i){
if(i<0||i>=size) throw new IllegalArgumentException("Array Index out of Bounds!");
int cnt = size-i-1;
T r = (T) elements[i];
System.arraycopy(elements, i+1, elements, i, cnt);
// elements[size] = null;
size--;
return r;
}
public T remove(Object o){
for (int i = 0; i < size; i++){
if(elements[i].equals(o)){
T r = (T) elements[i];
size--;
System.arraycopy(elements, i+1, elements, i, size-i);
return r;
}
}
// for (Object i : elements){
// if(o.equals(i)){
// size--;
// System.arraycopy(elements, )
// return (T) i;
// }
// }
return null;
}
public T removeAll(Object o){
for (Object i : elements){
if(o.equals(i)) remove(i);
}
return (T)o;
}
public boolean isEmpty(){
return (size==0);
}
public T get(int i){
if(i<0||i>=size) return null;
// System.out.println(this.size);
return (T) elements[i];
}
public void add(int i, T var){
if(i<0||i>size) throw new IllegalArgumentException("Array Index out of Bounds!");
enlarge();
// elements = Arrays.copyOf(elements, size);
System.arraycopy(elements, i, elements, i+1, size-i);
elements[i] = var;
size++;
}
public void set(int i, T var){
if(i < 0 || i>=size) throw new IllegalArgumentException("Array Index out of Bounds!");
elements[i] = var;
}
public boolean contains(Object o) {
for (Object i : elements){
if(i.equals(o))return true;
}
return false;
}
public void clear(){
size=0;
elements = Arrays.copyOf(elements, 0);
}
private void enlarge(){
Object[] newElements = new Object[size+1];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
}
| wsw2025/CS.12.01-Lab.1.2.1 | src/DynamicArray.java |
247,642 | public class ArrayDeque<T> implements Deque<T> {
/** The starting size of our array list. */
private T[] items;
private int size;
private int first;
private int last;
private double factor;
private final double Rfactor = 0.25;
public ArrayDeque() {
items = (T[]) new Object[8];
size = 0;
first = items.length / 2 + 1;
last = items.length / 2;
}
/** adds item to the front of the list. */
@Override
public void addFirst(T item) {
first -= 1;
size += 1;
if (isReachtheEnd(first)) {
first = items.length - 1;
}
if (isOverLap()) {
enlarge();
}
items[first] = item;
}
/** adds item to the back of the list. */
@Override
public void addLast(T item) {
last += 1;
size += 1;
if (isReachtheEnd(last)) {
last = 0;
}
if (isOverLap()) {
enlarge();
}
items[last] = item;
}
/** removes first item from the list, */
@Override
public T removeFirst() {
if (!isEmpty()) {
T result = items[first];
items[first] = null;
first += 1;
size -= 1;
if (isReachtheEnd(first)) {
first = 0;
}
if (isOverSize()) {
shrink();
} else if (isOverLap()) {
enlarge();
}
return result;
}
return null;
}
/** removes last item from the list. */
@Override
public T removeLast() {
if (!isEmpty()) {
T result = items[last];
items[last] = null;
last -= 1;
size -= 1;
if (isReachtheEnd(last)) {
last = items.length - 1;
}
if (isOverSize()) {
shrink();
} else if (isOverLap()) {
enlarge();
}
return result;
}
return null;
}
/** Gets ith item from the list. */
@Override
public T get(int i) {
if (first + i >= items.length) {
int index = i + first - items.length;
if (index <= last) {
return items[index];
} else {
return null;
}
} else {
return items[i + first];
}
}
/** returns the size of the list. */
@Override
public int size() {
return size;
}
/** resizing the list. */
private void enlarge() {
int length = items.length * 2;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, length / 4, items.length - first);
System.arraycopy(items, 0, result, length / 4 + size - first - 1, last + 1);
items = result;
first = length / 4;
last = length / 4 + size - 1;
}
private void shrink() {
if (first < last) {
int length = size * 3;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, items.length / 3, size);
first = items.length / 3;
last = size + first - 1;
items = result;
} else {
int length = size * 2;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, length / 4, items.length - first);
System.arraycopy(items, 0, result, length / 4 + size - last - 1, last + 1);
first = length / 4;
last = first + size - 1;
items = result;
}
}
/** There are three meanings:
* 1. first or last was over the bound.
* 2. first equals to last.
* 3. size is larger than 16 and usage factor should less than 0.25.
*/
private boolean isOverSize() {
factor = Double.valueOf(size) / Double.valueOf(items.length);
return (factor < Rfactor) && (items.length >= 16);
}
private boolean isReachtheEnd(int index) {
return index < 0 || index >= items.length;
}
private boolean isOverLap() {
return (first == last) && (size != 1);
}
@Override
public void printDeque() {
for (int i = 0; i < size; i++) {
System.out.print(get(i) + " ");
}
System.out.println();
}
}
| PolymagicYang/data-structure-in-Java | proj1b/ArrayDeque.java |
247,643 | public class ArrayDeque<T> {
/** The starting size of our array list. */
private T[] items;
private int size;
private int first;
private int last;
private double factor;
private final double Rfactor = 0.25;
public ArrayDeque() {
items = (T[]) new Object[8];
size = 0;
first = items.length / 2 + 1;
last = items.length / 2;
}
/** adds item to the front of the list. */
public void addFirst(T item) {
first -= 1;
size += 1;
if (isReachtheEnd(first)) {
first = items.length - 1;
}
if (isOverLap()) {
enlarge();
}
items[first] = item;
}
/** adds item to the back of the list. */
public void addLast(T item) {
last += 1;
size += 1;
if (isReachtheEnd(last)) {
last = 0;
}
if (isOverLap()) {
enlarge();
}
items[last] = item;
}
/** removes first item from the list, */
public T removeFirst() {
if (!isEmpty()) {
T result = items[first];
items[first] = null;
first += 1;
size -= 1;
if (isReachtheEnd(first)) {
first = 0;
}
if (isOverSize()) {
shrink();
} else if (isOverLap()) {
enlarge();
}
return result;
}
return null;
}
/** removes last item from the list. */
public T removeLast() {
if (!isEmpty()) {
T result = items[last];
items[last] = null;
last -= 1;
size -= 1;
if (isReachtheEnd(last)) {
last = items.length - 1;
}
if (isOverSize()) {
shrink();
} else if (isOverLap()) {
enlarge();
}
return result;
}
return null;
}
/** Gets ith item from the list. */
public T get(int i) {
if (first + i >= items.length) {
int index = i + first - items.length;
if (index <= last) {
return items[index];
} else {
return null;
}
} else {
return items[i + first];
}
}
/** returns the size of the list. */
public int size() {
return size;
}
/** resizing the list. */
private void enlarge() {
int length = items.length * 2;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, length / 4, items.length - first);
System.arraycopy(items, 0, result, length / 4 + size - first - 1, last + 1);
items = result;
first = length / 4;
last = length / 4 + size - 1;
}
private void shrink() {
if (first < last) {
int length = size * 3;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, items.length / 3, size);
first = items.length / 3;
last = size + first - 1;
items = result;
} else {
int length = size * 2;
T[] result = (T []) new Object[length];
System.arraycopy(items, first, result, length / 4, items.length - first);
System.arraycopy(items, 0, result, length / 4 + size - last - 1, last + 1);
first = length / 4;
last = first + size - 1;
items = result;
}
}
/** There are three meanings:
* 1. first or last was over the bound.
* 2. first equals to last.
* 3. size is larger than 16 and usage factor should less than 0.25.
*/
private boolean isOverSize() {
factor = Double.valueOf(size) / Double.valueOf(items.length);
return (factor < Rfactor) && (items.length >= 16);
}
private boolean isReachtheEnd(int index) {
return index < 0 || index >= items.length;
}
private boolean isOverLap() {
return (first == last) && (size != 1);
}
public boolean isEmpty() {
return (items[first] == null) || (items[last] == null);
}
public void printDeque() {
for (int i = 0; i < size; i++) {
System.out.print(get(i) + " ");
}
System.out.println();
}
}
| PolymagicYang/data-structure-in-Java | proj1a/ArrayDeque.java |
247,644 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Circle {
private final Point center;
private final double radius;
public Circle(Point center, double radius) {
this.center = center;
this.radius = radius;
}
public Circle() {
center = new Point();
radius = 0;
}
public Circle(double x, double y, double radius) {
center = new Point(x, y);
this.radius = radius;
}
public Point getCenter() {
return center;
}
public double getRadius() {
return radius;
}
public Circle enlarge(double f) {
return new Circle(center, radius * f);
}
public double getArea() {
return Math.PI * radius * radius;
}
public String toString() {
return String.format("(%f,%f), %f", center.getX(), center.getY(), radius);
}
public static Circle readFromFile(String inFileName) throws FileNotFoundException {
return readFromFile(new File(inFileName));
}
public static Circle readFromFile(File in) {
try(Scanner sc = new Scanner(in)) {
double x = sc.nextDouble();
double y = sc.nextDouble();
double radius = sc.nextDouble();
return new Circle(x, y, radius);
} catch (FileNotFoundException | InputMismatchException e) {
return new Circle();
}
}
public void saveToFile(String outFileName) throws FileNotFoundException {
saveToFile(new File(outFileName));
}
public void saveToFile(File outFile) throws FileNotFoundException {
try (PrintWriter pw = new PrintWriter(outFile)) {
pw.println(center.getX());
pw.println(center.getY());
pw.println(radius);
}
}
}
| balihb/java-gyak | 20-21-2/06/04/Circle.java |
247,645 | import images.*;
/**
* Processes an image provided by the user
*/
public class Processing {
private APImage image;
/**
* constructor to create a Processing object by initializing processing image
* @param s file name to access the image file
*/
public Processing(String s) {
image = new APImage(s);
}
/**
* returns the image instance variable
* @return APImage image instance variable
*/
public APImage getImage() {
return image;
}
/**
* converts the image to black and white
* @return the black and white image
*/
//Convert an image to BW (Christina)
public APImage convertBW() {
image.draw();
APImage newImage = image.clone();
for (Pixel little : newImage) {
//take the average of the colors
int average = (little.getRed() + little.getBlue() + little.getGreen())/3;
if (average < 128) {
//set the same Pixel to black
little.setRed(0);
little.setGreen(0);
little.setBlue(0);
}
else {
//set it to white
little.setRed(255);
little.setGreen(255);
little.setBlue(255);
}
}
return newImage;
}
/**
* converts the image to grayscale
* @return the grayscale image
*/
public APImage convertGray() {
APImage ret = image.clone();
for (Pixel p : ret) {
int average = (p.getRed() + p.getBlue() + p.getGreen())/3;
p.setRed(average);
p.setGreen(average);
p.setBlue(average);
}
return ret;
}
/**
* converts the image to luminance grayscale
* @return the luminance grayscale image
*/
//Convert image to luminance grayscale (Christina)
public APImage lumGray() {
//an image is not an array of pixels, you can't traverse it like this
APImage ret = image.clone();
int width = ret.getWidth();
int height = ret.getHeight();
for(int w = 0; w < width; w++) {
for(int h = 0; h < height; h++) {
Pixel p = ret.getPixel(w, h);
int average = (int)(p.getRed() * 0.299 + p.getBlue() * .114 + p.getGreen() * .587);
p.setRed(average);
p.setGreen(average);
p.setBlue(average);
}
}
return ret;
}
/**
* rotates the image left by 90 degrees
* @return the rotated left image
*/
//Rotate left 90, right 90, 180 (Isha)
public APImage rotateL() {
//APImage ret = image.clone();
int newheight = image.getWidth();
int newwidth = image.getHeight();
APImage ret = new APImage(newwidth, newheight);
for (int i = 0; i < ret.getHeight(); i++) {
for (int j = 0; j < ret.getWidth(); j++) {
ret.setPixel(j, ret.getHeight()-1-i, image.getPixel(i, j));
}
}
return ret;
}
/**
* rotates the image right by 90 degrees
* @return the rotated right image
*/
public APImage rotateR() {
int newheight = image.getWidth();
int newwidth = image.getHeight();
APImage ret = new APImage(newwidth, newheight);
for (int i = 0; i < ret.getHeight(); i++) {
for (int j = 0; j < ret.getWidth(); j++) {
ret.setPixel(ret.getWidth() - j - 1, i, image.getPixel(i, j));
}
}
return ret;
}
/**
* flip the image 180 degrees
* @return the flipped image
*/
public APImage rotateFlip() {
APImage ret = new APImage(image.getWidth(), image.getHeight());
for (int i = ret.getWidth() - 1; i >= 0; i--) {
for (int j = ret.getHeight()-1; j >= 0; j--) {
ret.setPixel(i, j, image.getPixel(image.getWidth()-i-1, image.getHeight()-j-1));
}
}
return ret;
}
/**
* apply a sepia effect to the image
* @return the sepia image
*/
// Convert to sepia (Isha)
public APImage sepia() {
APImage ret = convertGray();
for(Pixel p: ret) {
if(p.getRed() < 63) {
p.setRed((int)(p.getRed() * 1.1));
p.setBlue((int)(p.getBlue() * 0.9));
} else if (p.getRed() < 192) {
p.setRed( (int)(p.getRed() * 1.15));
p.setBlue((int)(p.getBlue() * 0.85));
} else {
p.setRed(Math.min((int)(p.getRed() * 1.08), 255));
p.setBlue((int)(p.getBlue() * 0.93));
}
}
return ret;
}
/**
* darkens the image by a factor
* @param factor - the darkening factor
* @return the darkened image
*/
// Darken/brighten image (Felicia)
public APImage darken(int factor) {
APImage ret = image.clone();
//ret.draw();
for(Pixel p: ret) {
int darkRed = p.getRed()-factor;
int darkGreen = p.getGreen()-factor;
int darkBlue = p.getBlue()-factor;
p.setRed(Math.max(0, darkRed));
p.setGreen(Math.max(0, darkGreen));
p.setBlue(Math.max(0, darkBlue));
// p.setRed(darkRed);
// p.setGreen(darkGreen);
// p.setBlue(darkBlue);
}
return ret;
}
/**
* brightens the image by a factor
* @param factor - the brightening factor
* @return the brightened image
*/
public APImage brighten(int factor) {
APImage ret = image.clone();
//ret.draw();
for(Pixel p: ret) {
int brightRed = p.getRed()+factor;
int brightGreen = p.getGreen()+factor;
int brightBlue = p.getBlue()+factor;
p.setRed(Math.min(255, brightRed));
p.setGreen(Math.min(255, brightGreen));
p.setBlue(Math.min(255, brightBlue));
// p.setRed(darkRed);
// p.setGreen(darkGreen);
// p.setBlue(darkBlue);
}
return ret;
}
/**
* filter the image by one or more RGB values
* @param red - red RGB factor
* @param green - green RGB factor
* @param blue - blue RGB factor
* @return the color filtered image
*/
//Do color filtering (Christina)
public APImage colorFilter (int red, int green, int blue) {
APImage ret = image.clone();
int width = ret.getWidth();
int height = ret.getHeight();
for(int w = 0; w < width; w++) {
for(int h = 0; h < height; h++) {
Pixel p = ret.getPixel(w, h);
if (p.getRed() + red > 255) {
p.setRed(255);
}
else if (p.getRed() + red < 0) {
p.setRed(0);
}
else {
p.setRed(p.getRed() + red);
}
if (p.getGreen() + green > 255) {
p.setGreen(255);
}
else if (p.getGreen() + green < 0) {
p.setGreen(0);
}
else {
p.setGreen(p.getGreen() + green);
}
if (p.getBlue() + blue > 255) {
p.setBlue(255);
}
else if (p.getBlue() + blue < 0) {
p.setBlue(0);
}
else {
p.setBlue(p.getBlue() + blue);
}
}
}
return ret;
}
/**
* posterizes image
* @return the posterized image
*/
/* Posterize image (Saee)
*/
public APImage posterize() {
int width = image.getWidth();
int height = image.getHeight();
APImage i = new APImage(width, height);
int randomRedOne = (int)(Math.random()*256);
int randomGreenOne = (int)(Math.random()*256);
int randomBlueOne = (int)(Math.random()*256);
int randomRedTwo = (int)(Math.random()*256);
int randomGreenTwo = (int)(Math.random()*256);
int randomBlueTwo = (int)(Math.random()*256);
for(int w = 0; w < width; w++) {
for(int h = 0; h < height; h++) {
Pixel p = image.getPixel(w, h);
if(p.getBlue() <= 100 && p.getRed() <= 100 && p.getGreen() <= 100) {
i.setPixel(w, h, new Pixel(randomRedOne, randomGreenOne, randomBlueOne));
} else {
i.setPixel(w, h, new Pixel(randomRedTwo, randomGreenTwo, randomBlueTwo));
}
}
}
return i;
}
/**
* converts the image to photographic negative
* @return the photographic negative image
*/
/* Convert to photographic negative (Saee)
*/
public APImage photographicNegative() {
APImage ret = convertGray();
for(Pixel p : ret) {
p.setRed(255 - p.getRed());
p.setBlue(255 - p.getBlue());
p.setGreen(255 - p.getGreen());
}
return ret;
}
/**
* sharpen image
* @return the sharpened image
*/
/* Sharpen (Saee)
*/
public APImage sharpen(int threshold, int degree) {
int width = image.getWidth();
int height = image.getHeight();
APImage ret = new APImage(width, height);
for(int w = 1; w < width; w++) {
for(int h = 0; h < height - 1; h++) {
Pixel curr = image.getPixel(w, h);
Pixel left = image.getPixel(w - 1, h);
Pixel bottom = image.getPixel(w, h +1);
int currAve = (curr.getRed() + curr.getBlue() + curr.getGreen())/3;
int leftAve = (left.getRed() + left.getBlue() + left.getGreen())/3;
int bottomAve = (bottom.getRed() + bottom.getBlue() + bottom.getGreen())/3;
Pixel changingPixel = ret.getPixel(w, h);
if(Math.abs(currAve - leftAve) > threshold || Math.abs(currAve - bottomAve) > threshold) {
changingPixel.setRed(Math.max(0, curr.getRed() - degree));
changingPixel.setGreen(Math.max(0, curr.getGreen() - degree));
changingPixel.setBlue(Math.max(0, curr.getBlue() - degree));
} else {
changingPixel.setRed(curr.getRed());
changingPixel.setGreen(curr.getGreen());
changingPixel.setBlue(curr.getBlue());
}
}
}
return ret;
}
/**
* blur image
* @return the blurred image
*/
public APImage blur() {
int width = image.getWidth();
int height = image.getHeight();
APImage ret = new APImage(width, height);
for(int w = 0; w < width; w++) {
for(int h = 0; h < height; h++) {
int sumRed = 0;
int sumGreen = 0;
int sumBlue = 0;
int pixelsAccounted = 0;
if(w > 0) {
sumRed += image.getPixel(w-1, h).getRed();
sumBlue += image.getPixel(w-1, h).getBlue();
sumGreen += image.getPixel(w-1, h).getGreen();
pixelsAccounted++;
}
if(w < width-1) {
sumRed += image.getPixel(w+1, h).getRed();
sumBlue += image.getPixel(w+1, h).getBlue();
sumGreen += image.getPixel(w+1, h).getGreen();
pixelsAccounted++;
}
if(h > 0) {
sumRed += image.getPixel(w, h-1).getRed();
sumBlue += image.getPixel(w, h-1).getBlue();
sumGreen += image.getPixel(w, h-1).getGreen();
pixelsAccounted++;
}
if(h < height-1) {
sumRed += image.getPixel(w, h+1).getRed();
sumBlue += image.getPixel(w, h+1).getBlue();
sumGreen += image.getPixel(w, h+1).getGreen();
pixelsAccounted++;
}
int redAverage = sumRed/pixelsAccounted;
int greenAverage = sumGreen/pixelsAccounted;
int blueAverage = sumBlue/pixelsAccounted;
Pixel curr = ret.getPixel(w, h);
curr.setRed(redAverage);
curr.setGreen(greenAverage);
curr.setBlue(blueAverage);
}
}
return ret;
}
/**
* shrinks the image by a factor
* @param factor - the shrinking factor
* @return the shrunken image
*/
//Shrink (Felicia)
public APImage shrink(int factor) {
int shrunkenWidth = (image.getWidth()/factor);
int shrunkenHeight = (image.getHeight()/factor);
APImage shrunkenImage = new APImage(shrunkenWidth, shrunkenHeight);
for(int i = 0; i < shrunkenWidth; i++) {
for(int j = 0; j < shrunkenHeight; j++) {
shrunkenImage.setPixel(i, j, image.getPixel(i*factor, j*factor));
}
}
return shrunkenImage;
}
/**
* enlarges the image by a factor
* @param factor - the enlarging factor
* @return the enlarged image
*/
//Enlarge (Felicia)
public APImage enlarge(int factor) {
int enlargedWidth = (image.getWidth()*factor);
int enlargedHeight = (image.getHeight()*factor);
APImage enlargedImage = new APImage(enlargedWidth, enlargedHeight);
for(int i = 0; i < enlargedWidth; i++) {
for(int j = 0; j < enlargedHeight; j++) {
enlargedImage.setPixel(i, j, image.getPixel(i/factor, j/factor));
}
}
return enlargedImage;
}
/*
* VIDEO EDITING (Together)
* SLIDESSSSS (Together)
*/
}
| saeephalke/Image-Processing | src/Processing.java |
247,646 | package sun.awt.geom;
import java.awt.geom.Rectangle2D;
final class Order1
extends Curve
{
private double x0;
private double y0;
private double x1;
private double y1;
private double xmin;
private double xmax;
public Order1(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, int paramInt)
{
super(paramInt);
x0 = paramDouble1;
y0 = paramDouble2;
x1 = paramDouble3;
y1 = paramDouble4;
if (paramDouble1 < paramDouble3)
{
xmin = paramDouble1;
xmax = paramDouble3;
}
else
{
xmin = paramDouble3;
xmax = paramDouble1;
}
}
public int getOrder()
{
return 1;
}
public double getXTop()
{
return x0;
}
public double getYTop()
{
return y0;
}
public double getXBot()
{
return x1;
}
public double getYBot()
{
return y1;
}
public double getXMin()
{
return xmin;
}
public double getXMax()
{
return xmax;
}
public double getX0()
{
return direction == 1 ? x0 : x1;
}
public double getY0()
{
return direction == 1 ? y0 : y1;
}
public double getX1()
{
return direction == -1 ? x0 : x1;
}
public double getY1()
{
return direction == -1 ? y0 : y1;
}
public double XforY(double paramDouble)
{
if ((x0 == x1) || (paramDouble <= y0)) {
return x0;
}
if (paramDouble >= y1) {
return x1;
}
return x0 + (paramDouble - y0) * (x1 - x0) / (y1 - y0);
}
public double TforY(double paramDouble)
{
if (paramDouble <= y0) {
return 0.0D;
}
if (paramDouble >= y1) {
return 1.0D;
}
return (paramDouble - y0) / (y1 - y0);
}
public double XforT(double paramDouble)
{
return x0 + paramDouble * (x1 - x0);
}
public double YforT(double paramDouble)
{
return y0 + paramDouble * (y1 - y0);
}
public double dXforT(double paramDouble, int paramInt)
{
switch (paramInt)
{
case 0:
return x0 + paramDouble * (x1 - x0);
case 1:
return x1 - x0;
}
return 0.0D;
}
public double dYforT(double paramDouble, int paramInt)
{
switch (paramInt)
{
case 0:
return y0 + paramDouble * (y1 - y0);
case 1:
return y1 - y0;
}
return 0.0D;
}
public double nextVertical(double paramDouble1, double paramDouble2)
{
return paramDouble2;
}
public boolean accumulateCrossings(Crossings paramCrossings)
{
double d1 = paramCrossings.getXLo();
double d2 = paramCrossings.getYLo();
double d3 = paramCrossings.getXHi();
double d4 = paramCrossings.getYHi();
if (xmin >= d3) {
return false;
}
double d6;
double d5;
if (y0 < d2)
{
if (y1 <= d2) {
return false;
}
d6 = d2;
d5 = XforY(d2);
}
else
{
if (y0 >= d4) {
return false;
}
d6 = y0;
d5 = x0;
}
double d8;
double d7;
if (y1 > d4)
{
d8 = d4;
d7 = XforY(d4);
}
else
{
d8 = y1;
d7 = x1;
}
if ((d5 >= d3) && (d7 >= d3)) {
return false;
}
if ((d5 > d1) || (d7 > d1)) {
return true;
}
paramCrossings.record(d6, d8, direction);
return false;
}
public void enlarge(Rectangle2D paramRectangle2D)
{
paramRectangle2D.add(x0, y0);
paramRectangle2D.add(x1, y1);
}
public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt)
{
if ((paramDouble1 == y0) && (paramDouble2 == y1)) {
return getWithDirection(paramInt);
}
if (x0 == x1) {
return new Order1(x0, paramDouble1, x1, paramDouble2, paramInt);
}
double d1 = x0 - x1;
double d2 = y0 - y1;
double d3 = x0 + (paramDouble1 - y0) * d1 / d2;
double d4 = x0 + (paramDouble2 - y0) * d1 / d2;
return new Order1(d3, paramDouble1, d4, paramDouble2, paramInt);
}
public Curve getReversedCurve()
{
return new Order1(x0, y0, x1, y1, -direction);
}
public int compareTo(Curve paramCurve, double[] paramArrayOfDouble)
{
if (!(paramCurve instanceof Order1)) {
return super.compareTo(paramCurve, paramArrayOfDouble);
}
Order1 localOrder1 = (Order1)paramCurve;
if (paramArrayOfDouble[1] <= paramArrayOfDouble[0]) {
throw new InternalError("yrange already screwed up...");
}
paramArrayOfDouble[1] = Math.min(Math.min(paramArrayOfDouble[1], y1), y1);
if (paramArrayOfDouble[1] <= paramArrayOfDouble[0]) {
throw new InternalError("backstepping from " + paramArrayOfDouble[0] + " to " + paramArrayOfDouble[1]);
}
if (xmax <= xmin) {
return xmin == xmax ? 0 : -1;
}
if (xmin >= xmax) {
return 1;
}
double d1 = x1 - x0;
double d2 = y1 - y0;
double d3 = x1 - x0;
double d4 = y1 - y0;
double d5 = d3 * d2 - d1 * d4;
double d6;
if (d5 != 0.0D)
{
double d7 = (x0 - x0) * d2 * d4 - y0 * d1 * d4 + y0 * d3 * d2;
d6 = d7 / d5;
if (d6 <= paramArrayOfDouble[0])
{
d6 = Math.min(y1, y1);
}
else
{
if (d6 < paramArrayOfDouble[1]) {
paramArrayOfDouble[1] = d6;
}
d6 = Math.max(y0, y0);
}
}
else
{
d6 = Math.max(y0, y0);
}
return orderof(XforY(d6), localOrder1.XforY(d6));
}
public int getSegment(double[] paramArrayOfDouble)
{
if (direction == 1)
{
paramArrayOfDouble[0] = x1;
paramArrayOfDouble[1] = y1;
}
else
{
paramArrayOfDouble[0] = x0;
paramArrayOfDouble[1] = y0;
}
return 1;
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\awt\geom\Order1.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | msjian/java1.8.0_151 | sun/awt/geom/Order1.java |
247,647 | class Circle {
double radius;
double x,y;
double getArea() {
return Math.PI*radius*radius;
}
void enlarge(double f) { //2
radius *= f;
}
} | murtazamnm/Java | Lab2/Circle.java |
247,648 | import java.awt.*;
class Circle {
int x, y; // center
int radius;
Color color;
Circle(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
void draw(Graphics g) {
g.setColor(this.color);
g.fillOval(this.x - this.radius,
this.y - this.radius,
this.radius * 2,
this.radius * 2);
}
void enlarge() {
this.radius += 1;
}
} | hpmsora/Java-Introduction-to-Software-Systems-C212 | Lab05/Circle.java |
247,649 | public class Circle {
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public void enlarge(double f) {
radius *= f;
}
public double getArea() {
return Math.pow(radius, 2) * Math.PI;
}
}
| rolee15/prognyelvek-java | gyak2/Circle.java |
247,650 | import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
System.out.println("Please input integer values between 0 and 10,000, " +
"when you are done inputting, please type NULL (Case Sensitive)");
Scanner input = new Scanner(System.in);
int [] array = new int[2];
String temp ;
for (int i = 0; i < array.length; i++)
{
temp = input.nextLine();
if (temp.equals("NULL"))
{
i = array.length;
}
else
{
array[i] = Integer.parseInt(temp);
}
if (i == array.length - 1)
{
System.out.println("INSIDE FIRST IF STATEMENT");
System.out.println(Arrays.toString(array));
array = enlarge(array); //array is filled, and I need to pass it over to enlargen the array,
// but then I need to store that new array back into the old array variable
}
}
ArrayList<Student> theList = new ArrayList<>();
}
static int[] enlarge(int[] array)
{
int [] newArray = new int[array.length * 2];
for (int i = 0; i < array.length; i++)
{
newArray[i] = array[i];
}
return newArray;
}
}
class Student
{
} | ayhashimi/ReplitPractice | src/Main.java |
247,651 | import java.util.*;
import java.io.*;
public class DatabaseProcessing{
static ArrayList<PeopleRecord> LoadData(String filename) throws Exception{//this method load every data for each person in class PeopleRecord,it returns an arraylist that contains all people's PeopleRecord
ArrayList<PeopleRecord> data= new ArrayList<>();//create an arratlist to store data
File file=new File(filename); //open file
FileReader fr= new FileReader(file); //read file
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!=null) { //read the file line by line
String[] ddata=line.split(";"); //split each line's data by ";"
PeopleRecord a=new PeopleRecord();
a.GivenName=ddata[0];
a.FamilyName=ddata[1];
a.CompanyName=ddata[2];
a.address=ddata[3];
a.city=ddata[4];
a.country=ddata[5];
a.state=ddata[6];
a.zip=ddata[7];
a.phone1=ddata[8];
a.phone2=ddata[9];
a.email=ddata[10];
a.web=ddata[11];
a.birthday=ddata[12];
data.add(a);// store the whole data of a person into PeopleRecord
}
br.close();//finish reading the file
return data;//return the arraylist
}
static void getMostFrequentWords(int count, int len)throws Exception{// this method prints the top n words as required, it returns nothing but will print directly
if(len<3) {
throw new Exception("ShortLengthException");//if the len does not reach the requirement, throw shortlengthexception
}
ArrayList<PeopleRecord> data=LoadData("your_path/people.txt"); //an arraylist that store all people's data through class PeopleRecord
ArrayList<String> ans= new ArrayList<>();//create an arraylist for all the info that are needed to be processed
for(int i=0;i<data.size();i++) {
if(data.get(i)!=null) {
ans.add(data.get(i).GivenName);
ans.add(data.get(i).FamilyName);
ans.add(data.get(i).CompanyName);
ans.add(data.get(i).address);
ans.add(data.get(i).city);
ans.add(data.get(i).country);
ans.add(data.get(i).state); // add all the data into the arraylist
}
}
ArrayList<String> AfterProcessing=new ArrayList<>();//create an arraylist to store data that is processing(all alphabet,len as required)
for(int i=0;i<ans.size();i++) {
String[] words=ans.get(i).split(" ");
for(int j=0;j<words.length;j++) { //loop every word split by blank
if(words[j].length()<len) continue; //ignore the word smaller than len
boolean flag=true;
for(int k=0;k<words[j].length();k++) {//loop every element of the word
int character= (int) (words[j].charAt(k));
if((character>=65&&character<=90)||(character>=97&&character<=122)) { //check whether is alphabet
}
else {
flag=false;
}
}
if(flag==true) AfterProcessing.add(words[j]);//input the filtered data into the new arraylist
}
}
QuadraticHashMap<String,Integer> dict=new QuadraticHashMap<>();//create a haspmap to continue process data
for(int i=0;i<AfterProcessing.size();i++) {
dict.put(AfterProcessing.get(i));//put all data into the hashmap
}
String[] FinalAns=dict.process(count); //the array stores top n data as required
for(int i=0;i<FinalAns.length;i++) {
if(FinalAns[i]!=null) {
System.out.println("The "+(i+1)+" most frequent word is: "+FinalAns[i]);//print out the top n words
}
}
}
static PeopleRecord[] search(ArrayList<PeopleRecord> data,String x,String y) {
MyBST<MyBST.Node> tree1=new MyBST<>();//create a BST
for(int i=0;i<data.size();i++) {
tree1.insert(data.get(i),"name");//input data
}
PeopleRecord[] ans=tree1.search("James", "Miller");
return ans;
}
static PeopleRecord[] sort(MyBST<MyBST.Node> tree1,String s) throws Exception{
MyHeap<MyHeap.Node> heap1=new MyHeap<>();
ArrayList<PeopleRecord> data=new ArrayList<>();
tree1.getAllData(tree1.root, data);
if(s.equals("name")) {
for(int i=0;i<data.size();i++) {
heap1.insert(data.get(i),"name");//input the data
}
int count2=heap1.HeapList.size();
PeopleRecord[] ans=new PeopleRecord[count2];
for(int i=0;i<count2;i++) {
MyHeap.Node testa=heap1.remove("name");
//put the data in descending order
ans[i]=testa.val;
}
return ans;
}
else if(s.equals("Birthday")) {
for(int i=0;i<data.size();i++) {
heap1.insert(data.get(i),"Birthday");//input the data
}
int count2=heap1.HeapList.size();
PeopleRecord[] ans=new PeopleRecord[count2];
for(int i=0;i<count2;i++) {
MyHeap.Node testa=heap1.remove("Birthday");
//put the data in descending order
ans[i]=testa.val;
}
return ans;
}
return null;
}
public static void main(String[] args) throws Exception{
/* 1.this section check whether the loaddata is corrent*/
ArrayList<PeopleRecord> data=LoadData("C:/Users/28621/eclipse-workspace/CS201 Final Project/src/people.txt");
System.out.println("The datas are: ");
for(int i=0;i<data.size();i++) {
System.out.print("("+data.get(i).GivenName+","+data.get(i).FamilyName+") ");//take name as an example, it should print out all the name;
}
System.out.println();
System.out.println();
/*loaddata check complete*/
/*2.this section check whether the BST can work*/
MyBST<MyBST.Node> tree1=new MyBST<>();//create a BST according to name order
for(int i=0;i<data.size();i++) {
tree1.insert(data.get(i),"name");//input data
}
//check the method "getinfo" is correct or not,it should print out the height and number of node
int[] info=tree1.getInfo();
System.out.println("The height of name-order tree is: "+info[0]);
System.out.println("The number of the node of name-order tree is: "+info[1]);
System.out.println();
System.out.println("The name-order tree structure through pre-order is: ");
tree1.preOrder(tree1.root);
System.out.println();
System.out.println();
//getinfo check complete//
System.out.println("The search result of James Miller is: ");
PeopleRecord[] a=search(data,"James","Miller");
if(a!=null) {
for(int i=0;i<a.length;i++) {
System.out.print("("+a[i].GivenName+","+a[i].FamilyName+") ");//print out the search result of james miller
}
}
else {
System.out.print("Null");
}
int check1=0;
for(int i=0;i<data.size();i++) {
if(data.get(i).GivenName.equals("James")&&data.get(i).FamilyName.equals("Miller")) {check1++;}//through linear search, it should have 3 james miller
}
System.out.print(", the number of James Miller should be "+check1);
System.out.println();//check the method "search" complete
System.out.println();
MyBST<MyBST.Node> tree2=new MyBST<>();//create a BST according to birthday order
for(int i=0;i<data.size();i++) {
tree2.insert(data.get(i),"Birthday");//input data
}
int[] info2=tree2.getInfo();
System.out.println("The height of birthday-order tree is: "+info2[0]);
System.out.println("The number of the node of birthday-irder tree is: "+info2[1]);
System.out.println();
System.out.println("The birthday-order tree structure through pre-order is: ");
tree2.preOrderBirthday(tree2.root);
System.out.println();
System.out.println();
//getinfo check complete//
System.out.println();
System.out.print("The people has the birthday of 02/14/1954 should be :");
PeopleRecord[] b=tree2.searchBirthday("02/14/1954");
if(b!=null) {
for(int i=0;i<b.length;i++) {
System.out.print("("+b[i].GivenName+" "+b[i].FamilyName+","+b[i].birthday+") ");//print out the search result of the certain birthday
}
}
else {
System.out.print("Null");
}
System.out.println();
//check the method "search" is correct or not//
/*BST check complete*/
System.out.println();
/*3.this section check sort is correct or not*/
System.out.println("Check whether the data comes out in descending order(name): ");
PeopleRecord[] check2=sort(tree1,"name");
for(int i=0;i<check2.length;i++) {
System.out.print("("+check2[i].GivenName+","+check2[i].FamilyName+") ");//check whether the data comes out in descending order(name)
}
System.out.println();
System.out.println();
System.out.println("Check whether the data comes out in descending order(Birthday): ");
PeopleRecord[] check3=sort(tree1,"Birthday");
for(int i=0;i<check3.length;i++) {
System.out.print("("+check3[i].GivenName+","+check3[i].FamilyName+","+check3[i].birthday+") ");//check whether the data comes out in descending order(Birthday)
}
System.out.println();
/*sort check complete*/
/*4.this section check QuadraticHaspMap is correct or not*/
QuadraticHashMap<String,PeopleRecord> QMap=new QuadraticHashMap<>();//create a new haspmap
for(int i=0;i<data.size();i++) {
QMap.put(data.get(i));//input the data
}
//check the method"search"
System.out.println();
System.out.println("Check if there is James Miller:");
System.out.println(QMap.search("James","Miller"));//should print true since there exist james miller cause we just proved before
System.out.println();
System.out.println("Check if there is A A:");
System.out.println(QMap.search("A","A"));//should print false because no such person
//method "search" check complete
System.out.println();
//check the method "get"
System.out.println("Check if there is James Miller and print out all people named this: ");
PeopleRecord[] name1=QMap.get("James","Miller");//should get 3 james miller since we already know there are 3 james miller proved before
for(int i=0;i<name1.length;i++) {
System.out.print("("+name1[i].GivenName+","+name1[i].FamilyName+") ");//print out the get result
}
System.out.println();
System.out.println();
//check the method "get" complete
//check the method "remove"
System.out.println("Check if there is Butt:");
System.out.println(QMap.search("James","Butt"));//prove that we have james butt now
System.out.println();
QMap.remove("James", "Butt");
System.out.println("Check if there is Butt after remove:");
System.out.println(QMap.search("James","Butt"));//prove that we don't have james butt now because we successfully removed it
System.out.println();
//check the method "remove" complete
/*QuadraticHashMap check complete*/
/*5.this section check the method "getMostFrequentWords"*/
System.out.println("Check the top n words that meet the requirement: ");
getMostFrequentWords(10, 3);//should print out as required
}
}
class PeopleRecord implements Comparable<PeopleRecord>{
String GivenName,FamilyName,CompanyName,address, city, country, state, zip, phone1, phone2, email, web, birthday;
PeopleRecord(String GivenName, String FamilyName, String CompanyName, String address, String city, String country, String state, String zip, String phone1, String phone2, String email, String web, String birthday) {
this.GivenName=GivenName;
this.FamilyName=FamilyName;
this.CompanyName=CompanyName;
this.address=address;
this.city=city;
this.country=country;
this.state=state;
this.zip=zip;
this.phone1=phone1;
this.phone2=phone2; // add all the parameters into the constructor and initialization them
this.email=email;
this.web=web;
this.birthday=birthday;
}
PeopleRecord(){
// an empty constructor
}
public int compareTo(PeopleRecord a) {//name comparator
String GivenName1=GivenName.toLowerCase(); // change all the element into lower case
String GivenName2=a.GivenName.toLowerCase();
for(int i=0;i<GivenName1.length();i++) {
if(i==GivenName2.length()) return 1; // givenname1 completely equals to givenname2
else {
if(((int) GivenName1.charAt(i))==((int) GivenName2.charAt(i))) continue; // consider the givenname1 and givenname2 might overlap at the beginning and differ at the end,
else {
if(((int) GivenName1.charAt(i))<((int) GivenName2.charAt(i))) return -1; // compare every element of the given name
else return 1;
}
}
}
String FamilyName1=FamilyName.toLowerCase();
String FamilyName2=a.FamilyName.toLowerCase();
for(int i=0;i<FamilyName1.length();i++) {
if(i==FamilyName2.length()) return 1;
else {
if(((int) FamilyName1.charAt(i))==((int) FamilyName2.charAt(i))) continue;
else {
if(((int) FamilyName1.charAt(i))<((int) FamilyName2.charAt(i))) return -1;
else return 1;
}
}
}
return 0; //if given name and family name are all the same
}
public int compareTo2(PeopleRecord a) {//birthday comparator
String[] Birthday1=birthday.split("/");
String[] Birthday2=a.birthday.split("/");
for(int j=0;j<4;j++) {
int char1= (int) (Birthday1[2].charAt(j));
int char2= (int) (Birthday2[2].charAt(j));
if (char1==char2) continue;
else if(char1<char2) {return 1;}
else {return -1;}
}
for(int j=0;j<2;j++) {
int char1= (int) (Birthday1[0].charAt(j));
int char2= (int) (Birthday2[0].charAt(j));
if (char1==char2) continue;
else if(char1<char2) {return 1;}
else {return -1;}
}
for(int j=0;j<2;j++) {
int char1= (int) (Birthday1[1].charAt(j));
int char2= (int) (Birthday2[1].charAt(j));
if (char1==char2) continue;
else if(char1<char2) {return 1;}
else {return -1;}
}
return 0;
}
}
class MyBST<Node>{
Node root;
int countsize=0;
static class Node{
PeopleRecord val;
Node left;
Node right; //create basic unit for tree
Node(PeopleRecord p){
this.val=p;
}
}
public void insert(PeopleRecord x,String s) {//insert data
countsize++;
root=insert(root,x,s);
}
private Node insert(Node root, PeopleRecord x,String s) {
if (s.equals("name")) {
if(root==null) {
root=new Node(x);
return root; // check if root is empty, if root is empty, just insert into the root position
}
if(x.compareTo(root.val)==-1) root.left=insert(root.left,x,s);
else if (x.compareTo(root.val)==1) root.right=insert(root.right,x,s); //else using recursion to compare insert value to its parentnode
else {root.left=insert(root.left,x,s);} // if the insert value equals to its parentnode, default insert is to its left
return root;
}
else if (s.equals("Birthday")) {
if(root==null) {
root=new Node(x);
return root; // check if root is empty, if root is empty, just insert into the root position
}
if(x.compareTo2(root.val)==-1) root.left=insert(root.left,x,s);
else if (x.compareTo2(root.val)==1) root.right=insert(root.right,x,s); //else using recursion to compare insert value to its parentnode
else {root.left=insert(root.left,x,s);} // if the insert value equals to its parentnode, default insert is to its left
return root;
}
return null;
}
public void delete(PeopleRecord x,String s) {//delete data
countsize--;
root=delete(root,x,s);
}
private Node delete(Node root,PeopleRecord x,String s) {
if(s.equals("name")) {
if(root==null) return null;
if(x.compareTo(root.val)<0) root.left=delete(root.left,x,s);
else if(x.compareTo(root.val)>0) root.right=delete(root.right,x,s);
else {
if(root.left==null) return root.right;
else if(root.right==null) return root.left;
Node minNode=findMin(root.right);
root.val=minNode.val;
root.right=delete(root.right,root.val,s);
}
return root;
}
if(s.equals("Birthday")) {
if(root==null) return null;
if(x.compareTo2(root.val)<0) root.left=delete(root.left,x,s);
else if(x.compareTo2(root.val)>0) root.right=delete(root.right,x,s);
else {
if(root.left==null) return root.right;
else if(root.right==null) return root.left;
Node minNode=findMin(root.right);
root.val=minNode.val;
root.right=delete(root.right,root.val,s);
}
return root;
}
return null;
}
private Node findMin(Node n) {//find the minimum side of the BST
while(n.left!=null) {
n=n.left;
}
return n;
}
public PeopleRecord[] search(String x,String y) {
PeopleRecord[] s=search(root,x,y); // put all the record into array
return s;
}
public PeopleRecord[] searchBirthday(String str) {
PeopleRecord[] s=searchBirthday(root,str);
return s;
}
private PeopleRecord[] searchBirthday(Node root,String s) {
PeopleRecord temp= new PeopleRecord(null,null,null,null,null,null,null,null,null,null,null,null,s); //only consider the given name and family name
PeopleRecord[] ans=new PeopleRecord[countsize];
int c=countsize;
int index=0;
if(root==null) return null;
while(c>=0) {
c--; //loop util all the same record all found
if(root.val.compareTo2(temp)==0) {ans[index]=root.val;index++;root=root.left;} //find all the record equal to temp and add all them into an array
else if (root.val.compareTo2(temp)<0) root=root.right; //if temp is bigger than root serach the right tree
else {root=root.left;}
if(root==null) {
break;
}
}
if(ans[0]==null) return null;
else{
int count2=0;
for(int i=0;i<ans.length;i++) {
if(ans[i]!=null) count2++;
}
PeopleRecord[] FinalAns=new PeopleRecord[count2]; //check if there is anything null in the ans, and add all to another array after deleting null
for(int i=0;i<count2;i++) {
FinalAns[i]=ans[i];
}
return FinalAns;
}
}
private PeopleRecord[] search(Node root,String x,String y) {
PeopleRecord temp= new PeopleRecord(x,y,null,null,null,null,null,null,null,null,null,null,null); //only consider the given name and family name
PeopleRecord[] ans=new PeopleRecord[countsize];
int c=countsize;
int index=0;
if(root==null) return null;
while(c>=0) {
c--; //loop util all the same record all found
if(root.val.compareTo(temp)==0) {ans[index]=root.val;index++;root=root.left;} //find all the record equal to temp and add all them into an array
else if (root.val.compareTo(temp)<0) root=root.right; //if temp is bigger than root serach the right tree
else {root=root.left;}
if(root==null) {
break;
}
}
if(ans[0]==null) return null;
else{
int count2=0;
for(int i=0;i<ans.length;i++) {
if(ans[i]!=null) count2++;
}
PeopleRecord[] FinalAns=new PeopleRecord[count2]; //check if there is anything null in the ans, and add all to another array after deleting null
for(int i=0;i<count2;i++) {
FinalAns[i]=ans[i];
}
return FinalAns;
}
}
public void preOrder(Node n) {
System.out.print("("+n.val.GivenName+","+n.val.FamilyName+")-");
Node Lnode=n.left;
if(Lnode!=null) preOrder(Lnode); // preorder traversal of BST
Node Rnode=n.right;
if(Rnode!=null) preOrder(Rnode);
}
public void preOrderBirthday(Node n) {
System.out.print("("+n.val.GivenName+","+n.val.FamilyName+","+n.val.birthday+")-");
Node Lnode=n.left;
if(Lnode!=null) preOrder(Lnode); // preorder traversal of BST
Node Rnode=n.right;
if(Rnode!=null) preOrder(Rnode);
}
public void getAllData(Node n,ArrayList<PeopleRecord> a){//return a arraylist that contains all data
a.add(n.val);
Node Lnode=n.left;
if(Lnode!=null) getAllData(Lnode,a); // preorder traversal of BST
Node Rnode=n.right;
if(Rnode!=null) getAllData(Rnode,a);
}
private int getHeight(Node root) {
if(root==null) {
return 0;
}
int left=getHeight(root.left);
int right=getHeight(root.right); //use recursion to lefttree and righttree height
if (right>left) {
return right+1; // return the highest tree height
}else {
return left+1;
}
}
public int[] getInfo() {
int[] ans=new int[2];
ans[0]=getHeight(root);//return the number of the node and height
ans[1]=countsize;
return ans;
}
}
class MyHeap<Node>{
ArrayList<Node> HeapList=new ArrayList<>();
public MyHeap() {
}
static class Node{
PeopleRecord val;
Node(PeopleRecord p){
this.val=p; //basic unit for MyHeap
}
}
private int getParent(int index) throws Exception {
if(index==0) throw new IllegalArgumentException("No parent");//get parent index
return (index-1)/2;
}
private int getLChild(int index) {
return index*2+2;//get left child index
}
private int getRChild(int index) {
return index*2+1;//get right child index
}
public void insert(PeopleRecord a,String s) throws Exception{
Node n=new Node(a);
HeapList.add(n);//first add new data the the end
if(s.equals("name")) {
updateUp(HeapList.size()-1);
}
if(s.equals("Birthday")){
updateUpBirthday(HeapList.size()-1);
}// the update the heap
}
public Node remove(String s) {
Node n=HeapList.get(0);
HeapList.set(0, HeapList.get(HeapList.size()-1)); // swap the root with the last node
HeapList.set(HeapList.size()-1, n);
HeapList.remove(HeapList.size()-1); //remove the last node
if(s.equals("name")) {
updateDown(0);
}
if(s.equals("Birthday")) {
updateDownBirthday(0);
} // swiftdown the root
return n;
}
private void updateDown(int i) {
while(getLChild(i)<HeapList.size()) { //if there is child, siftdown
int j=getLChild(i); //assume leftchild is bigger
if(getRChild(i)<HeapList.size()&&HeapList.get(getRChild(i)).val.compareTo(HeapList.get(j).val)>=0) {
j=getRChild(i); // the right one is bigger, than bigger child will be the right one
}
if(HeapList.get(i).val.compareTo(HeapList.get(j).val)>0) break; //achieve maxheap
Node temp=HeapList.get(j);
HeapList.set(j, HeapList.get(i)); // swipe bigger child and parent
HeapList.set(i, temp);
i=j;
}
}
private void updateDownBirthday(int i) {
while(getLChild(i)<HeapList.size()) { //if there is child, siftdown
int j=getLChild(i); //assume leftchild is bigger
if(getRChild(i)<HeapList.size()&&HeapList.get(getRChild(i)).val.compareTo2(HeapList.get(j).val)>=0) {
j=getRChild(i); // the right one is bigger, than bigger child will be the right one
}
if(HeapList.get(i).val.compareTo2(HeapList.get(j).val)>0) break; //achieve maxheap
Node temp=HeapList.get(j);
HeapList.set(j, HeapList.get(i)); // swipe bigger child and parent
HeapList.set(i, temp);
i=j;
}
}
private void updateUp(int i) throws Exception{
while (i>0&&HeapList.get(i).val.compareTo(HeapList.get(getParent(i)).val)>0) {
Node temp=HeapList.get(i);
HeapList.set(i, HeapList.get(getParent(i))); //if child node bigger than parent node, siftup
HeapList.set(getParent(i), temp);
i=getParent(i); // renew the index
}
}
private void updateUpBirthday(int i) throws Exception{
while (i>0&&HeapList.get(i).val.compareTo2(HeapList.get(getParent(i)).val)>0) {
Node temp=HeapList.get(i);
HeapList.set(i, HeapList.get(getParent(i))); //if child node bigger than parent node, siftup
HeapList.set(getParent(i), temp);
i=getParent(i); // renew the index
}
}
}
class QuadraticHashMap<K,V>{
static final int DEFAULT_CAPACITY=16;
static final float LOAD_FACTOR=0.75f;
int size;
int capacity;
int threshold;
String[] keys;
PeopleRecord[] values;
int[] value;
public QuadraticHashMap() {
size=0;
this.capacity=DEFAULT_CAPACITY;
threshold= (int) (DEFAULT_CAPACITY*LOAD_FACTOR);//to check the limit
keys=new String[capacity];
values=new PeopleRecord[capacity];
value=new int[capacity];
}
public int hash(PeopleRecord p) {
String hashName=p.GivenName+p.FamilyName;
return (hashName.hashCode()&Integer.MAX_VALUE)%capacity; // avoid hash result to be negative
}
private int hash(String key) {
return (key.hashCode()&Integer.MAX_VALUE)%capacity;//get the hashvalue
}
private void enlarge() {
this.capacity*=2;
this.threshold=(int) (capacity*LOAD_FACTOR); // if the key reach the threshold, map enlarge (x2)
String[] newKeys=new String[capacity];
PeopleRecord[] newValues=new PeopleRecord[capacity];
int[] newValue=new int[capacity];
for(int i=0;i<keys.length;i++) { //copy all the old keys, values into the new array
newKeys[i]=keys[i];
}
for(int i=0;i<values.length;i++) {
newValues[i]=values[i];
}
for(int i=0;i<value.length;i++) {
newValue[i]=value[i];
}
keys=newKeys;
values=newValues;
value=newValue;
}
public void put(String s) {
if(search(s)==true) {
for(int i=0;i<keys.length;i++) {
if(keys[i]!=null) {
if(keys[i].equals(s)) { value[i]++;break;} //put the data in the map
}
}
}
else {
int hashValue=hash(s);
int site=hashValue;
int quadraticIndex=1;
if(size>=threshold) enlarge();
while(keys[site]!=null) {
site=(site+quadraticIndex*quadraticIndex++)%capacity;//if occupied, the use quadratic method to find an another available place
}
keys[site]=s;
value[site]=1;
size++;
return;
}
}
public void put(PeopleRecord val){
int hashValue = hash(val);
int site=hashValue;
int quadraticIndex=1;
if(size>=threshold) enlarge();// enlarge the map if it's size reaches the threshold
while(keys[site]!=null) {
site=(site+quadraticIndex*quadraticIndex++)%capacity; //hash until it find an empty space for it
}
keys[site] = val.GivenName+val.FamilyName; //store the data into array
values[site] = val;
size++;
return;}
public String[] process(int count) {
String[] newKeys=new String[keys.length];
int[] newValue=new int[value.length];
int num=count;
for(int i=0;i<num;i++) {
if(count==0) break;
int maxi=-1;
int index=-1;
for(int j=0;j<value.length;j++) {
if(value[j]>maxi&&value[j]!=-1) {
maxi=value[j]; //record the highest frequent word, and index
index=j;
}
}
for(int k=0;k<newValue.length;k++) {
if(newValue[k]==0) {
newValue[k]=maxi;
newKeys[k]=keys[index];//add most frequent word into array
count--;
break;
}
}
keys[index]=null; //after put most frequent word into array, manually delete it
value[index]=-1;
}
return newKeys;
}
public PeopleRecord[] get(String x,String y) {
ArrayList<PeopleRecord> ans=new ArrayList<>();
if(search(x,y)==true) {//check whether key exist
for(int i=0;i<keys.length;i++) {
if(keys[i]!=null) {
if(keys[i].equals(x+y)) ans.add(values[i]); // if key exist,add the value to an new arraylist
}
}
}
PeopleRecord[] FinalAns=new PeopleRecord[ans.size()];
for(int i=0;i<ans.size();i++) { //change the data type
FinalAns[i]=ans.get(i);
}
return FinalAns;
}
public boolean search(String s) {
for(int i=0;i<keys.length;i++) {
if(keys[i]!=null) {
if(keys[i].equals(s)) return true;
}
}
return false;
}
public boolean search(String x,String y) {
for(int i=0;i<keys.length;i++) { //loop the keys array to find out whether the key exists
if(keys[i]!=null) {
if(keys[i].equals(x+y)) return true;
}
}
return false;
}
public void remove(String x,String y) {
String key=x+y;
if (!search(x,y)) return; //search for key
int site=hash(key), quadraticIndex=1;
while (!key.equals(keys[site])) {
site=(site +quadraticIndex*quadraticIndex++)%capacity; //search for index
}
keys[site]=null; //manually remove the key and value after first find it, in order to remove all the record
values[site]=null;
for(int i=site;i<keys.length-1;i++) {
keys[site]=keys[site+1]; // the gaps in the map are filled by the data behind it
values[site]=values[site+1];
}
size--;
}}
| D-K-Deng/DataProcessing_Practice | DatabaseProcessing.java |
247,652 | package group_5;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import java.lang.*;
import physics.*;
class Flipper extends Gizmo {
//extra fields for flippers only
//these booleans specify whether the flipper's pivot corner is
// offset from (x, y) in the right and downward directions
private boolean pivotRight;
private boolean pivotDown;
//leftflippers pivot counterclockwise - tell them apart
private boolean leftFlipper;
//booleans to tell if the flipper is moving and which way
private boolean forwardMotion;
private boolean backwardMotion;
//angle of flipper (0-360)
private double flipperAngle;
//max and min angles for flipper (0-360)
private double startAngle;
private double flippedAngle;
//constructors
public Flipper(GameBoard gb, String name, int xL, int yL,
boolean left) {
this.gb = gb;
this.x = xL*GameBoard.PixelsPerL;
this.y = yL*GameBoard.PixelsPerL;
this.width = 2;
this.height = 2;
this.name = name;
this.refCoef = 0.95;
this.leftFlipper = left;
this.forwardMotion = false;
this.backwardMotion = false;
this.flipperAngle = 270.0;
this.startAngle = 270.0;
if (leftFlipper) {
flippedAngle = 0.0;
pivotRight = false;
pivotDown = false;
this.gt = GizmoType.LeftFlipper;
} else {
flippedAngle = 180.0;
pivotRight = true;
pivotDown = false;
this.gt = GizmoType.RightFlipper;
}
}
/**
*@modifies this
*@effects change the corner of this flipper to be next of the four
*bounding box corners in a clockwise rotation
*/
public void rotate() {
//define offsets from (x, y) in response to current pivot state
if (!pivotRight && !pivotDown) {
pivotRight = true;
} else if (pivotRight && !pivotDown) {
pivotDown = true;
} else if (pivotRight && pivotDown) {
pivotRight = false;
} else if (!pivotRight && pivotDown) {
pivotDown = false;
}
//rotate all defining angles clockwise 90 degrees
flipperAngle += 270.0;
flipperAngle %= 360.0;
startAngle += 270.0;
startAngle %= 360.0;
flippedAngle += 270.0;
flippedAngle %= 360.0;
}
@Override
public void enlarge() {
// TODO Auto-generated method stub
}
public void startAction() {
//flippers only have one action - ignore action variable
if (!forwardMotion && !backwardMotion
&& (flipperAngle == startAngle)) {
//if not moving, and in start state, start forward motion
gb.addToActiveList(this);
forwardMotion = true;
} else if (!forwardMotion && !backwardMotion
&& (flipperAngle == flippedAngle)) {
//if not moving, and in flipped state, start backward motion
gb.addToActiveList(this);
backwardMotion = true;
} else if (forwardMotion) {
//if moving forward, reverse direction
//don't need to add to active list, already there
forwardMotion = false;
backwardMotion = true;
}
//if moving backward, do nothing
}
public void action() {
// FLIPPERANGVEL deg/sec * 0.001 sec/msec * MSECPERTICK msec/tick
// * 1 tick = degreesToFlip in one tick
double degreesToFlip = GameBoard.FLIPPERANGVEL * GameBoard.MSECPERTICK * 0.001;
if (degreesToFlip != 90.0)
degreesToFlip = degreesToFlip % 90;
if (forwardMotion) {
if (leftFlipper) {
//left flipper forwards = counterclockwise
flipperAngle = (flipperAngle + degreesToFlip + 360) % 360;
//if becomes more than or equal to flipped, set to flipped state
//and end (remove active, set bool to false)
if (anglediff(startAngle, flipperAngle) >= 90) {
flipperAngle = flippedAngle;
forwardMotion = false;
gb.removeFromActiveList(this);
}
} else {
//right flipper forwards = clockwise
flipperAngle = (flipperAngle - degreesToFlip + 360) % 360;
//if becomes more than or equal to flipped, set to flipped state
//and end (remove active, set bool to false)
if (anglediff(startAngle, flipperAngle) <= -90) {
flipperAngle = flippedAngle;
forwardMotion = false;
gb.removeFromActiveList(this);
}
}
} else if (backwardMotion) {
if (leftFlipper) {
//left flipper backwards = clockwise
flipperAngle = (flipperAngle - degreesToFlip + 360) % 360;
//if becomes less than or equal to unflipped, set to unflipped
//state and end (remove active, set bool to false)
if (anglediff(startAngle, flipperAngle) <= 0) {
flipperAngle = startAngle;
backwardMotion = false;
gb.removeFromActiveList(this);
}
} else {
//right flipper backwards = counterclockwise
flipperAngle = (flipperAngle + degreesToFlip + 360) % 360;
//if becomes less than or equal to unflipped, set to unflipped
//state and end (remove active, set bool to false)
if (anglediff(startAngle, flipperAngle) >= 0) {
flipperAngle = startAngle;
backwardMotion = false;
gb.removeFromActiveList(this);
}
}
}
}
private double anglediff(double a, double b) {
a %= 360;
b %= 360;
if ((b - a) < -180) { b += 360; }
else if ((b - a) > 180) { a += 360; }
return b - a;
}
public String getSaveString() {
String ss = "";
if (leftFlipper) {
ss += "LeftFlipper ";
} else {
ss += "RightFlipper ";
}
ss += name + " " + (x/GameBoard.PixelsPerL) + " " + (y/GameBoard.PixelsPerL);
int rotatecount = 0;
if (!pivotRight && !pivotDown) {
rotatecount = 0;
} else if (pivotRight && !pivotDown) {
rotatecount = 1;
} else if (pivotRight && pivotDown) {
rotatecount = 2;
} else if (!pivotRight && pivotDown) {
rotatecount = 3;
}
if (!leftFlipper) {
//if rightflipper, subtract one from rotatecount and mod 4
//(rightflipper pivot starts in topright, not topleft)
rotatecount += 3;
rotatecount %= 4;
}
for (int i = 0; i < rotatecount; i++) {
ss += "\r\nRotate " + name;
}
return ss;
}
public double getAngularVelocity() {
//NEGATIVE OF INTERNAL FLIPPER STATE!
//differences in our rotation definition and physics API
if ((leftFlipper && forwardMotion)
|| (!leftFlipper && backwardMotion)) {
return -1*Math.toRadians(GameBoard.FLIPPERANGVEL);
} else if ((leftFlipper && backwardMotion)
|| (!leftFlipper && forwardMotion)) {
return Math.toRadians(GameBoard.FLIPPERANGVEL);
}
return 0;
}
public Point2D.Double getPivot() {
double radius = GameBoard.PixelsPerL*0.25;
double pivotx, pivoty;
if (pivotRight) {
pivotx = x + GameBoard.PixelsPerL*width - radius;
} else {
pivotx = x + radius;
}
if (pivotDown) {
pivoty = y + GameBoard.PixelsPerL*height - radius;
} else {
pivoty = y + radius;
}
return new Point2D.Double(pivotx, pivoty);
}
/**
*@return a Point2D.Double of the non-pivot center of this flipper,
*in its start position (not turned at all)
*/
private Point2D.Double getStartNonPivot() {
double radiusdiff = GameBoard.PixelsPerL*1.5;
Point2D.Double pivot = getPivot();
//find nonpivot center by extending in direction of startAngle by
//appropriate radius difference
double nonpivotx = pivot.x
+ radiusdiff*Math.cos(Math.toRadians(startAngle));
double nonpivoty = pivot.y
- radiusdiff*Math.sin(Math.toRadians(startAngle));
return new Point2D.Double(nonpivotx, nonpivoty);
}
private List getShapes() {
List shapes = new ArrayList();
double radius = GameBoard.PixelsPerL*0.25;
Point2D.Double pivot = getPivot();
Point2D.Double nonpivot = getStartNonPivot();
double x1 = pivot.x + radius*Math.cos(Math.toRadians(startAngle+90));
double y1 = pivot.y - radius*Math.sin(Math.toRadians(startAngle+90));
double x2 = pivot.x + radius*Math.cos(Math.toRadians(startAngle-90));
double y2 = pivot.y - radius*Math.sin(Math.toRadians(startAngle-90));
double x3 = nonpivot.x + radius*Math.cos(Math.toRadians(startAngle-90));
double y3 = nonpivot.y - radius*Math.sin(Math.toRadians(startAngle-90));
double x4 = nonpivot.x + radius*Math.cos(Math.toRadians(startAngle+90));
double y4 = nonpivot.y - radius*Math.sin(Math.toRadians(startAngle+90));
double[] xs = {x1, x2, x3, x4};
double[] ys = {y1, y2, y3, y4};
//min x should also be min y!!! we are looking at unrotated state
//x1 == x2, x3 == x4, y1 == y2, y3 == y4
Arrays.sort(xs);
Arrays.sort(ys);
//center rectangle
Shape rect = new Rectangle2D.Double(xs[0], ys[0],
xs[2]-xs[0],
ys[2]-ys[0]);
//pivot ellipse
Shape pivel = new Ellipse2D.Double(pivot.x - radius,
pivot.y - radius,
2*radius, 2*radius);
//extreme ellipse
Shape nonpivel = new Ellipse2D.Double(nonpivot.x - radius,
nonpivot.y - radius,
2*radius, 2*radius);
//create a transformer to rotate shapes around pivot point by
//startAngle - flipperAngle
double rotang = Math.toRadians(startAngle - flipperAngle);
AffineTransform rotator =
AffineTransform.getRotateInstance(rotang, pivot.x, pivot.y);
//apply rotation by transformer to each shape
rect = rotator.createTransformedShape(rect);
pivel = rotator.createTransformedShape(pivel);
nonpivel = rotator.createTransformedShape(nonpivel);
//add rotated shapes to List and return
shapes.add(rect);
shapes.add(pivel);
shapes.add(nonpivel);
return shapes;
}
public boolean containsPoint(Point p) {
List shapes = getShapes();
//use java.awt.Shape contains(Point)
for (int i = 0; i < shapes.size(); i++) {
Shape tempshape = (Shape)shapes.get(i);
//if any of the shapes contain the point, return true
if (tempshape.contains(p)) {
return true;
}
}
return false;
}
public List getBoundaryShape(Ball mover) {
List shapes = new ArrayList();
double radius = GameBoard.PixelsPerL*0.25;
Point2D.Double pivot = getPivot();
Point2D.Double nonpivot = getStartNonPivot();
double x1 = pivot.x + radius*Math.cos(Math.toRadians(startAngle+90));
double y1 = pivot.y - radius*Math.sin(Math.toRadians(startAngle+90));
double x2 = pivot.x + radius*Math.cos(Math.toRadians(startAngle-90));
double y2 = pivot.y - radius*Math.sin(Math.toRadians(startAngle-90));
double x3 = nonpivot.x + radius*Math.cos(Math.toRadians(startAngle-90));
double y3 = nonpivot.y - radius*Math.sin(Math.toRadians(startAngle-90));
double x4 = nonpivot.x + radius*Math.cos(Math.toRadians(startAngle+90));
double y4 = nonpivot.y - radius*Math.sin(Math.toRadians(startAngle+90));
//create Shape objects (these are rotatable by AffineTransform)
Point2D.Double pt1 = new Point2D.Double(x1, y1);
Point2D.Double pt2 = new Point2D.Double(x2, y2);
Point2D.Double pt3 = new Point2D.Double(x3, y3);
Point2D.Double pt4 = new Point2D.Double(x4, y4);
Point2D.Double nonpiv = new Point2D.Double(nonpivot.x, nonpivot.y);
//create a transformer to rotate shapes around pivot point by
//startAngle - flipperAngle
double rotang = Math.toRadians(startAngle - flipperAngle);
AffineTransform rotator =
AffineTransform.getRotateInstance(rotang, pivot.x, pivot.y);
//apply rotation by transformer to each shape
pt1 = (Point2D.Double)rotator.transform((Point2D)pt1, (Point2D)pt1);
pt2 = (Point2D.Double)rotator.transform((Point2D)pt2, (Point2D)pt2);
pt3 = (Point2D.Double)rotator.transform((Point2D)pt3, (Point2D)pt3);
pt4 = (Point2D.Double)rotator.transform((Point2D)pt4, (Point2D)pt4);
nonpiv = (Point2D.Double)rotator.transform((Point2D)nonpiv,
(Point2D)nonpiv);
//now rebuild physics shapes from rotated shapes
//center rectangle, defined by two lines (P1->P4, P2->P3)
shapes.add(new LineSegment(pt1.x, pt1.y, pt4.x, pt4.y));
shapes.add(new LineSegment(pt2.x, pt2.y, pt3.x, pt3.y));
//4 zero-radius circles - if needed
shapes.add(new Circle(pt1, 0));
shapes.add(new Circle(pt2, 0));
shapes.add(new Circle(pt3, 0));
shapes.add(new Circle(pt4, 0));
//pivot ellipse - note: pivot hasn't moved, just use original
shapes.add(new Circle(pivot, radius));
//extreme ellipse
shapes.add(new Circle(nonpiv, radius));
//shapes.add(new Circle(((Line2D.Double)pivotline).getP2(), radius));
return shapes;
}
public void paint(Graphics2D g) {
g.setColor(Color.YELLOW);
java.util.List shapes = getShapes();
for (int i = 0; i < shapes.size(); i++) {
Shape shapetodraw = (Shape)shapes.get(i);
//paint each shape onto the board
g.fill(shapetodraw);
}
Point2D.Double pivot = getPivot();
g.setColor(Color.red);
g.fill(new Ellipse2D.Double(pivot.x - 2, pivot.y - 2, 4, 4));
}
public void fire(Ball firer) {
gb.addScore(15);
super.fire(firer);
}
} | MartyPang/GizmoBallGame | src/group_5/Flipper.java |
247,653 | package dt03;
import java.util.Arrays;
import java.util.Stack;
// template <typename T, class E>
// class MyClass{
// }
//top, push, pop, empty
public class MyStack {
public static void main(String[] args) throws Exception {
Stack<String> s1 = new Stack<String>();
s1.push("Hello");
s1.push("Kitty");
System.out.println("Top: " + s1.peek());
System.out.println("Size: " + s1.size());
S s = new S();
s.push(s.push(3)+1);
System.out.println(s.push(5));
System.out.println("");
System.out.print(s.toString());
s.pop();
s.pop();
s.pop();
s.pop();
}
}
class S {
private int[] arr = null;
private int size = 0; //push,pop
private int capacity = 0;
private final int limit = 100;
public S() {
arr = new int[limit];
capacity = limit;
}
private void enlarge() {
int[] temp = arr;
// 创建一个大数组,将原数组内容拷贝过去
// arr = Arrays.copyOf(temp, temp.length+limit); //创建加大拷贝
arr = new int [temp.length + limit];
for(int i =0; i< temp.length; i++) {
arr[i] = temp[i];
}
capacity = arr.length;
temp = null;
}
public int push(int elem) {
if(size == capacity)
enlarge();
arr[size++] = elem;
return elem;
}
public int pop() throws Exception {
if(size == 0)
throw new Exception("No element in stack!");
int temp = arr[size-1];
size --;
return temp;
}
public String toString() {
String s = "";
for(int i = size-1; i>0; i--)
s = s + String.valueOf(arr[i]) +"\n";
s += arr[0];
return s;
}
} | chivalryq/Lessons4JavaSE | src/dt03/MyStack.java |
247,654 | package Graph;
import java.util.ArrayList;
/**
* This is an implementation of a Graph.Graph ADT using an ArrayList.
* A graph is a freeform data structure made of vertices connected by edges.
* A graph, G, can be defined as G = (V, E). Where V(G) is a finite, nonempty set of vertieces and E(G) is a set of edges
* written as pairs of vertices.
* @author Faycal Kilali, Dylan Kim
* @implSpec This is implemented as a unweighted graph (hence the boolean matrix). However, it can be easily adapted to a weighted graph by changing the type of the matrix and appropriately assigning weights.
* @implNote [row][column].
* @param <T> the parameterized type
*/
public class Graph<T> implements GraphADT<T> {
private boolean[][] matrix;
private int size;
private final int DEF_CAP = 60;
private int capacity = DEF_CAP;
private T[] referenceMatrix;
private boolean[] arrayOfMarks;
public Graph(){
matrix = new boolean[DEF_CAP][DEF_CAP];
referenceMatrix = (T[]) new Object[DEF_CAP];
size = 0;
arrayOfMarks = new boolean[DEF_CAP];
}
/**
* Checks whether the graph is devoid of nodes or not.
* Time Complexity: 1
* @return true if the graph is devoid of nodes, false otherwise.
*/
@Override
public boolean isEmpty() {
if (size == 0){
return true;
}
return false;
}
/**
* Checks whether the graph is at capacity
* Time Complexity: O(1)
* @return true if graph is at capacity, false otherwise
*/
@Override
public boolean isFull() {
if (size == capacity){
return true;
}
return false;
}
/**
* Adds the Vertex to the matrix
* Time Complexity: (n+1)
* @implSpec the vertex must be
* @param vertex
*/
@Override
public void addVertex(T vertex) {
if (size != capacity){
referenceMatrix[size] = vertex;
size++;
}
else{
enLarge();
referenceMatrix[size] = vertex;
size++;
}
// If we were to use a remove method
//for (int i = 0; i < referenceMatrix.length; i++){
//}
}
/**
* Enlarges the underlying arrays
* Time Complexity:
*/
private void enLarge(){
capacity = capacity * 2;
boolean[][] largerMatrix = new boolean[capacity][capacity];
T[] largerReferenceMatrix = (T[]) new Object[capacity];
boolean[] largerArrayOfMarks = new boolean[capacity];
System.arraycopy(matrix, 0, largerMatrix, 0, matrix.length);
System.arraycopy(referenceMatrix, 0, largerReferenceMatrix, 0, size);
System.arraycopy(arrayOfMarks, 0, largerArrayOfMarks, 0, arrayOfMarks.length);
matrix = largerMatrix;
referenceMatrix = largerReferenceMatrix;
arrayOfMarks = largerArrayOfMarks;
}
@Override
public boolean hasVertex(T vertex) {
for (int i = 0; i < size; i++) {
if (referenceMatrix[i] != null && referenceMatrix[i].equals(vertex)) {
return true;
}
}
return false;
}
/**
* Creates an edge between two vertices.
* @implSpec the weight of any two vertices is 1 if the graph is unweighted.
* @implNote The weights are strictly integers, for now.
* @param fromVertex the direction of the edge coming from this vertex
* @param toVertex the edge coming towards this vertex
*/
@Override
public void addEdge(T fromVertex, T toVertex) {
int fromVertexIndex = -1;
int toVertexIndex = -1;
// Find indices of the vertices in the referenceMatrix
for (int i = 0; i < size; i++) {
if (referenceMatrix[i] != null && referenceMatrix[i].equals(fromVertex)) {
fromVertexIndex = i;
} else if (referenceMatrix[i] != null && referenceMatrix[i].equals(toVertex)) {
toVertexIndex = i;
}
}
// If either vertex is not found, return
if (fromVertexIndex == -1 || toVertexIndex == -1) {
return;
}
// Set connections in both directions for an undirected graph
matrix[fromVertexIndex][toVertexIndex] = true;
matrix[toVertexIndex][fromVertexIndex] = true;
}
// Pre-resolution
// /**
// * Creates an edge between two vertices.
// * @implSpec the weight of any two vertices is 1 if the graph is unweighted.
// * @implNote The weights are strictly integers, for now.
// * @param fromVertex the direction of the edge coming from this vertex
// * @param toVertex the edge coming towards this vertex
// */
// @Override
// public void addEdge(T fromVertex, T toVertex) {
// int fromVertexIndex = 0;
// int toVertexIndex = 0;
// boolean foundFromVertex = false;
// boolean foundToVertex = false;
//
// for (int i = 0; i < size && !(foundFromVertex || foundToVertex); i++) {
// if (referenceMatrix[i] != null && referenceMatrix[i].equals(fromVertex)) {
// fromVertexIndex = i;
// foundFromVertex = true;
// } else if (referenceMatrix[i] != null && referenceMatrix[i].equals(toVertex)) {
// toVertexIndex = i;
// foundToVertex = true;
// }
// }
//
// matrix[fromVertexIndex][toVertexIndex] = true;
// }
/**
* Retrieves the connected vertices to parameterized vertex
* @param vertex the root vertex to consider
* @return the connected vertices to the root vertex
*/
@Override
public ArrayList<T> getToVertices(T vertex) {
ArrayList<T> linkedVertices = new ArrayList<T>();
int vertexIndex = -1;
// Find the index of the vertex in the referenceMatrix
for (int i = 0; i < size; i++) {
if (referenceMatrix[i] != null && referenceMatrix[i].equals(vertex)) {
vertexIndex = i;
break;
}
}
// If the vertex is not found, return an empty list
if (vertexIndex == -1) {
return linkedVertices;
}
// Check for connected vertices based on the matrix
for (int i = 0; i < size; i++) {
// Add the connected vertex if the matrix indicates a connection
if (matrix[i][vertexIndex] && referenceMatrix[i] != null) {
linkedVertices.add(referenceMatrix[i]);
}
}
return linkedVertices;
}
/**
* Marks a vertex as previously traversed through
* @param vertex the vertex to mark
*/
@Override
public void markVertex(T vertex) {
for(int i=0;i<size;i++){
if(referenceMatrix[i].equals(vertex)){
arrayOfMarks[i] = true;
return;
}
}
}
/**
* Clears all the marks on the nodes
*/
@Override
public void clearMarks() {
for(int i=0; i<size;i++){
arrayOfMarks[i] = false;
}
}
/**
* Retrieves the state of whether a vertex has been traversed through or not.
* @param vertex the vertex to check if it has been traversed through
* @return true if previously traversed through, false otherwise
*/
@Override
public boolean isMarked(T vertex) {
for (int i = 0; i < size; i++){
if (referenceMatrix[i].equals(vertex)){
return arrayOfMarks[i];
}
}
return false;
}
/**
* Retrieves a single unmarked vertex.
* Can be used to check if a particular graph is disjoint, among other things.
* @return an unmarked vertex
*/
@Override
public T getUnmarked() {
for(int i=0;i<size;i++){
if(!arrayOfMarks[i]){
return referenceMatrix[i];
}
}
return null;
}
/**
* Gets the edges in the Graph.Graph E(G).
*/
public ArrayList<Edge<T>> getEdges() {
ArrayList<Edge<T>> edges = new ArrayList<Edge<T>>();
// FromVertex will be the reference matrix index at that position
// ToVertex will be the reference matrix index at the end of the edge
// Which, for our boolean matrix, will be [fromVertex][toVertex]
for (int row = 0; row < size; row++){
for (int column = 0; column < size; column++){
if (matrix[row][column] == true){
edges.add(new Edge<T>(referenceMatrix[row], referenceMatrix[column]));
}
}
}
return edges;
}
/**
* @implSpec To be implemented
* @return
*/
@Override
public String toString() {
return super.toString();
}
public T getVertex(int i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("Index out of bounds: " + i);
}
return referenceMatrix[i];
}
/**
* Method that takes the underlying Graph.Graph implementation
* and derives an object of the type 'People' that is a
* wrapper around the set of Vertices stored by the
* underlying Graph.Graph.
* <p>
* Basically just 'getVertices' but into a class rather than
* an ArrayList<T>.
*/
// @Override
// public People<T> getPeople() {
// People<T> people = new People<T>();
// for (int referenceIndex =0; referenceIndex < size; referenceIndex++){
// people.addNewPerson(referenceMatrix[referenceIndex]);
// }
// return people;
// }
/**
* Method that takes the underlying Graph.Graph implementation
* and derives an object of the type 'Bonds' that is a
* wrapper around the set of Edges stored by the
* underlying Graph.Graph.
* <p>
* Basically just 'getEdges' but into a class rather than
* an ArrayList<ArrayList<T>>. A trivial Graph.Edge class that
* just holds two objects of type T may be helpful, but
* that's up to you.
*/
// @Override
// public Bonds<T> getBonds() {
// Bonds<T> bonds = new Bonds<T>();
//
// // FromVertex will be the reference matrix index at that position
// // ToVertex will be the reference matrix index at the end of the edge
// // Which, for our boolean matrix, will be [fromVertex][toVertex]
//
// for (int row = 0; row < size; row++){
// for (int column = 0; column < size; column++){
// if (matrix[row][column] == true){
// bonds.addBond(referenceMatrix[row], referenceMatrix[column]);
// }
// }
// }
// return bonds;
// }
/**
* Method that takes a People object and uses it to overwrite
* the information represented by the underlying Graph.Graph object.
* <p>
* This should represent a wholesale replacement of the Vertices
* in the underlying Graph.Graph; do not merge the existing set of
* Vertices with the new People object.
* <p>
* This provides a convenient means of initializing our Graph.Graph
* all at once instead of adding one Vertice at a time.
* <p>
* You should perform some amount of validating the Vertices
* described in People to ensure that the existing Edges in
* the underlying Graph.Graph are not invalidated by the change in
* the set of Vertices.
*
* @param in
*/
// @Override
// public void updatePeople(People<T> in) {
// // Replace all our vertices with the parameterized people object
// // We must also check that the parameterized type does not invalidate the change in the set of vertices.
//
// // TRIVIAL CASE VALIDATION:
// if (in.getPeople().size() != size){
// throw new UnsupportedOperationException("Trivially incompatible with current edges, given that each node has an edge to itself");
// }
//
// // TODO: validate the case where sizes differ.
// //T[] tempReferenceMatrix = (T[])new Object[capacity];
// //for (int i = 0; i < in.getPeople().size(); i++){
// // tempReferenceMatrix[i] = in.getPeople().get(i);
// //}
//
//
// }
/**
* Method that takes a Bonds object and uses it to overwrite
* the information represented by the underlying Graph.Graph object.
* <p>
* This should represent a wholesale replacement of the Edges
* in the underlying Graph.Graph; do not merge the existing set of
* Edges with the new People object.
* <p>
* This provides a convenient means of initializing our Graph.Graph
* all at once instead of adding one Graph.Edge at a time.
* <p>
* You should perform some amount of validating the Edges
* described in Bonds to ensure that the appropriate Vertices
* exists in the underlying Graph.Graph for these to work.
*
* @param in
*/
// @Override
// public void updateBonds(Bonds<T> in) {
//
//
// // TRIVIAL CASE VALIDATION:
// if (in.getFromVertex().size() != size || in.getToVertex().size() != size){
// throw new UnsupportedOperationException("Trivially incompatible with current edges, given that each node has an edge to itself");
// }
//
// // TODO: validate the case where sizes differ.
// //T[] tempReferenceMatrix = (T[])new Object[capacity];
// //for (int i = 0; i < in.getPeople().size(); i++){
// // tempReferenceMatrix[i] = in.getPeople().get(i);
// //}
//
// }
}
| faycalki/robots-facility | Graph/Graph.java |
247,655 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.util.Collection;
import java.util.NoSuchElementException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
final int maxN = (int) 2e5 + 5;
long[] count;
EzIntArrayList[] adj;
int[] a;
ArrayList<Integer>[] nodes;
int[] timer;
int[] valid;
int[] Q;
int bfs(int source, int curTimer) {
int beg = 0;
int end = 0;
Q[end++] = source;
timer[source] = curTimer;
int ans = 0;
while (beg < end) {
int node = Q[beg++];
ans++;
for (int i = 0; i < adj[node].size(); i++) {
int neighbor = adj[node].get(i);
if (timer[neighbor] != curTimer && valid[a[neighbor]] == curTimer) {
timer[neighbor] = curTimer;
Q[end++] = neighbor;
}
}
}
return ans;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
adj = new EzIntArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new EzIntArrayList();
}
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
nodes = new ArrayList[maxN];
for (int i = 0; i < n; i++) {
if (nodes[a[i]] == null) nodes[a[i]] = new ArrayList<>();
nodes[a[i]].add(i);
}
count = new long[maxN];
timer = new int[n];
Q = new int[n];
valid = new int[maxN];
for (int i = maxN - 1; i >= 1; i--) {
int curTimer = i;
for (int j = i; j < maxN; j += i) valid[j] = curTimer;
for (int j = i; j < maxN; j += i)
if (nodes[j] != null) {
for (int start : nodes[j]) {
if (timer[start] == curTimer) continue;
long cnt = bfs(start, curTimer);
count[i] += (cnt * (cnt + 1)) >> 1;
}
}
for (int j = i + i; j < maxN; j += i) {
count[i] -= count[j];
}
}
for (int i = 0; i < maxN; i++) {
if (count[i] > 0) out.println(i + " " + count[i]);
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
}
class EzIntArrayList {
private static final int DEFAULT_CAPACITY = 10;
private static final double ENLARGE_SCALE = 2.0;
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
private int[] array;
private int size;
public EzIntArrayList() {
this(DEFAULT_CAPACITY);
}
public EzIntArrayList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
array = new int[capacity];
size = 0;
}
public EzIntArrayList(int[] srcArray) {
size = srcArray.length;
array = new int[size];
System.arraycopy(srcArray, 0, array, 0, size);
}
public EzIntArrayList(Collection<Integer> javaCollection) {
size = javaCollection.size();
array = new int[size];
int i = 0;
for (int element : javaCollection) {
array[i++] = element;
}
}
public int size() {
return size;
}
public boolean add(int element) {
if (size == array.length) {
enlarge();
}
array[size++] = element;
return true;
}
public int get(int index) {
return array[index];
}
private void enlarge() {
int newSize = Math.max(size + 1, (int) (size * ENLARGE_SCALE));
int[] newArray = new int[newSize];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
} | ishandutta2007/codeforces-m | mmaxio/normal/990/G.java |
247,656 | package com.example.administrator.moblieplatform;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* 地图类
*/
public class MapView extends WebView {
/**
* 地图是否已经加载,true为加载
*/
public boolean hasInit = false;
private static String TAG = "MapView";
private MapListener mapListener;
/**
* MapView使用方法
* <包名.MapView
* android:id="@+id/mapView"
* android:layout_width="match_parent"
* android:layout_height="match_parent">
* </包名.MapView>
*
* @param context
*/
public MapView(Context context) {
super(context);
}
public MapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MapView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MapView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public MapView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing) {
super(context, attrs, defStyleAttr, privateBrowsing);
}
public void setListener(MapListener mapListener) {
this.mapListener = mapListener;
init();
}
/**
* 初始化,必须执行此方法后,方可执行其他操作
*/
public void init() {
WebSettings webSettings = getSettings();
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
webSettings.setUseWideViewPort(true);// 可任意比例缩放
webSettings.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
webSettings.setJavaScriptEnabled(true);
addJavascriptInterface(new JsInteration(), "Android");
webSettings.setAppCacheEnabled(true);//缓存
webSettings.setDomStorageEnabled(true);
webSettings.setSupportMultipleWindows(true);// 新加
webSettings.setUseWideViewPort(true); // 关键点
webSettings.setAllowFileAccess(true); // 允许访问文件
webSettings.setSupportZoom(true); // 支持缩放
setDrawingCacheEnabled(true);
buildDrawingCache();
buildLayer();
setLayerType(View.LAYER_TYPE_HARDWARE, null);
setWebViewClient(new MWebView());
loadUrl("file:///android_asset/index.html");
}
/**
* 放大地图
*/
public void enlarge() {
loadMethod("zoomIn()");
}
/**
* 缩小地图
*/
public void narrow() {
loadMethod("zoomOut()");
}
/**
* 设置地图中心
*
* @param lat 纬度
* @param lng 经度
*/
public void setCenter(double lat, double lng) {
loadMethod("setCenter(" + lat + "," + lng + ")");
}
/**
* 根据坐标范围设置地图中心
*
* @param latMin 最小纬度
* @param lngMin 最小经度
* @param latMax 最大纬度
* @param lngMax 最大经度
*/
public void setView(double latMin, double lngMin, double latMax, double lngMax) {
loadMethod("setView(" + latMin + "," + lngMin + "," + latMax + "," + lngMax + ")");
}
/**
* 设置地图缩放等级
*
* @param level 缩放等级
*/
public void setZoom(Integer level) {
loadMethod("setZoom(" + level + ")");
}
/**
* 添加高亮显示,会自动覆盖上一个高亮点
*
* @param lat 纬度
* @param lng 经度
*/
public void addHighlight(Double lat, Double lng) {
loadMethod("addHighlight(" + lat + "," + lng + ")");
}
/**
* 清除高亮显示
*/
public void clearHighlight() {
loadMethod("clearHighlight()");
}
/**
* 开启/关闭点击地图弹出经纬度
*
* @param isShow true开启,false关闭
*/
public void setShowLatLng(boolean isShow) {
if (isShow) {
loadMethod("showLatLng()");
} else {
loadMethod("clearShowLatLng()");
}
}
/**
* 添加GeoJson到地图
*
* @param geoJson "{'type': 'FeatureCollection','features': [{'type': 'Feature','properties': {},'geometry': {'type': 'Point','coordinates': [35.5078125,69.53451763078358]}},{'type': 'Feature','properties': {},'geometry': {'type': 'Point','coordinates': [20.7421875,48.22467264956519]}}]}"
*/
public void addGeoJson(String geoJson) {
loadMethod("addGeoJson(" + geoJson + ")");
}
/**
* 移除geoJson图层
*/
public void removeGeoJson() {
loadMethod("removeGeoJson()");
}
/**
* 添加带图标点
*
* @param lat 经度
* @param lng 纬度
* @param icon 图标名称/test.png,图标必须放在assets/icon目录下,分辨率为48*48,图标中心与坐标对齐
*/
public void addIcon(double lat, double lng, String icon) {
loadMethod("addIcon(" + lat + "," + lng + ",\"" + icon + "\")");
}
/**
* 移除全部带图标点
*/
public void removeIcons() {
loadMethod("removeIcons()");
}
/**
* 添加WMS图层
*
* @param url 服务地址
* @param layers 图层名称
* @param format 调用图片格式
* @param name 自定义图层名称,方便关闭图层,最好使用唯一值
* @param minZoom 最小缩放等级
* @param maxZoom 最大缩放等级 minZoom<maxZoom
*/
public void addWMSLayer(String url, String layers, String format, String name, Integer minZoom, Integer maxZoom) {
loadMethod("addWMSLayer(\"" + url + "\",\"" + layers + "\",\"" + format + "\",\"" + name + "\"," + minZoom + "," + maxZoom + ")");
}
/**
* 添加WMTS图层
*
* @param url 服务地址
* @param layer 图层名称
* @param tileMatrixSet 切片使用的网格名称
* @param format 图片格式
* @param name 自定义图层名称
* @param minZoom 最小缩放等级
* @param maxZoom 最大缩放等级
* @param tileSize 切片大小
*/
public void addWMTSLayer(String url, String layer, String tileMatrixSet, String format, String name, Integer minZoom, Integer maxZoom, Integer tileSize) {
Log.e(TAG, "addWMTSLayer: ++");
loadMethod("addWMTSLayer(\"" + url + "\",\"" + layer + "\",\"" + tileMatrixSet + "\",\"" + format + "\",\"" + name + "\"," + minZoom + "," + maxZoom + "," + tileSize + ")");
}
/**
* 根据图层名称移除图层
*
* @param name 图层名称
*/
public void removeLayerByName(String name) {
loadMethod("removeLayerByName(\"" + name + "\")");
}
/**
* 切换地图底图
*
* @param source 来源-MapBox/高德/谷歌/天地图
* @param type 地图类型-道路图/卫星图
*/
public void switchBaseLayer(String source, String type) {
loadMethod("switchBaseLayer(\"" + source + "\",\"" + type + "\")");
}
private void loadMethod(String method) {
if (hasInit) {
loadUrl("javascript:" + method + "");
} else {
}
}
/**
* 加载完成事件
*/
class MWebView extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
Log.e("WebView", "加载完成");
hasInit = true;
super.onPageFinished(view, url);
mapListener.onMapLoaded();
}
}
class JsInteration {
/**
* 地图点击监听
*/
@JavascriptInterface
public void iconClick(double lat,double lng) {
mapListener.onIconClick(lat,lng);
}
}
}
| GISHanBo/Leaflet-Android | lib/MapView.java |
247,657 | package sun.awt.geom;
import java.awt.geom.IllegalPathStateException;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.PrintStream;
import java.util.Vector;
public abstract class Curve
{
public static final int INCREASING = 1;
public static final int DECREASING = -1;
protected int direction;
public static final int RECT_INTERSECTS = Integer.MIN_VALUE;
public static final double TMIN = 0.001D;
public static void insertMove(Vector paramVector, double paramDouble1, double paramDouble2)
{
paramVector.add(new Order0(paramDouble1, paramDouble2));
}
public static void insertLine(Vector paramVector, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4)
{
if (paramDouble2 < paramDouble4) {
paramVector.add(new Order1(paramDouble1, paramDouble2, paramDouble3, paramDouble4, 1));
} else if (paramDouble2 > paramDouble4) {
paramVector.add(new Order1(paramDouble3, paramDouble4, paramDouble1, paramDouble2, -1));
}
}
public static void insertQuad(Vector paramVector, double paramDouble1, double paramDouble2, double[] paramArrayOfDouble)
{
double d = paramArrayOfDouble[3];
if (paramDouble2 > d)
{
Order2.insert(paramVector, paramArrayOfDouble, paramArrayOfDouble[2], d, paramArrayOfDouble[0], paramArrayOfDouble[1], paramDouble1, paramDouble2, -1);
}
else
{
if ((paramDouble2 == d) && (paramDouble2 == paramArrayOfDouble[1])) {
return;
}
Order2.insert(paramVector, paramArrayOfDouble, paramDouble1, paramDouble2, paramArrayOfDouble[0], paramArrayOfDouble[1], paramArrayOfDouble[2], d, 1);
}
}
public static void insertCubic(Vector paramVector, double paramDouble1, double paramDouble2, double[] paramArrayOfDouble)
{
double d = paramArrayOfDouble[5];
if (paramDouble2 > d)
{
Order3.insert(paramVector, paramArrayOfDouble, paramArrayOfDouble[4], d, paramArrayOfDouble[2], paramArrayOfDouble[3], paramArrayOfDouble[0], paramArrayOfDouble[1], paramDouble1, paramDouble2, -1);
}
else
{
if ((paramDouble2 == d) && (paramDouble2 == paramArrayOfDouble[1]) && (paramDouble2 == paramArrayOfDouble[3])) {
return;
}
Order3.insert(paramVector, paramArrayOfDouble, paramDouble1, paramDouble2, paramArrayOfDouble[0], paramArrayOfDouble[1], paramArrayOfDouble[2], paramArrayOfDouble[3], paramArrayOfDouble[4], d, 1);
}
}
public static int pointCrossingsForPath(PathIterator paramPathIterator, double paramDouble1, double paramDouble2)
{
if (paramPathIterator.isDone()) {
return 0;
}
double[] arrayOfDouble = new double[6];
if (paramPathIterator.currentSegment(arrayOfDouble) != 0) {
throw new IllegalPathStateException("missing initial moveto in path definition");
}
paramPathIterator.next();
double d1 = arrayOfDouble[0];
double d2 = arrayOfDouble[1];
double d3 = d1;
double d4 = d2;
int i = 0;
while (!paramPathIterator.isDone())
{
double d5;
double d6;
switch (paramPathIterator.currentSegment(arrayOfDouble))
{
case 0:
if (d4 != d2) {
i += pointCrossingsForLine(paramDouble1, paramDouble2, d3, d4, d1, d2);
}
d1 = d3 = arrayOfDouble[0];
d2 = d4 = arrayOfDouble[1];
break;
case 1:
d5 = arrayOfDouble[0];
d6 = arrayOfDouble[1];
i += pointCrossingsForLine(paramDouble1, paramDouble2, d3, d4, d5, d6);
d3 = d5;
d4 = d6;
break;
case 2:
d5 = arrayOfDouble[2];
d6 = arrayOfDouble[3];
i += pointCrossingsForQuad(paramDouble1, paramDouble2, d3, d4, arrayOfDouble[0], arrayOfDouble[1], d5, d6, 0);
d3 = d5;
d4 = d6;
break;
case 3:
d5 = arrayOfDouble[4];
d6 = arrayOfDouble[5];
i += pointCrossingsForCubic(paramDouble1, paramDouble2, d3, d4, arrayOfDouble[0], arrayOfDouble[1], arrayOfDouble[2], arrayOfDouble[3], d5, d6, 0);
d3 = d5;
d4 = d6;
break;
case 4:
if (d4 != d2) {
i += pointCrossingsForLine(paramDouble1, paramDouble2, d3, d4, d1, d2);
}
d3 = d1;
d4 = d2;
}
paramPathIterator.next();
}
if (d4 != d2) {
i += pointCrossingsForLine(paramDouble1, paramDouble2, d3, d4, d1, d2);
}
return i;
}
public static int pointCrossingsForLine(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6)
{
if ((paramDouble2 < paramDouble4) && (paramDouble2 < paramDouble6)) {
return 0;
}
if ((paramDouble2 >= paramDouble4) && (paramDouble2 >= paramDouble6)) {
return 0;
}
if ((paramDouble1 >= paramDouble3) && (paramDouble1 >= paramDouble5)) {
return 0;
}
if ((paramDouble1 < paramDouble3) && (paramDouble1 < paramDouble5)) {
return paramDouble4 < paramDouble6 ? 1 : -1;
}
double d = paramDouble3 + (paramDouble2 - paramDouble4) * (paramDouble5 - paramDouble3) / (paramDouble6 - paramDouble4);
if (paramDouble1 >= d) {
return 0;
}
return paramDouble4 < paramDouble6 ? 1 : -1;
}
public static int pointCrossingsForQuad(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, int paramInt)
{
if ((paramDouble2 < paramDouble4) && (paramDouble2 < paramDouble6) && (paramDouble2 < paramDouble8)) {
return 0;
}
if ((paramDouble2 >= paramDouble4) && (paramDouble2 >= paramDouble6) && (paramDouble2 >= paramDouble8)) {
return 0;
}
if ((paramDouble1 >= paramDouble3) && (paramDouble1 >= paramDouble5) && (paramDouble1 >= paramDouble7)) {
return 0;
}
if ((paramDouble1 < paramDouble3) && (paramDouble1 < paramDouble5) && (paramDouble1 < paramDouble7))
{
if (paramDouble2 >= paramDouble4)
{
if (paramDouble2 < paramDouble8) {
return 1;
}
}
else if (paramDouble2 >= paramDouble8) {
return -1;
}
return 0;
}
if (paramInt > 52) {
return pointCrossingsForLine(paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble7, paramDouble8);
}
double d1 = (paramDouble3 + paramDouble5) / 2.0D;
double d2 = (paramDouble4 + paramDouble6) / 2.0D;
double d3 = (paramDouble5 + paramDouble7) / 2.0D;
double d4 = (paramDouble6 + paramDouble8) / 2.0D;
paramDouble5 = (d1 + d3) / 2.0D;
paramDouble6 = (d2 + d4) / 2.0D;
if ((Double.isNaN(paramDouble5)) || (Double.isNaN(paramDouble6))) {
return 0;
}
return pointCrossingsForQuad(paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, paramDouble5, paramDouble6, paramInt + 1) + pointCrossingsForQuad(paramDouble1, paramDouble2, paramDouble5, paramDouble6, d3, d4, paramDouble7, paramDouble8, paramInt + 1);
}
public static int pointCrossingsForCubic(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, double paramDouble9, double paramDouble10, int paramInt)
{
if ((paramDouble2 < paramDouble4) && (paramDouble2 < paramDouble6) && (paramDouble2 < paramDouble8) && (paramDouble2 < paramDouble10)) {
return 0;
}
if ((paramDouble2 >= paramDouble4) && (paramDouble2 >= paramDouble6) && (paramDouble2 >= paramDouble8) && (paramDouble2 >= paramDouble10)) {
return 0;
}
if ((paramDouble1 >= paramDouble3) && (paramDouble1 >= paramDouble5) && (paramDouble1 >= paramDouble7) && (paramDouble1 >= paramDouble9)) {
return 0;
}
if ((paramDouble1 < paramDouble3) && (paramDouble1 < paramDouble5) && (paramDouble1 < paramDouble7) && (paramDouble1 < paramDouble9))
{
if (paramDouble2 >= paramDouble4)
{
if (paramDouble2 < paramDouble10) {
return 1;
}
}
else if (paramDouble2 >= paramDouble10) {
return -1;
}
return 0;
}
if (paramInt > 52) {
return pointCrossingsForLine(paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble9, paramDouble10);
}
double d1 = (paramDouble5 + paramDouble7) / 2.0D;
double d2 = (paramDouble6 + paramDouble8) / 2.0D;
paramDouble5 = (paramDouble3 + paramDouble5) / 2.0D;
paramDouble6 = (paramDouble4 + paramDouble6) / 2.0D;
paramDouble7 = (paramDouble7 + paramDouble9) / 2.0D;
paramDouble8 = (paramDouble8 + paramDouble10) / 2.0D;
double d3 = (paramDouble5 + d1) / 2.0D;
double d4 = (paramDouble6 + d2) / 2.0D;
double d5 = (d1 + paramDouble7) / 2.0D;
double d6 = (d2 + paramDouble8) / 2.0D;
d1 = (d3 + d5) / 2.0D;
d2 = (d4 + d6) / 2.0D;
if ((Double.isNaN(d1)) || (Double.isNaN(d2))) {
return 0;
}
return pointCrossingsForCubic(paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, d3, d4, d1, d2, paramInt + 1) + pointCrossingsForCubic(paramDouble1, paramDouble2, d1, d2, d5, d6, paramDouble7, paramDouble8, paramDouble9, paramDouble10, paramInt + 1);
}
public static int rectCrossingsForPath(PathIterator paramPathIterator, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4)
{
if ((paramDouble3 <= paramDouble1) || (paramDouble4 <= paramDouble2)) {
return 0;
}
if (paramPathIterator.isDone()) {
return 0;
}
double[] arrayOfDouble = new double[6];
if (paramPathIterator.currentSegment(arrayOfDouble) != 0) {
throw new IllegalPathStateException("missing initial moveto in path definition");
}
paramPathIterator.next();
double d3;
double d1 = d3 = arrayOfDouble[0];
double d4;
double d2 = d4 = arrayOfDouble[1];
int i = 0;
while ((i != Integer.MIN_VALUE) && (!paramPathIterator.isDone()))
{
double d5;
double d6;
switch (paramPathIterator.currentSegment(arrayOfDouble))
{
case 0:
if ((d1 != d3) || (d2 != d4)) {
i = rectCrossingsForLine(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, d4);
}
d3 = d1 = arrayOfDouble[0];
d4 = d2 = arrayOfDouble[1];
break;
case 1:
d5 = arrayOfDouble[0];
d6 = arrayOfDouble[1];
i = rectCrossingsForLine(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d5, d6);
d1 = d5;
d2 = d6;
break;
case 2:
d5 = arrayOfDouble[2];
d6 = arrayOfDouble[3];
i = rectCrossingsForQuad(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, arrayOfDouble[0], arrayOfDouble[1], d5, d6, 0);
d1 = d5;
d2 = d6;
break;
case 3:
d5 = arrayOfDouble[4];
d6 = arrayOfDouble[5];
i = rectCrossingsForCubic(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, arrayOfDouble[0], arrayOfDouble[1], arrayOfDouble[2], arrayOfDouble[3], d5, d6, 0);
d1 = d5;
d2 = d6;
break;
case 4:
if ((d1 != d3) || (d2 != d4)) {
i = rectCrossingsForLine(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, d4);
}
d1 = d3;
d2 = d4;
}
paramPathIterator.next();
}
if ((i != Integer.MIN_VALUE) && ((d1 != d3) || (d2 != d4))) {
i = rectCrossingsForLine(i, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, d4);
}
return i;
}
public static int rectCrossingsForLine(int paramInt, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8)
{
if ((paramDouble6 >= paramDouble4) && (paramDouble8 >= paramDouble4)) {
return paramInt;
}
if ((paramDouble6 <= paramDouble2) && (paramDouble8 <= paramDouble2)) {
return paramInt;
}
if ((paramDouble5 <= paramDouble1) && (paramDouble7 <= paramDouble1)) {
return paramInt;
}
if ((paramDouble5 >= paramDouble3) && (paramDouble7 >= paramDouble3))
{
if (paramDouble6 < paramDouble8)
{
if (paramDouble6 <= paramDouble2) {
paramInt++;
}
if (paramDouble8 >= paramDouble4) {
paramInt++;
}
}
else if (paramDouble8 < paramDouble6)
{
if (paramDouble8 <= paramDouble2) {
paramInt--;
}
if (paramDouble6 >= paramDouble4) {
paramInt--;
}
}
return paramInt;
}
if (((paramDouble5 > paramDouble1) && (paramDouble5 < paramDouble3) && (paramDouble6 > paramDouble2) && (paramDouble6 < paramDouble4)) || ((paramDouble7 > paramDouble1) && (paramDouble7 < paramDouble3) && (paramDouble8 > paramDouble2) && (paramDouble8 < paramDouble4))) {
return Integer.MIN_VALUE;
}
double d1 = paramDouble5;
if (paramDouble6 < paramDouble2) {
d1 += (paramDouble2 - paramDouble6) * (paramDouble7 - paramDouble5) / (paramDouble8 - paramDouble6);
} else if (paramDouble6 > paramDouble4) {
d1 += (paramDouble4 - paramDouble6) * (paramDouble7 - paramDouble5) / (paramDouble8 - paramDouble6);
}
double d2 = paramDouble7;
if (paramDouble8 < paramDouble2) {
d2 += (paramDouble2 - paramDouble8) * (paramDouble5 - paramDouble7) / (paramDouble6 - paramDouble8);
} else if (paramDouble8 > paramDouble4) {
d2 += (paramDouble4 - paramDouble8) * (paramDouble5 - paramDouble7) / (paramDouble6 - paramDouble8);
}
if ((d1 <= paramDouble1) && (d2 <= paramDouble1)) {
return paramInt;
}
if ((d1 >= paramDouble3) && (d2 >= paramDouble3))
{
if (paramDouble6 < paramDouble8)
{
if (paramDouble6 <= paramDouble2) {
paramInt++;
}
if (paramDouble8 >= paramDouble4) {
paramInt++;
}
}
else if (paramDouble8 < paramDouble6)
{
if (paramDouble8 <= paramDouble2) {
paramInt--;
}
if (paramDouble6 >= paramDouble4) {
paramInt--;
}
}
return paramInt;
}
return Integer.MIN_VALUE;
}
public static int rectCrossingsForQuad(int paramInt1, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, double paramDouble9, double paramDouble10, int paramInt2)
{
if ((paramDouble6 >= paramDouble4) && (paramDouble8 >= paramDouble4) && (paramDouble10 >= paramDouble4)) {
return paramInt1;
}
if ((paramDouble6 <= paramDouble2) && (paramDouble8 <= paramDouble2) && (paramDouble10 <= paramDouble2)) {
return paramInt1;
}
if ((paramDouble5 <= paramDouble1) && (paramDouble7 <= paramDouble1) && (paramDouble9 <= paramDouble1)) {
return paramInt1;
}
if ((paramDouble5 >= paramDouble3) && (paramDouble7 >= paramDouble3) && (paramDouble9 >= paramDouble3))
{
if (paramDouble6 < paramDouble10)
{
if ((paramDouble6 <= paramDouble2) && (paramDouble10 > paramDouble2)) {
paramInt1++;
}
if ((paramDouble6 < paramDouble4) && (paramDouble10 >= paramDouble4)) {
paramInt1++;
}
}
else if (paramDouble10 < paramDouble6)
{
if ((paramDouble10 <= paramDouble2) && (paramDouble6 > paramDouble2)) {
paramInt1--;
}
if ((paramDouble10 < paramDouble4) && (paramDouble6 >= paramDouble4)) {
paramInt1--;
}
}
return paramInt1;
}
if (((paramDouble5 < paramDouble3) && (paramDouble5 > paramDouble1) && (paramDouble6 < paramDouble4) && (paramDouble6 > paramDouble2)) || ((paramDouble9 < paramDouble3) && (paramDouble9 > paramDouble1) && (paramDouble10 < paramDouble4) && (paramDouble10 > paramDouble2))) {
return Integer.MIN_VALUE;
}
if (paramInt2 > 52) {
return rectCrossingsForLine(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble9, paramDouble10);
}
double d1 = (paramDouble5 + paramDouble7) / 2.0D;
double d2 = (paramDouble6 + paramDouble8) / 2.0D;
double d3 = (paramDouble7 + paramDouble9) / 2.0D;
double d4 = (paramDouble8 + paramDouble10) / 2.0D;
paramDouble7 = (d1 + d3) / 2.0D;
paramDouble8 = (d2 + d4) / 2.0D;
if ((Double.isNaN(paramDouble7)) || (Double.isNaN(paramDouble8))) {
return 0;
}
paramInt1 = rectCrossingsForQuad(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, d1, d2, paramDouble7, paramDouble8, paramInt2 + 1);
if (paramInt1 != Integer.MIN_VALUE) {
paramInt1 = rectCrossingsForQuad(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble7, paramDouble8, d3, d4, paramDouble9, paramDouble10, paramInt2 + 1);
}
return paramInt1;
}
public static int rectCrossingsForCubic(int paramInt1, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, double paramDouble9, double paramDouble10, double paramDouble11, double paramDouble12, int paramInt2)
{
if ((paramDouble6 >= paramDouble4) && (paramDouble8 >= paramDouble4) && (paramDouble10 >= paramDouble4) && (paramDouble12 >= paramDouble4)) {
return paramInt1;
}
if ((paramDouble6 <= paramDouble2) && (paramDouble8 <= paramDouble2) && (paramDouble10 <= paramDouble2) && (paramDouble12 <= paramDouble2)) {
return paramInt1;
}
if ((paramDouble5 <= paramDouble1) && (paramDouble7 <= paramDouble1) && (paramDouble9 <= paramDouble1) && (paramDouble11 <= paramDouble1)) {
return paramInt1;
}
if ((paramDouble5 >= paramDouble3) && (paramDouble7 >= paramDouble3) && (paramDouble9 >= paramDouble3) && (paramDouble11 >= paramDouble3))
{
if (paramDouble6 < paramDouble12)
{
if ((paramDouble6 <= paramDouble2) && (paramDouble12 > paramDouble2)) {
paramInt1++;
}
if ((paramDouble6 < paramDouble4) && (paramDouble12 >= paramDouble4)) {
paramInt1++;
}
}
else if (paramDouble12 < paramDouble6)
{
if ((paramDouble12 <= paramDouble2) && (paramDouble6 > paramDouble2)) {
paramInt1--;
}
if ((paramDouble12 < paramDouble4) && (paramDouble6 >= paramDouble4)) {
paramInt1--;
}
}
return paramInt1;
}
if (((paramDouble5 > paramDouble1) && (paramDouble5 < paramDouble3) && (paramDouble6 > paramDouble2) && (paramDouble6 < paramDouble4)) || ((paramDouble11 > paramDouble1) && (paramDouble11 < paramDouble3) && (paramDouble12 > paramDouble2) && (paramDouble12 < paramDouble4))) {
return Integer.MIN_VALUE;
}
if (paramInt2 > 52) {
return rectCrossingsForLine(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble11, paramDouble12);
}
double d1 = (paramDouble7 + paramDouble9) / 2.0D;
double d2 = (paramDouble8 + paramDouble10) / 2.0D;
paramDouble7 = (paramDouble5 + paramDouble7) / 2.0D;
paramDouble8 = (paramDouble6 + paramDouble8) / 2.0D;
paramDouble9 = (paramDouble9 + paramDouble11) / 2.0D;
paramDouble10 = (paramDouble10 + paramDouble12) / 2.0D;
double d3 = (paramDouble7 + d1) / 2.0D;
double d4 = (paramDouble8 + d2) / 2.0D;
double d5 = (d1 + paramDouble9) / 2.0D;
double d6 = (d2 + paramDouble10) / 2.0D;
d1 = (d3 + d5) / 2.0D;
d2 = (d4 + d6) / 2.0D;
if ((Double.isNaN(d1)) || (Double.isNaN(d2))) {
return 0;
}
paramInt1 = rectCrossingsForCubic(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble7, paramDouble8, d3, d4, d1, d2, paramInt2 + 1);
if (paramInt1 != Integer.MIN_VALUE) {
paramInt1 = rectCrossingsForCubic(paramInt1, paramDouble1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d5, d6, paramDouble9, paramDouble10, paramDouble11, paramDouble12, paramInt2 + 1);
}
return paramInt1;
}
public Curve(int paramInt)
{
direction = paramInt;
}
public final int getDirection()
{
return direction;
}
public final Curve getWithDirection(int paramInt)
{
return direction == paramInt ? this : getReversedCurve();
}
public static double round(double paramDouble)
{
return paramDouble;
}
public static int orderof(double paramDouble1, double paramDouble2)
{
if (paramDouble1 < paramDouble2) {
return -1;
}
if (paramDouble1 > paramDouble2) {
return 1;
}
return 0;
}
public static long signeddiffbits(double paramDouble1, double paramDouble2)
{
return Double.doubleToLongBits(paramDouble1) - Double.doubleToLongBits(paramDouble2);
}
public static long diffbits(double paramDouble1, double paramDouble2)
{
return Math.abs(Double.doubleToLongBits(paramDouble1) - Double.doubleToLongBits(paramDouble2));
}
public static double prev(double paramDouble)
{
return Double.longBitsToDouble(Double.doubleToLongBits(paramDouble) - 1L);
}
public static double next(double paramDouble)
{
return Double.longBitsToDouble(Double.doubleToLongBits(paramDouble) + 1L);
}
public String toString()
{
return "Curve[" + getOrder() + ", " + "(" + round(getX0()) + ", " + round(getY0()) + "), " + controlPointString() + "(" + round(getX1()) + ", " + round(getY1()) + "), " + (direction == 1 ? "D" : "U") + "]";
}
public String controlPointString()
{
return "";
}
public abstract int getOrder();
public abstract double getXTop();
public abstract double getYTop();
public abstract double getXBot();
public abstract double getYBot();
public abstract double getXMin();
public abstract double getXMax();
public abstract double getX0();
public abstract double getY0();
public abstract double getX1();
public abstract double getY1();
public abstract double XforY(double paramDouble);
public abstract double TforY(double paramDouble);
public abstract double XforT(double paramDouble);
public abstract double YforT(double paramDouble);
public abstract double dXforT(double paramDouble, int paramInt);
public abstract double dYforT(double paramDouble, int paramInt);
public abstract double nextVertical(double paramDouble1, double paramDouble2);
public int crossingsFor(double paramDouble1, double paramDouble2)
{
if ((paramDouble2 >= getYTop()) && (paramDouble2 < getYBot()) && (paramDouble1 < getXMax()) && ((paramDouble1 < getXMin()) || (paramDouble1 < XforY(paramDouble2)))) {
return 1;
}
return 0;
}
public boolean accumulateCrossings(Crossings paramCrossings)
{
double d1 = paramCrossings.getXHi();
if (getXMin() >= d1) {
return false;
}
double d2 = paramCrossings.getXLo();
double d3 = paramCrossings.getYLo();
double d4 = paramCrossings.getYHi();
double d5 = getYTop();
double d6 = getYBot();
double d8;
double d7;
if (d5 < d3)
{
if (d6 <= d3) {
return false;
}
d8 = d3;
d7 = TforY(d3);
}
else
{
if (d5 >= d4) {
return false;
}
d8 = d5;
d7 = 0.0D;
}
double d10;
double d9;
if (d6 > d4)
{
d10 = d4;
d9 = TforY(d4);
}
else
{
d10 = d6;
d9 = 1.0D;
}
int i = 0;
int j = 0;
for (;;)
{
double d11 = XforT(d7);
if (d11 < d1)
{
if ((j != 0) || (d11 > d2)) {
return true;
}
i = 1;
}
else
{
if (i != 0) {
return true;
}
j = 1;
}
if (d7 >= d9) {
break;
}
d7 = nextVertical(d7, d9);
}
if (i != 0) {
paramCrossings.record(d8, d10, direction);
}
return false;
}
public abstract void enlarge(Rectangle2D paramRectangle2D);
public Curve getSubCurve(double paramDouble1, double paramDouble2)
{
return getSubCurve(paramDouble1, paramDouble2, direction);
}
public abstract Curve getReversedCurve();
public abstract Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt);
public int compareTo(Curve paramCurve, double[] paramArrayOfDouble)
{
double d1 = paramArrayOfDouble[0];
double d2 = paramArrayOfDouble[1];
d2 = Math.min(Math.min(d2, getYBot()), paramCurve.getYBot());
if (d2 <= paramArrayOfDouble[0])
{
System.err.println("this == " + this);
System.err.println("that == " + paramCurve);
System.out.println("target range = " + paramArrayOfDouble[0] + "=>" + paramArrayOfDouble[1]);
throw new InternalError("backstepping from " + paramArrayOfDouble[0] + " to " + d2);
}
paramArrayOfDouble[1] = d2;
if (getXMax() <= paramCurve.getXMin())
{
if (getXMin() == paramCurve.getXMax()) {
return 0;
}
return -1;
}
if (getXMin() >= paramCurve.getXMax()) {
return 1;
}
double d3 = TforY(d1);
double d4 = YforT(d3);
if (d4 < d1)
{
d3 = refineTforY(d3, d4, d1);
d4 = YforT(d3);
}
double d5 = TforY(d2);
if (YforT(d5) < d1) {
d5 = refineTforY(d5, YforT(d5), d1);
}
double d6 = paramCurve.TforY(d1);
double d7 = paramCurve.YforT(d6);
if (d7 < d1)
{
d6 = paramCurve.refineTforY(d6, d7, d1);
d7 = paramCurve.YforT(d6);
}
double d8 = paramCurve.TforY(d2);
if (paramCurve.YforT(d8) < d1) {
d8 = paramCurve.refineTforY(d8, paramCurve.YforT(d8), d1);
}
double d9 = XforT(d3);
double d10 = paramCurve.XforT(d6);
double d11 = Math.max(Math.abs(d1), Math.abs(d2));
double d12 = Math.max(d11 * 1.0E-14D, 1.0E-300D);
double d14;
double d15;
double d16;
if (fairlyClose(d9, d10))
{
d13 = d12;
d14 = Math.min(d12 * 1.0E13D, (d2 - d1) * 0.1D);
for (d15 = d1 + d13; d15 <= d2; d15 += d13) {
if (fairlyClose(XforY(d15), paramCurve.XforY(d15)))
{
if (d13 *= 2.0D > d14) {
d13 = d14;
}
}
else
{
d15 -= d13;
for (;;)
{
d13 /= 2.0D;
d16 = d15 + d13;
if (d16 <= d15) {
break;
}
if (fairlyClose(XforY(d16), paramCurve.XforY(d16))) {
d15 = d16;
}
}
}
}
if (d15 > d1)
{
if (d15 < d2) {
paramArrayOfDouble[1] = d15;
}
return 0;
}
}
if (d12 <= 0.0D) {
System.out.println("ymin = " + d12);
}
while ((d3 < d5) && (d6 < d8))
{
d13 = nextVertical(d3, d5);
d14 = XforT(d13);
d15 = YforT(d13);
d16 = paramCurve.nextVertical(d6, d8);
double d17 = paramCurve.XforT(d16);
double d18 = paramCurve.YforT(d16);
try
{
if (findIntersect(paramCurve, paramArrayOfDouble, d12, 0, 0, d3, d9, d4, d13, d14, d15, d6, d10, d7, d16, d17, d18)) {
break;
}
}
catch (Throwable localThrowable)
{
System.err.println("Error: " + localThrowable);
System.err.println("y range was " + paramArrayOfDouble[0] + "=>" + paramArrayOfDouble[1]);
System.err.println("s y range is " + d4 + "=>" + d15);
System.err.println("t y range is " + d7 + "=>" + d18);
System.err.println("ymin is " + d12);
return 0;
}
if (d15 < d18)
{
if (d15 > paramArrayOfDouble[0])
{
if (d15 >= paramArrayOfDouble[1]) {
break;
}
paramArrayOfDouble[1] = d15;
break;
}
d3 = d13;
d9 = d14;
d4 = d15;
}
else
{
if (d18 > paramArrayOfDouble[0])
{
if (d18 >= paramArrayOfDouble[1]) {
break;
}
paramArrayOfDouble[1] = d18;
break;
}
d6 = d16;
d10 = d17;
d7 = d18;
}
}
double d13 = (paramArrayOfDouble[0] + paramArrayOfDouble[1]) / 2.0D;
return orderof(XforY(d13), paramCurve.XforY(d13));
}
public boolean findIntersect(Curve paramCurve, double[] paramArrayOfDouble, double paramDouble1, int paramInt1, int paramInt2, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, double paramDouble9, double paramDouble10, double paramDouble11, double paramDouble12, double paramDouble13)
{
if ((paramDouble4 > paramDouble13) || (paramDouble10 > paramDouble7)) {
return false;
}
if ((Math.min(paramDouble3, paramDouble6) > Math.max(paramDouble9, paramDouble12)) || (Math.max(paramDouble3, paramDouble6) < Math.min(paramDouble9, paramDouble12))) {
return false;
}
double d1;
double d2;
double d3;
double d4;
double d5;
double d6;
if (paramDouble5 - paramDouble2 > 0.001D)
{
d1 = (paramDouble2 + paramDouble5) / 2.0D;
d2 = XforT(d1);
d3 = YforT(d1);
if ((d1 == paramDouble2) || (d1 == paramDouble5))
{
System.out.println("s0 = " + paramDouble2);
System.out.println("s1 = " + paramDouble5);
throw new InternalError("no s progress!");
}
if (paramDouble11 - paramDouble8 > 0.001D)
{
d4 = (paramDouble8 + paramDouble11) / 2.0D;
d5 = paramCurve.XforT(d4);
d6 = paramCurve.YforT(d4);
if ((d4 == paramDouble8) || (d4 == paramDouble11))
{
System.out.println("t0 = " + paramDouble8);
System.out.println("t1 = " + paramDouble11);
throw new InternalError("no t progress!");
}
if ((d3 >= paramDouble10) && (d6 >= paramDouble4) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2 + 1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, paramDouble8, paramDouble9, paramDouble10, d4, d5, d6))) {
return true;
}
if ((d3 >= d6) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2 + 1, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, d4, d5, d6, paramDouble11, paramDouble12, paramDouble13))) {
return true;
}
if ((d6 >= d3) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2 + 1, d1, d2, d3, paramDouble5, paramDouble6, paramDouble7, paramDouble8, paramDouble9, paramDouble10, d4, d5, d6))) {
return true;
}
if ((paramDouble7 >= d6) && (paramDouble13 >= d3) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2 + 1, d1, d2, d3, paramDouble5, paramDouble6, paramDouble7, d4, d5, d6, paramDouble11, paramDouble12, paramDouble13))) {
return true;
}
}
else
{
if ((d3 >= paramDouble10) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2, paramDouble2, paramDouble3, paramDouble4, d1, d2, d3, paramDouble8, paramDouble9, paramDouble10, paramDouble11, paramDouble12, paramDouble13))) {
return true;
}
if ((paramDouble13 >= d3) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1 + 1, paramInt2, d1, d2, d3, paramDouble5, paramDouble6, paramDouble7, paramDouble8, paramDouble9, paramDouble10, paramDouble11, paramDouble12, paramDouble13))) {
return true;
}
}
}
else if (paramDouble11 - paramDouble8 > 0.001D)
{
d1 = (paramDouble8 + paramDouble11) / 2.0D;
d2 = paramCurve.XforT(d1);
d3 = paramCurve.YforT(d1);
if ((d1 == paramDouble8) || (d1 == paramDouble11))
{
System.out.println("t0 = " + paramDouble8);
System.out.println("t1 = " + paramDouble11);
throw new InternalError("no t progress!");
}
if ((d3 >= paramDouble4) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1, paramInt2 + 1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble7, paramDouble8, paramDouble9, paramDouble10, d1, d2, d3))) {
return true;
}
if ((paramDouble7 >= d3) && (findIntersect(paramCurve, paramArrayOfDouble, paramDouble1, paramInt1, paramInt2 + 1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble7, d1, d2, d3, paramDouble11, paramDouble12, paramDouble13))) {
return true;
}
}
else
{
d1 = paramDouble6 - paramDouble3;
d2 = paramDouble7 - paramDouble4;
d3 = paramDouble12 - paramDouble9;
d4 = paramDouble13 - paramDouble10;
d5 = paramDouble9 - paramDouble3;
d6 = paramDouble10 - paramDouble4;
double d7 = d3 * d2 - d4 * d1;
if (d7 != 0.0D)
{
double d8 = 1.0D / d7;
double d9 = (d3 * d6 - d4 * d5) * d8;
double d10 = (d1 * d6 - d2 * d5) * d8;
if ((d9 >= 0.0D) && (d9 <= 1.0D) && (d10 >= 0.0D) && (d10 <= 1.0D))
{
d9 = paramDouble2 + d9 * (paramDouble5 - paramDouble2);
d10 = paramDouble8 + d10 * (paramDouble11 - paramDouble8);
if ((d9 < 0.0D) || (d9 > 1.0D) || (d10 < 0.0D) || (d10 > 1.0D)) {
System.out.println("Uh oh!");
}
double d11 = (YforT(d9) + paramCurve.YforT(d10)) / 2.0D;
if ((d11 <= paramArrayOfDouble[1]) && (d11 > paramArrayOfDouble[0]))
{
paramArrayOfDouble[1] = d11;
return true;
}
}
}
}
return false;
}
public double refineTforY(double paramDouble1, double paramDouble2, double paramDouble3)
{
double d1 = 1.0D;
for (;;)
{
double d2 = (paramDouble1 + d1) / 2.0D;
if ((d2 == paramDouble1) || (d2 == d1)) {
return d1;
}
double d3 = YforT(d2);
if (d3 < paramDouble3)
{
paramDouble1 = d2;
paramDouble2 = d3;
}
else if (d3 > paramDouble3)
{
d1 = d2;
}
else
{
return d1;
}
}
}
public boolean fairlyClose(double paramDouble1, double paramDouble2)
{
return Math.abs(paramDouble1 - paramDouble2) < Math.max(Math.abs(paramDouble1), Math.abs(paramDouble2)) * 1.0E-10D;
}
public abstract int getSegment(double[] paramArrayOfDouble);
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\awt\geom\Curve.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | msjian/java1.8.0_151 | sun/awt/geom/Curve.java |
247,658 | package sun.awt.geom;
import java.awt.geom.Rectangle2D;
final class Order0
extends Curve
{
private double x;
private double y;
public Order0(double paramDouble1, double paramDouble2)
{
super(1);
x = paramDouble1;
y = paramDouble2;
}
public int getOrder()
{
return 0;
}
public double getXTop()
{
return x;
}
public double getYTop()
{
return y;
}
public double getXBot()
{
return x;
}
public double getYBot()
{
return y;
}
public double getXMin()
{
return x;
}
public double getXMax()
{
return x;
}
public double getX0()
{
return x;
}
public double getY0()
{
return y;
}
public double getX1()
{
return x;
}
public double getY1()
{
return y;
}
public double XforY(double paramDouble)
{
return paramDouble;
}
public double TforY(double paramDouble)
{
return 0.0D;
}
public double XforT(double paramDouble)
{
return x;
}
public double YforT(double paramDouble)
{
return y;
}
public double dXforT(double paramDouble, int paramInt)
{
return 0.0D;
}
public double dYforT(double paramDouble, int paramInt)
{
return 0.0D;
}
public double nextVertical(double paramDouble1, double paramDouble2)
{
return paramDouble2;
}
public int crossingsFor(double paramDouble1, double paramDouble2)
{
return 0;
}
public boolean accumulateCrossings(Crossings paramCrossings)
{
return (x > paramCrossings.getXLo()) && (x < paramCrossings.getXHi()) && (y > paramCrossings.getYLo()) && (y < paramCrossings.getYHi());
}
public void enlarge(Rectangle2D paramRectangle2D)
{
paramRectangle2D.add(x, y);
}
public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt)
{
return this;
}
public Curve getReversedCurve()
{
return this;
}
public int getSegment(double[] paramArrayOfDouble)
{
paramArrayOfDouble[0] = x;
paramArrayOfDouble[1] = y;
return 0;
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\awt\geom\Order0.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | msjian/java1.8.0_151 | sun/awt/geom/Order0.java |
247,659 | package RPNCalculator;
import java.util.*;
import RPNCalculator.Stack;
/**
* ArrayStack class.
* @author Max, Harry, Tom.
*/
public class ArrayStack<T> implements Stack<T> {
/** final data field for default stack size. */
final static int DEFAULT=10;
/** data field for generic stack. */
T[]stack;
/** data field for stack size. */
public int size=0;
/** Default Constructor for ArrayStack class. */
public ArrayStack(){
stack= (T[]) new Object[DEFAULT];
}
/** Constructor for ArrayStack that creates a stack of a given size.
* @param n desired size of stack.
*/
public ArrayStack(int n){
stack= (T[]) new Object[n];
}
/**
* Push method.
* @param element - object to be added to the stack.
*/
public void push (T element) {
if (size >= stack.length) {
enlarge();
}
stack[size] = element;
size++;
}
/**
* Enlarge method - copies the array into a new array double the size.
*/
public void enlarge(){
stack=Arrays.copyOf(stack, 2*stack.length);
}
/**
* Peek method.
* @return the top element in the stack.
*/
public T peek() {
if (this.isEmpty()) {
try {
throw new Exception("Peek on empty stack");
} catch (Exception e) {
e.printStackTrace();
}
}
return stack[size-1];
}
/**
* Pop method.
* Removes and returns the top element in the stack.
* @return the top element in the stack.
*/
public T pop() {
if (this.isEmpty()) {
try {
throw new Exception("Pop from empty stack");
} catch (Exception e) {
e.printStackTrace();
}
}
size--;
return stack[size];
}
/**
* isEmpty method.
* checks if the stack is empty.
* @return boolean True if the stack is empty.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Size method.
* @return number of items in the stack.
*/
public int size() {
return size;
}
}
| maxvds/RPNCalculator | java/ArrayStack.java |
247,660 | package practice.knifemanager.mylist;
import java.util.Arrays;
public class MyArrayList extends MyAbstractList {
private static final int DEFAULT_CAPACITY = 10;
private Object[] data;
private int size;
public MyArrayList() {
this.data = new Object[DEFAULT_CAPACITY];
size = 0;
}
@Override
public MyIterator iterator() {
return new MyArrayListIterator(data);
}
@Override
public void append(Object thing) {
if (size >= data.length) enlarge();
data[size++] = thing;
}
@Override
public void insert(Object thing, int index) {
checkBound(index, size);
if (size >= data.length) enlarge();
System.arraycopy(data, index, data, index + 1, size - index);
data[index] = thing;
size++;
}
@Override
public void set(Object thing, int index) {
checkBound(index, size - 1);
data[index] = thing;
}
@Override
public void delete(int index) {
checkBound(index, size - 1);
System.arraycopy(data, index + 1, data, index, size - index - 1);
size--;
}
@Override
public void delete(Object thing) {
for (int i = 0; i < size; i++) {
if (data[i].equals(thing)) {
delete(i);
i--;
}
}
}
@Override
public Object get(int index) {
checkBound(index, size - 1);
return data[index];
}
@Override
public int size() {
return size;
}
@Override
public Object[] toArray() {
return Arrays.copyOf(data, size);
}
private void enlarge() {
Object[] newData = new Object[data.length * 2];
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
}
| yuk068/manager-program-example | mylist/MyArrayList.java |
247,661 | /* */ package sun.awt.geom;
/* */
/* */ import java.awt.geom.Rectangle2D;
/* */
/* */ final class Order1 extends Curve
/* */ {
/* */ private double x0;
/* */ private double y0;
/* */ private double x1;
/* */ private double y1;
/* */ private double xmin;
/* */ private double xmax;
/* */
/* */ public Order1(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, int paramInt)
/* */ {
/* 44 */ super(paramInt);
/* 45 */ this.x0 = paramDouble1;
/* 46 */ this.y0 = paramDouble2;
/* 47 */ this.x1 = paramDouble3;
/* 48 */ this.y1 = paramDouble4;
/* 49 */ if (paramDouble1 < paramDouble3) {
/* 50 */ this.xmin = paramDouble1;
/* 51 */ this.xmax = paramDouble3;
/* */ } else {
/* 53 */ this.xmin = paramDouble3;
/* 54 */ this.xmax = paramDouble1;
/* */ }
/* */ }
/* */
/* */ public int getOrder() {
/* 59 */ return 1;
/* */ }
/* */
/* */ public double getXTop() {
/* 63 */ return this.x0;
/* */ }
/* */
/* */ public double getYTop() {
/* 67 */ return this.y0;
/* */ }
/* */
/* */ public double getXBot() {
/* 71 */ return this.x1;
/* */ }
/* */
/* */ public double getYBot() {
/* 75 */ return this.y1;
/* */ }
/* */
/* */ public double getXMin() {
/* 79 */ return this.xmin;
/* */ }
/* */
/* */ public double getXMax() {
/* 83 */ return this.xmax;
/* */ }
/* */
/* */ public double getX0() {
/* 87 */ return this.direction == 1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY0() {
/* 91 */ return this.direction == 1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double getX1() {
/* 95 */ return this.direction == -1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY1() {
/* 99 */ return this.direction == -1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double XforY(double paramDouble) {
/* 103 */ if ((this.x0 == this.x1) || (paramDouble <= this.y0)) {
/* 104 */ return this.x0;
/* */ }
/* 106 */ if (paramDouble >= this.y1) {
/* 107 */ return this.x1;
/* */ }
/* */
/* 110 */ return this.x0 + (paramDouble - this.y0) * (this.x1 - this.x0) / (this.y1 - this.y0);
/* */ }
/* */
/* */ public double TforY(double paramDouble) {
/* 114 */ if (paramDouble <= this.y0) {
/* 115 */ return 0.0D;
/* */ }
/* 117 */ if (paramDouble >= this.y1) {
/* 118 */ return 1.0D;
/* */ }
/* 120 */ return (paramDouble - this.y0) / (this.y1 - this.y0);
/* */ }
/* */
/* */ public double XforT(double paramDouble) {
/* 124 */ return this.x0 + paramDouble * (this.x1 - this.x0);
/* */ }
/* */
/* */ public double YforT(double paramDouble) {
/* 128 */ return this.y0 + paramDouble * (this.y1 - this.y0);
/* */ }
/* */
/* */ public double dXforT(double paramDouble, int paramInt) {
/* 132 */ switch (paramInt) {
/* */ case 0:
/* 134 */ return this.x0 + paramDouble * (this.x1 - this.x0);
/* */ case 1:
/* 136 */ return this.x1 - this.x0;
/* */ }
/* 138 */ return 0.0D;
/* */ }
/* */
/* */ public double dYforT(double paramDouble, int paramInt)
/* */ {
/* 143 */ switch (paramInt) {
/* */ case 0:
/* 145 */ return this.y0 + paramDouble * (this.y1 - this.y0);
/* */ case 1:
/* 147 */ return this.y1 - this.y0;
/* */ }
/* 149 */ return 0.0D;
/* */ }
/* */
/* */ public double nextVertical(double paramDouble1, double paramDouble2)
/* */ {
/* 154 */ return paramDouble2;
/* */ }
/* */
/* */ public boolean accumulateCrossings(Crossings paramCrossings) {
/* 158 */ double d1 = paramCrossings.getXLo();
/* 159 */ double d2 = paramCrossings.getYLo();
/* 160 */ double d3 = paramCrossings.getXHi();
/* 161 */ double d4 = paramCrossings.getYHi();
/* 162 */ if (this.xmin >= d3)
/* 163 */ return false;
/* */ double d6;
/* */ double d5;
/* 166 */ if (this.y0 < d2) {
/* 167 */ if (this.y1 <= d2) {
/* 168 */ return false;
/* */ }
/* 170 */ d6 = d2;
/* 171 */ d5 = XforY(d2);
/* */ } else {
/* 173 */ if (this.y0 >= d4) {
/* 174 */ return false;
/* */ }
/* 176 */ d6 = this.y0;
/* 177 */ d5 = this.x0;
/* */ }
/* */ double d8;
/* */ double d7;
/* 179 */ if (this.y1 > d4) {
/* 180 */ d8 = d4;
/* 181 */ d7 = XforY(d4);
/* */ } else {
/* 183 */ d8 = this.y1;
/* 184 */ d7 = this.x1;
/* */ }
/* 186 */ if ((d5 >= d3) && (d7 >= d3)) {
/* 187 */ return false;
/* */ }
/* 189 */ if ((d5 > d1) || (d7 > d1)) {
/* 190 */ return true;
/* */ }
/* 192 */ paramCrossings.record(d6, d8, this.direction);
/* 193 */ return false;
/* */ }
/* */
/* */ public void enlarge(Rectangle2D paramRectangle2D) {
/* 197 */ paramRectangle2D.add(this.x0, this.y0);
/* 198 */ paramRectangle2D.add(this.x1, this.y1);
/* */ }
/* */
/* */ public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt) {
/* 202 */ if ((paramDouble1 == this.y0) && (paramDouble2 == this.y1)) {
/* 203 */ return getWithDirection(paramInt);
/* */ }
/* 205 */ if (this.x0 == this.x1) {
/* 206 */ return new Order1(this.x0, paramDouble1, this.x1, paramDouble2, paramInt);
/* */ }
/* 208 */ double d1 = this.x0 - this.x1;
/* 209 */ double d2 = this.y0 - this.y1;
/* 210 */ double d3 = this.x0 + (paramDouble1 - this.y0) * d1 / d2;
/* 211 */ double d4 = this.x0 + (paramDouble2 - this.y0) * d1 / d2;
/* 212 */ return new Order1(d3, paramDouble1, d4, paramDouble2, paramInt);
/* */ }
/* */
/* */ public Curve getReversedCurve() {
/* 216 */ return new Order1(this.x0, this.y0, this.x1, this.y1, -this.direction);
/* */ }
/* */
/* */ public int compareTo(Curve paramCurve, double[] paramArrayOfDouble) {
/* 220 */ if (!(paramCurve instanceof Order1)) {
/* 221 */ return super.compareTo(paramCurve, paramArrayOfDouble);
/* */ }
/* 223 */ Order1 localOrder1 = (Order1)paramCurve;
/* 224 */ if (paramArrayOfDouble[1] <= paramArrayOfDouble[0]) {
/* 225 */ throw new InternalError("yrange already screwed up...");
/* */ }
/* 227 */ paramArrayOfDouble[1] = Math.min(Math.min(paramArrayOfDouble[1], this.y1), localOrder1.y1);
/* 228 */ if (paramArrayOfDouble[1] <= paramArrayOfDouble[0]) {
/* 229 */ throw new InternalError("backstepping from " + paramArrayOfDouble[0] + " to " + paramArrayOfDouble[1]);
/* */ }
/* 231 */ if (this.xmax <= localOrder1.xmin) {
/* 232 */ return this.xmin == localOrder1.xmax ? 0 : -1;
/* */ }
/* 234 */ if (this.xmin >= localOrder1.xmax) {
/* 235 */ return 1;
/* */ }
/* */
/* 269 */ double d1 = this.x1 - this.x0;
/* 270 */ double d2 = this.y1 - this.y0;
/* 271 */ double d3 = localOrder1.x1 - localOrder1.x0;
/* 272 */ double d4 = localOrder1.y1 - localOrder1.y0;
/* 273 */ double d5 = d3 * d2 - d1 * d4;
/* */ double d6;
/* 275 */ if (d5 != 0.0D) {
/* 276 */ double d7 = (this.x0 - localOrder1.x0) * d2 * d4 - this.y0 * d1 * d4 + localOrder1.y0 * d3 * d2;
/* */
/* 279 */ d6 = d7 / d5;
/* 280 */ if (d6 <= paramArrayOfDouble[0])
/* */ {
/* 283 */ d6 = Math.min(this.y1, localOrder1.y1);
/* */ }
/* */ else {
/* 286 */ if (d6 < paramArrayOfDouble[1])
/* */ {
/* 288 */ paramArrayOfDouble[1] = d6;
/* */ }
/* */
/* 291 */ d6 = Math.max(this.y0, localOrder1.y0);
/* */ }
/* */
/* */ }
/* */ else
/* */ {
/* 297 */ d6 = Math.max(this.y0, localOrder1.y0);
/* */ }
/* 299 */ return orderof(XforY(d6), localOrder1.XforY(d6));
/* */ }
/* */
/* */ public int getSegment(double[] paramArrayOfDouble) {
/* 303 */ if (this.direction == 1) {
/* 304 */ paramArrayOfDouble[0] = this.x1;
/* 305 */ paramArrayOfDouble[1] = this.y1;
/* */ } else {
/* 307 */ paramArrayOfDouble[0] = this.x0;
/* 308 */ paramArrayOfDouble[1] = this.y0;
/* */ }
/* 310 */ return 1;
/* */ }
/* */ }
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: sun.awt.geom.Order1
* JD-Core Version: 0.6.2
*/ | yuexiahandao/RT-JAR-CODE | sun/awt/geom/Order1.java |
247,662 | package BasicStuff;
class Point {
private final double x;
private final double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public String toString() {
return "Point at (" + this.x + ", " + this.y + ")";
}
}
class Circle {
// attribute
private final double radius;
private final Point centre;
Circle(double radius, Point centre) {
this.radius = radius;
this.centre = centre;
}
public Circle enlarge(double factor) {
return new Circle(this.radius*factor, this.centre);
}
public String toString() {
return "Circle with centre (";
}
} | wilsonwid/java-stuff | BasicStuff/Circle.java |
247,663 | package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ControlCircle extends JFrame {
private JButton jbtEnlarge = new JButton("Enlarge");
private JButton jbtShrink = new JButton("Shrink");
private CirclePanel canvas = new CirclePanel();
public ControlCircle() {
JPanel panel = new JPanel(); // Use the panel to group buttons
panel.add(jbtEnlarge);
panel.add(jbtShrink);
this.add(canvas, BorderLayout.CENTER); // Add canvas to center
this.add(panel, BorderLayout.SOUTH); // Add buttons to the frame
jbtEnlarge.addActionListener(new EnlargeListener());
}
/** Main method */
public static void main(String[] args) {
JFrame frame = new ControlCircle();
frame.setTitle("ControlCircle");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
class EnlargeListener implements ActionListener { // Inner class
@Override
public void actionPerformed(ActionEvent e) {
canvas.enlarge();
}
}
class CirclePanel extends JPanel { // Inner class
private int radius = 5; // Default circle radius
/** Enlarge the circle */
public void enlarge() {
radius++;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
2 * radius, 2 * radius);
}
}
}
| arjitg/java-projects | GUI/ControlCircle.java |
247,664 | /*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Icy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.util;
import icy.painter.PathAnchor2D;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Stephane
*/
public class ShapeUtil
{
public static interface ShapeConsumer
{
public boolean consume(Shape shape);
}
public static enum BooleanOperator
{
OR, AND, XOR
}
/**
* @deprecated Use {@link BooleanOperator} instead.
*/
@Deprecated
public static enum ShapeOperation
{
OR
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.OR;
}
},
AND
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.AND;
}
},
XOR
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.XOR;
}
};
public abstract BooleanOperator getBooleanOperator();
}
/**
* Use the {@link Graphics} clip area and {@link Shape} bounds informations to determine if
* the specified {@link Shape} is visible in the specified Graphics object.
*/
public static boolean isVisible(Graphics g, Shape shape)
{
if (shape == null)
return false;
return GraphicsUtil.isVisible(g, shape.getBounds());
}
/**
* Merge the specified list of {@link Shape} with the given {@link BooleanOperator}.<br>
*
* @param shapes
* Shapes we want to merge.
* @param operator
* {@link BooleanOperator} to apply.
* @return {@link Area} shape representing the result of the merge operation.
*/
public static Area merge(List<Shape> shapes, BooleanOperator operator)
{
final Area result = new Area();
// merge shapes
for (Shape shape : shapes)
{
switch (operator)
{
case OR:
result.add(new Area(shape));
break;
case AND:
result.intersect(new Area(shape));
break;
case XOR:
result.exclusiveOr(new Area(shape));
break;
}
}
return result;
}
/**
* @deprecated Use {@link #merge(List, BooleanOperator)} instead.
*/
@Deprecated
public static Area merge(Shape[] shapes, ShapeOperation operation)
{
return merge(Arrays.asList(shapes), operation.getBooleanOperator());
}
/**
* Do union between the 2 shapes and return result in an {@link Area} type shape.
*/
public static Area union(Shape shape1, Shape shape2)
{
final Area result = new Area(shape1);
result.add(new Area(shape2));
return result;
}
/**
* @deprecated Use {@link #union(Shape, Shape)} instead
*/
@Deprecated
public static Area add(Shape shape1, Shape shape2)
{
return union(shape1, shape2);
}
/**
* Intersect 2 shapes and return result in an {@link Area} type shape.
*/
public static Area intersect(Shape shape1, Shape shape2)
{
final Area result = new Area(shape1);
result.intersect(new Area(shape2));
return result;
}
/**
* Do exclusive union between the 2 shapes and return result in an {@link Area} type shape.
*/
public static Area exclusiveUnion(Shape shape1, Shape shape2)
{
final Area result = new Area(shape1);
result.exclusiveOr(new Area(shape2));
return result;
}
/**
* @deprecated Use {@link #exclusiveUnion(Shape, Shape)} instead.
*/
@Deprecated
public static Area xor(Shape shape1, Shape shape2)
{
return exclusiveUnion(shape1, shape2);
}
/**
* Subtract shape2 from shape1 return result in an {@link Area} type shape.
*/
public static Area subtract(Shape shape1, Shape shape2)
{
final Area result = new Area(shape1);
result.subtract(new Area(shape2));
return result;
}
/**
* Scale the specified {@link RectangularShape} by specified factor.
*
* @param shape
* the {@link RectangularShape} to scale
* @param factor
* the scale factor
* @param centered
* if true then scaling is centered (shape location is modified)
*/
public static void scale(RectangularShape shape, double factor, boolean centered)
{
final double w = shape.getWidth();
final double h = shape.getHeight();
final double newW = w * factor;
final double newH = h * factor;
if (centered)
{
final double deltaW = (newW - w) / 2;
final double deltaH = (newH - h) / 2;
shape.setFrame(shape.getX() - deltaW, shape.getY() - deltaH, newW, newH);
}
else
shape.setFrame(shape.getX(), shape.getY(), newW, newH);
}
/**
* Enlarge the specified {@link RectangularShape} by specified width and height.
*
* @param shape
* the {@link RectangularShape} to scale
* @param width
* the width to add
* @param height
* the height to add
* @param centered
* if true then enlargement is centered (shape location is modified)
*/
public static void enlarge(RectangularShape shape, double width, double height, boolean centered)
{
final double w = shape.getWidth();
final double h = shape.getHeight();
final double newW = w + width;
final double newH = h + height;
if (centered)
{
final double deltaW = (newW - w) / 2;
final double deltaH = (newH - h) / 2;
shape.setFrame(shape.getX() - deltaW, shape.getY() - deltaH, newW, newH);
}
else
shape.setFrame(shape.getX(), shape.getY(), newW, newH);
}
/**
* Translate a rectangular shape by the specified dx and dy value
*/
public static void translate(RectangularShape shape, int dx, int dy)
{
shape.setFrame(shape.getX() + dx, shape.getY() + dy, shape.getWidth(), shape.getHeight());
}
/**
* Translate a rectangular shape by the specified dx and dy value
*/
public static void translate(RectangularShape shape, double dx, double dy)
{
shape.setFrame(shape.getX() + dx, shape.getY() + dy, shape.getWidth(), shape.getHeight());
}
/**
* Permit to describe any PathIterator in a list of Shape which are returned
* to the specified ShapeConsumer
*/
public static boolean consumeShapeFromPath(PathIterator path, ShapeConsumer consumer)
{
final Line2D.Double line = new Line2D.Double();
final QuadCurve2D.Double quadCurve = new QuadCurve2D.Double();
final CubicCurve2D.Double cubicCurve = new CubicCurve2D.Double();
double lastX, lastY, curX, curY, movX, movY;
final double crd[] = new double[6];
curX = 0;
curY = 0;
movX = 0;
movY = 0;
while (!path.isDone())
{
final int segType = path.currentSegment(crd);
lastX = curX;
lastY = curY;
switch (segType)
{
case PathIterator.SEG_MOVETO:
curX = crd[0];
curY = crd[1];
movX = curX;
movY = curY;
break;
case PathIterator.SEG_LINETO:
curX = crd[0];
curY = crd[1];
line.setLine(lastX, lastY, curX, curY);
if (!consumer.consume(line))
return false;
break;
case PathIterator.SEG_QUADTO:
curX = crd[2];
curY = crd[3];
quadCurve.setCurve(lastX, lastY, crd[0], crd[1], curX, curY);
if (!consumer.consume(quadCurve))
return false;
break;
case PathIterator.SEG_CUBICTO:
curX = crd[4];
curY = crd[5];
cubicCurve.setCurve(lastX, lastY, crd[0], crd[1], crd[2], crd[3], curX, curY);
if (!consumer.consume(cubicCurve))
return false;
break;
case PathIterator.SEG_CLOSE:
line.setLine(lastX, lastY, movX, movY);
if (!consumer.consume(line))
return false;
break;
}
path.next();
}
return true;
}
/**
* Return all PathAnchor points from the specified shape
*/
public static ArrayList<PathAnchor2D> getAnchorsFromShape(Shape shape)
{
final PathIterator pathIt = shape.getPathIterator(null);
final ArrayList<PathAnchor2D> result = new ArrayList<PathAnchor2D>();
final double crd[] = new double[6];
final double mov[] = new double[2];
while (!pathIt.isDone())
{
final int segType = pathIt.currentSegment(crd);
PathAnchor2D pt = null;
switch (segType)
{
case PathIterator.SEG_MOVETO:
mov[0] = crd[0];
mov[1] = crd[1];
case PathIterator.SEG_LINETO:
pt = new PathAnchor2D(crd[0], crd[1]);
break;
case PathIterator.SEG_QUADTO:
pt = new PathAnchor2D(crd[0], crd[1], crd[2], crd[3]);
break;
case PathIterator.SEG_CUBICTO:
pt = new PathAnchor2D(crd[0], crd[1], crd[2], crd[3], crd[4], crd[5]);
break;
case PathIterator.SEG_CLOSE:
pt = new PathAnchor2D(mov[0], mov[1]);
// CLOSE points aren't visible
pt.setVisible(false);
break;
}
if (pt != null)
{
pt.setType(segType);
result.add(pt);
}
pathIt.next();
}
return result;
}
/**
* Update specified path from the specified list of PathAnchor2D
*/
public static Path2D buildPathFromAnchors(Path2D path, ArrayList<PathAnchor2D> points)
{
path.reset();
for (PathAnchor2D pt : points)
{
switch (pt.getType())
{
case PathIterator.SEG_MOVETO:
path.moveTo(pt.getX(), pt.getY());
break;
case PathIterator.SEG_LINETO:
path.lineTo(pt.getX(), pt.getY());
break;
case PathIterator.SEG_QUADTO:
path.quadTo(pt.getPosQExtX(), pt.getPosQExtY(), pt.getX(), pt.getY());
break;
case PathIterator.SEG_CUBICTO:
path.curveTo(pt.getPosCExtX(), pt.getPosCExtY(), pt.getPosQExtX(), pt.getPosQExtY(), pt.getX(),
pt.getY());
break;
case PathIterator.SEG_CLOSE:
path.closePath();
break;
}
}
if (points.size() > 0)
path.closePath();
return path;
}
/**
* Create and return a path from the specified list of PathAnchor2D
*/
public static Path2D getPathFromAnchors(ArrayList<PathAnchor2D> points)
{
return buildPathFromAnchors(new Path2D.Double(), points);
}
/**
* @deprecated Use {@link GraphicsUtil#drawPathIterator(PathIterator, Graphics2D)} instead
*/
@Deprecated
public static void drawFromPath(PathIterator path, final Graphics2D g)
{
GraphicsUtil.drawPathIterator(path, g);
}
/**
* Return true if the specified PathIterator intersects with the specified Rectangle
*/
public static boolean pathIntersects(PathIterator path, final Rectangle2D rect)
{
return !consumeShapeFromPath(path, new ShapeConsumer()
{
@Override
public boolean consume(Shape shape)
{
if (shape.intersects(rect))
return false;
return true;
}
});
}
}
| oeway/Icy-Kernel | icy/util/ShapeUtil.java |
247,665 | public class Circle
{
public double x;
public double y;
public double radius;
public Circle(double x, double y, double radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
void enlarge(double f)
{
this.radius *= 2;
}
void getArea()
{
double area = Math.PI * this.radius * this.radius;
System.out.println("The area is: " + area);
}
}
| NicoNL/javaELTE2023 | LAB2/Circle.java |
247,666 | /* */ package sun.awt.geom;
/* */
/* */ import java.awt.geom.Rectangle2D;
/* */ import java.util.Vector;
/* */
/* */ final class Order2 extends Curve
/* */ {
/* */ private double x0;
/* */ private double y0;
/* */ private double cx0;
/* */ private double cy0;
/* */ private double x1;
/* */ private double y1;
/* */ private double xmin;
/* */ private double xmax;
/* */ private double xcoeff0;
/* */ private double xcoeff1;
/* */ private double xcoeff2;
/* */ private double ycoeff0;
/* */ private double ycoeff1;
/* */ private double ycoeff2;
/* */
/* */ public static void insert(Vector paramVector, double[] paramArrayOfDouble, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, int paramInt)
/* */ {
/* 56 */ int i = getHorizontalParams(paramDouble2, paramDouble4, paramDouble6, paramArrayOfDouble);
/* 57 */ if (i == 0)
/* */ {
/* 60 */ addInstance(paramVector, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramInt);
/* 61 */ return;
/* */ }
/* */
/* 64 */ double d = paramArrayOfDouble[0];
/* 65 */ paramArrayOfDouble[0] = paramDouble1; paramArrayOfDouble[1] = paramDouble2;
/* 66 */ paramArrayOfDouble[2] = paramDouble3; paramArrayOfDouble[3] = paramDouble4;
/* 67 */ paramArrayOfDouble[4] = paramDouble5; paramArrayOfDouble[5] = paramDouble6;
/* 68 */ split(paramArrayOfDouble, 0, d);
/* 69 */ int j = paramInt == 1 ? 0 : 4;
/* 70 */ int k = 4 - j;
/* 71 */ addInstance(paramVector, paramArrayOfDouble[j], paramArrayOfDouble[(j + 1)], paramArrayOfDouble[(j + 2)], paramArrayOfDouble[(j + 3)], paramArrayOfDouble[(j + 4)], paramArrayOfDouble[(j + 5)], paramInt);
/* */
/* 73 */ addInstance(paramVector, paramArrayOfDouble[k], paramArrayOfDouble[(k + 1)], paramArrayOfDouble[(k + 2)], paramArrayOfDouble[(k + 3)], paramArrayOfDouble[(k + 4)], paramArrayOfDouble[(k + 5)], paramInt);
/* */ }
/* */
/* */ public static void addInstance(Vector paramVector, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, int paramInt)
/* */ {
/* 82 */ if (paramDouble2 > paramDouble6)
/* 83 */ paramVector.add(new Order2(paramDouble5, paramDouble6, paramDouble3, paramDouble4, paramDouble1, paramDouble2, -paramInt));
/* 84 */ else if (paramDouble6 > paramDouble2)
/* 85 */ paramVector.add(new Order2(paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramInt));
/* */ }
/* */
/* */ public static int getHorizontalParams(double paramDouble1, double paramDouble2, double paramDouble3, double[] paramArrayOfDouble)
/* */ {
/* 113 */ if ((paramDouble1 <= paramDouble2) && (paramDouble2 <= paramDouble3)) {
/* 114 */ return 0;
/* */ }
/* 116 */ paramDouble1 -= paramDouble2;
/* 117 */ paramDouble3 -= paramDouble2;
/* 118 */ double d1 = paramDouble1 + paramDouble3;
/* */
/* 120 */ if (d1 == 0.0D) {
/* 121 */ return 0;
/* */ }
/* 123 */ double d2 = paramDouble1 / d1;
/* */
/* 125 */ if ((d2 <= 0.0D) || (d2 >= 1.0D)) {
/* 126 */ return 0;
/* */ }
/* 128 */ paramArrayOfDouble[0] = d2;
/* 129 */ return 1;
/* */ }
/* */
/* */ public static void split(double[] paramArrayOfDouble, int paramInt, double paramDouble)
/* */ {
/* */ double tmp10_9 = paramArrayOfDouble[(paramInt + 4)]; double d5 = tmp10_9; paramArrayOfDouble[(paramInt + 8)] = tmp10_9;
/* */ double tmp24_23 = paramArrayOfDouble[(paramInt + 5)]; double d6 = tmp24_23; paramArrayOfDouble[(paramInt + 9)] = tmp24_23;
/* 142 */ double d3 = paramArrayOfDouble[(paramInt + 2)];
/* 143 */ double d4 = paramArrayOfDouble[(paramInt + 3)];
/* 144 */ d5 = d3 + (d5 - d3) * paramDouble;
/* 145 */ d6 = d4 + (d6 - d4) * paramDouble;
/* 146 */ double d1 = paramArrayOfDouble[(paramInt + 0)];
/* 147 */ double d2 = paramArrayOfDouble[(paramInt + 1)];
/* 148 */ d1 += (d3 - d1) * paramDouble;
/* 149 */ d2 += (d4 - d2) * paramDouble;
/* 150 */ d3 = d1 + (d5 - d1) * paramDouble;
/* 151 */ d4 = d2 + (d6 - d2) * paramDouble;
/* 152 */ paramArrayOfDouble[(paramInt + 2)] = d1;
/* 153 */ paramArrayOfDouble[(paramInt + 3)] = d2;
/* 154 */ paramArrayOfDouble[(paramInt + 4)] = d3;
/* 155 */ paramArrayOfDouble[(paramInt + 5)] = d4;
/* 156 */ paramArrayOfDouble[(paramInt + 6)] = d5;
/* 157 */ paramArrayOfDouble[(paramInt + 7)] = d6;
/* */ }
/* */
/* */ public Order2(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, int paramInt)
/* */ {
/* 165 */ super(paramInt);
/* */
/* 169 */ if (paramDouble4 < paramDouble2)
/* 170 */ paramDouble4 = paramDouble2;
/* 171 */ else if (paramDouble4 > paramDouble6) {
/* 172 */ paramDouble4 = paramDouble6;
/* */ }
/* 174 */ this.x0 = paramDouble1;
/* 175 */ this.y0 = paramDouble2;
/* 176 */ this.cx0 = paramDouble3;
/* 177 */ this.cy0 = paramDouble4;
/* 178 */ this.x1 = paramDouble5;
/* 179 */ this.y1 = paramDouble6;
/* 180 */ this.xmin = Math.min(Math.min(paramDouble1, paramDouble5), paramDouble3);
/* 181 */ this.xmax = Math.max(Math.max(paramDouble1, paramDouble5), paramDouble3);
/* 182 */ this.xcoeff0 = paramDouble1;
/* 183 */ this.xcoeff1 = (paramDouble3 + paramDouble3 - paramDouble1 - paramDouble1);
/* 184 */ this.xcoeff2 = (paramDouble1 - paramDouble3 - paramDouble3 + paramDouble5);
/* 185 */ this.ycoeff0 = paramDouble2;
/* 186 */ this.ycoeff1 = (paramDouble4 + paramDouble4 - paramDouble2 - paramDouble2);
/* 187 */ this.ycoeff2 = (paramDouble2 - paramDouble4 - paramDouble4 + paramDouble6);
/* */ }
/* */
/* */ public int getOrder() {
/* 191 */ return 2;
/* */ }
/* */
/* */ public double getXTop() {
/* 195 */ return this.x0;
/* */ }
/* */
/* */ public double getYTop() {
/* 199 */ return this.y0;
/* */ }
/* */
/* */ public double getXBot() {
/* 203 */ return this.x1;
/* */ }
/* */
/* */ public double getYBot() {
/* 207 */ return this.y1;
/* */ }
/* */
/* */ public double getXMin() {
/* 211 */ return this.xmin;
/* */ }
/* */
/* */ public double getXMax() {
/* 215 */ return this.xmax;
/* */ }
/* */
/* */ public double getX0() {
/* 219 */ return this.direction == 1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY0() {
/* 223 */ return this.direction == 1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double getCX0() {
/* 227 */ return this.cx0;
/* */ }
/* */
/* */ public double getCY0() {
/* 231 */ return this.cy0;
/* */ }
/* */
/* */ public double getX1() {
/* 235 */ return this.direction == -1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY1() {
/* 239 */ return this.direction == -1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double XforY(double paramDouble) {
/* 243 */ if (paramDouble <= this.y0) {
/* 244 */ return this.x0;
/* */ }
/* 246 */ if (paramDouble >= this.y1) {
/* 247 */ return this.x1;
/* */ }
/* 249 */ return XforT(TforY(paramDouble));
/* */ }
/* */
/* */ public double TforY(double paramDouble) {
/* 253 */ if (paramDouble <= this.y0) {
/* 254 */ return 0.0D;
/* */ }
/* 256 */ if (paramDouble >= this.y1) {
/* 257 */ return 1.0D;
/* */ }
/* 259 */ return TforY(paramDouble, this.ycoeff0, this.ycoeff1, this.ycoeff2);
/* */ }
/* */
/* */ public static double TforY(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4)
/* */ {
/* 267 */ paramDouble2 -= paramDouble1;
/* 268 */ if (paramDouble4 == 0.0D)
/* */ {
/* 274 */ d1 = -paramDouble2 / paramDouble3;
/* 275 */ if ((d1 >= 0.0D) && (d1 <= 1.0D))
/* 276 */ return d1;
/* */ }
/* */ else
/* */ {
/* 280 */ d1 = paramDouble3 * paramDouble3 - 4.0D * paramDouble4 * paramDouble2;
/* */
/* 282 */ if (d1 >= 0.0D) {
/* 283 */ d1 = Math.sqrt(d1);
/* */
/* 290 */ if (paramDouble3 < 0.0D) {
/* 291 */ d1 = -d1;
/* */ }
/* 293 */ d2 = (paramDouble3 + d1) / -2.0D;
/* */
/* 295 */ double d3 = d2 / paramDouble4;
/* 296 */ if ((d3 >= 0.0D) && (d3 <= 1.0D)) {
/* 297 */ return d3;
/* */ }
/* 299 */ if (d2 != 0.0D) {
/* 300 */ d3 = paramDouble2 / d2;
/* 301 */ if ((d3 >= 0.0D) && (d3 <= 1.0D)) {
/* 302 */ return d3;
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* 339 */ double d1 = paramDouble2;
/* 340 */ double d2 = paramDouble2 + paramDouble3 + paramDouble4;
/* 341 */ return 0.0D < (d1 + d2) / 2.0D ? 0.0D : 1.0D;
/* */ }
/* */
/* */ public double XforT(double paramDouble) {
/* 345 */ return (this.xcoeff2 * paramDouble + this.xcoeff1) * paramDouble + this.xcoeff0;
/* */ }
/* */
/* */ public double YforT(double paramDouble) {
/* 349 */ return (this.ycoeff2 * paramDouble + this.ycoeff1) * paramDouble + this.ycoeff0;
/* */ }
/* */
/* */ public double dXforT(double paramDouble, int paramInt) {
/* 353 */ switch (paramInt) {
/* */ case 0:
/* 355 */ return (this.xcoeff2 * paramDouble + this.xcoeff1) * paramDouble + this.xcoeff0;
/* */ case 1:
/* 357 */ return 2.0D * this.xcoeff2 * paramDouble + this.xcoeff1;
/* */ case 2:
/* 359 */ return 2.0D * this.xcoeff2;
/* */ }
/* 361 */ return 0.0D;
/* */ }
/* */
/* */ public double dYforT(double paramDouble, int paramInt)
/* */ {
/* 366 */ switch (paramInt) {
/* */ case 0:
/* 368 */ return (this.ycoeff2 * paramDouble + this.ycoeff1) * paramDouble + this.ycoeff0;
/* */ case 1:
/* 370 */ return 2.0D * this.ycoeff2 * paramDouble + this.ycoeff1;
/* */ case 2:
/* 372 */ return 2.0D * this.ycoeff2;
/* */ }
/* 374 */ return 0.0D;
/* */ }
/* */
/* */ public double nextVertical(double paramDouble1, double paramDouble2)
/* */ {
/* 379 */ double d = -this.xcoeff1 / (2.0D * this.xcoeff2);
/* 380 */ if ((d > paramDouble1) && (d < paramDouble2)) {
/* 381 */ return d;
/* */ }
/* 383 */ return paramDouble2;
/* */ }
/* */
/* */ public void enlarge(Rectangle2D paramRectangle2D) {
/* 387 */ paramRectangle2D.add(this.x0, this.y0);
/* 388 */ double d = -this.xcoeff1 / (2.0D * this.xcoeff2);
/* 389 */ if ((d > 0.0D) && (d < 1.0D)) {
/* 390 */ paramRectangle2D.add(XforT(d), YforT(d));
/* */ }
/* 392 */ paramRectangle2D.add(this.x1, this.y1);
/* */ }
/* */
/* */ public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt)
/* */ {
/* */ double d1;
/* 397 */ if (paramDouble1 <= this.y0) {
/* 398 */ if (paramDouble2 >= this.y1) {
/* 399 */ return getWithDirection(paramInt);
/* */ }
/* 401 */ d1 = 0.0D;
/* */ } else {
/* 403 */ d1 = TforY(paramDouble1, this.ycoeff0, this.ycoeff1, this.ycoeff2);
/* */ }
/* */ double d2;
/* 405 */ if (paramDouble2 >= this.y1)
/* 406 */ d2 = 1.0D;
/* */ else {
/* 408 */ d2 = TforY(paramDouble2, this.ycoeff0, this.ycoeff1, this.ycoeff2);
/* */ }
/* 410 */ double[] arrayOfDouble = new double[10];
/* 411 */ arrayOfDouble[0] = this.x0;
/* 412 */ arrayOfDouble[1] = this.y0;
/* 413 */ arrayOfDouble[2] = this.cx0;
/* 414 */ arrayOfDouble[3] = this.cy0;
/* 415 */ arrayOfDouble[4] = this.x1;
/* 416 */ arrayOfDouble[5] = this.y1;
/* 417 */ if (d2 < 1.0D)
/* 418 */ split(arrayOfDouble, 0, d2);
/* */ int i;
/* 421 */ if (d1 <= 0.0D) {
/* 422 */ i = 0;
/* */ } else {
/* 424 */ split(arrayOfDouble, 0, d1 / d2);
/* 425 */ i = 4;
/* */ }
/* 427 */ return new Order2(arrayOfDouble[(i + 0)], paramDouble1, arrayOfDouble[(i + 2)], arrayOfDouble[(i + 3)], arrayOfDouble[(i + 4)], paramDouble2, paramInt);
/* */ }
/* */
/* */ public Curve getReversedCurve()
/* */ {
/* 434 */ return new Order2(this.x0, this.y0, this.cx0, this.cy0, this.x1, this.y1, -this.direction);
/* */ }
/* */
/* */ public int getSegment(double[] paramArrayOfDouble) {
/* 438 */ paramArrayOfDouble[0] = this.cx0;
/* 439 */ paramArrayOfDouble[1] = this.cy0;
/* 440 */ if (this.direction == 1) {
/* 441 */ paramArrayOfDouble[2] = this.x1;
/* 442 */ paramArrayOfDouble[3] = this.y1;
/* */ } else {
/* 444 */ paramArrayOfDouble[2] = this.x0;
/* 445 */ paramArrayOfDouble[3] = this.y0;
/* */ }
/* 447 */ return 2;
/* */ }
/* */
/* */ public String controlPointString() {
/* 451 */ return "(" + round(this.cx0) + ", " + round(this.cy0) + "), ";
/* */ }
/* */ }
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: sun.awt.geom.Order2
* JD-Core Version: 0.6.2
*/ | yuexiahandao/RT-JAR-CODE | sun/awt/geom/Order2.java |
247,667 | import java.io.*;
import java.util.HashMap;
import java.util.Queue;
import java.util.ArrayDeque;
import java.util.ArrayList;
/**
* Adjacency matrix implementation for the FriendshipGraph interface.
*
* Your task is to complete the implementation of this class. You may add methods, but ensure your modified class compiles and runs.
*
* @author Jeffrey Chan, 2016.
*/
public class AdjMatrix <T extends Object> implements FriendshipGraph<T>
{
private static final int gSize = 10;
private static final boolean preBuildGraph = false;
private static final boolean allowGraphLoops = false;
private static final boolean printOutput = false;
private HashMap<String, Integer> indexer = new HashMap<String, Integer>();
private sArray[] adjMatRows;
/**
* Contructs prefilled or empty graph.
*/
public AdjMatrix() {
if (preBuildGraph) {
adjMatRows = new sArray[gSize];
for (int i=0; i<gSize; i++) {
adjMatRows[i] = new sArray(gSize);
adjMatRows[i].setLabel(String.valueOf(i));
indexer.put(String.valueOf(i), i);
}
} else {
adjMatRows = new sArray[0];
}
} // end of AdjMatrix()
/**
* We are assuming the Adjacency Matrix is a square.
*/
public void addVertex(T vertLabel) {
//if (adjMatRows == null) return;
if (getIntVal(vertLabel) < 0) System.err.println("Value must convert to a positive integer.");
//If Vertex already exists, do not add it again;
if (checkForVertex(vertLabel)) {
//System.err.println("Vertex already exists, not being added. Nothing done.");
return;
}
//Array needs to be dynamic so initially unset
//But here we check for it beuing set, if not create it
if (adjMatRows == null) {
adjMatRows = new sArray[1];
adjMatRows[0] = new sArray(1);
adjMatRows[0].setLabel("0");
indexer.put("0", 0);
}
for (int i=0; i<adjMatRows.length; i++) {
adjMatRows[i].expand();
}
enlarge(String.valueOf(vertLabel));
indexer.put(String.valueOf(vertLabel), indexer.size());
output();
} // end of addVertex()
public void addEdge(T srcLabel, T tarLabel) {
//Check for loop allowance
//if (adjMatRows == null) return;
if (!allowGraphLoops && String.valueOf(srcLabel).equals(String.valueOf(tarLabel)) ) {
return;
}
//Ensure vertices exist, else create them
if (indexer.get(String.valueOf(srcLabel)) == null) {
addVertex(srcLabel);
}
if (indexer.get(String.valueOf(tarLabel)) == null) {
addVertex(tarLabel);
}
//get indexes of corresponding edge in vertex
int srcI = getVertexIndex(String.valueOf(srcLabel));
int tarI = getVertexIndex(String.valueOf(tarLabel));
if (adjMatRows[srcI].getEdge(tarI) == 1 && adjMatRows[tarI].getEdge(srcI) == 1) {
System.err.println("Edge already exists, not being added. Nothing done.");
return;
}
//Set connection in corresponding vertex
int edgeVal = adjMatRows[srcI].getHasEdgeValue();
adjMatRows[srcI].setEdge(tarI, edgeVal);
adjMatRows[tarI].setEdge(srcI, edgeVal);
output();
} // end of addEdge()
@SuppressWarnings("unchecked")
public ArrayList<T> neighbours(T vertLabel) {
ArrayList<T> neighbours = new ArrayList<T>();
if (!checkForVertex(vertLabel)) {
//System.err.println("Vertex does not exist or is invalid.");
return neighbours;
}
int vertI = getVertexIndex(String.valueOf(vertLabel));
if (vertI == -1) return null;
for (int i=0; i<adjMatRows[vertI].getSize(); i++) {
if (adjMatRows[vertI].getEdge(i) == 1) {
neighbours.add((T) String.valueOf(i));
}
}
neighbours = getNeighbours(String.valueOf(vertLabel));
return neighbours;
} // end of neighbours()
public void removeVertex(T vertLabel) {
int newI = 0;
if (!checkForVertex(vertLabel)) {
System.err.println("Vertex does not exist or is invalid.");
return;
}
int tarI = getVertexIndex(String.valueOf(vertLabel));
//remove lookup reference in hashmap
indexer.remove(String.valueOf(vertLabel));
//remove corresponding matrix 'row'
sArray[] newrows = new sArray[adjMatRows.length-1];
for (int i=0; i<adjMatRows.length; i++) {
adjMatRows[i].remove(tarI);
if (i != tarI) {
newrows[newI] = new sArray(adjMatRows[i].getSize());
newrows[newI] = adjMatRows[i];
newI++;
}
}
adjMatRows = new sArray[newrows.length];
adjMatRows = newrows;
output();
} // end of removeVertex()
public void removeEdge(T srcLabel, T tarLabel) {
//if (adjMatRows == null) return;
if (!checkForVertex(srcLabel) || !checkForVertex(tarLabel)) {
System.err.println("Vertex parameters are invalid.");
return;
}
//get indexes of corresponding vertex
int srcI = getVertexIndex(String.valueOf(srcLabel));
int tarI = getVertexIndex(String.valueOf(tarLabel));
if (adjMatRows[srcI].getEdge(tarI) == 0 && adjMatRows[tarI].getEdge(srcI) == 0) {
System.err.println("No relationship exists. Nothing done.");
return;
}
//Reset edge value to 'no connection'
int edgeVal = adjMatRows[srcI].getNoEdgeValue();
adjMatRows[srcI].setEdge(tarI, edgeVal);
adjMatRows[tarI].setEdge(srcI, edgeVal);
output();
} // end of removeEdges()
public void printVertices(PrintWriter os) {
if ( os != null ) {
for (int i=0; i<adjMatRows.length; i++) {
os.print(adjMatRows[i].getLabel() + " ");
}
}
} // end of printVertices()
public void printEdges(PrintWriter os) {
if (os != null) {
for (int i=0; i<adjMatRows.length; i++) {
for (int j=0; j<adjMatRows[i].getSize(); j++) {
if (adjMatRows[i].getEdge(j) == 1) {
os.print(adjMatRows[i].getLabel() + " " + adjMatRows[j].getLabel());
System.out.println(adjMatRows[i].getLabel() + " " + adjMatRows[j].getLabel());
}
}
}
}
} // end of printEdges()
public int shortestPathDistance(T vertLabel1, T vertLabel2) {
int spd = 0;
//If Start vertex and End vertex are same. return 0;
if (String.valueOf(vertLabel1).equals(String.valueOf(vertLabel2))) {
return spd;
}
HashMap<String, Integer> visited = new HashMap<String, Integer>();
HashMap<String, Integer> referenced = new HashMap<String, Integer>();
Queue<String> daQ = new ArrayDeque<>();
Boolean incremented = false;
//Prime Queue with source vertex;
//Using Strings for Hashmap lookup
daQ.add(String.valueOf(vertLabel1));
referenced.put(String.valueOf(vertLabel1), spd);
visited.put(String.valueOf(vertLabel1), 1);
String current = String.valueOf(vertLabel1);
while(daQ.size() != 0) {
current = daQ.poll();
//Check if current node is the target
if(current.equals(String.valueOf(vertLabel2))) {
return spd;
}
//Get neighbours of currently selected node;
ArrayList<T> neighbours = new ArrayList<>(getNeighbours(current));
if(neighbours.size() == 0) {
return spd;
}
//ADD to hashmap of current and children so as to not increment path distance per beighbour
incremented = false;
for (int a=0; a<neighbours.size(); a++) {
if (referenced.get(String.valueOf(current)) == null || referenced.get(String.valueOf(neighbours.get(a))) == null) {
referenced.put(String.valueOf(neighbours.get(a)), spd);
if (!incremented) {
spd++;
incremented = true;
}
}
}
for (int a=0; a<neighbours.size(); a++) {
//EXIT IF Neighbour is the target node. Clear queue and return path distance.
if(String.valueOf(neighbours.get(a)).equals(String.valueOf(vertLabel2))) {
daQ.clear();
return spd;
}
//ADD current neighbour to visited list
if (visited.get(String.valueOf(neighbours.get(a))) == null) {
visited.put(String.valueOf(neighbours.get(a)), spd);
daQ.add(String.valueOf(neighbours.get(a)));
}
}
}
return disconnectedDist;
}
/**
* Adjacency Matrix helpers
* Written by
* Mark Scicluna
*
*/
private Boolean checkForVertex(T vertLabel) {
if (getIntVal(vertLabel) < 0 || indexer.get(String.valueOf(vertLabel)) == null) {
return false;
}
return true;
}
private int getIntVal(T vertLabel) {
if (Character.isLetter(((String) vertLabel).charAt(0))) {
char c = ((String) vertLabel).charAt(0);
return Character.getNumericValue(c);
} else {
return Integer.parseInt((String) vertLabel);
}
}
@SuppressWarnings("unchecked")
private ArrayList<T> getNeighbours(String vertLabel) {
ArrayList<T> neighbours = new ArrayList<T>();
int vertI = getVertexIndex(vertLabel);
if (vertI == -1) return null;
for (int i=0; i<adjMatRows[vertI].getSize(); i++) {
if (adjMatRows[vertI].getEdge(i) == 1) {
neighbours.add((T) adjMatRows[i].getLabel());
}
}
return neighbours;
}
private int getVertexIndex(String label) {
for (int i=0; i<adjMatRows.length; i++) {
String c = (String) adjMatRows[i].getLabel();
if (c.equals(label)) {
return i;
}
}
return -1;
}
private int getDensity() {
if (adjMatRows == null) return 0;//-1 ?
int edgyCount = 0;
for (int i=0; i<adjMatRows.length; i++) {
for (int j=0; j<adjMatRows[i].getSize(); j++) {
if (adjMatRows[i].getEdge(j) == adjMatRows[i].getHasEdgeValue()) {
edgyCount++;
}
}
}
int avg = (int) Math.ceil((double)edgyCount / adjMatRows.length);
return avg ;
};
private int getSize() {
return adjMatRows.length;
};
private void enlarge(String label) {
sArray[] copy = new sArray[adjMatRows.length];
copy = adjMatRows;
adjMatRows = new sArray[copy.length+1];
for (int i=0; i<copy.length; i++) {
adjMatRows[i] = copy[i];
}
adjMatRows[adjMatRows.length-1] = new sArray(adjMatRows.length);
adjMatRows[adjMatRows.length-1].setLabel(label);
}
/**
* Debug/Visualisation.
* Can get fairly unwieldy for large samples...
* Hence intial conditions for allowing output.
* But good for small samples to test functionality.
*
*/
public void output() {
if (!printOutput) return;
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter("testing/current_graph.txt");
printWriter.print(" ");
System.out.print(" ");
for (int j=0; j<(adjMatRows[0].getSize()); j++) {
printWriter.print(adjMatRows[j].getLabel() + " ");
System.out.print(adjMatRows[j].getLabel() + " ");
}
printWriter.println("");
System.out.println("");
for (int i=0; i<(adjMatRows.length); i++) {
printWriter.print(adjMatRows[i].getLabel() + " ");
System.out.print(adjMatRows[i].getLabel() + " ");
for (int j=0; j<(adjMatRows[i].getSize()); j++) {
printWriter.print(adjMatRows[i].getEdge(j) + " ");
System.out.print(adjMatRows[i].getEdge(j) + " ");
}
printWriter.println("");
System.out.println("");
}
printWriter.println("");
System.out.println("");
printWriter.println("DENSITY (avg): " + getDensity() +"%");
printWriter.println("SIZE: " + getSize());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
} // end of class AdjMatrix | carkus/AA_Assignment1 | src/AdjMatrix.java |
247,668 | /* */ package sun.awt.geom;
/* */
/* */ import java.awt.geom.QuadCurve2D;
/* */ import java.awt.geom.Rectangle2D;
/* */ import java.util.Vector;
/* */
/* */ final class Order3 extends Curve
/* */ {
/* */ private double x0;
/* */ private double y0;
/* */ private double cx0;
/* */ private double cy0;
/* */ private double cx1;
/* */ private double cy1;
/* */ private double x1;
/* */ private double y1;
/* */ private double xmin;
/* */ private double xmax;
/* */ private double xcoeff0;
/* */ private double xcoeff1;
/* */ private double xcoeff2;
/* */ private double xcoeff3;
/* */ private double ycoeff0;
/* */ private double ycoeff1;
/* */ private double ycoeff2;
/* */ private double ycoeff3;
/* */ private double TforY1;
/* */ private double YforT1;
/* */ private double TforY2;
/* */ private double YforT2;
/* */ private double TforY3;
/* */ private double YforT3;
/* */
/* */ public static void insert(Vector paramVector, double[] paramArrayOfDouble, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, int paramInt)
/* */ {
/* 63 */ int i = getHorizontalParams(paramDouble2, paramDouble4, paramDouble6, paramDouble8, paramArrayOfDouble);
/* 64 */ if (i == 0)
/* */ {
/* 67 */ addInstance(paramVector, paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble7, paramDouble8, paramInt);
/* 68 */ return;
/* */ }
/* */
/* 71 */ paramArrayOfDouble[3] = paramDouble1; paramArrayOfDouble[4] = paramDouble2;
/* 72 */ paramArrayOfDouble[5] = paramDouble3; paramArrayOfDouble[6] = paramDouble4;
/* 73 */ paramArrayOfDouble[7] = paramDouble5; paramArrayOfDouble[8] = paramDouble6;
/* 74 */ paramArrayOfDouble[9] = paramDouble7; paramArrayOfDouble[10] = paramDouble8;
/* 75 */ double d = paramArrayOfDouble[0];
/* 76 */ if ((i > 1) && (d > paramArrayOfDouble[1]))
/* */ {
/* 78 */ paramArrayOfDouble[0] = paramArrayOfDouble[1];
/* 79 */ paramArrayOfDouble[1] = d;
/* 80 */ d = paramArrayOfDouble[0];
/* */ }
/* 82 */ split(paramArrayOfDouble, 3, d);
/* 83 */ if (i > 1)
/* */ {
/* 85 */ d = (paramArrayOfDouble[1] - d) / (1.0D - d);
/* 86 */ split(paramArrayOfDouble, 9, d);
/* */ }
/* 88 */ int j = 3;
/* 89 */ if (paramInt == -1) {
/* 90 */ j += i * 6;
/* */ }
/* 92 */ while (i >= 0) {
/* 93 */ addInstance(paramVector, paramArrayOfDouble[(j + 0)], paramArrayOfDouble[(j + 1)], paramArrayOfDouble[(j + 2)], paramArrayOfDouble[(j + 3)], paramArrayOfDouble[(j + 4)], paramArrayOfDouble[(j + 5)], paramArrayOfDouble[(j + 6)], paramArrayOfDouble[(j + 7)], paramInt);
/* */
/* 99 */ i--;
/* 100 */ if (paramInt == 1)
/* 101 */ j += 6;
/* */ else
/* 103 */ j -= 6;
/* */ }
/* */ }
/* */
/* */ public static void addInstance(Vector paramVector, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, int paramInt)
/* */ {
/* 114 */ if (paramDouble2 > paramDouble8) {
/* 115 */ paramVector.add(new Order3(paramDouble7, paramDouble8, paramDouble5, paramDouble6, paramDouble3, paramDouble4, paramDouble1, paramDouble2, -paramInt));
/* */ }
/* 117 */ else if (paramDouble8 > paramDouble2)
/* 118 */ paramVector.add(new Order3(paramDouble1, paramDouble2, paramDouble3, paramDouble4, paramDouble5, paramDouble6, paramDouble7, paramDouble8, paramInt));
/* */ }
/* */
/* */ public static int getHorizontalParams(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double[] paramArrayOfDouble)
/* */ {
/* 164 */ if ((paramDouble1 <= paramDouble2) && (paramDouble2 <= paramDouble3) && (paramDouble3 <= paramDouble4)) {
/* 165 */ return 0;
/* */ }
/* 167 */ paramDouble4 -= paramDouble3;
/* 168 */ paramDouble3 -= paramDouble2;
/* 169 */ paramDouble2 -= paramDouble1;
/* 170 */ paramArrayOfDouble[0] = paramDouble2;
/* 171 */ paramArrayOfDouble[1] = ((paramDouble3 - paramDouble2) * 2.0D);
/* 172 */ paramArrayOfDouble[2] = (paramDouble4 - paramDouble3 - paramDouble3 + paramDouble2);
/* 173 */ int i = QuadCurve2D.solveQuadratic(paramArrayOfDouble, paramArrayOfDouble);
/* 174 */ int j = 0;
/* 175 */ for (int k = 0; k < i; k++) {
/* 176 */ double d = paramArrayOfDouble[k];
/* */
/* 178 */ if ((d > 0.0D) && (d < 1.0D)) {
/* 179 */ if (j < k) {
/* 180 */ paramArrayOfDouble[j] = d;
/* */ }
/* 182 */ j++;
/* */ }
/* */ }
/* 185 */ return j;
/* */ }
/* */
/* */ public static void split(double[] paramArrayOfDouble, int paramInt, double paramDouble)
/* */ {
/* */ double tmp11_10 = paramArrayOfDouble[(paramInt + 6)]; double d7 = tmp11_10; paramArrayOfDouble[(paramInt + 12)] = tmp11_10;
/* */ double tmp26_25 = paramArrayOfDouble[(paramInt + 7)]; double d8 = tmp26_25; paramArrayOfDouble[(paramInt + 13)] = tmp26_25;
/* 198 */ double d5 = paramArrayOfDouble[(paramInt + 4)];
/* 199 */ double d6 = paramArrayOfDouble[(paramInt + 5)];
/* 200 */ d7 = d5 + (d7 - d5) * paramDouble;
/* 201 */ d8 = d6 + (d8 - d6) * paramDouble;
/* 202 */ double d1 = paramArrayOfDouble[(paramInt + 0)];
/* 203 */ double d2 = paramArrayOfDouble[(paramInt + 1)];
/* 204 */ double d3 = paramArrayOfDouble[(paramInt + 2)];
/* 205 */ double d4 = paramArrayOfDouble[(paramInt + 3)];
/* 206 */ d1 += (d3 - d1) * paramDouble;
/* 207 */ d2 += (d4 - d2) * paramDouble;
/* 208 */ d3 += (d5 - d3) * paramDouble;
/* 209 */ d4 += (d6 - d4) * paramDouble;
/* 210 */ d5 = d3 + (d7 - d3) * paramDouble;
/* 211 */ d6 = d4 + (d8 - d4) * paramDouble;
/* 212 */ d3 = d1 + (d3 - d1) * paramDouble;
/* 213 */ d4 = d2 + (d4 - d2) * paramDouble;
/* 214 */ paramArrayOfDouble[(paramInt + 2)] = d1;
/* 215 */ paramArrayOfDouble[(paramInt + 3)] = d2;
/* 216 */ paramArrayOfDouble[(paramInt + 4)] = d3;
/* 217 */ paramArrayOfDouble[(paramInt + 5)] = d4;
/* 218 */ paramArrayOfDouble[(paramInt + 6)] = (d3 + (d5 - d3) * paramDouble);
/* 219 */ paramArrayOfDouble[(paramInt + 7)] = (d4 + (d6 - d4) * paramDouble);
/* 220 */ paramArrayOfDouble[(paramInt + 8)] = d5;
/* 221 */ paramArrayOfDouble[(paramInt + 9)] = d6;
/* 222 */ paramArrayOfDouble[(paramInt + 10)] = d7;
/* 223 */ paramArrayOfDouble[(paramInt + 11)] = d8;
/* */ }
/* */
/* */ public Order3(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, double paramDouble7, double paramDouble8, int paramInt)
/* */ {
/* 232 */ super(paramInt);
/* */
/* 236 */ if (paramDouble4 < paramDouble2) paramDouble4 = paramDouble2;
/* 237 */ if (paramDouble6 > paramDouble8) paramDouble6 = paramDouble8;
/* 238 */ this.x0 = paramDouble1;
/* 239 */ this.y0 = paramDouble2;
/* 240 */ this.cx0 = paramDouble3;
/* 241 */ this.cy0 = paramDouble4;
/* 242 */ this.cx1 = paramDouble5;
/* 243 */ this.cy1 = paramDouble6;
/* 244 */ this.x1 = paramDouble7;
/* 245 */ this.y1 = paramDouble8;
/* 246 */ this.xmin = Math.min(Math.min(paramDouble1, paramDouble7), Math.min(paramDouble3, paramDouble5));
/* 247 */ this.xmax = Math.max(Math.max(paramDouble1, paramDouble7), Math.max(paramDouble3, paramDouble5));
/* 248 */ this.xcoeff0 = paramDouble1;
/* 249 */ this.xcoeff1 = ((paramDouble3 - paramDouble1) * 3.0D);
/* 250 */ this.xcoeff2 = ((paramDouble5 - paramDouble3 - paramDouble3 + paramDouble1) * 3.0D);
/* 251 */ this.xcoeff3 = (paramDouble7 - (paramDouble5 - paramDouble3) * 3.0D - paramDouble1);
/* 252 */ this.ycoeff0 = paramDouble2;
/* 253 */ this.ycoeff1 = ((paramDouble4 - paramDouble2) * 3.0D);
/* 254 */ this.ycoeff2 = ((paramDouble6 - paramDouble4 - paramDouble4 + paramDouble2) * 3.0D);
/* 255 */ this.ycoeff3 = (paramDouble8 - (paramDouble6 - paramDouble4) * 3.0D - paramDouble2);
/* 256 */ this.YforT1 = (this.YforT2 = this.YforT3 = paramDouble2);
/* */ }
/* */
/* */ public int getOrder() {
/* 260 */ return 3;
/* */ }
/* */
/* */ public double getXTop() {
/* 264 */ return this.x0;
/* */ }
/* */
/* */ public double getYTop() {
/* 268 */ return this.y0;
/* */ }
/* */
/* */ public double getXBot() {
/* 272 */ return this.x1;
/* */ }
/* */
/* */ public double getYBot() {
/* 276 */ return this.y1;
/* */ }
/* */
/* */ public double getXMin() {
/* 280 */ return this.xmin;
/* */ }
/* */
/* */ public double getXMax() {
/* 284 */ return this.xmax;
/* */ }
/* */
/* */ public double getX0() {
/* 288 */ return this.direction == 1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY0() {
/* 292 */ return this.direction == 1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double getCX0() {
/* 296 */ return this.direction == 1 ? this.cx0 : this.cx1;
/* */ }
/* */
/* */ public double getCY0() {
/* 300 */ return this.direction == 1 ? this.cy0 : this.cy1;
/* */ }
/* */
/* */ public double getCX1() {
/* 304 */ return this.direction == -1 ? this.cx0 : this.cx1;
/* */ }
/* */
/* */ public double getCY1() {
/* 308 */ return this.direction == -1 ? this.cy0 : this.cy1;
/* */ }
/* */
/* */ public double getX1() {
/* 312 */ return this.direction == -1 ? this.x0 : this.x1;
/* */ }
/* */
/* */ public double getY1() {
/* 316 */ return this.direction == -1 ? this.y0 : this.y1;
/* */ }
/* */
/* */ public double TforY(double paramDouble)
/* */ {
/* 334 */ if (paramDouble <= this.y0) return 0.0D;
/* 335 */ if (paramDouble >= this.y1) return 1.0D;
/* 336 */ if (paramDouble == this.YforT1) return this.TforY1;
/* 337 */ if (paramDouble == this.YforT2) return this.TforY2;
/* 338 */ if (paramDouble == this.YforT3) return this.TforY3;
/* */
/* 340 */ if (this.ycoeff3 == 0.0D)
/* */ {
/* 342 */ return Order2.TforY(paramDouble, this.ycoeff0, this.ycoeff1, this.ycoeff2);
/* */ }
/* 344 */ double d1 = this.ycoeff2 / this.ycoeff3;
/* 345 */ double d2 = this.ycoeff1 / this.ycoeff3;
/* 346 */ double d3 = (this.ycoeff0 - paramDouble) / this.ycoeff3;
/* 347 */ int i = 0;
/* 348 */ double d4 = (d1 * d1 - 3.0D * d2) / 9.0D;
/* 349 */ double d5 = (2.0D * d1 * d1 * d1 - 9.0D * d1 * d2 + 27.0D * d3) / 54.0D;
/* 350 */ double d6 = d5 * d5;
/* 351 */ double d7 = d4 * d4 * d4;
/* 352 */ double d8 = d1 / 3.0D;
/* */ double d9;
/* 354 */ if (d6 < d7) {
/* 355 */ double d10 = Math.acos(d5 / Math.sqrt(d7));
/* 356 */ d4 = -2.0D * Math.sqrt(d4);
/* 357 */ d9 = refine(d1, d2, d3, paramDouble, d4 * Math.cos(d10 / 3.0D) - d8);
/* 358 */ if (d9 < 0.0D) {
/* 359 */ d9 = refine(d1, d2, d3, paramDouble, d4 * Math.cos((d10 + 6.283185307179586D) / 3.0D) - d8);
/* */ }
/* */
/* 362 */ if (d9 < 0.0D)
/* 363 */ d9 = refine(d1, d2, d3, paramDouble, d4 * Math.cos((d10 - 6.283185307179586D) / 3.0D) - d8);
/* */ }
/* */ else
/* */ {
/* 367 */ int j = d5 < 0.0D ? 1 : 0;
/* 368 */ double d12 = Math.sqrt(d6 - d7);
/* 369 */ if (j != 0) {
/* 370 */ d5 = -d5;
/* */ }
/* 372 */ double d14 = Math.pow(d5 + d12, 0.3333333333333333D);
/* 373 */ if (j == 0) {
/* 374 */ d14 = -d14;
/* */ }
/* 376 */ double d16 = d14 == 0.0D ? 0.0D : d4 / d14;
/* 377 */ d9 = refine(d1, d2, d3, paramDouble, d14 + d16 - d8);
/* */ }
/* 379 */ if (d9 < 0.0D)
/* */ {
/* 381 */ double d11 = 0.0D;
/* 382 */ double d13 = 1.0D;
/* */ while (true) {
/* 384 */ d9 = (d11 + d13) / 2.0D;
/* 385 */ if ((d9 == d11) || (d9 == d13)) {
/* */ break;
/* */ }
/* 388 */ double d15 = YforT(d9);
/* 389 */ if (d15 < paramDouble) {
/* 390 */ d11 = d9; } else {
/* 391 */ if (d15 <= paramDouble) break;
/* 392 */ d13 = d9;
/* */ }
/* */ }
/* */
/* */ }
/* */
/* 398 */ if (d9 >= 0.0D) {
/* 399 */ this.TforY3 = this.TforY2;
/* 400 */ this.YforT3 = this.YforT2;
/* 401 */ this.TforY2 = this.TforY1;
/* 402 */ this.YforT2 = this.YforT1;
/* 403 */ this.TforY1 = d9;
/* 404 */ this.YforT1 = paramDouble;
/* */ }
/* 406 */ return d9;
/* */ }
/* */
/* */ public double refine(double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5)
/* */ {
/* 412 */ if ((paramDouble5 < -0.1D) || (paramDouble5 > 1.1D)) {
/* 413 */ return -1.0D;
/* */ }
/* 415 */ double d1 = YforT(paramDouble5);
/* */ double d2;
/* */ double d3;
/* 417 */ if (d1 < paramDouble4) {
/* 418 */ d2 = paramDouble5;
/* 419 */ d3 = 1.0D;
/* */ } else {
/* 421 */ d2 = 0.0D;
/* 422 */ d3 = paramDouble5;
/* */ }
/* 424 */ double d4 = paramDouble5;
/* 425 */ double d5 = d1;
/* 426 */ int i = 1;
/* 427 */ while (d1 != paramDouble4)
/* */ {
/* */ double d6;
/* 428 */ if (i == 0) {
/* 429 */ d6 = (d2 + d3) / 2.0D;
/* 430 */ if ((d6 == d2) || (d6 == d3)) {
/* */ break;
/* */ }
/* 433 */ paramDouble5 = d6;
/* */ } else {
/* 435 */ d6 = dYforT(paramDouble5, 1);
/* 436 */ if (d6 == 0.0D) {
/* 437 */ i = 0;
/* 438 */ continue;
/* */ }
/* 440 */ double d7 = paramDouble5 + (paramDouble4 - d1) / d6;
/* 441 */ if ((d7 == paramDouble5) || (d7 <= d2) || (d7 >= d3)) {
/* 442 */ i = 0;
/* 443 */ continue;
/* */ }
/* 445 */ paramDouble5 = d7;
/* */ }
/* 447 */ d1 = YforT(paramDouble5);
/* 448 */ if (d1 < paramDouble4) {
/* 449 */ d2 = paramDouble5; } else {
/* 450 */ if (d1 <= paramDouble4) break;
/* 451 */ d3 = paramDouble5;
/* */ }
/* */
/* */ }
/* */
/* 456 */ int j = 0;
/* */
/* 480 */ return paramDouble5 > 1.0D ? -1.0D : paramDouble5;
/* */ }
/* */
/* */ public double XforY(double paramDouble) {
/* 484 */ if (paramDouble <= this.y0) {
/* 485 */ return this.x0;
/* */ }
/* 487 */ if (paramDouble >= this.y1) {
/* 488 */ return this.x1;
/* */ }
/* 490 */ return XforT(TforY(paramDouble));
/* */ }
/* */
/* */ public double XforT(double paramDouble) {
/* 494 */ return ((this.xcoeff3 * paramDouble + this.xcoeff2) * paramDouble + this.xcoeff1) * paramDouble + this.xcoeff0;
/* */ }
/* */
/* */ public double YforT(double paramDouble) {
/* 498 */ return ((this.ycoeff3 * paramDouble + this.ycoeff2) * paramDouble + this.ycoeff1) * paramDouble + this.ycoeff0;
/* */ }
/* */
/* */ public double dXforT(double paramDouble, int paramInt) {
/* 502 */ switch (paramInt) {
/* */ case 0:
/* 504 */ return ((this.xcoeff3 * paramDouble + this.xcoeff2) * paramDouble + this.xcoeff1) * paramDouble + this.xcoeff0;
/* */ case 1:
/* 506 */ return (3.0D * this.xcoeff3 * paramDouble + 2.0D * this.xcoeff2) * paramDouble + this.xcoeff1;
/* */ case 2:
/* 508 */ return 6.0D * this.xcoeff3 * paramDouble + 2.0D * this.xcoeff2;
/* */ case 3:
/* 510 */ return 6.0D * this.xcoeff3;
/* */ }
/* 512 */ return 0.0D;
/* */ }
/* */
/* */ public double dYforT(double paramDouble, int paramInt)
/* */ {
/* 517 */ switch (paramInt) {
/* */ case 0:
/* 519 */ return ((this.ycoeff3 * paramDouble + this.ycoeff2) * paramDouble + this.ycoeff1) * paramDouble + this.ycoeff0;
/* */ case 1:
/* 521 */ return (3.0D * this.ycoeff3 * paramDouble + 2.0D * this.ycoeff2) * paramDouble + this.ycoeff1;
/* */ case 2:
/* 523 */ return 6.0D * this.ycoeff3 * paramDouble + 2.0D * this.ycoeff2;
/* */ case 3:
/* 525 */ return 6.0D * this.ycoeff3;
/* */ }
/* 527 */ return 0.0D;
/* */ }
/* */
/* */ public double nextVertical(double paramDouble1, double paramDouble2)
/* */ {
/* 532 */ double[] arrayOfDouble = { this.xcoeff1, 2.0D * this.xcoeff2, 3.0D * this.xcoeff3 };
/* 533 */ int i = QuadCurve2D.solveQuadratic(arrayOfDouble, arrayOfDouble);
/* 534 */ for (int j = 0; j < i; j++) {
/* 535 */ if ((arrayOfDouble[j] > paramDouble1) && (arrayOfDouble[j] < paramDouble2)) {
/* 536 */ paramDouble2 = arrayOfDouble[j];
/* */ }
/* */ }
/* 539 */ return paramDouble2;
/* */ }
/* */
/* */ public void enlarge(Rectangle2D paramRectangle2D) {
/* 543 */ paramRectangle2D.add(this.x0, this.y0);
/* 544 */ double[] arrayOfDouble = { this.xcoeff1, 2.0D * this.xcoeff2, 3.0D * this.xcoeff3 };
/* 545 */ int i = QuadCurve2D.solveQuadratic(arrayOfDouble, arrayOfDouble);
/* 546 */ for (int j = 0; j < i; j++) {
/* 547 */ double d = arrayOfDouble[j];
/* 548 */ if ((d > 0.0D) && (d < 1.0D)) {
/* 549 */ paramRectangle2D.add(XforT(d), YforT(d));
/* */ }
/* */ }
/* 552 */ paramRectangle2D.add(this.x1, this.y1);
/* */ }
/* */
/* */ public Curve getSubCurve(double paramDouble1, double paramDouble2, int paramInt) {
/* 556 */ if ((paramDouble1 <= this.y0) && (paramDouble2 >= this.y1)) {
/* 557 */ return getWithDirection(paramInt);
/* */ }
/* 559 */ double[] arrayOfDouble = new double[14];
/* */
/* 561 */ double d1 = TforY(paramDouble1);
/* 562 */ double d2 = TforY(paramDouble2);
/* 563 */ arrayOfDouble[0] = this.x0;
/* 564 */ arrayOfDouble[1] = this.y0;
/* 565 */ arrayOfDouble[2] = this.cx0;
/* 566 */ arrayOfDouble[3] = this.cy0;
/* 567 */ arrayOfDouble[4] = this.cx1;
/* 568 */ arrayOfDouble[5] = this.cy1;
/* 569 */ arrayOfDouble[6] = this.x1;
/* 570 */ arrayOfDouble[7] = this.y1;
/* 571 */ if (d1 > d2)
/* */ {
/* 586 */ double d3 = d1;
/* 587 */ d1 = d2;
/* 588 */ d2 = d3;
/* */ }
/* 590 */ if (d2 < 1.0D)
/* 591 */ split(arrayOfDouble, 0, d2);
/* */ int i;
/* 594 */ if (d1 <= 0.0D) {
/* 595 */ i = 0;
/* */ } else {
/* 597 */ split(arrayOfDouble, 0, d1 / d2);
/* 598 */ i = 6;
/* */ }
/* 600 */ return new Order3(arrayOfDouble[(i + 0)], paramDouble1, arrayOfDouble[(i + 2)], arrayOfDouble[(i + 3)], arrayOfDouble[(i + 4)], arrayOfDouble[(i + 5)], arrayOfDouble[(i + 6)], paramDouble2, paramInt);
/* */ }
/* */
/* */ public Curve getReversedCurve()
/* */ {
/* 608 */ return new Order3(this.x0, this.y0, this.cx0, this.cy0, this.cx1, this.cy1, this.x1, this.y1, -this.direction);
/* */ }
/* */
/* */ public int getSegment(double[] paramArrayOfDouble) {
/* 612 */ if (this.direction == 1) {
/* 613 */ paramArrayOfDouble[0] = this.cx0;
/* 614 */ paramArrayOfDouble[1] = this.cy0;
/* 615 */ paramArrayOfDouble[2] = this.cx1;
/* 616 */ paramArrayOfDouble[3] = this.cy1;
/* 617 */ paramArrayOfDouble[4] = this.x1;
/* 618 */ paramArrayOfDouble[5] = this.y1;
/* */ } else {
/* 620 */ paramArrayOfDouble[0] = this.cx1;
/* 621 */ paramArrayOfDouble[1] = this.cy1;
/* 622 */ paramArrayOfDouble[2] = this.cx0;
/* 623 */ paramArrayOfDouble[3] = this.cy0;
/* 624 */ paramArrayOfDouble[4] = this.x0;
/* 625 */ paramArrayOfDouble[5] = this.y0;
/* */ }
/* 627 */ return 3;
/* */ }
/* */
/* */ public String controlPointString() {
/* 631 */ return "(" + round(getCX0()) + ", " + round(getCY0()) + "), " + "(" + round(getCX1()) + ", " + round(getCY1()) + "), ";
/* */ }
/* */ }
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: sun.awt.geom.Order3
* JD-Core Version: 0.6.2
*/ | yuexiahandao/RT-JAR-CODE | sun/awt/geom/Order3.java |
247,669 | import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Circle
{
protected double x = 0;
protected double y = 0;
protected double radius = 1;
public Circle(double x, double y, double radius)
{
this.x = x;
this.y = y;
if (radius <= 0)
{
throw new IllegalArgumentException("Circle setRadius(): radius is negative");
// vagy System.exit(1);
// vagy radius = 1;
// etc . . .
}
this.radius = radius;
}
public static Circle readFromFile(String filename) throws FileNotFoundException, IOException
{
File input = new File(filename);
BufferedReader bf = null;
bf = new BufferedReader(new FileReader(input));
//System.err.println("Successfully opened file: " + filename);
double x = Double.parseDouble(bf.readLine());
double y = Double.parseDouble(bf.readLine());
double radius = Double.parseDouble(bf.readLine());
bf.close();
return new Circle(x, y, radius);
}
public void saveToFile(String filename) throws FileNotFoundException
{
File output = new File(filename);
// try with resources
try (PrintWriter pw = new PrintWriter(output))
{
pw.println(x);
pw.println(y);
pw.println(radius);
}
}
public void enlarge(double f)
{
radius *= f;
}
public double getArea()
{
return Math.PI * radius * radius;
}
public double getRadius()
{
return radius;
}
public String toString()
{
return "(x: " + x + ", y: " + y + ", r: " + radius + ")";
}
}
| Asatillo/JavaBasics | lab/lab7/Circle.java |
247,670 | package lab13;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
class CirclePane extends StackPane {
private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge() {
circle.setRadius(circle.getRadius() + 2);
}
public void shrink() {
circle.setRadius(circle.getRadius() > 2 ?
circle.getRadius() - 2 : circle.getRadius());
}
}
public class ControlCircle extends Application {
class EnlargeHandler implements EventHandler<ActionEvent> {
@Override // Override the handle method
public void handle(ActionEvent e) {
circlePane.enlarge();
}
}
class ShrinkHandler implements EventHandler<ActionEvent> {
@Override // Override the handle method
public void handle(ActionEvent e) {
circlePane.shrink();
}
}
// The main method is only needed for the IDE with limited
// JavaFX support. Not needed for running from the command line.
public static void main(String[] args) {
launch(args);
}
private CirclePane circlePane = new CirclePane();
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Hold two buttons in an HBox
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
// Create and register the handlers
btEnlarge.setOnAction(new EnlargeHandler());
btShrink.setOnAction(new ShrinkHandler());
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 200, 150);
primaryStage.setTitle("ControlCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
}
| calindoran/year2LabWork | lab13/ControlCircle.java |
247,671 | /*
* Copyright 2010-2015 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Icy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.util;
import icy.painter.Anchor2D;
import icy.painter.PathAnchor2D;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Stephane
*/
public class ShapeUtil
{
public static interface PathConsumer
{
/**
* Consume the specified path.<br>
* Return false to interrupt consumption.
*/
public boolean consumePath(Path2D path, boolean closed);
}
public static interface ShapeConsumer
{
/**
* Consume the specified Shape.<br>
* Return false to interrupt consumption.
*/
public boolean consume(Shape shape);
}
public static enum BooleanOperator
{
OR, AND, XOR
}
/**
* @deprecated Use {@link BooleanOperator} instead.
*/
@Deprecated
public static enum ShapeOperation
{
OR
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.OR;
}
},
AND
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.AND;
}
},
XOR
{
@Override
public BooleanOperator getBooleanOperator()
{
return BooleanOperator.XOR;
}
};
public abstract BooleanOperator getBooleanOperator();
}
/**
* Use the {@link Graphics} clip area and {@link Shape} bounds informations to determine if
* the specified {@link Shape} is visible in the specified Graphics object.
*/
public static boolean isVisible(Graphics g, Shape shape)
{
if (shape == null)
return false;
return GraphicsUtil.isVisible(g, shape.getBounds2D());
}
/**
* Returns <code>true</code> if the specified Shape define a closed Shape (Area).<br>
* Returns <code>false</code> if the specified Shape define a open Shape (Path).<br>
*/
public static boolean isClosed(Shape shape)
{
final PathIterator path = shape.getPathIterator(null);
final double crd[] = new double[6];
while (!path.isDone())
{
if (path.currentSegment(crd) == PathIterator.SEG_CLOSE)
return true;
path.next();
}
return false;
}
/**
* Merge the specified list of {@link Shape} with the given {@link BooleanOperator}.<br>
*
* @param shapes
* Shapes we want to merge.
* @param operator
* {@link BooleanOperator} to apply.
* @return {@link Area} shape representing the result of the merge operation.
*/
public static Shape merge(List<Shape> shapes, BooleanOperator operator)
{
Shape result = new Area();
// merge shapes
for (Shape shape : shapes)
{
switch (operator)
{
case OR:
result = union(result, shape);
break;
case AND:
result = intersect(result, shape);
break;
case XOR:
result = exclusiveUnion(result, shape);
break;
}
}
return result;
}
/**
* @deprecated Use {@link #merge(List, BooleanOperator)} instead.
*/
@Deprecated
public static Shape merge(Shape[] shapes, ShapeOperation operation)
{
return merge(Arrays.asList(shapes), operation.getBooleanOperator());
}
/**
* Process union between the 2 shapes and return result in a new Shape.
*/
public static Shape union(Shape shape1, Shape shape2)
{
// first compute closed area union
final Area area = new Area(getClosedPath(shape1));
area.add(new Area(getClosedPath(shape2)));
// then compute open path (polyline) union
final Path2D result = new Path2D.Double(getOpenPath(shape1));
result.append(getOpenPath(shape2), false);
// then append result
result.append(area, false);
return result;
}
/**
* @deprecated Use {@link #union(Shape, Shape)} instead
*/
@Deprecated
public static Shape add(Shape shape1, Shape shape2)
{
return union(shape1, shape2);
}
/**
* Intersects 2 shapes and return result in an {@link Area} type shape.<br>
* If one of the specified Shape is not an Area (do not contains any pixel) then an empty Area is returned.
*/
public static Area intersect(Shape shape1, Shape shape2)
{
// trivial optimization
if (!isClosed(shape1) || !isClosed(shape2))
return new Area();
final Area result = new Area(getClosedPath(shape1));
result.intersect(new Area(getClosedPath(shape2)));
return result;
}
/**
* Do exclusive union between the 2 shapes and return result in an {@link Area} type shape.<br>
* If one of the specified Shape is not an Area (do not contains any pixel) then it just return the other Shape in
* Area format. If both Shape are not Area then an empty Area is returned.
*/
public static Area exclusiveUnion(Shape shape1, Shape shape2)
{
// trivial optimization
if (!isClosed(shape1))
{
if (!isClosed(shape2))
return new Area();
return new Area(shape2);
}
// trivial optimization
if (!isClosed(shape2))
return new Area(shape1);
final Area result = new Area(getClosedPath(shape1));
result.exclusiveOr(new Area(getClosedPath(shape2)));
return result;
}
/**
* @deprecated Use {@link #exclusiveUnion(Shape, Shape)} instead.
*/
@Deprecated
public static Area xor(Shape shape1, Shape shape2)
{
return exclusiveUnion(shape1, shape2);
}
/**
* Subtract shape2 from shape1 return result in an {@link Area} type shape.
*/
public static Area subtract(Shape shape1, Shape shape2)
{
// trivial optimization
if (!isClosed(shape1))
return new Area();
if (!isClosed(shape2))
return new Area(shape1);
final Area result = new Area(getClosedPath(shape1));
result.subtract(new Area(getClosedPath(shape2)));
return result;
}
/**
* Scale the specified {@link RectangularShape} by specified factor.
*
* @param shape
* the {@link RectangularShape} to scale
* @param factor
* the scale factor
* @param centered
* if true then scaling is centered (shape location is modified)
*/
public static void scale(RectangularShape shape, double factor, boolean centered)
{
final double w = shape.getWidth();
final double h = shape.getHeight();
final double newW = w * factor;
final double newH = h * factor;
if (centered)
{
final double deltaW = (newW - w) / 2;
final double deltaH = (newH - h) / 2;
shape.setFrame(shape.getX() - deltaW, shape.getY() - deltaH, newW, newH);
}
else
shape.setFrame(shape.getX(), shape.getY(), newW, newH);
}
/**
* Enlarge the specified {@link RectangularShape} by specified width and height.
*
* @param shape
* the {@link RectangularShape} to scale
* @param width
* the width to add
* @param height
* the height to add
* @param centered
* if true then enlargement is centered (shape location is modified)
*/
public static void enlarge(RectangularShape shape, double width, double height, boolean centered)
{
final double w = shape.getWidth();
final double h = shape.getHeight();
final double newW = w + width;
final double newH = h + height;
if (centered)
{
final double deltaW = (newW - w) / 2;
final double deltaH = (newH - h) / 2;
shape.setFrame(shape.getX() - deltaW, shape.getY() - deltaH, newW, newH);
}
else
shape.setFrame(shape.getX(), shape.getY(), newW, newH);
}
/**
* Translate a rectangular shape by the specified dx and dy value
*/
public static void translate(RectangularShape shape, int dx, int dy)
{
shape.setFrame(shape.getX() + dx, shape.getY() + dy, shape.getWidth(), shape.getHeight());
}
/**
* Translate a rectangular shape by the specified dx and dy value
*/
public static void translate(RectangularShape shape, double dx, double dy)
{
shape.setFrame(shape.getX() + dx, shape.getY() + dy, shape.getWidth(), shape.getHeight());
}
/**
* Permit to describe any PathIterator in a list of Shape which are returned
* to the specified ShapeConsumer
*/
public static boolean consumeShapeFromPath(PathIterator path, ShapeConsumer consumer)
{
final Line2D.Double line = new Line2D.Double();
final QuadCurve2D.Double quadCurve = new QuadCurve2D.Double();
final CubicCurve2D.Double cubicCurve = new CubicCurve2D.Double();
double lastX, lastY, curX, curY, movX, movY;
final double crd[] = new double[6];
curX = 0;
curY = 0;
movX = 0;
movY = 0;
while (!path.isDone())
{
final int segType = path.currentSegment(crd);
lastX = curX;
lastY = curY;
switch (segType)
{
case PathIterator.SEG_MOVETO:
curX = crd[0];
curY = crd[1];
movX = curX;
movY = curY;
break;
case PathIterator.SEG_LINETO:
curX = crd[0];
curY = crd[1];
line.setLine(lastX, lastY, curX, curY);
if (!consumer.consume(line))
return false;
break;
case PathIterator.SEG_QUADTO:
curX = crd[2];
curY = crd[3];
quadCurve.setCurve(lastX, lastY, crd[0], crd[1], curX, curY);
if (!consumer.consume(quadCurve))
return false;
break;
case PathIterator.SEG_CUBICTO:
curX = crd[4];
curY = crd[5];
cubicCurve.setCurve(lastX, lastY, crd[0], crd[1], crd[2], crd[3], curX, curY);
if (!consumer.consume(cubicCurve))
return false;
break;
case PathIterator.SEG_CLOSE:
line.setLine(lastX, lastY, movX, movY);
if (!consumer.consume(line))
return false;
break;
}
path.next();
}
return true;
}
/**
* Consume all sub path of the specified {@link PathIterator}.<br>
* We consider a new sub path when we meet both a {@link PathIterator#SEG_MOVETO} segment or after a
* {@link PathIterator#SEG_CLOSE} segment (except the ending one).
*/
public static void consumeSubPath(PathIterator pathIt, PathConsumer consumer)
{
final double crd[] = new double[6];
Path2D current = null;
while (!pathIt.isDone())
{
switch (pathIt.currentSegment(crd))
{
case PathIterator.SEG_MOVETO:
// had a previous not closed path ? --> consume it
if (current != null)
consumer.consumePath(current, false);
// create new path
current = new Path2D.Double(pathIt.getWindingRule());
current.moveTo(crd[0], crd[1]);
break;
case PathIterator.SEG_LINETO:
current.lineTo(crd[0], crd[1]);
break;
case PathIterator.SEG_QUADTO:
current.quadTo(crd[0], crd[1], crd[2], crd[3]);
break;
case PathIterator.SEG_CUBICTO:
current.curveTo(crd[0], crd[1], crd[2], crd[3], crd[4], crd[5]);
break;
case PathIterator.SEG_CLOSE:
// close path and consume it
current.closePath();
consumer.consumePath(current, true);
// clear path
current = null;
break;
}
pathIt.next();
}
// have a last not closed path ? --> consume it
if (current != null)
consumer.consumePath(current, false);
}
/**
* Consume all sub path of the specified {@link Shape}.<br>
* We consider a new sub path when we meet both a {@link PathIterator#SEG_MOVETO} segment or after a
* {@link PathIterator#SEG_CLOSE} segment (except the ending one).
*/
public static void consumeSubPath(Shape shape, PathConsumer consumer)
{
consumeSubPath(shape.getPathIterator(null), consumer);
}
/**
* Returns only the open path part of the specified Shape.<br>
* By default all sub path inside a Shape are considered closed which can be a problem when drawing or using
* {@link Path2D#contains(double, double)} method.
*/
public static Path2D getOpenPath(Shape shape)
{
final PathIterator pathIt = shape.getPathIterator(null);
final Path2D result = new Path2D.Double(pathIt.getWindingRule());
consumeSubPath(pathIt, new PathConsumer()
{
@Override
public boolean consumePath(Path2D path, boolean closed)
{
if (!closed)
result.append(path, false);
return true;
}
});
return result;
}
/**
* Returns only the closed path part of the specified Shape.<br>
* By default all sub path inside a Shape are considered closed which can be a problem when drawing or using
* {@link Path2D#contains(double, double)} method.
*/
public static Path2D getClosedPath(Shape shape)
{
final PathIterator pathIt = shape.getPathIterator(null);
final Path2D result = new Path2D.Double(pathIt.getWindingRule());
consumeSubPath(pathIt, new PathConsumer()
{
@Override
public boolean consumePath(Path2D path, boolean closed)
{
if (closed)
result.append(path, false);
return true;
}
});
return result;
}
/**
* Return all PathAnchor points from the specified shape
*/
public static ArrayList<PathAnchor2D> getAnchorsFromShape(Shape shape, Color color, Color selectedColor)
{
final PathIterator pathIt = shape.getPathIterator(null);
final ArrayList<PathAnchor2D> result = new ArrayList<PathAnchor2D>();
final double crd[] = new double[6];
final double mov[] = new double[2];
while (!pathIt.isDone())
{
final int segType = pathIt.currentSegment(crd);
PathAnchor2D pt = null;
switch (segType)
{
case PathIterator.SEG_MOVETO:
mov[0] = crd[0];
mov[1] = crd[1];
case PathIterator.SEG_LINETO:
pt = new PathAnchor2D(crd[0], crd[1], color, selectedColor, segType);
break;
case PathIterator.SEG_QUADTO:
pt = new PathAnchor2D(crd[0], crd[1], crd[2], crd[3], color, selectedColor);
break;
case PathIterator.SEG_CUBICTO:
pt = new PathAnchor2D(crd[0], crd[1], crd[2], crd[3], crd[4], crd[5], color, selectedColor);
break;
case PathIterator.SEG_CLOSE:
pt = new PathAnchor2D(mov[0], mov[1], color, selectedColor, segType);
// CLOSE points aren't visible
pt.setVisible(false);
break;
}
if (pt != null)
result.add(pt);
pathIt.next();
}
return result;
}
/**
* Return all PathAnchor points from the specified shape
*/
public static ArrayList<PathAnchor2D> getAnchorsFromShape(Shape shape)
{
return getAnchorsFromShape(shape, Anchor2D.DEFAULT_NORMAL_COLOR, Anchor2D.DEFAULT_SELECTED_COLOR);
}
/**
* Update specified path from the specified list of PathAnchor2D
*/
public static Path2D buildPathFromAnchors(Path2D path, List<PathAnchor2D> points, boolean closePath)
{
path.reset();
for (PathAnchor2D pt : points)
{
switch (pt.getType())
{
case PathIterator.SEG_MOVETO:
path.moveTo(pt.getX(), pt.getY());
break;
case PathIterator.SEG_LINETO:
path.lineTo(pt.getX(), pt.getY());
break;
case PathIterator.SEG_QUADTO:
path.quadTo(pt.getPosQExtX(), pt.getPosQExtY(), pt.getX(), pt.getY());
break;
case PathIterator.SEG_CUBICTO:
path.curveTo(pt.getPosCExtX(), pt.getPosCExtY(), pt.getPosQExtX(), pt.getPosQExtY(), pt.getX(),
pt.getY());
break;
case PathIterator.SEG_CLOSE:
path.closePath();
break;
}
}
if ((points.size() > 1) && closePath)
path.closePath();
return path;
}
/**
* Update specified path from the specified list of PathAnchor2D
*/
public static Path2D buildPathFromAnchors(Path2D path, List<PathAnchor2D> points)
{
return buildPathFromAnchors(path, points, true);
}
/**
* Create and return a path from the specified list of PathAnchor2D
*/
public static Path2D getPathFromAnchors(List<PathAnchor2D> points, boolean closePath)
{
return buildPathFromAnchors(new Path2D.Double(), points, closePath);
}
/**
* Create and return a path from the specified list of PathAnchor2D
*/
public static Path2D getPathFromAnchors(List<PathAnchor2D> points)
{
return buildPathFromAnchors(new Path2D.Double(), points, true);
}
/**
* @deprecated Use {@link GraphicsUtil#drawPathIterator(PathIterator, Graphics2D)} instead
*/
@Deprecated
public static void drawFromPath(PathIterator path, final Graphics2D g)
{
GraphicsUtil.drawPathIterator(path, g);
}
/**
* Return true if the specified PathIterator intersects with the specified Rectangle
*/
public static boolean pathIntersects(PathIterator path, final Rectangle2D rect)
{
return !consumeShapeFromPath(path, new ShapeConsumer()
{
@Override
public boolean consume(Shape shape)
{
if (shape.intersects(rect))
return false;
return true;
}
});
}
}
| volker-baecker/Icy-Kernel | icy/util/ShapeUtil.java |
247,672 | package hus.oop.de1.fraction;
import java.util.Arrays;
import java.util.Comparator;
import hus.oop.lab11.abstractfactory.shape.FactoryProducer;
public class DataSet {
private static int DEFAULT_CAPACITY = 8;
private Fraction[] data;
private int length;
/**
* Hàm dựng khởi tạo mảng chứa các phân số có kích thước là DEFAULT_CAPACITY.
*/
public DataSet() {
data = new Fraction[DEFAULT_CAPACITY];
length = 0;
}
/**
* Hàm dựng khởi tạo mảng chứa các phân số theo data.
* @param data
*/
public DataSet(Fraction[] data) {
this.data = data;
}
/**
* Phương thức chèn phân số fraction vào vị trí index.
* Nếu index nằm ngoài đoạn [0, length] thì không chèn được vào.
* Nếu mảng hết chỗ để thêm dữ liệu, mở rộng kích thước mảng gấp đôi.
* @param fraction là một phân số.
* @return true nếu chèn được số vào, false nếu không chèn được số vào.
*/
public boolean insert(Fraction fraction, int index) {
/* TODO */
if (checkBoundaries(0, length)) {
return false;
}
if (length >= data.length) {
enlarge();
}
for (int i = length; i > index; i--) {
data[i] = data[i - 1];
}
data[index] = fraction;
length++;
return true;
}
/**
* Phương thức tạo ra một tập dữ liệu lưu các phân số tối giản của các phân số trong tập dữ liệu gốc.
* @return tập dữ liệu mới lưu các phân số tối giản của các phân số trong tập dữ liệu gốc.
*/
public DataSet toSimplify() {
/* TODO */
DataSet result = new DataSet();
for (Fraction fraction : data) {
fraction.simplify();
result.append(fraction);
}
return result;
}
/**
* Phương thức thêm phân số fraction vào vị trí cuối cùng chưa có dứ liệu của mảng data.
* Nếu mảng hết chỗ để thêm dữ liệu, mở rộng kích thước mảng gấp đôi.
* @param fraction
* @return
*/
public void append(Fraction fraction) {
/* TODO */
if (length >= data.length) {
enlarge();
}
data[length++] = fraction;
length++;
}
/**
* Sắp xếp mảng các phân số theo thứ tự có giá trị tăng dần.
* Nếu hai phân số bằng nhau thì sắp xếp theo thứ tự có mẫu số tăng dần.
* @return mảng mới được sắp xếp theo thứ tự có giá trị tăng dần.
*/
public Fraction[] sortIncreasing() {
/* TODO */
Fraction[] sorted = data.clone();
Arrays.sort(sorted, Fraction::compareTo);
return sorted;
}
/**
* Sắp xếp mảng các phân số theo thứ tự có giá trị giảm dần.
* Nếu hai phân số bằng nhau thì sắp xếp theo thứ tự có mẫu số giảm dần.
* @return mảng mới được sắp xếp theo thứ tự có giá trị giảm dần.
*/
public Fraction[] sortDecreasing() {
/* TODO */
Fraction[] result = data.clone();
Arrays.sort(result, new Comparator<Fraction>() {
public int compare(Fraction o1, Fraction o2) {
return o2.compareTo(o1);
}
});
return result;
}
/**
* Phương thức mở rộng kích thước mảng gấp đôi, bằng cách tạo ra mảng mới có kích thước
* gấp đôi, sau đó copy dự liệu từ mảng cũ vào.
*/
private void enlarge() {
/* TODO */
Fraction[] newFrac = new Fraction[length*2];
System.arraycopy(data, 0, newFrac, 0, data.length);
data = newFrac;
}
/**
* Phương thức kiểm tra xem index có nằm trong khoảng [0, upperBound] hay không.
* @param index
* @param upperBound
* @return true nếu index nằm trong khoảng [0, upperBound], false nếu ngược lại.
*/
private boolean checkBoundaries(int index, int upperBound) {
/* TODO */
return ((index < 0) && (index > upperBound));
}
/**
* In ra tập dữ liệu theo định dạng [a1, a2, ... , an].
* @return
*/
@Override
public String toString() {
/* TODO */
StringBuilder res = new StringBuilder();
res.append("[");
for (Fraction fraction : data) {
res.append(fraction.toString() + " ");
}
res.append("]");
return res.toString();
}
/**
* In ra mảng các phân số fractions theo định dạng [a1, a2, ... , an].
* @param fractions
*/
public static void printFractions(Fraction[] fractions) {
/* TODO */
DataSet data = new DataSet(fractions);
System.out.println(data.toString());
}
}
| tasdus-117/oop | de1/fraction/DataSet.java |
247,673 | package rstar;
/* Modified by Josephine Wong 23 Nov 1997
Improve User Interface of the program
*/
public class Constants
{
public static final boolean recordLeavesOnly = false;
/* These values are now set by the users - see UserInterface module.*/
// for experimental rects
public static final int MAXCOORD = 100;
public static final int MAXWIDTH = 60;
public static final int NUMRECTS = 200;
public static final int DIMENSION = 2;
public static final int BLOCKLENGTH = 1024;
public static final int CACHESIZE = 128;
// for queries
static final int RANGEQUERY = 0;
static final int POINTQUERY = 1;
static final int CIRCLEQUERY = 2;
static final int RINGQUERY = 3;
static final int CONSTQUERY = 4;
// for buffering
static final int SIZEOF_BOOLEAN = 1;
static final int SIZEOF_SHORT = 2;
static final int SIZEOF_CHAR = 1;
static final int SIZEOF_BYTE = 1;
static final int SIZEOF_FLOAT = 4;
static final int SIZEOF_INT = 4;
public final static int RTDataNode__dimension = 2;
public final static float MAXREAL = (float)9.99e20;
public final static int MAX_DIMENSION = 256;
// for comparisons
public final static float min(float a, float b) {return (a < b)? a : b;}
public final static int min(int a, int b) {return (a < b)? a : b;}
public final static float max(float a, float b) {return (a > b)? a : b;}
public final static int max(int a, int b) {return (a > b)? a : b;}
// for comparing mbrs
public final static int OVERLAP=0;
public final static int INSIDE=1;
public final static int S_NONE=2;
// for the insert algorithm
public final static int SPLIT=0;
public final static int REINSERT=1;
public final static int NONE=2;
// for header blocks
public final static int BFHEAD_LENGTH = SIZEOF_INT*2;
// sorting criteria
public final static int SORT_LOWER_MBR = 0; //for mbrs
public final static int SORT_UPPER_MBR = 1; //for mbrs
public final static int SORT_CENTER_MBR = 2; //for mbrs
public final static int SORT_MINDIST = 3; //for branchlists
public final static int BLK_SIZE=4096;
public final static int MAXLONGINT=32768;
public final static int NUM_TRIES=10;
// for errors
public static void error (String msg, boolean fatal)
{
System.out.println(msg);
if (fatal) System.exit(1);
}
// returns the d-dimension area of the mbr
public static float area(int dimension, float mbr[])
{
int i;
float sum;
sum = (float)1.0;
for (i = 0; i < dimension; i++)
sum *= mbr[2*i+1] - mbr[2*i];
return sum;
}
// returns the margin of the mbr. That is the sum of all projections
// to the axes
public static float margin(int dimension, float mbr[])
{
int i;
int ml, mu, m_last;
float sum;
sum = (float)0.0;
m_last = 2*dimension;
ml = 0;
mu = ml + 1;
while (mu < m_last)
{
sum += mbr[mu] - mbr[ml];
ml += 2;
mu += 2;
}
return sum;
}
// ist ein Skalar in einem Intervall ?
public static boolean inside(float p, float lb, float ub)
{
return (p >= lb && p <= ub);
}
// ist ein Vektor in einer Box ?
public static boolean inside(float v[], float mbr[], int dimension)
{
int i;
for (i = 0; i < dimension; i++)
if (!inside(v[i], mbr[2*i], mbr[2*i+1]))
return false;
return true;
}
// calcutales the overlapping area of r1 and r2
// calculate overlap in every dimension and multiplicate the values
public static float overlap(int dimension, float r1[], float r2[])
{
float sum;
int r1pos, r2pos, r1last;
float r1_lb, r1_ub, r2_lb, r2_ub;
sum = (float)1.0;
r1pos = 0; r2pos = 0;
r1last = 2 * dimension;
while (r1pos < r1last)
{
r1_lb = r1[r1pos++];
r1_ub = r1[r1pos++];
r2_lb = r2[r2pos++];
r2_ub = r2[r2pos++];
// calculate overlap in this dimension
if (inside(r1_ub, r2_lb, r2_ub))
// upper bound of r1 is inside r2
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r1_ub - r1_lb);
else
sum *= (r1_ub - r2_lb);
}
else
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r2_ub - r1_lb);
else
{
if (inside(r2_lb, r1_lb, r1_ub) && inside(r2_ub, r1_lb, r1_ub))
// r1 contains r2
sum *= (r2_ub - r2_lb);
else
// r1 and r2 do not overlap
sum = (float)0.0;
}
}
}
return sum;
}
// enlarge r in a way that it contains s
public static void enlarge(int dimension, float mbr[], float r1[], float r2[])
{
int i;
//mbr = new float[2*dimension];
for (i = 0; i < 2*dimension; i += 2)
{
mbr[i] = min(r1[i], r2[i]);
mbr[i+1] = max(r1[i+1], r2[i+1]);
}
/*System.out.println("Enlarge was called with parameters:");
System.out.println("r1 = " + r1[0] + " " + r1[1] + " " + r1[2] + " " + r1[3]);
System.out.println("r2 = " + r2[0] + " " + r2[1] + " " + r2[2] + " " + r2[3]);
System.out.println("r1 = " + mbr[0] + " " + mbr[1] + " " + mbr[2] + " " + mbr[3]);
*/
//#ifdef CHECK_MBR
// check_mbr(dimension,*mbr);
//#endif
}
/**
* returns true if the two mbrs intersect
*/
public static boolean section(int dimension, float mbr1[], float mbr2[])
{
int i;
for (i = 0; i < dimension; i++)
{
if (mbr1[2*i] > mbr2[2*i + 1] || mbr1[2*i + 1] < mbr2[2*i])
return false;
}
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_c(int dimension, float mbr1[], Object center, float radius)
{
float r2;
r2 = radius * radius;
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if ((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)
return false;
else
return true;
}
//new function
public static boolean section_c_2(int dimension, float mbr1[], Object center, float radius)
{
if (radius < MINDIST(center,mbr1))
return false;
else
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_ring(int dimension, float mbr1[], Object center, float radius1, float radius2)
{
float r_c1; //inner circle radius
float r_c2; //outer circle radius
if (radius1 < radius2)
{
r_c1 = radius1 * radius1;
r_c2 = radius2 * radius2;
}
else
{
r_c1 = radius2 * radius2;
r_c2 = radius1 * radius1;
}
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if (((r_c1 - MAXDIST(center,mbr1)) < (float)1.0e-8) &&
((MINDIST(center,mbr1) - r_c2) < (float)1.0e-8))
return true;
else
return false;
}
/** This is a generic version of C.A.R Hoare's Quick Sort
* algorithm. This will handle arrays that are already
* sorted, and arrays with duplicate keys.
*
* If you think of a one dimensional array as going from
* the lowest index on the left to the highest index on the right
* then the parameters to this function are lowest index or
* left and highest index or right. The first time you call
* this function it will be with the parameters 0, a.length - 1.
*
* @param a a Sortable array
* @param lo0 left boundary of array partition
* @param hi0 right boundary of array partition
*/
public static void quickSort(Sortable a[], int lo0, int hi0, int sortCriterion)
{
int lo = lo0;
int hi = hi0;
Sortable mid;
if (hi0 > lo0)
{
/* Arbitrarily establishing partition element as the midpoint of
* the array.
*/
mid = a[ ( lo0 + hi0 ) / 2 ];
// loop through the array until indices cross
while( lo <= hi )
{
/* find the first element that is greater than or equal to
* the partition element starting from the left Index.
*/
while( ( lo < hi0 ) && ( a[lo].lessThan(mid, sortCriterion) ))
++lo;
/* find an element that is smaller than or equal to
* the partition element starting from the right Index.
*/
while( ( hi > lo0 ) && ( a[hi].greaterThan(mid, sortCriterion)))
--hi;
// if the indexes have not crossed, swap
if( lo <= hi )
{
swap(a, lo, hi);
++lo;
--hi;
}
}
/* If the right index has not reached the left side of array
* must now sort the left partition.
*/
if( lo0 < hi )
quickSort( a, lo0, hi, sortCriterion );
/* If the left index has not reached the right side of array
* must now sort the right partition.
*/
if( lo < hi0 )
quickSort( a, lo, hi0, sortCriterion );
}
}
//Swaps two entries in an array of objects to be sorted.
//See Constants.quickSort()
public static void swap(Sortable a[], int i, int j)
{
Sortable T;
T = a[i];
a[i] = a[j];
a[j] = T;
}
/**
* computes the square of the Euclidean distance between 2 points
*/
public static float objectDIST(PPoint point1, PPoint point2)
{
//
// Berechnet das Quadrat der euklid'schen Metrik.
// (Der tatsaechliche Abstand ist uninteressant, weil
// die anderen Metriken (MINDIST und MINMAXDIST fuer
// die NearestNarborQuery nur relativ nie absolut
// gebraucht werden; nur Aussagen "<" oder ">" sind
// relevant.
//
float sum = (float)0;
int i;
for( i = 0; i < point1.dimension; i++)
sum += java.lang.Math.pow(point1.data[i] - point2.data[i], 2);
//return( sqrt(sum) );
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINDIST between 1 pt and 1 MBR (see [Rous95])
* the MINDIST ensures that the nearest neighbor from this pt to a
* rect in this MBR is at at least this distance
*/
public static float MINDIST(Object pt, float bounces[])
{
//
// Berechne die kuerzeste Entfernung zwischen einem Punkt Point
// und einem MBR bounces (Lotrecht!)
//
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float r;
int i;
for(i = 0; i < point.dimension; i++)
{
if (point.data[i] < bounces[2*i])
r = bounces[2*i];
else
{
if (point.data[i] > bounces[2*i+1])
r = bounces[2*i+1];
else
r = point.data[i];
}
sum += java.lang.Math.pow(point.data[i] - r , 2);
}
//return(sum);
return((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MAXDIST between 1 pt and 1 MBR. It is defined as the
* maximum distance of a MBR vertex against the specified point
* Used as an upper bound of the furthest rectangle inside an MBR from a specific
* point
*/
public static float MAXDIST(Object pt, float bounces[])
{
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float maxdiff;
int i;
for(i = 0; i < point.dimension; i++)
{
maxdiff = max(java.lang.Math.abs(point.data[i] - bounces[2*i]),
java.lang.Math.abs(point.data[i] - bounces[2*i+1]));
sum += java.lang.Math.pow(maxdiff, 2);
}
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINMAXDIST between 1 pt and 1 MBR (see [Rous95])
* the MINMAXDIST ensures that there is at least 1 object in the MBR
* that is at most MINMAXDIST far away of the point
*/
public static float MINMAXDIST(PPoint point, float bounces[])
{
// Berechne den kleinsten maximalen Abstand von einem Punkt Point
// zu einem MBR bounces.
// Wird benutzt zur Abschaetzung von Abstaenden bei NearestNarborQuery.
// Kann als Supremum fuer die aktuell kuerzeste Distanz:
// Alle Punkte mit einem Abstand > MINMAXDIST sind keine Kandidaten mehr
// fuer den NearestNarbor
// vgl. Literatur:
// Nearest Narbor Query v. Roussopoulos, Kelley und Vincent,
// University of Maryland
float sum = 0;
float minimum = (float)1.0e20;
float S = 0;
float rmk, rMi;
int k,i,j;
for( i = 0; i < point.dimension; i++)
{
rMi = (point.data[i] >= (bounces[2*i]+bounces[2*i+1])/2)
? bounces[2*i] : bounces[2*i+1];
S += java.lang.Math.pow( point.data[i] - rMi , 2 );
}
for( k = 0; k < point.dimension; k++)
{
rmk = ( point.data[k] <= (bounces[2*k]+bounces[2*k+1]) / 2 ) ?
bounces[2*k] : bounces[2*k+1];
sum = (float)java.lang.Math.pow(point.data[k] - rmk , 2 );
rMi = (point.data[k] >= (bounces[2*k]+bounces[2*k+1]) / 2 )
? bounces[2*k] : bounces[2*k+1];
sum += S - java.lang.Math.pow(point.data[k] - rMi , 2);
minimum = min(minimum,sum);
}
return(minimum);
//return ((float)java.lang.Math.sqrt(minimum));
}
/*
public static int sortmindist(Object element1, Object element2)
{
//
// Vergleichsfunktion fuer die Sortierung der BranchList bei der
// NearestNarborQuery (Sort, Branch and Prune)
//
BranchList e1,e2;
e1 = (BranchList ) element1;
e2 = (BranchList ) element2;
if (e1.mindist < e2.mindist)
return(-1);
else if (e1.mindist > e2.mindist)
return(1);
else
return(0);
}*/
public static int pruneBranchList(float nearest_distanz/*[]*/, Object activebranchList[], int n)
{
// Schneidet im Array BranchList alle Eintraege ab, deren Distanz groesser
// ist als die aktuell naeheste Distanz
//
BranchList bl[];
int i,j,k, aktlast;
bl = (BranchList[]) activebranchList;
// 1. Strategie:
//
// Ist MINDIST(P,M1) > MINMAXDIST(P,M2), so kann der
// NearestNeighbor auf keinen Fall mehr in M1 liegen!
//
aktlast = n;
for( i = 0; i < aktlast ; i++ )
{
if (bl[i].minmaxdist < bl[aktlast-1].mindist)
for(j = 0; (j < aktlast) ; j++ )
if ((i!=j) && (bl[j].mindist>bl[i].minmaxdist))
{
aktlast = j;
break;
}
}
// 2. Strategie:
//
// nearest_distanz > MINMAXDIST(P,M)
// -> nearest_distanz = MIMMAXDIST(P,M)
//
for( i = 0; i < aktlast; i++)
if (nearest_distanz/*[0]*/ > bl[i].minmaxdist)
nearest_distanz/*[0]*/ = bl[i].minmaxdist;
// 3. Strategie:
//
// nearest_distanz < MINDIST(P,M)
//
// in M kann der Nearest-Narbor sicher nicht mehr liegen.
//
for( i = 0; (i < aktlast) && (nearest_distanz/*[0]*/ >= bl[i].mindist) ; i++);
aktlast = i;
// printf("n: %d aktlast: %d \n",n,aktlast);
return (aktlast);
}
public static int testBranchList(Object abL[], Object sL[], int n, int last)
{
// Schneidet im Array BranchList alle Eintr"age ab, deren Distanz gr"o"ser
// ist als die aktuell naeheste Distanz
//
BranchList activebranchList[], sectionList[];
int i,number, aktlast;
activebranchList = (BranchList[]) abL;
sectionList = (BranchList[]) sL;
aktlast = last;
for(i = last; i < n ; i++)
{
number = activebranchList[i].entry_number;
if (sectionList[number].section)
{
// obwohl vom Abstand her dieser Eintrag gecanceld werden
// m"usste, wird hier der Eintrag in die ABL wieder
// aufgenommen, da evtl. ein Treffer der range-Query zu erwarten ist!
//
// An der letzten Stelle der Liste kommt der aktuelle Eintrag!
aktlast++;
activebranchList[aktlast].entry_number = activebranchList[i].entry_number;
activebranchList[aktlast].mindist = activebranchList[i].mindist;
activebranchList[aktlast].minmaxdist = activebranchList[i].minmaxdist; }
}
return (aktlast);
}
public static void check_mbr(int dimension, float mbr[])
{
}
public static rectangle toRectangle (float rect[])
{
rectangle r = new rectangle(0);
r.LX = (int) rect[0];
r.UX = (int) rect[1];
r.LY = (int) rect[2];
r.UY = (int) rect[3];
return r;
}
} | Haibo-Wang-ORG/Most-Popular-Route | src/rstar/Constants.java |
247,674 |
/*-- Assignment 4, CSCE-314
-- Section: 500
-- Student Name: Robert Quan
-- JavaFX Basics*/
package controlcircle;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
/**
*
* @author rquan
* This program tests the functions and
* demos the uses of JavaFx
* NOTE must have JavaFX files to run,
* I used Netbeans
*/
public class ControlCircle extends Application {
private CirclePane circlePane1 = new CirclePane(); //Create two CirclePanes
private CirclePane circlePane2 = new CirclePane();
@Override
public void start(Stage primaryStage) {
HBox hBox = new HBox();
hBox.setSpacing(100);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("First");
Button btShrink = new Button("Second");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
btEnlarge.setOnAction(new EnglargeHandler());
btShrink.setOnAction(new ShrinkHandler());
BorderPane borderPane = new BorderPane();
borderPane.setLeft(circlePane1);
borderPane.setRight(circlePane2);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
Scene scene = new Scene(borderPane,300,250);
primaryStage.setTitle("ControlCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
class EnglargeHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
circlePane1.enlarge();
circlePane2.shrink();
}
}
class ShrinkHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
circlePane1.shrink();
circlePane2.enlarge();
}
}
public static void main(String[] args) {
launch(args);
}
}
class CirclePane extends StackPane{
private Circle circle = new Circle(50);
public CirclePane(){
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge(){
circle.setRadius(circle.getRadius()+(0.1*circle.getRadius()*Math.random()));
circle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
}
public void shrink(){
circle.setRadius(circle.getRadius()> 2 ?
circle.getRadius()-(0.1*circle.getRadius()*Math.random()) : circle.getRadius());
circle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
}
}
| hquan212/CSCE314-Summer2017 | HW4/ControlCircle.java |
247,675 | /**
* @file Memory.java
* @author Droken
* @author ZanyMonk
* @brief Memory class
*
* Represents the memory of a program composed of 8-bit cells.
*/
import java.util.Vector;
public class Memory {
private final Vector<Character> memory;
private int pointer;
public Memory(int size) {
this.memory = new Vector<>();
this.pointer = 0;
this.addMemSpace(size);
}
private void addMemSpace(int n) {
for(int i = 0; i < n; i++)
this.memory.add((char)0);
}
public Character current() {
Character value;
try {
value = this.memory.elementAt(this.pointer);
return value;
} catch(ArrayIndexOutOfBoundsException e) {
this.enlarge();
System.err.println("[!] Pointer (" + this.pointer + ") is out of memory.\nMemory has been enlarged to " + this.memory.size() + " blocks.");
return this.current();
}
}
public boolean set(char input) {
if(input > 255)
return false;
this.memory.setElementAt(input, this.pointer);
return true;
}
@SuppressWarnings("empty-statement")
public String dump(int lines) {
int last = this.memory.size()-1;
int start = Math.max(this.pointer-this.pointer%10-31, 0);
int end = start+10*lines-1;
int n, length = 50;
String out = "";
for(int i = start; i <= end; i++) {
n = (int)this.memory.elementAt(i);
if((i-start%10)%10 == 0 && i != end)
out += "\n| " + new String(new char[5-Integer.toString(i).length()]).replace("\0", " ")+i+" |";
if(i == this.pointer)
out += (char)27+"[32m";
out += new String(new char[4-Integer.toString(n).length()]).replace("\0", " ") + n;
if(i == this.pointer)
out += (char)27+"[39m";
if((i-start%10+1)%10 == 0 || i == end)
out += " |";
}
return out;
// System.out.println(out);
// this.interpreter.dump(length);
}
public String dump() {
return this.dump(10);
}
public void enlarge() {
this.addMemSpace(1000);
}
public boolean movePointerLeft() {
this.pointer--;
if(this.pointer < 0) {
this.pointer = this.memory.size()-1;
}
return true;
}
public void movePointerRight() {
this.pointer++;
}
}
| ZanyMonk/BFInterpreter | src/Memory.java |
247,676 | package sample;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ControlCircle extends Application {
private CirclePane circlePane = new CirclePane();
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Hold two buttons in an HBox
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
// Create and register the handler
btEnlarge.setOnAction(new EnlargeHandler());
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 200, 150);
primaryStage.setTitle("ControlCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
class EnlargeHandler implements EventHandler<ActionEvent> {
@Override // Override the handle method
public void handle(ActionEvent e) {
circlePane.enlarge();
}
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
class CirclePane extends StackPane {
private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge() {
circle.setRadius(circle.getRadius() + 2);
}
public void shrink() {
circle.setRadius(circle.getRadius() > 2 ?
circle.getRadius() - 2 : circle.getRadius());
}
}
| ashishrsai/Intermediate-Programming-Lab-Solutions | Week 9/ControlCircle.java |
247,677 | // A map that associates a body with a force exerted on it. The number of
// key-value pairs is not limited.
//
public class BodyForceMap {
//TODO: declare variables.
private int initialCapacity;
private Body[] keys;
private Vector3[] values;
private int currentElemCount;
// Initializes this map with an initial capacity.
// Precondition: initialCapacity > 0.
public BodyForceMap(int initialCapacity) {
this.initialCapacity = initialCapacity;
this.currentElemCount = 0;
this.keys = new Body[initialCapacity];
this.values = new Vector3[initialCapacity];
}
// Adds a new key-value association to this map. If the key already exists in this map,
// the value is replaced and the old value is returned. Otherwise 'null' is returned.
// Precondition: key != null.
public Vector3 put(Body key, Vector3 force) {
int foundIndex = binarySearchFindKey(key);
//Does the key already exist?
if(foundIndex == -1){
for(int i = 0; i < keys.length; i++){
if(keys[i] != null){
if(keys[i].mass() < key.mass()){
//We need to right shift
if(keys.length == currentElemCount){enlarge(keys,1); enlarge(values, 1);} //Array is enlarged by 1 to make place
rightRotatebyOne(keys); //make place for new key
keys[i] = key; //key is inserted into the new freed index by rotatingRight
rightRotatebyOne(values);
values[i] = force;
currentElemCount++;
return null;
}
}
else{
keys[i] = key;
values[i] = force;
currentElemCount++;
return null;
}
}
}else{ //if key does exist
Vector3 oldVal = values[foundIndex];
values[foundIndex] = force; //replace associated new value
return oldVal;
}
return null;
}
/**
* Modifies and returns the same array which was increased in size
* by enlargeBy
* @param toEnlarge array to be enlarged
* @param enlargeBy size to be enlarged
* @return the specified array which was given as a parameter
*/
private Object[] enlarge(Object[] toEnlarge, int enlargeBy){
Object[] result = new Object[toEnlarge.length + enlargeBy];
for(int i = 0; i < toEnlarge.length; i++){
result[i] = toEnlarge[i];
}
return result;
}
private void rightRotatebyOne(Object toRotateByOne[])
{
Object tempLast = toRotateByOne[toRotateByOne.length-1];
for(int i = toRotateByOne.length - 2; i >= 0; i--){
toRotateByOne[i+1] = toRotateByOne[i];
}
toRotateByOne[0] = tempLast;
}
// Returns the value associated with the specified key, i.e. the returns the force vector
// associated with the specified body. Returns 'null' if the key is not contained in this map.
// Precondition: key != null.
public Vector3 get(Body key) {
int foundIndex = binarySearchFindKey(key);
if(foundIndex != -1){
return values[foundIndex];
}
return null;
}
private int binarySearchFindKey(Body search) {
int left = 0;
int right = keys.length - 1;
while (left <= right) {
int middle = left + ((right - left) / 2);
if(keys[middle] == search) {
return middle;
}else if(keys[middle] == null){
right--;
}else if (keys[middle].mass() < search.mass()) {
right = middle - 1;
} else {
left = middle + 1;
}
}
return -1;
}
}
| Reonharudo/planet-simulation | src/BodyForceMap.java |
247,678 | import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
public class DrawArea extends JPanel {
DrawPad drawPad;
Shape[] list = new Shape[50000];//图形数组
int index = 0;//绘制图形数目索引
int R,G,B;//彩色值
float stroke = 1.0f;//默认笔画粗细
int bold,italic;//字体风格
BufferedImage image;//背景图像存储
private int currentchoice = 4;//当前状态pan。铅笔
private Color col=Color.BLACK;//默认笔画颜色
DrawArea(DrawPad dp){//构造函数
this.drawPad = dp;
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));//设置光标颜色
setBackground(Color.WHITE);
addMouseListener(new MouseA());
addMouseMotionListener(new MouseB());
createNewitem();
}//构造函数
void draw(Graphics2D g2b,Shape i){
i.draw(g2b);
}//画笔传到每个类
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int j = 0;
while (j<=index){
if (j==0){
g.drawImage(image,0,0,this);//底图为打开的图片
}
draw(g2d,list[j]);
j++;
}
}//绘制此容器中的每个组件
void createNewitem(){
if(currentchoice==16)//文本输入
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
else
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
switch (currentchoice){
case 3:list[index] = new Eraser();break;
case 4:list[index] = new pencil();break;
case 5:list[index] = new Line();break;
case 6:list[index] = new Rect();break;
case 7:list[index] = new fillRect();break;
case 8:list[index] = new Oval();break;
case 9:list[index] = new fillOval();break;
case 10:list[index] = new Circle();break;
case 11:list[index] = new fillCircle();break;
case 12:list[index] = new RoundRect();break;
case 13:list[index] = new fillRoundRect();break;
case 16:list[index] = new word();break;
}
list[index].R = R;
list[index].G = G;
list[index].B = B;
list[index].stroke = stroke;
list[index].bold=bold;
list[index].italic=italic;
}
public void setIndex(int x){
index = x;
}//修改图形数组索引
public void setColor(Color col){
this.col=col;
}//修改画板默认颜色
public void setStroke(float f){
this.stroke = f;
}//设置画笔粗细
public void chooseColor(){
col = JColorChooser.showDialog(this,"请选择颜色",col);//选择颜色
try{
R = col.getRed();
G = col.getGreen();
B = col.getBlue();
} catch (Exception e){
list[index].R = 0;
list[index].G = 0;
list[index].B = 0;
}
list[index].R = R;
list[index].G = G;
list[index].B = B;
}//颜色选择器
public void setStroke(){
String intput;
intput = JOptionPane.showInputDialog("请输入画笔粗细");//输入框
try{
stroke = Float.parseFloat(intput);//分析数字
}catch (Exception e){
stroke = 1.0f;
}
list[index].stroke = stroke;
}//使用键盘输入画笔粗细
public void setCurrentchoice(int i){
currentchoice = i;
}//设置当前画板画笔状态
public void setFont(int i,int font){
if (i==1){
bold=font;
}else if (i==2){
italic=font;
}else {
bold=italic=Font.PLAIN;
}
}//设置字体风格
public void setFontName(String name) {
list[index].font_familyName = name;
}//选择字体
public void ReturnIndex(){
if (index>0){
this.index--;
}
}//撤回
public void enlarge(){
for (int j = 0;j<=index;j++){
list[j].x1=list[j].x1*2;
list[j].y1=list[j].y1*2;
list[j].x2=list[j].x2*2;
list[j].y2=list[j].y2*2;
list[j].stroke=list[j].stroke*2;
}
}//放大
public void narrow(){
for (int j = 0;j<=index;j++){
list[j].x1=list[j].x1/2;
list[j].y1=list[j].y1/2;
list[j].x2=list[j].x2/2;
list[j].y2=list[j].y2/2;
list[j].stroke=list[j].stroke/2;
}
}//缩小
class MouseA extends MouseAdapter{
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
drawPad.setStratBar("鼠标进入在:["+e.getX()+","+e.getY()+"]");
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
drawPad.setStratBar("鼠标退出在:["+e.getX()+","+e.getY()+"]");
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
drawPad.setStratBar("鼠标按住在:["+e.getX()+","+e.getY()+"]");
list[index].x1 = list[index].x2 = e.getX();
list[index].y1 = list[index].y2 = e.getY();
//Eraser pan
if (currentchoice == 3||currentchoice == 4){
list[index].x1 = list[index].x2 = e.getX();
list[index].y1 = list[index].y2 = e.getY();
index++;
createNewitem();
}
if(currentchoice == 16){//文字
list[index].x1 = e.getX();
list[index].y1 = e.getY();
String input ;
input = JOptionPane.showInputDialog("请输入你要写入的文字!");
list[index].word = input;
index++;
currentchoice = 16;
createNewitem();//创建新的图形的基本单元对象
repaint();//重绘组件
}
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
drawPad.setStratBar("鼠标松开:["+e.getX()+","+e.getY()+"]");
if (currentchoice==3||currentchoice==4){
list[index].x1 = e.getX();
list[index].y1 = e.getY();
}
list[index].x2 = e.getX();
list[index].y2 = e.getY();
repaint();
index++;
createNewitem();
}
}//鼠标监听类
class MouseB extends MouseMotionAdapter{
@Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
drawPad.setStratBar("鼠标拖动在:["+e.getX()+","+e.getY()+"]");
if (currentchoice==3||currentchoice==4){
list[index-1].x1=list[index].x2 = list[index].x1=e.getX();
list[index-1].y1=list[index].y2 = list[index].y1=e.getY();
index++;
createNewitem();
}else {
list[index].x2 = e.getX();
list[index].y2 = e.getY();
}
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
drawPad.setStratBar("鼠标移动在:["+e.getX()+","+e.getY()+"]");
}
}
}
| mr-ma-peng/Drawingboard | src/DrawArea.java |
247,679 | // Circle.java
import java.awt.*;
class Circle {
int x, y; // center
int radius;
Color color;
Circle(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
void draw(Graphics g) {
g.setColor(this.color);
g.fillOval(this.x - this.radius,
this.y - this.radius,
this.radius * 2,
this.radius * 2);
g.setColor(Color.BLACK);
g.drawOval(this.x - this.radius,
this.y - this.radius,
this.radius * 2,
this.radius * 2);
}
void enlarge() {
this.radius += 1;
}
} | c212/snake-fall2018 | vanishingFood/Circle.java |
247,681 | package com.fairytale110.mycustomviews.Widget;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import com.fairytale110.mycustomviews.Utils.ColorUtil;
import java.text.DecimalFormat;
/**
* Created by fairytale110
* Creat date 2016/9/14 15:57
* Copy Right www.xkyiliao.com
* function 可旋转 饼状图
*/
@SuppressWarnings("all")
public class _fa_pieChartView extends View implements ValueAnimator.AnimatorUpdateListener {
private int ACTION_ROTATION = 1;//旋转Action
private int ACTION_ENLARGE = 2;//放大半径action
private int ACTION_ = ACTION_ROTATION;//当前Action
private int width, height;//画布宽高
private String TAG = getClass().getSimpleName();
/**
* 圆弧颜色
* 注意,目前的问题是,不能有重复的颜色,不然无法确定唯一index
* 【请自行添加 set方法】
*/
private String[] arcColors = new String[]{"#FD9033", "#F98AEC", "#FF3564", "#92BEFF", "#ABEA3D"};
/**
* 默认圆弧颜色
*/
private String defaultColor = "#A9A9A9";
private String tittleStr = "总支出";
private String totalPrice = "";
/**
* 像素密度、圆弧厚度,要旋转的角度、放大系数(最大0.5F)、数据和、字体大小
*/
private float density, charRi, degree, gain, dataSum, tittleSize, priceSize;
private long DURATION = 1000;//动画时长 毫秒
private long DURATION_GAIN = 2000;//动画时长 毫秒
private Float[] datas = {};
private Bitmap bitmap;
RectF rectF, rectFSelected;
private Paint txtPaint;//文本画笔
private Paint paintArc;//圆弧画笔
private ValueAnimator valueAnimator;
private OnItemChangedListener mOnItemChangedListener;
public _fa_pieChartView(Context context) {
super(context);
init();
}
public _fa_pieChartView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public _fa_pieChartView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.density = getResources().getDisplayMetrics().density;
this.paintArc = new Paint(Paint.ANTI_ALIAS_FLAG);
this.paintArc.setStyle(Paint.Style.STROKE);
this.paintArc.setAntiAlias(true);
this.paintArc.setColor(Color.RED);
this.txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.txtPaint.setAntiAlias(true);
this.txtPaint.setTextSize(12 * this.density);
this.txtPaint.setTextAlign(Paint.Align.CENTER);
this.txtPaint.setColor(Color.GRAY);
DecimalFormat decimalFomat = new DecimalFormat("##0.00");
this.totalPrice = decimalFomat.format(this.dataSum);
if (arcColors.length < datas.length) {
throw new IllegalArgumentException("颜色数组长度 不能小于 数据数组长度");
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
if (height > width) {
height = width;
} else {
width = height;
}
this.charRi = width / 6;
this.paintArc.setStrokeWidth(charRi);
rectF = new RectF();
rectF.left = -width / 2 + charRi / 1.5f;
rectF.right = width / 2 - charRi / 1.5f;
rectF.top = -width / 2 + charRi / 1.5f;
rectF.bottom = width / 2 - charRi / 1.5f;
// 半径变小 位置下移,角度不变
rectFSelected = new RectF();
rectFSelected.left = -width / 2 + charRi / 1.5f;
rectFSelected.right = width / 2 - charRi / 1.5f;
rectFSelected.top = -width / 2 + charRi / 1.5f;
rectFSelected.bottom = width / 2 - charRi / 1.5f;
this.tittleSize = 1.5F * (width - charRi * 2) / (6 * tittleStr.length());
this.priceSize = tittleSize*1.5F;
setMeasuredDimension(width, height);
}
private float startAngleTemp;
private void drawBackg(Canvas canvas) {
if (this.datas == null || this.dataSum == 0F) {
paintArc.setColor(Color.parseColor(defaultColor));
canvas.drawArc(rectF, 0F, 360F, false, paintArc);
return;
}
for (int i = 0; i < datas.length; i++) {
canvas.save();
paintArc.setColor(Color.parseColor(arcColors[i]));
startAngleTemp = 90F - 180F * datas[0] / dataSum;
if (i != 0) {
for (int j = 0; j < i; j++) {
startAngleTemp += 360F * datas[j] / dataSum;
}
}
if (this.ACTION_ == this.ACTION_ROTATION) {
if (curColorIndex == i && degree == degreeT && datas.length > 1) {
if (mOnItemChangedListener != null)
this.mOnItemChangedListener.onItemChanged(i, datas[i]);
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
gain(0.5f);
}
canvas.drawArc(rectF, startAngleTemp - 1.5f, 360F * datas[i] / dataSum + 1.5f, false, paintArc);
} else if (this.ACTION_ == this.ACTION_ENLARGE) {
if (curColorIndex == i && datas.length > 1) {
setRectFSelected();
canvas.drawArc(rectFSelected, startAngleTemp + 2f, 360F * datas[i] / dataSum - 5.5f, false, paintArc);
} else {
canvas.drawArc(rectF, startAngleTemp - 1.5f, 360F * datas[i] / dataSum + 1.5f, false, paintArc);
}
}
canvas.restore();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(tittleStr, width / 2 - tittleStr.length() / 2, width / 2 - tittleSize/1.5F , txtPaint);
txtPaint.setTextSize(priceSize);
txtPaint.setFakeBoldText(true);
txtPaint.setColor(Color.BLACK);
canvas.drawText(totalPrice, width / 2 - tittleStr.length() / 2, width / 2 + priceSize/1.5F, txtPaint);
txtPaint.setTextSize(tittleSize);
txtPaint.setFakeBoldText(false);
txtPaint.setColor(Color.GRAY);
canvas.translate(width / 2, width / 2);
canvas.rotate(degree);
drawBackg(canvas);
}
private float degreeT = 0;
private float curtX, curtY;
private float offsetDegree = 90f; //初始偏移量
private float curIndexdegree = 0f; //点击的色块角度
private float curIndexOffsetdegree = 0f; //点击的色块中线 偏移角度
private int curColorIndex = 0; //点击的色块 index
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
curtX = event.getX();
curtY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (this.datas == null || this.dataSum == 0F) {
break;
}
setDrawingCacheEnabled(true);
bitmap = getDrawingCache();
if (bitmap == null) {
Log.w(TAG, "bitmap == null");
break;
}
int pixel = bitmap.getPixel((int) curtX, (int) curtY);
setDrawingCacheEnabled(false);
//获取颜色RGB
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
int tarIndex = 0;
String curColorHex = ColorUtil.toHex(redValue, greenValue, blueValue);
for (int i = 0; i < arcColors.length; i++) {
if (curColorHex.equals(arcColors[i])) {
tarIndex = i;
break;
}
}
if (curColorIndex == tarIndex) {
break;
}
curColorIndex = tarIndex;
curIndexdegree = 360 * datas[curColorIndex] / dataSum;
if (curColorIndex == 0) {
curIndexOffsetdegree = 90;
} else {
curIndexOffsetdegree = 90;
for (int j = 0; j < curColorIndex; j++) {
if (j == 0) {
curIndexOffsetdegree += 180 * datas[j] / dataSum;
} else {
curIndexOffsetdegree += 360 * datas[j] / dataSum;
}
}
curIndexOffsetdegree += curIndexdegree / 2;
}
degreeT += offsetDegree - curIndexOffsetdegree;
offsetDegree = curIndexOffsetdegree;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
rotation(degreeT);
break;
}
return true;
}
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
if (this.ACTION_ == this.ACTION_ROTATION) {
degree = Float.valueOf(valueAnimator.getAnimatedValue().toString());
} else if (this.ACTION_ == this.ACTION_ENLARGE) {
gain = Float.valueOf(valueAnimator.getAnimatedValue().toString());
}
invalidate();
}
private void animateToValue(float value) {
if (this.ACTION_ == this.ACTION_ROTATION) {
if (valueAnimator == null) {
valueAnimator = createAnimator(value);
}
valueAnimator.setFloatValues(this.degree, value);
valueAnimator.setDuration(DURATION);
} else if (this.ACTION_ == this.ACTION_ENLARGE) {
valueAnimator = createAnimator(value);
valueAnimator.setFloatValues(this.gain, value);
valueAnimator.setDuration(DURATION_GAIN);
}
if (valueAnimator.isRunning()) {
valueAnimator.cancel();
}
valueAnimator.start();
}
private ValueAnimator createAnimator(float value) {
ValueAnimator valueAnimator = null;
if (this.ACTION_ == this.ACTION_ROTATION) {
valueAnimator = ValueAnimator.ofFloat(this.degree, value);
valueAnimator.setDuration(DURATION);
} else if (this.ACTION_ == this.ACTION_ENLARGE) {
valueAnimator = ValueAnimator.ofFloat(this.gain, value);
valueAnimator.setDuration(DURATION_GAIN);
}
valueAnimator.setInterpolator(new OvershootInterpolator());
valueAnimator.addUpdateListener(this);
return valueAnimator;
}
private void rotation(float degree) {
this.ACTION_ = this.ACTION_ROTATION;
if (this.degree != degree) {
animateToValue(degree);
}
}
private void gain(float gain) {
this.ACTION_ = this.ACTION_ENLARGE;
animateToValue(gain);
}
private void setRectFSelected() {
rectFSelected.left = -width / 2 + charRi / (1.5F + gain);
rectFSelected.right = width / 2 - charRi / (1.5F + gain);
rectFSelected.top = -width / 2 + charRi / (1.5F + gain);
rectFSelected.bottom = width / 2 - charRi / (1.5F + gain);
}
public void setDatas(Float[] dataFlo) {
if (dataFlo == null)
return;
if (dataFlo != null && dataFlo.length < 1)
return;
this.datas = dataFlo;
if (arcColors.length < datas.length) {
throw new IllegalArgumentException("颜色数组长度 不能小于 数据数组长度");
}
this.dataSum = 0f;
for (float dataitem :
dataFlo) {
this.dataSum += dataitem;
}
DecimalFormat decimalFomat = new DecimalFormat(".00");
this.totalPrice = decimalFomat.format(this.dataSum);
invalidate();
}
public void setOnItemChangedListener(OnItemChangedListener listener) {
this.mOnItemChangedListener = listener;
}
public interface OnItemChangedListener {
void onItemChanged(int index, float value);
}
}
| fairytale2016/PieChartView_Android_cn | _fa_pieChartView.java |
247,682 | package ij.plugin;
import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.frame.*;
import ij.macro.Interpreter;
import ij.plugin.filter.*;
import ij.util.Tools;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Vector;
/** This plugin implements the commands in the Edit/Section submenu. */
public class Selection implements PlugIn, Measurements {
private ImagePlus imp;
private float[] kernel = {1f, 1f, 1f, 1f, 1f};
private float[] kernel3 = {1f, 1f, 1f};
private static int bandSize = 15; // pixels
private static Color linec, fillc;
private static int lineWidth = 1;
private static boolean smooth;
private static boolean adjust;
public void run(String arg) {
imp = WindowManager.getCurrentImage();
if (arg.equals("add"))
{addToRoiManager(imp); return;}
if (imp==null)
{IJ.noImage(); return;}
if (arg.equals("all"))
imp.setRoi(0,0,imp.getWidth(),imp.getHeight());
else if (arg.equals("none"))
imp.deleteRoi();
else if (arg.equals("restore"))
imp.restoreRoi();
else if (arg.equals("spline"))
fitSpline();
else if (arg.equals("interpolate"))
interpolate();
else if (arg.equals("circle"))
fitCircle(imp);
else if (arg.equals("ellipse"))
createEllipse(imp);
else if (arg.equals("hull"))
convexHull(imp);
else if (arg.equals("mask"))
createMask(imp);
else if (arg.equals("from"))
createSelectionFromMask(imp);
else if (arg.equals("inverse"))
invert(imp);
else if (arg.equals("toarea"))
lineToArea(imp);
else if (arg.equals("toline"))
areaToLine(imp);
else if (arg.equals("properties"))
{setProperties("Properties ", imp.getRoi()); imp.draw();}
else if (arg.equals("band"))
makeBand(imp);
else if (arg.equals("tobox"))
toBoundingBox(imp);
else if (arg.equals("rotate"))
rotate(imp);
else if (arg.equals("enlarge"))
enlarge(imp);
}
private void rotate(ImagePlus imp) {
Roi roi = imp.getRoi();
if (IJ.macroRunning()) {
String options = Macro.getOptions();
if (options!=null && (options.indexOf("grid=")!=-1||options.indexOf("interpolat")!=-1)) {
IJ.run("Rotate... ", options); // run Image>Transform>Rotate
return;
}
}
(new RoiRotator()).run("");
}
private void enlarge(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi!=null) {
Undo.setup(Undo.ROI, imp);
roi = (Roi)roi.clone();
(new RoiEnlarger()).run("");
} else
noRoi("Enlarge");
}
/*
if selection is closed shape, create a circle with the same area and centroid, otherwise use<br>
the Pratt method to fit a circle to the points that define the line or multi-point selection.<br>
Reference: Pratt V., Direct least-squares fitting of algebraic surfaces", Computer Graphics, Vol. 21, pages 145-152 (1987).<br>
Original code: Nikolai Chernov's MATLAB script for Newton-based Pratt fit.<br>
(http://www.math.uab.edu/~chernov/cl/MATLABcircle.html)<br>
Java version: https://github.com/mdoube/BoneJ/blob/master/src/org/doube/geometry/FitCircle.java<br>
Authors: Nikolai Chernov, Michael Doube, Ved Sharma
*/
void fitCircle(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("Fit Circle");
return;
}
if (roi.isArea()) { //create circle with the same area and centroid
Undo.setup(Undo.ROI, imp);
ImageProcessor ip = imp.getProcessor();
ip.setRoi(roi);
ImageStatistics stats = ImageStatistics.getStatistics(ip, Measurements.AREA+Measurements.CENTROID, null);
double r = Math.sqrt(stats.pixelCount/Math.PI);
imp.deleteRoi();
int d = (int)Math.round(2.0*r);
Roi roi2 = new OvalRoi((int)Math.round(stats.xCentroid-r), (int)Math.round(stats.yCentroid-r), d, d);
transferProperties(roi, roi2);
imp.setRoi(roi2);
return;
}
Polygon poly = roi.getPolygon();
int n=poly.npoints;
int[] x = poly.xpoints;
int[] y = poly.ypoints;
if (n<3) {
IJ.error("Fit Circle", "At least 3 points are required to fit a circle.");
return;
}
// calculate point centroid
double sumx = 0, sumy = 0;
for (int i=0; i<n; i++) {
sumx = sumx + poly.xpoints[i];
sumy = sumy + poly.ypoints[i];
}
double meanx = sumx/n;
double meany = sumy/n;
// calculate moments
double[] X = new double[n], Y = new double[n];
double Mxx=0, Myy=0, Mxy=0, Mxz=0, Myz=0, Mzz=0;
for (int i=0; i<n; i++) {
X[i] = x[i] - meanx;
Y[i] = y[i] - meany;
double Zi = X[i]*X[i] + Y[i]*Y[i];
Mxy = Mxy + X[i]*Y[i];
Mxx = Mxx + X[i]*X[i];
Myy = Myy + Y[i]*Y[i];
Mxz = Mxz + X[i]*Zi;
Myz = Myz + Y[i]*Zi;
Mzz = Mzz + Zi*Zi;
}
Mxx = Mxx/n;
Myy = Myy/n;
Mxy = Mxy/n;
Mxz = Mxz/n;
Myz = Myz/n;
Mzz = Mzz/n;
// calculate the coefficients of the characteristic polynomial
double Mz = Mxx + Myy;
double Cov_xy = Mxx*Myy - Mxy*Mxy;
double Mxz2 = Mxz*Mxz;
double Myz2 = Myz*Myz;
double A2 = 4*Cov_xy - 3*Mz*Mz - Mzz;
double A1 = Mzz*Mz + 4*Cov_xy*Mz - Mxz2 - Myz2 - Mz*Mz*Mz;
double A0 = Mxz2*Myy + Myz2*Mxx - Mzz*Cov_xy - 2*Mxz*Myz*Mxy + Mz*Mz*Cov_xy;
double A22 = A2 + A2;
double epsilon = 1e-12;
double ynew = 1e+20;
int IterMax= 20;
double xnew = 0;
int iterations = 0;
// Newton's method starting at x=0
for (int iter=1; iter<=IterMax; iter++) {
iterations = iter;
double yold = ynew;
ynew = A0 + xnew*(A1 + xnew*(A2 + 4.*xnew*xnew));
if (Math.abs(ynew)>Math.abs(yold)) {
if (IJ.debugMode) IJ.log("Fit Circle: wrong direction: |ynew| > |yold|");
xnew = 0;
break;
}
double Dy = A1 + xnew*(A22 + 16*xnew*xnew);
double xold = xnew;
xnew = xold - ynew/Dy;
if (Math.abs((xnew-xold)/xnew) < epsilon)
break;
if (iter >= IterMax) {
if (IJ.debugMode) IJ.log("Fit Circle: will not converge");
xnew = 0;
}
if (xnew<0) {
if (IJ.debugMode) IJ.log("Fit Circle: negative root: x = "+xnew);
xnew = 0;
}
}
if (IJ.debugMode) IJ.log("Fit Circle: n="+n+", xnew="+IJ.d2s(xnew,2)+", iterations="+iterations);
// calculate the circle parameters
double DET = xnew*xnew - xnew*Mz + Cov_xy;
double CenterX = (Mxz*(Myy-xnew)-Myz*Mxy)/(2*DET);
double CenterY = (Myz*(Mxx-xnew)-Mxz*Mxy)/(2*DET);
double radius = Math.sqrt(CenterX*CenterX + CenterY*CenterY + Mz + 2*xnew);
if (Double.isNaN(radius)) {
IJ.error("Fit Circle", "Points are collinear.");
return;
}
CenterX = CenterX + meanx;
CenterY = CenterY + meany;
Undo.setup(Undo.ROI, imp);
imp.deleteRoi();
IJ.makeOval((int)Math.round(CenterX-radius), (int)Math.round(CenterY-radius), (int)Math.round(2*radius), (int)Math.round(2*radius));
}
void fitSpline() {
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Spline"); return;}
int type = roi.getType();
boolean segmentedSelection = type==Roi.POLYGON||type==Roi.POLYLINE;
if (!(segmentedSelection||type==Roi.FREEROI||type==Roi.TRACED_ROI||type==Roi.FREELINE))
{IJ.error("Spline", "Polygon or polyline selection required"); return;}
if (roi instanceof EllipseRoi)
return;
PolygonRoi p = (PolygonRoi)roi;
Undo.setup(Undo.ROI, imp);
if (!segmentedSelection && p.getNCoordinates()>3) {
if (p.subPixelResolution())
p = trimFloatPolygon(p, p.getUncalibratedLength());
else
p = trimPolygon(p, p.getUncalibratedLength());
}
String options = Macro.getOptions();
if (options!=null && options.indexOf("straighten")!=-1)
p.fitSplineForStraightening();
else if (options!=null && options.indexOf("remove")!=-1)
p.removeSplineFit();
else
p.fitSpline();
imp.draw();
LineWidthAdjuster.update();
}
void interpolate() {
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Interpolate"); return;}
if (roi.getType()==Roi.POINT)
return;
if (IJ.isMacro()&&Macro.getOptions()==null)
Macro.setOptions("interval=1");
GenericDialog gd = new GenericDialog("Interpolate");
gd.addNumericField("Interval:", 1.0, 1, 4, "pixel");
gd.addCheckbox("Smooth", IJ.isMacro()?false:smooth);
gd.addCheckbox("Adjust interval to match", IJ.isMacro()?false:adjust);
gd.showDialog();
if (gd.wasCanceled())
return;
double interval = gd.getNextNumber();
smooth = gd.getNextBoolean();
Undo.setup(Undo.ROI, imp);
adjust = gd.getNextBoolean();
int sign = adjust ? -1 : 1;
FloatPolygon poly = roi.getInterpolatedPolygon(sign*interval, smooth);
int t = roi.getType();
int type = roi.isLine()?Roi.FREELINE:Roi.FREEROI;
if (t==Roi.POLYGON && interval>1.0)
type = Roi.POLYGON;
if ((t==Roi.RECTANGLE||t==Roi.OVAL||t==Roi.FREEROI) && interval>=8.0)
type = Roi.POLYGON;
if ((t==Roi.LINE||t==Roi.FREELINE) && interval>=8.0)
type = Roi.POLYLINE;
if (t==Roi.POLYLINE && interval>=8.0)
type = Roi.POLYLINE;
ImageCanvas ic = imp.getCanvas();
if (poly.npoints<=150 && ic!=null && ic.getMagnification()>=12.0)
type = roi.isLine()?Roi.POLYLINE:Roi.POLYGON;
Roi p = new PolygonRoi(poly,type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setName(roi.getName());
transferProperties(roi, p);
imp.setRoi(p);
}
private void transferProperties(Roi roi1, Roi roi2) {
if (roi1==null || roi2==null)
return;
roi2.setStrokeColor(roi1.getStrokeColor());
if (roi1.getStroke()!=null)
roi2.setStroke(roi1.getStroke());
roi2.setDrawOffset(roi1.getDrawOffset());
}
PolygonRoi trimPolygon(PolygonRoi roi, double length) {
int[] x = roi.getXCoordinates();
int[] y = roi.getYCoordinates();
int n = roi.getNCoordinates();
x = smooth(x, n);
y = smooth(y, n);
float[] curvature = getCurvature(x, y, n);
Rectangle r = roi.getBounds();
double threshold = rodbard(length);
//IJ.log("trim: "+length+" "+threshold);
double distance = Math.sqrt((x[1]-x[0])*(x[1]-x[0])+(y[1]-y[0])*(y[1]-y[0]));
x[0] += r.x; y[0]+=r.y;
int i2 = 1;
int x1,y1,x2=0,y2=0;
for (int i=1; i<n-1; i++) {
x1=x[i]; y1=y[i]; x2=x[i+1]; y2=y[i+1];
distance += Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) + 1;
distance += curvature[i]*2;
if (distance>=threshold) {
x[i2] = x2 + r.x;
y[i2] = y2 + r.y;
i2++;
distance = 0.0;
}
}
int type = roi.getType()==Roi.FREELINE?Roi.POLYLINE:Roi.POLYGON;
if (type==Roi.POLYLINE && distance>0.0) {
x[i2] = x2 + r.x;
y[i2] = y2 + r.y;
i2++;
}
PolygonRoi p = new PolygonRoi(x, y, i2, type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setName(roi.getName());
imp.setRoi(p);
return p;
}
double rodbard(double x) {
// y = c*((a-x/(x-d))^(1/b)
// a=3.9, b=.88, c=712, d=44
double ex;
if (x == 0.0)
ex = 5.0;
else
ex = Math.exp(Math.log(x/700.0)*0.88);
double y = 3.9-44.0;
y = y/(1.0+ex);
return y+44.0;
}
int[] smooth(int[] a, int n) {
FloatProcessor fp = new FloatProcessor(n, 1);
for (int i=0; i<n; i++)
fp.putPixelValue(i, 0, a[i]);
GaussianBlur gb = new GaussianBlur();
gb.blur1Direction(fp, 2.0, 0.01, true, 0);
for (int i=0; i<n; i++)
a[i] = (int)Math.round(fp.getPixelValue(i, 0));
return a;
}
float[] getCurvature(int[] x, int[] y, int n) {
float[] x2 = new float[n];
float[] y2 = new float[n];
for (int i=0; i<n; i++) {
x2[i] = x[i];
y2[i] = y[i];
}
ImageProcessor ipx = new FloatProcessor(n, 1, x2, null);
ImageProcessor ipy = new FloatProcessor(n, 1, y2, null);
ipx.convolve(kernel, kernel.length, 1);
ipy.convolve(kernel, kernel.length, 1);
float[] indexes = new float[n];
float[] curvature = new float[n];
for (int i=0; i<n; i++) {
indexes[i] = i;
curvature[i] = (float)Math.sqrt((x2[i]-x[i])*(x2[i]-x[i])+(y2[i]-y[i])*(y2[i]-y[i]));
}
return curvature;
}
PolygonRoi trimFloatPolygon(PolygonRoi roi, double length) {
FloatPolygon poly = roi.getFloatPolygon();
float[] x = poly.xpoints;
float[] y = poly.ypoints;
int n = poly.npoints;
x = smooth(x, n);
y = smooth(y, n);
float[] curvature = getCurvature(x, y, n);
double threshold = rodbard(length);
//IJ.log("trim: "+length+" "+threshold);
double distance = Math.sqrt((x[1]-x[0])*(x[1]-x[0])+(y[1]-y[0])*(y[1]-y[0]));
int i2 = 1;
double x1,y1,x2=0,y2=0;
for (int i=1; i<n-1; i++) {
x1=x[i]; y1=y[i]; x2=x[i+1]; y2=y[i+1];
distance += Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) + 1;
distance += curvature[i]*2;
if (distance>=threshold) {
x[i2] = (float)x2;
y[i2] = (float)y2;
i2++;
distance = 0.0;
}
}
int type = roi.getType()==Roi.FREELINE?Roi.POLYLINE:Roi.POLYGON;
if (type==Roi.POLYLINE && distance>0.0) {
x[i2] = (float)x2;
y[i2] = (float)y2;
i2++;
}
PolygonRoi p = new PolygonRoi(x, y, i2, type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setDrawOffset(roi.getDrawOffset());
p.setName(roi.getName());
imp.setRoi(p);
return p;
}
float[] smooth(float[] a, int n) {
FloatProcessor fp = new FloatProcessor(n, 1);
for (int i=0; i<n; i++)
fp.setf(i, 0, a[i]);
GaussianBlur gb = new GaussianBlur();
gb.blur1Direction(fp, 2.0, 0.01, true, 0);
for (int i=0; i<n; i++)
a[i] = fp.getf(i, 0);
return a;
}
float[] getCurvature(float[] x, float[] y, int n) {
float[] x2 = new float[n];
float[] y2 = new float[n];
for (int i=0; i<n; i++) {
x2[i] = x[i];
y2[i] = y[i];
}
ImageProcessor ipx = new FloatProcessor(n, 1, x, null);
ImageProcessor ipy = new FloatProcessor(n, 1, y, null);
ipx.convolve(kernel, kernel.length, 1);
ipy.convolve(kernel, kernel.length, 1);
float[] indexes = new float[n];
float[] curvature = new float[n];
for (int i=0; i<n; i++) {
indexes[i] = i;
curvature[i] = (float)Math.sqrt((x2[i]-x[i])*(x2[i]-x[i])+(y2[i]-y[i])*(y2[i]-y[i]));
}
return curvature;
}
void createEllipse(ImagePlus imp) {
IJ.showStatus("Fitting ellipse");
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Fit Ellipse"); return;}
if (roi.isLine())
{IJ.error("Fit Ellipse", "\"Fit Ellipse\" does not work with line selections"); return;}
ImageProcessor ip = imp.getProcessor();
ip.setRoi(roi);
int options = Measurements.CENTROID+Measurements.ELLIPSE;
ImageStatistics stats = ImageStatistics.getStatistics(ip, options, null);
double dx = stats.major*Math.cos(stats.angle/180.0*Math.PI)/2.0;
double dy = - stats.major*Math.sin(stats.angle/180.0*Math.PI)/2.0;
double x1 = stats.xCentroid - dx;
double x2 = stats.xCentroid + dx;
double y1 = stats.yCentroid - dy;
double y2 = stats.yCentroid + dy;
double aspectRatio = stats.minor/stats.major;
Undo.setup(Undo.ROI, imp);
imp.deleteRoi();
Roi roi2 = new EllipseRoi(x1,y1,x2,y2,aspectRatio);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void convexHull(ImagePlus imp) {
Roi roi = imp.getRoi();
int type = roi!=null?roi.getType():-1;
if (!(type==Roi.FREEROI||type==Roi.TRACED_ROI||type==Roi.POLYGON||type==Roi.POINT))
{IJ.error("Convex Hull", "Polygonal or point selection required"); return;}
if (roi instanceof EllipseRoi)
return;
//if (roi.subPixelResolution() && roi instanceof PolygonRoi) {
// FloatPolygon p = ((PolygonRoi)roi).getFloatConvexHull();
// if (p!=null)
// imp.setRoi(new PolygonRoi(p.xpoints, p.ypoints, p.npoints, roi.POLYGON));
//} else {
Polygon p = roi.getConvexHull();
if (p!=null) {
Undo.setup(Undo.ROI, imp);
Roi roi2 = new PolygonRoi(p.xpoints, p.ypoints, p.npoints, roi.POLYGON);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
}
// Finds the index of the upper right point that is guaranteed to be on convex hull
int findFirstPoint(int[] xCoordinates, int[] yCoordinates, int n, ImagePlus imp) {
int smallestY = imp.getHeight();
int x, y;
for (int i=0; i<n; i++) {
y = yCoordinates[i];
if (y<smallestY)
smallestY = y;
}
int smallestX = imp.getWidth();
int p1 = 0;
for (int i=0; i<n; i++) {
x = xCoordinates[i];
y = yCoordinates[i];
if (y==smallestY && x<smallestX) {
smallestX = x;
p1 = i;
}
}
return p1;
}
void createMask(ImagePlus imp) {
Roi roi = imp.getRoi();
boolean useInvertingLut = Prefs.useInvertingLut;
Prefs.useInvertingLut = false;
boolean selectAll = roi!=null && roi.getType()==Roi.RECTANGLE && roi.getBounds().width==imp.getWidth()
&& roi.getBounds().height==imp.getHeight() && imp.isThreshold();
if (roi==null || !(roi.isArea()||roi.getType()==Roi.POINT) || selectAll) {
createMaskFromThreshold(imp);
Prefs.useInvertingLut = useInvertingLut;
return;
}
ImagePlus maskImp = null;
Frame frame = WindowManager.getFrame("Mask");
if (frame!=null && (frame instanceof ImageWindow))
maskImp = ((ImageWindow)frame).getImagePlus();
if (maskImp==null) {
ImageProcessor ip = new ByteProcessor(imp.getWidth(), imp.getHeight());
if (!Prefs.blackBackground)
ip.invertLut();
maskImp = new ImagePlus("Mask", ip);
maskImp.show();
}
ImageProcessor ip = maskImp.getProcessor();
ip.setRoi(roi);
ip.setValue(255);
ip.fill(ip.getMask());
Calibration cal = imp.getCalibration();
if (cal.scaled()) {
Calibration cal2 = maskImp.getCalibration();
cal2.pixelWidth = cal.pixelWidth;
cal2.pixelHeight = cal.pixelHeight;
cal2.setUnit(cal.getUnit());
}
maskImp.updateAndRepaintWindow();
Prefs.useInvertingLut = useInvertingLut;
}
void createMaskFromThreshold(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
if (ip.getMinThreshold()==ImageProcessor.NO_THRESHOLD)
{IJ.error("Create Mask", "Area selection or thresholded image required"); return;}
double t1 = ip.getMinThreshold();
double t2 = ip.getMaxThreshold();
IJ.run("Duplicate...", "title=mask");
ImagePlus imp2 = WindowManager.getCurrentImage();
ImageProcessor ip2 = imp2.getProcessor();
ip2.setThreshold(t1, t2, ip2.getLutUpdateMode());
IJ.run("Convert to Mask");
}
void createSelectionFromMask(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
if (ip.getMinThreshold()!=ImageProcessor.NO_THRESHOLD) {
IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
return;
}
if (!ip.isBinary()) {
IJ.error("Create Selection",
"This command creates a composite selection from\n"+
"a mask (8-bit binary image with white background)\n"+
"or from an image that has been thresholded using\n"+
"the Image>Adjust>Threshold tool. The current\n"+
"image is not a mask and has not been thresholded.");
return;
}
int threshold = ip.isInvertedLut()?255:0;
ip.setThreshold(threshold, threshold, ImageProcessor.NO_LUT_UPDATE);
IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
}
void invert(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null || !roi.isArea())
{IJ.error("Inverse", "Area selection required"); return;}
ShapeRoi s1, s2;
if (roi instanceof ShapeRoi)
s1 = (ShapeRoi)roi;
else
s1 = new ShapeRoi(roi);
s2 = new ShapeRoi(new Roi(0,0, imp.getWidth(), imp.getHeight()));
Undo.setup(Undo.ROI, imp);
imp.setRoi(s1.xor(s2));
}
void lineToArea(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null || !roi.isLine())
{IJ.error("Line to Area", "Line selection required"); return;}
Undo.setup(Undo.ROI, imp);
Roi roi2 = null;
if (roi.getType()==Roi.LINE) {
double width = roi.getStrokeWidth();
if (width<=1.0)
roi.setStrokeWidth(1.0000001);
FloatPolygon p = roi.getFloatPolygon();
roi.setStrokeWidth(width);
roi2 = new PolygonRoi(p, Roi.POLYGON);
roi2.setDrawOffset(roi.getDrawOffset());
} else {
ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight());
ip2.setColor(255);
roi.drawPixels(ip2);
//new ImagePlus("ip2", ip2.duplicate()).show();
ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
ThresholdToSelection tts = new ThresholdToSelection();
roi2 = tts.convert(ip2);
}
transferProperties(roi, roi2);
roi2.setStrokeWidth(0);
Color c = roi2.getStrokeColor();
if (c!=null) // remove any transparency
roi2.setStrokeColor(new Color(c.getRed(),c.getGreen(),c.getBlue()));
imp.setRoi(roi2);
Roi.previousRoi = (Roi)roi.clone();
}
void areaToLine(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null || !roi.isArea()) {
IJ.error("Area to Line", "Area selection required");
return;
}
Undo.setup(Undo.ROI, imp);
Polygon p = roi.getPolygon();
if (p==null) return;
int type1 = roi.getType();
if (type1==Roi.COMPOSITE) {
IJ.error("Area to Line", "Composite selections cannot be converted to lines.");
return;
}
int type2 = Roi.POLYLINE;
if (type1==Roi.OVAL||type1==Roi.FREEROI||type1==Roi.TRACED_ROI
||((roi instanceof PolygonRoi)&&((PolygonRoi)roi).isSplineFit()))
type2 = Roi.FREELINE;
Roi roi2 = new PolygonRoi(p.xpoints, p.ypoints, p.npoints, type2);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void toBoundingBox(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("To Bounding Box");
return;
}
Undo.setup(Undo.ROI, imp);
Rectangle r = roi.getBounds();
imp.deleteRoi();
Roi roi2 = new Roi(r.x, r.y, r.width, r.height);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void addToRoiManager(ImagePlus imp) {
if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager())
IJ.error("run(\"Add to Manager\") may not work in batch mode macros");
Frame frame = WindowManager.getFrame("ROI Manager");
if (frame==null)
IJ.run("ROI Manager...");
if (imp==null) return;
Roi roi = imp.getRoi();
if (roi==null) return;
frame = WindowManager.getFrame("ROI Manager");
if (frame==null || !(frame instanceof RoiManager))
IJ.error("ROI Manager not found");
RoiManager rm = (RoiManager)frame;
boolean altDown= IJ.altKeyDown();
IJ.setKeyUp(IJ.ALL_KEYS);
if (altDown && !IJ.macroRunning())
IJ.setKeyDown(KeyEvent.VK_SHIFT);
if (roi.getState()==Roi.CONSTRUCTING) { //wait (up to 2 sec.) until ROI finished
long start = System.currentTimeMillis();
while (true) {
IJ.wait(10);
if (roi.getState()!=Roi.CONSTRUCTING)
break;
if ((System.currentTimeMillis()-start)>2000) {
IJ.beep();
IJ.error("Add to Manager", "Selection is not complete");
return;
}
}
}
rm.allowRecording(true);
rm.runCommand("add");
rm.allowRecording(false);
IJ.setKeyUp(IJ.ALL_KEYS);
}
boolean setProperties(String title, Roi roi) {
if ((roi instanceof PointRoi) && Toolbar.getMultiPointMode()) {
((PointRoi)roi).displayCounts();
return true;
}
Frame f = WindowManager.getFrontWindow();
if (f!=null && f.getTitle().indexOf("3D Viewer")!=-1)
return false;
if (roi==null) {
IJ.error("This command requires a selection.");
return false;
}
RoiProperties rp = new RoiProperties(title, roi);
boolean ok = rp.showDialog();
if (IJ.debugMode)
IJ.log(roi.getDebugInfo());
return ok;
}
private void makeBand(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("Make Band");
return;
}
Roi roiOrig = roi;
if (!roi.isArea()) {
IJ.error("Make Band", "Area selection required");
return;
}
Calibration cal = imp.getCalibration();
double pixels = bandSize;
double size = pixels*cal.pixelWidth;
int decimalPlaces = 0;
if ((int)size!=size)
decimalPlaces = 2;
GenericDialog gd = new GenericDialog("Make Band");
gd.addNumericField("Band Size:", size, decimalPlaces, 4, cal.getUnits());
gd.showDialog();
if (gd.wasCanceled())
return;
size = gd.getNextNumber();
if (Double.isNaN(size)) {
IJ.error("Make Band", "invalid number");
return;
}
int n = (int)Math.round(size/cal.pixelWidth);
if (n >255) {
IJ.error("Make Band", "Cannot make bands wider that 255 pixels");
return;
}
int width = imp.getWidth();
int height = imp.getHeight();
Rectangle r = roi.getBounds();
ImageProcessor ip = roi.getMask();
if (ip==null) {
ip = new ByteProcessor(r.width, r.height);
ip.invert();
}
ImageProcessor mask = new ByteProcessor(width, height);
mask.insert(ip, r.x, r.y);
ImagePlus edm = new ImagePlus("mask", mask);
boolean saveBlackBackground = Prefs.blackBackground;
Prefs.blackBackground = false;
int saveType = EDM.getOutputType();
EDM.setOutputType(EDM.BYTE_OVERWRITE);
IJ.run(edm, "Distance Map", "");
EDM.setOutputType(saveType);
Prefs.blackBackground = saveBlackBackground;
ip = edm.getProcessor();
ip.setThreshold(0, n, ImageProcessor.NO_LUT_UPDATE);
int xx=-1, yy=-1;
for (int x=r.x; x<r.x+r.width; x++) {
for (int y=r.y; y<r.y+r.height; y++) {
if (ip.getPixel(x, y)<n) {
xx=x; yy=y;
break;
}
}
if (xx>=0||yy>=0)
break;
}
int count = IJ.doWand(edm, xx, yy, 0, null);
if (count<=0) {
IJ.error("Make Band", "Unable to make band");
return;
}
ShapeRoi roi2 = new ShapeRoi(edm.getRoi());
if (!(roi instanceof ShapeRoi))
roi = new ShapeRoi(roi);
ShapeRoi roi1 = (ShapeRoi)roi;
roi2 = roi2.not(roi1);
Undo.setup(Undo.ROI, imp);
transferProperties(roiOrig, roi2);
imp.setRoi(roi2);
bandSize = n;
}
void noRoi(String command) {
IJ.error(command, "This command requires a selection");
}
}
| Barchid/VISA | IJ/src/ij/plugin/Selection.java |
247,683 | package ij.plugin;
import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.frame.*;
import ij.macro.Interpreter;
import ij.plugin.filter.*;
import ij.util.Tools;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Vector;
/** This plugin implements the commands in the Edit/Selection submenu. */
public class Selection implements PlugIn, Measurements {
private ImagePlus imp;
private float[] kernel = {1f, 1f, 1f, 1f, 1f};
private float[] kernel3 = {1f, 1f, 1f};
private static int bandSize = 15; // pixels
private static Color linec, fillc;
private static int lineWidth = 1;
private static boolean smooth;
private static boolean adjust;
public void run(String arg) {
imp = WindowManager.getCurrentImage();
if (arg.equals("add"))
{addToRoiManager(imp); return;}
if (imp==null)
{IJ.noImage(); return;}
if (arg.equals("all")) {
imp.saveRoi();
imp.setRoi(0,0,imp.getWidth(),imp.getHeight());
} else if (arg.equals("none"))
imp.deleteRoi();
else if (arg.equals("restore"))
imp.restoreRoi();
else if (arg.equals("spline"))
fitSpline();
else if (arg.equals("interpolate"))
interpolate();
else if (arg.equals("circle"))
fitCircle(imp);
else if (arg.equals("ellipse"))
createEllipse(imp);
else if (arg.equals("hull"))
convexHull(imp);
else if (arg.equals("mask"))
createMask(imp);
else if (arg.equals("from"))
createSelectionFromMask(imp);
else if (arg.equals("inverse"))
invert(imp);
else if (arg.equals("toarea"))
lineToArea(imp);
else if (arg.equals("toline"))
areaToLine(imp);
else if (arg.equals("properties"))
{setProperties("Properties ", imp.getRoi()); imp.draw();}
else if (arg.equals("band"))
makeBand(imp);
else if (arg.equals("tobox"))
toBoundingBox(imp);
else if (arg.equals("rotate"))
rotate(imp);
else if (arg.equals("enlarge"))
enlarge(imp);
}
private void rotate(ImagePlus imp) {
Roi roi = imp.getRoi();
if (IJ.macroRunning()) {
String options = Macro.getOptions();
if (options!=null && (options.indexOf("grid=")!=-1||options.indexOf("interpolat")!=-1)) {
IJ.run("Rotate... ", options); // run Image>Transform>Rotate
return;
}
}
(new RoiRotator()).run("");
}
private void enlarge(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi!=null) {
Undo.setup(Undo.ROI, imp);
roi = (Roi)roi.clone();
(new RoiEnlarger()).run("");
} else
noRoi("Enlarge");
}
/*
if selection is closed shape, create a circle with the same area and centroid, otherwise use<br>
the Pratt method to fit a circle to the points that define the line or multi-point selection.<br>
Reference: Pratt V., Direct least-squares fitting of algebraic surfaces", Computer Graphics, Vol. 21, pages 145-152 (1987).<br>
Original code: Nikolai Chernov's MATLAB script for Newton-based Pratt fit.<br>
(http://www.math.uab.edu/~chernov/cl/MATLABcircle.html)<br>
Java version: https://github.com/mdoube/BoneJ/blob/master/src/org/doube/geometry/FitCircle.java<br>
Authors: Nikolai Chernov, Michael Doube, Ved Sharma
*/
void fitCircle(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("Fit Circle");
return;
}
if (roi.isArea()) { //create circle with the same area and centroid
Undo.setup(Undo.ROI, imp);
ImageProcessor ip = imp.getProcessor();
ip.setRoi(roi);
ImageStatistics stats = ImageStatistics.getStatistics(ip, Measurements.AREA+Measurements.CENTROID, null);
double r = Math.sqrt(stats.pixelCount/Math.PI);
imp.deleteRoi();
int d = (int)Math.round(2.0*r);
Roi roi2 = new OvalRoi((int)Math.round(stats.xCentroid-r), (int)Math.round(stats.yCentroid-r), d, d);
transferProperties(roi, roi2);
imp.setRoi(roi2);
return;
}
Polygon poly = roi.getPolygon();
int n=poly.npoints;
int[] x = poly.xpoints;
int[] y = poly.ypoints;
if (n<3) {
IJ.error("Fit Circle", "At least 3 points are required to fit a circle.");
return;
}
// calculate point centroid
double sumx = 0, sumy = 0;
for (int i=0; i<n; i++) {
sumx = sumx + poly.xpoints[i];
sumy = sumy + poly.ypoints[i];
}
double meanx = sumx/n;
double meany = sumy/n;
// calculate moments
double[] X = new double[n], Y = new double[n];
double Mxx=0, Myy=0, Mxy=0, Mxz=0, Myz=0, Mzz=0;
for (int i=0; i<n; i++) {
X[i] = x[i] - meanx;
Y[i] = y[i] - meany;
double Zi = X[i]*X[i] + Y[i]*Y[i];
Mxy = Mxy + X[i]*Y[i];
Mxx = Mxx + X[i]*X[i];
Myy = Myy + Y[i]*Y[i];
Mxz = Mxz + X[i]*Zi;
Myz = Myz + Y[i]*Zi;
Mzz = Mzz + Zi*Zi;
}
Mxx = Mxx/n;
Myy = Myy/n;
Mxy = Mxy/n;
Mxz = Mxz/n;
Myz = Myz/n;
Mzz = Mzz/n;
// calculate the coefficients of the characteristic polynomial
double Mz = Mxx + Myy;
double Cov_xy = Mxx*Myy - Mxy*Mxy;
double Mxz2 = Mxz*Mxz;
double Myz2 = Myz*Myz;
double A2 = 4*Cov_xy - 3*Mz*Mz - Mzz;
double A1 = Mzz*Mz + 4*Cov_xy*Mz - Mxz2 - Myz2 - Mz*Mz*Mz;
double A0 = Mxz2*Myy + Myz2*Mxx - Mzz*Cov_xy - 2*Mxz*Myz*Mxy + Mz*Mz*Cov_xy;
double A22 = A2 + A2;
double epsilon = 1e-12;
double ynew = 1e+20;
int IterMax= 20;
double xnew = 0;
int iterations = 0;
// Newton's method starting at x=0
for (int iter=1; iter<=IterMax; iter++) {
iterations = iter;
double yold = ynew;
ynew = A0 + xnew*(A1 + xnew*(A2 + 4.*xnew*xnew));
if (Math.abs(ynew)>Math.abs(yold)) {
if (IJ.debugMode) IJ.log("Fit Circle: wrong direction: |ynew| > |yold|");
xnew = 0;
break;
}
double Dy = A1 + xnew*(A22 + 16*xnew*xnew);
double xold = xnew;
xnew = xold - ynew/Dy;
if (Math.abs((xnew-xold)/xnew) < epsilon)
break;
if (iter >= IterMax) {
if (IJ.debugMode) IJ.log("Fit Circle: will not converge");
xnew = 0;
}
if (xnew<0) {
if (IJ.debugMode) IJ.log("Fit Circle: negative root: x = "+xnew);
xnew = 0;
}
}
if (IJ.debugMode) IJ.log("Fit Circle: n="+n+", xnew="+IJ.d2s(xnew,2)+", iterations="+iterations);
// calculate the circle parameters
double DET = xnew*xnew - xnew*Mz + Cov_xy;
double CenterX = (Mxz*(Myy-xnew)-Myz*Mxy)/(2*DET);
double CenterY = (Myz*(Mxx-xnew)-Mxz*Mxy)/(2*DET);
double radius = Math.sqrt(CenterX*CenterX + CenterY*CenterY + Mz + 2*xnew);
if (Double.isNaN(radius)) {
IJ.error("Fit Circle", "Points are collinear.");
return;
}
CenterX = CenterX + meanx;
CenterY = CenterY + meany;
Undo.setup(Undo.ROI, imp);
imp.deleteRoi();
IJ.makeOval((int)Math.round(CenterX-radius), (int)Math.round(CenterY-radius), (int)Math.round(2*radius), (int)Math.round(2*radius));
}
void fitSpline() {
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Spline"); return;}
int type = roi.getType();
boolean segmentedSelection = type==Roi.POLYGON||type==Roi.POLYLINE;
if (!(segmentedSelection||type==Roi.FREEROI||type==Roi.TRACED_ROI||type==Roi.FREELINE))
{IJ.error("Spline Fit", "Polygon or polyline selection required"); return;}
if (roi instanceof EllipseRoi)
return;
PolygonRoi p = (PolygonRoi)roi;
Undo.setup(Undo.ROI, imp);
if (!segmentedSelection && p.getNCoordinates()>3) {
if (p.subPixelResolution())
p = trimFloatPolygon(p, p.getUncalibratedLength());
else
p = trimPolygon(p, p.getUncalibratedLength());
}
String options = Macro.getOptions();
if (options!=null && options.indexOf("straighten")!=-1)
p.fitSplineForStraightening();
else if (options!=null && options.indexOf("remove")!=-1)
p.removeSplineFit();
else
p.fitSpline();
imp.draw();
LineWidthAdjuster.update();
}
void interpolate() {
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Interpolate"); return;}
if (roi.getType()==Roi.POINT)
return;
if (IJ.isMacro()&&Macro.getOptions()==null)
Macro.setOptions("interval=1");
GenericDialog gd = new GenericDialog("Interpolate");
gd.addNumericField("Interval:", 1.0, 1, 4, "pixel");
gd.addCheckbox("Smooth", IJ.isMacro()?false:smooth);
gd.addCheckbox("Adjust interval to match", IJ.isMacro()?false:adjust);
gd.showDialog();
if (gd.wasCanceled())
return;
double interval = gd.getNextNumber();
smooth = gd.getNextBoolean();
Undo.setup(Undo.ROI, imp);
adjust = gd.getNextBoolean();
int sign = adjust ? -1 : 1;
FloatPolygon poly = roi.getInterpolatedPolygon(sign*interval, smooth);
int t = roi.getType();
int type = roi.isLine()?Roi.FREELINE:Roi.FREEROI;
if (t==Roi.POLYGON && interval>1.0)
type = Roi.POLYGON;
if ((t==Roi.RECTANGLE||t==Roi.OVAL||t==Roi.FREEROI) && interval>=8.0)
type = Roi.POLYGON;
if ((t==Roi.LINE||t==Roi.FREELINE) && interval>=8.0)
type = Roi.POLYLINE;
if (t==Roi.POLYLINE && interval>=8.0)
type = Roi.POLYLINE;
ImageCanvas ic = imp.getCanvas();
if (poly.npoints<=150 && ic!=null && ic.getMagnification()>=12.0)
type = roi.isLine()?Roi.POLYLINE:Roi.POLYGON;
Roi p = new PolygonRoi(poly,type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setName(roi.getName());
transferProperties(roi, p);
imp.setRoi(p);
}
private static void transferProperties(Roi roi1, Roi roi2) {
if (roi1==null || roi2==null)
return;
roi2.setStrokeColor(roi1.getStrokeColor());
if (roi1.getStroke()!=null)
roi2.setStroke(roi1.getStroke());
roi2.setDrawOffset(roi1.getDrawOffset());
}
PolygonRoi trimPolygon(PolygonRoi roi, double length) {
int[] x = roi.getXCoordinates();
int[] y = roi.getYCoordinates();
int n = roi.getNCoordinates();
x = smooth(x, n);
y = smooth(y, n);
float[] curvature = getCurvature(x, y, n);
Rectangle r = roi.getBounds();
double threshold = rodbard(length);
//IJ.log("trim: "+length+" "+threshold);
double distance = Math.sqrt((x[1]-x[0])*(x[1]-x[0])+(y[1]-y[0])*(y[1]-y[0]));
x[0] += r.x; y[0]+=r.y;
int i2 = 1;
int x1,y1,x2=0,y2=0;
for (int i=1; i<n-1; i++) {
x1=x[i]; y1=y[i]; x2=x[i+1]; y2=y[i+1];
distance += Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) + 1;
distance += curvature[i]*2;
if (distance>=threshold) {
x[i2] = x2 + r.x;
y[i2] = y2 + r.y;
i2++;
distance = 0.0;
}
}
int type = roi.getType()==Roi.FREELINE?Roi.POLYLINE:Roi.POLYGON;
if (type==Roi.POLYLINE && distance>0.0) {
x[i2] = x2 + r.x;
y[i2] = y2 + r.y;
i2++;
}
PolygonRoi p = new PolygonRoi(x, y, i2, type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setName(roi.getName());
imp.setRoi(p);
return p;
}
double rodbard(double x) {
// y = c*((a-x/(x-d))^(1/b)
// a=3.9, b=.88, c=712, d=44
double ex;
if (x == 0.0)
ex = 5.0;
else
ex = Math.exp(Math.log(x/700.0)*0.88);
double y = 3.9-44.0;
y = y/(1.0+ex);
return y+44.0;
}
int[] smooth(int[] a, int n) {
FloatProcessor fp = new FloatProcessor(n, 1);
for (int i=0; i<n; i++)
fp.putPixelValue(i, 0, a[i]);
GaussianBlur gb = new GaussianBlur();
gb.blur1Direction(fp, 2.0, 0.01, true, 0);
for (int i=0; i<n; i++)
a[i] = (int)Math.round(fp.getPixelValue(i, 0));
return a;
}
float[] getCurvature(int[] x, int[] y, int n) {
float[] x2 = new float[n];
float[] y2 = new float[n];
for (int i=0; i<n; i++) {
x2[i] = x[i];
y2[i] = y[i];
}
ImageProcessor ipx = new FloatProcessor(n, 1, x2, null);
ImageProcessor ipy = new FloatProcessor(n, 1, y2, null);
ipx.convolve(kernel, kernel.length, 1);
ipy.convolve(kernel, kernel.length, 1);
float[] indexes = new float[n];
float[] curvature = new float[n];
for (int i=0; i<n; i++) {
indexes[i] = i;
curvature[i] = (float)Math.sqrt((x2[i]-x[i])*(x2[i]-x[i])+(y2[i]-y[i])*(y2[i]-y[i]));
}
return curvature;
}
PolygonRoi trimFloatPolygon(PolygonRoi roi, double length) {
FloatPolygon poly = roi.getFloatPolygon();
float[] x = poly.xpoints;
float[] y = poly.ypoints;
int n = poly.npoints;
x = smooth(x, n);
y = smooth(y, n);
float[] curvature = getCurvature(x, y, n);
double threshold = rodbard(length);
//IJ.log("trim: "+length+" "+threshold);
double distance = Math.sqrt((x[1]-x[0])*(x[1]-x[0])+(y[1]-y[0])*(y[1]-y[0]));
int i2 = 1;
double x1,y1,x2=0,y2=0;
for (int i=1; i<n-1; i++) {
x1=x[i]; y1=y[i]; x2=x[i+1]; y2=y[i+1];
distance += Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) + 1;
distance += curvature[i]*2;
if (distance>=threshold) {
x[i2] = (float)x2;
y[i2] = (float)y2;
i2++;
distance = 0.0;
}
}
int type = roi.getType()==Roi.FREELINE?Roi.POLYLINE:Roi.POLYGON;
if (type==Roi.POLYLINE && distance>0.0) {
x[i2] = (float)x2;
y[i2] = (float)y2;
i2++;
}
PolygonRoi p = new PolygonRoi(x, y, i2, type);
if (roi.getStroke()!=null)
p.setStrokeWidth(roi.getStrokeWidth());
p.setStrokeColor(roi.getStrokeColor());
p.setDrawOffset(roi.getDrawOffset());
p.setName(roi.getName());
imp.setRoi(p);
return p;
}
float[] smooth(float[] a, int n) {
FloatProcessor fp = new FloatProcessor(n, 1);
for (int i=0; i<n; i++)
fp.setf(i, 0, a[i]);
GaussianBlur gb = new GaussianBlur();
gb.blur1Direction(fp, 2.0, 0.01, true, 0);
for (int i=0; i<n; i++)
a[i] = fp.getf(i, 0);
return a;
}
float[] getCurvature(float[] x, float[] y, int n) {
float[] x2 = new float[n];
float[] y2 = new float[n];
for (int i=0; i<n; i++) {
x2[i] = x[i];
y2[i] = y[i];
}
ImageProcessor ipx = new FloatProcessor(n, 1, x, null);
ImageProcessor ipy = new FloatProcessor(n, 1, y, null);
ipx.convolve(kernel, kernel.length, 1);
ipy.convolve(kernel, kernel.length, 1);
float[] indexes = new float[n];
float[] curvature = new float[n];
for (int i=0; i<n; i++) {
indexes[i] = i;
curvature[i] = (float)Math.sqrt((x2[i]-x[i])*(x2[i]-x[i])+(y2[i]-y[i])*(y2[i]-y[i]));
}
return curvature;
}
void createEllipse(ImagePlus imp) {
IJ.showStatus("Fitting ellipse");
Roi roi = imp.getRoi();
if (roi==null)
{noRoi("Fit Ellipse"); return;}
if (roi.isLine())
{IJ.error("Fit Ellipse", "\"Fit Ellipse\" does not work with line selections"); return;}
ImageProcessor ip = imp.getProcessor();
ip.setRoi(roi);
int options = Measurements.CENTROID+Measurements.ELLIPSE;
ImageStatistics stats = ImageStatistics.getStatistics(ip, options, null);
double dx = stats.major*Math.cos(stats.angle/180.0*Math.PI)/2.0;
double dy = - stats.major*Math.sin(stats.angle/180.0*Math.PI)/2.0;
double x1 = stats.xCentroid - dx;
double x2 = stats.xCentroid + dx;
double y1 = stats.yCentroid - dy;
double y2 = stats.yCentroid + dy;
double aspectRatio = stats.minor/stats.major;
Undo.setup(Undo.ROI, imp);
imp.deleteRoi();
Roi roi2 = new EllipseRoi(x1,y1,x2,y2,aspectRatio);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void convexHull(ImagePlus imp) {
long startTime = System.currentTimeMillis();
Roi roi = imp.getRoi();
if (roi == null) { IJ.error("Convex Hull", "Selection required"); return; }
if (roi instanceof Line) { IJ.error("Convex Hull", "Area selection, point selection, or segmented or free line required"); return; }
FloatPolygon p = roi.getFloatConvexHull();
if (p!=null) {
Undo.setup(Undo.ROI, imp);
Roi roi2 = new PolygonRoi(p, roi.POLYGON);
transferProperties(roi, roi2);
imp.setRoi(roi2);
IJ.showTime(imp, startTime, "Convex Hull ", 1);
}
}
// Finds the index of the upper right point that is guaranteed to be on convex hull
/*int findFirstPoint(int[] xCoordinates, int[] yCoordinates, int n, ImagePlus imp) {
int smallestY = imp.getHeight();
int x, y;
for (int i=0; i<n; i++) {
y = yCoordinates[i];
if (y<smallestY)
smallestY = y;
}
int smallestX = imp.getWidth();
int p1 = 0;
for (int i=0; i<n; i++) {
x = xCoordinates[i];
y = yCoordinates[i];
if (y==smallestY && x<smallestX) {
smallestX = x;
p1 = i;
}
}
return p1;
}*/
void createMask(ImagePlus imp) {
Roi roi = imp.getRoi();
boolean useInvertingLut = Prefs.useInvertingLut;
Prefs.useInvertingLut = false;
boolean selectAll = roi!=null && roi.getType()==Roi.RECTANGLE && roi.getBounds().width==imp.getWidth()
&& roi.getBounds().height==imp.getHeight() && imp.isThreshold();
boolean overlay = imp.getOverlay()!=null && imp.getProcessor().getMinThreshold()==ImageProcessor.NO_THRESHOLD;
if (!overlay && (roi==null || selectAll)) {
createMaskFromThreshold(imp);
Prefs.useInvertingLut = useInvertingLut;
return;
}
if (roi==null && imp.getOverlay()==null) {
IJ.error("Create Mask", "Selection, overlay or threshold required");
return;
}
ByteProcessor mask = imp.createRoiMask();
if (!Prefs.blackBackground)
mask.invertLut();
mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
ImagePlus maskImp = null;
Frame frame = WindowManager.getFrame("Mask");
if (frame!=null && (frame instanceof ImageWindow))
maskImp = ((ImageWindow)frame).getImagePlus();
if (maskImp!=null && maskImp.getBitDepth()==8) {
ImageProcessor ip = maskImp.getProcessor();
ip.copyBits(mask, 0, 0, Blitter.OR);
maskImp.setProcessor(ip);
} else {
maskImp = new ImagePlus("Mask", mask);
maskImp.show();
}
Calibration cal = imp.getCalibration();
if (cal.scaled()) {
Calibration cal2 = maskImp.getCalibration();
cal2.pixelWidth = cal.pixelWidth;
cal2.pixelHeight = cal.pixelHeight;
cal2.setUnit(cal.getUnit());
}
maskImp.updateAndRepaintWindow();
Prefs.useInvertingLut = useInvertingLut;
Recorder.recordCall("mask = imp.createRoiMask();");
}
void createMaskFromThreshold(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
if (ip.getMinThreshold()==ImageProcessor.NO_THRESHOLD) {
IJ.error("Create Mask", "Area selection, overlay or thresholded image required");
return;
}
ByteProcessor mask = imp.createThresholdMask();
if (!Prefs.blackBackground)
mask.invertLut();
mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
ImagePlus maskImp = new ImagePlus("mask",mask);
Calibration cal = imp.getCalibration();
if (cal.scaled()) {
Calibration cal2 = maskImp.getCalibration();
cal2.pixelWidth = cal.pixelWidth;
cal2.pixelHeight = cal.pixelHeight;
cal2.setUnit(cal.getUnit());
}
maskImp.show();
Recorder.recordCall("mask = imp.createThresholdMask();");
}
void createSelectionFromMask(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
if (ip.getMinThreshold()!=ImageProcessor.NO_THRESHOLD) {
IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
return;
}
if (!ip.isBinary()) {
IJ.error("Create Selection",
"This command creates a composite selection from\n"+
"a mask (8-bit binary image with white background)\n"+
"or from an image that has been thresholded using\n"+
"the Image>Adjust>Threshold tool. The current\n"+
"image is not a mask and has not been thresholded.");
return;
}
int threshold = ip.isInvertedLut()?255:0;
ip.setThreshold(threshold, threshold, ImageProcessor.NO_LUT_UPDATE);
IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
}
void invert(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi == null)
{run("all"); return;}
if (!roi.isArea())
{IJ.error("Inverse", "Area selection required"); return;}
Roi inverse = roi.getInverse(imp);
Undo.setup(Undo.ROI, imp);
imp.setRoi(inverse);
}
private void lineToArea(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null || !roi.isLine())
{IJ.error("Line to Area", "Line selection required"); return;}
Undo.setup(Undo.ROI, imp);
Roi roi2 = lineToArea(roi);
imp.setRoi(roi2);
Roi.previousRoi = (Roi)roi.clone();
}
/** Converts a line selection into an area selection. */
public static Roi lineToArea(Roi roi) {
Roi roi2 = null;
if (roi.getType()==Roi.LINE) {
double width = roi.getStrokeWidth();
if (width<=1.0)
roi.setStrokeWidth(1.0000001);
FloatPolygon p = roi.getFloatPolygon();
roi.setStrokeWidth(width);
roi2 = new PolygonRoi(p, Roi.POLYGON);
roi2.setDrawOffset(roi.getDrawOffset());
} else {
roi = (Roi)roi.clone();
int lwidth = (int)roi.getStrokeWidth();
if (lwidth<1)
lwidth = 1;
Rectangle bounds = roi.getBounds();
int width = bounds.width + lwidth*2;
int height = bounds.height + lwidth*2;
ImageProcessor ip2 = new ByteProcessor(width, height);
roi.setLocation(lwidth, lwidth);
ip2.setColor(255);
roi.drawPixels(ip2);
ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
ThresholdToSelection tts = new ThresholdToSelection();
roi2 = tts.convert(ip2);
if (roi2==null)
return roi;
if (bounds.x==0&&bounds.y==0)
roi2.setLocation(0, 0);
else
roi2.setLocation(bounds.x-lwidth/2, bounds.y-lwidth/2);
}
transferProperties(roi, roi2);
roi2.setStrokeWidth(0);
Color c = roi2.getStrokeColor();
if (c!=null) // remove any transparency
roi2.setStrokeColor(new Color(c.getRed(),c.getGreen(),c.getBlue()));
return roi2;
}
void areaToLine(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null || !roi.isArea()) {
IJ.error("Area to Line", "Area selection required");
return;
}
Undo.setup(Undo.ROI, imp);
Polygon p = roi.getPolygon();
if (p==null) return;
int type1 = roi.getType();
if (type1==Roi.COMPOSITE) {
IJ.error("Area to Line", "Composite selections cannot be converted to lines.");
return;
}
int type2 = Roi.POLYLINE;
if (type1==Roi.OVAL||type1==Roi.FREEROI||type1==Roi.TRACED_ROI
||((roi instanceof PolygonRoi)&&((PolygonRoi)roi).isSplineFit()))
type2 = Roi.FREELINE;
Roi roi2 = new PolygonRoi(p.xpoints, p.ypoints, p.npoints, type2);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void toBoundingBox(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("To Bounding Box");
return;
}
Undo.setup(Undo.ROI, imp);
Rectangle r = roi.getBounds();
imp.deleteRoi();
Roi roi2 = new Roi(r.x, r.y, r.width, r.height);
transferProperties(roi, roi2);
imp.setRoi(roi2);
}
void addToRoiManager(ImagePlus imp) {
if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager())
IJ.error("run(\"Add to Manager\") may not work in batch mode macros");
Frame frame = WindowManager.getFrame("ROI Manager");
if (frame==null)
IJ.run("ROI Manager...");
if (imp==null) return;
Roi roi = imp.getRoi();
if (roi==null) return;
frame = WindowManager.getFrame("ROI Manager");
if (frame==null || !(frame instanceof RoiManager))
IJ.error("ROI Manager not found");
RoiManager rm = (RoiManager)frame;
boolean altDown= IJ.altKeyDown();
IJ.setKeyUp(IJ.ALL_KEYS);
if (altDown && !IJ.macroRunning())
IJ.setKeyDown(KeyEvent.VK_SHIFT);
if (roi.getState()==Roi.CONSTRUCTING) { //wait (up to 2 sec.) until ROI finished
long start = System.currentTimeMillis();
while (true) {
IJ.wait(10);
if (roi.getState()!=Roi.CONSTRUCTING)
break;
if ((System.currentTimeMillis()-start)>2000) {
IJ.beep();
IJ.error("Add to Manager", "Selection is not complete");
return;
}
}
}
rm.allowRecording(true);
rm.runCommand("add");
rm.allowRecording(false);
IJ.setKeyUp(IJ.ALL_KEYS);
}
boolean setProperties(String title, Roi roi) {
if ((roi instanceof PointRoi) && Toolbar.getMultiPointMode() && IJ.altKeyDown()) {
((PointRoi)roi).displayCounts();
return true;
}
Frame f = WindowManager.getFrontWindow();
if (f!=null && f.getTitle().indexOf("3D Viewer")!=-1)
return false;
if (roi==null) {
IJ.error("This command requires a selection.");
return false;
}
RoiProperties rp = new RoiProperties(title, roi);
boolean ok = rp.showDialog();
if (IJ.debugMode)
IJ.log(roi.getDebugInfo());
return ok;
}
private void makeBand(ImagePlus imp) {
Roi roi = imp.getRoi();
if (roi==null) {
noRoi("Make Band");
return;
}
Roi roiOrig = roi;
if (!roi.isArea()) {
IJ.error("Make Band", "Area selection required");
return;
}
Calibration cal = imp.getCalibration();
double pixels = bandSize;
double size = pixels*cal.pixelWidth;
int decimalPlaces = 0;
if ((int)size!=size)
decimalPlaces = 2;
GenericDialog gd = new GenericDialog("Make Band");
gd.addNumericField("Band Size:", size, decimalPlaces, 4, cal.getUnits());
gd.showDialog();
if (gd.wasCanceled())
return;
size = gd.getNextNumber();
if (Double.isNaN(size)) {
IJ.error("Make Band", "invalid number");
return;
}
int n = (int)Math.round(size/cal.pixelWidth);
if (n >255) {
IJ.error("Make Band", "Cannot make bands wider that 255 pixels");
return;
}
int width = imp.getWidth();
int height = imp.getHeight();
Rectangle r = roi.getBounds();
ImageProcessor ip = roi.getMask();
if (ip==null) {
ip = new ByteProcessor(r.width, r.height);
ip.invert();
}
ImageProcessor mask = new ByteProcessor(width, height);
mask.insert(ip, r.x, r.y);
ImagePlus edm = new ImagePlus("mask", mask);
boolean saveBlackBackground = Prefs.blackBackground;
Prefs.blackBackground = false;
int saveType = EDM.getOutputType();
EDM.setOutputType(EDM.BYTE_OVERWRITE);
IJ.run(edm, "Distance Map", "");
EDM.setOutputType(saveType);
Prefs.blackBackground = saveBlackBackground;
ip = edm.getProcessor();
ip.setThreshold(0, n, ImageProcessor.NO_LUT_UPDATE);
int xx=-1, yy=-1;
for (int x=r.x; x<r.x+r.width; x++) {
for (int y=r.y; y<r.y+r.height; y++) {
if (ip.getPixel(x, y)<n) {
xx=x; yy=y;
break;
}
}
if (xx>=0||yy>=0)
break;
}
int count = IJ.doWand(edm, xx, yy, 0, null);
if (count<=0) {
IJ.error("Make Band", "Unable to make band");
return;
}
ShapeRoi roi2 = new ShapeRoi(edm.getRoi());
if (!(roi instanceof ShapeRoi))
roi = new ShapeRoi(roi);
ShapeRoi roi1 = (ShapeRoi)roi;
roi2 = roi2.not(roi1);
Undo.setup(Undo.ROI, imp);
transferProperties(roiOrig, roi2);
imp.setRoi(roi2);
bandSize = n;
}
void noRoi(String command) {
IJ.error(command, "This command requires a selection");
}
}
| uschmidt83/imagej1 | ij/plugin/Selection.java |
247,684 | import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
/**
* Class that controls sprites
* Can i get any more vague ... i think i can.
* @author Andrey Grebenik (Kuro)
* @version 1.0
* @since 2016-11-19
*/
public class GLimage extends Component {
private CustomUtils.AudioController a;
// the texture.
private Texture texture;
// special id that is given to every object.
private int identity;
// x and y position.
public int x;
public int y;
int enl = 0;
// vertical and horisontal stretch
private int sV = 0, sH = 0;
// texture height and width.
int height;
int width;
// the tag that the GLimage has/has not been given
private String tag = "default.tag";
// Temporary variable slots.
private boolean normal = true;
// list of all GLimages so the GLimage can know where what is.
private ArrayList<GLimage> images = new ArrayList<>();
//the filepath of the current image.
private String path;
private int max;
/**
* When the GLimage is initialized this is called.
* Creates a GLimage at [ @param Px, @param Py ] with an image of @param path.
* @param path the image path of the GLimage
* @param Px the start x position.
* @param Py the start y position.
* @throws IOException if you are a complete idiot and somehow can't get your filepaths right.
*/
public GLimage(String path, int Px, int Py) throws IOException
{
x = Px;
y = Py;
this.path = path;
tag = "default";
init();
}
public GLimage(String path, int Px, int Py, boolean letter) throws IOException
{
x = Px;
y = Py;
this.path = path;
normal = !letter;
tag = "default";
init();
}
/**
* When the GLimage is initialized this is called.
* Creates a GLimage at [ @param Px, @param Py ] with an image of @param path.
* @param path the image path of the GLimage
* @param Px the start x position.
* @param Py the start y position.
* @param tag the tag with which the object is going to be tagged.
* @throws IOException if you are a complete idiot and somehow can't get your filepaths right.
*/
public GLimage(String path, int Px, int Py, String tag) throws IOException
{
tag = tag;
x = Px;
y = Py;
this.path = path;
init();
}
/**
* Loads the image and sets width and height of it.
* @throws IOException if you can't bother to change your '\'to a '\\' or a '/'
*/
public void init() throws IOException
{
String pth = "";
if(normal)
{
pth = "Assets\\Art\\Tiles\\";
}
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(pth+path));
height = texture.getImageHeight();
width = texture.getImageWidth();
Random rand = new Random();
this.identity = rand.nextInt();
a = new CustomUtils.AudioController();
}
/**
* render the GLimage on the screen at [ @param x, @param y ].
*/
public void render() {
Color.white.bind();
texture.bind();
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(x - enl, y - enl);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(x + texture.getTextureWidth() + sH + enl, y - enl);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(x + texture.getTextureWidth() + sH + enl, y + texture.getTextureHeight() + sV + enl);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(x - enl, y + texture.getTextureHeight() + sV + enl);
GL11.glEnd();
}
public void enlarge(int size)
{
this.enl = size;
}
public void stretch(int width, int height)
{
this.sV = height;
this.sH = width;
}
public void addFX(String path, String name) throws IOException, CustomUtils.AudioControllerException
{
a.addSound("Assets\\Audio\\SFX\\"+path, name+".sf");
//Tools.p("loaded FX > Assets\\Audio\\SFX\\"+path+" as "+name+".sf");
}
public void playFX(String name,double volume) throws CustomUtils.AudioControllerException
{
a.playSoundEffect(name+".sf",volume);
//Tools.p("playing FX > "+name+".sf");
}
public void addMU(String path, String name) throws IOException, CustomUtils.AudioControllerException
{
a.addSound("Assets\\Audio\\BGM\\"+path, name+".mu");
//Tools.p("loaded MU > Assets\\Audio\\SFX\\"+path+" as "+name+".mu");
}
public void playMU(String name,double volume) throws CustomUtils.AudioControllerException
{
a.playMusic(name+".mu",volume,true);
//Tools.p("playing MU > "+name+".mu");
}
}
| AMP-studios/Proj01 | src/GLimage.java |
247,685 | 404: Not Found | quangprobui2001/FinalExam | MyArrayVector.java |
247,686 | import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class DrawPad extends JFrame implements ActionListener,ItemListener {
private JToolBar button_panel;// 按钮面板
private JMenuBar menuBar;// 菜单条
private JMenu file, color, stroke;// 菜单(文件,颜色,编辑)
private JMenuItem newfile, openfile, savefile, exit;//文件 菜单项
private JMenuItem colorchoice, cancel,narrow,enlarge;//颜色,编辑,菜单项
private JLabel startbar;// 状态栏
private DrawArea drawArea;// 画布
private JComboBox<String> combox;//字体选择下拉框
String[] fontname;//字体
private String[] icon_path = { "src/icons/newfile.png", "src/icons/openfile.png", "src/icons/savefile.png", "src/icons/eraser.png",
"src/icons/pan.png", "src/icons/line.png", "src/icons/rect.png", "src/icons/frect.png", "src/icons/oval.png",
"src/icons/foval.png", "src/icons/circle.png", "src/icons/fcircle.png", "src/icons/roundrect.png",
"src/icons/froundrect.png", "src/icons/color.png", "src/icons/stroke.png", "src/icons/word.png" };
private Icon[] icons;
private String Prompt_message[] = { "新建图片", "打开图片", "保存图片", "橡皮擦", "铅笔", "直线", "空心矩形", "实心矩形", "空心椭圆", "实心椭圆",
"空心圆", "实心圆", "空心圆角矩形", "实心圆角矩形", "颜色", "线条粗细", "文字输入" };
JButton[] button;// 工具条中的按钮组
private JButton bold, italic, plain;// 字体格式
public DrawPad(String string) {
super(string);
// 菜单初始化
file = new JMenu("文件");
color = new JMenu("颜色");
stroke = new JMenu("编辑");
menuBar = new JMenuBar();
menuBar.add(file);
menuBar.add(color);
menuBar.add(stroke);
this.setJMenuBar(menuBar);
this.setTitle(string);
newfile = new JMenuItem("新建");
openfile = new JMenuItem("打开");
savefile = new JMenuItem("保存");
exit = new JMenuItem("退出");
file.add(newfile);
file.add(openfile);
file.add(savefile);
file.add(exit);
// 菜单项注册监听
newfile.addActionListener(this);
openfile.addActionListener(this);
savefile.addActionListener(this);
exit.addActionListener(this);
colorchoice = new JMenuItem("调色板");
color.add(colorchoice);
colorchoice.addActionListener(this);
cancel = new JMenuItem("撤回");
stroke.add(cancel);
cancel.addActionListener(this);
enlarge = new JMenuItem("放大");
narrow = new JMenuItem("缩小");
stroke.add(enlarge);
stroke.add(narrow);
enlarge.addActionListener(this);
narrow.addActionListener(this);
// 工具栏
button_panel = new JToolBar("工具箱",JToolBar.HORIZONTAL);
button_panel.setBackground(Color.LIGHT_GRAY);
icons = new ImageIcon[icon_path.length];//按钮图标数组
button = new JButton[icon_path.length];
for (int i = 0; i < icon_path.length; i++) {
icons[i] = new ImageIcon(icon_path[i]);
button[i] = new JButton(icons[i]);
button[i].setToolTipText(Prompt_message[i]);
button_panel.add(button[i]);
button[i].setBackground(Color.white);
button[i].addActionListener(this);
}
bold = new JButton("B");
bold.setFont(new Font(Font.DIALOG, Font.BOLD, 20));
bold.addActionListener(this);
italic = new JButton("I");
italic.setFont(new Font(Font.DIALOG, Font.ITALIC, 20));
italic.addActionListener(this);
plain = new JButton("reset");
plain.setFont(new Font(Font.DIALOG, Font.PLAIN, 20));
plain.addActionListener(this);
GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment();// 字体可用名称
fontname = g.getAvailableFontFamilyNames();
combox = new JComboBox(fontname);
combox.addItemListener(this);
combox.setMaximumSize(new Dimension(70, 40));// 下拉最大尺寸
button_panel.add(bold);
button_panel.add(italic);
button_panel.add(plain);
button_panel.add(combox);
startbar = new JLabel("坐标");
startbar.setFont(new Font("Serief", Font.ITALIC + Font.BOLD, 25));
startbar.setForeground(Color.black);
drawArea = new DrawArea(this);
Container con = getContentPane();
con.add(button_panel, BorderLayout.NORTH);
con.add(drawArea, BorderLayout.CENTER);
con.add(startbar, BorderLayout.SOUTH);
Toolkit tool = getToolkit();
Dimension dim = tool.getScreenSize();
setBounds(100, 100, dim.width - 200, dim.height - 200);
setVisible(true);
validate();// 参数校验
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//界面初始化
public void setStratBar(String s) {
startbar.setText(s);
}//鼠标状态标签栏
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 3; i <= 13; i++) {
if (e.getSource() == button[i]) {
drawArea.setCurrentchoice(i);
drawArea.createNewitem();
drawArea.repaint();
}
}
if (e.getSource() == newfile || e.getSource() == button[0]) {
this.newFile();
} else if (e.getSource() == openfile || e.getSource() == button[1]) {
this.openFile();
} else if (e.getSource() == savefile || e.getSource() == button[2]) {
this.saveFile();
} else if (e.getSource() == exit) {
System.exit(0);
} else if (e.getSource() == colorchoice || e.getSource() == button[14]) {
drawArea.chooseColor();
} else if (e.getSource() == button[15]) {
drawArea.setStroke();
} else if (e.getSource() == button[16]) {
drawArea.setCurrentchoice(16);
drawArea.createNewitem();
drawArea.repaint();
}else if (e.getSource()==cancel){
drawArea.ReturnIndex();
drawArea.createNewitem();
drawArea.repaint();
}else if (e.getSource()==enlarge){
drawArea.enlarge();
drawArea.createNewitem();
drawArea.repaint();
}else if (e.getSource()==narrow){
drawArea.narrow();
drawArea.createNewitem();
drawArea.repaint();
}
if (e.getSource() == bold) {
drawArea.setFont(1, Font.BOLD);
drawArea.createNewitem();
}
if (e.getSource() == italic) {
drawArea.setFont(2, Font.ITALIC);
drawArea.createNewitem();
}
if (e.getSource() == plain) {
drawArea.setFont(3, Font.PLAIN);
drawArea.createNewitem();
}
}//actionlistener接口方法
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == combox) {
drawArea.setFontName(fontname[combox.getSelectedIndex()]);
}
}//itemstatechanged接口方法
public BufferedImage createImage(DrawArea panel) {
int width = DrawPad.this.getWidth();
int height = DrawPad.this.getHeight();
BufferedImage panelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = panelImage.createGraphics();
g2D.setColor(Color.white);// 填充背景色
g2D.fillRect(0, 0, width, height);
g2D.translate(0, 0);//画笔坐标定义为原点
panel.paintComponent(g2D);
g2D.dispose();// 释放部分资源
return panelImage;
}//将画板保存成bufferimage
// 保存画板
public void saveFile() {
// 文件选择器
JFileChooser fileChooser = new JFileChooser();
// 设置文件显示类型为仅显示文件
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// 文件过滤器
JpgFilter jpg = new JpgFilter();
BmpFilter bmp = new BmpFilter();
PngFilter png = new PngFilter();
// 向用户可选择的文件过滤器列表添加一个过滤器
fileChooser.addChoosableFileFilter(jpg);
fileChooser.addChoosableFileFilter(bmp);
fileChooser.addChoosableFileFilter(png);
// 返回当前的文本过滤器,并设置成当前的选择
fileChooser.setFileFilter(fileChooser.getFileFilter());
// 弹出一个 "Save File" 文件选择器对话框
int result = fileChooser.showSaveDialog(DrawPad.this);
if (result == JFileChooser.CANCEL_OPTION)
return;
File fileName = fileChooser.getSelectedFile();
if (!fileName.getName().endsWith(fileChooser.getFileFilter().getDescription())) {
String t = fileName.getPath() + fileChooser.getFileFilter().getDescription();
fileName = new File(t);
}
fileName.canWrite();
if (fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(fileChooser, "无效的文件名", "错误", JOptionPane.ERROR_MESSAGE);
BufferedImage image = createImage(drawArea);
try {
ImageIO.write(image, "png", fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
// 打开文件
public void openFile() {
// 文件选择器
JFileChooser fileChooser = new JFileChooser();
// 设置文件显示类型为仅显示文件
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// 文件过滤器
JpgFilter jpg = new JpgFilter();
BmpFilter bmp = new BmpFilter();
PngFilter png = new PngFilter();
// 向用户可选择的文件过滤器列表添加一个过滤器。
fileChooser.addChoosableFileFilter(jpg);
fileChooser.addChoosableFileFilter(bmp);
fileChooser.addChoosableFileFilter(png);
// 返回当前的文本过滤器,并设置成当前的选择
fileChooser.setFileFilter(fileChooser.getFileFilter());
// 弹出一个 "Open File" 文件选择器对话框
int result = fileChooser.showOpenDialog(DrawPad.this);
if (result == JFileChooser.CANCEL_OPTION)
return;
// 得到选择文件的名字
File fileName = fileChooser.getSelectedFile();
if (!fileName.getName().endsWith(fileChooser.getFileFilter().getDescription())) {
JOptionPane.showMessageDialog(DrawPad.this, "文件格式错误");
return;
}
fileName.canRead();
if (fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(fileChooser, "无效的文件名", "错误", JOptionPane.ERROR_MESSAGE);
BufferedImage image;
try {
drawArea.index = 0;
image = ImageIO.read(fileName);
drawArea.image = image;
drawArea.createNewitem();
drawArea.repaint();
drawArea.index++;
drawArea.setCurrentchoice(4);
drawArea.createNewitem();
} catch (IOException e) {
e.printStackTrace();
}
}
// 新建画板
public void newFile() {
drawArea.setIndex(0);
drawArea.setCurrentchoice(4);
drawArea.setColor(Color.black);
drawArea.setStroke(3);
drawArea.createNewitem();
repaint();
}
}
class JpgFilter extends FileFilter {//jpg图片过滤
public boolean accept(File f) {
if (f.isDirectory())
return true;
return f.getName().endsWith(".jpg");
}
public String getDescription() {
return ".jpg";
}
}
class BmpFilter extends FileFilter {//bmp图片过滤
public boolean accept(File f) {
if (f.isDirectory())
return true;
return f.getName().endsWith(".bmp");
}
public String getDescription() {
return ".bmp";
}
}
class PngFilter extends FileFilter {//png图片过滤
public boolean accept(File f) {
if (f.isDirectory())
return true;
return f.getName().endsWith(".png");
}
public String getDescription() {
return ".png";
}
} | mr-ma-peng/Drawingboard | src/DrawPad.java |
247,697 | class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
int currentMax = nums[0];
for(int i=1;i<nums.length;i++){
currentMax = Math.max(nums[i], nums[i]+currentMax);
max = Math.max(max, currentMax);
}
return max;
}
} | iamtanbirahmed/100DaysOfLC | 53.java |
247,700 | import java.util.Scanner;
class Array{
public static void main(String[] args)
{
try{
int i,x;
Scanner s=new Scanner(System.in);
System.out.println("Enter no of elements in array:");
int n =s.nextInt();
int arr[]=new int[n];
for(i=0;i<n;i++)
{
System.out.print("Enter element "+(i+1)+" =");
arr[i]=s.nextInt();
}
x=arr[0];
for(i=1;i<n;i++)
{
if(x<arr[i])
{
x=arr[i];
}
}
System.out.println("The largest number is="+x);
}
catch(Exception e)
{
System.out.println("invalid");
}
}
}
| Nagendra475/nagendra | 84.java |
247,715 | package Recursion;
public class Q4 {
static void printArray(int ans[], int n) {
System.out.print("Reversed array is:- \n");
for (int i = 0; i < n; i++) {
System.out.print(ans[i] + " ");
}
}
//Function to reverse array using an auxiliary array
static void reverseArray(int arr[], int n) {
int[] ans = new int[n];
for (int i = n - 1; i >= 0; i--) {
ans[n - i - 1] = arr[i];
}
printArray(ans, n);
}
public static void main(String[] args) {
int n = 5;
int arr[] = { 5, 4, 3, 2, 1};
reverseArray(arr, n);
}
}
| PRATHAMKARMARKAR/DSA | Q4.java |
247,724 | // Program to Convert String to String Array
class StringToArray {
public static void main(String[] args) {
String inputString = "Hello, World! This is a sample string.";
String[] stringArray = inputString.split(" ");
for (String word : stringArray) {
System.out.println(word);
}
}
}
| jatinvats01/7061_javaproject | 12.java |
247,776 | class C{public static void main(String[]a){int n=a.length,m=0,i=0,j=0,h=0,p=0,q=0,s=0,t=0,b=-1,c=2147483647,x=0,y=0;char[][]r=new char[n][];char u;for(String k:a){j=k.length();m=(j>m)?j:m;}for(String k:a)r[i++]=java.util.Arrays.copyOf(k.toCharArray(),m);int[][][]d=new int[n][m][2];for(j=m-1;j>=0;j--){for(i=0;i<n;i++){u=r[i][j];p=(u=='\0'||u==' '||u=='|'?0:u-'0');if(j==m-1)d[i][j][1]=p;else{if(u=='|')d[i][j][0]=-1;else{for(h=-1;h<2;h++){x=i+h;y=j+1;if(x>=0&&x<n){if(d[x][y][0]==-1){s=x-1;while(s>=0&&r[s][y]=='|')s--;t=x+1;while(t<n&&r[t][y]=='|')t++;if((s>=0&&t<n&&d[s][y][1]<d[t][y][1])||(s>=0&&t>=n)){t=d[s][y][1];s=4;}else{s=6;t=d[t][y][1];}d[x][y][0]=s;d[x][y][1]=t;}q=d[x][y][1]+p;if(d[i][j][0]==0||q<d[i][j][1]){d[i][j][0]=h+2;d[i][j][1]=q;}}}}}if(j==0&&(b<0||d[i][j][1]<c)){b=i;c=d[i][j][1];}}}String o="";i=b;j=0;while(j<m){u=r[i][j];if(u=='\0')j=m;else{o+=u+",";h=d[i][j][0]-2;if(h>1)i+=h-3;else{i+=h;j++;}}}System.out.println(o+"\b:"+c);}}
| ProgrammerDan/chicken-golf | C.java |
247,787 | package coding;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Roy_frequently {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t= Integer.parseInt(s.nextLine());
Map<Character, Integer> mapper = new HashMap<Character, Integer>();
mapper.put('.', 1);
mapper.put(',', 2);
mapper.put('?', 3);
mapper.put('!', 4);
mapper.put('1', 5);
mapper.put('a', 1);
mapper.put('b', 2);
mapper.put('c', 3);
mapper.put('2', 4);
mapper.put('d', 1);
mapper.put('e', 2);
mapper.put('f', 3);
mapper.put('3', 4);
mapper.put('g', 1);
mapper.put('h', 2);
mapper.put('i', 3);
mapper.put('4', 4);
mapper.put('j', 1);
mapper.put('k', 2);
mapper.put('l', 3);
mapper.put('5', 4);
mapper.put('m', 1);
mapper.put('n', 2);
mapper.put('o', 3);
mapper.put('6', 4);
mapper.put('p', 1);
mapper.put('q', 2);
mapper.put('r', 3);
mapper.put('s', 4);
mapper.put('7', 5);
mapper.put('t', 1);
mapper.put('u', 2);
mapper.put('v', 3);
mapper.put('8', 4);
mapper.put('w', 1);
mapper.put('x', 2);
mapper.put('y', 3);
mapper.put('z', 4);
mapper.put('9', 5);
mapper.put('_', 1);
mapper.put('0', 2);
Map<Character, Integer> mapper1 = new HashMap<Character, Integer>();
mapper1.put('.', 1);
mapper1.put(',', 1);
mapper1.put('?', 1);
mapper1.put('!', 1);
mapper1.put('1', 1);
mapper1.put('a', 2);
mapper1.put('b', 2);
mapper1.put('c', 2);
mapper1.put('2', 2);
mapper1.put('d', 3);
mapper1.put('e', 3);
mapper1.put('f', 3);
mapper1.put('3', 3);
mapper1.put('g', 4);
mapper1.put('h', 4);
mapper1.put('i', 4);
mapper1.put('4', 4);
mapper1.put('j', 5);
mapper1.put('k', 5);
mapper1.put('l', 5);
mapper1.put('5', 5);
mapper1.put('m', 6);
mapper1.put('n', 6);
mapper1.put('o', 6);
mapper1.put('6', 6);
mapper1.put('p', 7);
mapper1.put('q', 7);
mapper1.put('r', 7);
mapper1.put('s', 7);
mapper1.put('7', 7);
mapper1.put('t', 8);
mapper1.put('u', 8);
mapper1.put('v', 8);
mapper1.put('8', 9);
mapper1.put('w', 9);
mapper1.put('x', 9);
mapper1.put('y', 9);
mapper1.put('z', 9);
mapper1.put('9', 9);
mapper1.put('_', 0);
mapper1.put('0', 0);
for(int ii =0;ii<t;ii++){
int ans = 0;
String data = s.nextLine();
int handNow = 1;
for(int i=0;i<data.length();i++){
Character now = data.charAt(i);
int times = mapper.get(now);
if(handNow != mapper1.get(now)){
ans++;
handNow = mapper1.get(now);
}
ans = ans + times;
}
System.out.println(ans);
}
}
}
| umeshravuru/hackerrank | Roy_frequently.java |
247,789 | package com.thealgorithms.datastructures.caches;
import java.util.HashMap;
import java.util.Map;
/**
* Java program for LFU Cache (https://en.wikipedia.org/wiki/Least_frequently_used)
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/
public class LFUCache<K, V> {
private class Node {
private K key;
private V value;
private int frequency;
private Node previous;
private Node next;
Node(K key, V value, int frequency) {
this.key = key;
this.value = value;
this.frequency = frequency;
}
}
private Node head;
private Node tail;
private Map<K, Node> map = null;
private Integer capacity;
private static final int DEFAULT_CAPACITY = 100;
public LFUCache() {
this.capacity = DEFAULT_CAPACITY;
}
public LFUCache(Integer capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
}
/**
* This method returns value present in the cache corresponding to the key passed as parameter
*
* @param <K> key for which value is to be retrieved
* @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is
* not present in the cache
*/
public V get(K key) {
if (this.map.get(key) == null) {
return null;
}
Node node = map.get(key);
removeNode(node);
node.frequency += 1;
addNodeWithUpdatedFrequency(node);
return node.value;
}
/**
* This method stores <K> key and <V> value in the cache
*
* @param <K> key which is to be stored in the cache
* @param <V> value which is to be stored in the cache
*/
public void put(K key, V value) {
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
node.frequency += 1;
removeNode(node);
addNodeWithUpdatedFrequency(node);
} else {
if (map.size() >= capacity) {
map.remove(this.head.key);
removeNode(head);
}
Node node = new Node(key, value, 1);
addNodeWithUpdatedFrequency(node);
map.put(key, node);
}
}
/**
* This method stores the node in the cache with updated frequency
*
* @param Node node which is to be updated in the cache
*/
private void addNodeWithUpdatedFrequency(Node node) {
if (tail != null && head != null) {
Node temp = this.head;
while (temp != null) {
if (temp.frequency > node.frequency) {
if (temp == head) {
node.next = temp;
temp.previous = node;
this.head = node;
break;
} else {
node.next = temp;
node.previous = temp.previous;
temp.previous.next = node;
temp.previous = node;
break;
}
} else {
temp = temp.next;
if (temp == null) {
tail.next = node;
node.previous = tail;
node.next = null;
tail = node;
break;
}
}
}
} else {
tail = node;
head = tail;
}
}
/**
* This method removes node from the cache
*
* @param Node node which is to be removed in the cache
*/
private void removeNode(Node node) {
if (node.previous != null) {
node.previous.next = node.next;
} else {
this.head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else {
this.tail = node.previous;
}
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java |
247,792 | /* Write a method called mode that returns the most frequently occurring
* element of an array of integers. Assume that the array has at least one
* element and that every element in the array has a value between 0 and 100
* inclusive. Break ties by choosing the lower value.
*/
public int mode(int[] n) {
int[] counts = new int[101];
int maxCount = 0;
int maxKey = -1;
for(int i = 0; i < n.length; i++) {
counts[n[i]]++;
if(counts[n[i]] > maxCount) {
maxCount = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
| ramakastriot/practiceit | chapter7/mode.java |
247,795 | package de.ruedigermoeller.fastcast.test;
import org.nustaq.fastcast.impl.TopicStats;
import org.nustaq.fastcast.api.*;
import org.nustaq.fastcast.util.FCUtils;
import de.ruedigermoeller.heapoff.bytez.Bytez;
import de.ruedigermoeller.heapoff.structs.FSTStruct;
import de.ruedigermoeller.heapoff.structs.FSTStructAllocator;
import de.ruedigermoeller.heapoff.structs.structtypes.StructString;
import de.ruedigermoeller.heapoff.structs.unsafeimpl.FSTStructFactory;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created with IntelliJ IDEA.
* User: ruedi
* Date: 10/3/13
* Time: 3:32 PM
* To change this template use File | Settings | File Templates.
*/
@DecodeInTransportThread(true)
public class StructBench extends FCTopicService {
// create single processeor thread
Executor processor = (ExecutorService) FCUtils.createBoundedSingleThreadExecutor("structbend", 10000);
boolean useProcessorThread = false;
static int receiveCount;
static int filterCount;
static long lastTime;
private char assignedChar = 'A';
public static class StructMessage extends FSTStruct {
protected StructString instrument = new StructString(4);
protected double price;
protected int quantity;
protected long time;
public StructString getInstrument() {
return instrument;
}
public void setInstrument(StructString instrument) {
this.instrument = instrument;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
@RemoteHelper
public void sendStructMessage( FSTStruct offheaped ) {
if ( ! offheaped.isOffHeap() )
throw new RuntimeException("Expect offheaped struct");
receiveBinary(offheaped.getBase(), (int) offheaped.getOffset(),offheaped.getByteSize());
}
@Override
@RemoteMethod(-1) // internal flag, do not use negative indizes in your code
public void receiveBinary(Bytez bytes, int offset, int length) {
StructMessage volatileStructPointer = (StructMessage) FSTStructFactory.getInstance().getStructPointer(bytes, offset);
if ( filter(volatileStructPointer) ) {
if (useProcessorThread) {
// that's why multithreaded processing frequently does not break even
final StructMessage copy = (StructMessage) volatileStructPointer.createCopy();
processor.execute( new Runnable() {
@Override
public void run() {
processMessage(copy);
}
});
} else {
// if decodeInTransportThread == true => hurry up here, else packet losses might happen frequently
processMessage(volatileStructPointer);
}
}
}
@RemoteMethod(1)
public void assignStartChar(char c) {
assignedChar = c;
System.out.println("got assigned '"+c+"'");
}
@RemoteMethod(2)
public void bitteMeldeDich(FCFutureResultHandler res) {
res.sendResult("nothing");
}
private void processMessage(StructMessage copy) {
receiveCount++;
long l = System.currentTimeMillis();
// System.out.println("rec "+copy.getInstrument()+" "+copy.getQuantity());
if (l - lastTime > 1000) {
synchronized (getClass()) {
if (l - lastTime > 1000) {
System.out.println("received/s " + receiveCount+" filtered "+filterCount);
receiveCount = 0;
filterCount = 0;
lastTime = System.currentTimeMillis();
TopicStats stats = getRemoting().getStats(getTopicName());
}
}
}
}
/**
* @param volatileStructPointer
* @return true if message should get processed
*/
private boolean filter(StructMessage volatileStructPointer) {
boolean res = volatileStructPointer.getInstrument().chars(0) == assignedChar;
if ( ! res ) {
filterCount++;
}
return res;
}
public static void main(String arg[]) throws IOException, InterruptedException {
// NEVER FORGET WHEN REMOTING STRUCTS
// NEVER FORGET WHEN REMOTING STRUCTS
// NEVER FORGET WHEN REMOTING STRUCTS
FSTStructFactory.getInstance().registerClz(StructMessage.class);
// NEVER FORGET WHEN REMOTING STRUCTS
// NEVER FORGET WHEN REMOTING STRUCTS
// NEVER FORGET WHEN REMOTING STRUCTS
FCRemoting fc = FastCast.getFastCast();
fc.joinCluster("structbench.yaml", "Bench", null);
if ( arg.length == 1 ) // => sender
{
System.out.println("Running in Sender mode ..");
fc.startSending("structbench");
final StructBench remote = (StructBench) fc.getRemoteService("structbench");
// assign each listener a filter first char
final AtomicInteger ch = new AtomicInteger('A');
remote.bitteMeldeDich(new FCFutureResultHandler() {
@Override
public void resultReceived(Object obj, String sender) {
FCSendContext.get().setReceiver(sender);
char newChar = (char) ch.getAndIncrement();
remote.assignStartChar(newChar);
System.out.println("assigned "+sender+" char "+newChar);
}
});
FSTStructAllocator alloc = new FSTStructAllocator(50000);
StructMessage msgTemplate = (StructMessage) alloc.newStruct(new StructMessage()).detach();
int count = 0;
while( true ) {
int rand = (int) (Math.random()*10);
msgTemplate.getInstrument().setString( ((char)('A'+rand))+"LV");
msgTemplate.setPrice(Math.random()*100);
msgTemplate.setQuantity((int) (Math.random()*1000));
msgTemplate.setTime(System.currentTimeMillis());
// System.out.println("send binary "+msgTemplate.getBase()+" "+msgTemplate.getOffset()+" "+msgTemplate.getByteSize());
// remote.receiveBinary(msgTemplate.getBase(),msgTemplate.getOffset(),msgTemplate.getByteSize());
remote.sendStructMessage(msgTemplate);
// if ( rand == 0 )
// Thread.sleep(1);
}
} else {
System.out.println("Running in Receiver mode ..");
fc.start("structbench");
}
}
}
| RuedigerMoeller/fast-cast | attic/StructBench.java |
247,797 | package utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import p.Resettable;
import w.InputStreamSugar;
/**
* Some utilities that emulate C stlib methods or provide convenient functions
* to do repetitive system and memory related stuff.
*
* @author Maes
*/
public final class C2JUtils {
public static char[] strcpy(char[] s1, final char[] s2) {
System.arraycopy(s2, 0, s1, 0, Math.min(s1.length, s2.length));
return s1;
}
public static char[] strcpy(char[] s1, final char[] s2, int off, int len) {
for (int i = 0; i < len; i++) {
s1[i] = s2[i + off];
}
return s1;
}
public static char[] strcpy(char[] s1, final char[] s2, int off) {
for (int i = 0; i < Math.min(s1.length, s2.length - off); i++) {
s1[i] = s2[i + off];
}
return s1;
}
public static char[] strcpy(char[] s1, String s2) {
for (int i = 0; i < Math.min(s1.length, s2.length()); i++) {
s1[i] = s2.charAt(i);
}
return s1;
}
/** Return a byte[] array from the string's chars,
* ANDed to the lowest 8 bits.
*
* @param str
* @return
*/
public static byte[] toByteArray(String str) {
byte[] retour = new byte[str.length()];
for (int i = 0; i < str.length(); i++) {
retour[i] = (byte) (str.charAt(i) & 0xFF);
}
return retour;
}
/**
* Finds index of first element of array matching key. Useful whenever an
* "indexOf" property is required or you encounter the C-ism [pointer-
* array_base] used to find array indices in O(1) time. However, since this
* is just a dumb unsorted search, running time is O(n), so use this method
* only sparingly and in scenarios where it won't occur very frequently
* -once per level is probably OK-, but watch out for nested loops, and
* cache the result whenever possible. Consider adding an index or ID type
* of field to the searched type if you require to use this property too
* often.
*
* @param array
* @param key
* @return
*/
public static int indexOf(Object[] array, Object key) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return i;
}
}
return -1;
}
/**
* Emulates C-style "string comparison". "Strings" are considered
* null-terminated, and comparison is performed only up to the smaller of
* the two.
*
* @param s1
* @param s2
* @return
*/
public static boolean strcmp(char[] s1, final char[] s2) {
boolean match = true;
for (int i = 0; i < Math.min(s1.length, s2.length); i++) {
if (s1[i] != s2[i]) {
match = false;
break;
}
}
return match;
}
public static boolean strcmp(char[] s1, String s2) {
return strcmp(s1, s2.toCharArray());
}
/**
* C-like string length (null termination).
*
* @param s1
* @return
*/
public static int strlen(char[] s1) {
if (s1 == null)
return 0;
int len = 0;
while (s1[len++] > 0) {
if (len >= s1.length)
break;
}
return len - 1;
}
/**
* Return a new String based on C-like null termination.
*
* @param s
* @return
*/
public static String nullTerminatedString(char[] s) {
if (s == null)
return "";
int len = 0;
while (s[len++] > 0) {
if (len >= s.length)
break;
}
return new String(s, 0, len - 1);
}
/**
* Automatically "initializes" arrays of objects with their default
* constuctor. It's better than doing it by hand, IMO. If you have a better
* way, be my guest.
*
* @param os
* @param c
* @throws Exception
* @throws
*/
public static <T> void initArrayOfObjects(T[] os, Class<T> c) {
try {
for (int i = 0; i < os.length; i++) {
os[i] = c.newInstance();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.err.println("Failure to allocate " + os.length
+ " objects of class" + c.getName() + "!");
System.exit(-1);
}
}
/**
* Automatically "initializes" arrays of objects with their default
* constuctor. It's better than doing it by hand, IMO. If you have a better
* way, be my guest.
*
* @param os
* @throws Exception
* @throws
*/
@Deprecated
public static <T> void initArrayOfObjects(T[] os) {
@SuppressWarnings("unchecked")
Class<T> c = (Class<T>) os.getClass().getComponentType();
try {
for (int i = 0; i < os.length; i++) {
os[i] = c.newInstance();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.err.println("Failure to allocate " + os.length
+ " objects of class " + c.getName() + "!");
System.exit(-1);
}
}
/**
* Use of this method is very bad. It prevents refactoring measures. Also,
* the use of reflection is acceptable on initialization, but in runtime it
* causes performance loss. Use instead:
* SomeType[] array = new SomeType[length];
* Arrays.setAll(array, i -> new SomeType());
*
* - Good Sign 2017/05/07
*
* Uses reflection to automatically create and initialize an array of
* objects of the specified class. Does not require casting on "reception".
*
* @param <T>
* @param c
* @param num
* @return
* @return
*/
@Deprecated
public static <T> T[] createArrayOfObjects(Class<T> c, int num) {
T[] os;
os=getNewArray(c,num);
try {
for (int i = 0; i < os.length; i++) {
os[i] = c.newInstance();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.err.println("Failure to instantiate " + os.length + " objects of class " + c.getName() + "!");
System.exit(-1);
}
return os;
}
/**
* Uses reflection to automatically create and initialize an array of
* objects of the specified class. Does not require casting on "reception".
* Requires an instance of the desired class. This allows getting around
* determining the runtime type of parametrized types.
*
*
* @param <T>
* @param instance An instance of a particular class.
* @param num
* @return
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T[] createArrayOfObjects(T instance, int num) {
T[] os;
Class<T> c=(Class<T>) instance.getClass();
os=getNewArray(c,num);
try {
for (int i = 0; i < os.length; i++) {
os[i] = c.newInstance();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.err.println("Failure to instantiate " + os.length
+ " objects of class " + c.getName() + "!");
System.exit(-1);
}
return os;
}
/**
* Automatically "initializes" arrays of objects with their default
* constuctor. It's better than doing it by hand, IMO. If you have a better
* way, be my guest.
*
* @param os
* @param startpos inclusive
* @param endpos non-inclusive
* @throws Exception
* @throws
*/
public static <T> void initArrayOfObjects(T[] os, int startpos, int endpos) {
@SuppressWarnings("unchecked")
Class<T> c = (Class<T>) os.getClass().getComponentType();
try {
for (int i = startpos; i < endpos; i++) {
os[i] = c.newInstance();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.err.println("Failure to allocate " + os.length
+ " objects of class " + c.getName() + "!");
System.exit(-1);
}
}
/** This method gets eventually inlined, becoming very fast */
public static int toUnsignedByte(byte b) {
return (0x000000FF & b);
}
// Optimized array-fill methods designed to operate like C's memset.
public static void memset(boolean[] array, boolean value, int len) {
if (len > 0)
array[0] = value;
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
public static void memset(byte[] array, byte value, int len) {
if (len > 0)
array[0] = value;
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
public static void memset(char[] array, char value, int len) {
if (len > 0)
array[0] = value;
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
public static void memset(int[] array, int value, int len) {
if (len > 0)
array[0] = value;
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
public static void memset(short[] array, short value, int len) {
if (len > 0) {
array[0] = value;
}
for (int i = 1; i < len; i += i) {
System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
}
}
public static long unsigned(int num) {
return 0xFFFFFFFFL & num;
}
public static char unsigned(short num) {
return (char) num;
}
/**
* Convenient alias for System.arraycopy(src, 0, dest, 0, length);
*
* @param dest
* @param src
* @param length
*/
@SuppressWarnings("SuspiciousSystemArraycopy")
public static void memcpy(Object dest, Object src, int length) {
System.arraycopy(src, 0, dest, 0, length);
}
public static boolean testReadAccess(String URI) {
InputStream in;
// This is bullshit.
if (URI == null) {
return false;
}
if (URI.length() == 0) {
return false;
}
try {
in = new FileInputStream(URI);
} catch (FileNotFoundException e) {
// Not a file...
URL u;
try {
u = new URL(URI);
} catch (MalformedURLException e1) {
return false;
}
try {
in = u.openConnection().getInputStream();
} catch (IOException e1) {
return false;
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
return true;
}
// All is well. Go on...
return true;
}
public static boolean testWriteAccess(String URI) {
OutputStream out;
// This is bullshit.
if (URI == null) {
return false;
}
if (URI.length() == 0) {
return false;
}
try {
out = new FileOutputStream(URI);
} catch (FileNotFoundException e) {
// Not a file...
URL u;
try {
u = new URL(URI);
} catch (MalformedURLException e1) {
return false;
}
try {
out = u.openConnection().getOutputStream();
} catch (IOException e1) {
return false;
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
return true;
}
// All is well. Go on...
return true;
}
/**
* Returns true if flags are included in arg. Synonymous with (flags &
* arg)!=0
*
* @param flags
* @param arg
* @return
*/
public static boolean flags(int flags, int arg) {
return ((flags & arg) != 0);
}
public static boolean flags(long flags, long arg) {
return ((flags & arg) != 0);
}
/**
* Returns 1 for true and 0 for false. Useful, given the amount of
* "arithmetic" logical functions in legacy code. Synonymous with
* (expr?1:0);
*
* @param flags
* @param arg
* @return
*/
public static int eval(boolean expr) {
return (expr ? 1 : 0);
}
/**
* Returns 1 for non-null and 0 for null objects. Useful, given the amount
* of "existential" logical functions in legacy code. Synonymous with
* (expr!=null);
*
* @param flags
* @param arg
* @return
*/
public static boolean eval(Object expr) {
return (expr != null);
}
/**
* Returns true for expr!=0, false otherwise.
*
* @param flags
* @param arg
* @return
*/
public static boolean eval(int expr) {
return expr != 0;
}
/**
* Returns true for expr!=0, false otherwise.
*
* @param flags
* @param arg
* @return
*/
public static boolean eval(long expr) {
return expr != 0;
}
public static void resetAll(final Resettable[] r) {
for (final Resettable r1 : r) {
r1.reset();
}
}
/**
* Useful for unquoting strings, since StringTokenizer won't do it for us.
* Returns null upon any failure.
*
* @param s
* @param c
* @return
*/
public static String unquote(String s, char c) {
int firstq = s.indexOf(c);
int lastq = s.lastIndexOf(c);
// Indexes valid?
if (isQuoted(s,c))
return s.substring(firstq + 1, lastq);
return null;
}
public static boolean isQuoted(String s, char c) {
int q1 = s.indexOf(c);
int q2 = s.lastIndexOf(c);
char c1,c2;
// Indexes valid?
if (q1 != -1 && q2 != -1) {
if (q1 < q2) {
c1=s.charAt(q1);
c2=s.charAt(q2);
return (c1==c2);
}
}
return false;
}
public static String unquoteIfQuoted(String s, char c) {
String tmp = unquote(s, c);
if (tmp != null)
return tmp;
return s;
}
/**
* Return either 0 or a hashcode
*
* @param o
*/
public static int pointer(Object o) {
if (o == null)
return 0;
else
return o.hashCode();
}
public static boolean checkForExtension(String filename, String ext) {
// Null filenames satisfy null extensions.
if ((filename == null || filename.isEmpty()) && (ext == null || ext.isEmpty())) {
return true;
} else if (filename == null) { // avoid NPE - Good Sign 2017/05/07
filename = "";
}
String separator = System.getProperty("file.separator");
// Remove the path upto the filename.
int lastSeparatorIndex = filename.lastIndexOf(separator);
if (lastSeparatorIndex != -1) {
filename = filename.substring(lastSeparatorIndex + 1);
}
String realext;
// Get extension separator. It SHOULD be . on all platforms, right?
int pos = filename.lastIndexOf('.');
if (pos >= 0 && pos <= filename.length() - 2) { // Extension present
// Null comparator on valid extension
if (ext == null || ext.isEmpty()) return false;
realext = filename.substring(pos + 1);
return realext.compareToIgnoreCase(ext) == 0;
} else if (ext == null || ext.isEmpty()) { // No extension, and null/empty comparator
return true;
}
// No extension, and non-null/nonempty comparator.
return false;
}
/** Return the filename without extension, and stripped
* of the path.
*
* @param s
* @return
*/
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf('.');
if (extensionIndex == -1) {
return filename;
}
return filename.substring(0, extensionIndex);
}
/**
* This method is supposed to return the "name" part of a filename. It was
* intended to return length-limited (max 8 chars) strings to use as lump
* indicators. There's normally no need to enforce this behavior, as there's
* nothing preventing the engine from INTERNALLY using lump names with >8
* chars. However, just to be sure...
*
* @param path
* @param limit Set to any value >0 to enforce a length limit
* @param whole keep extension if set to true
* @return
*/
public static String extractFileBase(String path, int limit, boolean whole) {
if (path==null) return path;
int src = path.length() - 1;
String separator = System.getProperty("file.separator");
src = path.lastIndexOf(separator)+1;
if (src < 0) // No separator
src = 0;
int len = path.lastIndexOf('.');
if (whole || len<0 ) len=path.length()-src; // No extension.
else len-= src;
// copy UP to the specific number of characters, or all
if (limit > 0) len = Math.min(limit, len);
return path.substring(src, src + len);
}
/** Maes: File intead of "inthandle" */
public static long filelength(File handle) {
try {
return handle.length();
} catch (Exception e) {
System.err.println("Error fstating");
return -1;
}
}
@SuppressWarnings("unchecked")
public static <T> T[] resize(T[] oldarray, int newsize) {
if (oldarray[0] != null) {
return resize(oldarray[0], oldarray, newsize);
}
T cls;
try {
cls = (T) oldarray.getClass().getComponentType().newInstance();
return resize(cls, oldarray, newsize);
} catch (IllegalAccessException | InstantiationException e) {
System.err.println("Cannot autodetect type in resizeArray.\n");
return null;
}
}
/** Generic array resizing method. Calls Arrays.copyOf but then also
* uses initArrayOfObject for the "abundant" elements.
*
* @param <T>
* @param instance
* @param oldarray
* @param newsize
* @return
*/
public static <T> T[] resize(T instance, T[] oldarray, int newsize) {
// Hmm... nope.
if (newsize <= oldarray.length) {
return oldarray;
}
// Copy old array with built-in stuff.
T[] tmp = Arrays.copyOf(oldarray, newsize);
// Init the null portions as well
C2JUtils.initArrayOfObjects(tmp, oldarray.length, tmp.length);
System.out.printf("Old array of type %s resized. New capacity: %d\n", instance.getClass(), newsize);
return tmp;
}
/** Resize an array without autoinitialization. Same as Arrays.copyOf(..), just
* prints a message.
*
* @param <T>
* @param oldarray
* @param newsize
* @return
*/
public static <T> T[] resizeNoAutoInit(T[] oldarray, int newsize) {
// For non-autoinit types, this is enough.
T[] tmp = Arrays.copyOf(oldarray, newsize);
System.out.printf("Old array of type %s resized without auto-init. New capacity: %d\n",
tmp.getClass().getComponentType(), newsize);
return tmp;
}
@SuppressWarnings("unchecked")
public static <T> T[] getNewArray(T instance, int size) {
Class<T> c = (Class<T>) instance.getClass();
try {
return (T[]) Array.newInstance(c, size);
} catch (NegativeArraySizeException e) {
e.printStackTrace();
System.err.println("Failure to allocate " + size
+ " objects of class " + c.getName() + "!");
System.exit(-1);
}
return null;
}
public final static<T> T[] getNewArray(int size,T instance){
@SuppressWarnings("unchecked")
Class<T> c=(Class<T>) instance.getClass();
return getNewArray(c,size);
}
@SuppressWarnings("unchecked")
public final static<T> T[] getNewArray(Class<T> c,int size){
try {
return (T[]) Array.newInstance(c, size);
} catch (NegativeArraySizeException e) {
e.printStackTrace();
System.err.println("Failure to allocate " + size
+ " objects of class " + c.getName() + "!");
System.exit(-1);
}
return null;
}
/**
* Try to guess whether a URI represents a local file, a network any of the
* above but zipped. Returns
*
* @param URI
* @return an int with flags set according to InputStreamSugar
*/
public static int guessResourceType(String URI) {
int result = 0;
InputStream in;
// This is bullshit.
if (URI == null || URI.length() == 0) {
return InputStreamSugar.BAD_URI;
}
try {
in = new FileInputStream(new File(URI));
// It's a file
result |= InputStreamSugar.FILE;
} catch (FileNotFoundException e) {
// Not a file...
URL u;
try {
u = new URL(URI);
} catch (MalformedURLException e1) {
return InputStreamSugar.BAD_URI;
}
try {
in = u.openConnection().getInputStream();
result |= InputStreamSugar.NETWORK_FILE;
} catch (IOException e1) {
return InputStreamSugar.BAD_URI;
}
}
// Try guessing if it's a ZIP file. A bit lame, really
// TODO: add proper validation, and maybe MIME type checking
// for network streams, for cases that we can't really
// tell from extension alone.
if (checkForExtension(URI, "zip")) {
result |= InputStreamSugar.ZIP_FILE;
}
try {
in.close();
} catch (IOException e) {
}
// All is well. Go on...
return result;
}
private C2JUtils() {}
}
| AXDOOMER/mochadoom | src/utils/C2JUtils.java |
247,800 | /*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang;
/**
* The <code>Short</code> class wraps a value of primitive type
* <code>short</code> in an object. An object of type
* <code>Short</code> contains a single field whose type is
* <code>short</code>.
*
* <p>
*
* In addition, this class provides several methods for converting a
* <code>short</code> to a <code>String</code> and a
* <code>String</code> to a <code>short</code>, as well as other
* constants and methods useful when dealing with a <code>short</code>.
*
* @author Nakul Saraiya
* @version %I%, %G%
* @see java.lang.Number
* @since JDK1.1
*/
public final class Short extends Number implements Comparable<Short> {
/**
* A constant holding the minimum value a <code>short</code> can
* have, -2<sup>15</sup>.
*/
public static final short MIN_VALUE = -32768;
/**
* A constant holding the maximum value a <code>short</code> can
* have, 2<sup>15</sup>-1.
*/
public static final short MAX_VALUE = 32767;
/**
* The <code>Class</code> instance representing the primitive type
* <code>short</code>.
*/
public static final Class<Short> TYPE = (Class<Short>) Class.getPrimitiveClass("short");
/**
* Returns a new <code>String</code> object representing the
* specified <code>short</code>. The radix is assumed to be 10.
*
* @param s the <code>short</code> to be converted
* @return the string representation of the specified <code>short</code>
* @see java.lang.Integer#toString(int)
*/
public static String toString(short s) {
return Integer.toString((int)s, 10);
}
/**
* Parses the string argument as a signed decimal
* <code>short</code>. The characters in the string must all be
* decimal digits, except that the first character may be an ASCII
* minus sign <code>'-'</code> (<code>'\u002D'</code>) to
* indicate a negative value. The resulting <code>short</code> value is
* returned, exactly as if the argument and the radix 10 were
* given as arguments to the {@link #parseShort(java.lang.String,
* int)} method.
*
* @param s a <code>String</code> containing the <code>short</code>
* representation to be parsed
* @return the <code>short</code> value represented by the
* argument in decimal.
* @exception NumberFormatException If the string does not
* contain a parsable <code>short</code>.
*/
public static short parseShort(String s) throws NumberFormatException {
return parseShort(s, 10);
}
/**
* Parses the string argument as a signed <code>short</code> in
* the radix specified by the second argument. The characters in
* the string must all be digits, of the specified radix (as
* determined by whether {@link java.lang.Character#digit(char,
* int)} returns a nonnegative value) except that the first
* character may be an ASCII minus sign <code>'-'</code>
* (<code>'\u002D'</code>) to indicate a negative value. The
* resulting <code>byte</code> value is returned.
* <p>
* An exception of type <code>NumberFormatException</code> is
* thrown if any of the following situations occurs:
* <ul>
* <li> The first argument is <code>null</code> or is a string of
* length zero.
*
* <li> The radix is either smaller than {@link
* java.lang.Character#MIN_RADIX} or larger than {@link
* java.lang.Character#MAX_RADIX}.
*
* <li> Any character of the string is not a digit of the specified
* radix, except that the first character may be a minus sign
* <code>'-'</code> (<code>'\u002D'</code>) provided that the
* string is longer than length 1.
*
* <li> The value represented by the string is not a value of type
* <code>short</code>.
* </ul>
*
* @param s the <code>String</code> containing the
* <code>short</code> representation to be parsed
* @param radix the radix to be used while parsing <code>s</code>
* @return the <code>short</code> represented by the string
* argument in the specified radix.
* @exception NumberFormatException If the <code>String</code>
* does not contain a parsable <code>short</code>.
*/
public static short parseShort(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (short)i;
}
/**
* Returns a <code>Short</code> object holding the value
* extracted from the specified <code>String</code> when parsed
* with the radix given by the second argument. The first argument
* is interpreted as representing a signed <code>short</code> in
* the radix specified by the second argument, exactly as if the
* argument were given to the {@link #parseShort(java.lang.String,
* int)} method. The result is a <code>Short</code> object that
* represents the <code>short</code> value specified by the string.
* <p> In other words, this method returns a <code>Short</code> object
* equal to the value of:
*
* <blockquote><code>
* new Short(Short.parseShort(s, radix))
* </code></blockquote>
*
* @param s the string to be parsed
* @param radix the radix to be used in interpreting <code>s</code>
* @return a <code>Short</code> object holding the value
* represented by the string argument in the
* specified radix.
* @exception NumberFormatException If the <code>String</code> does
* not contain a parsable <code>short</code>.
*/
public static Short valueOf(String s, int radix)
throws NumberFormatException {
return new Short(parseShort(s, radix));
}
/**
* Returns a <code>Short</code> object holding the
* value given by the specified <code>String</code>. The argument
* is interpreted as representing a signed decimal
* <code>short</code>, exactly as if the argument were given to
* the {@link #parseShort(java.lang.String)} method. The result is
* a <code>Short</code> object that represents the
* <code>short</code> value specified by the string. <p> In other
* words, this method returns a <code>Byte</code> object equal to
* the value of:
*
* <blockquote><code>
* new Short(Short.parseShort(s))
* </code></blockquote>
*
* @param s the string to be parsed
* @return a <code>Short</code> object holding the value
* represented by the string argument
* @exception NumberFormatException If the <code>String</code> does
* not contain a parsable <code>short</code>.
*/
public static Short valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
/**
* Returns a <tt>Short</tt> instance representing the specified
* <tt>short</tt> value.
* If a new <tt>Short</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Short(short)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param s a short value.
* @return a <tt>Short</tt> instance representing <tt>s</tt>.
* @since 1.5
*/
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
/**
* Decodes a <code>String</code> into a <code>Short</code>.
* Accepts decimal, hexadecimal, and octal numbers given by
* the following grammar:
*
* <blockquote>
* <dl>
* <dt><i>DecodableString:</i>
* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
* <dd><i>Sign<sub>opt</sub></i> <code>0x</code> <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> <code>0X</code> <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> <code>#</code> <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> <code>0</code> <i>OctalDigits</i>
* <p>
* <dt><i>Sign:</i>
* <dd><code>-</code>
* </dl>
* </blockquote>
*
* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
* are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">§3.10.1</a>
* of the <a href="http://java.sun.com/docs/books/jls/html/">Java
* Language Specification</a>.
* <p>
* The sequence of characters following an (optional) negative
* sign and/or radix specifier ("<code>0x</code>",
* "<code>0X</code>", "<code>#</code>", or
* leading zero) is parsed as by the <code>Short.parseShort</code>
* method with the indicated radix (10, 16, or 8). This sequence
* of characters must represent a positive value or a {@link
* NumberFormatException} will be thrown. The result is negated
* if first character of the specified <code>String</code> is the
* minus sign. No whitespace characters are permitted in the
* <code>String</code>.
*
* @param nm the <code>String</code> to decode.
* @return a <code>Short</code> object holding the <code>short</code>
* value represented by <code>nm</code>
* @exception NumberFormatException if the <code>String</code> does not
* contain a parsable <code>short</code>.
* @see java.lang.Short#parseShort(java.lang.String, int)
*/
public static Short decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Short result;
// Handle minus sign, if present
if (nm.startsWith("-")) {
negative = true;
index++;
}
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index))
throw new NumberFormatException("Negative sign in wrong position");
try {
result = Short.valueOf(nm.substring(index), radix);
result = negative ? new Short((short)-result.shortValue()) :result;
} catch (NumberFormatException e) {
// If number is Short.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? new String("-" + nm.substring(index))
: nm.substring(index);
result = Short.valueOf(constant, radix);
}
return result;
}
/**
* The value of the <code>Short</code>.
*
* @serial
*/
private final short value;
/**
* Constructs a newly allocated <code>Short</code> object that
* represents the specified <code>short</code> value.
*
* @param value the value to be represented by the
* <code>Short</code>.
*/
public Short(short value) {
this.value = value;
}
/**
* Constructs a newly allocated <code>Short</code> object that
* represents the <code>short</code> value indicated by the
* <code>String</code> parameter. The string is converted to a
* <code>short</code> value in exactly the manner used by the
* <code>parseShort</code> method for radix 10.
*
* @param s the <code>String</code> to be converted to a
* <code>Short</code>
* @exception NumberFormatException If the <code>String</code>
* does not contain a parsable <code>short</code>.
* @see java.lang.Short#parseShort(java.lang.String, int)
*/
public Short(String s) throws NumberFormatException {
this.value = parseShort(s, 10);
}
/**
* Returns the value of this <code>Short</code> as a
* <code>byte</code>.
*/
public byte byteValue() {
return (byte)value;
}
/**
* Returns the value of this <code>Short</code> as a
* <code>short</code>.
*/
public short shortValue() {
return value;
}
/**
* Returns the value of this <code>Short</code> as an
* <code>int</code>.
*/
public int intValue() {
return (int)value;
}
/**
* Returns the value of this <code>Short</code> as a
* <code>long</code>.
*/
public long longValue() {
return (long)value;
}
/**
* Returns the value of this <code>Short</code> as a
* <code>float</code>.
*/
public float floatValue() {
return (float)value;
}
/**
* Returns the value of this <code>Short</code> as a
* <code>double</code>.
*/
public double doubleValue() {
return (double)value;
}
/**
* Returns a <code>String</code> object representing this
* <code>Short</code>'s value. The value is converted to signed
* decimal representation and returned as a string, exactly as if
* the <code>short</code> value were given as an argument to the
* {@link java.lang.Short#toString(short)} method.
*
* @return a string representation of the value of this object in
* base 10.
*/
public String toString() {
return String.valueOf((int)value);
}
/**
* Returns a hash code for this <code>Short</code>.
*/
public int hashCode() {
return (int)value;
}
/**
* Compares this object to the specified object. The result is
* <code>true</code> if and only if the argument is not
* <code>null</code> and is a <code>Short</code> object that
* contains the same <code>short</code> value as this object.
*
* @param obj the object to compare with
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Short) {
return value == ((Short)obj).shortValue();
}
return false;
}
/**
* Compares two <code>Short</code> objects numerically.
*
* @param anotherShort the <code>Short</code> to be compared.
* @return the value <code>0</code> if this <code>Short</code> is
* equal to the argument <code>Short</code>; a value less than
* <code>0</code> if this <code>Short</code> is numerically less
* than the argument <code>Short</code>; and a value greater than
* <code>0</code> if this <code>Short</code> is numerically
* greater than the argument <code>Short</code> (signed
* comparison).
* @since 1.2
*/
public int compareTo(Short anotherShort) {
return this.value - anotherShort.value;
}
/**
* The number of bits used to represent a <tt>short</tt> value in two's
* complement binary form.
* @since 1.5
*/
public static final int SIZE = 16;
/**
* Returns the value obtained by reversing the order of the bytes in the
* two's complement representation of the specified <tt>short</tt> value.
*
* @return the value obtained by reversing (or, equivalently, swapping)
* the bytes in the specified <tt>short</tt> value.
* @since 1.5
*/
public static short reverseBytes(short i) {
return (short) (((i & 0xFF00) >> 8) | (i << 8));
}
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 7515723908773894738L;
}
| zxiaofan/JDK | JDK1.6-Java SE Development Kit 6u45/src/java/lang/Short.java |
247,801 | package vcode;
/**
*
* @author: wuhongjun
* @version:1.0
*/
public class Quant {
protected static final int netsize = 256; /* number of colours used */
/* four primes near 500 - assume no image has a length so large */
/* that it is divisible by all four primes */
protected static final int prime1 = 499;
protected static final int prime2 = 491;
protected static final int prime3 = 487;
protected static final int prime4 = 503;
protected static final int minpicturebytes = (3 * prime4);
/* minimum size for input image */
/*
* Program Skeleton ---------------- [select samplefac in range 1..30] [read
* image from input file] pic = (unsigned char*) malloc(3*width*height);
* initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output
* image header, using writecolourmap(f)] inxbuild(); write output image using
* inxsearch(b,g,r)
*/
/*
* Network Definitions -------------------
*/
protected static final int maxnetpos = (netsize - 1);
protected static final int netbiasshift = 4; /* bias for colour values */
protected static final int ncycles = 100; /* no. of learning cycles */
/* defs for freq and bias */
protected static final int intbiasshift = 16; /* bias for fractions */
protected static final int intbias = (((int) 1) << intbiasshift);
protected static final int gammashift = 10; /* gamma = 1024 */
protected static final int gamma = (((int) 1) << gammashift);
protected static final int betashift = 10;
protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */
protected static final int betagamma = (intbias << (gammashift - betashift));
/* defs for decreasing radius factor */
protected static final int initrad = (netsize >> 3); /* for 256 cols, radius starts */
protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */
protected static final int radiusbias = (((int) 1) << radiusbiasshift);
protected static final int initradius = (initrad * radiusbias); /* and decreases by a */
protected static final int radiusdec = 30; /* factor of 1/30 each cycle */
/* defs for decreasing alpha factor */
protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */
protected static final int initalpha = (((int) 1) << alphabiasshift);
protected int alphadec; /* biased by 10 bits */
/* radbias and alpharadbias used for radpower calculation */
protected static final int radbiasshift = 8;
protected static final int radbias = (((int) 1) << radbiasshift);
protected static final int alpharadbshift = (alphabiasshift + radbiasshift);
protected static final int alpharadbias = (((int) 1) << alpharadbshift);
/*
* Types and Global Variables --------------------------
*/
protected byte[] thepicture; /* the input image itself */
protected int lengthcount; /* lengthcount = H*W*3 */
protected int samplefac; /* sampling factor 1..30 */
// typedef int pixel[4]; /* BGRc */
protected int[][] network; /* the network itself - [netsize][4] */
protected int[] netindex = new int[256];
/* for network lookup - really 256 */
protected int[] bias = new int[netsize];
/* bias and freq arrays for learning */
protected int[] freq = new int[netsize];
protected int[] radpower = new int[initrad];
/* radpower for precomputation */
/*
* Initialise network in range (0,0,0) to (255,255,255) and set parameters
* -----------------------------------------------------------------------
*/
public Quant(byte[] thepic, int len, int sample) {
int i;
int[] p;
thepicture = thepic;
lengthcount = len;
samplefac = sample;
network = new int[netsize][];
for (i = 0; i < netsize; i++) {
network[i] = new int[4];
p = network[i];
p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize;
freq[i] = intbias / netsize; /* 1/netsize */
bias[i] = 0;
}
}
public byte[] colorMap() {
byte[] map = new byte[3 * netsize];
int[] index = new int[netsize];
for (int i = 0; i < netsize; i++)
index[network[i][3]] = i;
int k = 0;
for (int i = 0; i < netsize; i++) {
int j = index[i];
map[k++] = (byte) (network[j][0]);
map[k++] = (byte) (network[j][1]);
map[k++] = (byte) (network[j][2]);
}
return map;
}
/*
* Insertion sort of network and building of netindex[0..255] (to do after
* unbias)
* -----------------------------------------------------------------------------
* --
*/
public void inxbuild() {
int i, j, smallpos, smallval;
int[] p;
int[] q;
int previouscol, startpos;
previouscol = 0;
startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; /* index on g */
/* find smallest in i..netsize-1 */
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { /* index on g */
smallpos = j;
smallval = q[1]; /* index on g */
}
}
q = network[smallpos];
/* swap p (i) and q (smallpos) entries */
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
/* smallval entry is now in position i */
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; /* really 256 */
}
/*
* Main Learning Loop ------------------
*/
public void learn() {
int i, j, b, g, r;
int radius, rad, alpha, step, delta, samplepixels;
byte[] p;
int pix, lim;
if (lengthcount < minpicturebytes)
samplefac = 1;
alphadec = 30 + ((samplefac - 1) / 3);
p = thepicture;
pix = 0;
lim = lengthcount;
samplepixels = lengthcount / (3 * samplefac);
delta = samplepixels / ncycles;
alpha = initalpha;
radius = initradius;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (i = 0; i < rad; i++)
radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
// fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad);
if (lengthcount < minpicturebytes)
step = 3;
else if ((lengthcount % prime1) != 0)
step = 3 * prime1;
else {
if ((lengthcount % prime2) != 0)
step = 3 * prime2;
else {
if ((lengthcount % prime3) != 0)
step = 3 * prime3;
else
step = 3 * prime4;
}
}
i = 0;
while (i < samplepixels) {
b = (p[pix + 0] & 0xff) << netbiasshift;
g = (p[pix + 1] & 0xff) << netbiasshift;
r = (p[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad != 0)
alterneigh(rad, j, b, g, r); /* alter neighbours */
pix += step;
if (pix >= lim)
pix -= lengthcount;
i++;
if (delta == 0)
delta = 1;
if (i % delta == 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (j = 0; j < rad; j++)
radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
// fprintf(stderr,"finished 1D learning: final alpha=%f
// !\n",((float)alpha)/initalpha);
}
/*
* Search for BGR values 0..255 (after net is unbiased) and return colour index
* ----------------------------------------------------------------------------
*/
public int map(int b, int g, int r) {
int i, j, dist, a, bestd;
int[] p;
int best;
bestd = 1000; /* biggest possible dist is 256*3 */
best = -1;
i = netindex[g]; /* index on g */
j = i - 1; /* start at netindex[g] and work outwards */
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; /* inx key */
if (dist >= bestd)
i = netsize; /* stop iter */
else {
i++;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; /* inx key - reverse dif */
if (dist >= bestd)
j = -1; /* stop iter */
else {
j--;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return (best);
}
public byte[] process() {
learn();
unbiasnet();
inxbuild();
return colorMap();
}
/*
* Unbias network to give byte values 0..255 and record position i to prepare
* for sort
* -----------------------------------------------------------------------------
* ------
*/
public void unbiasnet() {
int i;// j;
for (i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; /* record colour no */
}
}
/*
* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in
* radpower[|i-j|]
* -----------------------------------------------------------------------------
* ----
*/
protected void alterneigh(int rad, int i, int b, int g, int r) {
int j, k, lo, hi, a, m;
int[] p;
lo = i - rad;
if (lo < -1)
lo = -1;
hi = i + rad;
if (hi > netsize)
hi = netsize;
j = i + 1;
k = i - 1;
m = 1;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
} // prevents 1.3 miscompilation
}
if (k > lo) {
p = network[k--];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
}
}
}
}
/*
* Move neuron i towards biased (b,g,r) by factor alpha
* ----------------------------------------------------
*/
protected void altersingle(int alpha, int i, int b, int g, int r) {
/* alter hit neuron */
int[] n = network[i];
n[0] -= (alpha * (n[0] - b)) / initalpha;
n[1] -= (alpha * (n[1] - g)) / initalpha;
n[2] -= (alpha * (n[2] - r)) / initalpha;
}
/*
* Search for biased BGR values ----------------------------
*/
protected int contest(int b, int g, int r) {
/* finds closest neuron (min dist) and updates freq */
/* finds best neuron (min dist-bias) and returns position */
/* for frequently chosen neurons, freq[i] is high and bias[i] is negative */
/* bias[i] = gamma*((1/netsize)-freq[i]) */
int i, dist, a, biasdist, betafreq;
int bestpos, bestbiaspos, bestd, bestbiasd;
int[] n;
bestd = ~(((int) 1) << 31);
bestbiasd = bestd;
bestpos = -1;
bestbiaspos = bestpos;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = n[0] - b;
if (dist < 0)
dist = -dist;
a = n[1] - g;
if (a < 0)
a = -a;
dist += a;
a = n[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return (bestbiaspos);
}
} | playcommunity/play-community | app/vcode/Quant.java |
247,802 | package com.stellarsoftware.beam;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*; // Rectangle2D
import java.awt.print.*; // printing
import java.awt.font.*; // font metric
import java.awt.datatransfer.*; // clipboard
import java.beans.*; // vetoableChangeListener
import java.io.*; // files
import javax.swing.*; // everything else
import javax.swing.event.*; // for MenuEvents and InternalFrameAdapter
@SuppressWarnings("serial")
/**
* A164: installing CopyFieldBottom()
* key listener: line 1027
* implementor: line 1221
*
*
* A158: testing permanent scrollbars, to possibly eliminate the
* self-scrolling on Mac platform triggered by resize drag.
*
* A152: TextMode needs line-break pushdown and line-yank pullup.
*
*
* EPanel.java --- an editor panel for the EJIF frame.
* This class contains a private full size charTable...
* private char charTable[][] = new char[JMAX+1][IMAX+1];
* but clients may have tighter limitations on table size.
*
* No need to mention: AdjustmentListener, KeyListener, MouseListener,
* MouseMotionListener, FocusListener, accelerator...
*
* 2D edit technique: char charTable[][] contains the text.
*
* This class replaces JTextArea and adds many new features.
*
* A129: has DMF.nEdits, helping graphics to coordinate repaints.
*
* Caret on/off is driven by BJIF and EJIF, not locally.
* Caret location is managed here.
*
* Focus is driven by EJIF's internalFrameListener.
* JScrollBars are managed here.
*
* A118 implements a simple undo with a single String buffer.
* stashUndo is called at the start of methods...
* doDelete()
* vLoadString()
* clearTable()
* putTypedChar()
* widenTable()
* narrowTable()
* copyFieldDown().
*
* stashForUndo() is not called in myEJIF.setDirty(true) because that method
* of myGJIF is called very frequently: each microchange in the table.
* doUndo() is called only within MyKeyHandler::keyPressed for VK_Z.
*
* Seems to me that stashForUndo() ought to be called at start of AutoAdjust
* to permit backing out of .OPT and .RAY adjustments. To accomplish this
* it will need to be public, not private. DONE; and conveyed through EJIF.
*
*
* (c) 2006 Stellar Software
**/
class EPanel extends JPanel implements B4constants, MouseWheelListener
{
// public static final long serialVersionUID = 42L; // Xlint 8 Oct 2014
public EPanel(EJIF ejif) // constructor
{
// no need to initialize base class JPanel "super()"
///// testing suggestion from StackOverflow....
///// this.setDoubleBuffered(false);
///// does it work? Nope.
myEJIF = ejif;
vsbReference = null;
clearTable();
//--------set up fieldArray helpers-----------------
nfields = 0;
for (int f=0; f<MAXFIELDS; f++)
{
iFieldStartCol[f] = 0;
iFieldWidth[f] = 0;
iFieldTagCol[f] = 0;
iFieldDecimalPlaces[f] = 0;
cFieldFormat[f] = '-';
}
//---initialize sizes; also refresh these each repaint().
//---repaint() gets called for every resizing.
px = getSize().width; // pixels
py = getSize().height; // pixels
iWidth = px/charwidth; // number of chars wide
jHeight = py/charheight; // number of chars tall
//---focusTraversal must be disabled for VK_TAB key to work
//---Caret management does not use focus: mere epiphenomenon.
//---so we don't need a focusListener.
//---Focus influences keystrokes only.
//---But wait! how can LossOfFocus force a caretfree repaint?
this.setFocusTraversalKeysEnabled(false);
this.setFocusable(true);
this.addKeyListener(new MyKeyHandler());
this.addMouseListener(new MyMouseHandler());
this.addMouseMotionListener(new MyMouseMotionHandler());
// possible simplification here:
// Swing MouseInputAdapter = MouseListener + MouseMotionListener().
// but it does not include any wheel listening.
this.addMouseWheelListener(this);
// Now find out editor contents to manage scroll bars:
// No no install permanent scrollbars: A158, A163
hsbReference = myEJIF.createHSB();
iOff = 0;
vsbReference = myEJIF.createVSB();
jOff = 0;
getAllLineLengths();
myEJIF.setDirty(false);
} //--------end constructor---------------
public void setCaretFlag(boolean b)
// Required support for abstract class EJIF
{
bCaret = b;
}
public void refreshSizes()
// After major edits, reestablishes table size & line lengths
// These are needed internally for further editing.
{
getAllLineLengths();
}
public void paintComponent(Graphics g)
// Paints the visible JPanel and the caret each blink.
// The frame title is repainted by EJIF.
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
fontsize = U.parseInt(DMF.reg.getuo(UO_EDIT, 6));
fontsize = Math.max(3, Math.min(100, fontsize));
boolean bBold = "T".equals(DMF.reg.getuo(UO_EDIT, 7));
int iBold = bBold ? Font.BOLD : Font.PLAIN;
Font myFont = new Font("Monospaced", iBold, fontsize);
g2.setFont(myFont);
charheight = fontsize;
charwidth = getFontWidth(g2, myFont);
g2.setPaint(Color.BLACK);
setEditSmoothing(g2);
px = getSize().width; // pixels showing
iWidth = px/charwidth; // characters showing
py = getSize().height; // pixels showing
jHeight = py/charheight; // characters showing
manageVSB(); // scroll bar management when size changes
manageHSB();
int jmin = jOff;
int jmax = jOff + jHeight;
for (int j=jmin; j<jmax; j++) // j = row of table
{
int jwin = j-jmin; // jwin = row within window
if (j < JMAX-1) // within the table
{
g2.setPaint(isRowMarked(j) ? BLUEGRAY : Color.WHITE);
g2.fillRect(0, jwin*charheight+JPOFF, px, charheight);
g2.setPaint(Color.BLACK);
linelen[j] = getOneLineLength(j);
int count = Math.max(0, linelen[j] - iOff);
String s = new String(charTable[j], iOff, count);
g2.drawString(s, 0, (jwin+1)*charheight);
// alternative: g2.drawChars(....)
}
else // beyond the table
{
g2.setPaint(Color.GRAY);
g2.fillRect(0, jwin*charheight+JPOFF, px, charheight);
}
}
if (myEJIF.getCaretStatus())
{
int i = (iCaret-iOff)*charwidth + IOC;
int j = (jCaret-jOff)*charheight + JOC;
int caretwidth = charwidth;
if("T".equals(DMF.reg.getuo(UO_EDIT, 10))) // text mode
caretwidth = charwidth/4;
g2.setXORMode(Color.YELLOW);
g2.fillRect(i, j, caretwidth, charheight);
}
// EJIF manages its own title, has own paintComponent().
} //----end paintComponent()
public void setCaretXY(int field, int row)
{
int nfields = getFieldInfo();
if ((field>=0) && (field<nfields))
iCaret = iFieldStartCol[field];
if ((row>=0) && (row<JMAX-2))
jCaret = row;
}
public int getCaretY() // added A106 for AutoRayGen
{
return jCaret;
}
//------------ public administrative methods---------------
private void setEditSmoothing(Graphics2D g2)
{
if ("T".equals(DMF.reg.getuo(UO_EDIT, 8)))
{
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
else
{
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
}
public void setVerticalPosition(int rowNumber)
// Called by Frame when scrollbar produces a message
{
jOff = rowNumber;
repaint(); // OS eventually calls paintComponent() below
}
public void setHorizontalPosition(int colNumber)
// Called by Frame when scrollbar produces a message
{
iOff = colNumber;
repaint();
}
public int getFieldInfo()
// field start is the transition (start or colon)->noncolon
// field end is transition noncolon->(colon or end)
// iFieldWidth[] **excludes** the tag char.
// returns the number of fields found.
{
/// start by zeroing the field globals...
nfields = 0;
for (int f=0; f<MAXFIELDS; f++)
{
iFieldStartCol[f] = 0;
iFieldWidth[f] = 0;
iFieldTagCol[f] = 0;
iFieldDecimalPlaces[f] = 0;
cFieldFormat[f] = '-';
}
int rlen = getOneLineLength(RULER);
if (rlen < 5)
return 0; // no fields!
/// search the ruler for its colons...
char colon = ':';
char tc = colon;
char pc = colon;
int point = 0;
boolean bstart, btag;
for (int i=0; i<rlen; i++)
{
tc = (i < rlen-1) ? charTable[RULER][i] : colon;
bstart = (pc == colon) && (tc != colon);
btag = (pc != colon) && (tc == colon);
if (bstart)
iFieldStartCol[nfields] = i;
if ((tc == '.') || (tc == ','))
{
point = i;
cFieldFormat[nfields] = tc;
}
if ((tc=='E') || (tc=='e'))
cFieldFormat[nfields] = tc;
if (btag)
{
iFieldTagCol[nfields] = i;
iFieldWidth[nfields] = i - iFieldStartCol[nfields];
if (point > iFieldStartCol[nfields])
iFieldDecimalPlaces[nfields] = i-point-1;
else
iFieldDecimalPlaces[nfields] = iFieldWidth[nfields]/2;
if (nfields < MAXFIELDS-1)
nfields++;
}
pc = tc;
}
return nfields;
}
public String getFieldFull(int f, int jrow)
// String excludes tag char but includes leading & trailing blanks
// For clean string contents, user should apply .trim()
{
if ((f<0) || (f >= nfields))
return new String("");
if ((jrow<0) || (jrow>=nlines))
return new String("");
int iLeft = iFieldStartCol[f];
int width = iFieldWidth[f];
return new String(charTable[jrow], iLeft, width);
}
public String getFieldTrim(int ifield, int jrow)
// Returns the trimmed field, no leading or trailing blanks
{
return getFieldFull(ifield, jrow).trim();
}
public double getFieldDouble(int ifield, int jrow)
// empty returns -0.0; badnum returns Double.NaN
// U.suckDouble() includes trimming and -0 for empty.
{
return U.suckDouble(getFieldFull(ifield, jrow));
}
public int getFieldWidth(int f)
{
return iFieldWidth[f];
}
public void putFieldString(int f, int jrow, String s)
// Puts a field into an existing table with room.
{
if ((f<0) || (f>=nfields) || (jrow<0) || (jrow>nlines))
return;
int ileft = iFieldStartCol[f];
int len = (jrow==0) ? s.length() : iFieldWidth[f]; // no tag.
for (int i=0; i<len; i++)
charTable[jrow][ileft + i] = U.getCharAt(s, i);
myEJIF.setDirty(true);
// note: U.getCharAt() returns blanks as needed.
}
public void forceFieldString(int f, int jrow, String s)
// Enlarges table if necessary to accommodate jrow
{
if ((f<0) || (f>=nfields) || (jrow<0) || (jrow>JMAX-5))
return;
if (jrow >= nlines)
{
putLineWithColons(jrow);
nlines = jrow+1;
}
int ileft = iFieldStartCol[f];
int len = iFieldWidth[f]; // excludes tag.
for (int i=0; i<len; i++)
charTable[jrow][ileft + i] = U.getCharAt(s, i);
myEJIF.setDirty(true);
// note: U.getCharAt() returns blanks as needed.
}
public void putFieldDouble(int f, int jrow, double d)
{
String s = U.fmtc(d,
iFieldWidth[f],
iFieldDecimalPlaces[f],
cFieldFormat[f]);
putFieldString(f, jrow, s);
myEJIF.setDirty(true);
}
public void forceFieldDouble(int f, int jrow, double d)
{
String s = U.fmtc(d,
iFieldWidth[f],
iFieldDecimalPlaces[f],
cFieldFormat[f]);
forceFieldString(f, jrow, s);
myEJIF.setDirty(true);
}
public char getTagChar(int f, int jrow)
{
return charTable[jrow][iFieldTagCol[f]];
}
public void putTagChar(int f, int jrow, char c)
{
charTable[jrow][iFieldTagCol[f]] = c;
myEJIF.setDirty(true);
}
public boolean hasContent()
{
return (getAllLineLengths() > 0);
}
public int getLineCount()
{
return getAllLineLengths();
}
public int getLineLength(int jrow)
{
return linelen[jrow];
}
public int getICaret()
{
return iCaret;
}
public int getJCaret()
{
return jCaret;
}
public int getCaretFieldNum()
{
return getWhichField(iCaret);
}
public int getNumFields()
{
return getFieldInfo();
}
public int getGuideNumber()
// Returns the intended number of user records in the table.
{
String s = new String(charTable[0], 0, 20);
return U.suckInt(s);
}
public boolean isMarked() // public for edit graying
{
return jDrag >= 0;
}
public void doUnmarkRepaint()
{
jDrag = -1;
repaint();
}
public void doSelectAll() // for edit menu
{
getAllLineLengths();
jDown = 0;
jDrag = nlines-1;
repaint();
}
//------------- public i/o methods-------------------------
public String getLine(int j)
// assumes that getAllLineLengths() has been called first
// to initialize nlines and individual line lengths.
{
if ((j<0) || (j>=nlines))
return "";
return new String(charTable[j], 0, linelen[j]);
}
public void vLoadSkeleton()
{
int ifw = U.parseInt(DMF.reg.getuo(UO_EDIT, 3));
ifw = Math.max(6, Math.min(100, ifw));
DMF.nEdits++;
clearTable();
for (int i=0; i<100; i++)
charTable[2][i] = '-';
for (int j=2; j<15; j++)
for (int i=ifw; i<100; i+=ifw)
charTable[j][i] = ':';
iMouse = jMouse = jDown = iCaret = jCaret = iOff = jOff = 0;
jDrag = -1;
myEJIF.setDirty(false);
getAllLineLengths();
getFieldInfo();
}
public boolean save(File f)
// Uses println() to generate local platform EOLs.
{
getAllLineLengths(); // sets up linelengths & nlines.
try
{
PrintWriter pw = new PrintWriter(new FileWriter(f), true);
for (int j=0; j<nlines; j++)
{
String s = new String(charTable[j], 0, linelen[j]);
pw.println(s);
}
pw.close();
myEJIF.setDirty(false);
return true;
}
catch (IOException ioe)
{ return false; }
}
public String getMarkedText()
// Reads text in a table.
// This does not upset jCaret or existing markings,
// so that "cut" can subsequently doDelete().
// Performs tab delimiter substitutions when option=TABS.
{
getAllLineLengths();
if (!isMarked())
return "";
StringBuffer sb = new StringBuffer(10000);
int j0 = Math.min(jDown, jDrag);
int j1 = Math.max(jDown, jDrag);
for (int j=j0; j<=j1; j++)
{
sb.append(charTable[j], 0, linelen[j]);
sb.append('\n');
}
//------perform tab substitutions-------------
//-------use charTable[2] as ruler------------
//------don't clobber any EOLs!---------------
if (DMF.reg.getuo(UO_EDIT, 5).equals("T"))
{
int iX=0, j=j0;
for (int i=0; i<sb.length(); i++)
{
if (j>0)
if ((charTable[2][iX]==COLON) && (sb.charAt(i)!='\n'))
sb.setCharAt(i, TAB);
iX++;
if (sb.charAt(i) == '\n')
{
iX=0;
j++;
}
}
}
return new String(sb);
}
public void setCaretToMark()
{
int jMark = Math.min(jDown, jDrag);
if (jMark >= 0)
jCaret = jMark;
}
public void doDelete()
// deletes lines that are in the marked zone
// this might be faster using System.arrayCopy()
{
DMF.nEdits++;
getAllLineLengths();
stashForUndo();
if (!isMarked())
return;
int j0 = Math.min(jDown, jDrag);
int j1 = Math.max(jDown, jDrag);
int nmarked = 1 + j1 - j0;
for (int j=j0; j<JMAX-nmarked; j++)
for (int i=0; i<IMAX; i++)
charTable[j][i] = charTable[j+nmarked][i];
for (int j=JMAX-nmarked; j<JMAX; j++)
clearLine(j);
// any need to rearrange jCaret?
getAllLineLengths();
myEJIF.setDirty(true);
doUnmarkRepaint();
}
public void vLoadString(String s, boolean preclear)
// Handles PC, Mac, Unix EOL format strings from file or clipboard.
// Always inserts, never overwrites.
// Can receive entire table: decides colons vs CSV/Tab;
// or just the data portion of a table, uses existing ruler.
// Called by EJIF.pasteInto() or by EJIF.loadFile().
// For pastes, want caret left at bottom of each.
// For fresh loads, prefer jCaret = 0.
// What about complete pastes where jStart == 0? Bottom.
// So, use preclear to set jCaret = 0.
{
DMF.nEdits++;
stashForUndo();
if (s.length() < 1)
return;
if (preclear)
clearTable(); // also zeroes caret, scrollers
getAllLineLengths();
int i=0;
char c, cprev=' ';
boolean bComplete = (jCaret == 0);
boolean bForeign = (getDelimiterStatus(s, jCaret) == 2);
period = 1 + U.parseInt(DMF.reg.getuo(UO_EDIT, 3));
period = Math.max(4, Math.min(20, period));
// start loading at line = jCaret...
for (int k=0; k<s.length(); k++)
{
if (i==0) // start a new line?
pushDownOneLine(jCaret); // insertion; clears jCaret line too.
c = U.getCharAt(s, k);
switch (c)
{
// case COMMA:
// case SEMICOLON:
case TAB:
if (jCaret < 3) // build new ruler
i = formulaTagPos(i, period);
else // use existing ruler
i = rulerTagPos(i, period);
if ((i<IMAX) && (jCaret<JMAX) && (jCaret>1))
charTable[jCaret][i] = COLON;
if (i<IMAX-2)
i++; // prepare for next character
break;
case LF:
if (cprev==CR) break;
i=0; jCaret++; break;
case CR:
i=0; jCaret++; break;
default:
if ((c>=SPACE) && (c<='~') && (i<IMAX-2))
{
charTable[jCaret][i] = c;
i++;
}
}
if (jCaret>=JMAX-2)
break;
cprev = c;
}
getAllLineLengths();
iCaret = 0;
if (preclear)
jCaret = 0;
getFieldInfo();
repaint();
}
public void stashForUndo()
// called locally for significant changes to the charTable,
// or via EJIF at start of AutoAdjust (hence public).
{
sUndo = getTableString();
nstash++;
}
//-----------------end of public methods-------------------------
//-----------------begin private area----------------------------
//-----------------begin private area----------------------------
//-----------------begin private area----------------------------
//-----------------begin private area----------------------------
//--------move all these constants into Constants.java??----------
private static final Color BLUEGRAY = new Color(188, 188, 255);
private static final int JPOFF = 3; // vert paint offset
private static final int IOC = 0; // horiz caret offset
private static final int JOC = 2; // vert caret offset
private static final int TABJUMP = 8;
private static final int VERTJUMP = 8;
//-------------here is the char table-----------------
private char charTable[][] = new char[JMAX+1][IMAX+1];
//-------------other private fields---------------
private String sUndo = new String("");
private int nstash = 0; // diagnostics only
private int linelen[] = new int[JMAX];
private int nlines = 0;
private int maxlinelen = 0;
private int period = 10; // fieldwidth+1
private int fontsize = 16;
private int charwidth = 8; // horiz char spacing
private int charheight = 16; // vert char spacing
private boolean bCaret = false;
private int iCaret, jCaret; // caret column & row
private int iOff, jOff; // scroll offset column & row
private int iMouse, jMouse; // unused
private int jDown=0; // start of drag, for graying
private int jDrag=-1; // -1=noMark, else end of drag
private int px, py; // client window w,h in pixels
private int iWidth, jHeight; // client window w,h in chars
private JScrollBar vsbReference = null;
private JScrollBar hsbReference = null;
private EJIF myEJIF = null;
//----------fieldArray helpers: obsolescent??------------
private int nfields = 0;
private int iFieldStartCol[] = new int[MAXFIELDS];
private int iFieldWidth[] = new int[MAXFIELDS];
private int iFieldTagCol[] = new int[MAXFIELDS];
private int iFieldDecimalPlaces[] = new int[MAXFIELDS];
private char cFieldFormat[] = new char[MAXFIELDS];
private char cColons[] = new char[IMAX];
//--------------private methods-------------------
private String getTableString()
// Multipurpose string sucker.
// Called by private swapUndo() and by public stashForUndo().
{
StringBuffer sb = new StringBuffer(1000);
getAllLineLengths();
for (int j=0; j<nlines; j++)
{
sb.append(charTable[j], 0, linelen[j]);
sb.append('\n');
}
return sb.toString();
}
private void putTableString(String sGiven)
// Clears the charTable and installs a given String.
// Also tidies up the diagnostics, and redisplays.
// Assumes EOL is '\n' and so is not multiplatform.
{
DMF.nEdits++;
int i=0, j=0, k=0;
for (j=0; j<JMAX; j++) // clear the table
for (i=0; i<IMAX; i++)
charTable[j][i] = ' ';
i=0;
j=0;
for (k=0; k<sGiven.length(); k++) // char loop
{
char c = U.getCharAt(sGiven, k);
if (c == '\n')
{
j++;
i=0;
}
else
{
charTable[j][i] = c;
i++;
}
}
getAllLineLengths();
getFieldInfo();
repaint();
}
private void swapUndo()
// called by local myKeyHandler() method for Ctl-Z.
{
DMF.nEdits++;
if (sUndo.length() < 1)
return;
String sTemp = getTableString();
putTableString(sUndo);
sUndo = sTemp;
}
private int formulaTagPos(int i, int p)
// Used by vLoadString to generate tags when ruler=formula.
// if p=10: 0...9->9; 10...19->19 etc
{
return ((i+p)/p)*p - 1; // new formula, equal field widths
}
private int rulerTagPos(int i, int p)
// Used by vLoadString to generate tags from a given ruler.
// Used by myKeyHandler to implement TAB function.
// If "i" lies beyond final ruler colon, it reverts to the formula.
// Least possible result is i, that is no skipping; nondecreasing.
// Assumes charTable[2][i] has been properly set up!
{
for (int k=i; k<IMAX-2; k++)
if (charTable[2][k] == COLON)
return k;
return formulaTagPos(i, p);
}
int doBackTab(int i)
// Used by myKeyHandler to implement BackTab.
// Avoids use of field organizers.
{
for (int k=i-2; k>0; k--)
if (charTable[2][k] == COLON)
return k+1;
return 0;
}
private int getWhichField(int icol)
// Each field must have a ruler colon tag.
{
if (nfields < 1)
return ABSENT;
if (icol < iFieldStartCol[0])
return ABSENT;
if (icol > iFieldTagCol[nfields-1])
return ABSENT; // no such field
for (int f=0; f<MAXFIELDS; f++)
if (iFieldTagCol[f] >= icol)
return f;
return 0;
}
private void clearLine(int j)
// When exactly is this called?
{
DMF.nEdits++;
for (int i=0; i<IMAX; i++)
charTable[j][i] = ' ';
myEJIF.setDirty(true);
}
private void pushDownOneLine(int j)
// Used by vLoadString() and TextMode ENTER key
// Inserts one blank line into the table at "j".
// For multiple line calls, we want only the initial preview saved.
// so here, no stashForUndo().
{
DMF.nEdits++;
j = Math.max(0, j);
for (int t=JMAX; t>j; t--)
System.arraycopy(charTable[t-1], 0, charTable[t], 0, IMAX);
clearLine(j);
myEJIF.setDirty(true);
}
private void pullUpOneLine(int j)
// line j will vanish, receiving text of j+1, etc.
// used by TextMode backspace at jCaret=0
{
DMF.nEdits++;
for (int t=j; t<JMAX; t++)
System.arraycopy(charTable[t+1], 0, charTable[t], 0, IMAX);
}
private void clearTable()
{
DMF.nEdits++;
stashForUndo();
for (int j=0; j<JMAX; j++)
clearLine(j);
iMouse = jMouse = jDown = iCaret = jCaret = iOff = jOff = 0;
jDrag = -1;
myEJIF.setDirty(false);
getFieldInfo();
}
private int getDelimiterStatus(String s, int jcaret)
// Examines a prospective data string for its delimiters.
// if jcaret<3, tests rulerline, else tests lineZero.
// Returns 0=unknown, 1=colons=native, 2=foreign=CSV/Tab
// Needed if a string is to be inserted at jCaret=0,
// because native->UseColonPattern; foreign->Use UO_EDIT_FWIDTH.
{
int j=0, ftype=0;
int jtest = Math.max(0, 2-jcaret);
for (int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if (c=='\n')
j++;
if (j==jtest) // test line
{
switch (c)
{
case COLON: ftype=1; break;
// case COMMA:
// case SEMICOLON:
case TAB: ftype=2; break;
}
if (ftype != 0)
break;
}
if (j>jtest)
break;
}
return ftype;
}
private boolean isRowMarked(int j)
{
if (jDrag<0)
return false;
return (j-jDown)*(j-jDrag) <= 0;
}
private int getAllLineLengths()
// Sets local nlines and linelen[] and maxlinelen.
// Individual linelen[] can be as big as IMAX-1
{
nlines = 0;
maxlinelen = 0;
for (int j=JMAX-1; j>=0; j--)
{
linelen[j] = getOneLineLength(j);
if ((nlines==0) && (linelen[j]>0))
nlines = j+1;
if (linelen[j] > maxlinelen)
maxlinelen = linelen[j];
}
for (int i=0; i<IMAX; i++)
cColons[i] = (charTable[RULER][i] == ':') ? ':' : ' ';
manageVSB();
return nlines;
}
private void putLineWithColons(int j)
// use this only after having run getAllLineLengths()
{
DMF.nEdits++;
if (j > RULER)
for (int i=0; i<IMAX; i++)
charTable[j][i] = cColons[i];
myEJIF.setDirty(true);
}
private int getOneLineLength(int j)
{
charTable[j][IMAX-1] = SPACE; // enforce terminal SP
int len = 0;
for (int i=IMAX-1; i>=0; i--)
if (charTable[j][i] != SPACE)
{
len = i+1;
break;
}
return len;
}
StringBuffer fieldToStringBuffer()
// converts field or marked segment into a stringBuffer
{
getAllLineLengths();
int jmin = isMarked() ? Math.min(jDown, jDrag) : 0;
int jmax = isMarked() ? Math.max(jDown, jDrag) : nlines-1;
StringBuffer sb = new StringBuffer((jmax-jmin+2)*IMAX);
for (int j=jmin; j<=jmax; j++)
{
sb.append(charTable[j], 0, linelen[j]);
sb.append(LF);
}
return sb;
}
private class MyKeyHandler implements KeyListener
{
public void keyPressed(KeyEvent event)
{
switch (event.getKeyCode())
{
case KeyEvent.VK_HOME:
iCaret = jCaret = 0;
break;
case KeyEvent.VK_PAGE_UP:
jCaret = Math.max(0, jCaret-VERTJUMP);
break;
case KeyEvent.VK_PAGE_DOWN:
jCaret = Math.min(JMAX-2, jCaret+VERTJUMP);
break;
case KeyEvent.VK_Z:
if (event.isControlDown() || event.isMetaDown())
swapUndo();
break;
case KeyEvent.VK_LEFT:
if (event.isControlDown() || event.isMetaDown())
narrowTable(iCaret); // narrow
else
iCaret = Math.max(0, iCaret-1);
break;
case KeyEvent.VK_RIGHT:
if (event.isControlDown() || event.isMetaDown())
widenTable(iCaret, false); // widen, no colons
else if (event.isAltDown()) // Alt Right
widenTable(iCaret, true); // widen, insert colons
else
iCaret = Math.min(IMAX-2, iCaret+1);
break;
case KeyEvent.VK_UP:
jCaret = Math.max(0, jCaret-1);
break;
case KeyEvent.VK_DOWN:
if (event.isAltDown()) // Alt + Down
{
if (event.isControlDown())
CopyFieldBottom();
else
CopyFieldDown();
}
else
jCaret = Math.min(JMAX-2, jCaret+1);
break;
case KeyEvent.VK_ENTER:
if ("T".equals(DMF.reg.getuo(UO_EDIT, 10))) // text mode
{
if (jCaret < JMAX)
{
stashForUndo();
pushDownOneLine(jCaret+1); // clear line below
int ncopy = IMAX - iCaret; // nchars to copy
System.arraycopy(charTable[jCaret], iCaret, charTable[jCaret+1], 0, ncopy);
for (int i=iCaret; i<IMAX; i++) // blank source chars
charTable[jCaret][i] = SPACE;
jCaret++;
iCaret = 0;
}
}
else // table mode, no table changes.
{
iCaret = 0;
jCaret = Math.min(JMAX-2, jCaret+1);
}
break;
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_DELETE:
stashForUndo();
if ("T".equals(DMF.reg.getuo(UO_EDIT, 10))) // text mode
{
if ((iCaret==0) && (jCaret>0)) // pull up OK
{
int istart = getOneLineLength(jCaret-1);
int iavail = IMAX - istart;
for (int k=0; k<iavail; k++) // append to above
charTable[jCaret-1][k+istart] = charTable[jCaret][k];
pullUpOneLine(jCaret); // raise lines below
jCaret--;
iCaret = istart;
}
else if (iCaret>0) // pull chars leftward
{
iCaret--;
for (int k=iCaret; k<IMAX-2; k++)
charTable[jCaret][k] = charTable[jCaret][k+1];
}
}
else if (iCaret > 0) // table mode
{
iCaret--;
charTable[jCaret][iCaret] = ' ';
}
myEJIF.setDirty(true);
if (jCaret == RULER)
getFieldInfo();
break;
case KeyEvent.VK_TAB:
if (event.isShiftDown())
iCaret = doBackTab(iCaret);
else
iCaret = 1+rulerTagPos(iCaret, period);
break;
case KeyEvent.VK_F7:
narrowTable(iCaret);
break;
case KeyEvent.VK_F8:
widenTable(iCaret, false);
break;
case KeyEvent.VK_F9:
widenTable(iCaret, true);
break;
case KeyEvent.VK_F10:
CopyFieldDown();
event.consume();
break;
}
if (iCaret < iOff)
iOff = iCaret;
if (iCaret >= iOff + iWidth-1)
iOff = Math.max(0, iCaret-iWidth+1);
if (jCaret < jOff)
jOff = jCaret;
if (jCaret >= jOff + jHeight-1)
jOff = Math.max(0, jCaret-jHeight+1);
if (vsbReference != null)
vsbReference.setValue(jOff);
if (hsbReference != null)
hsbReference.setValue(iOff);
repaint();
}
public void keyReleased(KeyEvent event)
{
}
public void keyTyped(KeyEvent event)
// Process typed chars only, lower & upper case.
// Accelerator keys are handled elsewhere.
{
DMF.nEdits++;
char c = event.getKeyChar();
int mod = event.getModifiers();
if ((c>=' ') && (c<='~')) // avoids BKSP and DEL
if ((mod==0) || (mod==java.awt.Event.SHIFT_MASK))
{
stashForUndo();
iCaret = Math.max(0, Math.min(IMAX-2, iCaret));
jCaret = Math.max(0, Math.min(JMAX-1, jCaret));
if("T".equals(DMF.reg.getuo(UO_EDIT, 10))) // text mode shove right
for (int k=IMAX-1; k>iCaret; k--)
charTable[jCaret][k] = charTable[jCaret][k-1];
charTable[jCaret][iCaret] = c;
iCaret = Math.min(IMAX-2, iCaret+1); // increment iCaret
if ((c>' ') && (jCaret+1>nlines))
nlines = jCaret+1; // helps Vscrolling
if ((c>' ') && (iCaret>maxlinelen))
maxlinelen = iCaret; // helps Hscrolling
myEJIF.setDirty(true);
}
if (jCaret == RULER)
getFieldInfo();
}
} //---end private class MyKeyHandler------------
void widenTable(int i, boolean bColons)
{
DMF.nEdits++;
getAllLineLengths();
stashForUndo();
for (int j=1; j<nlines; j++)
{
System.arraycopy(charTable[j], i, charTable[j], i+1, IMAX-i-1);
charTable[j][i] = SPACE;
}
if (bColons)
for (int j=RULER; j<nlines; j++)
charTable[j][i] = ':';
else
charTable[RULER][i] = '-';
myEJIF.setDirty(true);
getAllLineLengths();
getFieldInfo();
}
void narrowTable(int i)
{
DMF.nEdits++;
if ((i<0) || (i>IMAX-2))
return;
stashForUndo();
getAllLineLengths();
for (int j=1; j<nlines; j++)
System.arraycopy(charTable[j], i+1, charTable[j], i, IMAX-i-1);
getAllLineLengths();
getFieldInfo();
myEJIF.setDirty(true);
}
void CopyFieldDown()
/// copies the data field and its tag char.
{
DMF.nEdits++;
if ((jCaret>RULER) && (jCaret<nlines-1))
{
// stashForUndo(); // yikes! ruins the function.
int field = getWhichField(iCaret);
String s = getFieldFull(field, jCaret);
char c = getTagChar(field, jCaret);
jCaret++;
putFieldString(field, jCaret, s);
putTagChar(field, jCaret, c);
myEJIF.setDirty(true);
}
}
void CopyFieldBottom()
/// copies field and tag all the way to the bottom
{
DMF.nEdits++;
if ((jCaret>RULER) && (jCaret<nlines-1))
{
// stashForUndo(); // yikes! ruins the function.
int field = getWhichField(iCaret);
String s = getFieldFull(field, jCaret);
char c = getTagChar(field, jCaret);
for (int j=jCaret+1; j<nlines; j++)
{
putFieldString(field, j, s);
putTagChar(field, j, c);
}
myEJIF.setDirty(true);
}
}
//------------------- mouse stuff --------------------
private class MyMouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
iCaret = ((int) event.getPoint().getX())/charwidth + iOff;
iCaret = Math.max(0, Math.min(IMAX-2, iCaret));
jCaret = ((int) event.getPoint().getY())/charheight + jOff;
jCaret = Math.max(0, Math.min(JMAX-1, jCaret));
jDown = jCaret;
jDrag = -1;
repaint();
}
}
private class MyMouseMotionHandler implements MouseMotionListener
{
public void mouseMoved(MouseEvent event)
{
}
public void mouseDragged(MouseEvent event)
// Horstmann & Cornell v.1 p.308: drag beyond borders OK.
// Uses beyond-borders drag numbers to force scrolling.
// Remember to reposition the caret.
// Remember to keep caret within display area.
// Remember to update the vertical scrollbar.
{
int jPix = event.getY();
if ((jPix < 0) && (jOff > 0))
jOff--;
if ((jPix > py) && (jOff < JMAX-10))
jOff++;
jPix = Math.max(0, Math.min(py, jPix)); // anti escape
jDrag = jPix/charheight + jOff;
jDrag = Math.max(0, Math.min(JMAX-1, jDrag));
jCaret = jDrag;
if (vsbReference != null)
vsbReference.setValue(jOff); // update vertical scrollbar
repaint();
}
}
public void mouseWheelMoved(MouseWheelEvent e)
{
int notches = e.getWheelRotation();
if (notches == 0)
return;
jOff += 4*notches;
jOff = Math.max(0, Math.min(JMAX-10, jOff));
// now move the host frame's scroll button
if (vsbReference != null)
vsbReference.setValue(jOff);
repaint();
}
//---------------scrollbar management----------------
private void manageVSB() // vertical scrollbar
{
boolean bNeed = (nlines>=jHeight) || (jOff>0);
if ((myEJIF!=null) && (vsbReference==null) && bNeed)
vsbReference = myEJIF.createVSB();
/**********no no do not destroy*************
if ((myEJIF!=null) && (vsbReference!=null) && !bNeed)
vsbReference = myEJIF.destroyVSB();
*******************************************/
/// added Mar 2012, A135 making VSB track actual nlines
if ((myEJIF!=null) && (vsbReference!=null) && bNeed)
vsbReference.setMaximum(nlines);
}
private void manageHSB() // horizontal scrollbar
{
boolean bNeed = (maxlinelen>=iWidth) || (iOff>0);
if ((myEJIF!=null) && (hsbReference==null) && bNeed)
hsbReference = myEJIF.createHSB();
/*************no no do not destroy************************
if ((myEJIF!=null) && (hsbReference!=null) && !bNeed)
hsbReference = myEJIF.destroyHSB();
*******************************************************/
}
//-------------- static utilities --------------
static void beep()
{
Toolkit.getDefaultToolkit().beep();
}
static int getFontWidth(Graphics2D g2, Font f)
// Given a size: int size = 32;
// Define a font: Font font = new Font("Monospaced", Font.BOLD, size);
// Set the font: g2.setFont(font);
// Then, call this:
{
FontRenderContext frc = g2.getFontRenderContext();
return (int) f.getStringBounds("a", frc).getWidth();
}
} //-----------end EPanel class------------------------------
| StellarSoftwareBerkeley/BeamFour | Sources/EPanel.java |
247,803 | package exec;
import java.io.BufferedWriter;
import java.util.Scanner;
import java.util.Vector;
import util.DCUtil;
public class QLogger {
public static void main(String args[]) {
QLogger q = new QLogger();
try {
q.init();
q.run();
} catch (Exception e) { e.printStackTrace(); System.exit(-1); }
}
public void run() throws Exception {
BufferedWriter bw = DCUtil.openWriter("Test.txt");
Scanner scanner = new Scanner(System.in);
for (int i=0; i < qlist.size(); i++) {
System.out.println(qlist.elementAt(i));
bw.write("..............");
bw.newLine();
bw.write(qlist.elementAt(i));
bw.newLine();
long start = System.currentTimeMillis();
String input = scanner.nextLine();
long end = System.currentTimeMillis();
bw.write(input);
bw.newLine();
bw.write( String.valueOf((end-start)) );
bw.newLine();
}
bw.flush();
bw.close();
System.out.println(" All Done ");
}
public void init() {
qlist.add("Press Enter to Start");
qlist.add("What is the most frequently occurring component in 1998");
}
public Vector<String> qlist = new Vector<String>();
}
| vialab/VehicleVis | src/exec/QLogger.java |
247,805 | import java.util.HashMap;
import java.util.Map;
public class FindMostFrequently {
public static int find(String s){
String[] numberStrings = s.split(", ");
int[] intArray = new int[numberStrings.length];
for (int i = 0; i < numberStrings.length; i++) {
intArray[i] = Integer.parseInt(numberStrings[i]);
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < intArray.length; i++) {
if(map.containsKey(intArray[i])){
map.put(intArray[i], map.get(intArray[i]) + 1);
}
else{
map.put(intArray[i], 1);
}
}
int result = 0;
int maxValue = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() > maxValue){
maxValue = entry.getValue();
result = entry.getKey();
}
}
return result;
}
public static void main(String[] args) {
String s = "100, 40, 75, 75, 20, 100, 75, 50, 30, 1, 55, 75, 25, 50, 90, 80, 65, 25, 45, 100";
System.out.println(find(s));
}
}
| QuocZuong/leetcode | FindMostFrequently.java |
247,807 | package com;
/**
* This class contains common operations for data structure like array, arrayList, HashMap etc.
*
* */
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
public class ComUtil {
/**
* String Operations
* */
public static void tokenize(String line, ArrayList<String> tokens) {
StringTokenizer strTok = new StringTokenizer(line);
while (strTok.hasMoreTokens()) {
String token = strTok.nextToken();
tokens.add(token);
}
}
/**
* Print
* */
public static void print(ArrayList tokens) {
for (int i = 0; i < tokens.size(); i++) {
System.out.print(tokens.get(i) + " ");
}
System.out.print("\n");
System.out.print("\n");
}
public static void print(String[] files) {
for (int i = 0; i < files.length; i++) {
System.out.print(files[i] + " ");
}
System.out.print("\n");
}
public static void print(double[] probs, String string, String end) {
for(int i = 0; i < probs.length; i++) {
System.out.print(probs[i] + string);
}
System.out.print(end);
}
/**
* HashMap Operations
* */
public static void printHash(HashMap<String, Integer> hashMap) {
System.out.println("Print HashMap");
Set s = hashMap.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
System.out.println(m.getKey() + "\t" + m.getValue());
}
}
public static ArrayList<String> getHashMap(HashMap<String, String> hm) {
ArrayList<String> a = new ArrayList<String>();
Set s = hm.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
a.add(m.getKey() + "\t" + m.getValue());
}
return a;
}
public static ArrayList<String> getHashMap2(HashMap<String, Integer> hm) {
ArrayList<String> a = new ArrayList<String>();
Set s = hm.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
a.add(m.getKey() + "\t" + m.getValue());
}
return a;
}
public static String getKeysFromValue(HashMap<Integer, String> hm,
String value) {
Set s = hm.entrySet();
// Move next key and value of HashMap by iterator
Iterator it = s.iterator();
while (it.hasNext()) {
// key=value separator this by Map.Entry to get key and value
Map.Entry m = (Map.Entry) it.next();
if (m.getValue().equals(value))
return m.getKey() + "";
}
System.err.println("Error, can't find the data in Hashmap!");
return null;
}
public static void readHash(String type_map, HashMap<String, String> typeMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
FileUtil.readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
ComUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!typeMap.containsKey(tokens.get(0)))
typeMap.put(tokens.get(0), tokens.get(1));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
public static void readHash2(String type_map,
HashMap<String, Integer> hashMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
FileUtil.readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
ComUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!hashMap.containsKey(tokens.get(0)))
hashMap.put(tokens.get(0),
new Integer(tokens.get(1)));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
public static void readHash3(String type_map,
HashMap<String, Double> hashMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
FileUtil.readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
ComUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!hashMap.containsKey(tokens.get(0)))
hashMap.put(tokens.get(0),
new Double(tokens.get(1)));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
public static double readHashTopValue(HashMap<String, Integer> scores, int k) {
List list = new LinkedList(scores.entrySet());
int count = 0;
int value = 0;
double res = 0;
for (Iterator it = list.iterator(); count < k && it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
value = (Integer) entry.getValue();
res += (double) value * Math.log(2) / Math.log(count + 2);
// res += (Integer) entry.getValue();
count++;
}
return res;
}
/**
* Frequently used functions
* */
static public int count(String a, String contains) {
int i = 0;
int count = 0;
while (a.contains(contains)) {
i = a.indexOf(contains);
a = a.substring(0, i)
+ a.substring(i + contains.length(), a.length());
count++;
}
return count;
}
@SuppressWarnings("unchecked")
public static HashMap<?,?> sortByValue(HashMap<?,?> map, final int flag) {
// flag = 0 decreasing order otherwise increasing
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
if(flag == 0 )
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
else
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
HashMap result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
public static double getSumValue(HashMap<String, Double> map) {
Double count = 0.0D;
List list = new LinkedList(map.entrySet());
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
count += map.get(entry.getKey());
}
return count;
}
public static int getFrequentElement(int[] bcp) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> count = new ArrayList<Integer>();
ArrayList<Integer> uniId = new ArrayList<Integer>();
int id = 0;
for (int col = 0; col < bcp.length; col++) {
// System.out.print(bcp[col] + "\t");
int no = 0;
if (!map.containsKey(bcp[col])) {
map.put(bcp[col], id++);
count.add(1);
uniId.add(bcp[col]);
} else {
no = map.get(bcp[col]);
count.set(no, count.get(no) + 1);
}
}
int maximum = Integer.MIN_VALUE;
int maxId = Integer.MIN_VALUE;
for (int i = 0; i < count.size(); i++) {
// System.out.print(uniId.get(i) + ":" + count.get(i) + ",\t");
if (maximum < count.get(i)) {
maximum = count.get(i);
maxId = uniId.get(i);
}
}
// System.out.println();
map.clear();
uniId.clear();
count.clear();
return maxId;
}
public static void getFrequentElement(int[][] bcp, int[] res, char flag) {
if (flag == 'r') {
for (int row = 0; row < bcp.length; row++) {
res[row] = getFrequentElement(bcp[row]);
}
} else {
int colL = bcp[0].length;
int[] column = new int[bcp.length];
for (int col = 0; col < colL; col++) {
for (int row = 0; row < bcp.length; row++) {
column[row] = bcp[row][col];
}
res[col] = getFrequentElement(column);
}
}
}
public static short getFrequentElement(short[] bcp) {
HashMap<Short, Short> map = new HashMap<Short, Short>();
ArrayList<Short> count = new ArrayList<Short>();
ArrayList<Short> uniId = new ArrayList<Short>();
short id = 0;
for (short col = 0; col < bcp.length; col++) {
// System.out.print(bcp[col] + "\t");
short no = 0;
if (!map.containsKey(bcp[col])) {
map.put(bcp[col], id++);
count.add((short) 1);
uniId.add(bcp[col]);
} else {
no = map.get(bcp[col]);
count.set(no, (short) (count.get(no) + 1));
}
}
short maximum = Short.MIN_VALUE;
short maxId = Short.MIN_VALUE;
for (int i = 0; i < count.size(); i++) {
// System.out.print(uniId.get(i) + ":" + count.get(i) + ",\t");
if (maximum < count.get(i)) {
maximum = count.get(i);
maxId = uniId.get(i);
}
}
// System.out.println();
map.clear();
uniId.clear();
count.clear();
return maxId;
}
public static boolean getFrequentElementBinary(int[] sample) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> count = new ArrayList<Integer>();
ArrayList<Integer> uniId = new ArrayList<Integer>();
int id = 0;
for (int col = 0; col < sample.length; col++) {
// System.out.print(bcp[col] + "\t");
int no = 0;
if (!map.containsKey(sample[col])) {
map.put(sample[col], id++);
count.add(1);
uniId.add(sample[col]);
} else {
no = map.get(sample[col]);
count.set(no, count.get(no) + 1);
}
}
int maximum = Integer.MIN_VALUE;
int maxId = Integer.MIN_VALUE;
for (int i = 0; i < count.size(); i++) {
// System.out.print(uniId.get(i) + ":" + count.get(i) + ",\t");
if (maximum < count.get(i)) {
maximum = count.get(i);
maxId = uniId.get(i);
}
}
// System.out.println();
map.clear();
uniId.clear();
count.clear();
if(maxId == 1)
return true;
else
return false;
}
public static int[] CountElmt(ArrayList<Integer> newScores1,
ArrayList<Integer> scores) {
int a[] = new int[scores.size()];
for (int i = 0; i < scores.size(); i++) {
a[i] = 0;
}
for (int i = 0; i < newScores1.size(); i++) {
int value = newScores1.get(i);
int pos = scores.indexOf(value);
a[pos]++;
}
return a;
}
public static int countCommElmts(ArrayList<Integer> newScores1,
ArrayList<Integer> newScores2) {
int count = 0;
for (int i = 0; i < newScores1.size(); i++) {
if (newScores1.get(i) == newScores2.get(i))
count++;
}
return count;
}
public static void uniqe(int[] words, ArrayList<Integer> tempUniqueWords,
ArrayList<Integer> tempCounts) {
for (int i = 0; i < words.length; i++) {
if (tempUniqueWords.contains(words[i])) {
int index = tempUniqueWords.indexOf(words[i]);
tempCounts.set(index, tempCounts.get(index) + 1);
} else {
tempUniqueWords.add(words[i]);
tempCounts.add(1);
}
}
}
public static void uniqe(ArrayList<Integer> items) {
// add elements to al, including duplicates
HashSet<Integer> hs = new HashSet<Integer>();
hs.addAll(items);
items.clear();
items.addAll(hs);
}
public static void getTop(float[] array, ArrayList<Integer> rankList, int i) {
rankList.clear();
int index = 0;
HashSet<Integer> scanned = new HashSet<Integer>();
float max = Float.MIN_VALUE;
for (int m = 0; m < i && m < array.length; m++) {
boolean flag = false;
max = Float.MIN_VALUE;
for (int no = 0; no < array.length; no++) {
if (!scanned.contains(no) && array[no] >= max) {
index = no;
max = array[no];
flag = true;
}
}
if(flag) { // found value
scanned.add(index);
rankList.add(index);
// rankProbs.add(array[index]);
}
//System.out.println(m + "\t" + index);
}
}
public static void getTop(float[] array, ArrayList<Integer> rankList,
ArrayList<Float> rankProbs, int i) {
// clear
rankList.clear();
rankProbs.clear();
//
int index = 0;
int count = 0;
HashSet<Integer> scanned = new HashSet<Integer>();
float max = Float.MIN_VALUE;
for (int m = 0; m < i && m < array.length; m++) {
boolean flag = false;
max = Float.MIN_VALUE;
for (int no = 0; no < array.length; no++) {
if (array[no] >= max && !scanned.contains(no)) {
index = no;
max = array[no];
flag = true;
}
}
if(flag) { // found value
scanned.add(index);
rankList.add(index);
rankProbs.add(array[index]);
}
//System.out.println(m + "\t" + index);
}
}
public static void getTopNZ(float[] array, int[] counts,
ArrayList<Integer> rankList, ArrayList<Float> rankProbs, int i, int threshold) {
// clear
rankList.clear();
rankProbs.clear();
//
int index = 0;
float max = Float.MIN_VALUE;
for (int m = 0; m < i && m < array.length; m++) {
boolean flag = false;
max = Float.MIN_VALUE;
for (int no = 0; no < array.length; no++) {
if(counts[no] >= threshold) {
if (array[no] >= max && !rankList.contains(no)) {
index = no;
max = array[no];
flag = true;
}
}
}
if(flag) { // found value
rankList.add(index);
// rankProbs.add(array[index]);
rankProbs.add(counts[index] + 0.0f);
}
//System.out.println(m + "\t" + index);
}
}
//yl: roulette sampling
//input is an array of probability and its length
//output is the sampled value
public static int sample(double[] probs, int T) {
// roulette sampling
double []pt = new double[T];
pt[0] = probs[0];
for (int i = 1; i < T; i++) {
pt[i] = probs[i] + pt[i-1];
}
double rouletter = (double) (Math.random() * pt[T - 1]);
short sample = 0;
for (sample = 0; sample < T; sample++) {
if (pt[sample] > rouletter)
break;
}
if(sample < 0 | sample >= T) {
ComUtil.print(probs, "\t", "\n");
System.out.println("Sampling error!");
System.exit(0);
}
return sample;
}
} | yangliuy/NeuralResponseRanking | retrieval/src/com/ComUtil.java |
247,808 | /**
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.workgroup.util;
import java.util.*;
/**
* Utility methods frequently used by data classes and design-time
* classes.
*/
public final class ModelUtil {
private ModelUtil() {
// Prevents instantiation.
}
/**
* This is a utility method that compares two objects when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>o1</CODE> and <CODE>o2</CODE> are the same object
* according to the <CODE>==</CODE> operator, return
* <CODE>true</CODE>.
* <LI>Otherwise, if either <CODE>o1</CODE> or <CODE>o2</CODE> is
* <CODE>null</CODE>, return <CODE>false</CODE>.
* <LI>Otherwise, return <CODE>o1.equals(o2)</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areDifferent(Object, Object)} method.<P>
* <p/>
* For array types, one of the <CODE>equals</CODE> methods in
* {@link java.util.Arrays} should be used instead of this method.
* Note that arrays with more than one dimension will require some
* custom code in order to implement <CODE>equals</CODE> properly.
*/
public static final boolean areEqual(Object o1, Object o2) {
if (o1 == o2) {
return true;
} else if (o1 == null || o2 == null) {
return false;
} else {
return o1.equals(o2);
}
}
/**
* This is a utility method that compares two Booleans when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>b1</CODE> and <CODE>b2</CODE> are both TRUE or
* neither <CODE>b1</CODE> nor <CODE>b2</CODE> is TRUE,
* return <CODE>true</CODE>.
* <LI>Otherwise, return <CODE>false</CODE>.
* </OL>
* <p/>
*/
public static final boolean areBooleansEqual(Boolean b1, Boolean b2) {
// !jwetherb treat NULL the same as Boolean.FALSE
return (b1 == Boolean.TRUE && b2 == Boolean.TRUE) || (b1 != Boolean.TRUE && b2 != Boolean.TRUE);
}
/**
* This is a utility method that compares two objects when one or
* both of the objects might be <CODE>null</CODE>. The result
* returned by this method is determined as follows:
* <OL>
* <LI>If <CODE>o1</CODE> and <CODE>o2</CODE> are the same object
* according to the <CODE>==</CODE> operator, return
* <CODE>false</CODE>.
* <LI>Otherwise, if either <CODE>o1</CODE> or <CODE>o2</CODE> is
* <CODE>null</CODE>, return <CODE>true</CODE>.
* <LI>Otherwise, return <CODE>!o1.equals(o2)</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areEqual(Object, Object)} method.<P>
* <p/>
* For array types, one of the <CODE>equals</CODE> methods in
* {@link java.util.Arrays} should be used instead of this method.
* Note that arrays with more than one dimension will require some
* custom code in order to implement <CODE>equals</CODE> properly.
*/
public static final boolean areDifferent(Object o1, Object o2) {
return !areEqual(o1, o2);
}
/**
* This is a utility method that compares two Booleans when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>b1</CODE> and <CODE>b2</CODE> are both TRUE or
* neither <CODE>b1</CODE> nor <CODE>b2</CODE> is TRUE,
* return <CODE>false</CODE>.
* <LI>Otherwise, return <CODE>true</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areBooleansEqual(Boolean, Boolean)} method.<P>
*/
public static final boolean areBooleansDifferent(Boolean b1, Boolean b2) {
return !areBooleansEqual(b1, b2);
}
/**
* Returns <CODE>true</CODE> if the specified array is not null
* and contains a non-null element. Returns <CODE>false</CODE>
* if the array is null or if all the array elements are null.
*/
public static final boolean hasNonNullElement(Object[] array) {
if (array != null) {
final int n = array.length;
for (int i = 0; i < n; i++) {
if (array[i] != null) {
return true;
}
}
}
return false;
}
/**
* Returns a single string that is the concatenation of all the
* strings in the specified string array. A single space is
* put between each string array element. Null array elements
* are skipped. If the array itself is null, the empty string
* is returned. This method is guaranteed to return a non-null
* value, if no expections are thrown.
*/
public static final String concat(String[] strs) {
//NOTRANS
return concat(strs, " ");
}
/**
* Returns a single string that is the concatenation of all the
* strings in the specified string array. The strings are separated
* by the specified delimiter. Null array elements are skipped. If
* the array itself is null, the empty string is returned. This
* method is guaranteed to return a non-null value, if no expections
* are thrown.
*/
public static final String concat(String[] strs, String delim) {
if (strs != null) {
final StringBuilder buf = new StringBuilder();
final int n = strs.length;
for (int i = 0; i < n; i++) {
final String str = strs[i];
if (str != null) {
buf.append(str).append(delim);
}
}
final int length = buf.length();
if (length > 0) {
// Trim trailing space.
buf.setLength(length - 1);
}
return buf.toString();
} else {
// NOTRANS
return "";
}
}
/**
* Returns <CODE>true</CODE> if the specified {@link String} is not
* <CODE>null</CODE> and has a length greater than zero. This is
* a very frequently occurring check.
*/
public static final boolean hasLength(String s) {
return (s != null && s.length() > 0);
}
/**
* Returns <CODE>null</CODE> if the specified string is empty or
* <CODE>null</CODE>. Otherwise the string itself is returned.
*/
public static final String nullifyIfEmpty(String s) {
return ModelUtil.hasLength(s) ? s : null;
}
/**
* Returns <CODE>null</CODE> if the specified object is null
* or if its <CODE>toString()</CODE> representation is empty.
* Otherwise, the <CODE>toString()</CODE> representation of the
* object itself is returned.
*/
public static final String nullifyingToString(Object o) {
return o != null ? nullifyIfEmpty(o.toString()) : null;
}
/**
* Determines if a string has been changed.
*
* @param oldString is the initial value of the String
* @param newString is the new value of the String
* @return true If both oldString and newString are null or if they are
* both not null and equal to each other. Otherwise returns false.
*/
public static boolean hasStringChanged(String oldString, String newString) {
if (oldString == null && newString == null) {
return false;
} else if ((oldString == null && newString != null) || (oldString != null && newString == null)) {
return true;
} else {
return !oldString.equals(newString);
}
}
public static String getTimeFromLong(long diff) {
final String HOURS = "h";
final String MINUTES = "min";
final String SECONDS = "sec";
final long MS_IN_A_DAY = 1000 * 60 * 60 * 24;
final long MS_IN_AN_HOUR = 1000 * 60 * 60;
final long MS_IN_A_MINUTE = 1000 * 60;
final long MS_IN_A_SECOND = 1000;
diff = diff % MS_IN_A_DAY;
long numHours = diff / MS_IN_AN_HOUR;
diff = diff % MS_IN_AN_HOUR;
long numMinutes = diff / MS_IN_A_MINUTE;
diff = diff % MS_IN_A_MINUTE;
long numSeconds = diff / MS_IN_A_SECOND;
diff = diff % MS_IN_A_SECOND;
StringBuilder buf = new StringBuilder();
if (numHours > 0) {
buf.append(numHours + " " + HOURS + ", ");
}
if (numMinutes > 0) {
buf.append(numMinutes + " " + MINUTES + ", ");
}
buf.append(numSeconds + " " + SECONDS);
String result = buf.toString();
return result;
}
/**
* Build a List of all elements in an Iterator.
*/
public static <T> List<T> iteratorAsList(Iterator<T> i) {
ArrayList<T> list = new ArrayList<T>(10);
while (i.hasNext()) {
list.add(i.next());
}
return list;
}
/**
* Creates an Iterator that is the reverse of a ListIterator.
*/
public static <T> Iterator<T> reverseListIterator(ListIterator<T> i) {
return new ReverseListIterator<T>(i);
}
}
/**
* An Iterator that is the reverse of a ListIterator.
*/
class ReverseListIterator<T> implements Iterator<T> {
private ListIterator<T> _i;
ReverseListIterator(ListIterator<T> i) {
_i = i;
while (_i.hasNext()) _i.next();
}
public boolean hasNext() {
return _i.hasPrevious();
}
public T next() {
return _i.previous();
}
public void remove() {
_i.remove();
}
}
| masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018 | Corpus/ecf/1184.java |
247,809 | /**
* Manager for Camp Site
* @author Jacob Hammond, Jordan fowler, Lex Whalen, Tze-Chen Lin
* CSCE 247
* October 28, 2022
*/
import java.util.ArrayList;
import java.util.UUID;
public class CampSiteManager{
private ThemeManager themeManager;
private int year;
private String startMonth;
private UUID themeId;
private String name;
private String address;
private ArrayList<FAQ> frequentlyAskedQuestions;
private static CampSiteManager campSiteManager;
// managers
PersonManager personManager;
ReviewManager reviewManager;
CabinManager cabinManager;
/**
* Constructor for CampsiteManager
* @param name is person's name
* @param address is person's address
* @param year is person's year
* @param startMonth
* @param themeManager
*/
private CampSiteManager(String name, String address, int year,String startMonth,ThemeManager themeManager) {
this.personManager = new PersonManager(FileIO.getAdmins(),FileIO.getGuardians(),FileIO.getDependents(),FileIO.getEmergencyContacts());
this.reviewManager = new ReviewManager(FileIO.getReviews());
this.cabinManager = new CabinManager(FileIO.getCabins());
this.name = name;
this.address = address;
this.frequentlyAskedQuestions =FileIO.getFaqs();
this.year = year;
this.startMonth = startMonth;
this.themeManager=themeManager;
}
public boolean isEqual(CampSiteManager c) {
if(!c.getName().equals(this.name)) return false;
if(!c.getAddress().equals(this.address)) return false;
if(c.getYear() != (this.year)) return false;
if(!c.getStartMonth().equals(this.startMonth)) return false;
return true;
}
/**
* Creates instance of CampSiteManager
* @return CampSiteManager
*/
public static CampSiteManager getInstance() {
if(campSiteManager == null){
campSiteManager = FileIO.getCamp();
return campSiteManager;
}
return campSiteManager;
}
/**
*
* @param name
* @param address
* @param year
* @param startMonth
* @param themeManager
* @return
*/
public static CampSiteManager getInstance(String name, String address, int year,String startMonth, ThemeManager themeManager) {
//To-Do
if(campSiteManager == null){
campSiteManager = new CampSiteManager(name, address, year,startMonth,themeManager);
return campSiteManager;
}
return campSiteManager;
}
/**
* Gives name
* @return name
*/
public String getName() {
return name;
}
/**
* Set's name
* @param name is the name
*/
public void setName(String name){
this.name = name;
}
/**
* Get's address
* @return address
*/
public String getAddress() {
return address;
}
/**
* Get's price per camper
* @return price "7"
*/
public int getPricePerCamper() {
return 7;
}
/**
* Get's current theme ID
* @return theme ID
*/
public UUID getCurrentThemeID() {
return this.themeManager.getId();
}
/**
* Allows viewing of Coordinators
*/
public void viewCoordinators() {
this.personManager.viewCoordinators();
}
/**
* Prints information about campsite
*/
public String toString() {
String out = "Cabin: " + this.name +"\n";
out += "Year: " + this.year + "\n";
out += "Rating: " + this.getAvgRating() +"\n";
out += "Start month: "+ this.getStartMonth() +"\n";
out += "Themes: "+"\n";
out += this.themeManager.toString();
return out;
}
/**
* Allows viewing of Admins
*/
public void viewAdmins() {
this.personManager.viewAdmins();;
}
/**
* Allows viewing of cabins
*/
public void viewCabins() {
this.cabinManager.viewCabins();
}
/**
* Allows viewing cabins by coordinator
* @param coordinator
*/
public void viewCabinsByCoordinator(Dependent coordinator){
this.cabinManager.viewCabinsByCoordinator(coordinator);
}
/**
* Allows viewing of cabin schedules based on coordinator
* @param coordinator is the coordinator of the cabins
*/
public void viewCabinSchedulesByCoordinator(Dependent coordinator){
this.cabinManager.viewCabinSchedulesByCoordinator(coordinator);
}
/**
* View the cabin coordinators at a specific cabin
* @param cabinID
*/
public void viewCabinCoordinators(String cabinID) {
if(!this.cabinManager.viewCabinCoordinators(cabinID)){
System.out.println("A cabin with that ID cannot be found.");
}
}
/**
* Checks cabins for dependents
* @param g is the guardian
* @return true or false
*/
public boolean checkCabinsForDependents(Guardian g){
return this.cabinManager.checkCabinsForDependents(g);
}
/**
* Gets cabin by index
* @param index is the index
* @return the Cabin
*/
public Cabin getCabinByIndex(int index){
return this.cabinManager.getCabinByIndex(index);
}
/**
* Adds camper to cabin
* @param camper is camper to be added
* @param cabin is the cabin where camper is added
* @return true/false
*/
public boolean addCamperToCabin(Dependent camper,Cabin cabin) {
return this.cabinManager.addCamperToCabin(camper,cabin);
}
/**
* View all reviews
*/
public void viewAllReviews(){
this.reviewManager.viewAllReviews();
}
/**
* view reviews by author
* @param author is author of review
*/
public void viewReviewsByAuthor(String author) {
this.reviewManager.viewReviewsByAuthor(author);
}
/**
* view reviews by rating
* @param rating is the rating
*/
public void viewReviewsByRating(int rating) {
this.reviewManager.viewReviewsByRating(rating);
}
/**
* Add reviews
* @param authorFullName are author
* @param rating is the rating
* @param title is the title
* @param body is the body
*/
public void addReview(String authorFullName, int rating,String title, String body){
this.reviewManager.addReview(authorFullName, rating,title,body);
}
/**
* Allows for guardian registration
* @param firstName is first name
* @param lastName is last name
* @param birthDate birth day
* @param username is username
* @param password is password
* @param email is email
* @param phone is phone
* @param address is address
* @return Guardian
*/
public Guardian registerGuardian(String firstName, String lastName, String birthDate, String username, String password, String email, String phone,String address) {
return this.personManager.registerGuardian(firstName, lastName, birthDate, username, password, email, phone,address) ;
}
/**
* Remove Dependents
* @param g is the guardian
* @param dept is the dependent
* @return true/false
*/
public boolean removeDependent(Guardian g, Dependent dept) {
return this.personManager.removeDependent(g,dept);
}
/**
* Allows for admin registration
* @param admin is administrator
* @return CampAdmin
*/
public CampAdmin registerAdmin(CampAdmin admin) {
return this.personManager.registerAdmin(admin);
}
/**
* Allows for Coordinator registration
* @param firstName is the first name
* @param lastName is the last name
* @param username is the user name
* @param password is the password
* @param birthDate is the birth day
* @param phone is the phone number
* @param email is the email
* @return is a dependent
*/
public Dependent registerCoordinator(String firstName, String lastName, String username, String password, String birthDate, String phone, String email) {
return this.personManager.registerCoordinator(firstName, lastName, username, password, birthDate, phone, email);
}
/**
* Allows for viewing of dependents from guardian ID
* @param guardianId is the guardian ID
* @return true/false
*/
public boolean viewDependentsFromGuardian(UUID guardianId){
Guardian g = this.personManager.getGuardianById(guardianId);
if(g!=null){
g.viewDependents();
return true;
}
return false;
}
/**
* View Cabin Couns
* @param cabinIndex is cabin index
* @return true/false
*/
public boolean viewCabinCouncelors(int cabinIndex) {
Cabin cabin = this.cabinManager.getCabinByIndex(cabinIndex);
if(cabin != null){
System.out.println("Cabin: " + cabin.getCabinName() + "'s councelors\n");
cabin.viewCabinCouncelors();
return true;
}
return false;
}
/**
* Allows for dependent to get added
* @param guardianId is ID
* @param firstName is first name
* @param lastName is last name
* @param birthDate is birth day
* @param address is address
* @param medNotes are med notes
* @param ems is ems info
*/
public void addDependent(UUID guardianId,String firstName, String lastName, String birthDate, String address,ArrayList<String> medNotes, ArrayList<EmergencyContact> ems) {
this.personManager.addDependent(guardianId, firstName, lastName, birthDate, address,medNotes,ems);
}
/**
* Allows for written reviews
* @param firstName is the author first name
* @param lastName is the last name
* @param rating is the rating
* @param title is the title of review
* @param text is the review text
*/
public void writeReview(String firstName,String lastName,int rating, String title, String text) {
this.reviewManager.addReview(firstName + " " + lastName,rating,title,text);
}
/**
* Removes Reviews
* @param author is the author
* @param title is the title
*/
public void removeReview(Guardian author, String title) {
if(!this.reviewManager.removeReview(title, author)){
System.out.println("Cannot remove review. Check the title or the permissions.\n");
return;
}
System.out.println("Review successfully removed.\n");
}
/**
* View Dependents
* @param id is the UUID
* @return true/false
*/
public boolean viewDependent(String id) {
UUID uuid = UUID.fromString(id);
Dependent dep = this.personManager.getDependentById(uuid);
if(dep!=null){
System.out.println(dep);
return true;
}
return false;
}
/**
* View Contact Info
* @param id is UUID
* @return true/false
*/
public boolean viewContactInformation(String id) {
UUID uuid = UUID.fromString(id);
Dependent dep = this.personManager.getDependentById(uuid);
if(dep!=null){
System.out.println("Contacts for: " + dep.getFullName());
dep.viewEmergencyContacts();
}
//To-Do
return false;
}
/**
* Allows guardina to login
* @param username is usernmae
* @param password is password
* @return Guardian
*/
public Guardian loginGuardian(String username, String password){
return this.personManager.loginGuardian(username, password);
}
/**
* Allows dependent to login
* @param username is usernmae
* @param password is password
* @return dependent
*/
public Dependent loginDependent(String username, String password){
return this.personManager.loginDependent(username,password);
}
/**
* Allow admin to login
* @param username is username
* @param password is password
* @return CampAdmin
*/
public CampAdmin loginAdmin(String username, String password){
return this.personManager.loginAdmin(username,password);
}
/**
* Allows logging out
* @param username is username
* @param password is password
* @return true/false
*/
public boolean logout(String username, String password) {
return this.personManager.logout(username,password);
}
/**
* View Camp
*/
public void viewCamp(){
System.out.println(this.toString());
}
/**
* Checks if guardian has dependents
* @param g is guardian
* @return true/false
*/
public boolean guardianHasDependents(Guardian g){
return this.personManager.guardianHasDependents(g);
}
/**
* checks if guardian has campers registered
* @param g is guardian
* @return true/false
*/
public boolean guardianHasCampersRegistered(Guardian g){
return this.cabinManager.guardianHasCampersRegistered(g);
}
/**
* chekcs if guardian has registered cabin
* @param g is Guardian
*/
public void viewGuardianRegisteredCabins(Guardian g){
// view the cabins that you have registered
this.cabinManager.viewGuardianRegisteredCabins(g);
}
/**
* View Cabin names
*/
public void viewCabinNames(){
this.cabinManager.viewCabinNames();
}
/**
* View Cabin by Index
* @param index is the cabin index
*/
public void viewCabinByIndex(int index){
this.cabinManager.viewCabinByIndex(index);
}
/**
* View camper names by guardian
* @param guardianId is gurdian UUID
*/
public void viewCamperNamesByGuardian(UUID guardianId){
this.personManager.viewCamperNamesByGuardian(guardianId);
}
/**
* collects dependent by name
* @param guardianId is UUID
* @param firstName is first name
* @param lastName is last name
* @return dependent being searched for
*/
public Dependent getDependentByName(UUID guardianId,String firstName, String lastName){
return this.personManager.getDependentByName(guardianId,firstName, lastName);
}
/**
* get cabin count
* @return number of cabins
*/
public int getCabinCount(){
return this.cabinManager.getCabinCount();
}
/**
* View emergency contacts
* @param dep is the dependent
*/
public void viewEmergencyContacts(Dependent dep){
this.personManager.viewEmergencyContacts(dep) ;
}
/**
* Get the year
* @return year
*/
public int getYear(){
return this.year;
}
/**
* Sets year
* @param year is year
*/
public void setYear(int year){
this.year = year;
}
/**
* Get avg rating
* @return the rating
*/
public double getAvgRating(){
return this.reviewManager.getAvgRating();
}
/**
* Get Camp rosters
* @param coordinator is coordinator we want roster from
* @return roster
*/
public String getCampRosters(Dependent coordinator){
return this.cabinManager.getCampRosters(coordinator);
}
/**
* Get dependent over cabins
* @param user is dependent
* @return list of cabins containing dependent
*/
public ArrayList<Cabin> getDependentCabins(Dependent user){
return this.cabinManager.getDependentCabins(user);
}
/**
* Get count based on dependent
* @param user is the dependent
* @return number of cabins
*/
public int getCabinCountByDependent(Dependent user){
return this.cabinManager.getCabinCountByDependent(user);
}
/**
* Gets cabin roster
* @param c is the cabim
* @return the roster for that cabin
*/
public String getCabinRoster(Cabin c){
return this.cabinManager.getCabinRoster(c);
}
/**
* Sets the theme
* @param t is the theme
*/
public void setThemeManager(ThemeManager t){
this.themeId= t.getId();
this.themeManager = t;
}
/**
* Resets the camp
*/
public void resetCamp(){
this.frequentlyAskedQuestions = new ArrayList<FAQ>();
this.name = "";
this.year = -1;
this.address = "";
this.personManager.reset();
this.reviewManager = new ReviewManager();
this.cabinManager = new CabinManager();
}
/**
* Setter for cabin manger
* @param cabinManager is the cabin manager for this camp
*/
public void setCabinManager(CabinManager cabinManager){
this.cabinManager = cabinManager;
}
/**
* Setter for address
* @param address is the address
*/
public void setAddress(String address){
this.address = address;
}
/**
* Setter for the starting month
* @param month is the start month
*/
public void setStartMonth(String month){
this.startMonth = month;
}
/**
* Gets the starting month
* @return the starting month
*/
public String getStartMonth(){
return this.startMonth;
}
/**
* Getter for Session count
* @return the number os sessions
*/
public int getSessionCount(){
return this.themeManager.getThemeCount();
}
/**
* Allows for viewing of the themes
*/
public void viewThemes(){
this.themeManager.viewThemes();
}
/**
* Allows for viewing of the cabin sessions
* @param cabinIndex is the index of the cabin that you want to view
* @param sessionIndex is the session you want to look at it
*/
public void viewIndexCabinSession(int cabinIndex,int sessionIndex){
this.cabinManager.viewIndexCabinSession(cabinIndex, sessionIndex);
}
/**
* Saves people, themes, reviews, cabins, and schedules and writes to file
*/
public void save(){
// saves all of the current data
// 1. Save People
this.personManager.save();
// 2. Save Themes
this.themeManager.save();
// 3. Save Reviews
this.reviewManager.save();
// 4. Save Cabins & Schedules
this.cabinManager.save();
//5. save camp
FileIO.writeCamp(this.campSiteManager);
}
}
| jah22/CampingApp | CampSiteManager.java |
247,810 | // LFU (Least Frequently Used) is a famous cache eviction algorithm.
// For a cache with capacity k, if the cache is full and need to evict a key in it, the key with the lease frequently used will be kicked out.
// Implement set and get method for LFU cache.
// Example
// Given capacity=3
// set(2,2)
// set(1,1)
// get(2)
// >> 2
// get(1)
// >> 1
// get(2)
// >> 2
// set(3,3)
// set(4,4)
// get(3)
// >> -1
// get(2)
// >> 2
// get(1)
// >> 1
// get(4)
// >> 4
public class LFUCache {
private final Map<Integer, CacheNode> cache;
private final LinkedHashSet[] frequencyList;
private int lowestFrequency;
private int maxFrequency;
private final int maxCacheSize;
// @param capacity, an integer
public LFUCache(int capacity) {
// Write your code here
this.cache = new HashMap<Integer, CacheNode>(capacity);
this.frequencyList = new LinkedHashSet[capacity * 2];
this.lowestFrequency = 0;
this.maxFrequency = capacity * 2 - 1;
this.maxCacheSize = capacity;
initFrequencyList();
}
// @param key, an integer
// @param value, an integer
// @return nothing
public void set(int key, int value) {
// Write your code here
CacheNode currentNode = cache.get(key);
if (currentNode == null) {
if (cache.size() == maxCacheSize) {
doEviction();
}
LinkedHashSet<CacheNode> nodes = frequencyList[0];
currentNode = new CacheNode(key, value, 0);
nodes.add(currentNode);
cache.put(key, currentNode);
lowestFrequency = 0;
} else {
currentNode.v = value;
}
addFrequency(currentNode);
}
public int get(int key) {
// Write your code here
CacheNode currentNode = cache.get(key);
if (currentNode != null) {
addFrequency(currentNode);
return currentNode.v;
} else {
return -1;
}
}
public void addFrequency(CacheNode currentNode) {
int currentFrequency = currentNode.frequency;
if (currentFrequency < maxFrequency) {
int nextFrequency = currentFrequency + 1;
LinkedHashSet<CacheNode> currentNodes = frequencyList[currentFrequency];
LinkedHashSet<CacheNode> newNodes = frequencyList[nextFrequency];
moveToNextFrequency(currentNode, nextFrequency, currentNodes, newNodes);
cache.put(currentNode.k, currentNode);
if (lowestFrequency == currentFrequency && currentNodes.isEmpty()) {
lowestFrequency = nextFrequency;
}
} else {
// Hybrid with LRU: put most recently accessed ahead of others:
LinkedHashSet<CacheNode> nodes = frequencyList[currentFrequency];
nodes.remove(currentNode);
nodes.add(currentNode);
}
}
public int remove(int key) {
CacheNode currentNode = cache.remove(key);
if (currentNode != null) {
LinkedHashSet<CacheNode> nodes = frequencyList[currentNode.frequency];
nodes.remove(currentNode);
if (lowestFrequency == currentNode.frequency) {
findNextLowestFrequency();
}
return currentNode.v;
} else {
return -1;
}
}
public int frequencyOf(int key) {
CacheNode node = cache.get(key);
if (node != null) {
return node.frequency + 1;
} else {
return 0;
}
}
public void clear() {
for (int i = 0; i <= maxFrequency; i++) {
frequencyList[i].clear();
}
cache.clear();
lowestFrequency = 0;
}
public int size() {
return cache.size();
}
public boolean isEmpty() {
return this.cache.isEmpty();
}
public boolean containsKey(int key) {
return this.cache.containsKey(key);
}
private void initFrequencyList() {
for (int i = 0; i <= maxFrequency; i++) {
frequencyList[i] = new LinkedHashSet<CacheNode>();
}
}
private void doEviction() {
int currentlyDeleted = 0;
double target = 1; // just one
while (currentlyDeleted < target) {
LinkedHashSet<CacheNode> nodes = frequencyList[lowestFrequency];
if (nodes.isEmpty()) {
break;
} else {
Iterator<CacheNode> it = nodes.iterator();
while (it.hasNext() && currentlyDeleted++ < target) {
CacheNode node = it.next();
it.remove();
cache.remove(node.k);
}
if (!it.hasNext()) {
findNextLowestFrequency();
}
}
}
}
private void moveToNextFrequency(CacheNode currentNode, int nextFrequency,
LinkedHashSet<CacheNode> currentNodes,
LinkedHashSet<CacheNode> newNodes) {
currentNodes.remove(currentNode);
newNodes.add(currentNode);
currentNode.frequency = nextFrequency;
}
private void findNextLowestFrequency() {
while (lowestFrequency <= maxFrequency && frequencyList[lowestFrequency].isEmpty()) {
lowestFrequency++;
}
if (lowestFrequency > maxFrequency) {
lowestFrequency = 0;
}
}
private class CacheNode {
public final int k;
public int v;
public int frequency;
public CacheNode(int k, int v, int frequency) {
this.k = k;
this.v = v;
this.frequency = frequency;
}
}
}
/*
Not worth looking at least for now
*/ | chendddong/LintCode | 24. LFU Cache.java |
247,811 | package examples;
import simbad.gui.Simbad;
import simbad.sim.*;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
/**
Derivate your own code from this example.
*/
public class Example1 {
/** Describe the robot */
static public class Robot extends Agent {
RangeSensorBelt sonars;
CameraSensor camera;
public Robot(Vector3d position, String name) {
super(position, name);
// Add camera
camera = RobotFactory.addCameraSensor(this);
// Add sonars
sonars = RobotFactory.addSonarBeltSensor(this);
}
/** This method is called by the simulator engine on reset. */
public void initBehavior() {
// nothing particular in this case
}
/** This method is call cyclically (20 times per second) by the simulator engine. */
public void performBehavior() {
// progress at 0.5 m/s
setTranslationalVelocity(0.5);
// frequently change orientation
if ((getCounter() % 100) == 0)
setRotationalVelocity(Math.PI / 2 * (0.5 - Math.random()));
// print front sonar every 100 frames
if (getCounter() % 100 == 0)
System.out
.println("Sonar num 0 = " + sonars.getMeasurement(0));
}
}
/** Describe the environement */
static public class MyEnv extends EnvironmentDescription {
public MyEnv() {
light1IsOn = true;
light2IsOn = false;
Wall w1 = new Wall(new Vector3d(9, 0, 0), 19, 1, this);
w1.rotate90(1);
add(w1);
Wall w2 = new Wall(new Vector3d(-9, 0, 0), 19, 2, this);
w2.rotate90(1);
add(w2);
Wall w3 = new Wall(new Vector3d(0, 0, 9), 19, 1, this);
add(w3);
Wall w4 = new Wall(new Vector3d(0, 0, -9), 19, 2, this);
add(w4);
Box b1 = new Box(new Vector3d(-3, 0, -3), new Vector3f(1, 1, 1),
this);
add(b1);
add(new Arch(new Vector3d(3, 0, -3), this));
add(new Robot(new Vector3d(0, 0, 0), "robot 1"));
}
}
public static void main(String[] args) {
// request antialising
System.setProperty("j3d.implicitAntialiasing", "true");
// create Simbad instance with given environment
Simbad frame = new Simbad(new MyEnv(), false);
}
} | jimmikaelkael/simbad | src/examples/Example1.java |
247,812 |
What is Inner class?
Any Class which is not a top level Class or any Class which is declared inside another Class
is Inner class.
class OuterClass{
class InnerClass{
public void display(){
System.out.println("Inner class.");
}
}
}
What are the types of Inner classes?⭐️
There are following types of such classes:
1. Member Inner class | Regular Inner class
2. Local Inner class
3. Anonymous Inner Class
4. Static Nested Class
What is Member Inner Class?⭐️
Member Inner Class is just regular inner Class which is not static member of the outer class.
It acts as other instance member of that class.
class OuterClass{
class InnerClass{
public void display(){
System.out.println("Inner class.");
}
}
}
-> Class Inner behaves as instance member of this Class Outer.
-> To access this class, we must create the object of Outer Class.
The Member inner classes can be private protected public final <default> abstract etc.
What is the difference between Static nested Class and Member Inner class?⭐️
Static Nested Class is the Class which is declared inside another Class with static modifier.
class Demo{
static class Nested{
public void method(){
System.out.println("Static Nested class.");
}
}
}
👉🏻 To create the instance of Member Inner class, an instance of Outer Class is required.
Whereas static nested Class does not require any outer Class instances. It can be Accessed just
like other static members of that class.
Demo.Nested obj = new Demo.Nested();
Obj.method();
👉🏻 In Member Inner class/ Non-static Nested class, we can access all the static and instance variables of the outer class.
Whereas, inside static nested class, we can only access the static variables of outer class.
👉🏻 We can not declare static methods inside Regular inner classes whereas in static nested classes,
we can do so.
So we can declare main method in static nested class, whereas in regular inner classes we cannot.
👉🏻 We can Import Nested Static Class with static import, whereas we normally Import the non
static nested classes.
What are Local Inner Classes?⭐️
Local inner classes are those classes which are declared inside a code block or a method.
class Main{
private String info = "Outer Class Member";
public void method1(){
class Printer{
public void printInfo(){
System.out.println(info);
}
}
}
}
-> Local inner classes can be used to define specific required functionality for that particular method.
👉🏻 Local Inner Class is a member of the method, so their scope is limited to that particular
method only; Local inner classes are the most rarely used inner classes.
Can we access local variable of the wrapping method inside local inner class?
Yes, we can access final or non-final local variables in local inner class, But We can not modify them.
If we Try to modify them, compiler will raise error.
What access modifiers can be used with Local inner classes?
Local inner is the local member of method, so it can not be declared as public private protected.
👉🏻 Local inner classes can only be final or abstract.
What is Anonymous Inner class?⭐️⭐️
Anonymous Inner Class is a Class which does not have name to reference and initialised at the same
place where it gets created.
👉🏻 For anonymous inner classes, only a single object is created.
Note: An Anonymous Inner Class always extend a Class or implement an interface.
When should we use Anonymous inner classes?
-> An Anonymous Inner Class can be used while making an instance of an object with certain additional
functionalities such as overloading methods of a class, or interface, without having actually any
subclass.
For example, Anonymous inner classes are common to extend Thread Class in order to override run method.
Similarly we can also create anonymous inner class, by implementing runnable interface.
-> Also Anonymous inner classes can be frequently used in GUI based applications for event handling.
We can write implementation classes for listener interfaces in graphics programming using them..
Can we create constructor in anonymous inner class?
We know the constructor has the same name as of the class. We can create constructor explicitly in
all other types of inner classes and static nested class.
But in the case of Anonymous inner class, we do not have the name of the class.
👉🏻 We cannot write any constructor explicitly in anonymous inner class.
What are differences between an Anonymous Inner Class and a normal class?
Both are different in many ways:
1. A normal Class can extend one Class and implement many interfaces at the same time, whereas
the Anonymous Inner Class can either extend one Class or implement one Interface at a time.
2. We write constructors in normal class, which are invoked at the time of instance creation.
But we cannot write any constructor in anonymous inner class.
👉🏻 These classes are initialised at the time of creation itself with the default constructor.
3. We write normal classes for our standard requirements whereas we write anonymous inner classes
when we do not need any separate Class for some temporary requirements,
or when we need to provide implementations to methods for a single object.
Can we have static members inside anonymous inner classes?
No, we cannot declare static data members or static member function inside anonymous inner class.
-> In-fact we can not define any static member inside any inner class. we can do so only in
Static nested classes.
What are the ways of creating Anonymous inner classes?⭐️
Ways to Create anonymous inner classes,
1. By extending a class:
Thread t = new Thread(){
public void run(){
System.out.println("Anonymous inner Thread");
}
};
t.start();
2. By implementing an interface:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Runnable");
}
} ;
Thread th = new Thread(r);
th.start();
3. Defining inside any method or constructor argument:
Thread t = new Thread(new Runnable(){
public void run(){
System.out.println("Child Thread");
}
}}).start();
What are the advantages of inner classes?
We use nested Class when it is useful to only one class. So keeping them together helps in the
packaging of the classes.
By using Inner classes we develop more readable and maintainable code, because it logically
groups the classes in one place.
With inner classes we can access outer Class private members and at the same time we can hide
inner Class from the outer world. Inner classes implements encapsulation.
We also optimize the code by writing inner classes as it requires less code to write.
Can we write Nested Interface inside an Interface?
Answer is Yes.
When an Interface is required for one Interface only then we may write Interface inside Interface.
for example,
In Map Interface we have the Interface Entry, which is used for Map only.
Entry represents a key-value pair inside map.
👉🏻 The inner interfaces which are declared inside Interface are always public and static,
even if we do not make them public or static explicitly.
👉🏻 Inner interfaces can be implemented independently.
Is it possible to define Interface inside Class or Class inside interface?
Answer is Yes. Both cases are possible.
If we define Interface inside class, it is always static.
We can declare it as private public or protected according to our requirement.
class Demo{
public interface Inner{
}
}
And if any Class is closely associated with any Interface then it may be defined inside the interface.
For example, class EmailDetails is required for the interface EmailService.
So we can define it inside this interface.
interface EmailService{
public void sendMail(EmailDetails e);
class EmailDetails{
..
..
}
}
Note: If we implement the Interface with its own inner Class then it is called as its default implementation.
| basicsstrong/java_interview_questions | Inner-classes.java |
247,813 | /*
* Copyright 2011, Zettabyte Storage LLC
*
* This file is part of Vash.
*
* Vash is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Vash is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Vash. If not, see <http://www.gnu.org/licenses/>.
*/
package vash;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import vash.operation.ColorNode;
import vash.operation.Operation;
import vash.operation.OperationFactory;
import vash.operation.OperationNode;
import vash.value.Value;
/**
* A tree of operations which represent the computation of an image.
*/
public class Tree {
/*
* ChannelParameters overlays TreeParameters, masking or augmenting values as needed on a
* per channel basis.
*/
class ChannelParameters {
// operations which are excluded from inclusion in this channel
HashSet<Operation> exclude;
ChannelParameters() {
exclude = new HashSet<Operation>();
}
void addExclude(Operation op) {
exclude.add(op);
}
boolean isExcluded(Operation op) {
return exclude.contains(op);
}
}
// we use these at class construction to precompute values
private static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
// operation sets for our guided random walks
private static final Operation[] TOPS = {
Operation.RGB,
};
private static final Operation[] NODES = {
// Unary
Operation.ABSOLUTE,
Operation.INVERT,
// Binary
Operation.ADD,
Operation.DIVIDE,
Operation.EXPONENTIATE,
Operation.MODULUS,
Operation.MULTIPLY,
// Trig
Operation.SINC,
Operation.SINE,
Operation.SPIRAL,
Operation.SQUIRCLE,
};
private static final Operation[] LEAFS = {
Operation.CONST,
Operation.ELLIPSE,
Operation.FLOWER,
Operation.GRADIENT_LINEAR,
Operation.GRADIENT_RADIAL,
Operation.POLAR_THETA,
};
private static final Operation [] NODES_AND_LEAFS = concat(NODES, LEAFS);
// tree parameters
private final TreeParameters params;
private final ColorNode tree;
private final ArrayList<Value> values = new ArrayList<Value>();
private ImageParameters ip;
/**
* Construct a tree with the given tree parameters.
* @param params TreeParameters that will define this tree
*/
public Tree(TreeParameters params) {
this.params = params;
this.tree = this._buildToplevel();
this.tree.accumulateValues(this.values);
}
/**
* Not for public use.
* @param s
* @param count
* @return
*/
public static boolean[] __buildChannelMask(Seed s, int count) {
switch(count) {
case 3: return new boolean[] {true, true, true};
case 2:
switch(s.nextInt(3)) {
case 0: return new boolean[] {false, true, true};
case 1: return new boolean[] {true, false, true};
case 2: return new boolean[] {true, true, false};
}
case 1:
switch(s.nextInt(3)) {
case 0: return new boolean[] {true, false, false};
case 1: return new boolean[] {false, true, false};
case 2: return new boolean[] {false, false, true};
}
case 0: return new boolean[] {false, false, false};
default: throw new IllegalArgumentException("BuildChannelMask needs count in [0..3]");
}
}
/**
* Not for public use.
* @param s
* @param channels
* @return
*/
public static int __getChannelExclusionCount(Seed s, double channels) {
// NOTE: we have not touched these doubles at all, so it is safe to compare directly here
if(channels <= 0.0) { // 0 channels
return 3;
} else if(channels > 0.0 && channels < 1.0) { // maybe 1 channel
if(s.nextDouble() > channels) // larger number in channels = higher probability 2 (not 3)
return 3;
else
return 2;
} else if(channels == 1.0) { // 1 channel
return 2;
} else if(channels > 1.0 && channels < 2.0) { // 1 and maybe 2 channels
if(s.nextDouble() > (channels - 1.0)) // larger number in channels = higher probability 1 (not 2)
return 2;
else
return 1;
} else if(channels == 2.0) { // 2 channel
return 1;
} else if(channels > 2.0 && channels < 3.0) { // 2 and maybe 3 channels
if(s.nextDouble() > (channels - 2.0)) // larger number in channels = higher probability 0 (not 1)
return 1;
else
return 0;
}
// 3 channels: no exclusions
return 0;
}
// drive channel exclusion selection for each operation on each channel
private void _setupChannelExclusions(ChannelParameters[] chans) {
Seed s = params.getSeed();
for(Operation op : NODES_AND_LEAFS) {
double n_channels = params.getOperationChannels(op);
int n_exclude = __getChannelExclusionCount(s, n_channels);
boolean[] exclude = __buildChannelMask(s, n_exclude);
for(int i = 0; i < 3; i++) {
if(exclude[i]) {
chans[i].addExclude(op);
}
}
}
}
private ColorNode _buildToplevel() {
// only allow one plane to have the singleton class
if(this.params.getSeed().getAlgorithm().equals("1.1")) {
// toplevel (color) node
ColorNode rgb = (ColorNode)_selectAndCreateOp(0, new ChannelParameters());
// channel parameters
ChannelParameters[] chan = {
new ChannelParameters(),
new ChannelParameters(),
new ChannelParameters()
};
_setupChannelExclusions(chan);
// build each channel and attach to color node
OperationNode r = _buildNode(1, chan[0]);
OperationNode g = _buildNode(1, chan[1]);
OperationNode b = _buildNode(1, chan[2]);
rgb.setChild(0, r);
rgb.setChild(1, g);
rgb.setChild(2, b);
return rgb;
} else {
return (ColorNode)_buildNode(0, new ChannelParameters());
}
}
private OperationNode _buildNode(int level, ChannelParameters chan) {
OperationNode op = _selectAndCreateOp(level, chan);
for(int i = 0; i < op.getChildCount(); i++) {
OperationNode child = _buildNode(level + 1, chan);
op.setChild(i, child);
}
return op;
}
private Operation _selectOp(int level, ChannelParameters chan) {
// select list of ops to select from
Operation[] ops;
double rand, pos;
if(level == 0) {
ops = TOPS;
} else if(level <= this.params.getMinDepth()) {
ops = NODES;
} else if(level >= this.params.getMaxDepth()) {
ops = LEAFS;
} else {
ops = NODES_AND_LEAFS;
}
// compute the total for our ops
double total = 0.0;
for(Operation op : ops) {
if(chan.isExcluded(op)) { continue; }
total += this.params.getOperationRatio(op);
}
// get a random number in [0, total]
rand = this.params.getSeed().nextDouble() * total;
// walk the table until we find our op
pos = 0.0;
for(Operation op : ops) {
if(chan.isExcluded(op)) { continue; }
pos += this.params.getOperationRatio(op);
if(pos > rand) {
return op;
}
}
throw new RuntimeException("Overflowed our OperationytecodeTable somehow at level: " + Integer.toString(level));
}
private OperationNode _selectAndCreateOp(int level, ChannelParameters chan) {
return OperationFactory.createNode(_selectOp(level, chan), this.params.getSeed());
}
/**
* Write a string representation of this tree to a given filename.
* @throws IOException
*/
public void show(String filename) throws IOException {
OutputStream fp;
if(filename.equals("-")) {
fp = System.out;
} else {
fp = new FileOutputStream(filename);
}
this.tree.show(fp, 0);
fp.close();
}
/**
* Provide parameters for the construction of images from this tree. These
* parameters are independent of the tree itself and it is frequently useful
* to give several to a single tree over its lifetime, e.g. if we are generating
* multiple image resolutions from one tree. This method must be called with
* an ImageParameters before calling generateCurrentFrame.
*/
public void setGenerationParameters(ImageParameters ip) {
this.ip = ip;
}
void setTime(double t, double dt) {
for(Value v : this.values) {
v.setTime(t, dt);
}
}
/**
* Compute an image from this tree. Before calling this function,
* setGenerationParameters must be called with an ImageParameters object.
*/
public byte[] generateCurrentFrame() {
if(this.ip == null)
throw new IllegalArgumentException("setGenerationParameters must be called to set ImageParameters");
return this.tree.compute(this.ip, true);
}
}
| thevash/vash | src/vash/Tree.java |
247,814 | /*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* EclipseSource - modification after copying to ECF filetransfer provider
*******************************************************************************/
package org.eclipse.ecf.provider.filetransfer.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.ecf.internal.provider.filetransfer.Activator;
/**
* Polls a progress monitor periodically and handles timeouts over extended
* durations. For this class to be effective, a high numAttempts should be
* specified, and the underlying stream should time out frequently on reads
* (every second or so).
*
* Supports resuming partially completed operations after an
* InterruptedIOException if the underlying stream does. Check the
* bytesTransferred field to determine how much of the operation completed;
* conversely, at what point to resume.
*
* @since 3.0
*/
public class PollingInputStream extends FilterInputStream {
private int numAttempts;
private IProgressMonitor monitor;
private boolean cancellable;
//$NON-NLS-1$
private String readTimeoutMessage = "Timeout while reading input stream";
//$NON-NLS-1$
private String closeTimeoutMessage = "Timeout while closing input stream";
/**
* Creates a new polling input stream.
*
* @param in
* the underlying input stream
* @param numAttempts
* the number of attempts before issuing an
* InterruptedIOException, if 0, retries indefinitely until
* canceled
* @param monitor
* the progress monitor to be polled for cancellation
*/
public PollingInputStream(InputStream in, int numAttempts, IProgressMonitor monitor) {
super(in);
this.numAttempts = numAttempts;
this.monitor = monitor;
this.cancellable = true;
}
/**
* Creates a new polling input stream.
*
* @param in
* the underlying input stream
* @param numAttempts
* the number of attempts before issuing an
* InterruptedIOException, if 0, retries indefinitely until
* canceled
* @param monitor
* the progress monitor to be polled for cancellation
* @param readTimeoutMessage message to go with InteruptedIOException if read timeout
* @param closeTimeoutMessage message to go with InteruptedIOException if close timeout
* @since 3.1
*/
public PollingInputStream(InputStream in, int numAttempts, IProgressMonitor monitor, String readTimeoutMessage, String closeTimeoutMessage) {
super(in);
this.numAttempts = numAttempts;
this.monitor = monitor;
this.cancellable = true;
if (readTimeoutMessage != null)
this.readTimeoutMessage = readTimeoutMessage;
if (closeTimeoutMessage != null)
this.closeTimeoutMessage = closeTimeoutMessage;
}
/**
* Wraps the underlying stream's method. It may be important to wait for an
* input stream to be closed because it holds an implicit lock on a system
* resource (such as a file) while it is open. Closing a stream may take
* time if the underlying stream is still servicing a previous request.
*
* @throws OperationCanceledException
* if the progress monitor is canceled
* @throws InterruptedIOException
* if the underlying operation times out numAttempts times
*/
public void close() throws InterruptedIOException {
int attempts = 0;
try {
readPendingInput();
} catch (IOException e) {
logError(e.getMessage(), e);
} finally {
boolean stop = false;
while (!stop) {
try {
if (in != null)
in.close();
stop = true;
} catch (InterruptedIOException e) {
if (checkCancellation())
throw new OperationCanceledException();
if (++attempts == numAttempts)
throw new InterruptedIOException(closeTimeoutMessage);
} catch (IOException e) {
}
}
}
}
private void logError(String message, IOException e) {
Activator a = Activator.getDefault();
if (a != null)
a.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, message, e));
}
/**
* Wraps the underlying stream's method.
*
* @return the next byte of data, or -1 if the end of the stream is reached.
* @throws OperationCanceledException
* if the progress monitor is canceled
* @throws InterruptedIOException
* if the underlying operation times out numAttempts times and
* no data was received, bytesTransferred will be zero
* @throws IOException
* if an i/o error occurs
*/
public int read() throws IOException {
int attempts = 0;
for (; ; ) {
if (checkCancellation())
throw new OperationCanceledException();
try {
return in.read();
} catch (InterruptedIOException e) {
if (++attempts == numAttempts)
throw new InterruptedIOException(readTimeoutMessage);
}
}
}
/**
* Wraps the underlying stream's method.
*
* @param buffer
* - the buffer into which the data is read.
* @param off
* - the start offset of the data.
* @param len
* - the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or -1 if there is
* no more data because the end of the stream has been reached.
* @throws OperationCanceledException
* if the progress monitor is canceled
* @throws InterruptedIOException
* if the underlying operation times out numAttempts times and
* no data was received, bytesTransferred will be zero
* @throws IOException
* if an i/o error occurs
*/
public int read(byte[] buffer, int off, int len) throws IOException {
int attempts = 0;
for (; ; ) {
if (checkCancellation())
throw new OperationCanceledException();
try {
return in.read(buffer, off, len);
} catch (InterruptedIOException e) {
if (e.bytesTransferred != 0)
return e.bytesTransferred;
if (++attempts == numAttempts)
throw new InterruptedIOException(readTimeoutMessage);
}
}
}
/**
* Wraps the underlying stream's method.
*
* @param count
* - the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @throws OperationCanceledException
* if the progress monitor is canceled
* @throws InterruptedIOException
* if the underlying operation times out numAttempts times and
* no data was received, bytesTransferred will be zero
* @throws IOException
* if an i/o error occurs
*/
public long skip(long count) throws IOException {
int attempts = 0;
for (; ; ) {
if (checkCancellation())
throw new OperationCanceledException();
try {
return in.skip(count);
} catch (InterruptedIOException e) {
if (e.bytesTransferred != 0)
return e.bytesTransferred;
if (++attempts == numAttempts)
throw new InterruptedIOException(readTimeoutMessage);
}
}
}
/**
* Reads any pending input from the input stream so that the stream can
* savely be closed.
*
* @throws IOException if some problem reading
*/
protected void readPendingInput() throws IOException {
byte[] buffer = new byte[2048];
while (true) {
int available = in.available();
if (available < 1)
break;
if (available > buffer.length)
available = buffer.length;
if (in.read(buffer, 0, available) < 1)
break;
}
}
/**
* Called to set whether cancellation will be checked by this stream.
* Turning cancellation checking off can be very useful for protecting
* critical portions of a protocol that shouldn't be interrupted. For
* example, it is often necessary to protect login sequences.
*
* @param cancellable
* a flag controlling whether this stream will check for
* cancellation.
*/
public void setIsCancellable(boolean cancellable) {
this.cancellable = cancellable;
}
/**
* Checked whether the monitor for this stream has been cancelled. If the
* cancellable flag is <code>false</code> then the monitor is never
* cancelled.
*
* @return <code>true</code> if the monitor has been cancelled and
* <code>false</code> otherwise.
*/
private boolean checkCancellation() {
if (cancellable) {
return monitor.isCanceled();
}
return false;
}
}
| masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018 | Corpus/ecf/484.java |
247,815 | import java.util.*;
/**
* In this example, we have modified the Trie class to include a frequency
* variable that keeps track of the number of times a word is inserted into the
* Trie. We have also added two new methods: getFrequency(String word) and
* getFrequentlySearchedWords(int limit).
* <p>
* The 'getFrequency(String word)method returns the frequency of a given word by
* traversing the Trie based on the characters in the word and returning
* thefrequency' value stored in the last node.
* </p>
* <p>
* The getFrequentlySearchedWords(int limit) method returns a list of the most
* frequently searched words up to the specified limit. It uses a breadth-first
* search (BFS) approach to traverse the Trie and collect the words that have a
* non-zero frequency, up to the limit.
* </p>
* <p>
* In the main method, we create a new Trie object, insert some words into it,
* and then call the getFrequentlySearchedWords method to obtain the most
* frequently searched words. In this example, we specify a limit of 2, so it
* will return the top two frequently searched words.
* <p/>
*
* @author MOPHE
* @ChatGPT
*/
public class Frequents {
public static void main(String[] args) {
String[] words = {"Java", "Python", "C++", "Java", "JavaScript", "Python", "Python", "C++", "Java", "Java"};
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
List<String> frequentlySearchedWords = trie.getFrequentlySearchedWords(2);
System.out.println("Frequently searched words: " + frequentlySearchedWords);
}
}
class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
int frequency;
public TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
frequency = 0;
}
}
class Trie {
private final TrieNode ROOT;
public Trie() {
ROOT = new TrieNode();
}
public void insert(String word) {
TrieNode current = ROOT;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.isEndOfWord = true;
current.frequency++;
}
public int getFrequency(String word) {
TrieNode current = ROOT;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
return 0;
}
current = node;
}
return current.frequency;
}
public List<String> getFrequentlySearchedWords(int limit) {
List<String> result = new ArrayList<>();
Queue<TrieNode> queue = new LinkedList<>();
queue.offer(ROOT);
while (!queue.isEmpty()) {
TrieNode current = queue.poll();
if (current.isEndOfWord && current.frequency > 0) {
result.add(getWord(current));
if (result.size() == limit) {
break;
}
}
for (TrieNode child : current.children.values()) {
queue.offer(child);
}
}
return result;
}
private String getWord(TrieNode node) {
StringBuilder sb = new StringBuilder();
while (node != ROOT) {
for (Map.Entry<Character, TrieNode> entry : node.children.entrySet()) {
if (entry.getValue() == node) {
sb.insert(0, entry.getKey());
break;
}
}
node = getParent(node);
}
return sb.toString();
}
private TrieNode getParent(TrieNode node) {
Queue<TrieNode> queue = new LinkedList<>();
queue.offer(ROOT);
while (!queue.isEmpty()) {
TrieNode current = queue.poll();
for (TrieNode child : current.children.values()) {
if (child == node) {
return current;
}
queue.offer(child);
}
}
return null;
}
}
| Mopheshi/Exercises | Frequents.java |
247,816 | package com;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import parser.StanfordTokenizer;
//import main.Documents;
public class FileUtil {
public static void readLines(String file, ArrayList<String> lines) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(file)));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void writeLines(String file, HashMap<?, ?> hashMap) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(file)));
Set<?> s = hashMap.entrySet();
Iterator<?> it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
writer.write(m.getKey() + "\t" + m.getValue() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void writeLines(String file, ArrayList<?> counts) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(file)));
for (int i = 0; i < counts.size(); i++) {
writer.write(counts.get(i) + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void writeLines(String file, ArrayList<String> uniWordMap,
ArrayList<Integer> uniWordMapCounts) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(file)));
for (int i = 0; i < uniWordMap.size()
|| i < uniWordMapCounts.size(); i++) {
writer.write(uniWordMap.get(i) + "\t" + uniWordMapCounts.get(i)
+ "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@SuppressWarnings("unchecked")
public static void writeLinesSorted(String file, ArrayList<?> uniWordMap,
ArrayList<?> uniWordMapCounts, int flag) {
// flag = 0 decreasing order otherwise increasing
HashMap map = new HashMap();
if (uniWordMap.size() != uniWordMapCounts.size()) {
System.err.println("Array sizes are not equal!!! Function returned.");
} else {
for (int i = 0; i < uniWordMap.size(); i++) {
map.put(uniWordMap.get(i), uniWordMapCounts.get(i));
}
map = (HashMap<String, Integer>) ComUtil.sortByValue(map, flag);
writeLines(file, map);
map.clear();
}
}
public static void tokenize(String line, ArrayList<String> tokens) {
StringTokenizer strTok = new StringTokenizer(line);
while (strTok.hasMoreTokens()) {
String token = strTok.nextToken();
tokens.add(token);
}
}
public static boolean tokenize(String line, ArrayList<String> words,
ArrayList<String> tags, String string, boolean flag) {
ArrayList<String> tokens = new ArrayList<String>();
FileUtil.tokenize(line, tokens);
for (int i = 0; i < tokens.size(); i++) {
int index = -1;
if (flag)
index = tokens.get(i).lastIndexOf("_");
else
index = tokens.get(i).indexOf("_");
if(index > -1) {
words.add(tokens.get(i).substring(0, index));
tags.add(tokens.get(i).substring(index + 1));
}
}
if(words.size() > 0)
return true;
else
return false;
}
public static void print(ArrayList<?> tokens) {
for (int i = 0; i < tokens.size(); i++) {
System.out.print(tokens.get(i) + " ");
}
System.out.print("\n");
}
// HashMap Operations
public static void printHash(HashMap<String, Integer> hashMap) {
Set<?> s = hashMap.entrySet();
Iterator<?> it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
System.out.println(m.getKey() + "\t" + m.getValue());
}
}
public static ArrayList<String> getHashMap(HashMap<?, ?> hm) {
ArrayList<String> a = new ArrayList<String>();
Set<?> s = hm.entrySet();
Iterator<?> it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
a.add(m.getKey() + "\t" + m.getValue());
}
return a;
}
public static String getKeysFromValue(HashMap<Integer, String> hm,
String value) {
Set<?> s = hm.entrySet();
// Move next key and value of HashMap by iterator
Iterator<?> it = s.iterator();
while (it.hasNext()) {
// key=value separator this by Map.Entry to get key and value
Map.Entry m = (Map.Entry) it.next();
if (m.getValue().equals(value))
return m.getKey() + "";
}
System.err.println("Error, can't find the data in Hashmap!");
return null;
}
public static void readHash(String type_map, HashMap<String, String> typeMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
FileUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!typeMap.containsKey(tokens.get(0)))
typeMap.put(tokens.get(0), tokens.get(1));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
public static void readHash2(String type_map,
HashMap<String, Integer> hashMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
FileUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!hashMap.containsKey(tokens.get(0)))
hashMap.put(tokens.get(0),
new Integer(tokens.get(1)));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
public static void readHash3(String type_map,
HashMap<String, Integer> hashMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
FileUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() < 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
String key = tokens.get(0);
String value = tokens.get(tokens.size() - 1);
for (int no = 1; no < tokens.size() - 1; no++) {
key += " " + tokens.get(no);
}
if (!hashMap.containsKey(key))
hashMap.put(key, new Integer(value));
else {
System.out.println(key + " " + value);
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
/**
* Create a directory by calling mkdir();
*
* @param dirFile
*/
public static void mkdir(File dirFile) {
try {
// File dirFile = new File(mkdirName);
boolean bFile = dirFile.exists();
if (bFile == true) {
System.err.println("The folder exists.");
} else {
System.err
.println("The folder do not exist,now trying to create a one...");
bFile = dirFile.mkdir();
if (bFile == true) {
System.out.println("Create successfully!");
} else {
System.err
.println("Disable to make the folder,please check the disk is full or not.");
}
}
} catch (Exception err) {
System.err.println("ELS - Chart : unexpected error");
err.printStackTrace();
}
}
public static void mkdir(File file, boolean b) {
if(b) {// true delete first
deleteDirectory(file);
mkdir(file);
} else {
mkdir(file);
}
}
/**
*
* @param path
* @return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
/**
* List files in a given directory
*
* */
static public String[] listFiles(String inputdir) {
File dir = new File(inputdir);
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i = 0; i < children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
return children;
}
/**
* List files in a given directory
*
* */
static public String[] listFilteredFiles(String inputdir,
final String filterCondition) {
File dir = new File(inputdir);
String[] children = dir.list();
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(filterCondition);
}
};
children = dir.list(filter);
return children;
}
/**
* List files recursively in a given directory
*
* */
static public void listFilesR() {
File dir = new File("directoryName");
String[] children = dir.list();
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
}
/**
* Frequently used functions
* */
static public int count(String a, String contains) {
int i = 0;
int count = 0;
while (a.contains(contains)) {
i = a.indexOf(contains);
a = a.substring(0, i)
+ a.substring(i + contains.length(), a.length());
count++;
}
return count;
}
public static void print(String[] files) {
for (int i = 0; i < files.length; i++) {
System.out.print(files[i] + " ");
}
System.out.print("\n");
}
public static void print(int[] c1) {
for (int i = 0; i < c1.length; i++) {
System.out.print(c1[i] + " ");
}
System.out.println();
}
public static void test() {
String a = "fdsfdsaf";
a += "\nfdsaf fd fd";
a += "\nfd sf fd fd\n";
System.out.println(a);
a = a.replaceAll("\n+", " ");
System.out.println(a);
System.exit(0);
}
public static void readHash(String type_map, HashMap<String, String> typeMap, boolean flag) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if(type_map != null) {
readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
FileUtil.tokenize(types.get(i), tokens);
if(tokens.size() != 0) {
if (tokens.size() != 2) {
for(int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j)+" ");
}
System.err
.println(type_map + " Error ! Not two elements in one line !");
return;
}
String tokens0 = "";
String tokens1 = "";
if(flag) {
tokens0 = tokens.get(0).trim();
tokens1 = tokens.get(1).trim();
} else {
tokens0 = tokens.get(1).trim();
tokens1 = tokens.get(0).trim();
}
if (!typeMap.containsKey(tokens0))
typeMap.put(tokens0, tokens1);
else {
System.err.println(tokens0 + " " + tokens1);
System.err
.println(type_map + " Ignore this one ! Same type in first column !");
}
}
tokens.clear();
}
}
}
}
public static String filter4tokenization(String inputstring) {
// inputstring = "fds fds Won't won't can't Can't ain't";
// aggregate common tokenization error
inputstring = inputstring.replaceAll("(?i)won't", "will not");
inputstring = inputstring.replaceAll("(?i)can't", "can not");
inputstring = inputstring.replaceAll("(?i)shan't", "shall not");
inputstring = inputstring.replaceAll("(?i)ain't", "am not");
return inputstring;
}
public static void tokenizeAndLowerCase(String line, ArrayList<String> tokens) {
// TODO Auto-generated method stub
StringTokenizer strTok = new StringTokenizer(line);
while (strTok.hasMoreTokens()) {
String token = strTok.nextToken();
tokens.add(token.toLowerCase().trim());
}
}
public static boolean isNoiseWord(String string) {
// TODO Auto-generated method stub
string = string.toLowerCase().trim();
Pattern MY_PATTERN = Pattern.compile(".*[a-zA-Z]+.*");
Matcher m = MY_PATTERN.matcher(string);
// filter @xxx and URL
if(string.matches(".*www\\..*") || string.matches(".*\\.com.*") ||
string.matches(".*http:.*") )
return true;
if (!m.matches()) {
return true;
} else
return false;
}
public static void writeArray(float[] pi, String piFileName) throws IOException {
// TODO Auto-generated method stub
BufferedWriter writer = new BufferedWriter(new FileWriter(piFileName));
for(int i = 0; i < pi.length; i++){
writer.append(pi[i] + "\t");
}
writer.flush();
writer.close();
}
public static void write3DArray(float[][][] theta, String thetaFileName) throws IOException {
// TODO Auto-generated method stub
BufferedWriter writer = new BufferedWriter(new FileWriter(thetaFileName));
for(int i = 0; i < theta.length; i++){
for(int j = 0; j < theta[i].length; j++){
for(int k = 0; k < theta[i][j].length; k++){
writer.append(i + "\t" + j + "\t" + k + "\t" + theta[i][j][k] + "\n");
}
}
writer.flush();
}
writer.flush();
writer.close();
}
public static void write2DArray(float[][] phiT, String phiTFileName) throws IOException {
// TODO Auto-generated method stub
BufferedWriter writer = new BufferedWriter(new FileWriter(phiTFileName));
for(int i = 0; i < phiT.length; i++){
for(int j = 0; j < phiT[i].length; j++){
writer.append(phiT[i][j] + "\t");
}
writer.append("\n");
}
writer.flush();
writer.close();
}
public static void write4DArray(float[][][][] phiAS, String phiASFileName) throws IOException {
// TODO Auto-generated method stub
BufferedWriter writer = new BufferedWriter(new FileWriter(phiASFileName));
for(int i = 0; i < phiAS.length; i++){
for(int j = 0; j < phiAS[i].length; j++){
for(int k = 0; k < phiAS[i][j].length; k++){
for(int m = 0; m < phiAS[i][j][k].length; m++){
writer.append(i + "\t" + j + "\t" + k + "\t" + m + "\t" + phiAS[i][j][k][m] + "\n");
}
}
writer.flush();
}
}
writer.flush();
writer.close();
}
public static <T> void saveClass(T docCollection, String file) {
System.err.println("saving a class to " + file);
try {
// write the model to file: outputDir + outname
FileOutputStream f_out = new FileOutputStream(file);
// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
// Write object out to disk
obj_out.writeObject(docCollection);
obj_out.flush();
obj_out.close();
} catch (IOException e) {
System.err.println("Exception thrown during test: " + e.toString());
}
}
@SuppressWarnings("unchecked")
public static <T> T loadClass(T docSet, String docfile) throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
System.out.println("reading a class from : " + docfile);
FileInputStream fis = new FileInputStream(docfile);
ObjectInputStream ois = new ObjectInputStream(fis);
docSet = (T) ois.readObject();
ois.close();
return docSet;
}
public static float[][] readArray(String file) {
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
readLines(file, lines);
tokenize(lines.get(0), tokens);
int d = tokens.size();
float[][] data = new float[lines.size()][d];
for(int i = 0; i < lines.size(); i++) {
tokens.clear();
tokenize(lines.get(i), tokens);
for(int j = 0; j < d; j++) {
data[i][j] = Float.parseFloat(tokens.get(j));
}
}
return data;
}
public static double[][] read2DArray(String file) {
// TODO Auto-generated method stub
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
readLines(file, lines);
tokenize(lines.get(0), tokens);
int d = tokens.size();
double[][] data = new double[lines.size()][d];
for(int i = 0; i < lines.size(); i++) {
tokens.clear();
tokenize(lines.get(i), tokens);
for(int j = 0; j < d; j++) {
data[i][j] = Double.parseDouble(tokens.get(j));
}
}
return data;
}
public static void copyFile(String srcfile, String targetFile) {
ArrayList<String> lines = new ArrayList<String>();
readLines(srcfile, lines);
writeLines(targetFile, lines);
}
public static void tokenizeStanfordTKAndLowerCase(String line, ArrayList<String> tokens){
ArrayList<String> sents = StanfordTokenizer.tokenizeSents(line);
for(String sent : sents){
String[] words = sent.replaceAll("\\pP|\\pS", "").split(" ");//remove punctuation and math symbols
for(String word : words){
tokens.add(word.toLowerCase().trim());
}
}
}
} | yangliuy/aNMM-CIKM16 | src/com/FileUtil.java |
247,817 | // Copyright (C) 2016 Electronic Arts Inc. All rights reserved.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.Properties;
import java.util.TreeMap;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.hyperic.sigar.Sigar;
/**
* Main class for running the R Server.
*
* To run on windows use:
* -DwampWWW=C:/wamp/www
*
* Runtime Properies (e.g. -DgcRefresh=120000)
* ---------------------------------------------------------
*
* wampWWW: The full-qualified directory for where to place html files. /RServer will be added to this path
* default: /var/www/html
*
* mainThreadRefresh: how often to check the status of jobs?
* default: 2000 (ms)
*
* statusThreadRefresh: how often to create a new php page?
* default: 5000 (ms)
*
* gcRefresh: how often to run the garbage collector?
* default: 60000 (ms)
*
* completedTaskSize: how many completed tasks to show at the bottom of the page?
* default: 100
*
* logHistorySize: On the index.php page, how many log entries to show?
* default: 20
*
* maxJobFiles: how many files to allow in the job history folder before cleaning up?
* default: 5000
*
* pageRefreshTime: for often to refresh the page (for web clients)?
* default: 5000 (ms)
*
* performanceLogSize: how many entries to maintain in the performance file (used by the server monitor app)
* default: 200
*
* serverEmail: Which account should send emails about RServer?
* default: "[email protected]"
*
* serverAdmin: Who is your admin for RServer?
* default: "[email protected]"
*
* smtp: the smtp server to use for email
* default: "mail.yourdomain.com"
*
* perforceBase: the name of Github project (used as the base directory for checking out files)
* default: "RServer"
*
* schedulePath: Where the schedule file is located within the Github depot
* default: "/tasks/Schedule.csv"
*
* rPath: The full qualified path to your R bin directory (Windows Only)
* default: "C:/Program Files/R/R-3.2.2/bin/"
*/
public class RServer {
public static final String ServerDate= "June 15, 2016";
// thread update speeds
private static long mainThreadRefresh = 2000;
private static long statusThreadRefresh = 5000;
private static long gcRefresh = 60000;
private static int completedTaskSize = 100;
private static int logHistorySize = 20;
private static int maxJobFiles = 500;
private static int pageRefreshTime = 5000;
private static int performanceLogSize = 200;
// server paths
private static boolean isLinux = true;
private static String wampWWW = "/var/www/html";
private static String logDir = wampWWW + "/RServer/logs/";
private static String requestsDir = wampWWW + "/RServer/requests/";
private static String routDir = wampWWW + "/RServer/Rout/";
private static String jobsDir = wampWWW + "/RServer/jobs/";
private static String indexPagePath = wampWWW + "/RServer/index.php";
private static String performanceLogDir = wampWWW + "/RServer/perf";
// email config
private static String serverEmail = "[email protected]";
private static String serverAdmin = "[email protected]";
private static String smtp = "mail.yourdomain.com";
// perforce paths
private static String perforceBase = "RServer";
private static String schedulePath = "/tasks/Schedule.csv";
private static String perforceWWW = "/www";
private static String gitDepot = "https://github.com/bgweber/RServer";
// working directory
private static String scriptPath = "/scripts/";
private static String rPath = "C:/Program Files/R/R-3.2.2/bin/";
/** The last time that perforce ran */
private long lastPerforceUpdate = 0;
/** when the server launched */
private static long bootTime = System.currentTimeMillis();
/** The list of schedules with a regular frequency */
private ArrayList<Schedule> regularSchedules = new ArrayList<Schedule>();
/** The list of ad hoc schedule to run */
private ArrayList<Schedule> adhocSchedules = new ArrayList<Schedule>();
/** Currently active tasks */
private TreeMap<String, Task> runningTasks = new TreeMap<String, Task>();
/** Completed tasks (regular and ad hoc) */
private LinkedList<Task> completed = new LinkedList<Task>();
/** Recent log messages */
private LinkedList<String> logEntries = new LinkedList<String>();
/** last garbage collection run */
private static long lastGC = System.currentTimeMillis();
/** for monitoring system usage */
private Sigar sigar = new Sigar();
/** store the last CPU reading, sigar.getCpuPerc() doesn't work if called too frequently */
private double cpuLoad = 0.0;
// String constants
private static final String PerforceTask = "Git";
// host config
private static String fullHostName = null;
// record how long updates took
private long updateHtmlTime = 0;
private long updatePerfLogTime = 0;
/**
* Start the server!
*/
public static void main(String[] args) {
// load the host name
try {
//fullHostName = InetAddress.getLocalHost().getCanonicalHostName();
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
fullHostName = in.readLine();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Set up wamp directories
wampWWW = getProperty("wampWWW", wampWWW);
logDir = wampWWW + "/RServer/logs/";
requestsDir = wampWWW + "/RServer/requests/";
routDir = wampWWW + "/RServer/Rout/";
jobsDir = wampWWW + "/RServer/jobs/";
indexPagePath = wampWWW + "/RServer/index.php";
scriptPath = wampWWW + "/RServer/scripts/";
performanceLogDir = wampWWW + "/RServer/perf";
isLinux = !wampWWW.contains(":");
// create necessary Wamp directories if not found
String[] directories = {
"/RServer",
"/RServer/jobs",
"/RServer/logs",
"/RServer/perf",
"/RServer/reports",
"/RServer/requests",
"/RServer/Rout",
"/RServer/scripts",
"/RServer/reports/RServer",
};
for (String dir : directories) {
File file = new File(wampWWW + dir);
if (!file.exists()) {
file.mkdir();
}
}
// set up folder permissions
try {
if (isLinux) { // only linux
Runtime.getRuntime().exec("sudo chmod 0777 " + wampWWW + "/RServer/requests").waitFor();
Runtime.getRuntime().exec("sudo chmod 0777 " + wampWWW + "/RServer/Rout").waitFor();
}
}
catch (Exception e) {
e.printStackTrace();
}
// load system properties
mainThreadRefresh = Long.parseLong(getProperty("mainThreadRefresh", "" + mainThreadRefresh));
statusThreadRefresh = Long.parseLong(getProperty("statusThreadRefresh", "" + statusThreadRefresh));
gcRefresh = Long.parseLong(getProperty("gcRefresh", "" + gcRefresh));
completedTaskSize = Integer.parseInt(getProperty("completedTaskSize", "" + completedTaskSize));
logHistorySize = Integer.parseInt(getProperty("logHistorySize", "" + logHistorySize));
maxJobFiles = Integer.parseInt(getProperty("maxJobFiles", "" + maxJobFiles));
pageRefreshTime = Integer.parseInt(getProperty("pageRefreshTime", "" + pageRefreshTime));
performanceLogSize = Integer.parseInt(getProperty("performanceLogSize", "" + performanceLogSize));
performanceLogDir = getProperty("performanceLogDir", performanceLogDir);
// server config
serverEmail = getProperty("serverEmail", serverEmail);
serverAdmin = getProperty("serverAdmin", serverAdmin);
smtp = getProperty("smtp", smtp);
// set up Perforce directories
perforceBase = getProperty("perforceBase", perforceBase);
schedulePath = perforceBase + getProperty("schedulePath", "" + schedulePath);
rPath = getProperty("rPath", rPath);
perforceBase = getProperty("perforceBase", perforceBase);
// delete prior performance log
File logFile = new File(performanceLogDir + "/ServerLoad.csv");
if (logFile.exists()) {
logFile.delete();
}
// start the server
new RServer().start();
}
/**
* Main server loop.
*
* The server status thread updates the dashboard file.
*
* The main thread checks for scheduels to run and new ad hoc schedules,
* does perforce updates, and manages creating working directories.
*/
public void start() {
Thread.currentThread().setName("Main server thread");
log("Starting " + (isLinux ? "Linux" : "Windows") + " Server");
// force Perfoce to refresh on start up
adhocSchedules.add(new Schedule(PerforceTask, "", "", serverAdmin, false, "", false, null));
regularSchedules = loadSchedules(true);
// create the server status thread
new Thread() {
public void run() {
Thread.currentThread().setName("Server status thread");
while (true) {
try {
long time = System.currentTimeMillis();
updateServerStatus();
updateHtmlTime = System.currentTimeMillis() - time;
time = System.currentTimeMillis();
updatePerformaceLog();
updatePerfLogTime = System.currentTimeMillis() - time;
Thread.sleep(statusThreadRefresh);
}
catch (Exception e) {
log("ERROR: updating server status (index.php): " + e.getMessage());
}
}
}
}.start();
// main server loop
while (true) {
try {
checkSchedules();
// GC time?
if ((System.currentTimeMillis() - lastGC) > gcRefresh) {
System.gc();
lastGC = System.currentTimeMillis();
}
Thread.sleep(mainThreadRefresh);
}
catch (Exception e) {
log("ERROR: main server thread: " + e.getMessage());
e.printStackTrace();
sendEmail(serverAdmin, "R Server Error",
"Excepton in main server thread: " + e.getMessage());
}
}
}
/**
* Check if any schedules need to run. Launches a new thread for each running schedule.
* Updates perforce if an ad-hoc schedule is running, or the perforce task is scheduled.
*
* Method overview
* ---------------
* 1. Check the requests directory for any ad-hoc task to run
* 2. Schedule the ad-hoc tasks to run
* 3. Check if any regular schedules should run
* 4. Update perforce if necessary
* 5. Set up the working directories for the new tasks
* 6. Run each task in a new thread
*/
public void checkSchedules() {
// 1. check for new ad hoc requests (poll the request directory)
File requestDir = new File(requestsDir);
if (requestDir.exists()) {
for (File file : requestDir.listFiles()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
// check if this is a valid file
if (line != null) {
String[] atts = line.split(",");
// ad-hoc request (.ad file)
if (file.getName().endsWith(".ad")) {
if (atts.length < 8) {
log("Invalid schedule: " + line);
}
else {
String task = atts[0].trim();
String path = atts[1].trim();
String script = atts[2].trim();
String owner = atts[3].trim();
boolean emailOnSuccess = "true".equalsIgnoreCase(atts[4].trim());
String params = atts[5].trim();
boolean shiny = "true".equalsIgnoreCase(atts[6].trim());
String jobId = atts[7].trim();
// do some basic error checking
if ((task.length() == 0 || path.length() == 0 || script.length() == 0 || owner.length() == 0)
&& !task.equalsIgnoreCase(PerforceTask)) {
log("Invalid schedule submitted: " + line);
updateJobStatus(jobId, "Invalid", null);
}
else {
Schedule schedule = new Schedule(task, path, script, owner, emailOnSuccess, params, shiny, jobId);
log("Loaded request for ad-hoc schedule: " + schedule.toString());
adhocSchedules.add(schedule);
// update the status of the job
updateJobStatus(jobId, "Submitted", null);
}
}
}
// kill process request (.kp file)
else if (file.getName().endsWith(".kp")) {
synchronized (RServer.this) {
String task = atts[0].trim();
Task runningTask = runningTasks.get(task);
if (runningTask != null && runningTask.getPID() > 0) {
log("Killing Process: " + task + " " + runningTask.getPID());
try {
runningTask.setAborted(true);
log("Sending command: " + "pkill -TERM -P " + runningTask.getPID());
Process p = Runtime.getRuntime().exec("pkill -TERM -P " + runningTask.getPID());
// Process p = Runtime.getRuntime().exec("kill -9 " + runningTask.getPID());
// Process p = Runtime.getRuntime().exec("taskkill /F /T /PID " + runningTask.getPID());
p.waitFor();
}
catch (Exception err) {
log("ERROR: failed to run task kill for : " + task + " " + runningTask.getPID());
err.printStackTrace();
}
}
else {
log("ERROR: unable to terminate process, not found: " + task);
}
}
}
}
else {
log("Empty request file found, ignoring: " + file.getName());
}
reader.close();
file.delete();
}
catch (Exception e) {
e.printStackTrace();
log("ERROR: Exception while reading ad-hoc schedule file: " + file + " " + e.getMessage());
}
}
}
else {
log("ERROR: directory for ad-hoc schedules not found: " + requestDir);
}
// 2. schedule the ad-hoc tasks to run (ignore duplicates)
ArrayList<Task> newTasks = new ArrayList<Task>();
boolean updatePerforce = false;
synchronized (RServer.this) {
for (Schedule schedule : adhocSchedules) {
if (runningTasks.containsKey(schedule.getTaskName()) == false) {
try {
Task task = new Task(schedule);
newTasks.add(task);
runningTasks.put(task.getTaskName(), task);
// always update perforce for ad-hoc tasks
updatePerforce = true;
}
catch (Exception e) {
log("ERROR: failed to schedule script: " + e.getMessage());
}
}
else {
log("ERROR: The schedule is already running: " + schedule.getTaskName());
}
}
adhocSchedules.clear();
}
// 3. check if any regular schedules should run
for (Schedule schedule : regularSchedules) {
if (System.currentTimeMillis() > schedule.getNextRunTime()) {
synchronized (RServer.this) {
if (runningTasks.get(schedule.getTaskName()) == null) {
try {
Task task = new Task(schedule);
newTasks.add(task);
runningTasks.put(task.getTaskName(), task);
schedule.setNextRunTime(false);
// update perforce?
if (PerforceTask.equalsIgnoreCase(task.getTaskName())) {
updatePerforce = true;
}
}
catch (Exception e) {
log("ERROR: failed to schedule script: " + e.getMessage());
}
}
}
}
}
// 4. update perforce in the main server thread if necessary
if (updatePerforce) {
log("Updating Git files");
try {
GitScript.update(isLinux, gitDepot);
}
catch (Exception e) {
log("Git update failed due to Excepton: " + e.getMessage());
sendEmail(serverAdmin, "Gitfailure on R Server",
"Git update failed due to IOExcepton: " + e.getMessage());
}
regularSchedules = loadSchedules(false);
lastPerforceUpdate = System.currentTimeMillis();
log("Git Update Completed");
}
// 5. set up the working directories for the new tasks
for (Task task : newTasks) {
try {
if (PerforceTask.equalsIgnoreCase(task.getTaskName())) {
continue;
}
File taskDir = new File(scriptPath + task.getTaskName());
if (taskDir.exists()) {
deleteDirectory(taskDir);
}
if (taskDir.mkdir()) {
File sourceDir = new File(perforceBase + task.getPerforcePath().replace("//", "/"));
if (sourceDir.exists()) {
copyDirectory(sourceDir, taskDir, false);
}
else {
log("ERROR: Invalid perforce directory for " + task.getTaskName() + ": " + task.getPerforcePath() + " ");
}
}
else {
log("ERROR: unable to make working directory for task: " + task.getTaskName() + " ");
}
}
catch (Exception e) {
log("ERROR: Error creating working directory for task: " + task.getTaskName() + ", " + e.getMessage());
}
}
// 6. Run each task in a new thread
for (Task task : newTasks) {
new Thread() {
public void run() {
try {
Thread.currentThread().setName("Task: " + task.getTaskName());
runTask(task);
}
catch (Exception e) {
log("ERROR: Running task: " + task.getTaskName() + ": " + e.getMessage());
}
}
}.start();
}
}
/**
* Runs the R script for the given task.
* Copies the Rout file to the server. Sends out an email with the outcome of the script.
*
* Method overview
* ---------------
* 1. Create a batch file to run the R script
* 2. Run the batch file as a new process and get the process ID
* 3. Wait for the process to complete
* 4. Check the outcome of the R Script
* 5. Copy the Rout file to the server
* 6. Email out the results
* 7. Mark the task as completed
*/
private void runTask(Task task) {
// if this is a Perforce task, update the web directories
if (PerforceTask.equalsIgnoreCase(task.getTaskName())) {
// copy R Package files to the wamp server
// Also: copy supporting web files to the base RServer direcotry
long time = System.currentTimeMillis();
copyDirectory(new File(perforceBase + perforceWWW),
new File(wampWWW + "/RServer"), true);
log("Updated web directory: " + (System.currentTimeMillis() - time) + " ms");
}
// update the status of the job
updateJobStatus(task.getJobId(), "Running", null);
try {
task.setOutcome(PerforceTask.equalsIgnoreCase(task.getTaskName()) ? "" : "Failure");
// get the task directory
File taskDir = new File(scriptPath + task.getTaskName());
File sourceDir = new File(perforceBase + task.getPerforcePath().replace("//", "/"));
if (taskDir.exists() && sourceDir.exists()) {
int result = 0;
// Run the task on Linux
if (isLinux) {
String command = "R CMD BATCH " // Linux Edit
+ (task.getParameters().length() > 0 ? "\"--args " + task.getParameters() + "\" " : "")
+ task.getrScript();
ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
pb.directory(new File(taskDir.getAbsolutePath()));
Process process = pb.start();
// Get the PID
try {
Field f = process.getClass().getDeclaredField("pid");
f.setAccessible(true);
task.setPID((int)f.get(process));
}
catch (Exception e) {
log("ERROR: unable to get PID for task: " + e.getMessage());
}
// 3. Wait for the process to complete
result = process.waitFor();
}
// run the task on Linux
else {
// 1. Create a batch file to run the R script
File batchFile = new File(taskDir.getPath() + "/run.bat");
BufferedWriter writer = new BufferedWriter(new FileWriter(batchFile));
writer.write("cd \"" + taskDir.getAbsolutePath() + "\"\n");
// Run an R Script
log("Running R Script: " + task.getTaskName());
writer.write("\"" + rPath + "\"R CMD BATCH "
+ (task.getParameters().length() > 0 ? "\"--args " + task.getParameters() + "\" " : "")
+ task.getrScript() + "\n" );
writer.close();
// 2. Run the batch file as a new process and get the process ID
Process process = new ProcessBuilder(batchFile.getAbsolutePath()).start();
// 3. Wait for the process to complete
result = process.waitFor();
}
// 4. Check the outcome of the R Script
boolean errorInScipt = false;
StringBuffer output = new StringBuffer();
File resultsFile = new File(taskDir.getPath() + "/" + task.getrScript() + ".Rout");
if (!resultsFile.exists()) { // DEAL with how Rout files are named (uppercase R means no .r in File name)
resultsFile = new File(taskDir.getPath() + "/" + task.getrScript().split("\\.")[0] + ".Rout");
}
if (resultsFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
String line = reader.readLine();
while (line != null) {
if (line.startsWith("Execution halted")) {
errorInScipt = true;
}
output.append(line + "\n");
line = reader.readLine();
}
reader.close();
}
// 5. Copy the Rout file to the server
Calendar today = Calendar.getInstance();
String outputDir = "output_" + today.get(Calendar.YEAR) + "-" +
(today.get(Calendar.MONTH) + 1) + "-" + today.get(Calendar.DAY_OF_MONTH);
if (new File(routDir + outputDir).exists() == false) {
new File(routDir + outputDir).mkdir();
}
task.setRout(outputDir + "/" + task.getTaskName() + "_" + System.currentTimeMillis()%100000 + ".Rout");
File outputFile = new File(routDir + task.getRout());
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(outputFile));
outputWriter.write(output.toString());
outputWriter.close();
// make the file readable from PHP
if (isLinux) {
Runtime.getRuntime().exec("sudo chmod 0777 " + outputFile).waitFor();
}
// 6. Email out the results
// check if process was cancelled
if (task.getAborted()) {
task.setOutcome ("Terminated");
log("R Script was aborted: " + task.getTaskName());
}
// check if process failed
else if (result > 0 || !resultsFile.exists()) {
// Execution error during the script
if (errorInScipt) {
log("ERROR: R Script failed during execution: " + task.getTaskName());
}
// unable to run R script
else {
log("ERROR: Unable to run R Script: " + task.getTaskName());
}
String url = "http://" +fullHostName + "/RServer/Rout/" + task.getRout();
sendEmail(task.getOwner(), "R Script Failed: " + task.getTaskName(),
"The R Script failed: " + task.getTaskName() + "\n" +
"Link to Rout file: " + url + "\n\n" +
"Output from R Script:\n" + output.toString());
}
// check if process compeleted
else {
task.setOutcome("Success");
log("R Script completed successfully: " + task.getTaskName());
if (task.getEmailOnSuccess()) {
String url = "http://" + fullHostName + "/RServer/Rout/" + task.getRout();
sendEmail(task.getOwner(), "R Script completed: " + task.getTaskName(),
"The R Script completed successfully: " + task.getrScript() + "\n\n" +
"Link to Rout file: " + url);
}
}
}
}
catch (Exception e) {
log("ERROR: running script: " + e.getMessage());
sendEmail(task.getOwner(), "R Script Failed: " + task.getTaskName(),
"The R Script failed to complete: " + task.getTaskName() + "\n\n" +
e.getMessage() + "\n" + e);
sendEmail(serverAdmin, "R Script Failed: " + task.getTaskName(),
"The R Script failed to complete: " + task.getTaskName() + "\n\n" +
e.getMessage() + "\n" + e);
}
// 7. Mark the task as completed
synchronized (RServer.this) {
runningTasks.remove(task.getTaskName());
task.setEndTime(System.currentTimeMillis());
completed.add(0, task);
if (completed.size() > completedTaskSize) {
completed.remove(completedTaskSize);
}
}
// update the status of the job
updateJobStatus(task.getJobId(), task.getOutcome(), task.getRout() != null ? "Rout/" + task.getRout() : "");
}
/**
* Updates the status of a Job.
*
* @param jobId - the job identifier
* @param status - the new status
* @param rout - a link to the .Rout file
*/
private void updateJobStatus(String jobId, String status, String rout) {
try {
if (jobId == null) {
return;
}
File dir = new File(jobsDir);
if (dir.exists()) {
String jobFile = jobsDir + "/" + jobId + ".csv";
BufferedWriter writer = new BufferedWriter(new FileWriter(jobFile));
writer.write("Status,rout\n");
writer.write(status + "," + (rout != null ? rout : "") + "\n");
writer.close();
}
else {
log("ERROR: unable to update job status: Jobs directory not found");
}
// check if we need to do some clean up
if (dir.exists()) {
if (dir.listFiles().length > maxJobFiles) {
File[] files = dir.listFiles();
Arrays.sort(files);
files[0].delete();
}
}
}
catch (Exception e) {
log("ERROR: unable to update job status: " + jobId + " " + status + " :" + e.getMessage());
}
}
/**
* Copies all files from the source directory to the target directory.
*/
private void copyDirectory(File sourceDir, File targetDir, boolean overwrite) {
try {
for (File file : sourceDir.listFiles()) {
if (file.isDirectory()) {
File newDir = new File(targetDir.getPath() + "/" + file.getName());
if (newDir.mkdir() || overwrite == true) {
copyDirectory(file, newDir, overwrite);
}
else {
log("ERROR: unable to create directory: " + newDir);
}
}
else {
File targetFile = new File(targetDir.getPath() + "/" + file.getName());
try {
// NOTE: Using file channels, because the source file is read-only and the target needs to be writtable
// delete the target file if it already exists
if (targetFile.exists()) {
targetFile.delete();
}
// copy the file
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(targetFile);
FileChannel inputChannel = inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
inputStream.close();
outputStream.close();
}
catch (Exception e) {
log("ERROR: unable to copy file to script directory: " + targetFile);
e.printStackTrace();
}
}
}
}
catch (Exception e) {
log("ERROR: copying working directory failed: " + e.getMessage() + " source: " + sourceDir + " target: " + targetDir);
e.printStackTrace();
}
}
/**
* Delete a directory (recursive)
*/
private void deleteDirectory(File dir) {
try {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
if (file.delete() == false) {
log("ERROR: unable to delete directory: " + file);
}
}
}
if (dir.delete() == false) {
log("ERROR: unable to delete directory: " + dir);
}
}
catch (Exception e) {
log("ERROR: deleting directories failed: " + e.getMessage());
}
}
/**
* Loads the schedules from the schedule file in the perforce directory.
*/
private ArrayList<Schedule> loadSchedules(boolean firstLoad) {
try {
log("Updating Schedule: " + schedulePath);
File file = new File(schedulePath);
if (!file.exists()) {
log("ERROR: Schedule file not found");
return new ArrayList<Schedule>();
}
ArrayList<Schedule> schedules = new ArrayList<Schedule>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
line = reader.readLine(); // eat the header
while (line != null) {
Schedule schedule = Schedule.parseSchedule(line, firstLoad);
if (schedule != null) {
schedules.add(schedule);
}
else if (line.trim().length() > 0) {
log("ERROR: Problem loading schedule. Entry: " + line);
}
line = reader.readLine();
}
reader.close();
return schedules;
}
catch (Exception e) {
log("ERROR: loading schedules failed: " + e.getMessage());
return new ArrayList<Schedule>();
}
}
/**
* Sends out an email.
*/
private void sendEmail(String toAddress, String subject, String body) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", smtp);
Message msg = new MimeMessage(Session.getDefaultInstance(props));
msg.setFrom(new InternetAddress(serverEmail));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
msg.setSubject(subject);
msg.setText(body);
Transport.send(msg);
}
catch (Exception e) {
log("ERROR: unable to send email: " + subject + ", " + e.getMessage());
}
}
/**
* Prints the message to the console and appends the message to the daily server log file.
*/
private void log(String message) {
try {
System.out.println("Log - " + message);
synchronized(RServer.this) {
logEntries.add(0, new Date(System.currentTimeMillis()).toString() + ": " + message);
if (logEntries.size() > logHistorySize) {
logEntries.remove(logHistorySize);
}
}
Calendar today = Calendar.getInstance();
String errorFile = logDir + "log_" + today.get(Calendar.YEAR) + "-" +
(today.get(Calendar.MONTH) + 1) + "-" + today.get(Calendar.DAY_OF_MONTH);
FileWriter fileWriter = new FileWriter(errorFile, true);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(new Date(System.currentTimeMillis()).toString() + ": " + message + "\n");
writer.close();
}
catch (Exception e) {
System.err.println("Failure during logging: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Generates the index.php file for the server dashboard.
*/
private void updateServerStatus() {
try {
StringBuffer page = new StringBuffer();
// php sign-in
page.append("<?php\n");
page.append("session_start();\n");
page.append("$username = 'Guest';\n");
page.append("if (array_key_exists('username', $_SESSION)) { $username = $_SESSION['username']; }\n");
page.append("?>\n");
// html header
page.append("<html>\n<head>\n <title>R Server</title>\n");
page.append(" <script>\n");
page.append(" function reload() { \n");
page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n");
page.append(" if (!isIE) location.reload();\n");
page.append(" }\n");
page.append(" setTimeout(reload, " + pageRefreshTime + ")\n");
page.append(" </script>\n");
page.append(" <link rel=\"stylesheet\" type=\"text/css\" href=\"rserver.css\">\n");
// html body
page.append("</head>\n<body>\n");
page.append("<div id=\"MainDiv\">\n\n");
// header
page.append("<div id=\"HeaderDiv\">\n");
page.append(" <div id=\"NavHeaderDiv\"></div>\n");
page.append(" <div id=\"NavLogo\"></div>\n");
page.append(" <a id=\"newHeaderNavigation-logo\" href=\"/RServer\" title=\"R Server\"></a>\n");
// links
page.append(" <ul id=\"NavBar\">\n");
page.append(" <li><a href=\"https://github.com/bgweber/RServer\">EA RServer</a></li>\n");
page.append(" <li><a href=\"NewTask.php\">Submit New Task</a>\n");
page.append(" <li><a href=\"Reports.php\">Reports</a></li>\n");
page.append(" <li><a href=\"logs\">Server Logs</a></li>\n");
page.append(" <li><a href=\"Rout\">Script Results</a></li>\n");
page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n");
page.append(" </ul>\n\n");
page.append("</div>\n\n");
// sub-header
page.append(" <div id=\"SubHeaderDiv\">\n");
page.append(" <h2 id=\"RHeader\">R Server: </h2>\n");
page.append("<?php if ((time() - " + System.currentTimeMillis()/1000 + ") < 10) { "
+ "echo \"<h2 id=\\\"ServerOnline\\\">Online</h2>\"; } else { "
+ "echo \"<h2 id=\\\"ServerOffline\\\">Offline</h2>\"; } ?>\n");
page.append(" </div>\n\n");
// IE Warning
page.append(" <div id=\"ContentDiv\">\n");
page.append(" <script>\n");
page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n");
page.append(" if (isIE) document.write('<p><h2>Note: Auto-reload is disabled for Internet Explorer. Please use Chrome, Firefox, or Opera.<h2>'); \n");
page.append(" </script>\n");
// server status
page.append("<h3 id=\"StatsHeader\">Server Statistics</h3>\n");
page.append("<table id=\"StatsTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Property</th>\n <th>Value</th>\n");
page.append(" </thead>\n");
if (fullHostName != null) {
page.append(" <tr><td>Server Name</td><td>" + fullHostName + "</td></tr>\n");
}
page.append(" <tr><td>Server Updated</td><td>" + new Date(System.currentTimeMillis()).toString() + "</td></tr>\n");
Runtime runtime = Runtime.getRuntime();
String memory = ((runtime.totalMemory() - runtime.freeMemory())/1024/1024) + " / " + ((runtime.totalMemory())/1024/1024) + " MB";
try {
double totalMem = sigar.getMem().getTotal()/1024/1024/1024.0;
double usedMem = (sigar.getMem().getTotal() - sigar.getMem().getFree())/1024/1024/1024.0;
cpuLoad = 1 - sigar.getCpuPerc().getIdle();
totalMem = ((int)(totalMem*10))/10.0;
usedMem = ((int)(usedMem*10))/10.0;
page.append(" <tr><td>Server CPU Usage</td><td>" + (((int)(cpuLoad*1000))/10.0) + "%</td></tr>\n");
page.append(" <tr><td>Server Memory</td><td>" + usedMem + " / " + totalMem + " GB</td></tr>\n");
}
catch (Exception e) {
log("ERROR: unable to update system stats: " + e.getMessage());
}
page.append(" <tr><td>Application Memory</td><td>" + memory + "</td></tr>\n");
page.append(" <tr><td>Thread Count</td><td>" + Thread.activeCount() + "</td></tr>\n");
page.append(" <tr><td>Git Updated</td><td>" + (lastPerforceUpdate > 0 ?
new Date(lastPerforceUpdate).toString() : "No history") + "</td></tr>\n");
page.append(" <tr><td>Server Launched</td><td>" + new Date(bootTime).toString() + "</td></tr>\n");
page.append(" <tr><td>Server Version</td><td>" + ServerDate + "</td></tr>\n");
page.append("</table>\n\n");
// report links
page.append("<h3 id=\"LogHeader\">R Server Reports</h3>\n");
page.append("<ul id=\"LogList\">\n");
page.append(" <li><a href=\"reports/RServer/RServerReport.html\">R Server Activity</a></li>\n");
page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n");
page.append("</ul>\n");
// currently running tasks
page.append("<h3 id=\"RunningHeader\">Running Tasks</h3>\n");
page.append("<table id=\"RunningTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>Log File</th>\n <th>Start Time</th>\n <th>Duration</th>\n "
+ "<th>Runtime Parameters</th>\n <th>Owner</th>\n <th>End Process</th>\n");
page.append(" </thead>\n");
synchronized (RServer.this) {
for (Task task : runningTasks.values()) {
long startTime = task.getStartTime();
long duration = (System.currentTimeMillis() - startTime)/1000;
page.append(" <tr>\n");
page.append(" <td>" + (task.getShinyApp() ? "<a href=\"" + task.getShinyUrl() + "\">" : "")
+ task.getTaskName() + (task.getShinyApp() ? "</a>" : "") + "</td>");
if (task.getrScript().toLowerCase().contains(".r") || task.getIsPython()) {
String link = "<a href=\"Rout.php?task=" + task.getTaskName() + "&log=" +
(task.getrScript().contains(".r") ? task.getrScript() + ".Rout" :
task.getrScript().split("\\.")[0] + ".Rout")
+ "\">" + task.getrScript() + "</a>";
page.append("\n <td>" + link + "</td>");
}
else {
page.append("\n <td> </td>");
}
page.append("\n <td>" + new Date(startTime).toString() + "</td>");
page.append("\n <td>" + (task.getShinyApp() ? "" : (duration/60 + " m " + duration%60 + " s")) + "</td>");
page.append("\n <td>" + task.getParameters() + "</td>");
page.append("\n <td>" + task.getOwner() + "</td>");
if (PerforceTask.equalsIgnoreCase(task.getTaskName())) {
page.append("\n <td> </td>");
}
else {
page.append("\n <td><form onsubmit=\"return confirm('Are you sure?')\""
+ " action=\"KillTask.php\" method=\"post\">"
+ "\n <input type=\"hidden\" name=\"name\" value=\"" + task.getTaskName() + "\" />"
+ "\n <button"
+ " >Terminate</button>\n </form></td>");
}
page.append("\n </tr>\n");
}
}
page.append("</table>\n\n");
// Recent log history
page.append("<h3 id=\"LogHeader\">Recent Log Entries</h3>\n");
synchronized(RServer.this) {
page.append("<ul id=\"LogList\">\n");
for (String log : logEntries) {
if (log.contains("ERROR:")) {
page.append(" <li class=\"FontLogError\">" + log + "</li>\n");
}
else {
page.append(" <li>" + log + "</li>\n");
}
}
page.append("</ul>\n\n");
}
// schedules
page.append("<h3 id=\"SchedulesHeader\">Scheduled Tasks</h3>\n");
page.append("<table id=\"ScheduleTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>R Script</th>\n <th>Runtime Parameters</th>\n <th>Frequency</th>\n "
+ "<th>Next Run Time</th>\n <th>Owner</th>\n <th>Run Now</th>\n");
page.append(" </thead>\n");
page.append("<ul id=\"LogList\">\n");
if (schedulePath.split("//").length > 1) {
page.append(" <li>Schedule File: //" + schedulePath.split("//")[1] + "</li>\n");
}
else {
page.append(" <li>Schedule File: " + schedulePath + "</li>\n");
}
page.append("</ul>\n");
for (Schedule schedule : regularSchedules) {
page.append(" <tr>\n");
page.append(" <td>" + schedule.getTaskName().replace("_", " ") + "</td>\n "
+ "<td>" + schedule.getrScript().replace("_", " ") + "</td>\n "
+ "<td>" + schedule.getParameters() + "</td>\n "
+ "<td>" + (schedule.getFrequency() == Schedule.Frequency.Now ? "Startup" : schedule.getFrequency()) + "</td>\n <td>"
+ (schedule.getFrequency() == Schedule.Frequency.Now || schedule.getFrequency() == Schedule.Frequency.Never ? " " : new Date(schedule.getNextRunTime()).toString())
+ "</td>\n <td>" +schedule.getOwner() + "</td>\n "
+ "<td><form onsubmit=\"return confirm('Are you sure?')\""
+ " action=\"SubmitTask.php\" method=\"post\">"
+ "\n <input type=\"hidden\" name=\"name\" value=\"" + schedule.getTaskName() + "\" />"
+ "\n <input type=\"hidden\" name=\"path\" value=\"" + schedule.getPerforcePath() + "\" />"
+ "\n <input type=\"hidden\" name=\"rscript\" value=\"" + schedule.getrScript() + "\" />"
+ "\n <input type=\"hidden\" name=\"email\" value=\"" + schedule.getOwner() + "\" />"
+ "\n <input type=\"hidden\" name=\"sendemail\" value=\"" + schedule.getEmailOnSuccess() + "\" />"
+ "\n <input type=\"hidden\" name=\"params\" value=\"" + schedule.getParameters() + "\" />"
+ "\n <input type=\"hidden\" name=\"shiny\" value=\"" + schedule.getShinyApp() + "\" />"
+ "\n <button"
+ ">Start</button>\n </form></td>\n");
page.append(" </tr>\n");
}
page.append("</table>\n\n");
// completed tasks
page.append("<h3 id=\"CompletedHeader\">Completed Tasks</h3>\n");
page.append("<table id=\"CompletedTable\">\n");
page.append(" <thead>\n");
page.append(" <th>Task Name</th>\n <th>Completion Time</th>\n <th>Duration</th>\n "
+ "<th>Runtime Parameters</th>\n <th>Outcome</th><th>.Rout log</th>\n <th>Owner</th>\n");
page.append(" </thead>\n");
synchronized (RServer.this) {
for (Task task : completed) {
long duration = (task.getEndTime() - task.getStartTime())/1000;
page.append(" <tr>\n");
page.append(" <td>" + task.getTaskName().replace("_", " ") + "</td>\n <td>");
page.append(" " + new Date(task.getEndTime()).toString() + "</td>\n <td>");
page.append(" " + (duration/60 + " m " + duration%60 + " s ") + "</td>\n <td>");
page.append(" " + task.getParameters() + "</td>\n <td>");
page.append(" " + (task.getOutcome().equals("Success") ? "<font class=\"FontTaskSuccess\">" : "<font class=\"FontTaskFailure\">"));
page.append(" " + task.getOutcome() + "</font></td>\n <td>");
if (task.getRout() != null) {
page.append("<a href=\"Rout.php?path=" + task.getRout() + "&log=" + task.getrScript() + ".Rout\">" + task.getrScript().replace("_", " ") + "</a></td>\n");
}
else {
page.append(" </td>\n");
}
page.append(" " + "<td>" + task.getOwner() + "</td>\n");
page.append(" </tr>\n");
}
}
page.append("</table>\n\n");
page.append("</div>\n\n");
page.append("<div id=\"FooterDiv\">\n");
page.append(" <a href=\"https://github.com/bgweber/RServer\">RServer on GitHub</a>\n");
page.append("</div>\n\n");
// html footer
page.append("</div>\n</body>\n</html>\n");
BufferedWriter writer = new BufferedWriter(new FileWriter(indexPagePath));
writer.write(page.toString());
writer.close();
}
catch (Exception e) {
log("ERROR: failure updating server status: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Logs system performance to a file.
*/
private void updatePerformaceLog() {
try {
Runtime runtime = Runtime.getRuntime();
double appUsedMem = (runtime.totalMemory() - runtime.freeMemory())/1024/1024;
double appTotalMem = (runtime.totalMemory())/1024/1024;
double totalMem = sigar.getMem().getTotal()/1024/1024/1024.0;
double usedMem = (sigar.getMem().getTotal() - sigar.getMem().getFree())/1024/1024/1024.0;
int threads = Thread.activeCount();
long currentTime = System.currentTimeMillis();
String logEntry = fullHostName + "," + bootTime + "," + currentTime + "," + cpuLoad + "," + threads + ","
+ appUsedMem + "," + appTotalMem + "," + usedMem + "," + totalMem + ","
+ updateHtmlTime + "," + updatePerfLogTime;
File logFile = new File(performanceLogDir + "/" + "ServerLoad.csv");
// File logFile = new File(performanceLogFile);
ArrayList<String> logData = new ArrayList<>();
if (logFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(logFile));
String line = reader.readLine();
line = reader.readLine(); // skip the header
while (line != null) {
logData.add(line);
line = reader.readLine();
}
reader.close();
}
while (logData.size() >= performanceLogSize) {
logData.remove(0);
}
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write("ServerName, BootTime, UpdateTime, CpuLoad, Threads, AppMemUsage(MB), AppMemTotal(MB), UsedMem(GB), TotalMeb(GB), HtmlUpdateTime, LogUpdateTime\n");
for (String log : logData) {
writer.write(log + "\n");
}
writer.write(logEntry + "\n");
writer.close();
}
catch (Exception e) {
log("ERROR: unable to update performace Log: " + e.getMessage());
}
}
/**
* Utility for loading system properties.
*/
public static String getProperty(String key, String value) {
return System.getProperty(key) != null ? System.getProperty(key) : value;
}
}
| bgweber/RServer | RServ/RServer.java |
247,820 | import java.awt.AWTException;
import java.awt.AWTKeyStroke;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.awt.AWTKeyStroke.getAWTKeyStroke;
import static java.awt.event.KeyEvent.SHIFT_DOWN_MASK;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author KIIT
*/
public class TyperXWorker
{
public static final int RUNNING = 1;
public static final int STOPPED = 0;
private final Robot robot;
private final TyperXView xFrame;
private final AtomicInteger isRunning;
private int startTime = 5;
private int keyStrokeDelay = 100;
private boolean removeFrontSpaces=false;
public TyperXWorker(TyperXView frame) throws AWTException
{
this.robot = new Robot();
this.xFrame = frame;
this.isRunning = new AtomicInteger(STOPPED);
}
public static AWTKeyStroke getKeyStroke(char c)
{
final String upperKeys = "`~'\"!@#$%^&*()_+{}|:<>?";
final String lowerKeys = "`~'\"1234567890-=[]\\;,./";
int index = upperKeys.indexOf(c);
if (index != -1) {
int keyCode;
boolean shift = false;
switch (c) {
// these chars need to be handled specially because
// they don't directly translate into the correct keycode
case '~':
keyCode=192;
shift=true;
break;
case '\"':
keyCode=222;
shift = true;
break;
case '`':
keyCode = KeyEvent.VK_BACK_QUOTE;
break;
case '\'':
keyCode = KeyEvent.VK_QUOTE;
break;
default:
keyCode = Character.toUpperCase(lowerKeys.charAt(index));
shift = true;
}
return getAWTKeyStroke(keyCode, shift ? SHIFT_DOWN_MASK : 0);
}
return getAWTKeyStroke(Character.toUpperCase(c), 0);
}
private void pressKey(char c, int miliSec)
{
AWTKeyStroke keyStroke = getKeyStroke(c);
int keyCode = keyStroke.getKeyCode();
boolean isShiftRequired = Character.isUpperCase(c) || keyStroke.getModifiers() == (InputEvent.SHIFT_MASK | SHIFT_DOWN_MASK);
if (isShiftRequired) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
try{
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (miliSec > 0) {
Thread.sleep(miliSec);
}
} catch (Exception exception) {
System.out.println("Error typing " + KeyEvent.getKeyText(keyCode));
exception.printStackTrace();
}
if (isShiftRequired) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
private void sendKeys(String keys)
{
Runnable typerRunnable = () -> runTyper(keys);
Thread thread = new Thread(typerRunnable);
thread.start();
}
private void runTyper(String keys)
{
if (removeFrontSpaces){
keys=removeFrontSpaces(keys);
}
for (int i = 0; i < startTime; i++) {
if (isRunning.get() == STOPPED) {
break;
}
this.xFrame.setStatus("Starting typing in " + (startTime - i) + " sec");
try{
Thread.sleep(1000L);
} catch (InterruptedException ex) {
Logger.getLogger(TyperXFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.xFrame.setStatus("Running now..");
char[] charArray = keys.toCharArray();
int numDigits = String.valueOf(charArray.length).length() - 2;
long typeStartTime = System.currentTimeMillis() / 1000;
long currentTime = 0;
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
if (isRunning.get() == STOPPED) {
break;
}
try{
pressKey(c, keyStrokeDelay);
int progress = (i * 100) / charArray.length;
this.xFrame.setProgress(progress);
/*
* Take a pause after x seconds. Simulates somewhat of human typing habits.
* x = number digits in the length of characters of the input string - 2
* multiplied by 10 (seconds). The pauses are length dependent, so that it
* stop very frequently for long paragraphs and stop adequetly for short paragraphs
*/
currentTime = System.currentTimeMillis() / 1000;
if((currentTime > typeStartTime) && ((currentTime - typeStartTime) % (10 * numDigits) == 0)) {
Thread.sleep(2000L);
}
} catch (Exception ex) {
Logger.getLogger(TyperXFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
xFrame.startUI();
this.isRunning.set(STOPPED);
}
public void startRequest(String text)
{
if (isRunning.compareAndSet(STOPPED, RUNNING)) {
xFrame.stopUI();
String converted=text.replace("\t"," ").replaceAll("[^\\x00-\\x7F]", " ");
this.sendKeys(converted);
}
}
public void stopRequest()
{
if (this.isRunning.compareAndSet(RUNNING, STOPPED)) {
xFrame.startUI();
}
}
public String removeFrontSpaces(String text){
String[] lines = text.split("\\r?\\n");
StringBuilder builder=new StringBuilder();
for (String line : lines){
builder.append(line.replaceFirst("\\s+","")).append("\n");
}
return builder.toString();
}
public int getStartTime()
{
return startTime;
}
public void setStartTime(int startTime)
{
this.startTime = startTime;
}
public int getKeyStrokeDelay()
{
return keyStrokeDelay;
}
public void setKeyStrokeDelay(int keyStrokeDelay)
{
this.keyStrokeDelay = keyStrokeDelay;
}
public boolean isRemoveFrontSpaces() {
return removeFrontSpaces;
}
public void setRemoveFrontSpaces(boolean removeFrontSpaces) {
this.removeFrontSpaces = removeFrontSpaces;
}
}
| Meghdut-Mandal/TyperX | src/TyperXWorker.java |
247,823 | import java.util.ArrayList;
/**
* CLI for the Customer's perspective.
* Provides an entry point for the system.
* @author Lane Lawley <[email protected]>
* @author Kyle Savarese <[email protected]>
* @author Sol Boucher <[email protected]>
* @author Piper Chester <[email protected]>
*/
public class CustomerCLI {
/**
* Prints out an error message if the user is trying to start a machine without an ID."
*/
private static void usage() {
System.err.println("In order to start a machine, you need to enter a valid ID.");
}
/**
* The main entry point to the program.
*/
public static void main(String[] args) {
if(args.length != 1) {
usage();
System.exit(1);
}
CustomerLoginScreen backend = null;
try {
backend = CustomerLoginScreen.buildInstance(Integer.parseInt(args[0]));
}
catch(NumberFormatException wrong) {
usage();
System.err.println("<machine ID> must be an integer");
System.exit(1);
}
if(backend == null) {
usage();
System.err.println("Supplied <machine ID> is either invalid or inactive");
System.exit(1);
}
System.out.println("Welcome to HCLC, LLC's Smart Vending Machine!\n---\n");
program:while(true) {
CLIUtilities.printTitle("Main Menu");
int cashOrId = CLIUtilities.option("I'm paying with cash", "I'll enter my customer ID", "I want to exit");
switch(cashOrId) {
case 0:
anonymousConnection(backend.cashLogin());
break;
case 1:
CustomerPurchaseScreen next = null;
do {
int id = CLIUtilities.promptInt("Please enter your customer ID");
next = backend.tryLogin(id);
} while (next == null);
productSelection(next);
break;
case 2:
break program;
}
}
System.out.println("Goodbye!");
}
/**
* Facility allowing someone without an account to use the machine.
* @param wallet the backend connection
*/
private static void anonymousConnection(CashCustomerPurchaseScreen wallet) {
screen:while(true) {
CLIUtilities.printTitle("Cash Payment");
System.out.println("You've added " + U.formatMoney(wallet.getBalance()) + " to this machine.");
int addOrSubtract = CLIUtilities.option("I want to insert cash", "I'm ready to purchase an item", "Return to main menu");
switch(addOrSubtract) {
case 0:
wallet.addCash(CLIUtilities.moneyPrompt("Insert money"));
break;
case 1:
productSelection(wallet);
break;
case 2:
System.out.println("Your change is " + U.formatMoney(wallet.getBalance()));
break screen;
}
}
}
/**
* Facility allowing someone with an account to login.
* @param account the backend connection
*/
private static void productSelection(CustomerPurchaseScreen account) {
FoodItem[][] display = account.listLayout();
screen:while(true) {
CLIUtilities.printTitle("Product Selection");
System.out.println("Welcome, " + account.getUserName() + "!");
System.out.println("Available funds: " + U.formatMoney(account.getBalance()));
int choice = CLIUtilities.option(
"Choose from vending machine layout",
"Choose from frequently bought items",
"Cancel purchase");
switch (choice)
{
case 0:
CLIUtilities.printLayout(display);
if(CLIUtilities.yesOrNo("Would you like to proceed with your purchase?")) {
String message=account.tryPurchase(new Pair<Integer, Integer>(CLIUtilities.promptInt("Enter X", true), CLIUtilities.promptInt("Enter Y", true)));
if(message.equals("Good")) {
System.out.println("Purchase complete: remaining balance is " + U.formatMoney(account.getBalance()));
break screen;
}
else
CLIUtilities.prompt(message + " please press enter to continue");
} else {
break screen; // BREAK THE SCREEN
}
break;
case 1:
ArrayList<FoodItem> items = account.getFrequentlyBought();
if (items.size() == 0)
{
CLIUtilities.prompt("You have no frequently bought items!\nplease press enter to continue");
break;
}
int chosenIndex = CLIUtilities.option(items);
String freqMessage = account.tryPurchase(items.get(chosenIndex));
if (freqMessage.equals("Good"))
{
System.out.println("Purchase complete: remaining balance is " + U.formatMoney(account.getBalance()));
break screen;
}
else
{
CLIUtilities.prompt(freqMessage + " please press enter to continue");
}
break;
case 2:
break screen;
}
}
}
}
| bitbanger/hclc_vending_machine | src/CustomerCLI.java |
247,824 | 404: Not Found | OurPeeGee/RPG-QUEST- | src/TestDriver.java |
247,826 | /*
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
*/
// O(mn)
// First flip top to bottom
// Then flip from top-left to bottom-right
// Since the swap operation is frequently used, we create a swap method
public class Solution {
public void rotate(int[][] matrix) {
int row = matrix.length;
int col = row;
// flip top to bottom
for(int i = 0; i < row / 2; i++) {
for(int j = 0; j < col; j++) {
swap(matrix, i, j, row - i - 1, j);
}
}
for(int i = 0; i < row; i++) {
// !!! j = i !!!
for(int j = i; j < col; j++) {
swap(matrix, i, j, j, i);
}
}
}
void swap(int[][] matrix, int r1, int c1, int r2, int c2) {
int temp = matrix[r1][c1];
matrix[r1][c1] = matrix[r2][c2];
matrix[r2][c2] = temp;
}
}
// Divide the image into row/2 layers.
// Doing the rotation: top to right, right to bottom, bottom to left, left to top.
// We can use a temporary integer to do the swap operation.
// So the time: O(mn), space O(1)
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0 || matrix[0].length==0)
return;
int layerNum = matrix.length/2;
for(int layer=0;layer<layerNum;layer++)
{
for(int i=layer;i<matrix.length-layer-1;i++)
{
int temp = matrix[layer][i];
matrix[layer][i] = matrix[matrix.length-1-i][layer];
matrix[matrix.length-1-i][layer] = matrix[matrix.length-1-layer][matrix.length-1-i];
matrix[matrix.length-1-layer][matrix.length-1-i] = matrix[i][matrix.length-1-layer];
matrix[i][matrix.length-1-layer] = temp;
}
}
}
| kidchen/InterviewPreparation | RotateImage.java |
Subsets and Splits