method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
4e8a30e7-248a-4106-98b4-d692c23e3a6e | 1 | public static String keyToLocatedString(String key) {
String ret = null;
try {
ret = locale.getString(key);
} catch (Exception e) {
ret = key;
}
return ret;
} |
2433a976-4a4f-4edd-b75d-f9f22d77d65a | 7 | public double[] instanceToSchema(Instance inst,
MiningSchema miningSchema) throws Exception {
Instances miningSchemaI = miningSchema.getMiningSchemaAsInstances();
// allocate enough space for both mining schema fields and any derived fields
double[] result = new double[miningSchema.getFieldsAsInstances().numAttributes()];
// Copy over the values
for (int i = 0; i < miningSchemaI.numAttributes(); i++) {
//if (miningSchemaI.attribute(i).isNumeric()) {
result[i] = inst.value(m_fieldsMap[i]);
if (miningSchemaI.attribute(i).isNominal() ||
miningSchemaI.attribute(i).isString()) {
// If not missing, look up the index of this incoming categorical value in
// the mining schema
if (!Utils.isMissingValue(inst.value(m_fieldsMap[i]))) {
int[] valueMap = m_nominalValueMaps[i];
int index = valueMap[(int)inst.value(m_fieldsMap[i])];
String incomingAttValue =
inst.attribute(m_fieldsMap[i]).value((int)inst.value(m_fieldsMap[i]));
/*int index = miningSchemaI.attribute(i).indexOfValue(incomingAttValue); */
if (index >= 0) {
result[i] = index;
} else {
// set this to "unknown" (-1) for nominal valued attributes
result[i] = UNKNOWN_NOMINAL_VALUE;
String warningString = "[MappingInfo] WARNING: Can't match nominal value "
+ incomingAttValue;
if (m_log != null) {
m_log.logMessage(warningString);
} else {
System.err.println(warningString);
}
}
}
}
}
// Now deal with missing values and outliers...
miningSchema.applyMissingAndOutlierTreatments(result);
// printInst(result);
// now fill in any derived values
ArrayList<DerivedFieldMetaInfo> derivedFields = miningSchema.getDerivedFields();
for (int i = 0; i < derivedFields.size(); i++) {
DerivedFieldMetaInfo temp = derivedFields.get(i);
// System.err.println("Applying : " + temp);
double r = temp.getDerivedValue(result);
result[i + miningSchemaI.numAttributes()] = r;
}
/*System.err.print("==> ");
for (int i = 0; i < result.length; i++) {
System.err.print(" " + result[i]);
}
System.err.println();*/
return result;
} |
57ef92b0-c19f-4750-8f7d-0afea6b3a71a | 4 | public static Level genWorldRandom(int cols, int rows, TexturePack tp) {
/** Brick density. */
final double pBrick = 0.8;
/** Probability of a light in the bg. */
final double pLight = 0.02;
Level level = new Level(cols, rows, tp);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (GEN.nextDouble() * row < pBrick) {
//solid bricks
level.setCell(col, row, Texture.brick);
} else {
//background bricks
if (GEN.nextDouble() < pLight) {
level.setCell(col, row, Texture.bgLightDead);
} else {
level.setCell(col, row, Texture.bg);
}
}
}
}
level.setStart(new Point(0, rows * Level.CELL_SIZE));
return level;
} |
4179398f-9271-4ffa-980e-56ee1dc6182a | 3 | public static void count_occurences(Integer[] v, Integer k) {
boolean started = false;
int counter = 0;
for (int value : v) {
if(value == k) {
counter++;
started = true;
} else if(started) {
System.out.println(counter);
return;
}
}
System.out.println(counter);
} |
e9ae6878-cf37-4852-a7eb-5a9cc4ebf605 | 8 | public void setConnections() {
System.out.println("Cog - Connecting cog nets");
// ======================== roomnet inhibits 'seenroom' in factnet
/*
for (int i = 0; i < RoomNet.getSize(); i++) {
if (RoomNet.neurons[i].isInhibitory()) {
int toNeuron = (i%40)+760;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-3.0);
toNeuron = ((i+1)%40)+760;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-3.0);
toNeuron = ((i+2)%40)+760;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-3.0);
toNeuron = (i%40)+800;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-2.0);
toNeuron = ((i+1)%40)+800;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-2.0);
toNeuron = ((i+2)%40)+800;
RoomNet.neurons[i].addConnection(FactNet.neurons[toNeuron],-3.0);
}
}
*/
double weight = .001;
/*
// ======================== cur room -> last room
for(int room=0; room<4; room++) {
int from = room*200;
int to = from+200;
for(int i=from; i < to; i++) {
if(!RoomNet.neurons[i].isInhibitory()) {
for(int syn=0; syn<3; syn++) {
RoomNet.neurons[i].addConnection(RoomNet2.neurons[getRandRange(from, to)], 1.5);
}
}
}
}
*/
// ======================== rooms->seqnet
for(int i=0; i<RoomNet.getSize(); i++) {
if(!RoomNet.neurons[i].isInhibitory()) {
for(int syn=0; syn<10; syn++) {
RoomNet.neurons[i].addConnection(CogSeqNet.neurons[getRandRange(0, CogSeqNet.getSize())], weight);
}
}
}
for(int i=0; i<CogSeqNet.getSize(); i++) {
if(!CogSeqNet.neurons[i].isInhibitory()) {
for(int syn=0; syn<25; syn++) {
CogSeqNet.neurons[i].addConnection(RoomNet.neurons[getRandRange(0, RoomNet.getSize())], weight);
CogSeqNet.neurons[i].addConnection(RoomNet2.neurons[getRandRange(0, RoomNet2.getSize())], weight);
}
}
}
// ======================== rooms2->sequence->room2
for(int i=0; i<RoomNet2.getSize(); i++) {
if(!RoomNet2.neurons[i].isInhibitory()) {
RoomNet2.neurons[i].addConnection(CogSeqNet.neurons[getRandRange(0, CogSeqNet.getSize())], weight);
}
}
} |
7e52be84-98ec-4c13-9f4d-764ee2a17201 | 5 | public void SetPrices(int posState, int numSymbols, int[] prices, int st)
{
final int a0 = SevenZip.Compression.RangeCoder.Encoder
.GetPrice0(_choice[0]);
final int a1 = SevenZip.Compression.RangeCoder.Encoder
.GetPrice1(_choice[0]);
final int b0 = a1
+ SevenZip.Compression.RangeCoder.Encoder
.GetPrice0(_choice[1]);
final int b1 = a1
+ SevenZip.Compression.RangeCoder.Encoder
.GetPrice1(_choice[1]);
int i = 0;
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
{
return;
}
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
{
return;
}
prices[st + i] = b0
+ _midCoder[posState].GetPrice(i
- Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
{
prices[st + i] = b1
+ _highCoder.GetPrice(i - Base.kNumLowLenSymbols
- Base.kNumMidLenSymbols);
}
} |
05a608af-64ed-4626-8bc6-19411e68b218 | 3 | public void run() {
try {
String response;
udpClient = new DatagramSocket();
udpServer = new DatagramSocket(PORT);
udpPackage = new DatagramPacket(new byte[123], 123);
/* Warte auf eingfehenden Nachrichten */
while (! isInterrupted()) {
udpServer.receive(udpPackage);
response = new String(udpPackage.getData(), 0, udpPackage.getLength(), "UTF-8");
this.chat.addOutput(response.trim());
}
udpClient.close();
} catch (IOException e) {
if (! isInterrupted()){
e.printStackTrace();
}
}
} |
4dcb6965-5535-42b0-836e-7ee1d6445967 | 5 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GcUsage gcUsage = (GcUsage) o;
if (gcCount != gcUsage.gcCount) return false;
if (gcTime != gcUsage.gcTime) return false;
return true;
} |
f10fcf22-1d9c-4515-bd7c-58260dc0efe7 | 6 | public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, board.length * 30, getHeight());
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == PLAYER) g.drawImage(imgPlayer, i * 30, j * 30, null);
else if (board[i][j] == WALL) g.drawImage(imgWall, i * 30, j * 30, null);
else if (board[i][j] == COIN) g.drawImage(imgCoin, i * 30, j * 30, null);
}
}
g.setColor(Color.WHITE);
g.drawString("Moves: " + moves, 20, 650);
g.drawString("Points: " + points, 100, 650);
g.setColor(Color.WHITE);
g.drawString("Press I to import your own level! Make sure the image file is 20x20", 20, 670);
g.drawString("Each pixel represents something: Red = Wall, Green = Coin, White = Player", 20, 685);
g.setColor(Color.RED);
if (moves == 0)
g.drawString("DONE! press R to play again!", 200, 650);
} |
8fa06c9b-bd54-4e47-b80e-dec73ba6220a | 9 | public void saveAsApplet() {
Frame frame = JOptionPane.getFrameForComponent(this);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(FileFilterFactory.getFilter("html"));
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
String s = Modeler.getInternationalText("SavePageAsHTML");
fileChooser.setDialogTitle(s != null ? s : "Save as an applet");
fileChooser.setApproveButtonMnemonic('S');
String latestPath = fileChooser.getLastVisitedPath();
if (latestPath != null)
fileChooser.setCurrentDirectory(new File(latestPath));
fileChooser.setAccessory(null);
String filename = FileUtilities.getFileName(pageAddress);
fileChooser.setSelectedFile(new File(FileUtilities.changeExtension(filename, "html")));
if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
filename = FileUtilities.fileNameAutoExtend(FileFilterFactory.getFilter("html"), fileChooser.getSelectedFile());
File file = new File(filename);
if (file.exists()) {
s = Modeler.getInternationalText("FileExists");
String s1 = Modeler.getInternationalText("File");
String s2 = Modeler.getInternationalText("Overwrite");
String s3 = Modeler.getInternationalText("Exists");
if (JOptionPane.showConfirmDialog(frame, (s1 != null ? s1 : "File") + " " + file.getName() + " " + (s3 != null ? s3 : "exists") + ", " + (s2 != null ? s2 : "overwrite") + "?", s != null ? s : "File exists", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
fileChooser.resetChoosableFileFilters();
return;
}
}
new AppletConverter(this).write(file);
fileChooser.rememberPath(fileChooser.getCurrentDirectory().toString());
}
fileChooser.resetChoosableFileFilters();
} |
60436edc-cffd-46fa-8c64-3f6d7d465f59 | 8 | public void takeShot(int x,int y)
{
this.setShots();
if (Battleship.getPlayers(Battleship.getEnemy()).getHitOrMiss(x,y))
{
this.setHits();
if (!Battleship.getPlayers(Battleship.getEnemy()).isSunk(x,y))
{
Battleship.getPlayers(Battleship.getEnemy()).setBboard(x,y,Color.orange);
if ((this.getUser().equals("Computer"))||(this.getUser().equals("CPU1"))||(this.getUser().equals("CPU2")))
{
this.setMHS(x,y,1);
this.setChit(true);
}
}
}
else
{
Battleship.getPlayers(Battleship.getEnemy()).setBboard(x,y,Color.blue);
if ((this.getUser().equals("Computer"))||(this.getUser().equals("CPU1"))||(this.getUser().equals("CPU2")))
{
this.setMHS(x,y,0);
this.setChit(false);
}
}
} |
81a5ce24-e5d7-4d38-bc3b-512fce5e4b3f | 1 | public int findPlayersFruitId(Player p){
int fruitId = -1;
if(FruitManager.getInstance().getFruitByPlayer(p) == null){
return fruitId;
}
fruitId = FruitManager.getInstance().getFruitByPlayer(p).getId();
return fruitId;
} |
519b2f74-02f5-42ac-9c5d-a1daa92b562e | 6 | 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(eje3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(eje3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(eje3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(eje3.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 eje3().setVisible(true);
}
});
} |
c60239be-a559-4aa1-8b4e-58e91a64d729 | 6 | public Match getNext(){
try
{
// read size of match
int r = 0;
byte[] b = new byte[4];
r = in.read(b);
if(r == -1)
{
return null;
}
ByteBuffer bb = ByteBuffer.wrap(b);
int size = bb.getInt();
// create byte array to hold the match data
b = new byte[size];
Match m;
// read data into byte array
r = in.read(b);
if(r == -1)
{
return null;
}
// construct match from byte array
m = new Match(b);
// check whether the match is valid (ignoring duration)
// and if the match is not valid, read the next match until
// a valid match is found.
while(!m.matchValid(false))
{
b = new byte[4];
r = in.read(b);
if(r == -1)
{
return null;
}
bb = ByteBuffer.wrap(b);
size = bb.getInt();
b = new byte[size];
r = in.read(b);
if(r == -1)
{
return null;
}
m = new Match(b);
}
return m;
}
catch (IOException ex)
{
Logger.getLogger(MatchData.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} |
e18bd636-b7d6-4155-8679-068d5b591355 | 1 | public static int getMessageHeight(String message, Font font, Graphics2D g){
g.setFont(font);
if(message.length() == 0)
return 0;
TextLayout tl = new TextLayout(message, font, g.getFontRenderContext());
return(int)tl.getBounds().getHeight();
} |
b8c0e93c-8294-4755-944b-ca57dfa3bbc0 | 6 | static public String numberToString(Number n)
throws JSONException {
if (n == null) {
throw new JSONException("Null pointer");
}
testValidity(n);
// Shave off trailing zeros and decimal point, if possible.
String s = n.toString();
if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
} |
67c4d6af-23b2-4a65-a7c6-dce215861f40 | 4 | public void dispose() {
for (Object cachedFile : cachedFiles) {
String fileName = (String) cachedFile;
try {
boolean success = (new File(fileName)).delete();
if (!success && logger.isLoggable(Level.FINE)) {
logger.fine("Error deleting cached file " + fileName);
}
}
catch (SecurityException e) {
logger.log(Level.FINE,
"Security error removing cached file " + fileName, e);
}
}
} |
b81f08db-8739-4d10-867c-cd075b9114c7 | 6 | public Particle(int _x, int _y, int _dx, int _dy, int _life, int _imageType, int _r, int _g, int _b){
this.x = _x;
this.y = _y;
this.dx = _dx;
this.dy = _dy;
this.life = _life;
c = new Color(_r, _g, _b);
if(_imageType == 0)
{
try{
image = new Image("Content/ImageFiles/diamond.png");
}catch(SlickException e){}
}
else if(_imageType == 1)
{
try{
image = new Image("Content/ImageFiles/star.png");
}catch(SlickException e){}
}
else if(_imageType == 2)
{
try{
image = new Image("Content/ImageFiles/circle.png");
}catch(SlickException e){}
}
} |
ab500327-c48e-4263-bf66-f27036628afb | 6 | public static int[] runFourCard (int [] c, long dead)
{
int res[] = new int[Valuation.NUM_RANKINGS];
for (int i=0; i<52; i++)
if (((one<<i)&dead) == 0)
for (int j=i+1; j<52; j++)
if (((one<<j)&dead) == 0)
for (int k=j+1; k<52; k++)
if (((one<<k)&dead) == 0)
{
c[4] = i;
c[5] = j;
c[6] = k;
Hand h = new Hand(c);
res[Valuation.value(h.evaluate())]++;
}
return res;
} |
2342c4ac-13b4-4c97-b2a6-1930f78073e6 | 9 | @Override
public void run() throws NullPointerException{
//public void execution(){
while(!dis.readyQueue.Is_Queue_Empty() || !dis.blockQueue.Is_Queue_Empty()){ //Is both Ready and Block queues empty
//instructionCount =10; //@Pravi: this won't be needed, as we are assigning a value
//to this variable after 3 lines from this point :)
if(!dis.readyQueue.Is_Queue_Empty()){ //Is readyQueue queue empty
currentProcess = dis.dequeueReady();
instructionCount =currentProcess.getNumOfInstructions();
}
else{ //If Ready queue is empty then dequeue from Block queue
currentProcess = dis.dequeueBlock();
dis.readyQueue.Enqueue(currentProcess);
currentProcess=dis.dequeueReady();
instructionCount =currentProcess.getNumOfInstructions();
}
// while(instructionCount!=0){
while(currentProcess.getNumOfInstructions()!=0){
//while(true){
// long startTime = System.currentTimeMillis();
// long endTime = startTime + OMEGA_OS.timeQuantum*1000; // eg: 60 seconds * 1000 ms/sec
// //while (System.currentTimeMillis() < endTime/OMEGA_OS.speedOfTheExecution){
// while (System.currentTimeMillis() < endTime){
num1 = 1 + randomVal.nextInt(5); //Random number generate to blockQueue the currentProcess
if(num1==currentProcess.getPID()){ //Running currentProcess blocked
dis.blockQueue.Enqueue(currentProcess);
System.out.println("Process "+currentProcess.getPID()+" is blocked"+" The time - "+currentProcess.getNumOfInstructions());
break;
}
else{ //If Runiing Process not blocked
//instructionCount--;
//time = currentProcess.getNumOfInstructions() - 1;
//currentProcess.setNumOfInstructions(time);
// long startTime = System.currentTimeMillis();
// long endTime = start + OMEGA_OS.timeQuantum*1000; // eg: 60 seconds * 1000 ms/sec
// while (System.currentTimeMillis() < end/OMEGA_OS.speedOfTheExecution){
currentProcess.setNumOfInstructions(currentProcess.getNumOfInstructions() - 1); //@Pravi: removed "time" variable
System.out.println("Process "+currentProcess.getPID()+" is running"+" The time - "+currentProcess.getNumOfInstructions());
if(currentProcess.getNumOfInstructions()==0){
System.out.println("The Process "+currentProcess.getPID()+" Execution complete!!!!!");
break;
}
}
}
if(instructionCount==0){ //Process ends execution
dis.readyQueue.Enqueue(currentProcess);
}
if(dis.blockQueue.Is_Queue_Empty()){ //Block queue empty
continue;
}
else{
num1 = 1 + randomVal.nextInt(5); //Random number generate to dequeue from blockQueue queue
if(num1==dis.blockQueue.getElement().getPID()){
currentProcess = dis.dequeueBlock();
dis.readyQueue.Enqueue(currentProcess);
}
else
continue;
}
}
} |
8f1f1186-89af-4d16-a9f4-806480c4a4ff | 7 | private static void write(SootClass sClass, int output_format) {
OutputStream streamOut = null;
try {
String filename = SourceLocator.v().getFileNameFor(sClass, output_format);
if (output_format == Options.output_format_class)
streamOut = new JasminOutputStream(new FileOutputStream(filename));
else
streamOut = new FileOutputStream(filename);
PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(streamOut));
if (output_format == Options.output_format_class) {
JasminClass jasClass = new JasminClass(sClass);
jasClass.print(writerOut);
} else if (output_format == Options.output_format_jimple)
Printer.v().printTo(sClass, writerOut);
else if (output_format == Options.output_format_dava)
DavaPrinter.v().printTo(sClass, writerOut);
writerOut.flush();
writerOut.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (streamOut != null)
try {
streamOut.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
88f5cb38-10c9-42d1-af1c-145dd86bf259 | 0 | public ConnectionInfo getConnectionInfo() {
return connectionInfo;
} |
8eda8b91-47c5-4fad-a332-34f483c79394 | 5 | private void notifyAtListner(final Subscriber<?, ?> listener, final Envelop data) {
executor.execute(new Runnable() {
@Override
public void run() {
final Filter f = listener.getFilter();
if (f.getManagedType() == null || data.getContentType().isAssignableFrom(f.getManagedType())) {
Serializable content = data.getContent();
if (f.passes(content)) {
listener.handle(data);
}
}
}
});
} |
4bb3d533-96cc-4a68-8994-f386d148c271 | 3 | public void sub(int[] S, int start){
for(int i = start; i < len; ++i){
if(i > start && S[i] == S[i-1]) continue;
seq.add(S[i]);
res.add(new ArrayList<Integer>(seq));
sub(S, i+1);
seq.remove(seq.size() - 1);
}
} |
407aa98e-d520-4fbc-b71a-5cf9a0418aca | 5 | @Test
public void testSetSocketTimeout() {
LOGGER.log(Level.INFO, "----- STARTING TEST testSetSocketTimeout -----");
String client_hash = "";
String client_hash2 = "";
String client_hash3 = "";
try {
client_hash = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED);
try {
server2.setSocketTimeout(100);
} catch (InvalidArgumentException | SocketException e) {
exception = true;
}
try {
client_hash2 = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadState(server2, client_hash2, SocketThread.CONFIRMED);
try {
server2.setUseSocketTimeout(true);
} catch (SocketException e) {
exception = true;
}
try {
client_hash3 = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadState(server2, client_hash3, SocketThread.CONFIRMED);
Assert.assertFalse(exception, "Exception found");
Assert.assertEquals(server2.getSocketTimeout(), 100, "Socket timeout value not changed on server");
Assert.assertEquals(server2.getSocketList().get(client_hash).getSocketTimeout(), 100, "Socket timeout value not changed on first SocketThread");
Assert.assertEquals(server2.getSocketList().get(client_hash2).getSocketTimeout(), 100, "Socket timeout value not changed on second SocketThread");
Assert.assertEquals(server2.getSocketList().get(client_hash3).getSocketTimeout(), 100, "Socket timeout value not changed on third SocketThread");
LOGGER.log(Level.INFO, "----- TEST testSetSocketTimeout COMPLETED -----");
} |
4286762e-18f1-49f0-8681-7d7f96a3737a | 8 | static int knapsackV(int[] p,int[] v,int maxV){
if (maxV <= 0 || p == null || v == null || p.length != v.length){
return 0;
}
int size = p.length;
if (size == 1){
if (v[0] <= maxV){
return p[0];
} else {
return 0;
}
}
//不能把原数组传进去,以免在执行第一个递归时改变了数组的值,
//然后再去执行第二个递归时参数非预期的改变
int[] tempArryP = new int[size - 1];
int[] tempArryV = new int[size - 1];
System.arraycopy(p, 0, tempArryP, 0, size - 1);
System.arraycopy(v, 0, tempArryV, 0, size - 1);
int tempP = p[size - 1];
int tempV = v[size - 1];
if (tempV > maxV)return knapsackV(tempArryP,tempArryV,maxV);
int preMaxP = knapsackV(tempArryP,tempArryV,maxV);
int currMaxP = knapsackV(tempArryP,tempArryV,maxV - tempV) + tempP;
if (preMaxP >= currMaxP) {
return preMaxP;
} else {
return currMaxP;
}
} |
fde81ace-6047-47d2-9b67-a441bc76adfa | 9 | public boolean testScore(String startScore) { //sees if string is valid score
String tempNumStr = "";
Integer firstInt = 0;
Integer secondInt = 0;
Double tempScore = 0.0;
if(startScore == "0") {
return true;
}else {
char[] aCharArray = startScore.toCharArray(); //turns input into array so it can be iterated over
for(char scoreChar : aCharArray) { // parses through string to get int before the "" and the int after
if(Character.toString(scoreChar).equals("/")) { //separates between first and second int
try {
firstInt = Integer.parseInt(tempNumStr);
}catch(NumberFormatException e) {
return false;
}
if(firstInt == null) { //makes sure that score input is valid
return false;
}
tempNumStr = ""; //resets tempNumStr so it can get value of secondInt
}else {
tempNumStr += Character.toString(scoreChar); //concats integer in case numbers are 2 digit
}
}
try {
secondInt = Integer.parseInt(tempNumStr);
}catch(NumberFormatException e) {
return false;
}
if(secondInt == null) { //makes sure that score input is valid
return false;
}
tempScore = (double)firstInt / (double)secondInt;
if(tempScore < 0 || tempScore > 1) { //checks to see if score is reasonable, ie not 7000% or something
return false;
}
return true;
}
} |
131b180e-8bdb-4efb-a7e0-8c5188741fcd | 8 | public static void writeFileUTF8(File file, StringBuffer str){
if(!file.exists()){
try {
if (file.createNewFile()){
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),defaultCharSet));
bw.write(str.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bw!=null) try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}else {
file.delete();
}
} |
cda534e1-2a33-43e7-920d-a65d57e06961 | 8 | public static void main(String[] args) {
if(args.length < 3) {
System.err.println("Not enough arguments!");
System.err.println(getHelp());
System.exit(0);
}
try {
float a = (float) Float.valueOf(args[1]);
float b = (float) Float.valueOf(args[2]);
if(a < 0 || b < 0) {
System.err.println("Numbers have to be positive");
System.err.println(getHelp());
System.exit(0);
}
ZuseBinaryFloatingPoint24Bit bfp24bit1 = new ZuseBinaryFloatingPoint24Bit(a);
ZuseBinaryFloatingPoint24Bit bfp24bit2 = new ZuseBinaryFloatingPoint24Bit(b);
switch (args[0]) {
case "add":
System.out.println("Addition: "+a+"+"+b);
ZuseBinaryFloatingPoint24Bit addres = new Operation().add(bfp24bit1, bfp24bit2);
System.out.println("adder: " + addres.floatValue(true));
break;
case "sub":
System.out.println("\nSubstraction: "+a+"-"+b);
ZuseBinaryFloatingPoint24Bit subres = new Operation().sub(bfp24bit1, bfp24bit2);
System.out.println("substracter: " + subres.floatValue(true));
break;
case "mul":
System.out.println("\nMuliplication: "+a+"*"+b);
ZuseBinaryFloatingPoint24Bit mulres = new Operation().mul(bfp24bit1, bfp24bit2);
System.out.println("multiplier: " + mulres.floatValue(true));
break;
case "div":
System.out.println("\nDivision: "+a+"/"+b);
ZuseBinaryFloatingPoint24Bit divres = new Operation().div(bfp24bit1, bfp24bit2);
System.out.println("divisor: " + divres.floatValue(true));
break;
default:
System.err.println("Wrong input operation!");
System.err.println(getHelp());
System.exit(0);
}
} catch (Exception e) {
System.err.println("Wrong number format input!");
System.err.println(getHelp());
System.exit(0);
}
} |
54900ca8-7c97-454d-b185-5db169e2d7a0 | 2 | public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(CONFIG_FILE);
} catch (IOException ex) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true;
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true;
}
return configuration.getBoolean("opt-out", false);
}
} |
e21155f1-4b18-4893-a890-b407931320f8 | 0 | public static ArrayList<Excel> scale(int coeff, ArrayList<Excel> toScale)
{
return Scalign.scale(coeff, toScale);
} |
02675388-9f82-45c5-9ec5-8e06d21900c6 | 4 | public ArrayList<Entity> retrieveSideWarps(){
ArrayList<Entity> warps = new ArrayList<>();
MapProperties prop = tileMap.getProperties();
Warp w;
if(prop.get("next")!=null){
w = main.findWarp(ID, 1);
w.setOffset(-4*Vars.TILE_SIZE, this.groundLevel);
warps.add(w);
// adds a trigger to show the title of the next location
if(w.getLink().outside){
TextTrigger tt = new TextTrigger(w.getWarpLoc().x + Vars.TILE_SIZE, w.getWarpLoc().y+
TextTrigger.DEFAULT_HEIGHT/2f-.36f*Vars.TILE_SIZE, "To "+w.getLink().locTitle, SpeechBubble.PositionType.RIGHT_MARGIN);
w.setTextTrigger(tt);
warps.add(tt);
}
} if(prop.get("previous")!=null){
w = main.findWarp(ID, 0);
w.setOffset(4*Vars.TILE_SIZE, this.groundLevel);
warps.add(w);
if(w.getLink().outside){
TextTrigger tt = new TextTrigger(w.getWarpLoc().x - Vars.TILE_SIZE, w.getWarpLoc().y+
TextTrigger.DEFAULT_HEIGHT/2f-.36f*Vars.TILE_SIZE, "To "+w.getLink().locTitle, SpeechBubble.PositionType.LEFT_MARGIN);
w.setTextTrigger(tt);
warps.add(tt);
}
}
return warps;
} |
1df42ab5-84d0-4e3f-bfe4-e1216de54f85 | 7 | public void insert(String column[], String value[], String type[])
{
if(conn!=null){
try
{
stmt = conn.createStatement();
String query = "insert into " + table_name + " (";
for(int i=0;i<column.length;i++){
query += column[i] + ", ";
}
query = query.substring(0, query.length()-2);
query += " ) values (";
for(int i=0;i<value.length;i++){
if(type[i].contentEquals("int"))
query += value[i] + ", ";
else
query += "'" + value[i] + "', ";
}
query = query.substring(0, query.length()-2);
query += " )";
stmt.execute(query);
//stmt.closeOnCompletion();
//
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
finally{
try {
if(stmt!=null)stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
884a2523-f7e3-48bb-a227-d3c572d59322 | 3 | public void updatePlayerDisplayName(Player p) {
String confPath = "players." + p.getName();
String title = fastTitles.getConfig().getString(confPath);
if (title == null || title.equalsIgnoreCase("none")) {
p.setDisplayName(p.getName());
} else {
String titleFormat = getTitle(title);
if (titleFormat != null) {
p.setDisplayName(formatString(colorize(titleFormat), p.getName()));
} else {
}
}
} |
bad2a741-7766-4018-8f32-f8327815e249 | 3 | @Override
public void cleanup() {
super.cleanup();
client.removeMessageListener(this);
if(!stateSwitch && client != null && client.isConnected()) {
client.close();
}
} |
e2b9d4fb-317f-4efb-acff-fa270f099e0b | 0 | public int GetEmptyTrips()
{
return emptyTrips;
} |
8e5103b9-00f2-43bf-98a1-4e15374b6cba | 4 | public static void main(String[] args) {
Scanner consoleScanner = new Scanner(System.in);
while (true) {
System.out.print("Would you like to do: [1] convert celsius to fahrenheit, [2] convert fahrenheit to celsius, [3] quit: ");
int input = 0;
input = consoleScanner.nextInt();
if (input == 1) {
celsius(consoleScanner);
} else if (input == 2) {
fahrenheit(consoleScanner);
} else if (input == 3) {
System.exit(0);
}
}
} |
07bf58f8-7f1f-4a82-b756-9fa7888448b1 | 4 | public void chooseImage() {
// get the entity from the map that is on either side of this. if one is a
// wall then we turn the graphic to a "-" if neither then we leave it as a
// "|"
if (getGameMap().isSceneryAtPoint(getX(), getY() + 1)) {
if (getGameMap().getSceneryAtPoint(getX(), getY() + 1) instanceof Wall) {
// DAD please make a note next time you try to change something (like
// using character codes instead of actual characters)
// I had a very weird bug where walls were 2s instead of lines and I had no idea what happened
wallGraphic = "|";
}
}
if (getGameMap().isSceneryAtPoint(getX(), getY() - 1)) {
if (getGameMap().getSceneryAtPoint(getX(), getY() - 1) instanceof Wall) {
wallGraphic = "|";
}
}
} |
f185581d-f811-4f86-be2e-07b0a53141dd | 7 | public SimpleFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("Forest:");
setLocation(400, 200);
Container con = getContentPane();
con.setLayout(new FlowLayout());
button1 = new JButton("Create");
button2 = new JButton("Read");
button3 = new JButton("Update");
button4 = new JButton("Delete");
textArea = new JTextArea();
con.add(button1);
con.add(button2);
con.add(button3);
con.add(button4);
con.add(textArea);
ArrayList<Oak> list1 = new ArrayList<Oak>();
ArrayList<DescriptionOak> list2 = new ArrayList<DescriptionOak>();
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Oak object1 = new Oak();
DescriptionOak object2 = new DescriptionOak();
object1 = Oak.createOak();
object2 = DescriptionOak.createOak(object1.getIdOak());
list1.add(object1);
list2.add(object2);
try {
DatabaseHelper object3 = new DatabaseHelper();
object3.insertOakDescriptionOak(
object3.getPreparedStatement(),
list1.get((list1.size() - 1)),
list2.get(list2.size() - 1));
} catch (SQLException r) {
}
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// list1.removeAll(list1);
// list2.removeAll(list2);
try {
DatabaseHelper object3 = new DatabaseHelper();
if (list1.isEmpty() == true) {
object3.selectOak(list1);
object3.selectDescriptionOak(list2);
}
} catch (SQLException r) {
}
textArea.setText(null);
for (int i = 0; i < list1.size(); i++) {
textArea.append(" Id of Oak = " + list1.get(i).getIdOak()
+ " ");
textArea.append(" Height of tree = "
+ list1.get(i).getHeightTree() + " ");
textArea.append(" Shape of lists of tree "
+ list1.get(i).getShapeListsTree() + " ");
textArea.append(" Age of tree= "
+ list1.get(i).getAgeTree() + " ");
textArea.append(" Number of Acorns = "
+ list1.get(i).getNumberAcorns() + " ");
textArea.append(" Number of branches = "
+ list1.get(i).getNumberBranches() + "\n");
// }
// for(int i=0;i<list2.size();i++)
// {
textArea.append(" Id of description = "
+ list2.get(i).getIdDescription() + " ");
textArea.append(" Id of Oak = " + list2.get(i).getIdOak()
+ " ");
textArea.append(" Type of Oak " + list2.get(i).getTypeOak()
+ " ");
textArea.append(" Size of acorn = "
+ list2.get(i).getSizeAcorn() + "\n");
}
}
});
button3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
// DatabaseHelper object3 = new DatabaseHelper();
list1.removeAll(list1);
list2.removeAll(list2);
{
DatabaseHelper object3 = new DatabaseHelper();
object3.selectOak(list1);
object3.selectDescriptionOak(list2);
}
// object3.deleteOakDescriptionOak(object3.getPreparedStatement());
// for (int i=0;i<list1.size();i++)
// {
// object3.insertOakDescriptionOak(object3.getPreparedStatement(),list1.get(i),list2.get(i));
// object3.selectOak(list1);
// object3.selectDescriptionOak(list2);
// }
} catch (SQLException r) {
}
}
});
button4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Scanner scan = new Scanner(System.in);
System.out.println("Input index to delete");
int index = scan.nextInt();
list1.remove(index);
list2.remove(index);
try {
DatabaseHelper object3 = new DatabaseHelper();
object3.deleteOakDescriptionOak(object3
.getPreparedStatement());
for (int i = 0; i < list1.size(); i++) {
object3.insertOakDescriptionOak(
object3.getPreparedStatement(),
list1.get((list1.size() - 1)),
list2.get(list2.size() - 1));
}
} catch (SQLException r) {
}
}
});
} |
9bd1bf58-ce5b-4316-b3d5-5aece8ab0622 | 0 | public byte[] toByteArray() {
return stream.toByteArray();
} |
cc8074c4-ec10-4774-afd0-2bf70c5534f5 | 1 | public void testConstructor_invalidObject_DateTimeZone() throws Throwable {
try {
new DateMidnight(new Object(), PARIS);
fail();
} catch (IllegalArgumentException ex) {}
} |
61d41f30-ce08-474a-81ee-aff67b15ed19 | 5 | private static final void method714(int i) {
Widget class46 = AbstractFontRasterizer.getWidget(i);
if (class46 != null) {
int i_520_ = i >>> 16;
Widget[] class46s = Class369_Sub2.aClass46ArrayArray8584[i_520_];
if (class46s == null) {
Widget[] class46s_521_
= Class348_Sub40_Sub33.aClass46ArrayArray9427[i_520_];
int i_522_ = class46s_521_.length;
class46s = Class369_Sub2.aClass46ArrayArray8584[i_520_]
= new Widget[i_522_];
ArrayUtils.arrayCopy(class46s_521_, 0, class46s, 0,
class46s_521_.length);
}
int i_523_;
for (i_523_ = 0; i_523_ < class46s.length; i_523_++) {
if (class46s[i_523_] == class46)
break;
}
if (i_523_ < class46s.length) {
ArrayUtils.arrayCopy(class46s, i_523_ + 1, class46s, i_523_,
class46s.length - i_523_ - 1);
class46s[class46s.length - 1] = class46;
}
}
} |
13cc657c-eba9-42bb-b94c-385e98835a09 | 3 | * @return The amount
*/
public int getComboAmount(int c) {
if (c == SimpleCreature.COMBO_ONE) {
return SimpleCreature.COMBO_ONE_AMOUNT;
}
if (c == SimpleCreature.COMBO_TWO) {
return SimpleCreature.COMBO_TWO_AMOUNT;
}
if (c == SimpleCreature.COMBO_THREE) {
return SimpleCreature.COMBO_TWO_AMOUNT;
}
return -1;
} |
a0a47023-4f81-4a96-81c3-5306dbfb036d | 9 | public void doSspcCdf(int first, int last, int date) throws CDFException{
float scint_temp = 0, dpu_temp = 0;
int numOfRecs = last - first;
float[][]
sspc_rebin = new float[numOfRecs][256],
sspc_error = new float[numOfRecs][256];
float[]
old_edges,
std_edges = SpectrumExtract.stdEdges(2, 2.4414f);
float[] peak = new float[numOfRecs];
int[]
frameGroup = new int[numOfRecs],
q = new int[numOfRecs];
long[] epoch = new long[numOfRecs];
System.out.println("\nSaving SSPC...");
//rebin the sspc spectra
for(int sspc_rec = 0, hkpg_rec = 0; sspc_rec < numOfRecs; sspc_rec++){
//find correct hkpg_rec
int target_frame =
CDF_Gen.data.frame_mod32[sspc_rec] -
(CDF_Gen.data.frame_mod32[sspc_rec] % 40);
while(
(CDF_Gen.data.frame_mod40[hkpg_rec] <= target_frame) &&
(hkpg_rec <= sspc_rec) &&
(hkpg_rec < CDF_Gen.data.frame_mod40.length)
){
hkpg_rec++;
}
//get temperatures
if(CDF_Gen.data.hkpg[Constants.T0][hkpg_rec] != Constants.HKPG_FILL){
scint_temp =
(CDF_Gen.data.hkpg[Constants.T0][hkpg_rec] *
CDF_Gen.data.hkpg_scale[Constants.T0]) +
CDF_Gen.data.hkpg_offset[Constants.T0];
}
if(CDF_Gen.data.hkpg[Constants.T5][hkpg_rec] != Constants.HKPG_FILL){
dpu_temp =
(CDF_Gen.data.hkpg[Constants.T5][hkpg_rec] *
CDF_Gen.data.hkpg_scale[Constants.T5]) +
CDF_Gen.data.hkpg_offset[Constants.T5];
}
//get the adjusted bin edges
old_edges =
SpectrumExtract.makeedges(
2, scint_temp, dpu_temp, CDF_Gen.data.peak511_bin[sspc_rec + first]
);
//rebin the spectrum
sspc_rebin[sspc_rec] = SpectrumExtract.rebin(
CDF_Gen.data.sspc[sspc_rec + first], old_edges, std_edges
);
float fill = CDFVar.getIstpVal("FLOAT_FILL").floatValue();
for(int bin_i = 0; bin_i < sspc_rebin[sspc_rec].length; bin_i++){
if(sspc_rebin[sspc_rec][bin_i] != fill){
float width = std_edges[bin_i + 1] - std_edges[bin_i];
//get the count error
sspc_error[sspc_rec][bin_i] =
(float)Math.sqrt(sspc_rebin[sspc_rec][bin_i])
/ (width * 32f);
//divide counts by bin width and adjust the time scale
sspc_rebin[sspc_rec][bin_i] /= (width * 32f);
}
}
}
for(int rec_i = 0, data_i = first; data_i < last; rec_i++, data_i++){
peak[rec_i] = CDF_Gen.data.peak511_bin[data_i];
frameGroup[rec_i] = CDF_Gen.data.frame_mod32[data_i];
epoch[rec_i] = CDF_Gen.data.epoch_mod32[data_i];
q[rec_i] = CDF_Gen.data.sspc_q[data_i];
}
String destName =
outputPath + "/" + date + "/" + "bar_" + id +
"_l2_" + "sspc" + "_20" + date + "_v" + revNum + ".cdf";
SSPC sspc = new SSPC(destName, "bar_" + id, date, 2);
System.out.println("sspc");
sspc.getCDF().addData("SSPC", sspc_rebin);
System.out.println("sspc error");
sspc.getCDF().addData("cnt_error", sspc_error);
System.out.println("Peak_511");
sspc.getCDF().addData("Peak_511", peak);
System.out.println("FrameGroup");
sspc.getCDF().addData("FrameGroup", frameGroup);
System.out.println("Epoch");
sspc.getCDF().addData("Epoch", epoch);
System.out.println("Q");
sspc.getCDF().addData("Q", q);
sspc.close();
} |
d8b1db98-edd5-4fcd-bd39-c7caa5ae2b31 | 0 | @Override
public boolean setDefault(boolean def) {
return (defaultGroup = def);
} |
1991a9bf-9254-4fc0-b176-8cabd6022bbe | 0 | @Override
public Set<String> getGroups() throws DataLoadFailedException {
return getList("groups", "name");
} |
2f0bc326-7c32-480a-b5bb-8fea5f3ad4f9 | 7 | private void fallIfPossible(World par1World, int par2, int par3, int par4)
{
if (BlockSand.canFallBelow(par1World, par2, par3 - 1, par4) && par3 >= 0)
{
byte var8 = 32;
if (!BlockSand.fallInstantly && par1World.checkChunksExist(par2 - var8, par3 - var8, par4 - var8, par2 + var8, par3 + var8, par4 + var8))
{
EntityFallingSand var9 = new EntityFallingSand(par1World, (double)((float)par2 + 0.5F), (double)((float)par3 + 0.5F), (double)((float)par4 + 0.5F), this.blockID);
par1World.spawnEntityInWorld(var9);
}
else
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
while (BlockSand.canFallBelow(par1World, par2, par3 - 1, par4) && par3 > 0)
{
--par3;
}
if (par3 > 0)
{
par1World.setBlockWithNotify(par2, par3, par4, this.blockID);
}
}
}
} |
18d1b3b1-106b-41cf-b70d-a12b5b12a2a3 | 9 | static void quickSortStringArray(String array[], int lo0, int hi0) {
int lo = lo0 ;
int hi = hi0 ;
String mid = null ;
if ( hi0 > lo0 ) {
mid = array[(lo0+hi0)/2] ;
while (lo <= hi) {
while ((lo < hi0) && (array[lo].compareTo(mid) < 0))
++lo ;
while ((hi > lo0) && (array[hi].compareTo(mid) > 0))
--hi ;
if ( lo <= hi ) {
String tmp = array[lo] ;
array[lo] = array[hi] ;
array[hi] = tmp ;
++lo ;
--hi ;
}
}
if ( lo0 < hi )
quickSortStringArray(array, lo0, hi) ;
if ( lo < hi0 )
quickSortStringArray(array, lo, hi0) ;
}
} |
e1141a96-8611-46d2-b866-af7a219d5203 | 9 | public static void checkEvolutions()
{
for(int i=0; i<userNumOfPokemon; i++)
{
if(user[i].status!=Pokemon.Status.FNT&&Mechanics.participatedInBattle[i]&&(user[i].evolve(user[i])!=user[i].species||user[i].evolve(user[i],JokemonDriver.trainerIdNumber)!=user[i].species))
{
ynWin=new YesNoWindow();
ynWin.addMessage("What? "+user[i].nickname+" is evolving!","Allow Evolution?");
while(ynWin.isVisible())
{
System.out.println("Wating for evolution decision...");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(ynWin.getYes())
{
b1.addText(user[i].nickname+" evolved into ");
if(user[i].evolve(user[i])!=user[i].species)
{
System.out.println(user[i].evolve(user[i]));
user[i]=user[i].evolution(user[i],user[i].evolve(user[i]));
user[i].move = Mechanics.levelUpMove(user[i],true);
b1.addText(user[i].toString(user[i].species)+"!");
}
else
{
System.out.println(user[i].evolve(user[i],JokemonDriver.trainerIdNumber));
user[i]=user[i].evolution(user[i],user[i].evolve(user[i],JokemonDriver.trainerIdNumber));
user[i].move = Mechanics.levelUpMove(user[i],true);
b1.addText(user[i].toString(user[i].species)+"!");
}
b1.createPokemonImages();
Pokedex.caught(user[i].pokedexNumber-1);
Pokedex.seen(user[i].pokedexNumber-1);
}
else
{
b1.addText("You cancelled the evolution...");
}
}
}
} |
572e13b7-637f-45ca-a914-f979c311b3cc | 1 | protected void type(By locator, String text)
{
if (text != null)
{
driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(text);
}
} |
ba46fa8d-eb87-42f7-aadc-92c5d9ba6a81 | 4 | private void getNextTetromino() {
// Get next tetromino and generate new one
Iterator<Tetromino> it = next.iterator();
if (it.hasNext()) {
tetromino = next.pop();
next.add(bag.draw());
} else {
tetromino = bag.draw();
}
// Notify listeners that tetrominoes preview is updated.
if (nextTetrominoesChangedListener != null)
nextTetrominoesChangedListener.onNextTetrominoesChanged(next);
// Lose player if game is lost.
if (isLost()) {
if (gameOverListener != null)
gameOverListener.onGameOver(false);
}
} |
acc6f36b-5d9c-49d8-b383-8cbe0f20b30a | 2 | public static void main(String[] args) throws IOException {
String filename = "fairyface";
BufferedImage img = ImageIO.read(new File(filename + ".png"));
int height = img.getHeight();
int width = img.getWidth();
int k = 1;
int horz = 2;
int vert = 4;
int hSize = height / horz;
int wSize = width / vert;
for(int y = 0; y < height; y += hSize) {
for(int x = 0; x < width; x += wSize) {
BufferedImage tile = img.getSubimage(x, y, wSize, hSize);
ImageIO.write(tile, "png", new File(filename + k + ".png"));
k++;
}
}
} |
43e3830e-0306-422b-99f4-d77ab7520b50 | 8 | private static void printKMax(int[] items, int k) {
Deque<Integer> que = new ArrayDeque<Integer>(k);
for (int i = 0; i < k; i++) {
// Remove index of items smaller than current item in the array
while (!que.isEmpty() && items[i] >= items[que.peekLast()]) {
que.pollLast();
}
que.addLast(i);
}
for (int i = k; i < items.length; i++) {
System.out.println(items[que.getFirst()]);
// Remove elements that are out of the sliding window
while (!que.isEmpty() && que.peekFirst() <= (i - k)) {
que.pollFirst();
}
// Remove index of items smaller than current item in the array
while (!que.isEmpty() && items[i] >= items[que.peekLast()]) {
que.pollLast();
}
que.addLast(i);
}
System.out.println(items[que.getFirst()]);
} |
3e27d511-1c6b-438b-8dd1-4372231597da | 5 | @Override
public Pos WhereSet(Bord bord,Pos clickPos) {
Pos retPos = null;
ArrayList<Point> handList = new ArrayList<Point>();
// おけるところすべてを取得してループをまわす
ArrayList<Pos> canSetList = bord.getCanSetList(getMyColor());
for (Pos pos : canSetList) {
Bord vrBord = bord.clone();
// 一度石を置く
vrBord.DoSet(pos, getMyColor(), true);
// 相手が次に一番いいところに打つ
Pos workPos = bord.SearchMaxPos(Stone.reverseStone(getMyColor()));
// 相手がパスか判断
if (workPos != null) {
vrBord.DoSet(workPos, Stone.reverseStone(getMyColor()), true);
}
// 相手の最善手のあと、自分も一番いいところにおいてみる
workPos = bord.SearchMaxPos(getMyColor());
if (workPos != null) {
// 自分がパスか判断
vrBord.DoSet(workPos, getMyColor(), true);
}
// 自分と相手の石の差を取得する
int getCnt = vrBord.GetCount(getMyColor()) - vrBord.GetCount(Stone.reverseStone(getMyColor()));
handList.add(new Point(getCnt, new Pos(pos.getX(), pos.getY())));
}
//結果が一番いいところを探す
int maxCnt = Integer.MIN_VALUE;
for (Point valuePos : handList) {
if (maxCnt < valuePos.getValue()) {
maxCnt = valuePos.getValue();
retPos = valuePos.getPos();
}
}
return retPos;
} |
cd306ec9-c206-410a-82b4-dbe5e92de269 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
else if (obj == null)
return false;
else if (getClass() != obj.getClass())
return false;
else {
Num other = (Num) obj;
if (x == null && other.x != null)
return false;
else if (!x.equals(other.x))
return false;
else
return true;
}
} |
7270b5a2-12c9-4c25-909d-e6557c366072 | 3 | public final boolean operator(Screen r) {
if (id != r.id)
return false;
if (!dimensions.equals(r.dimensions))
return false;
if (flags != r.flags)
return false;
return true;
} |
bbc0bf16-359c-4bd7-bcd9-18f02e7281bc | 1 | public void setDepth(int depth) {
this.depth = depth;
for (Node n : children.values()) {
n.setDepth(depth + 1);
}
} |
ede0088f-0973-49cf-87a3-2908b9b8f36b | 4 | public static void main(String[] args) {
try {
f(0);
f(1);
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally: f(1)");
}
try {
f(2);
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally: f(2)");
}
try {
f(3);
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally: f(3)");
}
try {
f(4);
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally: f(4)");
}
} |
2fcb140c-6eba-4091-8572-fdbb0ff33c57 | 9 | public static void main(String[] args) throws IOException {
boolean running = true;
while (running) {
System.out.println("0.\tQuit");
System.out.println("1.\tCustom packet");
System.out.println("2.\tIdent packet");
System.out.println("3.\tRequest flavors packet");
System.out.println("4.\tRequest top combos packet");
System.out.println("5.\tRequest combo info packet");
System.out.println("6.\tRate combo packet");
System.out.println("7.\tServer shutdown packet");
System.out.print("Enter choice: ");
int choice = s.nextInt();
switch (choice) {
case 0:
running = false;
break;
case 1:
sendData(customPacket());
break;
case 2:
sendData(identPacket());
break;
case 3:
sendData(new byte[] { 0x01 });
break;
case 4:
sendData(new byte[] { 0x02 });
break;
case 5:
sendData(comboInfoPacket());
break;
case 6:
sendData(rateComboPacket());
break;
case 7:
sendData(new byte[] { 0x7F });
break;
}
}
} |
a36c9eaa-eaba-44b9-831c-246f7942c511 | 6 | public void makeDeclaration(Set done) {
super.makeDeclaration(done);
if (isConstructor() && !isStatic()
&& (Options.options & Options.OPTION_ANON) != 0) {
ClassInfo clazz = getClassInfo();
InnerClassInfo outer = getOuterClassInfo(clazz);
ClassAnalyzer clazzAna = methodAnalyzer.getClassAnalyzer(clazz);
if (clazzAna != null && outer != null && outer.name == null) {
/*
* call makeDeclaration on the anonymous class, since _we_ will
* declare the anonymous class.
*/
clazzAna.makeDeclaration(done);
}
}
} |
cd97caa0-323d-4301-9370-081369c0a217 | 3 | @Override
public void keyEnterPressed() {
if (!Game.RELEASE) {
if (shouldRender) {
if (consoleText.isEmpty()) {
opening = false;
closing = true;
} else {
hudManager.processConsoleCommand(consoleText);
opening = false;
closing = false;
shouldRender = false;
consoleText = "";
positionY = 0 - MAX_HEIGHT;
}
} else {
shouldRender = true;
closing = false;
opening = true;
}
}
} |
c50a6225-2dea-403e-80a1-badf163a0387 | 9 | public MultiPointerServer() throws IOException, AWTException
{
thisPtr = this;
loadConfig(CONFIG_FILE);
/*
try
{
localAddr = InetAddress.getLocalHost();
if (localAddr.isLoopbackAddress())
{
localAddr = LinuxInetAddress.getLocalHost();
}
mLocalHostName = localAddr.getHostName();
mLocalHostIP = localAddr.getHostAddress();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
*/
// ローカルホスト名とIPアドレスを取得
try
{
InetAddress addr = InetAddress.getLocalHost();
mLocalHostName = addr.getHostName();
mLocalHostIP = addr.getHostAddress();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
mOSName = System.getProperty("os.name");
mOSArch = System.getProperty("os.arch");
mOSVersion = System.getProperty("os.version");
// ポートの重複チェック
try
{
ServerSocket serverSoc = new ServerSocket(mPortNum);
serverSoc.close();
}
catch( BindException e )
{
JOptionPane.showMessageDialog(null, "ポート番号:" + String.valueOf(mPortNum) + "が既に使用されています。\nサーバソフトが起動中でないか確認してください。\n起動していない場合、config.txtのport:の値を変更してください。");
System.exit(1);
return;
}
SystemTray tray = SystemTray.getSystemTray();
mPopupMenu = new PopupMenu("Wi-Fi Multi TouchPad Server");
makeMenu( mPopupMenu );
Image iconImage = ImageIO.read(new File("./res/icon.png"));
icon = new TrayIcon( iconImage, "Wi-Fi Multi TouchPad Server\nServer IP:" + mLocalHostIP, mPopupMenu);
icon.addMouseListener(this);
tray.add(icon);
// ウィンドウ表示
// mPointerFrame = new PointerFrame(200,200);
// mPointerFrame.setVisible(true);
// mPointerFrame.setAlwaysOnTop(true);
// ScreenKeyboard mScreenKeyboard = new ScreenKeyboard();
// mScreenKeyboard.setVisible(true);
// mScreenKeyboard.setAlwaysOnTop(true);
mReceiveThread = new ReceiveThread( this, mPortNum );
mReceiveThread.start();
mReceiveThreadUDP = new ReceiveThreadUDP( this, mPortNum );
mReceiveThreadUDP.start();
// 切断チェックスレッド
mDisconnectThread = new Thread(){
public void run()
{
while( true )
{
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String disconnectedIp = "";
synchronized( mIpList )
{
for( String ip : mIpList)
{
// ipへの接続確認。
InetSocketAddress socketAddress = new InetSocketAddress(ip, mPortNum );
//socketAddressの値に基づいて通信に使用するソケットを作成する。
Socket socket = new Socket();
//タイムアウトは10秒(10000msec)
try {
socket.connect(socketAddress, 10000);
/*
//接続先の情報を入れるInetAddress型のinadrを用意する。
InetAddress inadr;
//inadrにソケットの接続先アドレスを入れ、nullである場合には
//接続失敗と判断する。
//nullでなければ、接続確立している。
if ((inadr = socket.getInetAddress()) != null)
{
System.out.println("Connect to " + inadr);
}
else
{
System.out.println("Connection failed.");
return;
}
//メッセージの送信処理
//PrintWriter型のwriterに、ソケットの出力ストリームを渡す。
PrintWriter writer = new PrintWriter(socket.getOutputStream());
//ソケットから出力する。
writer.println( "Ho_!" );
//終了処理
writer.close();
*/
socket.close();
} catch (IOException e) {
// 切断されたと判断。
// e.printStackTrace();
disconnectedIp = ip;
break;
}
}
}
if( disconnectedIp.equals(""))
{
}
else
{
icon.displayMessage("Disconnected", disconnectedIp, TrayIcon.MessageType.INFO);
PointerFrame P = mIpPointerFrameMap.get( disconnectedIp );
if( P != null )
{
P.setVisible( false );
P = null;
mIpPointerFrameMap.remove( mIpList.indexOf( disconnectedIp ) );
}
mIpList.remove( mIpList.indexOf( disconnectedIp ) );
makeMenu( mPopupMenu );
}
}//while(true)
}
};
mDisconnectThread.start();
try {
mDisconnectThread.join();
} catch (InterruptedException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
DebugLog( "切断検出スレッドが終了しました。" );
// mClipThread = new ClipboardWatchThread( 500, mPortNum );
// mClipThread.start();
} |
52a8e611-63cd-4109-b4c6-c8f324944b75 | 2 | @Override
public boolean activate() {
return (Bank.isOpen()
&& !Widgets.get(13, 0).isOnScreen()
&& Settings.usingHerb
);
} |
70040d1d-bc85-40c9-8259-05f1c37169fb | 2 | public void removePerson(P p) {
GameData g = GameData.getCurrentGame();
if (p instanceof Contestant)
g.removeContestant((Contestant) p);
else if (p instanceof User)
g.removeUser((User) p);
fireTableDataChanged();
} |
2b97cc94-a2ca-4e85-968e-46d7fe27f388 | 0 | public Map<String, Long> getStatistics() {
throw new RuntimeException("not implemented");
} |
3569e3a7-ca57-4f95-b34a-e16e46f09672 | 4 | private void reply(IrcMessage rawmessage, String message)
{
if(rawmessage.getType() == MessageTypes.CHANMSG)
{
try{ rawmessage.getClient().PrivMsg(rawmessage.getChannel(), message, false); }
catch(Exception e){}
return;
}
else if(rawmessage.getType() == MessageTypes.QUERYMSG)
{
try{ rawmessage.getClient().PrivMsg(rawmessage.getUser().getNick(), message, false); }
catch(Exception e) {}
return;
}
} |
3d0ff398-819c-47b0-8615-3b20b0e5616b | 9 | public void Weights(){
for(int i=0; i<inputNodes.length; i++)
for(int j=0; j<inputNodes[i].brnO.length; j++){
// System.out.print(inputNodes[i].brnO[j].getWeight()+"\t");
inputNodes[i].brnO[j].updateWeight(alfa);
// System.out.print(inputNodes[i].brnO[j].getWeight()+"\n");
}
//System.out.print("\n");
hlpHiddenNodes = new HiddenNode[inputNodes[0].brnO.length];
for(int j=0; j<hlpHiddenNodes.length; j++)
hlpHiddenNodes[j]=inputNodes[0].brnO[j].rightNode();
for(int i = 0; i <hiddenLayersNo; i++){
for(int j=0; j<hlpHiddenNodes.length; j++){
hlpHiddenNodes[j].updateBias(alfa);
for(int h=0; h<hlpHiddenNodes[0].brnO.length; h++){
// System.out.print(hlpHiddenNodes[j].brnO[h].getWeight()+"\t");
hlpHiddenNodes[j].brnO[h].updateWeight(alfa);
// System.out.print(hlpHiddenNodes[j].brnO[h].getWeight()+"\n");
}
//System.out.print("\n");
}
if(i==hiddenLayersNo-1) break;
prevHiddenNodes = new HiddenNode[hlpHiddenNodes[0].brnO.length];
for(int j=0; j<prevHiddenNodes.length; j++)
prevHiddenNodes[j]=hlpHiddenNodes[0].brnO[j].rightNode();
hlpHiddenNodes=prevHiddenNodes;
}
for(int j=0; j<outputNodes.length; j++)
outputNodes[j].updateBias(alfa);
} |
b13c0cd0-b387-4120-bae3-c8701d3d1d3f | 1 | @Override
public boolean removeWatcher(WatchKey watchKey) throws IOException {
boolean isWatcherRemoved = JNotify.removeWatch((Integer) ((JNotifyWatchKey) watchKey).getWatchKey());
if (isWatcherRemoved) {
LOG.info(StringUtil.concatenateStrings("Watcher: ", watchKey.toString(), " was successfully unregistered."));
} else {
LOG.error(StringUtil.concatenateStrings("Failed to unregister watcher: ", watchKey.toString()));
}
return isWatcherRemoved;
} |
273be15e-9cad-4ba0-88ff-9c10c5866a1b | 1 | public static TennisGame getInstance(){
if(instancia == null){
instancia = new TennisGame();
}
return instancia;
} |
675bb9d0-33fc-493b-954a-d131c840f02a | 8 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Timing that = (Timing) o;
if (Double.compare(that.ioResponseTime, ioResponseTime) != 0) return false;
if (Double.compare(that.worstReadeTime, worstReadeTime) != 0) return false;
if (Double.compare(that.worstSamplingTime, worstSamplingTime) != 0) return false;
if (Double.compare(that.worstUpdateTime, worstUpdateTime) != 0) return false;
if (Double.compare(that.worstWriteTime, worstWriteTime) != 0) return false;
return true;
} |
57db3989-6f02-49ea-895c-3a74ad81ac24 | 0 | @Override
public void testAssumptionFailure(Failure failure) {
setCurrentFailure(failure);
logger.warn("END Testcase '{}' '{}' BLOCKED because '{}'.", new Object[] {getId(failure.getDescription()),
failure.getTestHeader(), failure.getMessage(), });
} |
77c1688a-495b-4ea1-a0b2-4fb35c103c0c | 8 | static final public void expressao_relacional() throws ParseException {
trace_call("expressao_relacional");
try {
adicao();
label_7:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMPARACAO:
case DIFERENTE:
case MAIOR_QUE:
case MENOR_QUE:
case MAIOR_OU_IGUAL:
case MENOR_OU_IGUAL:
;
break;
default:
jj_la1[15] = jj_gen;
break label_7;
}
operadores_relacionais();
adicao();
}
} finally {
trace_return("expressao_relacional");
}
} |
e0313f1a-a257-4964-966f-0832932266b1 | 3 | void disposeAccessibles() {
if (accessibles != null) {
for (int i = 0; i < accessibles.length; i++) {
if (accessibles[i] != null) {
accessibles[i].dispose();
}
}
accessibles = null;
}
} |
f48145e2-30e9-43a5-a06d-6f2a751a2fd7 | 0 | public String[] getSomeStrArray() {
return someStrArray;
} |
877786c8-8934-4c98-a103-77fa04571458 | 4 | private static boolean isPermutate(int i, int j){
int[] a = new int[10];
int[] b = new int[10];
String si = Integer.toString(i);
String sj = Integer.toString(j);
for(char ii : si.toCharArray()){
a[Integer.parseInt(""+ii)]++;
}
for(char jj : sj.toCharArray()){
b[Integer.parseInt(""+jj)]++;
}
for(int ti=0;ti<10;ti++){
if (a[ti] != b[ti]) return false;
}
return true;
} |
0a564b41-d53e-4c80-b813-96962592e342 | 8 | public static void run(URL warUrl, boolean consoleMode, String[] args)
throws Exception {
if (args.length == 0 || isHelp(args)) {
BootstrapCommon.printUsage(WebappBootstrapMain.class, "usage-webapp.txt");
System.exit(-1);
}
Options options = createOptions();
Parser parser = new GnuParser();
CommandLine cli = parser.parse(options, args);
args = cli.getArgs();
if (args.length != 1) {
BootstrapCommon.printUsage(WebappBootstrapMain.class, "usage-webapp.txt");
System.exit(-1);
}
String bundlePath = args[0];
System.setProperty("bundlePath", bundlePath);
int port = 8080;
if (cli.hasOption(ARG_PORT))
port = Integer.parseInt(cli.getOptionValue(ARG_PORT));
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(port);
server.setConnectors(new Connector[] {connector});
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/");
context.setWelcomeFiles(new String[] {"index.action"});
context.setWar(warUrl.toExternalForm());
// We store the command line object as a webapp context attribute so it can
// be used by the context loader to inject additional beans as needed
context.setAttribute(WebappCommon.COMMAND_LINE_CONTEXT_ATTRIBUTE, cli);
server.setHandler(context);
/**
* We specify a Jetty override descriptor to inject additional definitions
* into our web.xml configuration. Specifically, we specify a
* <context-param> to specify the "contextClass" that will be used to create
* our Spring ApplicationContext. We create a custom version that will
* inject additional beans based on command-line arguments.
*/
context.addOverrideDescriptor("/WEB-INF/override-web.xml");
if (cli.hasOption(WebappCommon.ARG_BUILD)) {
System.setProperty("hibernate.hbm2ddl.auto", "update");
System.setProperty("bundleCacheDir", bundlePath + "/cache");
System.setProperty("gtfsPath",
cli.getOptionValue(WebappCommon.ARG_GTFS_PATH));
context.addOverrideDescriptor("/WEB-INF/builder-override-web.xml");
}
try {
server.start();
System.err.println("=============================================================");
System.err.println("=");
System.err.println("= Your OneBusAway instance has started. Browse to:");
System.err.println("=");
System.err.println("= http://localhost:8080/");
System.err.println("=");
System.err.println("= to see your instance in action.");
if (consoleMode) {
System.err.println("=");
System.err.println("= When you are finished, press return to exit gracefully...");
}
System.err.println("=============================================================");
if (consoleMode) {
System.in.read();
server.stop();
server.join();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
} |
4d862a0a-ec6b-47cf-a09e-43f8e5329f94 | 8 | public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int startx = 0;
int starty = 0;
int endx = n - 1;
int endy = n - 1;
int num = 1;
while (startx <= endx && starty <= endy) {
for (int i = starty; i <= endy; i++) {
matrix[startx][i] = num;
num++;
}
for (int i = startx + 1; i <= endx; i++) {
matrix[i][endy] = num;
num++;
}
if (startx != endx) {
for (int i = endy - 1; i >= starty; i--) {
matrix[endx][i] = num;
num++;
}
}
if (starty != endy) {
for (int i = endx - 1; i > startx; i--) {
matrix[i][starty] = num;
num++;
}
}
startx++;
endx--;
starty++;
endy--;
}
return matrix;
} |
e64e737d-9bfa-47a3-aa7d-881058fc5d1c | 4 | private void removeAllComponents(Container container){
if(container.getComponentCount() != 0){
for (Component component : container.getComponents()) {
if(component instanceof Container){
Container childContainer = (Container) component;
if(childContainer.getComponentCount() != 0){
removeAllComponents(childContainer);
}
//System.out.println("removed: " + component.getClass());
removeAllListenersOnComponent(component);
((Container) component).removeAll();
component = null;
}
}
}
//System.out.println("removed: " + container.getClass());
container = null;
} |
cb16ba90-967d-41e7-a035-9fd789bd9d75 | 3 | public int calcFatorInc(Personagem personagem){
int valor = 0;
switch (personagem.getClasse()){
case 1:
valor = (int) (personagem.getQuantidadeVida() * 0.1);
break;
case 2:
valor = (int) (personagem.getQuantidadeVida() * 0.4);
break;
case 3:
valor = (int) (personagem.getQuantidadeVida() * 0.3);
break;
default:
System.out.println("Personagem nao é protagonista");
}
return valor;
} |
e38b0622-14a5-4f77-8438-61387230d9c7 | 7 | public static void main(String[] args) {
final String graphite_path = "/home/inescid/graphite/";
final String sniper_path = "/home/inescid/sniper-5.3/";
final String test_folder_path = "/home/inescid/Desktop/autotests/";
if(args.length == 0 || args.length > 6){
System.out.println("use --help option to obtain a listing of the availables options");
}
else{
if (args[0].equals("--help")) {
System.out.println("AutoTest sim_name cores_from cores_to option value");
System.out.println(" sim_name: graphite, sniper simulator to use");
System.out.println(" cores_from: 0,1,... number of cores for the first simulation (2^cores_from)");
System.out.println(" cores_to: 1,2... number of cores for the last simulation (2^cores_to), simulations are ran from (2^cores_from) up to (2^cores_to)");
System.out.println(" option: cores,.. option of the sim.cfg to change");
System.out.println(" value: 10,256.. value to assign to the option of the sim.cfg");
System.out.println("");
System.out.println("Example: AutoTest sniper parsec 0 10 --config-file 2d-mesh");
}
else if (args[0].equals("graphite")) {
System.out
.println("###################### STARTING GRAPHITE AUTOTESTS ######################");
GrahpiteTestGenerator testgen = new GrahpiteTestGenerator(
graphite_path, test_folder_path+"/graphite/");
System.out.println(args[2] + " " + args[3]);
GraphiteTest test = testgen.generateTest(
args[1],
numberCores(Integer.valueOf(args[2]),
Integer.valueOf(args[3])), args[4], args[5]);
test.execute();
System.out
.println("###################### END OF GRAPHITE AUTOTESTS ######################");
}
//
else if(args[0].equals("graphite-process")){
GraphiteResultProcess rp = new GraphiteResultProcess(args[1]);
rp.process();
//graphite-process folder-with-tests
}
else if(args[0].equals("sniper")){
System.out.println("###################### STARTING SNIPER AUTOTESTS ######################");
//System.out.println("##### SNIPER requires BENCHMARKS_ROOT and SNIPER_ROOT to be set");
SniperTestGenerator testgen = new SniperTestGenerator(
sniper_path, test_folder_path+"sniper/");
System.out.println(args[1] + " " + args[2]);
SniperTest test = testgen.generateTest(
args[1], // command
numberCoresSniper(Integer.valueOf(args[2]),
Integer.valueOf(args[3])),
args[4], //option
args[5]); //value
test.execute();
System.out
.println("###################### END OF SNIPER AUTOTESTS ######################");
//sniper parsec 2 3 --config-file 2d-mesh
}
else if(args[0].equals("sniper-process")){
SniperResultProcess rp = new SniperResultProcess(args[1], args[2]);
rp.process();
//sniper-process folder-with-tests swaptions
}
}
} |
c8599ae2-ad49-4e30-b530-db0f7e9a5cab | 2 | private void appendToBuffer(StringBuffer buf, String text, int depth, boolean appendLineEnd) {
for (int i = 0; i < depth; i++) {
buf.append(CHAR_TAB);
}
buf.append(text);
if (appendLineEnd) {
buf.append(CHAR_NEWLINE);
}
} |
e6610a82-d21e-4116-bb3d-de9849da857c | 9 | public String getConfigPath(String filename) {
if (isApplet()) return null;
File jgamedir;
try {
jgamedir = new File(System.getProperty("user.home"), ".jgame");
} catch (Exception e) {
// probably AccessControlException of unsigned webstart
return null;
}
if (!jgamedir.exists()) {
// try to create ".jgame"
if (!jgamedir.mkdir()) {
// fail
return null;
}
}
if (!jgamedir.isDirectory()) return null;
File file = new File(jgamedir,filename);
// try to create file if it didn't exist
try {
file.createNewFile();
} catch (IOException e) {
return null;
}
if (!file.canRead()) return null;
if (!file.canWrite()) return null;
try {
return file.getCanonicalPath();
} catch (IOException e) {
return null;
}
} |
ac1b7cfe-ee0d-4268-acdb-9d8921aa224d | 7 | @Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
switch (action) {
case "Start":
boolean validInput = true;
String userFisrtName = tfUserName.getText();
String userLastName = tfUserLastName.getText();
if (userFisrtName.equals("") || userLastName.equals("")) {
validInput = false;
dInvalidInput = new JDialog(this, "Error!");
dInvalidInput.setSize(new Dimension(200, 100));
dInvalidInput.setLocation(new Point(Global.SCREEN_WIDTH / 2,
Global.SCREEN_HEIGHT / 2));
JLabel lError = new JLabel("Please fill all the fields");
JButton ok = new JButton("OK");
ok.addActionListener(this);
dInvalidInput.getContentPane().setLayout(new GridLayout(2, 1));
dInvalidInput.getContentPane().add(lError);
dInvalidInput.getContentPane().add(ok);
dInvalidInput.setVisible(true);
dInvalidInput.setFocusable(true);
dInvalidInput.setResizable(false);
}
if (validInput == true) {
String serverMessage = null;
pw.println("REGUSER");
try {
serverMessage = br.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
if (serverMessage.equalsIgnoreCase("NAME"))
pw.println(userFisrtName + " " + userLastName);
else
pw.println("REGUSER");
TFQuestionFrame qFrame = new TFQuestionFrame(clientSocket);
this.setVisible(false);
qFrame.setVisible(true);
this.dispose();
}
break;
case "OK":
dInvalidInput.dispose();
break;
default:
}
} |
efa8df46-e7b6-4a21-b44e-d0c84b152db5 | 0 | public static Image getFaceDownCardImage() {
String curDir = System.getProperty("user.dir");
String pathName = curDir + "/classic_cards/";
Image pic = Toolkit.getDefaultToolkit().getImage(pathName + cardImageFileNames[cardImageFileNames.length - 1]);
return pic;
} |
8b97de8f-a095-40e5-a6ac-9b2aa589929b | 0 | @Override
public Object getValue() {
return this.nativeValue;
} |
8685428b-a9f7-4746-803c-6673e8719cb2 | 4 | @Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_D) {
MainChar.setRPress(false);
}
if (e.getKeyCode() == KeyEvent.VK_A) {
MainChar.setLPress(false);
}
if (e.getKeyCode() == KeyEvent.VK_S) {
MainChar.setDPress(false);
}
if (e.getKeyCode() == KeyEvent.VK_W) {
MainChar.setUPress(false);
}
} |
4e0e2f60-eb1a-4dfe-9244-bcfb06541b32 | 4 | @Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals(">>>>")) {
verplaatsOpdrachtNaarRechts();
} else if (action.equals("<<<<")) {
verwijderOpdrachtVanToegevoegdeOpdrachten();
} else if (action.equals("^^^^")) {
verplaatsOpdrachtNaarBoven();
} else if (action.equals("Registreer nieuwe quiz")) {
registreerNieuweQuiz();
}
} |
9842b9ea-76fd-44e1-858b-af5f9120196e | 5 | public static void setIntLE(final byte[] array, final int index, final int value, final int size) {
switch (size) {
case 0:
return;
case 1:
Bytes.setInt1(array, index, value);
break;
case 2:
Bytes.setInt2LE(array, index, value);
break;
case 3:
Bytes.setInt3LE(array, index, value);
break;
case 4:
Bytes.setInt4LE(array, index, value);
break;
default:
throw new IllegalArgumentException();
}
} |
e6910f92-36f0-48ab-ae11-94751c170c3c | 5 | private static int[] stringToArray_4(String s) {
int[] ret = null;
if ((s != null) && !s.equals("")) {
String[] tmp = s.split(SkinConstants.SPLIT2);
if (tmp.length == 4) {
ret = new int[4];
try {
for (int i = 0; i < tmp.length; i++) {
ret[i] = Integer.parseInt(tmp[i]);
}
} catch (NumberFormatException e) {
ret = null;
}
}
}
return ret;
} |
c28d67f1-cc87-4f71-bdd8-33cb034f6d63 | 1 | private boolean headerAlreadySent(Map<String, String> header, String name) {
boolean alreadySent = false;
for (String headerName : header.keySet()) {
alreadySent |= headerName.equalsIgnoreCase(name);
}
return alreadySent;
} |
72c436cd-85b0-49ce-9169-7178e418e0b2 | 4 | public void tick(long delta) {
// FOLLOW CAM
//------------
//
// Seems to only work correct in 1920 * 1080 resolution
// Probably to do with scaling...
//
// Work on this later! (tired, 23.55 now...)
//
//------------
if(game.hero.getX() > ((game.getCameraX() + (game.getWidth() * 0.7)))) {
game.setCameraX((long)(game.hero.getX() - (game.getWidth() * 0.7)));
}
if(game.hero.getY() > game.getCameraY() + (game.getHeight() * 0.7)) {
game.setCameraY((long)(game.hero.getY() - (game.getHeight() * 0.7)));
}
if(game.hero.getX() < game.getCameraX() + (game.getWidth() * 0.3)) {
game.setCameraX((long)(game.hero.getX() - game.getWidth() * 0.3));
}
if(game.hero.getY() < game.getCameraY() + (game.getHeight() * 0.3)) {
game.setCameraY((long)(game.hero.getY() - game.getHeight() * 0.3));
}
} |
58470678-21e2-4cd9-b24d-ee54929d7eaa | 6 | public static Method findMethod(Class<?> clazz, String method, Class<?>... parameters) {
for (Method m : clazz.getDeclaredMethods())
if (m.getName().equals(method) && Arrays.equals(m.getParameterTypes(), parameters))
return m;
if (clazz.getSuperclass() != null)
return findMethod(clazz.getSuperclass(), method, parameters);
return null;
} |
963949e6-bc25-4cfa-aaeb-59e8b0d98a7e | 8 | public static void main(String[] args){
try {
Object obj = Class.forName(args[0]).newInstance();
String[] temp = new String[args.length-1];
for(int i=1 ; i<args.length ; i++){
temp[i-1] = args[i];
}
CommandLineParser.parseCommandLine(temp,obj);
for(Method method : obj.getClass().getMethods()){
if(method.getName().contains("get")){
try {
System.out.println(method.getName() + ":" + method.invoke(obj));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} |
8c8e1132-b304-4ddb-83d6-59d6689693a4 | 7 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
else
if((affected!=null)&&(affected instanceof Room)&&(invoker!=null))
{
final Room room=(Room)affected;
for(int i=0;i<room.numInhabitants();i++)
{
final MOB inhab=room.fetchInhabitant(i);
if(inhab.fetchEffect(ID())==null)
{
final Ability A=(Ability)this.copyOf();
A.setSavable(false);
A.startTickDown(invoker,inhab,tickDown);
}
if(inhab.isInCombat())
inhab.curState().adjMovement(-1,inhab.maxState());
}
}
return true;
} |
58a2b5d7-3ffb-4ff5-82a7-277506fff754 | 7 | public ChordBoardAPPView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
// progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
}
}
});
} |
70260392-0f61-436e-a0d7-4a5bdfe216da | 7 | public void testDuringAddIndexes() throws Exception {
Directory dir1 = new MockRAMDirectory();
final IndexWriter writer = new IndexWriter(dir1, new WhitespaceAnalyzer(),
IndexWriter.MaxFieldLength.LIMITED);
writer.setInfoStream(infoStream);
writer.setMergeFactor(2);
// create the index
createIndexNoClose(false, "test", writer);
writer.commit();
final Directory[] dirs = new Directory[10];
for (int i=0;i<10;i++) {
dirs[i] = new MockRAMDirectory(dir1);
}
IndexReader r = writer.getReader();
final int NUM_THREAD = 5;
final float SECONDS = 3;
final long endTime = (long) (System.currentTimeMillis() + 1000.*SECONDS);
final List excs = Collections.synchronizedList(new ArrayList());
final Thread[] threads = new Thread[NUM_THREAD];
for(int i=0;i<NUM_THREAD;i++) {
threads[i] = new Thread() {
@Override
public void run() {
while(System.currentTimeMillis() < endTime) {
try {
writer.addIndexesNoOptimize(dirs);
} catch (Throwable t) {
excs.add(t);
throw new RuntimeException(t);
}
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
int lastCount = 0;
while(System.currentTimeMillis() < endTime) {
IndexReader r2 = r.reopen();
if (r2 != r) {
r.close();
r = r2;
}
Query q = new TermQuery(new Term("indexname", "test"));
final int count = new IndexSearcher(r).search(q, 10).totalHits;
assertTrue(count >= lastCount);
lastCount = count;
}
for(int i=0;i<NUM_THREAD;i++) {
threads[i].join();
}
assertEquals(0, excs.size());
writer.close();
_TestUtil.checkIndex(dir1);
r.close();
dir1.close();
} |
3c18abf3-3383-42a2-ae94-db03eb0915cf | 6 | public static boolean isPrime(int n) {
if (n <= 3) {
return n >= 2;
} else if (n % 2 == 0 || n % 3 == 0) {
return false;
} else {
for (int i = 5; i < (Math.sqrt(n) + 1); i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
}
return true;
} |
565c9c16-0a54-47fc-aca9-4357c4a9409e | 9 | public Queue<String> kamikazeXMLUnit (){
try {
path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path + "/xml/papabicho.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Units/Unit[@class='Kamikaze']";
NodeList nodeList;
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
} |
7c77d249-51b8-4fea-9b8f-0ef3c9c31b3d | 5 | @Override
public boolean userIsAuthorizedForService(String user, Service service) {
log.info("Checking user {}'s authorization for service {}", user, service);
try {
log.debug("Setting the statement parameters");
int index = params.indexOf("user");
if (index > -1)
statement.setString(index + 1, user);
index = params.indexOf("service-name");
if (index > -1)
statement.setString(index + 1, service.getName());
index = params.indexOf("service-type");
if (index > -1)
statement.setString(index + 1, service.getType());
log.debug("Executing the statement");
ResultSet rs = statement.executeQuery();
if (!rs.next())
return false;
return rs.getInt(1) > 0;
} catch (SQLException e) {
log.catching(Level.ERROR, e);
return false;
}
} |
256b46fe-7ba1-4d90-be39-34d5dfb8c2f8 | 7 | public static void main(String[] args) {
System.out.println("Welcome to CHATBOT");
String question;
boolean askAQuestion = true;
Scanner keyboard = new Scanner(System.in);
Bot bot = new Bot();
do {
System.out
.println("Tell Chatbox something (enter Goodbye to leave): ");
question = keyboard.nextLine();
if (question.equalsIgnoreCase("goodbye")
|| question.equalsIgnoreCase("bye")
|| question.equalsIgnoreCase("good bye")
|| question.equalsIgnoreCase("cya")
|| question.equalsIgnoreCase("see ya")
|| question.equalsIgnoreCase("see you")) {
askAQuestion = false;
} else
System.out.println("Bot says: \"" + bot.ask(question) + "\"");
} while (askAQuestion);
keyboard.close();
System.out.println("Bot says: \"Goodbye!\"");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.