text stringlengths 14 410k | label int32 0 9 |
|---|---|
protected void createFrame()
{
MyInternalFrame frame = new MyInternalFrame();
ScribbleApplet pad = new ScribbleApplet();
frame.add(pad.getContentPane());
frame.setVisible(true);
desktop.add(frame);
try
{
frame.setSelected(true);
}
catch (java.beans.PropertyVetoException e) {}
} | 1 |
public boolean isValidProduction(Production production) {
try {
checkProduction(production);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} | 1 |
@Override
public void doLoopAction() {
if (hit) {
super.ai();
}
if (changeAni) {
setAnimation();
changeAni = false;
}
} | 2 |
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startMissionButton) {
if(Board.getInstance().getTurn().getTurnType()==null){
Board.getInstance().initTurn();
}
TileContainerPanel.setBetable(true);
for (TilePanel panel : TileContainerPanel.getTilePanels()) {
panel.notBetable();
}
Board.getInstance().getTurn().startMission();
}
else if (e.getSource()==challengeButton){
String opp=teamChosen();
Board.getInstance().getTurn().setTempOpp(opp);
Board.getInstance().getTurn().setTurnType();
currentPanel=startButtons;
setPanel();
}
else if (e.getSource()==setScoreButton){
int score=(Integer)scoreCombo.getSelectedItem();
Board.getInstance().getTurn().getTurnType().setScore(score);
if(Board.getInstance().getTurn().isTurnOver()){
Board.getInstance().newTurn();
}
else
currentPanel=startButtons;
setPanel();
}
else if (e.getSource() == doneButton) { //mission shall end
Board.getInstance().stopMission();
}
else if (e.getSource() == yesButton) { //turn shall end
Board.getInstance().getTurn().finishTurn(true);
Board.getInstance().newTurn();
}
else if (e.getSource() == noButton) { //turn shall end
Board.getInstance().getTurn().finishTurn(false);
Board.getInstance().newTurn();
}
} | 9 |
@Override
public boolean Render3D(double _deltaTime) {
//TODO: Tighten the graphics on level 3.
//If the game is visible render your game.
if(application.isVisible()) {
}
return true;
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GPSimulatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GPSimulatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GPSimulatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GPSimulatorGUI.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 GPSimulatorGUI().setVisible(true);
}
});
} | 6 |
@Override
public void run() {
for (int i = 0; i < 4; i++) {
if (linesToBlow[i] != 99) {
for (int j = 0; j < 10; j++) {
tokens[linesToBlow[i]][j].flash();
}
}
}
refresh();
try {
Thread.sleep(120);
} catch (Exception e) {
System.out.println(e);
}
for (int i = 0; i < 4; i++) {
if (linesToBlow[i] != 99) {
for (int j = 0; j < 10; j++) {
tokens[linesToBlow[i]][j].unFlash();
}
}
}
refresh();
for (int i = 0; i < 4; i++) {
if (linesToBlow[i] != 99) {
moveAllDownStartFrom(linesToBlow[i]);
}
}
nextMove(0);
freezing = false;
} | 9 |
@Override
protected void sort(final int[] a) {
index.set(0);
ArrayList<Callable<Void>> list = new ArrayList<Callable<Void>>();
for (final int i : a) {
Callable<Void> thread = new Callable<Void>() {
@Override
public Void call() {
try {
Thread.sleep(i*50);
synchronized (this) {
int where = index.getAndIncrement();
set(i, where);
if (where + 1 == a.length)
sorting = false;
}
} catch (InterruptedException ex) {
Logger.getLogger(TimeSortingMethod.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
list.add(thread);
}
ExecutorService ex = Executors.newFixedThreadPool(a.length);
try {
ex.invokeAll(list);
} catch (InterruptedException ex1) {
Logger.getLogger(TimeSortingMethod.class.getName()).log(Level.SEVERE, null, ex1);
}
while (sorting);
ex.shutdown();
} | 5 |
static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} | 7 |
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
//ignored
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mf = new MainFrame();
mf.setLocationRelativeTo(null);
mf.setVisible(true);
}
});
} | 1 |
private String getClusterTextNote(int index) {
String note = "...";
switch (index) {
case (1):
note = "Advanced: Questions with few answers appearing to be difficult.";
break;
case (2):
note = "FAQ: Frequently Asked Question!";
break;
case (3):
note = "3 Shots: Questions with low score, little debated and no more than 3 answers!";
break;
case (4):
note = "Big 'n Fast: Well voted question with big and quick answers.";
break;
case (5):
note = "High Debated: The question started an interesting debate over the questioner and the answerers.";
break;
case (6):
note = "Uninteresting: Badly voted question without answers on average.";
break;
default:
}
return (note);
} | 6 |
private static void sendServerMessage( Server server, String message ) {
for ( ProxiedPlayer p : server.getInfo().getPlayers() ) {
for ( String line : message.split( "\n" ) ) {
p.sendMessage( line );
}
}
} | 2 |
public void Run()
{
// make sure game started properly
if (Initialize())
{
while(mIsRunning)
{
// handles window events
Display.update(true);
mGameTime.Update();
while (Keyboard.next())
{
GameProperties.GetInputHandler().HandleKeyboardEvent();
gameStates.peek().HandleKeyboardEvent();
}
while (Mouse.next())
{
GameProperties.GetInputHandler().HandleMouseEvent();
gameStates.peek().HandleMouseEvent();
}
// if the top gamestate is alive, update, otherwise remove it
if (gameStates.peek().IsAlive() != false)
{
gameStates.peek().Update(mGameTime);
}
else
{
gameStates.pop();
// if there are no more game-states, end the game, otherwise update the new top
if (!gameStates.empty())
{
gameStates.peek().Update(mGameTime);
}
else
{
mIsRunning = false;
break;
}
}
// clear screen and set modelview matrix
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
ClearScreen();
// draw top gamestate
gameStates.peek().Draw();
if ((Boolean)GameProperties.GetVariable("is_fps_capped").GetData())
{
// delay for constant framerate
Display.sync((Integer)GameProperties.GetVariable("fps_cap").GetData());
}
// handle close message
if (Display.isCloseRequested())
{
mIsRunning = false;
}
// handle adding a new state if current state requests a new state
if (gameStates.peek().IsNextState())
{
gameStates.push(gameStates.peek().TakeNextState());
}
}
}
else
{
System.out.println("Failed To Initialize!");
}
// close display
Display.destroy();
System.exit(0);
} | 9 |
private MenuItem createEditMenu(Menu menuBar) {
//Edit menu.
MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
item.setText(resAddressBook.getString("Edit_menu_title"));
Menu menu = new Menu(shell, SWT.DROP_DOWN);
item.setMenu(menu);
/**
* Add a listener to handle enabling and disabling
* some items in the Edit submenu.
*/
menu.addMenuListener(new MenuAdapter() {
public void menuShown(MenuEvent e) {
Menu menu = (Menu)e.widget;
MenuItem[] items = menu.getItems();
int count = table.getSelectionCount();
items[0].setEnabled(count != 0); // edit
items[1].setEnabled(count != 0); // copy
items[2].setEnabled(copyBuffer != null); // paste
items[3].setEnabled(count != 0); // delete
items[5].setEnabled(table.getItemCount() != 0); // sort
}
});
//Edit -> Edit
MenuItem subItem = new MenuItem(menu, SWT.PUSH);
subItem.setText(resAddressBook.getString("Edit"));
subItem.setAccelerator(SWT.MOD1 + 'E');
subItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TableItem[] items = table.getSelection();
if (items.length == 0) return;
editEntry(items[0]);
}
});
//Edit -> Copy
subItem = new MenuItem(menu, SWT.NONE);
subItem.setText(resAddressBook.getString("Copy"));
subItem.setAccelerator(SWT.MOD1 + 'C');
subItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TableItem[] items = table.getSelection();
if (items.length == 0) return;
copyBuffer = new String[table.getColumnCount()];
for (int i = 0; i < copyBuffer.length; i++) {
copyBuffer[i] = items[0].getText(i);
}
}
});
//Edit -> Paste
subItem = new MenuItem(menu, SWT.NONE);
subItem.setText(resAddressBook.getString("Paste"));
subItem.setAccelerator(SWT.MOD1 + 'V');
subItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (copyBuffer == null) return;
TableItem item = new TableItem(table, SWT.NONE);
item.setText(copyBuffer);
isModified = true;
}
});
//Edit -> Delete
subItem = new MenuItem(menu, SWT.NONE);
subItem.setText(resAddressBook.getString("Delete"));
subItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TableItem[] items = table.getSelection();
if (items.length == 0) return;
items[0].dispose();
isModified = true; }
});
new MenuItem(menu, SWT.SEPARATOR);
//Edit -> Sort(Cascade)
subItem = new MenuItem(menu, SWT.CASCADE);
subItem.setText(resAddressBook.getString("Sort"));
Menu submenu = createSortMenu();
subItem.setMenu(submenu);
return item;
} | 5 |
private static void load(String[] argv)
{
int argCount = argv.length;
for (int cnt = 0; cnt < argCount; cnt++)
{
// current string must start with "-"
if ((argv[cnt] == null) || (!argv[cnt].startsWith(ArgumentPrefix)))
continue;
// strip off leading "-"
String propName = argv[cnt].substring(ArgumentPrefix.length(), argv[cnt].length());
cnt++;
// following string must NOT start with "-"
if ((!(cnt < argCount)) || (argv[cnt] == null)
|| (argv[cnt].startsWith(ArgumentPrefix)))
continue;
String propValue = argv[cnt];
ConfigDb.addVariable(propName, propValue);
}
if (booleanVariable("help"))
{
System.out.println(ProgramDesc);
System.out.println();
System.out.println(ProgramName + " supports the following commandline options:");
System.out.println();
System.out.println(" Name Default Value Description");
System.out.println(" ==== ============= ===========");
System.out.println(optionHelpString());
System.exit(1);
}
} | 7 |
public void createNewGame(Playmode playmode, User[] user) throws IndexOutOfBoundsException{
int i = 0;
for (Team team : playmode.getTeams()) {
while(team.getCurrentPlayerCount() < team.getTeamSize()){
team.addUser(user[i]);
i++;
}
}
Game game = new Game(playmode);
int matchType = Match.TEST;
if(playmode.getTitel().equals("FFA")){
matchType = Match.FFA;
}else if(playmode.getTitel().equals("TEAM")){
matchType = Match.TEAM;
}else if(playmode.getTitel().equals("UNDERDOG")){
matchType = Match.UNDERDOG;
}else if(playmode.getTitel().equals("Test")){
matchType = Match.TEST;
}
// TODO find a way to add new games according to the playmode
game.addMatch(new SoccerMatch(matchType, playmode));
game.addMatch(new HorseRaceMatch(matchType, playmode));
ServerDataBaseManager sDBM = new ServerDataBaseManager();
sDBM.createNewGame(game);
gameIDtoGame.put(game.getGID(), game);
for (int j = 0; j < user.length; j++) {
userIDtoNewGame.put(user[j].getID(), game);
}
} | 7 |
public void setPopFecmod(Date popFecmod) {
this.popFecmod = popFecmod;
} | 0 |
public void readDataBase() {
try {
//Class.forName("com.mysql.jdbc.Driver");
java.sql.Driver d = (java.sql.Driver)Class.forName("solid.jdbc.SolidDriver").newInstance();
String connectSQL = "jdbc:solid://localhost:2315/dba/dba";
connect1 = DriverManager.getConnection(connectSQL);
connect2 = DriverManager.getConnection(connectSQL);
fillDatabase(connect1);
String countSql = "SELECT C_NO FROM users WHERE id = ? LIMIT 1";
countStatement1 = connect1.prepareStatement(countSql);
countStatement2 = connect2.prepareStatement(countSql);
} catch (Exception e) {
e.printStackTrace();
}
WritableWorkbook workbook = null;
WritableSheet[] sheets = new WritableSheet[4];
String[] isolations = new String[1];
isolations[0] = "REPEATABLE READ";
//isolations[1] = "READ COMMITTED";
//isolations[2] = "READ UNCOMMITTED";
//isolations[3] = "SERIALIZABLE";
isolations[0] = "SERIALIZABLE";
try {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyyMMdd_HHmmss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
workbook = Workbook.createWorkbook(new File(strDate+"_"+user_count+".xls"));
for(int i=0; i<isolations.length; i++) {
sheets[i] = workbook.createSheet(isolations[i], 0);
sheets[i].addCell(new Label(0, 0, "Conflicts (%)"));
sheets[i].addCell(new Label(1, 0, "Optimistic locking"));
sheets[i].addCell(new Label(2, 0, "Pessimistic locking"));
}
} catch (IOException | WriteException e) {
e.printStackTrace();
}
int i=1;
try {
for(int isolation=0; isolation<isolations.length; isolation++) {
String sql = "SET TRANSACTION ISOLATION LEVEL "+isolations[isolation];
//connect1.createStatement().executeUpdate(sql);
//connect2.createStatement().executeUpdate(sql);
for(int conflicts=0; conflicts<=100; conflicts+=10){
sheets[isolation].addCell(new Number(0, i, conflicts));
String conflict_list = this.getRandomIDs(conflicts);
System.out.println("Conflicts:" + conflict_list);
long time = 0;
int iters = 1;
for(int iter=1; iter<=iters; iter++){
connect1.setAutoCommit(true);
connect2.setAutoCommit(true);
connect1.createStatement().executeUpdate("ALTER TABLE users SET OPTIMISTIC");
time += this.testLocking(conflict_list);
}
sheets[isolation].addCell(new Number(1, i, time));
time = 0;
for(int iter=1; iter<=iters; iter++){
connect1.setAutoCommit(true);
connect2.setAutoCommit(true);
connect1.createStatement().executeUpdate("ALTER TABLE users SET PESSIMISTIC");
time += this.testLocking(conflict_list);
}
sheets[isolation].addCell(new Number(2, i, time));
i++;
System.out.println("Ready with "+conflicts);
}
}
workbook.write();
workbook.close();
} catch (WriteException | IOException | SQLException e1) {
e1.printStackTrace();
}
} | 8 |
@Override
protected void map(Writable key, VectorWritable value, Context context)
throws IOException, InterruptedException {
omega.computeYRow(value.get(), yRow);
// compute outer product update for YtY
if (yRow.isDense()) {
for (int i = 0; i < kp; i++) {
double yi;
if ((yi = yRow.getQuick(i)) == 0.0) {
continue; // avoid densing up here unnecessarily
}
for (int j = i; j < kp; j++) {
double yj;
if ((yj = yRow.getQuick(j)) != 0.0) {
mYtY.setQuick(i, j, mYtY.getQuick(i, j) + yi * yj);
}
}
}
} else {
/*
* the disadvantage of using sparse vector (aside from the fact that we
* are creating some short-lived references) here is that we obviously
* do two times more iterations then necessary if y row is pretty dense.
*/
for (Iterator<Vector.Element> iterI = yRow.iterateNonZero(); iterI
.hasNext();) {
Vector.Element eli = iterI.next();
int i = eli.index();
for (Iterator<Vector.Element> iterJ = yRow.iterateNonZero(); iterJ
.hasNext();) {
Vector.Element elj = iterJ.next();
int j = elj.index();
if (j < i) {
continue;
}
mYtY.setQuick(i, j, mYtY.getQuick(i, j) + eli.get() * elj.get());
}
}
}
} | 8 |
@Override
public List<Framedata> translateFrame( ByteBuffer buffer ) throws InvalidDataException {
buffer.mark();
List<Framedata> frames = super.translateRegularFrame( buffer );
if( frames == null ) {
buffer.reset();
frames = readyframes;
readingState = true;
if( currentFrame == null )
currentFrame = ByteBuffer.allocate( 2 );
else {
throw new InvalidFrameException();
}
if( buffer.remaining() > currentFrame.remaining() ) {
throw new InvalidFrameException();
} else {
currentFrame.put( buffer );
}
if( !currentFrame.hasRemaining() ) {
if( Arrays.equals( currentFrame.array(), closehandshake ) ) {
frames.add( new CloseFrameBuilder( CloseFrame.NORMAL ) );
return frames;
}
else{
throw new InvalidFrameException();
}
} else {
readyframes = new LinkedList<Framedata>();
return frames;
}
} else {
return frames;
}
} | 5 |
public void processConnectRequest(ServerCnxn cnxn, ByteBuffer incomingBuffer) throws IOException {
BinaryInputArchive bia = BinaryInputArchive.getArchive(new ByteBufferInputStream(incomingBuffer));
ConnectRequest connReq = new ConnectRequest();
connReq.deserialize(bia, "connect");
if (LOG.isDebugEnabled()) {
LOG.debug("Session establishment request from client "
+ cnxn.getRemoteSocketAddress()
+ " client's lastZxid is 0x"
+ Long.toHexString(connReq.getLastZxidSeen()));
}
boolean readOnly = false;
try {
readOnly = bia.readBool("readOnly");
cnxn.isOldClient = false;
} catch (IOException e) {
// this is ok -- just a packet from an old client which
// doesn't contain readOnly field
LOG.warn("Connection request from old client "
+ cnxn.getRemoteSocketAddress()
+ "; will be dropped if server is in r-o mode");
}
if (!readOnly && this instanceof ReadOnlyZooKeeperServer) {
String msg = "Refusing session request for not-read-only client "
+ cnxn.getRemoteSocketAddress();
LOG.info(msg);
throw new CloseRequestException(msg);
}
if (connReq.getLastZxidSeen() > zkDb.dataTree.lastProcessedZxid) {
String msg = "Refusing session request for client "
+ cnxn.getRemoteSocketAddress()
+ " as it has seen zxid 0x"
+ Long.toHexString(connReq.getLastZxidSeen())
+ " our last zxid is 0x"
+ Long.toHexString(getZKDatabase().getDataTreeLastProcessedZxid())
+ " client must try another server";
LOG.info(msg);
throw new CloseRequestException(msg);
}
int sessionTimeout = connReq.getTimeOut();
byte passwd[] = connReq.getPasswd();
int minSessionTimeout = getMinSessionTimeout();
if (sessionTimeout < minSessionTimeout) {
sessionTimeout = minSessionTimeout;
}
int maxSessionTimeout = getMaxSessionTimeout();
if (sessionTimeout > maxSessionTimeout) {
sessionTimeout = maxSessionTimeout;
}
cnxn.setSessionTimeout(sessionTimeout);
// We don't want to receive any packets until we are sure that the
// session is setup
cnxn.disableRecv();
long sessionId = connReq.getSessionId();
if (sessionId == 0) {
LOG.info("Client attempting to establish new session at "
+ cnxn.getRemoteSocketAddress());
createSession(cnxn, passwd, sessionTimeout);
} else {
long clientSessionId = connReq.getSessionId();
LOG.info("Client attempting to renew session 0x"
+ Long.toHexString(clientSessionId)
+ " at " + cnxn.getRemoteSocketAddress());
serverCnxnFactory.closeSession(sessionId);
cnxn.setSessionId(sessionId);
reopenSession(cnxn, sessionId, passwd, sessionTimeout);
}
} | 8 |
public static void main(String[] args) {
EvolvingGlobalProblemSetInitialisation starter = new EvolvingGlobalProblemSetInitialisation();
starter.initLanguage(new char[] { '0', '1' }, 10, "(1(01*0)*1|0)*");
int solutionFoundCounter = 0;
int noSolutionFound = 0;
List<Long> cycleCount = new LinkedList<Long>();
long tmpCycle;
long timeStamp;
int[] problemCount = new int[25];
int[] candidatesCount = new int[1];
int[] noCycles = new int[2];
problemCount[0] = 3;
problemCount[1] = 6;
problemCount[2] = 9;
problemCount[3] = 12;
problemCount[4] = 15;
problemCount[5] = 18;
problemCount[6] = 21;
problemCount[7] = 24;
problemCount[8] = 27;
problemCount[9] = 30;
problemCount[10] = 33;
problemCount[11] = 36;
problemCount[12] = 39;
problemCount[13] = 42;
problemCount[14] = 45;
problemCount[15] = 48;
problemCount[16] = 51;
problemCount[17] = 54;
problemCount[18] = 57;
problemCount[19] = 60;
problemCount[20] = 63;
problemCount[21] = 66;
problemCount[22] = 69;
problemCount[23] = 72;
problemCount[24] = 75;
candidatesCount[0] = 50;
noCycles[0] = 250;
noCycles[1] = 500;
int pc = 0;
int cc = 0;
int nc = 0;
for (int x = 0; x < 1; x++) {
System.out.println("x:" + x);
for (int n = 0; n < 25; n++) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
Logger l = new Logger("E_G_PS_" + df.format(new Date()) + ".log",
true);
pc = problemCount[n];
cc = candidatesCount[0];
nc = noCycles[1];
l.log("Problem Count: " + pc);
l.log("CandidatesCount: " + cc);
l.log("Max Cycles: " + nc);
solutionFoundCounter = 0;
noSolutionFound = 0;
cycleCount = new LinkedList<Long>();
for (int i = 0; i < 100; i++) {
timeStamp = System.currentTimeMillis();
starter.initProblems(pc);
starter.initCandidates(cc);
tmpCycle = starter.startEvolution(nc);
l.log(i + ": finished ("
+ (System.currentTimeMillis() - timeStamp) + "ms, "
+ tmpCycle + "cycles)");
if (starter.getWinner() != null) {
solutionFoundCounter++;
cycleCount.add(tmpCycle);
l.log(i + ": Solution found.");
// GraphvizRenderer.renderGraph(starter.getWinner().getObj(),
// "winner.svg");
} else {
noSolutionFound++;
l.log(i + ": No solution found.");
}
}
long max = 0;
long min = 10000;
long sum = 0;
for (long no : cycleCount) {
sum += no;
max = (no > max ? no : max);
min = (no < min ? no : min);
}
l.log("Solution Found: " + solutionFoundCounter);
l.log("Avg cycles: "
+ (cycleCount.size() > 0 ? sum / cycleCount.size()
: '0'));
l.log("Max cycles: " + max);
l.log("Min cycles: " + min);
l.log("No solution found: " + noSolutionFound);
l.finish();
}
}
} | 8 |
final boolean needsMod() {
return this.elements.contains(this.MOD_DATE)
|| this.elements.contains(this.MOD_DAY)
|| this.elements.contains(this.MOD_MONTH)
|| this.elements.contains(this.MOD_MONTH_STRING)
|| this.elements.contains(this.MOD_YEAR);
} | 4 |
@Override
public synchronized int calculatePlayerScore(PlayerQuizInstance quizInstance, Map<Question, Integer> guesses) throws RemoteException {
int playerQuizInstanceScore = 0;
//if guesses were not submitted, set quiz to not played to avoid blocking admin from closing it
if (guesses.isEmpty() || guesses.size() < quizInstance.getQuiz().getQuizQuestions().size()) {
quizInstance.setQuizPlayed(false);
}
for (Map.Entry<Question, Integer> entry : guesses.entrySet()) {
if (entry.getKey().getCorrectAnswer() == entry.getValue()) {
playerQuizInstanceScore = playerQuizInstanceScore + entry.getKey().getCorrectAnswerPoints();
}
}
for (PlayerQuizInstance current : playerQuizInstances) {
if (current.equals(quizInstance)) {
current.setTotalScore(playerQuizInstanceScore);
current.setQuizPlayed(false);
}
}
return playerQuizInstanceScore;
} | 6 |
public void printAllFiles()
{
System.out.println("Printing out the database");
try {
ResultSet result = printAllFiles.executeQuery();
while (result.next())
{
String fileName = result.getString("FileName");
Timestamp start = result.getTimestamp("StartTime");
Timestamp end = result.getTimestamp("EndTime");
long length= result.getLong("Length");
int row = result.getRow();
System.out.printf("Line %d: FileName=%s, StartTime=%s, EndTime=%s, Length=%s\n", row,fileName,start,end,length);
}
result.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 2 |
private void jTextFieldInterlocuteurCpRechercheKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldInterlocuteurCpRechercheKeyReleased
try {
List<projetrf.model.Ville> vv1 = RequetesVille.rechercheVilleByCp(jTextFieldInterlocuteurCpRecherche.getText().trim());
jComboBoxInterlocuteurVille.removeAllItems();
for (Ville ville : vv1) {
jComboBoxInterlocuteurVille.addItem(ville);
}
} catch (SQLException ex) {
Logger.getLogger(VueInterlocuteur.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jTextFieldInterlocuteurCpRechercheKeyReleased | 2 |
public static double avers(double a){
if(a<0.0D && a>2.0D) throw new IllegalArgumentException("avers argument (" + a + ") must be <= 2 and >= 0");
return Math.acos(1.0D - a);
} | 2 |
@Override
public void bid(String username, int itemId) {
for(Auction auc : search){
if(auc.getId() == itemId){
auc.currentBid++;
auc.owner = username;
}
}
} | 2 |
public void renderFilter()
{
image = loader.getImage();
raster = image.getRaster();
int[] pixels = new int[image.getWidth() * image.getHeight() * Constants.PIXEL_ARRAY_NO_ALPHA];
raster.getPixels(0, 0, image.getWidth(), image.getHeight(), pixels);
for(int i = 0; i < pixels.length; i += 3)
{
r = pixels[i];
g = pixels[i+1];
b = pixels[i+2];
//Make it gray
r = b = g;
//Boost the green only
g += (amount * 4);
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
pixels[i] = r;
pixels[i+1] = g;
pixels[i+2] = b;
}
raster.setPixels(0, 0, image.getWidth(), image.getHeight(), pixels);
MagicImage.frame.panel.repaint();
} | 7 |
@EventHandler
public void WitherSlow(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.Slow.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.Slow.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, plugin.getWitherConfig().getInt("Wither.Slow.Time"), plugin.getWitherConfig().getInt("Wither.Slow.Power")));
}
}
} | 7 |
protected Random getRandom()
{
return rand;
} | 0 |
private static String standardize(String line) {
for (int i = 0; i < line.length(); i += 1) {
if (Character.isWhitespace(line.charAt(i))
|| Character.isLetter(line.charAt(i))) {
continue;
} else {
System.exit(1);
}
}
String stuff = "";
for (int i = 0; i < line.length(); i += 1) {
if (Character.isWhitespace(line.charAt(i))) {
continue;
} else if (Character.isUpperCase(line.charAt(i))) {
stuff += line.charAt(i);
} else if (Character.isLowerCase(line.charAt(i))) {
stuff += Character.toUpperCase(line.charAt(i));
}
}
return stuff;
} | 7 |
protected Action updateAction(Action action, String name, String icon, String accel, Character mnemonic) {
Action result;
// did we already update that action for another component?
if (action == null) {
result = m_Actions.get(name);
return result;
}
result = action;
if ((name != null) && (name.length() > 0))
result.putValue(Action.NAME, name);
if ((icon != null) && (icon.length() > 0))
result.putValue(Action.SMALL_ICON, ComponentHelper.getImageIcon(icon));
if ((accel != null) && (accel.length() > 0))
result.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel));
if (mnemonic != null)
result.putValue(Action.MNEMONIC_KEY, new Integer(mnemonic.charValue()));
return result;
} | 8 |
private void excuteAction(SeleniumNode node) throws Exception {
ElementAction e = node.getField().getAnnotation(ElementAction.class);
if (Exist.NOTSURE.equals(e.isExist())) {
try {
e.type().findElement(super.driver, node.getPath());
} catch (NoSuchElementException e1) {
logger.debug("this element is not exist, path : " + node.getPath());
return;
}
}
switch (e.action()) {
case CLICK:
super.clickAction(node);
return;
case DOUBLECLICK:
super.doubleClickAction(node);
return;
case CONTEXTCLICK:
super.contextClickAction(node);
return;
case SETVALUE:
super.setValueAction(node);
return;
case ENTER:
super.enterAction(node);
return;
case ASSERT:
super.assertAction(node);
return;
default:
throw new IllegalArgumentException("Action枚举类使用异常,请查看");
}
} | 8 |
@Override
protected void cbThinking() {
super.cbThinking();
int round = getRoundNum();
if ( teammate.size() == 0 || round%3 == 2 ) {
setFireMode(ctx.MODE_FIRE_AUTO);
return;
}
if ( ctx.my.time > 100 ) {
if ( round%3 == 1 ) {
broadcastMessage(new BossEvent());
}
for( String mname : teammate ) {
if ( mname.equals(name) ) {
continue;
}
Enemy mate = ctx.nextMateMap.get(mname);
if ( mate == null ) {
continue;
}
if ( mate.name.equals(currentMate ) ) {
return;
}
sendMessage(mate.name,new BossEvent());
return;
}
setFireMode(ctx.MODE_FIRE_AUTO);
}
} | 8 |
public ParsePane(GrammarEnvironment environment, Grammar grammar) {
super(new BorderLayout());
this.grammar = grammar;
this.environment = environment;
} | 0 |
private void checkDesyncAction(final Game serverGame,
final Player serverPlayer) {
Game game = freeColClient.getGame();
boolean problemDetected = false;
Map serverMap = serverGame.getMap();
for (Tile t : serverMap.getAllTiles()) {
if (serverPlayer.canSee(t)) {
Iterator<Unit> unitIterator = t.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
if (u.isVisibleTo(serverPlayer)) {
if (game.getFreeColGameObject(u.getId(), Unit.class) == null) {
System.out.println("Desynchronization detected: Unit missing on client-side");
System.out.println(Messages.message(Messages.getLabel(u))
+ "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
try {
System.out.println("Possible unit on client-side: "
+ game.getMap().getTile(u.getTile().getPosition())
.getFirstUnit().getId());
} catch (NullPointerException npe) {
}
System.out.println();
problemDetected = true;
} else {
Unit clientSideUnit = game.getFreeColGameObject(u.getId(), Unit.class);
if (clientSideUnit.getTile() != null
&& !clientSideUnit.getTile().getId().equals(u.getTile().getId())) {
System.out.println("Unsynchronization detected: Unit located on different tiles");
System.out.println("Server: " + Messages.message(Messages.getLabel(u))
+ "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
System.out.println("Client: "
+ Messages.message(Messages.getLabel(clientSideUnit))
+ "(" + clientSideUnit.getId() + "). Position: "
+ clientSideUnit.getTile().getPosition());
System.out.println();
problemDetected = true;
}
}
}
}
}
}
gui.showInformationMessage((problemDetected)
? "menuBar.debug.compareMaps.problem"
: "menuBar.debug.compareMaps.checkComplete");
} | 9 |
private Token fetchValue () {
SimpleKey key = possibleSimpleKeys.get(flowLevel);
if (null == key) {
if (flowLevel == 0 && !allowSimpleKey) throw new TokenizerException("Found a mapping value where it is not allowed.");
} else {
possibleSimpleKeys.remove(flowLevel);
tokens.add(key.tokenNumber - tokensTaken, Token.KEY);
if (flowLevel == 0 && addIndent(key.column)) tokens.add(key.tokenNumber - tokensTaken, Token.BLOCK_MAPPING_START);
allowSimpleKey = false;
}
forward();
tokens.add(Token.VALUE);
return Token.VALUE;
} | 5 |
public CtrnnPhenotype(List<Integer> attributes, int numHiddenNeurons, int sensors, int motorType){
Iterator<Integer> attributeIt = attributes.iterator();
hiddenLayer = new ArrayList<INeuron>();
motorLayer = new ArrayList<INeuron>();
this.motorType = motorType;
for(int i = 0; i < numHiddenNeurons; i++){
double[] sensorWeights = new double[sensors];
for (int j = 0; j < sensors; j++){
sensorWeights[j] = convertWeight(attributeIt.next());
}
HiddenNeuron hidden = new HiddenNeuron(convertGain(attributeIt.next()),
convertTimeConstant(attributeIt.next()),
convertBias(attributeIt.next()),
convertWeight(attributeIt.next()),sensorWeights);
hiddenLayer.add(hidden);
}
for(int i = 0; i < 2; i++){
MotorNeuron motor = new MotorNeuron(convertGain(attributeIt.next()),
convertTimeConstant(attributeIt.next()),
convertBias(attributeIt.next()),
convertWeight(attributeIt.next()));
motorLayer.add(motor);
}
//===ALL SENSOR WEIGHTS ADDED=== 10 connections from sensory input to hidden layer
//===ALL BIASES ADDED=== 4 connections from bias node to hidden and motor layer
//===ALL LOOPS ADDED=== (as selfweight-parameter in constructor) 4 loops
for(INeuron hiddenNeuron: hiddenLayer){
ArrayList<INeuron> otherHiddens = new ArrayList<INeuron>(hiddenLayer);
otherHiddens.remove(hiddenNeuron);
for(INeuron otherNeuron: otherHiddens){
hiddenNeuron.addArc(otherNeuron, convertWeight(attributeIt.next()));
}
}
for(int i = 0; i < 2; i++){
for (int j = 0; j < numHiddenNeurons; j++){
motorLayer.get(i).addArc(hiddenLayer.get(j), convertWeight(attributeIt.next()));
}
}
motorLayer.get(0).addArc(motorLayer.get(1), convertWeight(attributeIt.next()));
motorLayer.get(1).addArc(motorLayer.get(0), convertWeight(attributeIt.next()));
//===ALL HIDDEN AND MOTOR CONNECTIONS ADDED=== 8 connections
//===TOTAL CONNECTIONS: 10 + 4 + 4 + 8 = 26
//===TOTAL PARAMETERS IN LAYER NODES: 2 * 4 = 8
//===TOTAL ATTRIBUTES: 8 + 26 = 34
} | 7 |
public final BufferedImage paintToImage(final BufferedImage _bi,
final PaintObjectWriting _o, final boolean _final,
final DPoint _p_start, final BufferedImage _g,
final DRect _rVisibleScope) {
//fetch list of points and go to the beginning of the list
List<DPoint> ls_point = _o.getPoints();
model.util.adt.list.Element<DPoint> d = _o.getPoints().getElement();
ls_point.toFirst();
//if list is empty return the bufferedImage which is not changed.
if (ls_point.isEmpty()) {
return _bi;
}
final Rectangle rect;
if (_rVisibleScope == null) {
rect = null;
} else {
rect = _rVisibleScope.getRectangle();
}
//if the painting is not final and id is for mathematics.
int tempId_operation = id_operation;
if (!_final && id_operation == Constants.PEN_ID_MATHS) {
tempId_operation = Constants.PEN_ID_LINES;
}
switch (tempId_operation) {
case Constants.PEN_ID_POINT:
operationPoint(ls_point, _bi, _final, _p_start, _g, rect);
break;
case Constants.PEN_ID_LINES:
operationLine(ls_point, _bi, _final, _p_start, _g, rect);
break;
case Constants.PEN_ID_MATHS:
operationMaths(
ls_point, _bi, _final, _p_start, _g);
break;
case Constants.PEN_ID_MATHS_SILENT:
System.out.println("c1");
operationMaths(
ls_point, _bi, _final, _p_start, _g);
break;
case Constants.PEN_ID_MATHS_SILENT_2:
System.out.println("c2");
operationMaths2(
_o, _bi, _final, _p_start, _g);
break;
default:
break;
}
_o.getPoints().goToElement(d);
return _bi;
} | 9 |
public WorldControl(final WorldGUI view)
{
this.view = view;
view.getGame().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
view.setNumOfPlayers(2);
view.showGame();
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
view.getTournament().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e){
view.chooseAmountOfPlayers();
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
view.getPlayer1().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
JFileChooser p1Chooser = new JFileChooser("");
int returnValue = p1Chooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = p1Chooser.getSelectedFile();
//Add selected file to tournament
String path = selectedFile.getPath();
path = path.replace("\\", "/");
view.addBrain(path);
System.out.println(path);
view.getChoice1().setText(selectedFile.getName());
}
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
view.getPlayer2().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
JFileChooser p2Chooser = new JFileChooser("");
int returnValue = p2Chooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = p2Chooser.getSelectedFile();
//Add selected file to tournament
String path = selectedFile.getPath();
path = path.replace("\\", "/");
view.addBrain(path);
System.out.println(path);
view.getChoice2().setText(selectedFile.getName());
}
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
view.getChoosen().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
view.setNumOfPlayers(Integer.parseInt(view.getNumOfPlayers().getText()));
view.showTournament();
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
for (int i = 0; i < view.getAmountOfPlayers(); i ++)
{
view.getButtonArray().get(i).addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
JButton button = (JButton)e.getSource();
String buttonName = button.getName();
JFileChooser brainChooser = new JFileChooser();
int returnValue = brainChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = brainChooser.getSelectedFile();
//Add selected file to tournament
view.getTextFieldArray().get(Integer.parseInt(buttonName)).setText(selectedFile.getName());
}
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
}
view.getStart().addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e){
System.out.println("Needs to be implemented!");
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
});
} | 4 |
public void onAction(String name, boolean isPressed, float tpf) {
if (name.equals("Izquierda")) {
izq = isPressed;
} else if (name.equals("Derecha")) {
der = isPressed;
} else if (name.equals("Arriba")) {
arriba = isPressed;
} else if (name.equals("Abajo")) {
abajo = isPressed;
} else if (name.equals("Saltar")) {
personajeRigidBody.jump();
}
} | 5 |
private void loadData(byte[] data) throws SQLException, IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
reader = new BufferedReader(inputStreamReader);
try {
// Process the data
parameterData.detectionsAdded = 0;
parameterData.errorCount = 0;
parameterData.rangeCheckErrorCount = 0;
parameterData.cubeName = getCubeName();
parameterData.outputFilename = file.getName();
UUID parameterId = UUID.randomUUID();
if (hasNoData(data)) {
return;
} else if (!hasParameterBlock(data)) {
parameterData.parameterNumber = getParameterNumber();
readData(parameterId);
} else {
readParameters();
if (parameterData.numberDetections > 0) {
readData(parameterId);
}
}
// Get the string for the parameters table
dataWriterCSV.writeParameters(
parameterId.getMostSignificantBits(),
parameterId.getLeastSignificantBits(),
parameterData.cubeName,
parameterData.outputFilename,
parameterData.dateRun,
parameterData.dateLoaded,
parameterData.searchType,
parameterData.blankPixelValue,
parameterData.flagTrim,
parameterData.flagNegative,
parameterData.flagMW,
parameterData.minMW,
parameterData.maxMW,
parameterData.beamArea,
parameterData.beamMaj,
parameterData.beamMin,
parameterData.flagBaseline,
parameterData.flagSmooth,
parameterData.smoothType,
parameterData.hanningWidth,
parameterData.kernMaj,
parameterData.kernMin,
parameterData.kernPA,
parameterData.flagATrous,
parameterData.reconDim,
parameterData.scaleMin,
parameterData.scaleMax,
parameterData.snrRecon,
parameterData.filterCode,
parameterData.filterName,
parameterData.flagRobustStats,
parameterData.statSec,
parameterData.flagFDR,
parameterData.alphaFDR,
parameterData.FDRnumCorChan,
parameterData.threshold,
parameterData.snrCut,
parameterData.minPix,
parameterData.minChannels,
parameterData.minVoxels,
parameterData.flagGrowth,
parameterData.growthThreshold,
parameterData.growthCut,
parameterData.flagAdjacent,
parameterData.threshSpatial,
parameterData.threshVelocity,
parameterData.flagRejectBeforeMerge,
parameterData.flagTwoStageMerging,
parameterData.spectralMethod,
parameterData.pixelCentre,
parameterData.detectionThreshold,
parameterData.noiseLevel,
parameterData.noiseSpread,
parameterData.mean,
parameterData.stdDev,
parameterData.median,
parameterData.madfm,
parameterData.madfmStdDev,
parameterData.numberDetections,
parameterData.parameterNumber,
parameterData.jobName,
parameterData.detectionsAdded,
parameterData.errorCount,
parameterData.rangeCheckErrorCount);
} catch (Exception e) {
e.printStackTrace();
logError(data, e);
} finally {
// Close the reader if it is still open
if (reader != null) {
reader.close();
}
}
} | 5 |
public Sound(String event, URL sound_res){
this.event = event;
try {
AudioInputStream audio_in = AudioSystem.getAudioInputStream(sound_res);
AudioFormat format = audio_in.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
this.audio = (Clip) AudioSystem.getLine(info);
this.audio.open(audio_in);
// Obtain the volume-control:
if (this.audio.isControlSupported(FloatControl.Type.MASTER_GAIN)){
volume_control = (FloatControl) audio.getControl(FloatControl.Type.MASTER_GAIN);
}
if (this.audio.isControlSupported(BooleanControl.Type.MUTE)){
mute_control = (BooleanControl) audio.getControl(BooleanControl.Type.MUTE);
}
} catch (LineUnavailableException e){
System.err.println("Something is blocking the audio line.");
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
} | 4 |
public static MethodSlot helpDefineMethodFromParseTree(Cons inputtree, String stringifiedsource, Object [] MV_returnarray) {
{ Stella_Object nametree = null;
Cons parameterstree = null;
KeywordKeyValueList methodoptions = KeywordKeyValueList.newKeywordKeyValueList();
Cons bodytree = null;
Symbol name = null;
Cons returntypestree = null;
boolean functionP = inputtree.value == Stella.SYM_STELLA_DEFUN;
MethodSlot oldmethod = null;
String signaturestring = ((stringifiedsource == null) ? Cons.stringifyMethodSignature(inputtree) : stringifiedsource);
{ Object [] caller_MV_returnarray = new Object[2];
nametree = Cons.destructureDefmethodTree(inputtree, methodoptions, caller_MV_returnarray);
parameterstree = ((Cons)(caller_MV_returnarray[0]));
bodytree = ((Cons)(caller_MV_returnarray[1]));
}
{ Object [] caller_MV_returnarray = new Object[1];
name = Stella_Object.destructureMethodNameTree(nametree, caller_MV_returnarray);
returntypestree = ((Cons)(caller_MV_returnarray[0]));
}
if (name == null) {
{ MethodSlot _return_temp = null;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(false);
return (_return_temp);
}
}
oldmethod = (functionP ? Symbol.getFunctionWithIdenticalSignature(name, signaturestring) : Symbol.getMethodWithIdenticalSignature(name, parameterstree, signaturestring));
if (oldmethod != null) {
{ MethodSlot _return_temp = oldmethod;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(true);
return (_return_temp);
}
}
KeywordKeyValueList.inPlaceNormalizeMethodOptions(methodoptions, name);
{ MethodSlot method = Symbol.defineStellaMethodSlot(name, returntypestree, functionP, parameterstree, methodoptions);
if (stringifiedsource == null) {
stringifiedsource = (MethodSlot.stringifyMethodBodyP(method) ? Native.stringify(((Cons)(Stella.readSExpressionFromString(signaturestring))).concatenate(bodytree, Stella.NIL)) : signaturestring);
}
method.methodStringifiedSource = stringifiedsource;
Slot.recordSlotHomeModule(method);
{ MethodSlot _return_temp = method;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(false);
return (_return_temp);
}
}
}
} | 6 |
synchronized public void updateMessages() {
while (bornlist.size() > 0)
list.add(bornlist.pop());
while (list.size() > 0 && list.peek().state == DeliverState.delivered) {
list.pop();
messageCount--;
}
} | 3 |
protected void setAge(int age)
{
this.age = age;
} | 0 |
public void run() {
FcpMessage fcpMessage = null;
Throwable throwable = null;
while (true) {
synchronized (this) {
if (shouldStop) {
break;
}
}
try {
String line = readLine();
logger.log(Level.FINEST, "read line: %1$s", line);
if (line == null) {
break;
}
if (line.length() == 0) {
continue;
}
line = line.trim();
//System.err.println("SERVER: " + line); // DCI
if (fcpMessage == null) {
fcpMessage = new FcpMessage(line);
continue;
}
if ("EndMessage".equalsIgnoreCase(line) || "Data".equalsIgnoreCase(line)) {
fcpConnection.handleMessage(fcpMessage);
fcpMessage = null;
}
int equalSign = line.indexOf('=');
if (equalSign == -1) {
/* something's fishy! */
continue;
}
String field = line.substring(0, equalSign);
String value = line.substring(equalSign + 1);
assert fcpMessage != null : "fcp message is null";
fcpMessage.setField(field, value);
} catch (IOException ioe1) {
throwable = ioe1;
break;
}
}
fcpConnection.handleDisconnect(throwable);
} | 9 |
public boolean compPotions(PotionTypeAdv potion, Player play, String sAction, ArrayList<PaymentCache> aPayer) {
HashMap<String, ArrayList<PotionTypeAdv>> hType = _jobsdata.getPotHash();
if(hType.isEmpty())
return false;
for(Map.Entry<String, ArrayList<PotionTypeAdv>> e : hType.entrySet()) {
String tier = e.getKey();
ArrayList<PotionTypeAdv> pots = e.getValue();
if(!tier.startsWith(sAction) || pots.isEmpty())
continue;
if(!pots.contains(potion))
continue;
PaymentCache payment = new PaymentCache(play, _jobsdata.getTierPays().get(sAction + ".pays"), getInteger(tier.substring(tier.length()-1)), _jobsdata.getBasePay(), _jobsdata.getName().toLowerCase());
aPayer.add(payment);
return true;
}
return false;
} | 5 |
@Override
public String buscarDocumentoPorFechaPago(String fechapago1, String fechapago2) {
ArrayList<Venta> geResult= new ArrayList<Venta>();
ArrayList<Venta> dbVentas = tablaVentas();
String result="";
Date xfechapago1;
Date xfechapago2;
Date f;
try{
if (fechapago1.equals("") || fechapago2.equals("")){
result="No puede dejar uno de los campos de fecha en blanco";
return result;
} else {
SimpleDateFormat dformat = new SimpleDateFormat("dd/MM/yyyy");
xfechapago1 = dformat.parse(fechapago1);
xfechapago2 = dformat.parse(fechapago2);
for (int i = 0; i < dbVentas.size() ; i++){
f=dformat.parse(dbVentas.get(i).getFechapago());
if((f.compareTo(xfechapago1))>=0 && (f.compareTo(xfechapago2))<=0){
geResult.add(dbVentas.get(i));
}
}
}
}catch (NullPointerException e) {
result="No hay Ventas entre las fechas proporcionadas";
}catch (ParseException e){
result=e.getMessage();
}
if (geResult.size()>0){
result=imprimir(geResult);
} else {
result="No se ha encontrado ningun registro";
}
return result;
} | 8 |
public void update() {
Window window = device.getFullScreenWindow();
if (window != null) {
BufferStrategy strategy = window.getBufferStrategy();
if (!strategy.contentsLost()) {
strategy.show();
}
}
// Sync the display on some systems.
// (on Linux, this fixes event queue problems)
Toolkit.getDefaultToolkit().sync();
} | 2 |
public CommandHandler(LogOre plugin, String highlight, String normal) {
StringBuilder i = new StringBuilder();
i.append(highlight)
.append(plugin.getDescription().getName())
.append(normal)
.append(" v")
.append(highlight)
.append(plugin.getDescription().getVersion())
.append(normal)
.append(".");
StringBuilder a = new StringBuilder("Made by ");
boolean first = true;
for (String author : plugin.getDescription().getAuthors()) {
if (first) {
a.append(highlight)
.append(author)
.append(normal);
first = false;
} else {
a.append(", ").append(highlight)
.append(author)
.append(normal);
}
}
this.plugin = plugin;
this.info = i.toString();
this.authors = a.append(".").toString();
final CommandHandler chand = this;
plugin.getCommand("orelog").setExecutor(chand);
} | 2 |
public void blinkparticle() {
if (untouchable > 0) {
if (blink > 15 && blink <= 30) {
setImage(invin);
}
else if (blink >= 0 && blink <= 15) {
setImage(empty);
}
}
else if (untouchable == 0) {
getWorld().removeObject(this);
}
} | 6 |
public static int KMPmatch(String source, String target) {
if (source == null || target == null || source.length() < target.length()) {
return -1;
}
if (target.equals("")) {
return 0;
}
int[] next = KMP.CalNext(target);
int i = 0, j = 0;
while (i < source.length()) {
if (source.charAt(i) == target.charAt(j)) {
i++;
j++;
if (j == target.length()) {
return i - j;
}
} else {
if (next[j] == -1) {
i++;
j = 0;
} else {
j = next[j];
}
}
}
return -1;
} | 8 |
public Set<Map.Entry<Byte,Short>> entrySet() {
return new AbstractSet<Map.Entry<Byte,Short>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TByteShortMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TByteShortMapDecorator.this.containsKey(k)
&& TByteShortMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Byte,Short>> iterator() {
return new Iterator<Map.Entry<Byte,Short>>() {
private final TByteShortIterator it = _map.iterator();
public Map.Entry<Byte,Short> next() {
it.advance();
byte ik = it.key();
final Byte key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
short iv = it.value();
final Short v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Byte,Short>() {
private Short val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Byte getKey() {
return key;
}
public Short getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Short setValue( Short value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Byte,Short> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Byte key = ( ( Map.Entry<Byte,Short> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Byte, Short>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TByteShortMapDecorator.this.clear();
}
};
} | 8 |
public static List<FieldRegistration> getFields(Class<?> clazz) throws FieldRegistrationException {
final List<FieldRegistration> fields = new ArrayList<FieldRegistration>();
while (clazz!=null){
for (Field field : clazz.getDeclaredFields()) {
FieldRegistration fieldRegistration = getField(field);
if (fieldRegistration != null) {
for (FieldRegistration f : fields){
if (f.getName().equals(fieldRegistration.getName()))
throw new FieldRegistrationException("Duplicate fields!");
}
fields.add(fieldRegistration);
}
}
clazz = clazz.getSuperclass();
}
return fields;
} | 6 |
public ItemMapping(IClientContext ctx) {
super(ctx);
final WrapperLoader<ItemDefinition> loader = ctx.definitions.system().itemLoader;
// map of items ids to real id
//try (PrintWriter items = new PrintWriter(new File("items.txt"))) {
int id = 0;
while (loader.canLoad(id)) {
final ItemDefinition definition = loader.load(id);
//if (definition.clientScriptData != null) {
//items.println(definition);
//}
if (definition.lent) {
map.put(id, definition.lentId);
} else if (definition.noted) {
map.put(id, definition.noteId);
} else if (definition.cosmetic) {
map.put(id, definition.cosmeticId);
}
// Exclude when id == id
//map.put(definition.noteId, id);
id++;
}
//} catch (FileNotFoundException e) {
// e.printStackTrace();
//}
} | 4 |
/*Delete User*/public boolean deleteUser(String where, String what) {
try{
if(where.length() > 40 || what.length() > 40)return false;
delete.setString(1, where);
delete.setString(2, what);
delete.executeUpdate();
return true;
}catch(Exception e){e.printStackTrace();}
return false;
} | 3 |
public boolean contains(Object src) {
return ((src == this.slider) || (src == this.spinner) || (src == this.radioButton) || (src == this.label));
} | 3 |
public static int search( byte[] text, int offset, byte[] pattern )
{
int[] next = initNext( pattern );
int i = offset, j = 0;
n = 1;
while ( i < text.length )
{
while ( j >= 0 && pattern[j] != text[i] )
{
j = next[j];
}
i++;
j++;
if ( j == pattern.length )
return i - pattern.length;
}
return -1;
} | 4 |
public void leaving(final String name, final Object o) {
// info(StringUtils.shortName(o.getClass()) + "-" + o.hashCode() + " leaving " + name + "()");
} | 0 |
public void crearPedido(int ancho , int largo, int d , int m , int a) {
//tinee que validar que no haya pedidos creados
boolean pedidoExistente = false;
for (int x = 0; x < pedidos.size(); x++) {
Pedido aux = (Pedido) pedidos.get(x);
if (cActual.getClienteId() == aux.getClienteId()) {
pedidoExistente = true;
System.out.println("Ya tienes un pedido existente");
break;
}
}
if (!pedidoExistente) {
pedidos.push(new Pedido(pedidos.getLast().getPedidoId()+1, cActual.getClienteId(), ancho , largo, d , m , a));
}
} | 3 |
static boolean isDigit(char ch) {
switch(ch) {
case '1': case '2': case '3':
case '4': case '5': case '6':
case '7': case '8': case '9':
return true;
}
return false;
} | 9 |
public void removePush() {
if (pushedLocal != null)
exceptionLocal = pushedLocal;
super.removePush();
} | 1 |
@Override
public void execute() {
Player receiver = getReceiver();
StringBuilder builder = new StringBuilder();
if (players != null && !players.isEmpty()) {
HashMap<String, String> values = new HashMap<String, String>(1);
builder.append(TerminalUtil.createHeadline("TimeBan rm")).append("\n");
for (String playerName : players) {
Ban removedBan = plugin.getController().getBans().remove(playerName);
values.put("{user}", playerName);
if (removedBan != null) {
String message = MessagesUtil.formatMessage("rm_result", values);
builder.append(message).append("\n");
} else {
String message = MessagesUtil.formatMessage("rm_no_result", values);
builder.append(message).append("\n");
}
}
String result = builder.toString();
if(receiver == null) {
TerminalUtil.printToConsole(result);
} else {
TerminalUtil.printToPlayer(receiver, result);
}
// stop here in case that rmAll is also true
return;
}
builder = new StringBuilder();
if (rmAll) {
plugin.getController().getBans().clear();
builder.append(TerminalUtil.createHeadline("TimeBan rm")).append("\n");
builder.append(MessagesUtil.formatMessage("rm_result_all", null));
String result = builder.toString();
if(receiver == null) {
TerminalUtil.printToConsole(result);
} else {
TerminalUtil.printToPlayer(receiver, result);
}
}
} | 7 |
public synchronized Serializable jvnInvalidateWriterForReader() throws JvnException {
System.out.println("invalidate writerforreader with state : "+STATE+" sur l'objet "+joi+" "+System.currentTimeMillis());
if(STATE != STATE_ENUM.RWC && STATE != STATE_ENUM.W){
STATE = STATE_ENUM.NL;
}
else{
wait_for_read = true;
if(STATE == STATE_ENUM.W || STATE == STATE_ENUM.RWC){
try {
System.out.println("waiting writerforreader"+" "+System.currentTimeMillis());
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return obj;
} | 5 |
private int sendImage(final String language, final String filePath, StringBuilder sb) throws ClientProtocolException, IOException {
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(SERVICE_URL);
final FileBody image = new FileBody(new File(filePath));
final MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(PARAM_IMAGE, image);
reqEntity.addPart(PARAM_LANGUAGE, new StringBody(language));
reqEntity.addPart(PARAM_APIKEY, new StringBody(getApiKey()));
httppost.setEntity(reqEntity);
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
final InputStream stream = resEntity.getContent();
byte bytes[] = new byte[4096];
int numBytes;
while ((numBytes=stream.read(bytes))!=-1) {
if (numBytes!=0) {
sb.append(new String(bytes, 0, numBytes));
}
}
}
return response.getStatusLine().getStatusCode();
} | 3 |
public void writePolyomino(boolean[][] polyomino) throws IOException{
assert polyomino.length == this.size;
assert polyomino[0].length == this.size;
int numBytes = (polyomino.length * polyomino[0].length + 7)/ 8;
byte[] bytesToAdd = new byte[numBytes];
byte currentByte=0;
for (int x=0; x<polyomino.length; x++){
for (int y=0; y<polyomino[0].length; y++){
int count = (x*polyomino[0].length + y);
if (count%8==0)
currentByte=0;
if (polyomino[x][y])
currentByte |= 1 << (count%8);
if (count%8 == 7)
bytesToAdd[count/8]=currentByte;
}
}
bytesToAdd[bytesToAdd.length-1]=currentByte;
o.write(bytesToAdd);
} | 5 |
public static void main(String[] args) {
// TODO Auto-generated method stub
} | 0 |
public void basicSetParcours(Parcours myParcours) {
if (this.parcours != myParcours) {
if (myParcours != null) {
if (this.parcours != myParcours) {
Parcours oldparcours = this.parcours;
this.parcours = myParcours;
if (oldparcours != null)
oldparcours.unsetWorkout();
}
}
}
} | 4 |
public boolean traiterAppelsExternes(Echeancier e, int date) {
if (this.getPriorite() == '^') {
//On parcourt les étages supérieurs
Etage et = this.getEtage();
while ((et = this.ascenseur.getEtageSuivant(et)) != null) {
//Si des gens attendent sur le palier
if (et.getFileAttente().size() > 0) {
System.out.println("Début ajouter appel externe 1");
e.ajouter(new EvenementPassage(date + vitesse, this.ascenseur.getEtageSuivant(etage)));
System.out.println("Fin ajouter appel externe 1");
return true;
}
}
} else if (this.getPriorite() == 'v') {
//On parcourt les étages inférieurs
Etage et = this.getEtage();
while ((et = this.ascenseur.getEtagePrecedant(et)) != null) {
//Si des gens attendent sur le palier
if (et.getFileAttente().size() > 0) {
System.out.println("Début ajouter appel externe 2");
e.ajouter(new EvenementPassage(date + vitesse, this.ascenseur.getEtagePrecedant(etage)));
System.out.println("Fin ajouter appel externe 2");
return true;
}
}
}
return false;
} | 6 |
private PrivateMessagingListener getPrivateMessagingListener(String nickname) {
for (PrivateMessagingListener listener : privateMessagingListeners) {
if ( listener.getNickname().equalsIgnoreCase(nickname) )
return listener;
}
return null;
} | 2 |
public double side(Box box) {
final Point2DInt corners[] = box.getCorners();
final double s0 = side(corners[0]);
final double s1 = side(corners[1]);
final double s2 = side(corners[2]);
final double s3 = side(corners[3]);
if (s0 > 0 && s1 > 0 && s2 > 0 && s3 > 0) {
return 1;
}
if (s0 < 0 && s1 < 0 && s2 < 0 && s3 < 0) {
return -1;
}
return 0;
} | 8 |
public void tick(int x, int y) {
this.x = x;
this.y = y;
if (timer.isDone()) {
frame++;
timer.start(tpf);
}
if(frame == 5) frame = 0;
} | 2 |
public List<Location> adjacentLocations(Location location)
{
assert location != null : "Null location passed to adjacentLocations";
// The list of locations to be returned.
List<Location> locations = new LinkedList<Location>();
if(location != null) {
int row = location.getRow();
int col = location.getCol();
for(int roffset = -1; roffset <= 1; roffset++) {
int nextRow = row + roffset;
if(nextRow >= 0 && nextRow < depth) {
for(int coffset = -1; coffset <= 1; coffset++) {
int nextCol = col + coffset;
// Exclude invalid locations and the original location.
if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) {
locations.add(new Location(nextRow, nextCol));
}
}
}
}
// Shuffle the list. Several other methods rely on the list
// being in a random order.
Collections.shuffle(locations, rand);
}
return locations;
} | 9 |
public Location getLocation()
{
if (currentLocation == DINER)
{
return diner;
}else
if (currentLocation == POLICE_STATION)
{
return policeStation;
}else
if (currentLocation == MANSION)
{
return mansion;
}else
if (currentLocation == CAR)
{
return car;
}else
if (currentLocation == POKER_ROOM ||
currentLocation == CLUB)
{
return pokerRoom;
}else
if (currentLocation == RACE_TRACKS)
{
return raceTracks;
}else
if (currentLocation == AMUSEMENT_PARK)
{
return amusementPark;
}else
if (currentLocation == CONSTRUCTION_SITE)
{
return constructionSite;
}
return null;
} | 9 |
@Override
public void keyPressed(KeyEvent ke) {
int key = 0;
try {
key = ke.getKeyCode();
}
catch(UnsupportedOperationException e) { }
switch(key) {
case KeyEvent.VK_RIGHT : //Mouvement vers la droite
moves.setDirection(1);
break;
case KeyEvent.VK_LEFT : //Mouvement vers la gauche
moves.setDirection(3);
break;
case KeyEvent.VK_UP : //Mouvement vers le haut
moves.setDirection(4);
break;
case KeyEvent.VK_DOWN : //Mouvement vers le bas
moves.setDirection(2);
break;
case KeyEvent.VK_SPACE : //Déposer une bombe
moves.setDirection(10);
break;
}
} | 6 |
private boolean seuraavanaNegatiiviMiinus() {
return syote.substring(paikka, paikka + 1).equals("-")
&& lauseke.nykyinenLohko().onTyhja();
} | 1 |
private void drawWorld(World world) {
// n.b. Z-ordering is decided by painter's algorithm
// draw the terrain
Stage stage = world.getStage();
for (int i = 0; i < stage.getHeightMap().size(); ++i) {
int height = stage.getHeightMap().get(i);
renderer.drawAtWithHeight(floorSpr, new Vector2(stage.getLeftPosition() + i * Stage.BLOCK_SIZE, 0), height);
}
// draw blood-splats
for (FloorBloodSplat blood : world.getBloodSplats()) {
bloodSplatSpr.setRotation(blood.getRotation());
renderer.drawAtWithAngle(bloodSplatSpr, blood.getPosition().sub(0, Stage.BLOCK_SIZE/4f), blood.getRotation());
}
// draw the signpost
if (world.checkpointIsSignpost()) {
float signpostX = world.getCheckpointX();
float signpostY = world.getFloorHeightAt(signpostX);
renderer.drawCenterBottom(signpostSpr, new Vector2(signpostX, signpostY - foregroundYOffset), false);
}
// draw pickups
for (AmmoPickup ammo : world.getAmmoPickups()) {
renderer.drawCenterBottom(ammoPickupSpr, ammo.getPosition().cpy().sub(0, foregroundYOffset), false);
}
// draw dinosaurs
for (Dino dino : world.getDinos()) {
DinoSprites bodyParts = dinoSprites.get(dino.getKind());
Sprite bodySpr = bodyParts.getBodySprite();
Sprite leftLegSpr = bodyParts.getLeftLegSprite();
Sprite rightLegSpr = bodyParts.getRightLegSprite();
boolean mirrorX = dino.getFacingDirection() == Facing.LEFT;
DinoBodyPartAnimator dinoAnim = new DinoBodyPartAnimator(dino);
renderer.drawAtScreenOffsetWithAngle(rightLegSpr, dino.getPosition(), dinoAnim.getRightLegPosition().cpy().mul(bodyParts.getScale(), bodyParts.getScale()).sub(0, foregroundYOffset), dinoAnim.getRightLegAngle(), mirrorX, false);
renderer.drawAtScreenOffsetWithAngle(leftLegSpr, dino.getPosition(), dinoAnim.getLeftLegPosition().cpy().mul(bodyParts.getScale(), bodyParts.getScale()).sub(0, foregroundYOffset), dinoAnim.getLeftLegAngle(), mirrorX, false);
renderer.drawCenterBottom(bodySpr, dino.getPosition().sub(0, foregroundYOffset), mirrorX);
}
// draw mid-air blood
for (MidAirBlood blood : world.getMidAirBloods()) {
renderer.drawCenteredAt(midAirBloodSpr, blood.getPosition().sub(0, foregroundYOffset));
}
// draw bullets
for (Bullet bullet : world.getBullets()) {
renderer.drawCenteredAt(bulletSpr, bullet.getPosition().sub(0, foregroundYOffset));
}
// draw granny
Granny granny = world.getGranny();
boolean mirrorGrannyX = granny.getFacingDirection() == Facing.LEFT;
GrannyBodyPartAnimator grannyAnim = new GrannyBodyPartAnimator(granny, world.getGunLocation(), world.getShootAtPosition());
if (world.getShootAtPosition() != null) {
renderer.drawCenterBottom(armlessGrannySpr, granny.getPosition().sub(0, foregroundYOffset), mirrorGrannyX);
renderer.drawAtScreenOffsetWithAngle(grannyArmSpr, world.getGunLocation().sub(0, foregroundYOffset), new Vector2(0, 0), grannyAnim.getArmAngle(), false, mirrorGrannyX);
} else {
renderer.drawCenterBottom(grannySpr, granny.getPosition().sub(0, foregroundYOffset), mirrorGrannyX);
}
renderer.drawAtScreenOffsetWithAngle(grannyRightLegSpr, granny.getPosition().sub(0, foregroundYOffset), grannyAnim.getRightLegPosition(), 0, mirrorGrannyX, false);
renderer.drawAtScreenOffsetWithAngle(grannyLeftLegSpr, granny.getPosition().sub(0, foregroundYOffset), grannyAnim.getLeftLegPosition(), 0, mirrorGrannyX, false);
// draw crosshair
renderer.drawCenteredAt(crosshairSpr, world.getAimAtPosition());
} | 8 |
private void removeAll(final boolean mark) {
if (mark) {
AbstractInsnNode insn = first;
while (insn != null) {
AbstractInsnNode next = insn.next;
insn.index = -1; // insn no longer belongs to an InsnList
insn.prev = null;
insn.next = null;
insn = next;
}
}
size = 0;
first = null;
last = null;
cache = null;
} | 2 |
static ArrayList<Field> getFields(Class<?> cls) {
if (cls == null) return new ArrayList<Field>();
ArrayList<Field> output = new ArrayList<Field>();
Field fieldlist[];
try {
fieldlist = cls.getFields();
output.addAll(Arrays.asList(fieldlist));
fieldlist = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++ ) {
Field fld = fieldlist[i];
if (fld == null) continue;
if (!output.contains(fld)) {
output.add(fld);
}
}
} catch (Throwable e) {
}
return output;
} | 6 |
public Document performFetch() throws SQLException {
//Output document
Document fetchData = null;
Dbhandle handle = new Dbhandle();
if (fetchAction == FetchAction.FETCH_USER) {
} else if (fetchAction == FetchAction.FETCH_MEETING) {
} else if (fetchAction == FetchAction.FETCH_EVENT) {
} else if (fetchAction == FetchAction.FETCH_USERS) {
} else if (fetchAction == FetchAction.LOGIN_FETCH) {
//Personal events
List<Event> eventList = handle.fetchUserEvents(ownerUsername);
//Other users events
//Available meeting rooms?
//All the other users in the database
//Meeting ID and meeting leader?
}
return fetchData;
} | 5 |
private void fireServerStartEvent(ServerStartEvent evt) {
Object[] listeners = serverStartListenerList.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==ServerStartListener.class) {
((ServerStartListener)listeners[i+1]).OnServerStartEvent(evt);
}
}
} | 2 |
public static void main(String[] args) throws Exception
{
PrivateField p = new PrivateField();
Class<?> classType = p.getClass();
Field field = classType.getDeclaredField("name");
/**
* Exception in thread "main" java.lang.IllegalAccessException: Class reflection.ModifiedPrivateField can not access a member of class reflection.PrivateField with modifiers "private"
* at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
* at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
* at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
* at java.lang.reflect.Field.set(Unknown Source)
* at reflection.ModifiedPrivateField.main(ModifiedPrivateField.java:16)
*/
//禁止java的访问控制检查
field.setAccessible(true);
field.set(p, "aaaa");
System.out.println(p.getName());
} | 1 |
public SolverState solve(ProblemDefinition problem) {
OccurrenceSelection occurrenceSelection;
AllocationSelection allocationSelection;
try {
occurrenceSelection = (OccurrenceSelection)Class.forName(
properties.getProperty("solver.occurrenceSelectionClassName", "net.personaltt.solver.heuristics.RouletteOccurrenceSelection")
).getConstructor(DataProperties.class).newInstance(properties);
allocationSelection = (AllocationSelection)Class.forName(
properties.getProperty("solver.allocationSelectionClassName", "net.personaltt.solver.heuristics.MainAllocationSelection")
).getConstructor(DataProperties.class).newInstance(properties);
} catch(Exception e) {
System.out.println("Cannot instantiate selections objects");
return null;
}
// init solver state
currentSolution = new MainSolverState();
currentSolution.init(problem.initialSchedule);
System.out.printf("Starting solver. Events %s\n", problem.problemOccurrences.size());
// initial is best found so far
currentSolution.saveBestSolution();
// Start timer
long startTime = System.currentTimeMillis();
long stuckedThreshold = Math.max((long)Math.pow(problem.problemOccurrences.size(), stuckedThresholdCoef), 1000);
// while we have time and is not termination condition met, improve solution
while(currentSolution.iterate() && System.currentTimeMillis() - startTime < timeoutLimit) {
//System.out.printf("\nIteration %s\n Cost\t%s\t%s\n", currentSolution.getItearation(), currentSolution.constraintsCost(), currentSolution.preferenceCost());
//printState();
if (pause) {
System.out.println("Paused");
synchronized(this) {
try {
this.wait();
} catch(Exception e) {
}
}
startTime = System.currentTimeMillis();
}
if ((currentSolution.getItearation() - currentSolution.getLastBestIteration()) > stuckedThreshold) {
System.out.printf(" Detected stuck. Ending solver.\n");
break;
}
// select variable - occurrence
Occurrence toSolve = occurrenceSelection.select(currentSolution);
//System.out.printf(" Selected occurrence %s at %s:%s\n", toSolve, toSolve.getAllocation(), toSolve.getAllocationCost());
// select and save allocation of occurrence
OccurrenceAllocation selectedAllocation = allocationSelection.select(currentSolution, toSolve);
if (selectedAllocation == null ) {
// System.out.printf("No allocation selected, skipping to next iteration");
continue;
}
//System.out.printf(" Selected allocation: %s:%s \n", selectedAllocation, toSolve.getPreferrenceCost(selectedAllocation));
boolean conflicts = currentSolution.setAllocation(toSolve, selectedAllocation);
//System.out.printf(" Conflicting %s\n", conflicts);
// store best solution
if (currentSolution.isBetterThanBest()) {
currentSolution.saveBestSolution();
//System.out.printf(">New best solution found: %s:%s\n", currentSolution.constraintsCost(), currentSolution.preferenceCost());
}
}
/*
System.out.printf("Best solution found: c%s p%s i%s, End: i%s\n",
currentSolution.getBestSolution().constraintsCost(),
currentSolution.getBestSolution().preferenceCost(),
currentSolution.getLastBestIteration(),
currentSolution.getItearation()
);
*/
// return best solution ever found
return currentSolution;
} | 8 |
private Integer readNumErrors(XMLStreamReader xmlsr) throws XMLStreamException {
Integer countNb = null;
// Compteur d'entrées dans un élément
int nbStart = 0;
// Type d'évemenement
int eventType;
// On est déjà dans l'élément, il faut récupérer l'attribut 'count'
int attCount = xmlsr.getAttributeCount();
for (int i = 0 ; i < attCount ; i++) {
if (xmlsr.getAttributeLocalName(i).equals("count"))
countNb = new Integer(xmlsr.getAttributeValue(i));
}
// Maintenant il faut sortir de cet élément
while (xmlsr.hasNext()) {
eventType = xmlsr.next();
if (eventType == XMLEvent.START_ELEMENT) {
nbStart = nbStart + 1;
} else if (eventType == XMLEvent.END_ELEMENT) {
nbStart = nbStart - 1;
if (nbStart < 0)
break;
}
}
return countNb;
} | 6 |
public void clearThawed() {
// Avoid concurrent modification exceptions.
ArrayList list = new ArrayList();
list.addAll(configurationToButtonMap.values());
Iterator it = list.iterator();
while (it.hasNext()) {
ConfigurationButton button = (ConfigurationButton) it.next();
if (button.state != ConfigurationButton.FREEZE)
remove(button.getConfiguration());
}
} | 2 |
public synchronized Iterator<RecordInfo> iterator(int sortIndex, boolean descending)
{
Iterator iter = null;
if (sortIndex < 0)
iter = Arrays.asList(unsortedRecords.toArray()).iterator();
else
{
final List<RecordInfo>[] whichList = descending ? reverseSorted : forwardSorted;
if ((whichList == null) || (sortIndex < 0) || (sortIndex >= whichList.length))
iter = empty.iterator();
else
{
synchronized (whichList)
{
if (whichList[sortIndex] != null)
iter = whichList[sortIndex].iterator();
else
{
final IndexedRowMapComparator comparator = descending ? reverseComparators[sortIndex] : forwardComparators[sortIndex];
final List<RecordInfo> newList = (List<RecordInfo>) unsortedRecords.clone();
Collections.sort(newList, comparator);
whichList[sortIndex] = newList;
iter = newList.iterator();
}
}
}
}
return iter;
} | 7 |
private void jTextFieldSearchLivreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldSearchLivreKeyTyped
// TODO add your handling code here:
if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
String toSearch = jTextFieldSearchLivre.getText();
if (jRadioButtonAllLivre.isSelected()) {
this.searchByMotsClesLivre(toSearch);
} else if (jRadioButtonIdLivre.isSelected()) {
try {
this.searchByIdLivre(toSearch);
} catch (Exception ex) {
Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex);
jLabelNbFoundLivre.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>");
}
} else if (jRadioButtonAutorLivre.isSelected()) {
try {
this.searchByAutorLivre(toSearch);
} catch (Exception ex) {
Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex);
jLabelNbFoundLivre.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>");
}
} else if (jRadioButtonTitleLivre.isSelected()) {
try {
this.searchByTitleLivre(toSearch);
} catch (Exception ex) {
Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex);
jLabelNbFoundLivre.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>");
}
}
}
} | 8 |
public static String parseMsg(String data) {
String[] lines = data.split("\n");
for (String line : lines) {
String[] parts = line.split(":", 2);
if (parts[0].equals("msg")) {
return parts[1];
}
}
return null;
} | 2 |
public void deleteRoom(Scanner sc) {
System.out.println("Delete a room");
System.out.print("Enter Room Number: ");
String deleteRm = sc.nextLine();
shsmb.dummyType();
shsmb.deleteRoom(deleteRm);
System.out.println("Successfully delete a room");
} | 0 |
public static synchronized ViewHelperFactory getInstance() {
if (viewHelperFactory == null) {
viewHelperFactory = new ViewHelperFactory();
}
return viewHelperFactory;
} | 1 |
private void appendParser(final String title) {
try {
GenericParser panel2add = null;
if (title.equals(NeighborhoodParser.NAME)) {
panel2add = new NeighborhoodParser(jTabbedPane1);
} else if (title.equals(ClustersParser.NAME)) {
panel2add = new ClustersParser(jTabbedPane1);
} else if (title.equals(EventParser.NAME)) {
panel2add = new EventParser(jTabbedPane1);
} else if (title.equals(SensorAggregationParser.NAME)) {
panel2add = new SensorAggregationParser(jTabbedPane1);
} else if (title.equals(SendParser.NAME)) {
panel2add = new SendParser(jTabbedPane1);
} else if (title.equals(ClusterOverlapParser.NAME)) {
panel2add = new ClusterOverlapParser(jTabbedPane1);
}
if (panel2add != null) {
jTabbedPane1.addTab(title, panel2add);
jTabbedPane1.updateUI();
}
} catch (Exception e1) {
LOGGER.debug(e1.toString());
}
} | 8 |
public static Department returnDepartment(String deptName)
{
Session session = sf.openSession();
org.hibernate.Transaction tr = session.beginTransaction();
String strSql ="from Department o where o.deptName =:dn";
Query query = session.createQuery(strSql);
query.setParameter("dn", deptName);
List<?> lst = query.list();
Iterator<?> iter = lst.iterator();
if (!iter.hasNext())
{
Department dept = new Department(deptName);
session.save(dept);
tr.commit();
session.close();
return dept;
}
Department dept = (Department)iter.next();
tr.commit();
session.close();
return dept;
} | 3 |
@Override
public void playerGamePlay(RSAService rsaService, ComService comServ,
User gameUser, ArrayList<User> gameUsers, SigService sig,
SearchGamesTask jgt) throws InvalidKeyException,
InvalidKeySpecException, NoSuchAlgorithmException,
NoSuchPaddingException, NoSuchProviderException,
IllegalBlockSizeException, BadPaddingException, IOException,
InterruptedException {
EncryptedHand myHand;
EncryptedCommunityCards encComCards;
PublicKey gameHostsPubKey = gameUsers.get(0).getPublicKey();
// take requests to decrypt a hand
comServ.decryptEncryptedHands(rsaService, gameUsers.size() - 1);
// need to pass in the game hosts public key... the game host
comServ.waitEncryptedDeck(rsaService, gameHostsPubKey);
System.out
.println("Got encrypted deck and encrypted again with my key.");
// wait for cards
myHand = comServ.waitEncryptedHand();
gameUser.setUsersOriginalHand(myHand);
System.out.println("Got my cards!");
//Add additional encryption on top of requests.... used to prevent replay attacks
RSAService overEncryption = new RSAService(rsaService.getP(), rsaService.getQ());
myHand = overEncryption.encryptEncHand(myHand);
// copy and randomly shuffle the user list to distribute requests
@SuppressWarnings("unchecked")
ArrayList<User> tmpGameUsers = (ArrayList<User>) gameUsers.clone();
Collections.shuffle(tmpGameUsers);
for (Iterator<User> usr = tmpGameUsers.iterator(); usr.hasNext();) {
User tmpUser = usr.next();
if (!tmpUser.getID().equals(gameUser.getID())) {
sig.createSignature(myHand);
myHand = comServ.requestDecryptHand(myHand, tmpUser);
}
}
myHand = rsaService.decyrptEncHand(myHand);
Hand hand = overEncryption.decyrptHand(myHand);
gameUser.setUsersHand(hand);
String card1 = Character.toString(hand.data.get(0).cardType) + "-"
+ new String(hand.data.get(0).suit);
String card2 = Character.toString(hand.data.get(1).cardType) + "-"
+ new String(hand.data.get(1).suit);
System.out.println("My Cards: " + card1 + " " + card2);
jgt.waitForInstructionsBuffer.put(card1);
jgt.waitForInstructionsBuffer.put(card2);
// subscribe to next lot of notification
comServ.decryptCommunityCards(rsaService, gameUsers.size() - 1, false);
// notify have hand and wait for community cards
encComCards = comServ.listenForCommunityCards();
// now stop decrypting hands
comServ.stopDecryptingHands();
// start decrypting the community cards
for (Iterator<User> usr = gameUsers.iterator(); usr.hasNext();) {
User tmpUser = usr.next();
if (!tmpUser.getID().equals(gameUser.getID())) {
sig.createSignature(encComCards);
encComCards = comServ.requestDecryptComCards(encComCards,
tmpUser);
} else {
User duplicateUser = new User(gameUser.getUsername(),
gameUser.getID(), gameUser.getPublicKey());
encComCards.addUserToDecryptedTable(duplicateUser);
}
}
CommunityCards comCards = rsaService.decyrptComCards(encComCards);
System.out.println("Community Cards:");
String communityCardsToBeSentToJoiner = "";
for (int i = 0; i < CommunityCards.NUM_CARDS; i++) {
communityCardsToBeSentToJoiner = communityCardsToBeSentToJoiner
.concat(Character.toString(comCards.data.get(i).cardType)
+ "-" + new String(comCards.data.get(i).suit) + " ");
System.out
.println(Character.toString(comCards.data.get(i).cardType)
+ "-" + new String(comCards.data.get(i).suit));
}
// start listening for users hands
comServ.listenUsersHands();
// verify community cards
System.out.println("Verifying community cards!");
comServ.verifyCommunityCards(comCards);
System.out.println("Community cards verified!");
// now stop decrypting community cards
comServ.stopDecryptingComCards();
jgt.waitForInstructionsBuffer.put(communityCardsToBeSentToJoiner);
// now broadcast you hand and wait for other hands
comServ.broadcastMyHand(gameUser);
ArrayList<User> userHands = comServ.blockUntilHaveUsersHands();
System.out.println("\nUsers Cards:");
for (int i = 0; i < userHands.size(); i++) {
User tmpUser = userHands.get(i);
Hand tmpHand = tmpUser.getUsersHand();
if (tmpUser.getID().equals(gameUser.getID())) {
System.out.println("Username: Me");
} else {
System.out.println("Username: " + tmpUser.getUsername().toString());
}
System.out.println("First Card: "
+ Character.toString(tmpHand.data.get(0).cardType) + "-"
+ tmpHand.data.get(0).suit.toString());
System.out.println("Second Card: "
+ Character.toString(tmpHand.data.get(1).cardType) + "-"
+ tmpHand.data.get(1).suit.toString());
}
// now determine the winner and check the winners cards
User winner = determineWinner(comCards, userHands);
if (!rsaService.checkWinnersHand(gameUser, userHands, winner,
rsaService)) {
comServ.callCheat(ComService.HAND_VERIFICATION_FAILED);
}
System.out.println("Winner was: " + new String(winner.getUsername()));
jgt.waitForInstructionsBuffer.put(winner.getUsername());
} | 8 |
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Object msg = e.getMessage();
if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) {
ctx.sendUpstream(e);
return;
}
HttpMessage currentMessage = this.currentMessage;
File localFile = this.file;
if (currentMessage == null) {
HttpMessage m = (HttpMessage) msg;
if (m.isChunked()) {
final String localName = UUID.randomUUID().toString();
List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
encodings.remove(HttpHeaders.Values.CHUNKED);
if (encodings.isEmpty()) {
m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
}
this.currentMessage = m;
this.file = new File(Configuration.getInstance().get("tempDir"), localName);
this.out = new FileOutputStream(file, true);
} else {
ctx.sendUpstream(e);
}
} else {
// TODO: If less that threshold then in memory
// Merge the received chunk into the content of the current message.
final HttpChunk chunk = (HttpChunk) msg;
if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) {
currentMessage.setHeader(HttpHeaders.Names.WARNING, "jws.netty.content.length.exceeded");
} else {
IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out);
if (chunk.isLast()) {
this.out.flush();
this.out.close();
currentMessage.setHeader(
HttpHeaders.Names.CONTENT_LENGTH,
String.valueOf(localFile.length()));
currentMessage.setContent(new FileChannelBuffer(localFile));
this.out = null;
this.currentMessage = null;
this.file = null;
Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress());
}
}
}
} | 8 |
private static void processLoadProject(String dataStr, Object key){
Project curProject = null;
ArrayList<Project> myProjs = new ArrayList<Project>();
String[] data = dataStr.trim().split("\n");
for (String line : data) {
String[] parts = line.split("\t");
parts[parts.length-1] = parts[parts.length-1].trim(); //Trim off any whitespace from the last part split, depending on the loading method and file storage mechanism, this can cause issues.
if (parts[0].equals("PROJECT")) {
if (curProject != null)
myProjs.add(curProject);
if( key instanceof Integer)
curProject = new Project(parts[1], (Integer)key);
else if( key instanceof String)
curProject = new Project(parts[1], (String)key);
} else if (parts[0].equals("FILE")) {
if( key instanceof Integer)
curProject.addFile(new SymitarFile((Integer)key,parts[2].trim(), FileType.valueOf(parts[1])));
else if ( key instanceof String )
curProject.addFile(new SymitarFile((String)key,parts[2].trim(), FileType.valueOf(parts[1])));
}
}
if (curProject != null)
myProjs.add(curProject);
projects.put(key, myProjs);
} | 9 |
public ItemStack transferStackInSlot(int par1)
{
ItemStack var2 = null;
Slot var3 = (Slot)this.inventorySlots.get(par1);
if (var3 != null && var3.getHasStack())
{
ItemStack var4 = var3.getStack();
var2 = var4.copy();
if (par1 < 9)
{
if (!this.mergeItemStack(var4, 9, 45, true))
{
return null;
}
}
else if (!this.mergeItemStack(var4, 0, 9, false))
{
return null;
}
if (var4.stackSize == 0)
{
var3.putStack((ItemStack)null);
}
else
{
var3.onSlotChanged();
}
if (var4.stackSize == var2.stackSize)
{
return null;
}
var3.onPickupFromSlot(var4);
}
return var2;
} | 7 |
public void startArena(String arenaName) {
if (getArena(arenaName) != null) { //If the arena exsists
final Arena arena = getArena(arenaName);
//Create an arena for using in this method
arena.sendMessage(ChatColor.GOLD + "The arena has BEGUN!");
//Set ingame
arena.setInGame(true);
for (String s: arena.getPlayers()) {
//Loop through every player in the arena
if (arena.getBowMen().contains(s)) {
Bukkit.getPlayer(s).teleport(arena.getSpawnLocationOne());
} else if (arena.getSurvivor().contains(s)) {
Bukkit.getPlayer(s).teleport(arena.getSpawnLocationTwo());
}
//Teleports the player to the arena start location
//Do custom stuff here, like give weapons etc,
//but for the purpose of this tutorial, i'll do nothing
// check every Tick if there are still survivors alive
this.myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(this.myPlugin, new Runnable() {
int time = 0;
@Override
public void run() {
time++;
ArrayList<String> remainingSurvivors = arena.getSurvivor();
if (remainingSurvivors.size() == 0 || time == 300) {
endArena(arena.getName());
}
}
}, 20L);
}
}
} | 6 |
static int validateDay( int y, int m, int d )
{
if( d > 28 )
{ // m is 0-based
if( m == 1 ) // TODO: Get maximum for year
{
d = 28;
}
else if( ((m == 3) || (m == 5) || (m == 8) || (m == 10)) && (d == 31) )
{
d = 30;
}
}
return d;
} | 7 |
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.