text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static boolean isBattery(int s) {
if(s==62529)
return true;
return false;
} | 1 |
public boolean equals(Object other) {
if (other instanceof Recipe) {
Recipe that = (Recipe) other;
if (that.size() == this.size()) {
RNode k = that.head;
while (k != null) {
if (!bevat(k.getElement())) {
return false;
}
k = k.getNext();
}
return true;
}
}
return false;
} | 4 |
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} | 8 |
private static Node addInteger(Node int1, Node int2){
int carry = 0;
Node newh = null;
Node curr = newh;
while(int1!=null && int2!=null){
if(newh==null){
newh=new Node((int1.v+int2.v+carry)%10);
newh.next = null;
curr = newh;
}else {
curr.next = new Node((int1.v+int2.v+carry)%10);
curr = curr.next;
curr.next = null;
}
carry = (int1.v+int2.v+carry)/10;
int1=int1.next;
int2=int2.next;
}
while(int1!=null){
curr.next = new Node((int1.v+carry)%10);
curr = curr.next;
curr.next = null;
carry = (int1.v+carry)/10;
int1=int1.next;
}
while(int2!=null){
curr.next = new Node((int2.v+carry)%10);
curr = curr.next;
curr.next = null;
carry = (int2.v+carry)/10;
int2=int2.next;
}
return newh;
} | 5 |
@Override
public void setHouseNumber(String houseNumber) {
super.setHouseNumber(houseNumber);
} | 0 |
@Override
public void keyPressed(KeyEvent e) {
//MOVEMENT KEYS
if (e.getKeyCode() == KeyEvent.VK_W){
if (player.jumpCount < player.jumpMax) {
player.gravity = 20;
player.setY(player.getY() - 10);
player.jumpCount++;
}
}
if (e.getKeyCode() == KeyEvent.VK_A){
left = true;
}
if (e.getKeyCode() == KeyEvent.VK_S){
// down = true;
}
if (e.getKeyCode() == KeyEvent.VK_D){
right = true;
}
//SHOOT KEYS
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftShoot = true ;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightShoot = true ;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upShoot = true ;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downShoot = true ;
}
} | 9 |
@Override
public void run() {
for(int i = 0; i < 20 ; i ++)
{
try {
Thread.sleep((long)Math.random() * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SampleCalc.decrease();
}
} | 2 |
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (this.id != null ? this.id.hashCode() : 0);
hash = 97 * hash + (this.datapagamento != null ? this.datapagamento.hashCode() : 0);
hash = 97 * hash + (int) (Double.doubleToLongBits(this.valor) ^ (Double.doubleToLongBits(this.valor) >>> 32));
hash = 97 * hash + (this.statuspagamento != null ? this.statuspagamento.hashCode() : 0);
hash = 97 * hash + (this.formapagamento != null ? this.formapagamento.hashCode() : 0);
hash = 97 * hash + (this.divida != null ? this.divida.hashCode() : 0);
return hash;
} | 5 |
public static void dumpArrayOfLinesToFile(
File file,
String encoding,
List lines,
List lineEndings
) {
try {
// Create Parent Directories
File parent = new File(file.getParent());
parent.mkdirs();
// Write the File
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
for (int i = 0; i < lines.size(); i++) {
String line = (String) lines.get(i);
String lineEnding = (String) lineEndings.get(i);
if (line != null) {
out.write(line);
}
if (lineEnding != null) {
out.write(lineEnding);
}
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 4 |
public String getThumbUrl() {
return thumbUrl;
} | 0 |
@Override
public boolean status(int row, int col) {
if (this.copyPapan[row][col].equals("W")) {
return true;
} else if (this.copyPapan[row][col].equals("=")) {
if (this.banyakIC == 0) {
return true;
} else {
return false;
}
} else {
return true;
}
} | 3 |
@Override
public void solveVelocityConstraints(final TimeStep step) {
final Body b1 = m_bodyA;
final Body b2 = m_bodyB;
final Vec2 v1 = b1.m_linearVelocity;
float w1 = b1.m_angularVelocity;
final Vec2 v2 = b2.m_linearVelocity;
float w2 = b2.m_angularVelocity;
float m1 = b1.m_invMass, m2 = b2.m_invMass;
float i1 = b1.m_invI, i2 = b2.m_invI;
// Solve motor constraint.
if (m_enableMotor && m_limitState != LimitState.EQUAL) {
float Cdot = w2 - w1 - m_motorSpeed;
float impulse = m_motorMass * (-Cdot);
float oldImpulse = m_motorImpulse;
float maxImpulse = step.dt * m_maxMotorTorque;
m_motorImpulse = MathUtils.clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
w1 -= i1 * impulse;
w2 += i2 * impulse;
}
final Vec2 temp = pool.popVec2();
final Vec2 r1 = pool.popVec2();
final Vec2 r2 = pool.popVec2();
// Solve limit constraint.
if (m_enableLimit && m_limitState != LimitState.INACTIVE) {
r1.set(m_localAnchor1).subLocal(b1.getLocalCenter());
r2.set(m_localAnchor2).subLocal(b2.getLocalCenter());
Mat22.mulToOut(b1.getTransform().R, r1, r1);
Mat22.mulToOut(b2.getTransform().R, r2, r2);
// Vec2 r1 = b2Mul(b1.getTransform().R, m_localAnchor1 - b1.getLocalCenter());
// Vec2 r2 = b2Mul(b2.getTransform().R, m_localAnchor2 - b2.getLocalCenter());
final Vec2 Cdot1 = pool.popVec2();
final Vec3 Cdot = pool.popVec3();
// Solve point-to-point constraint
Vec2.crossToOut(w1, r1, temp);
Vec2.crossToOut(w2, r2, Cdot1);
Cdot1.addLocal(v2).subLocal(v1).subLocal(temp);
float Cdot2 = w2 - w1;
Cdot.set(Cdot1.x, Cdot1.y, Cdot2);
// Vec2 Cdot1 = v2 + b2Cross(w2, r2) - v1 - b2Cross(w1, r1);
// float Cdot2 = w2 - w1;
// b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
Vec3 impulse = pool.popVec3();
m_mass.solve33ToOut(Cdot.negateLocal(), impulse);
// Cdot.negateLocal(); just leave negated, we don't use later
if (m_limitState == LimitState.EQUAL) {
m_impulse.addLocal(impulse);
}
else if (m_limitState == LimitState.AT_LOWER) {
float newImpulse = m_impulse.z + impulse.z;
if (newImpulse < 0.0f) {
m_mass.solve22ToOut(Cdot1.negateLocal(), temp);
//Cdot1.negateLocal(); just leave negated, we don't use it again
impulse.x = temp.x;
impulse.y = temp.y;
impulse.z = -m_impulse.z;
m_impulse.x += temp.x;
m_impulse.y += temp.y;
m_impulse.z = 0.0f;
}
}
else if (m_limitState == LimitState.AT_UPPER) {
float newImpulse = m_impulse.z + impulse.z;
if (newImpulse > 0.0f) {
m_mass.solve22ToOut(Cdot1.negateLocal(), temp);
//Cdot1.negateLocal(); just leave negated, we don't use it again
impulse.x = temp.x;
impulse.y = temp.y;
impulse.z = -m_impulse.z;
m_impulse.x += temp.x;
m_impulse.y += temp.y;
m_impulse.z = 0.0f;
}
}
final Vec2 P = pool.popVec2();
P.set(impulse.x, impulse.y);
temp.set(P).mulLocal(m1);
v1.subLocal(temp);
w1 -= i1 * (Vec2.cross(r1, P) + impulse.z);
temp.set(P).mulLocal(m2);
v2.addLocal(temp);
w2 += i2 * (Vec2.cross(r2, P) + impulse.z);
pool.pushVec2(2);
pool.pushVec3(2);
}
else {
r1.set(m_localAnchor1).subLocal(b1.getLocalCenter());
r2.set(m_localAnchor2).subLocal(b2.getLocalCenter());
Mat22.mulToOut(b1.getTransform().R, r1, r1);
Mat22.mulToOut(b2.getTransform().R, r2, r2);
// Vec2 r1 = b2Mul(b1.getTransform().R, m_localAnchor1 - b1.getLocalCenter());
// Vec2 r2 = b2Mul(b2.getTransform().R, m_localAnchor2 - b2.getLocalCenter());
// Solve point-to-point constraint
Vec2 Cdot = pool.popVec2();
Vec2 impulse = pool.popVec2();
Vec2.crossToOut(w1, r1, temp);
Vec2.crossToOut(w2, r2, Cdot);
Cdot.addLocal(v2).subLocal(v1).subLocal(temp);
m_mass.solve22ToOut(Cdot.negateLocal(), impulse); // just leave negated
m_impulse.x += impulse.x;
m_impulse.y += impulse.y;
temp.set(impulse).mulLocal(m1);
v1.subLocal(temp);
w1 -= i1 * Vec2.cross(r1, impulse);
temp.set(impulse).mulLocal(m2);
v2.addLocal(temp);
w2 += i2 * Vec2.cross(r2, impulse);
pool.pushVec2(2);
}
b1.m_angularVelocity = w1;
b2.m_angularVelocity = w2;
pool.pushVec2(3);
} | 9 |
public String getSource() {
return this.source;
} | 0 |
void encode(OutputStream os) throws IOException {
os.write(initCodeSize);
countDown = imgW * imgH;
xCur = yCur = curPass = 0;
compress(initCodeSize + 1, os);
os.write(0);
} | 5 |
public void registerProjectile(Projectile p) {
if (!projectiles.containsKey(p.getId())) {
projectiles.put(p.getId(), p);
}
} | 1 |
private static Node search(Node r, int v) {
Node curr = r;
while (curr != null) {
if (curr.v == v) {
return curr;
} else if (curr.v < v) {
curr = curr.right;
} else {
curr = curr.left;
}
}
return null;
} | 3 |
public static double calculate(String first, String second, String operation) {
double fNum = Double.parseDouble(first);
double sNum = Double.parseDouble(second);
double result = 0;
if (operation.equals("add")) {
result = fNum + sNum;
}
else if (operation.equals("subtract")) {
result = fNum - sNum;
}
else if (operation.equals("divide")) {
result = fNum / sNum;
}
else if (operation.equals("multiply")) {
result = fNum * sNum;
}
return result;
} | 4 |
private JLabel getJLabel0() {
if (jLabel0 == null) {
jLabel0 = new JLabel();
jLabel0.setText("sql:");
}
return jLabel0;
} | 1 |
public void setContestId(Integer contestId) {
this.contestId = contestId;
} | 0 |
private static int[] merge(int[] array1,int[] array2){
int length1 = array1.length;
int length2 = array2.length;
int[] resultarray = new int[length1+length2];
int indexofarray1 = 0;
int indexofarray2 = 0;
int indexofresultarray = 0;
while(indexofarray1 < length1 && indexofarray2 < length2){
if (array1[indexofarray1] <= array2[indexofarray2]) {
resultarray[indexofresultarray] = array1[indexofarray1];
indexofarray1++;
indexofresultarray++;
}else{
resultarray[indexofresultarray] = array2[indexofarray2];
indexofarray2++;
indexofresultarray++;
}
}
while(indexofarray1 < length1){
resultarray[indexofresultarray] = array1[indexofarray1];
indexofarray1++;
indexofresultarray++;
}
while(indexofarray2 < length2){
resultarray[indexofresultarray] = array2[indexofarray2];
indexofarray2++;
indexofresultarray++;
}
return resultarray;
} | 5 |
private void gameRender() {
if (dbImage == null) {
dbImage = createImage(pWidth, pHeight);
if (dbImage == null) {
System.out.println("dbImage is null");
return;
} else
dbg = dbImage.getGraphics();
}
// clear the background
dbg.setColor(Color.white);
dbg.fillRect(0, 0, pWidth, pHeight);
dbg.setColor(Color.blue);
dbg.setFont(font);
// report frame count & average FPS and UPS at top left
// dbg.drawString("Frame Count " + frameCount, 10, 25);
// dbg.drawString(
// "Average FPS/UPS: " + df.format(averageFPS) + ", "
// + df.format(averageUPS), 20, 20 ); // was (10,55)
dbg.setColor(Color.black);
// draw game elements
/**
* Draw Nodes
*/
ArrayList<Node> nodeCopy = new ArrayList<Node>(nodeList);
for(Node n : nodeCopy){
n.draw(dbg);
}
/**
* Draw player1 hand
*/
ArrayDeque<Block> p1Hand = player1.getHand().clone();
Iterator<Block> it = p1Hand.iterator();
int i = 1;
while(it.hasNext()){
Block b = (Block) it.next();
gui.setPlayer1HandAtIndex(b.getImage(), i);
i++;
}
/**
* Draw player2 hand
*/
ArrayDeque<Block> p2Hand = player2.getHand().clone();
Iterator<Block> it2 = p2Hand.iterator();
int j = 1;
while(it2.hasNext()){
Block b = (Block) it2.next();
gui.setPlayer2HandAtIndex(b.getImage(), j);
j++;
}
/**
* Draw grid (last to go over the nodes).
*/
this.grid.draw(dbg);
// TODO Make game objects draw themselves eg: point.draw(dbg).
if (gameOver)
gameOverMessage(dbg);
} // end of gameRender() | 6 |
public static int placeOrder(Order incord)
throws TableException{
java.sql.Statement stmt;
java.sql.ResultSet rs;
int orderid;
//extract data from the order object
Order ord = incord;
ArrayList<OrderItem> itemlist = ord.getOrderItems();
OrderItem item;
try
{
String createString = "insert into " + ORDERS_TABLE_NAME
+ " (CUSTOMER_ID, ORDER_DATE, ORDER_TOTAL ) VALUES("
+ ord.getCustomerID() + ", '" + getDateTime() + "', "
+ ord.calcOrderTotal() + " );";
stmt = sqlConn.createStatement();
//generated keys in this case is the order ID, which is an identity in the table
stmt.executeUpdate(createString, stmt.RETURN_GENERATED_KEYS);
rs = stmt.getGeneratedKeys();
rs.next();
orderid = rs.getInt(1);
try
{
for(int x = 0; x < itemlist.size(); x++)
{
item = itemlist.get(x);
OrderItemsDB.createItems(orderid, item.getProductID(), item.getProductQuant(), item.getProductPrice());
try
{
StockItemsDB.decrementStock(item.getProductID(), item.getProductQuant());
} //end try
catch (Exception e)
{
System.err.println("Error: " + e);
} //end catch
} //end for
} //end try
catch (OrderItemsDB.TableException e)
{
System.err.println("Error writing order items: " + e);
} //end catch
return orderid;
} //end try
catch (java.sql.SQLException e)
{
throw new TableException("Unable to create a new Order in the Database." + "\nDetail: " + e);
} //end catch
} //end placeOrder | 4 |
public static double EuclideanDistance(ArrayList<Double> l1, ArrayList<Double> l2){
if(l1.size() != l2.size()){
System.err.print("erro in input size\n");
}
int size = l1.size();
double sum = 0;
for(int i = 0; i < size; i++){
sum += (l1.get(i) - l2.get(i)) * (l1.get(i) - l2.get(i));
}
return Math.sqrt(sum);
} | 2 |
private void joinChat() {
if (isVerified && hasName) {
isInChat = true;
connection.send(NetMessage.newBuilder()
.setType(MessageType.REPLY)
.setReplyMessage(ReplyMessage.newBuilder()
.setType(MessageType.JOIN_CHAT)
.setStatus(true))
.build().toByteArray());
// connection.send(new NetObject(NetObject.ACKNOWLEDGE,NetObject.JOIN_CHAT,true));
manager.clientJoined(name);
} else
connection.send(NetMessage.newBuilder()
.setType(MessageType.REPLY)
.setReplyMessage(ReplyMessage.newBuilder()
.setType(MessageType.JOIN_CHAT)
.setStatus(false))
.build().toByteArray());
// connection.send(new NetObject(NetObject.ACKNOWLEDGE,NetObject.JOIN_CHAT,false));
} | 2 |
@Override
public Map<String, String> getSearchCritieras() {
Map<String, String> critieras = new HashMap<>();
if(!StringUtil.isEmpty(componentId.getText())) {
critieras.put("componentId", componentId.getText());
}
if(!StringUtil.isEmpty(date.getText())) {
critieras.put("date", date.getText());
}
if(!StringUtil.isEmpty(countBegin.getText())) {
critieras.put("countBegin", countBegin.getText());
}
if(!StringUtil.isEmpty(countEnd.getText())) {
critieras.put("countEnd", countEnd.getText());
}
if(!StringUtil.isEmpty(eId.getText())) {
critieras.put("eId", eId.getText());
}
if(!StringUtil.isEmpty(person.getText())) {
critieras.put("person", person.getText());
}
return critieras;
} | 6 |
public CodeEditor()
{
Font f;
JScrollPane []scrollPane;
JSplitPane componentSplitter ;
LineBar line;
Data data;
modifyLooks();
jlblStatus = new JLabel();
jta = (JTextArea) new TextArea();
lineBar = new LineBar();
outputWindow = new TextArea();
menuBar = (Menu)new Menu(this);
jFileChooser = new JFileChooser(new File("."));
classLoader = new ClassFileLoader();
f = new Font("Courier", Font.PLAIN, 13);
scrollPane = new JScrollPane[2];
for(int i=0; i<scrollPane.length; i++) scrollPane[i]= new JScrollPane();
componentSplitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane[0], scrollPane[1]);
line = new LineBar();
data = new Data();
initJavaRunner();
data.addObserver(line);
line.setEditable(false);
line.setBackground(Color.lightGray);
jta.setFont(f);
jta.setTabSize(4);
jta.getDocument().addDocumentListener(data);
line.setFont(f);
scrollPane[0].setViewportView(jta);
scrollPane[0].setRowHeaderView(line);
scrollPane[1].setViewportView(outputWindow);
componentSplitter.setDividerLocation(150);
this.setJMenuBar(menuBar);
this.add(componentSplitter, BorderLayout.CENTER);
this.add(jlblStatus, BorderLayout.PAGE_END);
} | 1 |
private double expectedScore(int[] distribution,int[] plate)
{
double[] problist = new double[numfruits * length + 1];
int minscore = numfruits * 1, maxscore = numfruits * length;
time01 = System.nanoTime();
initFruitProbs();
time11 += System.nanoTime() - time01;
time02 = System.nanoTime();
double expectedscore = 0.0;
int increment = 1;
/*
int increment = (int) Math.ceil((maxscore - minscore) / 55.0);
if(numfruits % 2 == 1)
minscore = minscore + 1;
if(increment % 2 == 1 && increment != 1)
increment = increment - 1;
*/
for(int i = minscore; i <= maxscore; i = i + increment)
{
problist[i] = problist[i - increment] + getFruitProbs(0,(int) Math.round(numfruits),i) * increment;
expectedscore = expectedscore + i * (Math.pow(problist[i], choicesleft) - Math.pow(problist[i - increment], choicesleft));
// outfile.println(Integer.toString(i) + "\t" + Double.toString(problist[i] - problist[i - 1]));
}
// outfile.println("");
// outfile.println(Integer.toString((int) expectedscore) + " " + Integer.toString((int) (plateScore(distribution) / choicesleft)) + " " + Integer.toString(choicesleft));
// outfile.flush();
time12 += System.nanoTime() - time02;
return Math.floor(expectedscore);
} | 1 |
@Override
public int attack(double agility, double luck) {
if(random.nextInt(100) < luck)
{
System.out.println("The power of Priest compells you!");
return random.nextInt((int) agility) * 3;
}
return 0;
} | 1 |
public long inserir(AreaFormacao areaformacao) throws Exception
{
String sql = "INSERT INTO areaformacao (nome) VALUES (?)";
long IdGerado = 0;
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, areaformacao.getNome());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
IdGerado = rs.getLong(1);
}
}
catch (SQLException e)
{
throw e;
}
return IdGerado;
} | 2 |
public StreamEngine (SocketChannel fd_, final Options options_, final String endpoint_)
{
handle = fd_;
inbuf = null;
insize = 0;
io_enabled = false;
outbuf = null;
outsize = 0;
handshaking = true;
session = null;
options = options_;
plugged = false;
terminating = false;
endpoint = endpoint_;
socket = null;
greeting = ByteBuffer.allocate (GREETING_SIZE);
greeting_output_buffer = ByteBuffer.allocate (GREETING_SIZE);
encoder = null;
decoder = null;
// Put the socket into non-blocking mode.
try {
Utils.unblock_socket (handle);
// Set the socket buffer limits for the underlying socket.
if (options.sndbuf != 0) {
handle.socket().setSendBufferSize((int)options.sndbuf);
}
if (options.rcvbuf != 0) {
handle.socket().setReceiveBufferSize((int)options.rcvbuf);
}
} catch (IOException e) {
throw new ZError.IOException(e);
}
} | 3 |
void makePairs() {
if (res > 1)
return;
boolean allVisited = true;
for (int i = 0; i < N; i++) {
allVisited &= visited[i];
}
if (allVisited) {
res++;
return;
}
for (int index = 0; index < N; index++)
for (int i = 0; i < N; i++) {
if (friends[index][i] && !visited[i]) {
visited[index] = true;
visited[i] = true;
makePairs();
visited[index] = false;
visited[i] = false;
}
}
} | 7 |
public void loadArgArray() {
push(argumentTypes.length);
newArray(OBJECT_TYPE);
for (int i = 0; i < argumentTypes.length; i++) {
dup();
push(i);
loadArg(i);
box(argumentTypes[i]);
arrayStore(OBJECT_TYPE);
}
} | 1 |
public void enterShop(HumanCharacter theHumanCharacter){
System.out.println("Welcome to the shop!");
System.out.println("What would you like to buy?");
System.out.println("Type 'mana potion' for Mana Potions --20g each");
System.out.println("Type 'health potion' for Health Potions --15g each");
System.out.println("Type 'exit' to leave.");
System.out.println("Your gold: " + theHumanCharacter.getGold());
System.out.print("Command:");
String choice = input.nextLine();
if(choice.compareTo("")==0){
System.out.println("Error catching...please input again...");
choice = input.nextLine();
}
if(choice.compareTo("mana potion") == 0){
theHumanCharacter.buyManaPotions(this.sellPotions("mana potion"));
}
else if(choice.compareTo("health potion") == 0){
theHumanCharacter.buyHealthPotions(this.sellPotions("health potion"));
}
else if(choice.compareTo("exit") == 0){
System.out.println("Good bye!");
}
} | 4 |
public static final int getDimension(Object array) {
if (array != null) {
Class<?> clazz = array.getClass();
if (clazz.isArray()) {
String className = clazz.getName();
int len = className.length();
for (int i = 0; i < len; i++) {
if (className.charAt(i) != '[') {
return i;
}
}
}
}
return -1;
} | 5 |
@Override
public synchronized String format(LogRecord record) {
StringBuffer sb = new StringBuffer();
dat.setTime(record.getMillis());
args[0] = dat;
StringBuffer text = new StringBuffer();
if (formatter == null) {
formatter = new MessageFormat(format);
}
formatter.format(args, text, null);
sb.append(text);
sb.append(" ");
if (record.getSourceClassName() != null) {
sb.append(record.getSourceClassName().substring(
record.getSourceClassName().lastIndexOf(".") + 1));
} else {
sb.append(record.getLoggerName());
}
if (record.getSourceMethodName() != null) {
sb.append(".");
sb.append(record.getSourceMethodName() + "()");
}
sb.append(" ");
String message = formatMessage(record);
sb.append(record.getLevel().getLocalizedName());
sb.append(": ");
sb.append(message);
sb.append(lineSeparator);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) { };
}
return sb.toString();
} | 5 |
@Override
public void onMove() { // Constante descendente e implementacion de onUp
// Movimiento del background
backgroundUX += (backgroundSpeed / Window.getW()) * App.getFTime();
// Movimiento del pajaro
pardal.move(); // Este es para que se mueva su sprite (animacion)
aceleracion += 750.0f * App.getFTime();
if (aceleracion >500)
aceleracion = 500.0f;
pardal.setAltura(pardal.getAltura() + aceleracion * App.getFTime());
// Si sale por arriba de la pantalla el pajaro
if(pardal.getAltura()-pardal.getH() <0) {
aceleracion = 0.0f;
pardal.setAltura(pardal.getH());
}
// Si sale por abajo
if (pardal.getAltura() >= Window.getH()) {
pardal.setAltura(Window.getH());
pause();
}
// Movimiento de las tuberias
tuberia.setX(tuberia.getX() - tubSpeed * App.getFTime());
tuberia2.setX(tuberia2.getX() - tubSpeed * App.getFTime());
if (tuberia.getX() < -tuberia.getW()) {
tuberia.setX(tuberia2.getX()+separacionTuberias);
tuberia.randomEspacio();
}
if (tuberia2.getX() < -tuberia2.getW()) {
tuberia2.setX(tuberia.getX()+separacionTuberias);
tuberia2.randomEspacio();
}
if (tuberia.chocaElPardalet(pardal.getX(), pardal.getAltura()-pardal.getH(), pardal.getW(), pardal.getH())) {
System.out.print("Tubo1");
if(pardal.getX()+pardal.getW()<tuberia.getX()){
pause();
}
}
if (tuberia2.chocaElPardalet(pardal.getX(), pardal.getAltura()-pardal.getH(), pardal.getW(), pardal.getH())) {
System.out.print("Tubo2");
if(pardal.getX()+pardal.getW()<tuberia.getX()){
pause();
}
}
} | 9 |
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
g.setColor(Color.WHITE);
if (ship != null) {
for (int i = 0; i < vh.vel.size(); i++) {
Moveable m = vh.get(i);
if (!m.isInScreen(frame.getSize()) && !isShip(m))
vh.vel.remove(i);
m.render(g);
}
g.drawString("Ship: ", 0, 30);
g.drawString("Rotation = " + (ship.rotation * (180 / Math.PI)), 0, 40);
g.drawString("Pos = " + ship.pos.x + " , " + ship.pos.y, 0, 50);
g.drawString("Vel = " + ship.vel.x + " , " + ship.vel.y, 0, 60);
if (vh.vel.size() > 0) {
Bullet b = null;
for (Moveable m : vh.vel) {
try {
b = (Bullet) m;
} catch (Exception e) {
b = null;
}
}
if (b != null) {
g.drawString("Most Recent Bullet: ", 0, 80);
g.drawString("Pos = " + b.pos.x + " , " + b.pos.y, 0, 90);
g.drawString("Vel = " + b.vel.x + " , " + b.vel.y, 0, 100);
}
}
}
g.drawString("FPS: " + fps, 0, 10);
} | 8 |
private void generateDeck()
{
Suit[] suits = Suit.values();
Figure[] figures = Figure.values();
for(Suit suit : suits)
{
for(Figure figure : figures)
{
cards.add(new Card(figure,suit));
}
}
} | 2 |
public static int getDirection(BoardNode node1, BoardNode node2){
int x1 = node1.getX();
int y1 = node1.getY();
int x2 = node2.getX();
int y2 = node2.getY();
if(isDown(node1, node2) == true){
node2.setDir(DOWN);
}
else if(isUp(node1, node2) == true){
node2.setDir(UP);
}
else if(isLeft(node1, node2) == true){
node2.setDir(LEFT);
}
else if(isRight(node1, node2) == true){
node2.setDir(RIGHT);
}
else if(isDownLeft(node1, node2) == true){
node2.setDir(DOWNLEFT);
}
else if(isDownRight(node1, node2) == true){
node2.setDir(DOWNRIGHT);
}
else if(isUpRight(node1, node2) == true){
node2.setDir(UPRIGHT);
}
else if(isUpLeft(node1, node2) == true){
node2.setDir(UPLEFT);
}
else{
node2.setDir(-1);
}
return node2.getDir();
} | 8 |
public void visitSwitchStmt(final SwitchStmt stmt) {
if (previous == stmt.index()) {
previous = stmt;
stmt.parent.visit(this);
}
} | 1 |
private static void test_powerOf2(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 2) {
boolean exp = (Boolean) t.tests[i];
int arg1 = (Integer) t.tests[i + 1];
boolean res = HW2Operations.powerOf2(arg1);
boolean cor = exp == res;
if (cor) {
++score;
}
pw.printf("%s(%8X): Expected: %5b Result: %5b Correct: %5b\n",
t.name, arg1, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 2);
} | 2 |
public int evaluateState(State state) {
int evaluatedValue = 0;
if (state.getCellList().get(0).getCellValue() != 1)
evaluatedValue += 1;
if (state.getCellList().get(1).getCellValue() != 2)
evaluatedValue += 1;
if (state.getCellList().get(2).getCellValue() != 3)
evaluatedValue += 1;
if (state.getCellList().get(3).getCellValue() != 8)
evaluatedValue += 1;
if (state.getCellList().get(4).getCellValue() != 0)
evaluatedValue += 1;
if (state.getCellList().get(5).getCellValue() != 4)
evaluatedValue += 1;
if (state.getCellList().get(6).getCellValue() != 7)
evaluatedValue += 1;
if (state.getCellList().get(7).getCellValue() != 6)
evaluatedValue += 1;
if (state.getCellList().get(8).getCellValue() != 5)
evaluatedValue += 1;
return evaluatedValue;
} | 9 |
public void setId(String id) {
this.id = id;
} | 0 |
public void visit_ineg(final Instruction inst) {
stackHeight -= 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
public static Cons yieldHardcodedInternRegisteredSymbolsTree() {
{ Cons interntrees = Cons.list$(Cons.cons(Stella.SYM_STELLA_STARTUP_TIME_PROGN, Cons.cons(Stella.KWD_SYMBOLS, Cons.cons(Stella.NIL, Stella.NIL))));
{ GeneralizedSymbol symbol = null;
Cons iter000 = Stella.$SYMBOL_SET$.theConsList;
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
symbol = ((GeneralizedSymbol)(iter000.value));
if (collect000 == null) {
{
collect000 = Cons.cons(Cons.cons((Stella_Object.symbolP(symbol) ? Stella.SYM_STELLA_INTERN_SYMBOL_AT : ((Stella_Object.surrogateP(symbol) ? Stella.SYM_STELLA_INTERN_SURROGATE_AT : Stella.SYM_STELLA_INTERN_KEYWORD_AT))), Cons.cons(StringWrapper.wrapString(symbol.symbolName), Cons.cons(IntegerWrapper.wrapInteger(symbol.symbolId), Stella.NIL))), Stella.NIL);
if (interntrees == Stella.NIL) {
interntrees = collect000;
}
else {
Cons.addConsToEndOfConsList(interntrees, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(Cons.cons((Stella_Object.symbolP(symbol) ? Stella.SYM_STELLA_INTERN_SYMBOL_AT : ((Stella_Object.surrogateP(symbol) ? Stella.SYM_STELLA_INTERN_SURROGATE_AT : Stella.SYM_STELLA_INTERN_KEYWORD_AT))), Cons.cons(StringWrapper.wrapString(symbol.symbolName), Cons.cons(IntegerWrapper.wrapInteger(symbol.symbolId), Stella.NIL))), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
return (interntrees);
}
} | 7 |
private SubmissionResult compileWithTestsAndRun(Submission submission) {
CompilationResult compilation;
try {
compilation = compileWithTests(submission);
} catch (CodeStyleException e) {
SubmissionResult result = new SubmissionResult();
result.setPass(false);
result.getCompilationErrors().add(e.getMessage());
return result;
}
if (compilation.passed()) {
return run(compilation);
} else {
return compilation.asSubmissionResult();
}
} | 2 |
private boolean zipPage(ZipOutputStream zipOut, File zipDir) {
if (zipOut == null)
return false;
boolean isChanged = saveReminder.isChanged();
saveTo(new File(zipDir, FileUtilities.getFileName(pageAddress)));
saveReminder.setChanged(isChanged); // reset the SaveReminder
nameModels(); // reset the model names
File[] f = zipDir.listFiles();
FileInputStream in = null;
int c;
boolean b = true;
try {
for (int i = 0; i < f.length; i++) {
zipOut.putNextEntry(new ZipEntry(f[i].getName()));
in = new FileInputStream(f[i]);
while ((c = in.read()) != -1)
zipOut.write(c);
in.close();
zipOut.closeEntry();
zipOut.flush();
}
zipOut.finish(); // necessary?
} catch (IOException e) {
e.printStackTrace();
b = false;
} finally {
if (in != null) { // just in case the last input stream is not closed
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
FileUtilities.deleteAllFiles(zipDir);
zipDir.delete();
}
return b;
} | 7 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RectangleShape that = (RectangleShape) o;
if (entered != that.entered) return false;
if (currentPoint != null ? !currentPoint.equals(that.currentPoint) : that.currentPoint != null) return false;
if (points != null ? !points.equals(that.points) : that.points != null) return false;
return true;
} | 8 |
public static void main(String[] args) {
int direction = (int) (Math.random() * 5);
switch (direction) {
case NORTH:
System.out.println("travelling north");
break;
case SOUTH:
System.out.println("travelling south");
break;
case EAST:
System.out.println("travelling east");
break;
case WEST:
System.out.println("travelling west");
break;
default:
assert false;
}
} | 4 |
public String[] getStreamInfo() {
String[] address = new String[4];
//get selectet Streams
if(browseTable.getSelectedRow() >= 0) {
Vector<String[]> streams = null;
//get Nr. of Stream
Object content = browseTable.getValueAt(browseTable.getSelectedRow(),0);
int nr = Integer.valueOf(content.toString());
//get Streams in Vector
//if the stream is filtered, get the filtered stream vector
//else the original
if(filter.isFiltered()) {
streams = filter.getFilteredStreamVector();
SRSOutput.getInstance().log("Use Filtered StreamVector");
} else {
streams = controlHttp.getStreams();
SRSOutput.getInstance().log("Use Normal StreamVector");
}
if(streams != null) {
//save main address from site (e.g www.shoutcast.com)
String url = controlHttp.getBaseAddress()+streams.get(nr)[5];
//get address from .pls file
address[0] = controlHttp.getfirstStreamFromURL(url);
address[1] = streams.get(nr)[0];
address[2] = streams.get(nr)[6];
address[3] = streams.get(nr)[7];
} else {
SRSOutput.getInstance().logE("Gets an empty FILTERED stream vector: can't get info");
}
}
return address;
} | 3 |
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Marquee();
}
});
} | 0 |
@Override
public void focusGained(FocusEvent e) {
handleUpdate();
} | 0 |
public void runInTheCloud() {
TestInfo testInfo = this.getTestInfo();
if (testInfo == null) {
BmLog.error("TestInfo is null, test won't be started");
return;
}
BmLog.info("Starting test " + testInfo.getId() + "-" + testInfo.getName());
TestInfoController.stop();
testInfo = rpc.runInTheCloud(this.getUserKey(), testInfo.getId());
setTestInfo(testInfo);
} | 1 |
@Test
public void testCoordPair() {
CoordPair pair = new CoordPair(676, 989);
assertTrue("toString contains values", pair.toString().contains("676") && pair.toString().contains("989"));
assertTrue("X value returned correctly", pair.getX() == 676);
assertTrue("Y value returned correctly", pair.getY() == 989);
Set<Integer> hashCodeSet = new HashSet<>();
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
hashCodeSet.add(new CoordPair(i, j).hashCode());
}
}
assertTrue("CoordPair [0-10][0-10] hash codes are unique", hashCodeSet.size() == 100);
} | 3 |
public void dontPassLine(int bet) {
if (money > 0 && bet <= money && bet >= 0) {
if (combinedRoll == 2 || combinedRoll == 3) {
player.addMoney(bet);
info.updateMoney();
} else if (combinedRoll == 7 || combinedRoll == 11) {
player.loseMoney(bet);
info.updateMoney();
} else if (combinedRoll == 12) {
player.addMoney(0);
info.updateMoney();
} else {
dice1.roll();
dice2.roll();
combinedRoll = dice1.combine(dice2);
this.dontPassLine(bet);
}
}
count++;
} | 8 |
private void setupMouseCallbacks() {
transferHandler = new GridMouseResultsTransferHandler();
constraintsModel = new GridMouseConstraintsModel(0, 0, maxWidth, maxHeight, CHR_PIXELS_WIDE, CHR_PIXELS_HIGH, PPUConstants.COLUMNS_PER_PATTERN_PAGE, PPUConstants.ROWS_PER_PATTERN_PAGE);
setTransferHandler(transferHandler);
if (modelRef == null) {
// add a generic mouse motion listener to help with tooltips
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
String text = "";
int index = constraintsModel.getArrayIndexFromPosition(e.getX(), e.getY());
if (index != NES_UI_Constants.INVALID_VALUE) {
int xIndex = constraintsModel.getGridXIndexFromPosition(e.getX(), e.getY());
int yIndex = constraintsModel.getGridYIndexFromPosition(e.getX(), e.getY());
text = "[" + xIndex + "," + yIndex + "] 0x" + ByteFormatter.formatSingleByteInt(index);
}
// determine position
setToolTipText(text);
}
});
return;
}
resultsModel = new GridMouseResultsModel(0, 0, PPUConstants.COLUMNS_PER_PATTERN_PAGE, PPUConstants.ROWS_PER_PATTERN_PAGE, modelRef.getCHRModel());
dragAdapter = new GridMouseInputAndDragAdapter(resultsModel);
addMouseListener(dragAdapter);
addMouseMotionListener(dragAdapter);
dragAdapter.refreshCTD(TransferHandler.NONE, getDropTarget());
dragAdapter.assignMousePressedCallback(MouseEvent.BUTTON1, new MouseActionCallback() {
public void doCallback(MouseEvent e, GridMouseResultsModel resultsModel) {
resultsModel.resetBox();
}
});
dragAdapter.assignMouseClickedCallback(MouseEvent.BUTTON1, new MouseActionCallback() {
public void doCallback(MouseEvent e, GridMouseResultsModel resultsModel) {
int index = constraintsModel.getArrayIndexFromPosition(e.getX(), e.getY());
if (index == NES_UI_Constants.INVALID_VALUE) {
return;
}
int xIndex = constraintsModel.getGridXIndexFromPosition(e.getX(), e.getY());
int yIndex = constraintsModel.getGridYIndexFromPosition(e.getX(), e.getY());
resultsModel.assignIndexX(xIndex);
resultsModel.assignIndexY(yIndex);
resultsModel.assignIndex(index);
processLeftClick(resultsModel.getIndex());
}
});
dragAdapter.assignMouseClickedCallback(MouseEvent.BUTTON3, new MouseActionCallback() {
public void doCallback(MouseEvent e, GridMouseResultsModel resultsModel) {
int index = constraintsModel.getArrayIndexFromPosition(e.getX(), e.getY());
if (index == NES_UI_Constants.INVALID_VALUE) {
return;
}
int xIndex = constraintsModel.getGridXIndexFromPosition(e.getX(), e.getY());
int yIndex = constraintsModel.getGridYIndexFromPosition(e.getX(), e.getY());
resultsModel.assignIndexX(xIndex);
resultsModel.assignIndexY(yIndex);
resultsModel.assignIndex(index);
processRightClick(resultsModel.getIndex());
}
});
dragAdapter.assignMouseMovedCallback(new MouseMoveCallback() {
public void doMoveCallback(MouseEvent e) {
String text = "";
int index = constraintsModel.getArrayIndexFromPosition(e.getX(), e.getY());
if (index != NES_UI_Constants.INVALID_VALUE) {
int xIndex = constraintsModel.getGridXIndexFromPosition(e.getX(), e.getY());
int yIndex = constraintsModel.getGridYIndexFromPosition(e.getX(), e.getY());
text = "[" + xIndex + "," + yIndex + "] 0x" + ByteFormatter.formatSingleByteInt(index);
}
// determine position
setToolTipText(text);
}
});
dragAdapter.assignMouseDraggedCallback(new MouseDragCallback() {
private void leftDrag(MouseEvent firstEvent, MouseEvent e, GridMouseResultsModel results) {
results.assignPatternPage(pageNum);
int relX = constraintsModel.getGridXIndexFromPosition(e.getX(), e.getY());
results.assignBoxX(relX);
int relY = constraintsModel.getGridYIndexFromPosition(e.getX(), e.getY());
results.assignBoxY(relY);
System.out.println(e.getX() + "," + e.getY() + " <> " + relX + "," + relY);
updatePatternTableSelection();
}
private void rightDrag(MouseEvent firstEvent, MouseEvent e, GridMouseResultsModel resultsModel) {
// you can ONLY drag a results box
if (!resultsModel.isBoxValid()) {
return;
}
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
//Tell the transfer handler to initiate the drag.
int action = ((e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) == InputEvent.CTRL_DOWN_MASK) ? TransferHandler.COPY : TransferHandler.MOVE;
handler.exportAsDrag(c, firstEvent, action);
dragAdapter.refreshCTD(action, c.getDropTarget());
}
public void doDragCallback(MouseEvent firstEvent, MouseEvent e, GridMouseResultsModel resultsModel) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
leftDrag(firstEvent, e, resultsModel);
}
if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
rightDrag(firstEvent, e, resultsModel);
}
}
});
} | 9 |
@Override
public void run () {
boolean backupOnlyWithPlayer = pSystem.getBooleanProperty(BOOL_BACKUP_ONLY_PLAYER);
if ((backupOnlyWithPlayer && server.getOnlinePlayers().length > 0)
|| !backupOnlyWithPlayer
|| isManuelBackup
|| backupName != null)
prepareBackup();
else
System.out.println("[BACKUP] Scheduled backup was aborted due to lack of players. Next backup attempt in " + pSystem.getIntProperty(INT_BACKUP_INTERVALL) / 1200 + " minutes.");
} | 5 |
public static Image convertStreamToPNG(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[defaultBufferSize];
int n;
while ((n = is.read(buf)) >= 0) {
baos.write(buf, 0, n);
}
baos.close();
return convertBlobToPNG(baos.toByteArray());
} | 1 |
public OutlinerDesktopManager() {
super();
} | 0 |
public Entity[] allInstancesAt(int x, int y) {
ArrayList<Entity> ans = new ArrayList<Entity>();
for(Entity e : entities) {
if(e.x == x && e.y == y && !e.willBeRemoved()) ans.add(e);
}
for(Entity e : addQueue) {
if(e.x == x && e.y == y && !e.willBeRemoved()) ans.add(e);
}
Entity[] ret = new Entity[ans.size()];
for(int i=0; i<ret.length; i++) {
ret[i] = ans.get(i);
}
return ret;
} | 9 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
} | 0 |
public double getFullCost()
{
double cost = 0;
for (Edge edge : edges)
cost += edge.getCost();
return cost;
} | 1 |
public Block[][] getBlocks(int x1, int y1, int x2, int y2){
Block[][] blocks = new Block[x2-x1+1][y2-y1+1];
for(int x = x1; x <= x2; x++){
for(int y = y1; y <= y2; y++){
blocks[x-x1][y-y1] = this.blocks[x/POSITION_MULTIPLYER+1][y/POSITION_MULTIPLYER+1]; //fucking no idea why there must be a +1 but otherwise it takes the wrong block
}
}
return blocks;
} | 2 |
public synchronized static String getConfigDirectoryPath() {
if(resourcePath == null) {
resourcePath = getUserHome();
}
if(resourcePath.charAt(resourcePath.length()-1) != File.separatorChar) {
resourcePath += File.separatorChar;
}
return resourcePath + "frontlinesms_h2_db";
} | 2 |
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() > 0 && e.getKeyCode() < 256) {
keys[e.getKeyCode()] = false;
}
} | 2 |
@Override
public List<Invoker<T>> list(Invocation invocation) throws RpcException {
if (isDestroyed()) {
throw new RpcException("Directory already destroyed .url: " + tpURL);
}
List<Invoker<T>> invokers = doList(invocation);
if (routers != null && routers.size() > 0) {
for (Router router: routers){
try {
invokers = router.route(invokers, tpURL, invocation);
} catch (Throwable t) {
logger.error("Failed to execute router: " + tpURL + ", cause: " + t.getMessage(), t);
}
}
}
return invokers;
} | 5 |
public void endArena(String arenaName) {
if (getArena(arenaName) != null) { //If the arena exsists
Arena arena = getArena(arenaName);
//Create an arena for using in this method
//Send them a message
arena.sendMessage(ChatColor.GOLD + "The Game is over");
if (arena.getSurvivor().size() == 0) {
arena.sendMessage(ChatColor.GOLD + "[BowTag] The Bowmen have won and earned xx");
ArrayList<String> bowMen = arena.getBowMen();
for (String s: bowMen) {
BowTag.economy.depositPlayer(s, 10.0);
Bukkit.getPlayer(s).sendMessage("You earnerd 10");
}
} else {
arena.sendMessage(ChatColor.GOLD + "[BowTag] The Survivors have won and earned xx");
ArrayList<String> survivor = arena.getSurvivor();
for (String s: survivor) {
BowTag.economy.depositPlayer(s, 10.0);
Bukkit.getPlayer(s).sendMessage("You earnerd 10");
}
}
//Set ingame
arena.setInGame(false);
for (String s: arena.getPlayers()) {
//Loop through every player in the arena
//Teleport them:
Player player = Bukkit.getPlayer(s); //Create a player by the name
player.teleport(arena.getEndLocation());
player.getInventory().clear(); //Clear the players inventory
player.setHealth(player.getMaxHealth()); //Heal the player
player.setFireTicks(0); //Heal the player even more ^ ^ ^
//Remove them all from the list
arena.getPlayers().remove(player.getName());
if (arena.getBowMen().contains(player.getName())) {
arena.getBowMen().remove(player.getName());
} else if (arena.getSurvivor().contains(player.getName())) {
arena.getSurvivor().remove(player.getName());
}
}
}
} | 7 |
private static ParkerPaulTaxable getRandomTaxable(int selection, int index) {
index += 1;
if (selection < 20) {
return new ParkerPaulBoat("ParkerPaulBoat " + index, getNumberBetween(10, 50), getNumberBetween(1, 4));
} else if (selection < 60) {
return new ParkerPaulTerrain(getFraction(0, 1000, 3), getNumberBetween(0, 200), "ParkerPaulTerrain " + index, getArea(), getPrice());
} else {
return new ParkerPaulBuilding(getNumberBetween(100, 10000), getNumberBetween(1, 4), "ParkerPaulBuilding " + index, getArea(), getPrice());
}
} | 2 |
public Customer SingleCustomerData(int CustID)
throws UnauthorizedUserException, BadConnectionException, DoubleEntryException
{
/* Variable Section Start */
/* Database and Query Preperation */
PreparedStatement statment = null;
ResultSet results = null;
String statString = "SELECT * FROM `customer` WHERE 'CustomerID' = ?";
/* Return Parameter */
ArrayList<Customer> BPArrayList = new ArrayList<Customer>();
Customer temp = new Customer();
/* Variable Section Stop */
/* TRY BLOCK START */
try
{
/* Preparing Statment Section Start */
statment = con.prepareStatement(statString);
statment.setInt(1, CustID);
/* Preparing Statment Section Stop */
/* Query Section Start */
results = statment.executeQuery();
while (results.next())
{
//rs.getBigDecimal("AMOUNT")
temp.setAddress(results.getString("Address"));
temp.setCity(results.getString("City"));
temp.setCustomerID(results.getInt("CustomerID"));
temp.setEmail(results.getString("Email"));
temp.setFirstName(results.getString("Fname"));
temp.setLastName(results.getString("Surname"));
temp.setMemberID(results.getString("MemberID"));
//temp.setPassword(statString);
temp.setPhone(results.getString("Phone"));
temp.setReservationCount(results.getInt("ReservationCount"));
temp.setState(results.getString("State"));
//temp.setUserID(results.getString("Address"));
temp.setZip(results.getInt("Zip"));
BPArrayList.add(temp);
}
/* ArrayList Prepare Section Stop */
}
catch(SQLException sqlE)
{
if(sqlE.getErrorCode() == 1142)
throw(new UnauthorizedUserException("AccessDenied"));
else if(sqlE.getErrorCode() == 1062)
throw(new DoubleEntryException("DoubleEntry"));
else
throw(new BadConnectionException("BadConnection"));
}
finally
{
try
{
if (results != null) results.close();
}
catch (Exception e) {};
try
{
if (statment != null) statment.close();
}
catch (Exception e) {};
}
/* TRY BLOCK STOP*/
/* Return to Buisness Section Start */
return temp;
/* Return to Buisness Section Start */
} | 8 |
public HashMap<String, Double> get_cosine_score_map(
ArrayList<String> url_list) throws SQLException {
HashMap<String, Result> temp_resultmap = null;
String query_word, url;
double score = 0, query_mag = 1;
double tfidf_doc, tfidf_query, doc_mag;
double temp_score;
String first_result=null;
for (int i = 0; i < query_words.length; i++)
{
boolean once=true;
query_word = query_words[i];
for (int j = 0; j < url_list.size(); j++)
{
url = url_list.get(j);
//artificially increasing scores
if(url.contains("~"+query_word)){
score+=200;
if(once){
first_result=url.split("~")[0]+"~"+query_word+"/";
System.out.println("first result "+url.split("~")[0]+"~"+query_word);
score_map.put(first_result, (double) 1000);
once=false;
}
}
temp_resultmap = resultsetmap.get(query_word);
Iterator<String> It = temp_resultmap.keySet().iterator();
while (It.hasNext())
{
String map_url = It.next().toString();
Result res = temp_resultmap.get(map_url);
if (map_url.compareTo(url) == 0)
{
tfidf_doc = res.tfidf;
tfidf_query = query_map.get(query_word);
score += tfidf_doc * tfidf_query;
doc_mag = Math.sqrt((double)res.TD);
score /= (doc_mag * query_mag);
//add 1 to the query in title
String title= Server.title_map.get(url);
if(title!=null) {
title=title.toLowerCase().replaceAll("[^a-zA-Z0-9'-]", " ").replace(" +", " ");
if(title.contains(Query)){
score+=1;
}
}
if (score_map.containsKey(url))
{
temp_score = score_map.get(url);
temp_score += score;
score_map.put(url, new Double(temp_score));
} else
{
score_map.put(url, new Double(score));
}
}
}
}
}
System.out.println("scoremap"+ score_map.toString());
return score_map;
} | 9 |
private void floodFill(char[][] mapa, int[][] numMap, int i, int j, int m,
int n, int num) {
numMap[i][j] = num;
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (k >= 0 && k < m && l >= 0 && l < n && mapa[k][l] == '@'
&& numMap[k][l] == 0) {
this.floodFill(mapa, numMap, k, l, m, n, num);
}
}
}
} | 8 |
private static void compareStacks() {
System.out.println(stacks[0].peek() + " vs " + stacks[1].peek());
if (((Card) stacks[0].peek()).compareTo((Card)stacks[1].peek()) == 0) {
war();
} else if (((Card)stacks[0].peek()).compareTo((Card)stacks[1].peek()) > 0) {
for (int i = 0; i < stacks.length; i++) {
while (stacks[i].stackSize() > 0) {
hands[0].put(stacks[i].get());
}
}
} else if (((Card)stacks[0].peek()).compareTo((Card)stacks[1].peek()) < 0) {
for (int i = stacks.length-1; i >= 0; i--) { //Trust me, I'm not crazy.
while (stacks[i].stackSize() > 0) {
hands[1].put(stacks[i].get());
}
}
}
} | 7 |
final public T atIndex(int i) {
if (i < 0 || i >= size) return null ;
int d = 0 ;
for (ListEntry <T> l = this ; (l = l.next) != this ; d++)
if (d == i) return l.refers ;
return null ;
} | 4 |
public final synchronized void writeValue(DataOutputStream out) throws IOException {
try {
if(_attribute.isArray()) {
out.writeInt(_count);
}
}
catch(ConfigurationException ex) {
throw new IOException(ex.getMessage());
}
if(_attributes == null) {
try {
if(_attribute.isArray() && _count == 0) return;
}
catch(ConfigurationException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
throw new IOException("Wert = null: Attributname: " + _attribute.getName() + " count: " + _count);
}
for(int i = 0; i < _attributes.length; ++i) {
if(_attributes[i] != null) {
_attributes[i].writeValue(out);
}
}
} | 8 |
public boolean execute(CommandSender sender, String[] args) {
String groupName = args[0];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String senderName = sender.getName();
if(!group.isFounder(senderName) && !group.isModerator(senderName) && !group.isMember(senderName)){
sendMessage(sender, ChatColor.RED, "Invalid permission to access this group");
return true;
}
sender.sendMessage(new StringBuilder().append("§cGroup Name:§e ").append(groupName).toString());
sender.sendMessage(new StringBuilder().append("§cOwner:§e ").append(group.getFounder()).toString());
sender.sendMessage(new StringBuilder().append("§cModerators:§e ").append(groupManager.getModeratorsOfGroup(groupName).size()).toString());
sender.sendMessage(new StringBuilder().append("§cMembers:§e ").append(groupManager.getMembersOfGroup(groupName).size()).toString());
if(group.isFounder(senderName) || group.isModerator(senderName)){
String password = group.getPassword();
sender.sendMessage(new StringBuilder().append("§cPassword:§e ").append(password).toString());
String joinable = "";
if(password != null && !password.equalsIgnoreCase("null")){
joinable = "Yes";
} else {
joinable = "No";
}
sender.sendMessage(new StringBuilder().append("§cJoinable:§e ").append(joinable).toString());
}
return true;
} | 8 |
protected void computeAddressByteArray(OSCJavaToByteArrayConverter stream) {
stream.write(address);
} | 0 |
@FXML
private void doPowerMethod(ActionEvent event) {
Scanner s = new Scanner(pmInput.getText());
int row = 0;
int col = 0;
ArrayList<Double> vals = new ArrayList();
try {
while (s.hasNextLine()) {
String line = s.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
vals.add(lineScanner.nextDouble());
if (row == 0) {
col++;
}
}
row++;
}
Matrix A = new Matrix(row, col);
double[] dvals = new double[vals.size()];
for (int i = 0; i < dvals.length; i++) {
dvals[i] = vals.get(i);
}
A.put(dvals);
s = new Scanner(pmVectorInput.getText());
ArrayList<Double> initVector = new ArrayList<>();
while (s.hasNextLine()) {
String line = s.nextLine();
Scanner lineScanner = new Scanner(line);
if (lineScanner.hasNextDouble()) {
initVector.add(lineScanner.nextDouble());
}
}
dvals = new double[initVector.size()];
for (int i = 0; i < dvals.length; i++) {
dvals[i] = initVector.get(i);
}
Vector x = new Vector(dvals);
PowerMethod pm = new PowerMethod(A, x, MAX_NUMBER_OF_ITERATIONS, TOLERANCE);
pmValue.setText(pm.getNorm() + "");
pmVector.setText(pm.getV() + "");
pmIteration.setText(pm.getIterationsNeeded() + "");
} catch (Exception e) {
pmValue.setText("INVALID INPUT");
}
} | 8 |
public void invert() {
invertedBevoreMoves = 0;
List<SchlangenGlied> glieder = new ArrayList<SchlangenGlied>();
addAllGlieder(glieder);
while (glieder.size() > 1) {
SchlangenGlied firstGlied = glieder.get(0);
SchlangenGlied lastGlied = glieder.get(glieder.size() - 1);
Point tmpLocation = firstGlied.getLocation();
firstGlied.setLocation(lastGlied.getLocation());
lastGlied.setLocation(tmpLocation);
glieder.remove(firstGlied);
glieder.remove(lastGlied);
}
} | 1 |
private List<List<String>> importData(){
List<List<String>> artistData = new ArrayList<List<String>>();
// Find all .artistcleaned.
StringBuilder sb = new StringBuilder();
List<String> dataFiles = new ArrayList<String>();
File[] files = new File("lyricsdata").listFiles();
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName();
String artistID = fileName.substring(0,fileName.lastIndexOf("."));
String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if(fileEnd.equals("lyriccleaned")) {
sb.append(artistID + "\n");
dataFiles.add(fileName);
}
}
}
try(PrintWriter pw = new PrintWriter("lyricsdata/document_order.txt")) {
pw.print(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Read all files
for(String fileName : dataFiles) {
ArrayList<String> artistBio = new ArrayList<String>();
artistData.add(artistBio);
try(BufferedReader br = new BufferedReader(new FileReader("lyricsdata/" + fileName))) {
String line = br.readLine();
while (line != null) {
artistBio.add(line);
line = br.readLine();
}
} catch(IOException e) {
e.printStackTrace();
}
}
return artistData;
} | 7 |
public static String formatSql(String sqlNeedFormat, String[] tableNames) {
StringBuilder key = new StringBuilder();
for (String tableName : tableNames) {
key.append(tableName);
}
key.append(sqlNeedFormat);
String keyStr = key.toString();
String sql = formattedSql.get(keyStr);
if (sql == null) {
MessageFormat format = new MessageFormat(sqlNeedFormat);
sql = format.format(tableNames);
formattedSql.put(keyStr, sql);
}
return sql;
} | 2 |
public static Object findAndClone(String name) {
for (int i = 0; i < total; i++) {
if (prototypes[i].getName().equals(name)) {
return prototypes[i].clone();
}
}
System.out.println(name + " not found");
return null;
} | 2 |
public void setPF(PixelFormat pf) {
pf_ = pf;
if (pf.bpp != 8 && pf.bpp != 16 && pf.bpp != 32) {
throw new ErrorException("setPF(): not 8, 16, or 32 bpp?");
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Regle other = (Regle) obj;
if (action == null) {
if (other.action != null)
return false;
} else if (!action.equals(other.action))
return false;
if (!conditions.equals(other.conditions))
return false;
return true;
} | 7 |
public Result addArg(final Arg<?> a) {
final F<Arg<?>, F<List<Arg<?>>, List<Arg<?>>>> cons = List.cons();
return new Result(args.map(cons.f(a)), r, t);
} | 4 |
public ArrayList<PhysicObject> getAllPhysicObjects()
{
ArrayList<PhysicObject> result = new ArrayList<PhysicObject>();
for ( GameObject child : children )
result.addAll( child.getAllPhysicObjects() );
if ( this instanceof PhysicObject )
result.add( (PhysicObject) this );
return result;
} | 2 |
private static void writeForLevel(String level) throws Exception
{
System.out.println(level);
BufferedWriter writer =new BufferedWriter(new FileWriter(new File(ConfigReader.getVanderbiltDir() + File.separator +
"spreadsheets" + File.separator +
"mergedKrakenRDP_" + level + ".txt")));
writer.write("sample\tisStoolOrSwab\ttaxa\tkrakenLevel\trdpLevel\tkraken16SLevel\tmaxKrakenFraction\n");
OtuWrapper rdpWrapper = new OtuWrapper(ConfigReader.getVanderbiltDir() + File.separator + "spreadsheets" +
File.separator + "pivoted_"+ level + "asColumns.txt");
OtuWrapper krakenWrapper = new OtuWrapper(ConfigReader.getVanderbiltDir() + File.separator + "spreadsheets" +
File.separator + "kraken_" + level + "_taxaAsColumns.txt");
OtuWrapper kraken16SWrapper = new OtuWrapper(ConfigReader.getVanderbiltDir()
+ File.separator +
"spreadsheets" + File.separator +
"kraken_" + level +"_taxaAsColumnsFor16S.txt");
HashSet<String> samples = new HashSet<String>();
samples.addAll(kraken16SWrapper.getSampleNames());
samples.retainAll(krakenWrapper.getSampleNames());
samples.retainAll(rdpWrapper.getSampleNames());
HashSet<String> taxa = getTaxaToInclude(rdpWrapper, krakenWrapper, kraken16SWrapper, samples);
for(String s : samples)
{
int rdpSampleKey = rdpWrapper.getIndexForSampleName(s);
int krakenSampleKey = krakenWrapper.getIndexForSampleName(s);
int kraken16SSampleKey = kraken16SWrapper.getIndexForSampleName(s);
for(String otu : taxa)
{
writer.write(s + "\t");
if( s.startsWith("ST"))
writer.write("stool\t");
else if ( s.startsWith("SW"))
writer.write("swab\t");
else throw new Exception(s);
writer.write(otu + "\t");
writer.write( getVal(krakenWrapper, krakenSampleKey, otu) + "\t" );
writer.write( getVal(rdpWrapper, rdpSampleKey, otu) + "\t" );
writer.write( getVal(kraken16SWrapper, kraken16SSampleKey, otu) + "\t" );
double krakenFraction = 0;
if( krakenWrapper.getIndexForOtuName(otu) != -1 )
{
krakenFraction = (double)krakenWrapper.getCountsForTaxa(otu) /
krakenWrapper.getTotalCounts();
}
double kraken16Fraction = 0;
if( kraken16SWrapper.getIndexForOtuName(otu) != -1 )
{
kraken16Fraction = (double)kraken16SWrapper.getCountsForTaxa(otu) /
kraken16SWrapper.getTotalCounts();
}
writer.write(Math.max(krakenFraction , kraken16Fraction )+ "\n");
}
}
writer.flush(); writer.close();
} | 6 |
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
Graphics2D g2D = (Graphics2D) g;
Object savedRenderingHint = null;
if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) {
savedRenderingHint = g2D.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AbstractLookAndFeel.getTheme().getTextAntiAliasingHint());
}
v.paint(g, textRect);
if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) {
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedRenderingHint);
}
} else {
// plain text
int mnemIndex = -1;
if (JTattooUtilities.getJavaVersion() >= 1.4) {
mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
}
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
if (isSelected) {
Color backColor = tabPane.getBackgroundAt(tabIndex);
if (backColor instanceof UIResource) {
g.setColor(AbstractLookAndFeel.getTabSelectionForegroundColor());
} else {
g.setColor(tabPane.getForegroundAt(tabIndex));
}
} else {
g.setColor(tabPane.getForegroundAt(tabIndex));
}
JTattooUtilities.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
g.setColor(tabPane.getBackgroundAt(tabIndex).brighter());
JTattooUtilities.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
JTattooUtilities.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
} | 8 |
public void set(final String area, final String name, final String value) {
if(area.contains("]")) throw new IllegalArgumentException("invalud area name: "
+ area);
if(name.contains("=")) throw new IllegalArgumentException("invalid name: " + name);
final Entry entry = new Entry(area.trim(), name.trim());
final String v = value.trim();
if(entries.containsKey(entry)) {
final String old = entries.get(entry);
if (v.equals(old)) return;
}
entries.put(entry, v);
hasChanged = true;
} | 4 |
@Override
public void execute() {
Player receiver = getReceiver();
StringBuilder builder = new StringBuilder();
builder.append(TerminalUtil.createHeadline("TimeBan list")).append("\n");
List<Ban> result = plugin.getController().searchBans(search, reverse);
if (!result.isEmpty()) {
HashMap<String, String> values = new HashMap<String, String>(3);
if (simple == true) {
for (Ban b : result) {
values.put("{user}", b.getPlayer().getName());
values.put("{until}", shortFormat.format(b.getUntil().getTime()));
values.put("{reason}", b.getReason());
String message = MessagesUtil.formatMessage("list_short_result", values);
builder.append(message).append("\n");
}
} else {
for (Ban b : result) {
values.put("{user}", b.getPlayer().getName());
values.put("{until}", b.getUntil().getTime().toString());
values.put("{reason}", b.getReason());
String message = MessagesUtil.formatMessage("list_result", values);
builder.append(message).append("\n");
}
}
} else {
builder.append("No results.");
}
String message = builder.toString();
if (receiver == null) {
TerminalUtil.printToConsole(message);
} else {
TerminalUtil.printToPlayer(receiver, message, page);
}
} | 5 |
public void mouseReleased(MouseEvent e) {
//Game Logic
if (!m_panel.getAnimationThread().isAlive()) {
if (getGame().getPlayer(getGame()
.getPlayerTurn() % TOTAL_PLAYERS)
.getPlayerType()
.equals("Human"))
if ((!getGame().gameWon() && !getGame().boardIsFull())
&& !m_panel.getAnimationThread().isAlive()) {
int x = Math.round(m_mouseX /
ConnectFourPanel.Y_SPACING);
performMove(x);
getGame().incrementTurn();
}
}
} | 5 |
@Override
public Integer read(DataInputStream in, PassthroughConnection ptc, KillableThread thread, boolean serverToClient, DownlinkState linkState) {
while(true) {
try {
value = in.readInt();
if(serverToClient) {
if(value == ptc.clientInfo.getPlayerEntityId()) {
value = Globals.getDefaultPlayerId();
} else if (value == Globals.getDefaultPlayerId()) {
ptc.printLogMessage("Player entity id collision (server to client) - breaking connection");
ptc.printLogMessage("Value: " + value);
ptc.printLogMessage("Default: " + Globals.getDefaultPlayerId());
ptc.printLogMessage("Active: " + ptc.clientInfo.getPlayerEntityId());
return null;
} else {
linkState.entityIds.add(value);
}
} else {
if(value == Globals.getDefaultPlayerId()) {
value = ptc.clientInfo.getPlayerEntityId();
} else if (value == ptc.clientInfo.getPlayerEntityId()) {
ptc.printLogMessage("Player entity id collision (client to server)- breaking connection");
ptc.printLogMessage("Value: " + value);
ptc.printLogMessage("Default: " + Globals.getDefaultPlayerId());
ptc.printLogMessage("Active: " + ptc.clientInfo.getPlayerEntityId());
return null;
}
}
} catch ( SocketTimeoutException toe ) {
if(timedOut(thread)) {
continue;
}
return null;
} catch (IOException e) {
return null;
}
super.timeout = 0;
return value;
}
} | 9 |
protected void checkCollisionWith(final Entity other) {
int shiftX = other.getPosition().getX() - pos.getX();
int shiftY = other.getPosition().getY() - pos.getY();
for (RectangularBounds trb : boundaries) {
for (RectangularBounds orb : other.getBoundaries()) {
if (trb.intersects(orb, shiftX, shiftY)) {
boolean pixelPerfect = usePixelPerfectCollision
|| other.isUsePixelPerfectCollision();
if (currentBitmap == null
|| other.getCurrentBitmap() == null) {
pixelPerfect = false;
}
if (!pixelPerfect || collidesPixelPerfectWith(other)) {
collisionWith(other);
break;
}
}
}
}
} | 8 |
public static void start(String[] args){
int port = 80;
if(args.length == 1){
try {
port = Integer.valueOf(args[0]);
if(port < 0 || port > 65536){
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
System.out.println("Invalid port value");
return;
}
}
else if(args.length > 1){
System.out.println("Invalid parameters number. Parameters format: [port]");
return;
}
HttpServer server = new HttpServer(port);
Thread t = new Thread(server);
t.start();
InputStream in = System.in;
Scanner input = new Scanner(in);
String line;
while((line = input.nextLine()) != null && line.length() != 0){
if(line.equals("stop")){
server.stop();
return;
} else {
System.out.println("Unknown command: "+line);
}
}
} | 8 |
@Override
public void contextInitialized(ServletContextEvent arg0) {
Watch time = new Watch();
time.start();
System.out.println("Server startet - create tree... (this could take a while - depending on input filesize)");
//create tree
String pathOrig = Container.pathOrig;
String pathFolder = Container.pathFolder;
String name = Container.name;
String type = Container.type;
Factory.createTree(0, pathOrig, pathFolder, name, type);
System.out.println("tree created in : "+ time.getElapsedTime() +"ms");
//create cluster hierarchy
System.out.println("create cluster... for mode 9");
try {
Container.setCluster(Cluster.clusterH());;
} catch (IOException e) {
e.printStackTrace();
System.out.println("cluster fail");
}
System.out.println("server fully loaded in : "+ time.getElapsedTime() +"ms");
time.stop();
} | 1 |
@Override public RSTNode update( int x, int y, int sizePower, long time, MessageSet messages, UpdateContext updateContext ) {
int relevantMessageCount = 0;
int size = 1<<sizePower;
for( Message m : messages ) {
boolean relevance =
BitAddressUtil.rangesIntersect(this, m) &&
m.targetShape.rectIntersection( x, y, size, size ) != RectIntersector.INCLUDES_NONE;
relevantMessageCount += relevance ? 1 : 0;
}
if( relevantMessageCount == 0 ) {
if( time < nextAutoUpdateTime ) {
return this;
}
messages = MessageSet.EMPTY;
}
// TODO: if relevantMessageCount < messages.length, could filter, here.
return _update( x, y, sizePower, time, messages, updateContext );
} | 5 |
public static boolean isFlashEdgeCase(byte[] request, int requestsize) {
for (int i = 0; i < requestsize && i < FLASH_POLICY_REQUEST.length; i++) {
if (FLASH_POLICY_REQUEST[i] != request[i]) {
return false;
}
}
return requestsize >= FLASH_POLICY_REQUEST.length;
} | 3 |
public void next(int width, int height) {
x += incX;
y += incY;
float random = (float)Math.random();
if (x + textWidth > width) {
x = width - textWidth;
incX = random * -width / 16 - 1;
}
if (x < 0) {
x = 0;
incX = random * width / 16 + 1;
}
if (y + textHeight > height) {
y = (height - textHeight)- 2;
incY = random * -height / 16 - 1;
}
if (y < 0) {
y = 0;
incY = random * height / 16 + 1;
}
} | 4 |
@Override
public Document getDocumentById(final String id) {
final File file = fileFor(id);
if (isExcluded(file) || !file.exists()) {
return null;
}
final boolean isRoot = isRoot(id);
final boolean isResource = isContentNode(id);
DocumentWriter writer = null;
File parentFile = file.getParentFile();
if (isResource) {
writer = newDocument(id);
final BinaryValue binaryValue = binaryFor(file);
writer.setPrimaryType(NT_RESOURCE);
writer.addProperty(JCR_DATA, binaryValue);
if (addMimeTypeMixin) {
String mimeType = null;
final String encoding = null; // We don't really know this
try {
mimeType = binaryValue.getMimeType();
} catch (final Throwable e) {
getLogger().error(e, JcrI18n.couldNotGetMimeType,
getSourceName(), id, e.getMessage());
}
writer.addProperty(JCR_ENCODING, encoding);
writer.addProperty(JCR_MIME_TYPE, mimeType);
}
writer.addProperty(JCR_LAST_MODIFIED, factories().getDateFactory()
.create(file.lastModified()));
writer.addProperty(JCR_LAST_MODIFIED_BY, null); // ignored
// make these binary not queryable. If we really want to query them,
// we need to switch to external binaries
writer.setNotQueryable();
parentFile = file;
} else if (file.isFile()) {
writer = newDocument(id);
writer.setPrimaryType(NT_FILE);
writer.addProperty(JCR_CREATED, factories().getDateFactory()
.create(file.lastModified()));
writer.addProperty(JCR_CREATED_BY, null); // ignored
final String childId =
isRoot ? JCR_CONTENT_SUFFIX : id + JCR_CONTENT_SUFFIX;
writer.addChild(childId, JCR_CONTENT);
} else {
writer = newFolderWriter(id, file, 0);
}
if (!isRoot) {
// Set the reference to the parent ...
final String parentId = idFor(parentFile);
writer.setParents(parentId);
}
// Add the extra properties (if there are any), overwriting any
// properties with the same names
// (e.g., jcr:primaryType, jcr:mixinTypes, jcr:mimeType, etc.) ...
writer.addProperties(extraPropertiesStore().getProperties(id));
// Add the 'mix:mixinType' mixin; if other mixins are stored in the
// extra properties, this will append ...
if (addMimeTypeMixin) {
writer.addMixinType(MIX_MIME_TYPE);
}
// Return the document ...
return writer.document();
} | 9 |
@Test
public void testProgressLocal() {
NetWork localNet = new NetWork(windows, linux, chrome);
PC[] pcAmount = localNet.getComputers();
// We're cheking start values
assertTrue(pcAmount[1].isInfected());
for (int i = 0; i < pcAmount.length; i++) {
if (i != 1) {
assertFalse(pcAmount[i].isInfected());
}
}
// first iteration
// 2 attacks 1
// 2 attacks 4
localNet.progress();
localNet.progress();
assertTrue(pcAmount[0].isInfected());
assertTrue(pcAmount[3].isInfected());
assertFalse(pcAmount[4].isInfected());
assertFalse(pcAmount[2].isInfected());
// second iteration
// 1 attacks 3
// 4 attack 5
localNet.progress();
for (int i = 0; i < pcAmount.length; i++) {
assertTrue(pcAmount[i].isInfected());
}
} | 3 |
@Override
public List<BankDeposit> readXML(String xmlFilePath) throws XMLReaderDOMException {
try {
XMLValidator validator = new XMLValidator();
validator.validateXML(xmlFilePath, DataPath.XSD_FILE);
deposits = new ArrayList<>();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(getClass().getResourceAsStream(xmlFilePath));
NodeList nList = doc.getElementsByTagName(XMLTag.BANK);
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
BankDeposit deposit = new BankDeposit();
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
deposit.setName(eElement.getElementsByTagName(XMLTag.NAME).item(0).getTextContent());
deposit.setCountry(eElement.getElementsByTagName(XMLTag.COUNTRY).item(0).getTextContent());
deposit.setType(DepositType.valueOf(eElement.getElementsByTagName(XMLTag.TYPE)
.item(0).getTextContent().toUpperCase()));
deposit.setDepositor(eElement.getElementsByTagName(XMLTag.DEPOSITOR).item(0).getTextContent());
deposit.setAccountId(eElement.getElementsByTagName(XMLTag.ACCOUNT_ID).item(0).getTextContent());
deposit.setAmount(Integer.parseInt(eElement.getElementsByTagName(XMLTag.AMOUNT).item(0).getTextContent()));
deposit.setProfitability(Integer.parseInt(eElement.getElementsByTagName(XMLTag.PROFITABILITY)
.item(0).getTextContent()));
deposit.setTimeConstraints(Integer.parseInt(eElement.getElementsByTagName(XMLTag.TIME_CONSTRAINTS)
.item(0).getTextContent()));
}
deposits.add(deposit);
}
} catch (ParserConfigurationException | SAXException | IOException ex) {
throw new XMLReaderDOMException(ex);
}
return deposits;
} | 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.