text stringlengths 14 410k | label int32 0 9 |
|---|---|
private int bestMove(int rm,int rw, int pm, int pw, int sm, int sw){
int bestMove = 0;
ArrayList<Double> move = new ArrayList<>();
if(rm!=0||rw==0){
move.add((double)rw/(double)rm);
}
if(pm!=0||pw==0){
move.add((double)pw/(double)pm);
}
if(sm!=0||sw==0){
move.add((double)pw/(double)pm);
}
if(move.size()>0){
for(int i = 0;i<move.size()-1;i++){
if(move.get(i)<move.get(i+1)){
bestMove = i+1;
}
}
return bestMove+1;
}else{
return new Random().nextInt(3);
}
} | 9 |
@Test
public void validaNome(){
assertTrue("Valida nome: ", validadorUsuarios.validaNome("ams") == true);
} | 0 |
private void readFrames(LittleEndianInputStream in, int ver)
throws IOException {
int numPoints = in.readUnsignedShort();
int alpha = 0;
if (ver == 8) {
switch (in.readShort()) {
case 0: break;
case 1: alpha = 1; break;
case 0x101: alpha = 4; break;
default: throw new FileFormatException("Unknown point size");
}
}
Vertex[] coords = new Vertex[numPoints];
for (int i = 0; i < numPoints; i++) {
Vertex point = new Vertex();
point.x1 = in.readShort();
point.y1 = in.readShort();
if (ver == 4) in.readShort();
point.x2 = in.readShort();
point.y2 = in.readShort();
for (int j = 0; j < alpha; j++)
point.alpha = Math.min(point.alpha, in.readFloat());
coords[i] = point;
}
xMin = in.readShort();
xMax = in.readShort();
yMin = in.readShort();
yMax = in.readShort();
int numFrames = in.readUnsignedShort();
frames = new Frame[numFrames];
for (int i = 0; i < numFrames; i++) {
frames[i] = new Frame();
frames[i].read(in, ver, coords);
}
} | 8 |
public void setWindowBorderthickness(int[] border) {
if ((border == null) || (border.length != 4)) {
this.window_Borderthickness = UIBorderthicknessInits.WINDOW.getBorderthickness();
} else {
this.window_Borderthickness = border;
}
somethingChanged();
} | 2 |
@Override
public void paint(Graphics g) {
locationImg = CreateGUI.returnInstance().createImageIcon("img/location.png", "Location");
Graphics2D g2 = (Graphics2D) g;
paintComponent(g2);
if(dragging) {
g2.setColor(Color.RED);
if(rectWidth/rectHeight < preferredRatio) {
rectWidth = rectHeight * preferredRatio;
}
else if(rectWidth/rectHeight > preferredRatio) {
rectHeight = rectWidth / preferredRatio;
}
g2.draw(new Rectangle2D.Double(x2, y2, rectWidth, rectHeight));
}
if(dirFromNode != null) {
int size = 32;
Image locImg = locationImg.getImage();
Image newImg = locImg.getScaledInstance(size, size, 0);
locationImg = new ImageIcon(newImg);
locationImg.paintIcon(this, g2, (int)((dirFromNode.getX() - upperLeftX) / (1000/factor))-size/2, (int)((upperLeftY - dirFromNode.getY()) / (1000/factor)-(size*0.875)));
}
if(dirToNode != null) {
int size = 32;
Image locImg = locationImg.getImage();
Image newImg = locImg.getScaledInstance(size, size, 0);
locationImg = new ImageIcon(newImg);
locationImg.paintIcon(this, g2, (int)((dirToNode.getX() - upperLeftX) / (1000/factor))-size/2, (int)((upperLeftY - dirToNode.getY()) / (1000/factor)-(size*0.875)));
}
dragging = false;
} | 5 |
private boolean checkForWinHorizontal() {
for (int i = 0; i < COL_COUNT; i++) {
Cell cell4 = arrayOfLogicCells[0][i];
Cell cell5 = arrayOfLogicCells[1][i];
Cell cell6 = arrayOfLogicCells[2][i];
if (cell4.isZeroChecked() && cell5.isZeroChecked()
&& cell6.isZeroChecked()) {
isWin = false;
isLose = true;
gameOver = true;
return true;
} else if (cell4.isXChecked() && cell5.isXChecked()
&& cell6.isXChecked()) {
isWin = true;
isLose = false;
gameOver = true;
return true;
}
}
return false;
} | 7 |
public void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 3 |
public boolean writeWorld(String fileName) {
try {
worldWriter = new BufferedWriter(new FileWriter(fileName));
worldWriter.write(Integer.toString(rows));
worldWriter.newLine();
worldWriter.write(Integer.toString(columns));
worldWriter.newLine();
for (int i = 0; i < rows; i++) {
String currentLine = "";
if (i%2 != 0) {
currentLine += " ";
}
for (int j = 0; j < columns; j++) {
if (j != columns - 1) {
currentLine += world[i][j].toString() + " ";
} else {
currentLine += world[i][j].toString();
}
}
worldWriter.write(currentLine);
worldWriter.newLine();
}
worldWriter.close();
return true;
} catch (IOException ioe) {
return false;
}
} | 5 |
public boolean equals(VertexSet that){
return this.cityMap.keySet().equals(that.cityMap.keySet());
} | 0 |
public final void update() {
++chunkUpdates;
int var1 = this.x;
int var2 = this.y;
int var3 = this.z;
int var4 = this.x + this.width;
int var5 = this.y + this.height;
int var6 = this.z + this.depth;
int var7;
for(var7 = 0; var7 < 2; ++var7) {
this.dirty[var7] = true;
}
for(var7 = 0; var7 < 2; ++var7) {
boolean var8 = false;
boolean var9 = false;
GL11.glNewList(this.baseListId + var7, 4864);
renderer.begin();
for(int var10 = var1; var10 < var4; ++var10) {
for(int var11 = var2; var11 < var5; ++var11) {
for(int var12 = var3; var12 < var6; ++var12) {
int var13;
if((var13 = this.level.getTile(var10, var11, var12)) > 0) {
Block var14;
if((var14 = Block.blocks[var13]).getRenderPass() != var7) {
var8 = true;
} else {
var9 |= var14.render(this.level, var10, var11, var12, renderer);
}
}
}
}
}
renderer.end();
GL11.glEndList();
if(var9) {
this.dirty[var7] = false;
}
if(!var8) {
break;
}
}
} | 9 |
private synchronized void checkWinCondition() {
int playersWithMoney = 0;
int winningPlayer = -1;
for(int i = 0; i < players.size(); i++) {
if(players.get(i).getMoney() > 0 || players.get(i).getProperty().size() > 0) {
playersWithMoney++;
// No one has won yet
if(playersWithMoney > 1) {
winningPlayer = -1;
break;
}
// Assume current player won
else if(playersWithMoney == 1)
winningPlayer = players.get(i).getNumber();
}
}
if(winningPlayer != -1) {
JOptionPane.showMessageDialog(null, "Congradulations Player " + winningPlayer + "! You have won the game!", "VICTORY", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
} | 6 |
public void drawPiece( int lx, int ty, float red,
float green, float blue, Graphics screen)
{
Color newColor = new Color(red, green, blue);
Color newBorder = new Color( (red > 0.5f) ? red - 0.5f : red,
(green > 0.5f) ? green - 0.5f : green,
(blue > 0.5f) ? blue - 0.5f : blue);
screen.setColor(newColor);
screen.fillRect(lx, ty, BLOCKSIZE, BLOCKSIZE);
screen.setColor(newBorder);
screen.drawRect(lx, ty, BLOCKSIZE, BLOCKSIZE);
} | 3 |
public boolean hasPrev()
{
if (currentPiped == null)
return false;
else if (currentPiped.hasPrev())
return true;
else if (previousPiped != null)
return previousPiped.hasPrev();
else if (!in.hasPrev())
return false;
else while (true)
{
// TODO - This is not the optimal way to do things,
// we're relying on the fact that an application will
// not be scanning back and forth frentically, but that it
// will only occasionally need to look to a prev element.
// The problem is that when we execute the pipe query, we need
// to scan to the end of the result set so as to maintain linearity
// in the overall "PipedResult".
// A more intelligent buffering of previous result sets need
// to be implemented if this proves to be a bottleneck (e.g.
// have a static variable for buffer size and grow it as the need
// arises). Or perhaps we should simply forbid bidirectionality in those
// results simply because it cannot be implemented efficiently....
pipe.setKey(in.prev());
previousPiped = pipe.execute();
if (previousPiped.hasNext())
{
do { previousPiped.next(); } while (previousPiped.hasNext());
return true;
}
else
{
previousPiped.close();
previousPiped = null;
if (!in.hasPrev())
return false;
}
}
} | 8 |
public static HelloCorba.Hello unchecked_narrow (org.omg.CORBA.Object obj)
{
if (obj == null)
return null;
else if (obj instanceof HelloCorba.Hello)
return (HelloCorba.Hello)obj;
else
{
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
HelloCorba._HelloStub stub = new HelloCorba._HelloStub ();
stub._set_delegate(delegate);
return stub;
}
} | 2 |
public boolean setLoadingStatusWidth(int width) {
boolean ret = true;
if (width <= 0) {
this.loadingStatusWidth = 0;
ret = false;
} else {
this.loadingStatusWidth = width;
}
somethingChanged();
return ret;
} | 1 |
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (position == null)
{
if (other.position != null)
return false;
} else if (!position.equals(other.position))
return false;
if (velocity == null)
{
if (other.velocity != null)
return false;
} else if (!velocity.equals(other.velocity))
return false;
return true;
} | 9 |
public void setCriteriaHightlight(int type) {
HashMap<String, Integer> ranks = null;
if (type == CriteriaStatistics.PRODUCT)
ranks = rankVarianceScore();
else if (type == CriteriaStatistics.WEIGHT)
ranks = rankVarianceWeight();
else if (type == CriteriaStatistics.SCORE)
ranks = rankVarianceUtility();
if (ranks == null) return;
for (BaseTableContainer base : prims.values()) {
Integer rank = ranks.get(base.getName());
if (rank != null) {
base.setHighLight(rank);
}
}
} | 6 |
public void shoot(Point2D direcVect) {
if(direcVect != null){
adjustVect = SPEED_NORME / (Math.sqrt(Math.pow(direcVect.getX(), 2) + Math.pow(direcVect.getY(), 2)));
speedX = (float) (direcVect.getX() * adjustVect);
speedY = (float) (direcVect.getY() * adjustVect);
}
else{
speedX = DEFAULT_SPEEDX;
speedY = DEFAULT_SPEEDY;
}
} | 1 |
private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) {
// This is directly applying Forney's Formula
int s = errorLocations.length;
int[] result = new int[s];
for (int i = 0; i < s; i++) {
int xiInverse = field.inverse(errorLocations[i]);
int denominator = 1;
for (int j = 0; j < s; j++) {
if (i != j) {
//denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes
int term = field.multiply(errorLocations[j], xiInverse);
int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
denominator = field.multiply(denominator, termPlus1);
}
}
result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
field.inverse(denominator));
if (field.getGeneratorBase() != 0) {
result[i] = field.multiply(result[i], xiInverse);
}
}
return result;
} | 5 |
public boolean isPoweringTo(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5)
{
if (!this.isRepeaterPowered)
{
return false;
}
else
{
int var6 = getDirection(par1IBlockAccess.getBlockMetadata(par2, par3, par4));
return var6 == 0 && par5 == 3 ? true : (var6 == 1 && par5 == 4 ? true : (var6 == 2 && par5 == 2 ? true : var6 == 3 && par5 == 5));
}
} | 8 |
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
Point eventP = e.getPoint();
int layer = -1;
int number = 0;
for (int i = 0; i < ffnn.getLayers().size(); i++) {
if (layer != -1)
break;
for (int j = 0; j < ffnn.getLayers().get(i)
.getNeuronCount(); j++) {
Point neuronP = getNeuronPoint(i, j);
if (neuronP.distance(eventP) < neuronDiameter / 2) {
layer = i;
number = j;
break;
}
}
}
if (layer == -1)
return;
JPopupMenu popup = new JPopupMenu();
if (layer != 0) {
JMenuItem thresholdChangeItem = new JMenuItem(
"Change thershold");
thresholdChangeItem.setName("change threshold$" + layer
+ ":" + number);
thresholdChangeItem
.addActionListener(NeuralNetworkGUI.this);
popup.add(thresholdChangeItem);
}
JMenu changeWeightSubMenu = new JMenu("Change weight to ...");
changeWeightSubMenu.addActionListener(NeuralNetworkGUI.this);
if (layer != ffnn.getLayers().size() - 1) {
JMenuItem changeWeightItems[] = new JMenuItem[ffnn
.getLayers().get(layer + 1).getNeuronCount()];
for (int i = 0; i < changeWeightItems.length; i++) {
changeWeightItems[i] = new JMenuItem("neuron " + i);
changeWeightItems[i].setName("change weight$" + layer
+ ":" + number + "^" + i);
changeWeightItems[i]
.addActionListener(NeuralNetworkGUI.this);
changeWeightSubMenu.add(changeWeightItems[i]);
}
popup.add(changeWeightSubMenu);
}
popup.show((Component) e.getSource(), e.getX(), e.getY());
}
} | 9 |
public boolean subclassOf(CtClass superclass) {
if (superclass == null)
return false;
String superName = superclass.getName();
CtClass curr = this;
try {
while (curr != null) {
if (curr.getName().equals(superName))
return true;
curr = curr.getSuperclass();
}
}
catch (Exception ignored) {}
return false;
} | 4 |
public static StructureBoundingBox findValidPlacement(List par0List, Random par1Random, int par2, int par3, int par4, int par5)
{
StructureBoundingBox var6 = new StructureBoundingBox(par2, par3, par4, par2, par3 + 2, par4);
if (par1Random.nextInt(4) == 0)
{
var6.maxY += 4;
}
switch (par5)
{
case 0:
var6.minX = par2 - 1;
var6.maxX = par2 + 3;
var6.maxZ = par4 + 4;
break;
case 1:
var6.minX = par2 - 4;
var6.minZ = par4 - 1;
var6.maxZ = par4 + 3;
break;
case 2:
var6.minX = par2 - 1;
var6.maxX = par2 + 3;
var6.minZ = par4 - 4;
break;
case 3:
var6.maxX = par2 + 4;
var6.minZ = par4 - 1;
var6.maxZ = par4 + 3;
}
return StructureComponent.findIntersecting(par0List, var6) != null ? null : var6;
} | 6 |
public String getTitle() {
return this.title;
} | 0 |
public KeyStroke getKey() {
return KeyStroke.getKeyStroke('s');
} | 0 |
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} | 9 |
private double turnTo(double direction, double tickTime){
double dirDiff = direction - head.rotation;
while(dirDiff < -180f) dirDiff += 360f;
while(dirDiff > 180f) dirDiff -= 360f;
double sign = Math.signum(dirDiff);
// already done?
if(dirDiff * sign <= 0.5d){
headVel = 0d;
return 0d;
}
// already time to decelerate?
if(dirDiff * sign <= headVel * headVel / def.headAcceleration * 0.5f){
// decelerate
headVel -= sign * def.headAcceleration * tickTime;
if(headVel * sign < 0.5d) headVel = 0f;
} else {
// accelerate if still possible
headVel += sign * def.headAcceleration * tickTime;
if(headVel * sign > def.headMaxVel) headVel = sign * def.headMaxVel;
}
return dirDiff;
} | 6 |
private void calculate() {
/* Calculating thing */
int last = 0;
int level = 0;
Set<ControlNode> calculated_lines = new HashSet<>();
for (int k = 0; k < nested.algorithm.size(); k++) {
/* Searching thru all the ControlNodes... */
if (nested.algorithm.get(k) instanceof ControlNode) {
ControlNode cast = ((ControlNode) nested.algorithm.get(k));
if (cast.val == '(') level++;
if (cast.val == ')') level--;
/*... for a splitter... */
if ((cast.val == ';' && level == 0)) {
/*... and if we already calculated that line, then just updating last node. */
if (calculated_lines.contains(cast)) {
last = k + 1;
}
/* ... and if not - calculating value and adding line splitter to calculated values */
/* Then reseting cycle, 'cause something might added a new one. */
else {
nested.calculateSandboxed(last, k);
calculated_lines.add(cast);
last = k = 0;
}
}
}
}
/* Removing all splitters */
for (Node nd : calculated_lines)
nested.algorithm.remove(nd);
} | 8 |
public void add(E o) {
checkForComodification();
lastReturned = head;
if(next == null) { // append to the end of the list
if(append(o)) {
expectedModCount++;
}
} else {
if(addBefore(o, next)) { // returns true if successfully inserted
nextIndex++;
expectedModCount++;
}
}
} | 3 |
private void loadStudy(Study study) {
// Do nothing if nothing selected.
if(study == null)
return;
// Get previous display state.
DisplayState state = study.getDisplayState();
if(state == null) // No previous display state
MedImage.getImageView().viewImages(connection, study, 0, null, null);
else
MedImage.getImageView().viewImages(connection, study,
state.getImageIndex(), state.getCurrState(), state.getCommands());
} | 2 |
public boolean opEquals(Operator o) {
return (o instanceof ThisOperator && ((ThisOperator) o).classInfo
.equals(classInfo));
} | 1 |
public BatchPane()
{
frame = Frame.getInstance();
setLayout(null);
FileFilter filter = new FileTypeFilter(".data", "Text files");
dataChooser = new JFileChooser();
dataChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
dataChooser.setFileFilter(filter);
FileFilter filter2 = new FileTypeFilter(".ttb", "Text files");
ttbChooser = new JFileChooser();
ttbChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
ttbChooser.setFileFilter(filter2);
JButton backButton = new MainButton("/images/back.png", "/images/backHover.png");
backButton.setBounds(10, 0, 71, 51);
this.add(backButton, 0);
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setView(frame.getNextView(0));
}
});
JLabel label = new JLabel("BATCH CLASSIFICATION");
label.setFont(new Font("Century Gothic", Font.PLAIN, 24));
label.setForeground(Color.WHITE);
label.setBounds(145, 46, 475, 30);
label.setHorizontalAlignment(SwingConstants.RIGHT);
add(label);
JPanel line = new JPanel();
line.setBackground(new Color(255, 204, 51));
line.setBounds(145, 83, 475, 1);
add(line);
JLabel dLabel = new JLabel("Data");
dLabel.setFont(new Font("Century Gothic", Font.PLAIN, 20));
dLabel.setForeground(Color.WHITE);
dLabel.setBounds(388, 91, 54, 30);
add(dLabel);
JPanel cpanel = new JPanel();
cpanel.setBackground(new Color(255, 204, 51));
cpanel.setBounds(205, 135, 124, 30);
add(cpanel);
JLabel cLabel = new JLabel("Classifier");
cLabel.setFont(new Font("Century Gothic", Font.PLAIN, 16));
cLabel.setForeground(Color.BLACK);
cLabel.setBounds(0, 0, 75, 30);
cpanel.add(cLabel);
JPanel fPanel = new JPanel();
fPanel.setBackground(Color.LIGHT_GRAY);
fPanel.setBounds(330, 135, 260, 30);
fPanel.setLayout(null);
add(fPanel);
fileLabel = new JLabel("-no classifier selected-");
fileLabel.setFont(new Font("Century Gothic", Font.PLAIN, 14));
fileLabel.setForeground(Color.BLACK);
fileLabel.setBounds(4, 0, 260, 30);
fPanel.add(fileLabel);
JButton cButton = new MainButton("/images/pencil.png", "/images/pencil.png");
cButton.setBorderPainted(false);
cButton.setBounds(595, 135, 35, 33);
add(cButton);
cButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectClassifier();
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(255, 204, 51));
panel.setBounds(205, 195, 124, 30);
add(panel);
JLabel label2 = new JLabel("Test Data");
label2.setFont(new Font("Century Gothic", Font.PLAIN, 16));
label2.setForeground(Color.BLACK);
label2.setBounds(0, 0, 107, 23);
panel.add(label2);
final JTextField textField1 = new MyTextField("click to select test data");
textField1.setBounds(330, 195, 260, 30);
textField1.setBorder(null);
textField1.setFont(new Font("Century Gothic", Font.PLAIN, 16));
textField1.setBorder(BorderFactory.createCompoundBorder( textField1.getBorder(),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
add(textField1);
textField1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String path = selectDataFile();
if(new File(path).exists())
textField1.setText(path);
}
});
JButton tButton = new MainButton("/images/pencil.png", "/images/pencil.png");
tButton.setBounds(595, 195, 35, 33);
add(tButton);
tButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String path = selectDataFile();
if(new File(path).exists())
textField1.setText(path);
}
});
JPanel line2 = new JPanel();
line2.setBackground(new Color(255, 204, 51));
line2.setBounds(205, 260, 415, 1);
add(line2);
JLabel label3 = new JLabel("Accuracy");
label3.setFont(new Font("Century Gothic", Font.PLAIN, 20));
label3.setForeground(Color.WHITE);
label3.setBounds(364, 268, 107, 29);
add(label3);
JLabel label4 = new JLabel("No. of CORRECT classification:");
label4.setFont(new Font("Century Gothic", Font.PLAIN, 16));
label4.setForeground(Color.WHITE);
label4.setBounds(208, 310, 235, 24);
add(label4);
JLabel label5 = new JLabel("No. of INCORRECT classification:");
label5.setFont(new Font("Century Gothic", Font.PLAIN, 16));
label5.setForeground(Color.WHITE);
label5.setBounds(208, 349, 250, 24);
add(label5);
correctLabel = new JLabel("--");
correctLabel.setFont(new Font("Century Gothic", Font.BOLD, 20));
correctLabel.setForeground(new Color(102, 255, 0));
correctLabel.setBounds(450, 308, 40, 29);
add(correctLabel);
incorrectLabel = new JLabel("--");
incorrectLabel.setFont(new Font("Century Gothic", Font.BOLD, 20));
incorrectLabel.setForeground(new Color(255, 51, 51));
incorrectLabel.setBounds(465, 346, 40, 29);
add(incorrectLabel);
percentLabel = new JLabel("0 %");
percentLabel.setFont(new Font("Century Gothic", Font.BOLD, 40));
percentLabel.setForeground(new Color(102, 255, 0));
percentLabel.setBounds(505, 320, 150, 40);
add(percentLabel);
percentLabel.setVisible(false);
JPanel line3 = new JPanel();
line3.setBackground(new Color(255, 204, 51));
line3.setBounds(145, 390, 475, 1);
//add(line3);
viewResultsButton = new JButton("VIEW RESULTS");
viewResultsButton.setBounds(500, 410, 110, 40);
add(viewResultsButton);
viewResultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(testData != null && result != null) {
ResultViewerDialog rvDialog = new ResultViewerDialog(testData, result);
rvDialog.setVisible(true);
} else
new MessageDialog("Ooops. Nothing to view.").setVisible(true);
}
});
/*JButton saveButton = new JButton("Save Results");
saveButton.setBounds(350, 410, 124, 30);
add(saveButton);
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileFilter filter = new FileTypeFilter(".txt", "Text files");
JFileChooser chooser = new JFileChooser("D:/kamatisan/");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(filter);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
ResultWriter resultWriter = new ResultWriter();
resultWriter.writeResult(chooser.getSelectedFile(), testData, result);
}
}
});*/
final ProgressPane progressPane = new ProgressPane();
progressPane.setLocation(0, 475);
this.add(progressPane);
prepareButton = new JButton("PREPARE");
prepareButton.setBounds(210, 410, 110, 40);
add(prepareButton);
prepareButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dataFile = new File(textField1.getText().trim());
if(dataFile.exists()) {
setComponents(false);
new Thread(new Runnable() {
@Override
public void run() {
DataReader dl = new DataReader(progressPane, dataFile);
if(dl.read())
testData = dl.getData();
setComponents(true);
}
}).start();
} else
new MessageDialog("Ooops. Please select a data file.").setVisible(true);
}
});
classifyButton = new JButton("CLASSIFY");
classifyButton.setBounds(320, 410, 180, 40);
add(classifyButton);
classifyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(solution == null)
new MessageDialog("Ooops. Please select a classifier").setVisible(true);
else if(testData == null)
new MessageDialog("Ooops. Please prepare before testing.").setVisible(true);
else
classifyBatch();
}
});
} | 8 |
public double[] predictDistribution() {
int[] fruitCounts = new int[12];
int totalFruit = 0;
double[] fruitProbabilities = new double[12];
for (int i = 0; i < firstRoundBowlHistory.length; i++) {
for (int j = 0; j < firstRoundBowlHistory[i].length; j++) {
fruitCounts[j] += firstRoundBowlHistory[i][j];
}
}
for (int i = 0; i < secondRoundBowlHistory.length; i++) {
for (int j = 0; j < secondRoundBowlHistory[i].length; j++) {
fruitCounts[j] += secondRoundBowlHistory[i][j];
}
}
for (int i: fruitCounts) {
totalFruit += i;
}
for (int i = 0; i < fruitCounts.length; i++) {
fruitProbabilities[i] = (double) fruitCounts[i] / totalFruit;
}
return fruitProbabilities;
} | 6 |
public JSONObject getData() {
JSONObject o = new JSONObject();
try {
for (Resource r : Resource.values()) {
o.put(r.name(), getF(r));
}
} catch (JSONException e) {
e.printStackTrace();
}
return o;
} | 2 |
private boolean upToDate (File verFile) {
boolean result = true;
try {
if (!verFile.exists()) {
verFile.getParentFile().mkdirs();
verFile.createNewFile();
result = false;
}
BufferedReader in = new BufferedReader(new FileReader(verFile));
String line = in.readLine();
int storedVersion = -1;
if (line != null) {
try {
storedVersion = Integer.parseInt(line.replace(".", ""));
} catch (NumberFormatException e) {
Logger.logWarn("Automatically fixing malformed version file for " + name, e);
line = null;
}
}
if (line == null || Integer.parseInt(version.replace(".", "")) != storedVersion) {
BufferedWriter out = new BufferedWriter(new FileWriter(verFile));
out.write(version);
out.flush();
out.close();
result = false;
}
in.close();
} catch (IOException e) {
Logger.logError("Error while checking texturepack version", e);
}
return result;
} | 6 |
public Vector<WorldMap> readMaps()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(mapFilename));
WorldMap wm = null;
String line = reader.readLine();
while (line != null)
{
line = line.toUpperCase();
//New map
if (line.startsWith("NEW"))
{
String[] t = split(line);
int size = Integer.parseInt(t[1]);
wm = new WorldMap(size);
}
//Pit
if (line.startsWith("P"))
{
String[] t = split(line);
int x = Integer.parseInt(t[1]);
int y = Integer.parseInt(t[2]);
wm.addPit(x,y);
}
//Wumpus
if (line.startsWith("W"))
{
String[] t = split(line);
int x = Integer.parseInt(t[1]);
int y = Integer.parseInt(t[2]);
wm.addWumpus(x,y);
}
//Gold
if (line.startsWith("G"))
{
String[] t = split(line);
int x = Integer.parseInt(t[1]);
int y = Integer.parseInt(t[2]);
wm.addGold(x,y);
}
//End of map
if (line.startsWith("END"))
{
maps.add(wm);
}
line = reader.readLine();
}
reader.close();
}
catch (Exception ex)
{
}
//Add some random maps
maps.add(MapGenerator.getRandomMap(42));
maps.add(MapGenerator.getRandomMap(1977));
maps.add(MapGenerator.getRandomMap(1990));
return maps;
} | 7 |
private void cycleFocusLevel(boolean next) {
if (next) {
// Next View to focus should be the first child View of the currently focused View. If there is no such View, the currently focused View should be clicked on.
List<View> focusableViews = getNextFocusableViews(next);
if (focusableViews.isEmpty()) {
// No focusable Views were found down the tree, so the user is clicking on the currently focused View
ClickListener clickListener = focusedView.getClickListener();
if (clickListener != null) {
clickListener.onClick(focusedView);
}
} else {
for (View view : focusableViews) {
View focusableViewParent = view.getParent();
if (focusableViewParent != null && focusableViewParent.equals(focusedView)) {
setFocus(view, true);
}
}
}
} else {
// Next View to focus should be the currently focused View's parent. If that View isn't focusable, find the next focusable View at the previous level.
View view = focusedView.getParent();
if (view != null) {
if (view.isFocusable()) {
setFocus(view, true);
} else {
// Find first focusable View at level before current level
List<View> focusableViews = getNextFocusableViews(next);
if (!focusableViews.isEmpty()) {
setFocus(focusableViews.get(0), true);
}
}
}
}
} | 9 |
public void write(VariableMap vars, File target) {
this.vars = vars;
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setValidating(false);
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder;
try {
docBuilder = dbfac.newDocumentBuilder();
//docBuilder.setErrorHandler(lastErrors);
doc = docBuilder.newDocument();
writeRoot();
//Write XML
File f = target;
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
DOMSource source = new DOMSource(doc);
OutputStream fos = new FileOutputStream(f);
StreamResult result = new StreamResult(fos);
trans.transform(source, result);
fos.close();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
public boolean removeNick(String nick) {
if (nicks.contains(nick)) {
nicks.removeElement(nick);
char c = nick.charAt(0);
switch (c) {
case '@': beginningVoiced--;
case '+': beginningNormal--;
default: count--;
}
return true;
} else
return false;
} | 3 |
public boolean[][] getPassableMap() {
final boolean[][] result = new boolean[getMapHeight()][getMapWidth()];
final byte[] bytes = ((DataBufferByte) mapImage.getRaster().getDataBuffer())
.getData();
final int w = getMapWidth();
final int h = getMapHeight();
for (int row = 0; row < h; row++) {
final int offset = w * row;
for (int col = 0; col < w; col++) {
final byte alpha = bytes[4 * (offset + col)];
// alpha < 128 ((alpha & 0xf) == 0) => passable
// alpha >= 128 ((alpha & 0xf) != 0) => impassable
if (((int) alpha & 0xf0) == 0) {
result[row][col] = true;
}
}
}
return result;
} | 3 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical target, boolean auto, int asLevel)
{
if(!auto)
return false;
final Physical P=target;
if(P==null)
return false;
if((P instanceof Item)&&(room==null))
return false;
if(P.fetchEffect("Falling")==null)
{
final Falling F=new Falling();
F.setProficiency(proficiency());
F.invoker=null;
if(P instanceof MOB)
F.invoker=(MOB)P;
else
F.invoker=CMClass.getMOB("StdMOB");
F.setSavable(false);
F.makeLongLasting();
P.addEffect(F);
if(!(P instanceof MOB))
CMLib.threads().startTickDown(F,Tickable.TICKID_MOB,1);
P.recoverPhyStats();
}
return true;
} | 7 |
public static String safeReverseTranscribe(String inString ) throws
Exception
{
StringBuffer buff = new StringBuffer();
for ( int x= inString.length() - 1; x >=0; x-- )
{
char c = inString.charAt(x);
if ( c == 'A' )
buff.append( 'T' );
else if ( c == 'T' )
buff.append( 'A' );
else if ( c == 'C' )
buff.append( 'G' );
else if ( c == 'G' )
buff.append ( 'C' );
else if ( c == 'N')
buff.append( 'N') ;
else if ( c== '-' )
buff.append('-');
else buff.append(c);
}
return buff.toString();
} | 7 |
public void pokemonFinalStats(int pokeDmg, double atkPercent,
double defPercent) {
GameFile.pokemonFullHp[0] = (int) (((double) ((GameFile.pokemon1Ivs[0]
+ (2 * baseHp) + 100) * GameFile.pokemonLevels[0]) / 100) + 10);
statAtk = (int) ((((double) ((GameFile.pokemon1Ivs[1] + (2 * baseAtk)) * GameFile.pokemonLevels[0]) / 100) + 5) * atkPercent);
statDef = (int) ((((double) ((GameFile.pokemon1Ivs[2] + (2 * baseDef)) * GameFile.pokemonLevels[0]) / 100) + 5) * defPercent);
statSpAtk = (int) ((((double) ((GameFile.pokemon1Ivs[3] + (2 * baseSpAtk)) * GameFile.pokemonLevels[0]) / 100) + 5) * spAtkPercent);
statSpDef = (int) ((((double) ((GameFile.pokemon1Ivs[4] + (2 * baseSpDef)) * GameFile.pokemonLevels[0]) / 100) + 5) * spDefPercent);
statSpeed = (int) ((((double) ((GameFile.pokemon1Ivs[5] + (2 * baseSpeed)) * GameFile.pokemonLevels[0]) / 100) + 5) * speedPercent);
GameFile.pokemonHp[0] = GameFile.pokemonFullHp[0] - pokeDmg;
if (GameFile.pokemonHp[0] < 0) {
GameFile.pokemonHp[0] = 0;
}
} | 1 |
public void resetTo(String contig, int leftEdgePos) throws IOException, EndOfContigException, FullQueueException {
if (reader.getCurrentContig() == null) {
reader.advanceToContig(contig);
}
if ((! reader.getCurrentContig().equals(contig))) {
bases.clear();
this.leftEdge = 1;
reader.advanceToContig(contig);
}
else {
if (leftEdgePos < indexOfRightEdge()) {
//System.out.println(" Shifting from " + leftEdge + "-" + indexOfRightEdge() + " to " + leftEdgePos + " without filling");
//Advance by amount less than current window size, so just shift and don't clear any bases
while(leftEdge < leftEdgePos) {
shift();
}
return;
}
}
//System.out.println(" Skipping from " + leftEdge + "-" + indexOfRightEdge() + " to " + leftEdgePos + " and re-filling");
bases.clear();
//Left edge may be at default value of -1
if (leftEdge < 0)
leftEdge = 1;
reader.advanceToPosition(leftEdgePos-1); //reader actually keeps things 0-indexed, so subtract 1
leftEdge = leftEdgePos;
int contigSize = (int) (reader.getContigLength(contig).intValue());
// System.out.println(">" + leftEdgePos);
for(int i=leftEdgePos; i<Math.min(leftEdgePos+windowSize, contigSize); i++) {
char c = reader.nextBase();
bases.add( c );
//System.out.print(c);
}
// System.out.println();
} | 6 |
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
try {
if (txtDNI_Agricultor.getText().compareTo("") != 0
&& txtNombres_Agricultor.getText().compareTo("") != 0
&& txtApePaterno_Agricultor.getText().compareTo("") != 0
&& txtApeMaterno_Agricultor.getText().compareTo("") != 0) {
String sexo = cboSexo_Agricultor.getSelectedItem().toString().equalsIgnoreCase("FEMENINO") ? "F" : "M";
ArrayList<ListaLateral> lista_laterales = new ArrayList<ListaLateral>();
int nroFilas = ((DefaultTableModel) jtDetalleLaterales_Agricultor.getModel()).getRowCount();
for (int f = 0; f < nroFilas; f++) {
ListaLateral l = new ListaLateral();
//l.setInt_id(Integer.parseInt(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 0).toString()));
l.setIdlateral(Integer.parseInt(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 0).toString()));
l.setIdsublateral(Integer.parseInt(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 1).toString()));
l.setDec_sinmedida(Double.parseDouble(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 4).toString()));
l.setDec_conmedida(Double.parseDouble(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 5).toString()));
l.setInt_numhectareas(Integer.parseInt(jtDetalleLaterales_Agricultor.getModel().getValueAt(f, 6).toString()));
lista_laterales.add(l);
}
//REGISTRAR AGRICULTOR
if (new BLAgricultor().RegistrarAgricultor(idAgricultor_Edit, txtNombres_Agricultor.getText(),
txtApeMaterno_Agricultor.getText(), txtApePaterno_Agricultor.getText(),
txtDireccion_Agricultor.getText(), txtEmail_Agricultor.getText(), txtDNI_Agricultor.getText(),
sexo, txtTelefono_Agricultor.getText(),
txtCelular_Agricultor.getText(), lista_laterales)) {
JOptionPane.showMessageDialog(null, "Registro Exitoso", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
limpiarTabla(jtAgricultor);
limpiarTabla(jtDetalleLaterales_Agricultor);
limpiarformulario_agricultor();
gettabla_agricultor_all("", 1);
idAgricultor_Edit = 0;
} else {
limpiarformulario_agricultor();
JOptionPane.showMessageDialog(null, "Registro Fallido", "Mensaje", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, " No se admiten campos vacios ", "Mensaje", 1);
}
} catch (Exception e) {
System.out.println("Error al registrar Orden Compra" + e.toString());
}
} | 8 |
public List<Attempt> solve() {
ArrayList<Attempt> successes = new ArrayList<Attempt>();
if (isMetGoal()) {
successes.add(this);
} else if (isGoodAttempt()) {
int moveIndex = -1;
for (int i = 0; i < moves.length; i++) {
if (null == moves[i]) {
moveIndex = i;
break;
}
}
if (moveIndex >= 0) {
System.out.println("recursing: " + this);
ArrayList<Attempt> subAttempts = new ArrayList<Attempt>();
Piece piece = pieces[moveIndex];
for (int sumsIndex = 0; sumsIndex < piece.getSums().length; sumsIndex++) {
int[] sums = piece.getSums(sumsIndex);
int maxPosition = goal.length - sums.length;
for (int position = 0; position <= maxPosition; position++) {
int[] subGoal = Arrays.copyOf(goal, goal.length);
for (int i = 0; i < sums.length; i++) {
subGoal[i + position] -= sums[i];
}
Move newMove = new Move(sumsIndex, position);
subAttempts.add(makeSubAttempt(moveIndex, newMove, subGoal));
}
}
subAttempts.add(makeSubAttempt(moveIndex, Move.EMPTY, goal));
for (Attempt subAttempt : subAttempts) {
successes.addAll(subAttempt.solve());
}
}
}
return successes;
} | 9 |
@Override public void init() {
signalTower = SignalTowerBuilder.create().build();
count = 0;
lastTimerCall = System.nanoTime();
timer = new AnimationTimer() {
@Override public void handle(long now) {
if (now > lastTimerCall + 2_000_000_000l) {
if (count == 3) count = 0;
switch(count) {
case 0:
signalTower.setColors(true, false, false);
break;
case 1:
signalTower.setColors(false, true, false);
break;
case 2:
signalTower.setColors(false, false, true);
break;
}
count++;
lastTimerCall = now;
}
}
};
} | 5 |
public boolean modifyStudent(String originNo, Student now) {
String select = "SELECT * FROM STUDENT WHERE NO=?";
try {
PreparedStatement ps = conn
.prepareStatement(select, ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ps.setString(1, originNo);
ResultSet rs = ps.executeQuery();
rs.first();
rs.updateString("NO", now.no);
rs.updateString("NAME", now.name);
rs.updateString("SEX", now.sex);
rs.updateDate("BIRTHDAY", now.birthday);
rs.updateString("ADDRESS", now.address);
rs.updateString("TEL", now.tel);
rs.updateString("EMAIL", now.email);
rs.updateRow();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ManualConfigure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ManualConfigure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ManualConfigure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ManualConfigure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ManualConfigure(null).setVisible(true);
}
});
} | 6 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (login != null ? !login.equals(user.login) : user.login != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
return true;
} | 7 |
public void update(InputHandler inHandler) {
// movement
setX_Point(getX_Point()-getxVel());
setY_Point(getY_Point()+getyVel());
if(isGravityOn()){
updateGravity();
if(getY_Point()>getHeight()){
setyVel(getyVel()-upAc);
}
}
// "droping"
if(getDropTimer().isReady()){
setDropTimer(new Timer(getDropTimerWait()));
Drop drop=new Drop(getX_Point(),getY_Point()+getHeight(),getxVel(),getxVel());
Level.getEntities().add(drop);
}
if(timer==null){
timer= new Timer(100);
}
if(timer.isReady()){
if(timeVar==0){
timeVarPosi=1;
}else if(timeVar==3){
timeVarPosi=-1;
}
timeVar+=timeVarPosi;
timer= new Timer(100);
}
} | 7 |
@Override
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException
{
dispatchHotkeys(container, delta);
if (currentState == STATE_DEAD || currentState == STATE_PAUSED) {
return;
}
map.update(this, container, delta);
// detect tower selection
Input in = container.getInput();
if (in.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
if (building == null) {
Iterator<Tower> it = availableTowers.iterator();
while (it.hasNext()) {
Tower t = it.next();
if (t.getRectangle().contains(in.getMouseX(), in.getMouseY())) {
building = t;
break;
}
}
} else {
try {
// place the tower
if (in.getMouseX() < WIDTH * SCALE && in.getMouseY() < HEIGHT * SCALE) { // only in the field
map.addTile(building, new Point(in.getMouseX() / SCALE, in.getMouseY() / SCALE));
building = null;
}
} catch (Exception e) {
System.out.println("cannot place tower");
}
}
}
} | 9 |
private static void showResults(HuntField field) {
int counter = 0;
for (FieldItem item : field.getItemsInField()) {
if (item.getType() == 'H') {
counter++;
Hunter hunter = (Hunter) item;
switch (hunter.hunted()) {
case 0:
System.out.println("Hunter " + counter + " hunted no ducks...");
break;
case 1:
System.out.println("Hunter " + counter + " hunted a duck.");
break;
default:
System.out.println("Hunter " + counter + " hunted " + hunter.hunted() + " ducks!");
break;
}
}
}
int victims = numberOfHunters - counter;
switch (victims) {
case 0:
System.out.println("No hunters died during this hunt!");
break;
case 1:
System.out.println("A hunter died during this hunt...");
break;
default:
System.out.println(victims + " hunters died during this hunt...");
break;
}
} | 6 |
private void drawBackground() {
g.setColor(Color.cyan);
g.fillRect(0, 0, WIDTH*SCALE, HEIGHT*SCALE);
} | 0 |
public int getVisibleColumnCount() {
int count = 0;
for (Column column : mColumns) {
if (column.isVisible()) {
count++;
}
}
return count;
} | 2 |
public static void main(String[] args) throws Exception {
String map = null;
//String group = null;
if (args.length > 0)
map = args[0];
if (args.length > 1)
L = Double.parseDouble(args[1]);
if (args.length > 2)
W = Double.parseDouble(args[2]);
if (args.length > 3)
gui = Boolean.parseBoolean(args[3]);
if (args.length > 4)
group = args[4];
if (args.length > 5)
s = Double.parseDouble(args[5]);
player = loadPlayer(group);
watermelon game = new watermelon();
//game.init();
game.read(map);
game.playgui();
} | 6 |
private void extend(ITNode currNode) throws IOException {
// loop over the brothers of that node
int i = 0;
while (i < currNode.getParent().getChildNodes().size()) {
// get the brother i
ITNode brother = currNode.getParent().getChildNodes().get(i);
// if the brother is not the current node
if (brother != currNode) {
// Property 1
// If the tidset of the current node is the same as the one
// of its brother
if (currNode.getTidset().equals(brother.getTidset())) {
// we can replace the current node itemset in the current node
// and the subtree by the union of the brother itemset
// and the current node itemset
replaceInSubtree(currNode, brother.getItemset());
// then we delete the brother
delete(brother);
}
// Property 2
// If the brother tidset contains the tidset of the current node
else if (brother.getTidset().containsAll(currNode.getTidset())) {
// Same as previous if condition except that we
// do not delete the brother.
replaceInSubtree(currNode, brother.getItemset());
i++;
}
// Property 3
// If the tidset of the current node contains the tidset of the
// brother
else if (currNode.getTidset().containsAll(brother.getTidset())) {
// Generate a candidate by performing
// the union of the itemsets of the current node and its brother
ITNode candidate = getCandidate(currNode, brother);
// delete the brother
delete(brother);
// if a candidate was obtained
if (candidate != null) {
// add the candidate as child node of the current node
currNode.getChildNodes().add(candidate);
candidate.setParent(currNode);
}
}
// Property 4
// if the tidset of the current node is not equal to the tidset
// of its brother
else if (!currNode.getTidset().equals(brother.getTidset())) {
// Generate a candidate by performing
// the union of the itemsets of the current node and its brother
ITNode candidate = getCandidate(currNode, brother);
// if a candidate was obtained
if (candidate != null) {
// add the candidate as child node of the current node
currNode.getChildNodes().add(candidate);
candidate.setParent(currNode);
}
i++; // go to next node
} else {
i++; // go to next node
}
} else {
i++; // go to next node
}
}
// for optimization, sort the child of the root according to the support
sortChildren(currNode);
// while the current node has child node
while (currNode.getChildNodes().size() > 0) {
// get the first child
ITNode child = currNode.getChildNodes().get(0);
extend(child); // extend it (charm is a depth-first search algorithm)
save(child); // save the node
delete(child); // then delte it
}
} | 9 |
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
new ChatServer(port);
} catch (Exception e) {
System.out.println("Enter a valid port.");
System.exit(0);
}
} | 1 |
public void eat() throws GameException
{
ArrayList<Actor> intersectingObjects = (ArrayList<Actor>) getIntersectingObjects(MovingObject.class);
if(intersectingObjects.isEmpty())
return;
for(int i=0; i < intersectingObjects.size(); i++)
{
MovingObject chosenActor = (MovingObject)intersectingObjects.get(0);
if(chosenActor instanceof Clone)
{
Clone chosenClone = (Clone) chosenActor;
if(chosenClone.getCloneNumber() < getCloneNumber())
return;
int newSize = Math.max(getSize(), chosenClone.getSize())+2;
getWorld().removeObject(chosenActor);
intersectingObjects.remove(0);
setSize(originalSize*newSize, originalSize*newSize);
size+=2;
}
else
{
getWorld().removeObject(chosenActor);
intersectingObjects.remove(0);
System.out.println("You loose!");
}
}
} | 4 |
public void passKeyPressed(ArrayList<KeyButtons> keyPressed)
{
if (!keyPressed.isEmpty() && keyPressed != null);
{
switch (whatcha)
{
case PLAYING:
stage.handlePressedKeys(keyPressed);
break;
case PAUSE:
pauzeMenu.handlePressedKeys(keyPressed);
break;
case MAIN:
mainMenu.handlePressedKeys(keyPressed);
break;
case SELECTSTAGE:
stageSelector.handlePressedKeys(keyPressed);
break;
}
}
} | 6 |
@Override
public double getIntersectionValue(Ray ray)
{
//sphere: r^2 = (x - x1)^2 + (y - y1)^2 + (z - z1)^2
//Line: x = at + b
// y = ct + d
// z = et + g
LinearEquation combinedX = LinearEquation.Add(ray.xEquation, -center.x);
LinearEquation combinedY = LinearEquation.Add(ray.yEquation, -center.y);
LinearEquation combinedZ = LinearEquation.Add(ray.zEquation, -center.z);
QuadraticEquation combined = QuadraticEquation.Add(
QuadraticEquation.Add(
LinearEquation.Multiply(combinedX, combinedX),
LinearEquation.Multiply(combinedY, combinedY)),
LinearEquation.Multiply(combinedZ, combinedZ));
combined.constant -= radius * radius;
//Find zeroes using quadratic equation
double a = combined.quadCoefficient;
double b = combined.linearCoefficient;
double c = combined.constant;
double numToSqrt = (b * b) - (4 * a * c);
if(numToSqrt < 0)
{
return Ray.NO_INTERSECTION;
}
if(a == 0) //Divide by zero not allowed
{
return Ray.NO_INTERSECTION;
}
double higherZero = (-b + Math.sqrt(numToSqrt))/(2 * a);
double lowerZero = (-b - Math.sqrt(numToSqrt))/(2 * a);
if(higherZero <= Ray.LOWER_T_BOUND && lowerZero <= Ray.LOWER_T_BOUND)
{
return Ray.NO_INTERSECTION;
}
else if (lowerZero <= Ray.LOWER_T_BOUND)
{
return higherZero;
}
else
{
return lowerZero;
}
} | 5 |
private int getCompositeNum() {
int n = 1;
List<Integer> primes = new ArrayList<>();
while ((n += 2) > 0) {
boolean isPrime = Problem3.isPrime(n);
if (isPrime) {
primes.add(n);
continue;
}
boolean hit = false;
for (int i = primes.size() - 1; i >= 0; i--) {
int p = primes.get(i);
int sub = (n - p) / 2;
int j = 0;
while (++j > 0) {
int square = (int) Math.pow(j, 2);
if (square < sub) {
continue;
} else {
if (square == sub) {
hit = true;
}
break;
}
}
if (hit) {
break;
}
}
if (!hit) {
return n;
}
}
return -1;
} | 8 |
private void set2(Delegate d) {
setVisible(d.visible);
setDraggable(d.draggable);
setRx(d.getX());
setRy(d.getY());
setAngle(d.getAngle());
setFont(d.getFont());
setFillMode(d.getFillMode());
setBorderType((byte) d.getBorderType());
setShadowType((byte) d.getShadowType());
setForegroundColor(d.getForegroundColor());
setLayer(d.getLayer());
setCallOut(d.isCallOut());
if (isCallOut())
getCallOutPoint().setLocation(d.getCallOutPoint());
setAttachmentPosition(d.getAttachmentPosition());
String s = d.getHostType();
if (s != null) {
int index = d.getHostIndex();
if (s.endsWith("Atom")) {
if (model instanceof MolecularModel) {
setHost(((MolecularModel) model).getAtom(index));
}
}
else if (s.endsWith("GayBerneParticle")) {
if (model instanceof MesoModel) {
setHost(((MesoModel) model).getParticle(index));
}
}
else if (s.endsWith("Obstacle")) {
setHost(model.getObstacles().get(index));
}
}
} | 7 |
@Override
public void close() {
for (int i = 0; i < printStreams.length; i++){
printStreams[i].close();
}
} | 1 |
@Override
public int read() throws IOException {
return (prt < data.length) ? (data[prt++]):-1;
} | 1 |
private double compute_conductance(fgraph fg,community com)
{
double m=0,c=0;
for(int i=0;i<fg.get_number_of_edges();i++)
{
edge e=fg.get_edge(i);
if(com.contains(e.get_n1())&&com.contains(e.get_n2()))
{
m++;
}
else if((com.contains(e.get_n1())&&!com.contains(e.get_n2()))||(!com.contains(e.get_n1())&&com.contains(e.get_n2())))
{
c++;
}
}
return (c/(m+c));
} | 7 |
public void analyzePath() {
addedLength = actualLongestPath.getLength();
Direction dir = board.getWaterDirection();
List<Pipe> path = actualLongestPath.getPath();
for (int i = 0; i < path.size(); i++) {
if (path.get(i).isCorner()) {
if (!replaceWithCross(path.get(i), i, dir))
if (i + 1 < path.size() && path.get(i + 1).isCorner())
if (twoCorners(path.get(i), path.get(i + 1), dir))
addStraightPipes(path, i, dir);
}
dir = path.get(i).modifyDirection(dir);
}
actualLongestPath.setPath(path);
actualLongestPath.setLength(addedLength);
if (longestPath == null
|| longestPath.getLength() < actualLongestPath.getLength())
longestPath = actualLongestPath;
} | 8 |
public static EntityInformation serializeEntity(InternalComponentManager componentManager, EntityRef clientEntity,
int entityId, EntityRef entity, Iterable<? extends EntityComponentFieldFilter> componentFieldFilters) {
EntityInformation entityInformation = new EntityInformation();
entityInformation.setEntityId(entityId);
for (Class<? extends Component> componentClass : entity.listComponents()) {
if (filtersAcceptComponent(clientEntity, entity, componentClass, componentFieldFilters)) {
Component component = entity.getComponent(componentClass);
ComponentInformation componentInformation = new ComponentInformation(componentClass);
Map<String, Class<?>> fieldTypes = componentManager.getComponentFieldTypes(component);
for (Map.Entry<String, Class<?>> fieldTypeEntry : fieldTypes.entrySet()) {
String fieldName = fieldTypeEntry.getKey();
if (filtersAcceptField(clientEntity, entity, componentClass, fieldName, componentFieldFilters)) {
componentInformation.addField(fieldName, componentManager.getComponentFieldValue(component, fieldName, fieldTypeEntry.getValue()));
}
}
entityInformation.addComponent(componentInformation);
}
}
return entityInformation;
} | 8 |
private void rellenaAleatorio() {
for(int y=0; y<numeros.length; y++){
int min = y * 10;
int max = ((y + 1) * 10) - 1;
if(min == 0) min = 1;
if(max == 89) max = 90;
for(int x=0; x<numeros[y].length; x++){
int aleatorio = 0;
boolean repetido = true;
while(repetido){
aleatorio = aleatorioConRango(min, max);
repetido = contiene(numeros[y], aleatorio);
numeros[y][x] = aleatorio;
}
}
}
} | 5 |
public static double clampDouble(double value, double min, double max)
{
return (value < min) ? min : (value > max) ? max : value;
} | 2 |
public void test() {
String f = "SafeCommandBlock";
PluginUpdateInfo tar = null;
for (PluginUpdateInfo pui : PluginUpdateInfo.plugins) {
if (pui.p.getDescription().getName().equals(f)) {
tar = pui;
}
}
VersionsComparer vs = new VersionsComparer(Comparer.VERSION_WEBSITE_COMPARE);
try {
System.out.println(""+vs.hasUpdate(tar));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public int GetTravelTime()
{
//return the travel time
return this.toLastBusStopTicks - this.firstTicks;
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProposedCard other = (ProposedCard) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id)
&& (areTwoIdsTransposesOfEachOther(id, other.id) == null))
return false;
return true;
} | 7 |
@Override
public void onDisable() {
GcConfig.plugin = null;
GcFiles.save();
Player [] list = Bukkit.getOnlinePlayers();
for (Player players : list) {
if (GcEntityListener.signLocation.containsKey(players)) {
Block block = GcEntityListener.signLocation.get(players).getBlock();
block.setType(Material.AIR);
GcEntityListener.signLocation.remove(players);
}
if (GcEntityListener.signExists.containsKey(players)) {
GcEntityListener.signExists.remove(players);
}
if (GcBlockListener.signLocation.containsKey(players)) {
Block block = GcBlockListener.signLocation.get(players).getBlock();
block.setType(Material.AIR);
GcBlockListener.signLocation.remove(players);
}
if (GcEntityListener.score.containsKey(players)) {
GcEntityListener.score.remove(players);
}
}
Log(Level.INFO, "was successfully disabled.");
} | 5 |
public final void unpause() {
if (paused.compareAndSet(true, false)) {
synchronized (this) {
notify();
}
}
} | 1 |
public static void token_stemming(String[] tokens, String[] suffixes) {
for (String token : tokens) {
int longestMatchedSuffixLen = 0;
for (String suffix : suffixes) {
boolean matches = token.endsWith(suffix);
boolean longer = longestMatchedSuffixLen < suffix.length();
if(matches && longer) longestMatchedSuffixLen = suffix.length();
}
int tokenLen = token.length();
System.out.println(token.substring(0,tokenLen - longestMatchedSuffixLen));
}
} | 4 |
private BlockStatement compileFor() throws ParseException, IOException {
// (
getSymbol('(', "( is excepted after for");
// <identifier>
getNextToken(Tokenizer.IDENTIFIER, "identifier is excepted after (");
// <var-name>
Vector<Expression> expressions = new Vector<Expression>();
Vector<Integer> lengths = new Vector<Integer>();
BlockStatement block = new BlockStatement();
String varName = compileLHS(null, expressions, lengths, block);
// =
if ((tokenizer.tokenType() != Tokenizer.SYMBOL) ||
(tokenizer.symbol() != '=')) {
throw new ParseException("= is excepted after variable",
tokenizer.lineNumber());
}
advance("program not ended");
//<from-value>
int from = compileConstValue().intValue();
// to
if ((tokenizer.tokenType() != Tokenizer.KEYWORD) ||
(tokenizer.keyword() != Tokenizer.KW_TO)) {
throw new ParseException("to is expected", tokenizer.lineNumber());
}
advance("program not ended");
//<to-value>
int to = compileConstValue().intValue();
// )
if ((tokenizer.tokenType() != Tokenizer.SYMBOL) ||
(tokenizer.symbol() != ')')) {
throw new ParseException(") is expected", tokenizer.lineNumber());
}
advance("program not ended");
Statement forBlock = compileStatement();
//duplicating the for block to-from+1 times
for (; from <= to; from++) {
//index not array
if (expressions.isEmpty()) {
block.addStatement(new AssignmentStatement(Function.getVar(varName),
new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP),
new IntConstant(BigInteger.valueOf(from)))));
} else {
block.addStatement(arrayStatment(varName, expressions, lengths,
new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP),
new IntConstant(BigInteger.valueOf(from)))));
}
block.addStatement(forBlock.duplicate());
}
return block;
} | 8 |
void dump(String indent) {
log.trace(indent + "***** CALL DUMP *****");
log.trace(indent + "TSCall: " + this);
log.trace(indent + "TSCall ID: " + this.callID);
log.trace(indent + "TSCall UCID: " + this.ucid);
log.trace(indent + "TSCall non-Call ID: " + this.nonCallID);
log.trace(indent + "TSCall state: " + this.state);
log.trace(indent + "TSCall needSnapshot: " + this.needSnapshot);
log.trace(indent + "TSCall age: " + this.my_age);
log.trace(indent + "TSCall connections: ");
synchronized (this.connections) {
for (int i = 0; i < this.connections.size(); i++) {
TSConnection conn = (TSConnection) this.connections
.elementAt(i);
conn.dump(indent + " ");
}
}
log.trace(indent + "TSCall trunks: ");
synchronized (this.trkVector) {
for (int i = 0; i < this.trkVector.size(); i++) {
TSTrunk trk = (TSTrunk) this.trkVector.elementAt(i);
trk.dump(indent + " ");
}
}
log.trace(indent + "TSCall handOffCall: " + this.handOffCall);
log.trace(indent + "TSCall stale connections: ");
synchronized (this.staleConnections) {
for (int i = 0; i < this.staleConnections.size(); i++) {
TSConnection conn = (TSConnection) this.staleConnections
.elementAt(i);
conn.dump(indent + " ");
}
}
log.trace(indent + "TSCall trunks: ");
log.trace(indent + "TSCall Monitor Threads: ");
synchronized (this.monitorThreads) {
for (int i = 0; i < this.monitorThreads.size(); i++) {
TsapiCallMonitor oThreads = (TsapiCallMonitor) this.monitorThreads
.elementAt(i);
oThreads.dump(indent + " ");
}
}
log.trace(indent + "TSCall Device Monitor Threads: ");
synchronized (this.deviceObsVector) {
for (int i = 0; i < this.deviceObsVector.size(); i++) {
TsapiCallMonitor oThreads = ((DeviceObs) this.deviceObsVector
.elementAt(i)).callback;
oThreads.dump(indent + " ");
}
}
log.trace(indent + "TSCall Stale Monitor Threads: ");
synchronized (this.staleObsVector) {
for (int i = 0; i < this.staleObsVector.size(); i++) {
TsapiCallMonitor oThreads = (TsapiCallMonitor) this.staleObsVector
.elementAt(i);
oThreads.dump(indent + " ");
}
}
log.trace(indent + "TSCall CallbackAndType Monitor Threads: ");
synchronized (this.callbackAndTypeVector) {
CallbackAndType cbAndType = null;
for (int i = 0; i < this.callbackAndTypeVector.size(); i++) {
cbAndType = (CallbackAndType) this.callbackAndTypeVector
.elementAt(i);
TsapiCallMonitor oThreads = cbAndType.callback;
oThreads.dump(indent + " ");
}
}
int i = 0;
for (String str : LucentUserToUserInfo.print(
TsapiPromoter.demoteUserToUserInfo(getUUI()), "CallUUI", indent
+ " ")) {
if (i == 0) {
log.trace(indent + "TSCALL UUI" + str);
} else {
log.trace(str);
}
i++;
}
log.trace(indent + "***** CALL DUMP END *****");
} | 9 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NightArrivedMessage)) return false;
NightArrivedMessage that = (NightArrivedMessage) o;
if (!Arrays.equals(playersName, that.playersName)) return false;
return true;
} | 3 |
public int maxPoints(Point[] points) {
int big =0;
int flag =0;
if(points.length<2){
return points.length;
}
for(int i = 0; i < points.length ; i++)
for(int j=i+1; j <points.length; j++){
if((points[i].x != points[j].x) || (points[i].y != points[j].y) ){
int temp = Number(points[i],points[j],points);
if(temp > big)
big = temp;
flag =1;
}
}
if(flag ==0) // 所有的点同一行或者同一列。
return points.length;
else
return big;
} | 7 |
private void sendImageToGUI()
{
if (bulbPower < images.size())
{
appFrame.changeImage(bulbPower);
}
} | 1 |
public void switchArriereState(){
_arriere = !_arriere;
_statutTexture = 0;
if (_arriere) {
_texture = _liste_texture_back.get(0);
} else {
_texture = _liste_texture.get(0);
}
} | 1 |
public void setLineEnding(String lineEnding) {this.lineEnding = lineEnding;} | 0 |
public Garage() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("voitures.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
if (br.readLine() == null) {
System.out.println("Aucune voiture sauvegardée !");
}
} catch (IOException e) {
e.printStackTrace();
}
this.voitures = new ArrayList();
} | 3 |
public PainelEsconde(Painel pn){
//tabuleiro.setLayout(null);
tabuleiro = pn;
//this.setBounds(10, 10, 500, 500);
//this.setBackground(null);
apagaBotao = new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
if( tabuleiro.isEnabled() && (jogoIniciado)){
JButton bt = ( (JButton)e.getSource() );
bt.setVisible(false);
tabuleiro.setEnabled(false);
if(tabuleiro.pos.get(tabuleiro.getCelula(bt.getX(), bt.getY())).preenchido){
tabuleiro.acertouTiro = true;
} else
tabuleiro.acertouTiro = false;
}
else if(!jogoIniciado)
JOptionPane.showMessageDialog(null, "Inicie o jogo para comecar");
else if((!tabuleiro.isEnabled()) && (jogoIniciado))
JOptionPane.showMessageDialog(null, "Espere sua vez");
}
};
for(int i = 0; i<10;i++){
for(int j=0; j<10; j++){
JButton quadrado = new JButton("");
quadrado.setBounds(j*50, i*50, 50, 50);
quadrado.setText("");
quadrado.setBorder(new LineBorder(Color.BLUE));
quadrado.addMouseListener(apagaBotao);
tabuleiro.add(quadrado);
}
}
tabuleiro.setEnabled(false);
} | 8 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MASK_MALICIOUS|verbalCastCode(mob,target,auto),L(auto?"A light fatigue overcomes <T-NAME>.":"^S<S-NAME> "+prayWord(mob)+" for extreme fatigue to overcome <T-NAMESELF>!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
{
final int harming=CMLib.dice().roll(10,adjustedLevel(mob,asLevel),50);
if((target.curState().getFatigue()<=CharState.FATIGUED_MILLIS)
&&(target.maxState().getFatigue()>Long.MIN_VALUE/2))
target.curState().setFatigue(CharState.FATIGUED_MILLIS+1);
target.curState().adjMovement(-harming,target.maxState());
target.tell(L("You feel fatigued!"));
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> point(s) at <T-NAMESELF> and @x1, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} | 8 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String operation = request.getParameter("operation");
Command com = null;
if(operation == null){
com = new ShowCommand();
} else if(operation.equals("add")){
com = new AddCommand();
} else if (operation.equals("addwrite")) {
com = new AddWriteCommand();
} else if(operation.equals("edit")){
com = new UpdateCommand();
} else if(operation.equals("addupdate")){
com = new AddUpdateCommand();
} else if(operation.equals("delete")){
com = new DeleteCommand();
} else if(operation.equals("adddelete")){
com = new AddDeleteCommand();
}
com.execute(request, response);
} | 7 |
public ControleurApplication(BDApplication modeleApp, VueApplication vueApp) {
this.modeleApp = modeleApp;
this.vueApp = vueApp;
controleurListe = new ControleurListe(modeleApp.getListe(),
vueApp.getVueListe());
for (int i = 0; i < vueApp.getVueCommande().NBBOUTONS; i++) {
this.vueApp.getVueCommande().getBoutons(i).addActionListener(this);
}
} | 1 |
private void render() {
if (!initialized) {
if (this instanceof IPreloadModifier){
IPreloadModifier modifier = (IPreloadModifier) this;
modifier.renderPreLoadScreen();
} else {
fontRenderer.setRenderingSize(5);
fontRenderer.setRenderingColor(ColorHelper.GREEN);
fontRenderer.renderString("SLDT's GameEngine " + EngineConstants.ENGINE_VERSION, getScreenWidth() - fontRenderer.getStringWidth("SLDT's GameEngine " + EngineConstants.ENGINE_VERSION), getScreenHeight() - 64);
Material i = renderEngine.getMaterial(background);
renderEngine.bindMaterial(i);
renderEngine.addTranslationMatrix(10, 10);
renderEngine.enableMiddleRotationScale();
renderEngine.setRotationLevel(-rotate);
renderEngine.setScaleLevel(1 - scale);
renderEngine.renderQuad(10, 10, getScreenWidth() - 20, getScreenHeight() - 20);
}
}
if (!gameUsesDefaultCursor) {
Mouse.setGrabbed(true);
}
if (!isWindowExiting) {
if (currentFrame != null) {
currentFrame.drawWindow(renderEngine, fontRenderer);
if (!gameUsesDefaultCursor) {
Mouse.setGrabbed(true);
} else if (!currentFrame.showCursor){
Mouse.setGrabbed(true);
}
}
}
if (isWindowExiting) {
renderEngine.bindColor(ColorHelper.BLACK);
renderEngine.renderQuad(0, 0, getScreenWidth(), getScreenHeight());
fontRenderer.setRenderingColor(ColorHelper.WHITE);
fontRenderer.renderString("Loading...", 20, 20);
}
particleEngine.doRender(renderEngine, fontRenderer);
renderGameOverlay();
} | 8 |
private int jjMoveStringLiteralDfa7_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(5, old0);
try { curChar = input_stream.readChar(); }
catch(EOFException e) {
jjStopStringLiteralDfa_0(6, active0);
return 7;
}
switch(curChar)
{
case 99:
return jjMoveStringLiteralDfa8_0(active0, 0x2000L);
case 101:
return jjMoveStringLiteralDfa8_0(active0, 0x10000L);
case 108:
if ((active0 & 0x200000000L) != 0L)
return jjStartNfaWithStates_0(7, 33, 43);
break;
case 116:
return jjMoveStringLiteralDfa8_0(active0, 0x8000000L);
case 119:
return jjMoveStringLiteralDfa8_0(active0, 0x80000L);
default :
break;
}
return jjStartNfa_0(6, active0);
} | 8 |
public Doctor(String name, String userName, String password, int room){
this.name=name;
this.userName=userName;
this.password=password;
this.room = room;
} | 0 |
private void writeAchievements(OutputStream out, List<AchievementRecord> achievements) throws IOException {
writeInt(out, achievements.size());
for (AchievementRecord rec : achievements) {
writeString(out, rec.getAchievementId());
int diff = 0;
switch(rec.getDifficulty()) {
case NORMAL: diff = 1; break;
case EASY: diff = 0; break;
}
writeInt(out, diff);
}
} | 3 |
@Test
public void testGenerateOnlyDistributionsEVRangeFromRestrictions() {
int maxEVs = 200;
int minEVs = 80;
when(restrictionsModel.getMaxEVs()).thenReturn(maxEVs);
when(restrictionsModel.getMinEVs()).thenReturn(minEVs);
Set<EVDistribution> initialCollection = evDistributionFactory.getInitialCollection(restrictionsModel);
int counter = 0;
for (int h = 0; h <= maxEVs; h += EV_STEP) {
for (int d = 0; d <= maxEVs; d += EV_STEP) {
for (int s = 0; s <= maxEVs; s += EV_STEP) {
EVDistribution expectedDistro = new EVDistribution(h, d, s, neutralNature);
int sum = h + d + s;
if (sum >= minEVs && sum <= maxEVs) {
assertTrue(initialCollection.contains(expectedDistro));
++counter;
} else {
assertFalse(initialCollection.contains(expectedDistro));
}
}
}
}
assertEquals(counter, initialCollection.size());
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ArrayWorld other = (ArrayWorld) obj;
return Arrays.deepEquals(cells, other.cells);
} | 3 |
@Override
public String[] getListOfMembers() {
List<Member> memberList = data.getListOfMembers();
String [] memberArray = new String[memberList.size()];
for(int i=0;i<memberList.size();i++){
memberArray[i]=memberList.get(i).getFirstname() + " " + memberList.get(i).getLastname();
}
return memberArray;
} | 1 |
@Override
public void dragOver(DropTargetDragEvent event) {
TreePanel panel = getPanel();
TreeContainerRow parentRow = null;
int insertIndex = -1;
if (acceptDrag(event)) {
Point pt = panel.toContentView(new Point(event.getLocation()));
TreeRoot root = panel.getRoot();
TreeRow overRow = panel.overRow(pt.y);
if (overRow != null) {
if (mRowSelection.getRows().get(0).getTreeRoot() != root || !panel.isRowOrAncestorSelected(overRow)) {
int indent = TreePanel.INDENT * overRow.getDepth();
if (panel.areDisclosureControlsShowing()) {
indent += TreePanel.INDENT;
}
if (overRow instanceof TreeContainerRow && pt.x > indent) {
parentRow = (TreeContainerRow) overRow;
insertIndex = 0;
} else {
parentRow = overRow.getParent();
insertIndex = overRow.getIndex();
Rectangle bounds = panel.getRowBounds(overRow);
if (pt.y > bounds.y + bounds.height / 2) {
insertIndex++;
}
}
}
} else {
parentRow = root;
insertIndex = root.getChildCount();
}
}
panel.adjustInsertionMarker(parentRow, insertIndex);
} | 8 |
protected boolean matchKind(Item item) {
if (this.type != item.type) return false ;
if (this.refers != null) {
if (item.refers == null) return false ;
if (! this.refers.equals(item.refers)) return false ;
}
return true ;
} | 4 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
boolean first = true, prevNoEmpty = true;
while ((line = in.readLine()) != null && line.length() != 0) {
if (!first && !prevNoEmpty)
out.append("\n");
first = false;
int sizeNeedle = Integer.parseInt(line.trim());
String needle = in.readLine().trim(), haystack = in.readLine().trim();
ArrayList<Integer> coincidencias = KMP(haystack, needle);
prevNoEmpty = coincidencias.isEmpty();
for (Integer integer : coincidencias)
out.append(integer + "\n");
}
System.out.print(out);
} | 5 |
public static void makeFieldAccessible(final Field field) throws SecurityException {
if (!field.isAccessible()) {
if (System.getSecurityManager() == null) {
field.setAccessible(true);
} else {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
field.setAccessible(true);
return null;
});
}
}
} | 2 |
private int find(int index){
int low = 0;
int high = fillLevel - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = index(mid);
if (midVal < index)
low = mid + 1;
else if (midVal > index)
high = mid - 1;
else
return mid;
}
return -(low + 1);
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.