text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void copyStateTo(RrdUpdater other) throws IOException, RrdException {
if(!(other instanceof Robin)) {
throw new RrdException(
"Cannot copy Robin object to " + other.getClass().getName());
}
Robin robin = (Robin) other;
int rowsDiff = rows - robin.rows;
if(rowsDiff == 0) {
// Identical dimensions. Do copy in BULK to speed things up
robin.pointer.set(pointer.get());
robin.values.writeBytes(values.readBytes());
}
else {
// different sizes
for(int i = 0; i < robin.rows; i++) {
int j = i + rowsDiff;
robin.store(j >= 0? getValue(j): Double.NaN);
}
}
} | 4 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Command cmd;
String action = request.getParameter("action");
switch (action) {
case "saveUser":
cmd = new SalvarUsuarioCommand();
break;
case "loginUser":
cmd = new LoginUsuarioCommand();
break;
case "logoutUser":
cmd = new LogoutUsuarioCommand();
break;
case "searchProduct":
cmd = new BuscarProdutoCommand();
break;
case "loadProduct":
cmd = new CarregarProdutoCommand();
break;
case "buyProduct":
cmd = new ComprarProdutosCommand();
break;
default:
cmd = null;
break;
}
if(cmd!=null)
cmd.execute(request, response);
} | 7 |
public void resolution() {
//temperature
double T = plat.getScore2();
//iterations a chaque pas de temperature
int Nt = 10;
//coef pour le recalcul de la temperature
double coef=0.6;
//generation d'un second plateau (pour comparaison)
Plateau plateau2;
while(plat.getScore2()!=0) {
for( int m=0; m < Nt; m++ ) {
plateau2 = voisin();
int delta = plateau2.getScore2() - plat.getScore2();
if(accepte( delta, T )){
plat = plateau2;
listePolyo=listeTmp;
}
}
//recalcul de la temperature
T = decroissance(T, coef);
}
} | 3 |
@Override
public void onMessage(Message message) {
try {
TextMessage textMsg = (TextMessage) message;
String text = textMsg.getText();
System.out.println(text);
String mode[] = text.split("/");
if(mode.length < 2){
System.out.println("Erro ao tentar interpretar mensagem.");
return;
}
if(mode[0].equals("venda")){
Operacao operation = Operacao.parseFromString(text.substring(6));
showMessage(operation, "venda");
if(operation != null){
if(!operation.isCompra()){
peer.checkOperation(operation);
}
}
return;
}
if(mode[0].equals("compra")){
Operacao operation = Operacao.parseFromString(text.substring(7));
showMessage(operation, "compra");
if(operation != null){
if(operation.isCompra()){
peer.checkOperation(operation);
}
}
return;
}
} catch (JMSException ex) {
ex.printStackTrace();
}
} | 8 |
public String returnBook(int isbn, int customerID) {
try{
String result = formattedTitle("Return Book");
// begin transaction
conn.setAutoCommit(false);
stmt = conn.createStatement();
// check the customer exists and lock
String sql = String.format("SELECT * FROM Customer WHERE CustomerID = %d FOR UPDATE;", customerID);
res = stmt.executeQuery(sql);
if(!res.isBeforeFirst()){
conn.rollback();
return result + String.format("\tCustomer %d does not exist.", customerID) + newLine();
}
res.next();
String custName = String.format("%s %s",res.getString("F_Name").trim(), res.getString("L_Name").trim());
// check book exists and lock
sql = String.format("SELECT * from Book where ISBN = %d FOR UPDATE;", isbn);
res = stmt.executeQuery(sql);
if(!res.isBeforeFirst()){
conn.rollback();
return result + String.format("\tBook %d does not exist.", isbn) + newLine();
}
res.next();
String title = res.getString("Title").trim();
// check that the book is on loan
boolean someOnLoan = res.getInt("numLeft") < res.getInt("NumOfCop");
// check that the customer is currently borrowing it and lock
sql = String.format("SELECT * from Cust_Book WHERE CustomerId = %d FOR UPDATE;", customerID);
res = stmt.executeQuery(sql);
if(!res.isBeforeFirst()){
conn.rollback();
return result + String.format("\tCustomer %d is not currently borrowing that book.", customerID) + newLine();
}
else if(!someOnLoan){
throw new SQLException("The database is in an inconsistent state. Customer " + customerID + " is borrowing the book "+ isbn + ", so there should be some copies out in the Book table.");
}
// delete the entry from Cust_Book
sql = String.format("DELETE FROM Cust_Book WHERE CustomerId = %d;", customerID);
int updated = stmt.executeUpdate(sql);
if(updated != 1){
conn.rollback();
return result + "\tSomething weird happened. The book could not be returned.";
}
// pause
JOptionPane.showMessageDialog(dialogParent, "Paused. Press ok to continue.", "Paused", JOptionPane.OK_OPTION);
// edit the numLeft in Book
sql = String.format("UPDATE Book SET numLeft = numLeft + 1 WHERE ISBN = %d", isbn);
updated = stmt.executeUpdate(sql);
if(updated != 1){
conn.rollback();
return result + "\tSomething weird happened, and the book could not be returned." + newLine();
}
// commit
conn.commit();
return result + String.format("\t(%d) %s successfully returned (%d) %s.", customerID, custName, isbn, title) + newLine();
} catch(SQLException e){
JOptionPane.showMessageDialog(dialogParent, e.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
return "";
} finally{
try {
res.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace(); // this shouldn't happen
}
}
} | 8 |
public int getDegree(int node) {
assert (node < N);
int result = 0;
switch (getState()) {
case ARR_ADJ:
for (int i = 0; i < N; i++) {
if (arr_adj[node][i] != 0)
result++;
}
break;
case ARR_INC:
for (int i = 0; i < M; i++)
if (arr_inc[node][i] < 0)
result++;
break;
case LIST_ADJ:
result = list_adj[node].size();
break;
}
return result;
} | 7 |
public void actionPerformed (ActionEvent event) {
char turn=game.getTurn();
String nextTurn = "Black" ;
if(turn == 'W')
nextTurn = "Black";
if(turn == 'B')
nextTurn = "White";
if (turn==' ')
return;
if (!game.isBlank(num)) {
md.append("\n\nThat square is already occupied!");
return;
}
// makeMove returns true if move is legal, false if move is illegal
if (!game.makeMove(num)) {
md.append("\nCannot place tile there, it would be surrounded\n");
return;
}
game.changeTurn();
// char winner=game.move(num);
// game.move2(num);
// game.changeTurn();
JButton jb = buttons[num];
jb.setFont(new Font("Arial",Font.BOLD,25));
// jb.setText(Character.toString(turn)); // this is how we convert char to String
for(int i=1;i<362;i++){
if(game.charAt(i) == 'W'){ //if element in Array list is W, set background color of JButton to WHITE
buttons[i].setBackground(Color.WHITE);
buttons[i].setForeground(Color.WHITE); // set font color of JButton to Black for visibility
}
else if(game.charAt(i) == 'B'){ //if element in ArrayList is B, set background color of JButton to BLACK
buttons[i].setBackground(Color.BLACK);
buttons[i].setForeground(Color.BLACK); // set font color of JButton to White for visibility
}
else if(game.charAt(i) == ' '){ //if ' ' element in Arraylist, set background color back to tan.
Color tan = new Color(210,180,140);
buttons[i].setBackground(tan);
buttons[i].setForeground(tan);
}
}
//prints current score of game and whos turn it is
md.append("\n\nWhite Score: " + game.getWScore() + "\nBlack Score: " + game.getBScore());
md.append("\n" + nextTurn +"s turn.");
// check for a winner
/* if (winner=='D')
md.append("\nPhooey. It's a draw.\n");
else if (winner!=' ')
md.append("\n"+ winner + " wins!\n");
*/
} | 9 |
public void update()
{
this.Velocity.mult(0.975f);
if((this.Velocity.X() < 0.1f && this.Velocity.X() > 0f) || (this.Velocity.X() > -0.1f && this.Velocity.X() < 0f))
this.Velocity.X(0f);
if((this.Velocity.Y() < 0.1f && this.Velocity.Y() > 0f) || (this.Velocity.Y() > -0.1f && this.Velocity.Y() < 0f))
this.Velocity.Y(0f);
} | 8 |
public static void printUsage(Class<?> resourceClass, String resourceName) {
InputStream is = resourceClass.getResourceAsStream(resourceName);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = reader.readLine()) != null) {
System.err.println(line);
}
} catch (IOException ex) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
}
} | 5 |
public void updateCurrentUser() {
try {
String statement = new String("UPDATE " + DBTable + " SET "
+ "username=?, password=?, url=?, permission=?, isblocked=?, isdead=?, practicenumber=?, highscorenumber=?"
+ " WHERE userid=?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, homepageURL);
stmt.setInt(4, permission);
stmt.setBoolean(5, isBlocked);
stmt.setBoolean(6, isDead);
stmt.setInt(7, practiceNumber);
stmt.setInt(8, highScoreNumber);
stmt.setInt(9, userID);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case(KeyEvent.VK_W) : rocket.player.buttom[0] = false; break;
case(KeyEvent.VK_A) : rocket.player.buttom[1] = false; break;
case(KeyEvent.VK_S) : rocket.player.buttom[2] = false; break;
case(KeyEvent.VK_D) : rocket.player.buttom[3] = false; break;
}
} | 4 |
private void compute() throws EmptyStackException{
LinkedRBinaryTree<?> op=opStack.pop();
LinkedRBinaryTree<?> right=valueStack.pop();
LinkedRBinaryTree<?> left=null;
// Ni cos, ni sin
if(!(op.root().element().equals("sin") || op.root().element().equals("cos"))){
left=valueStack.pop();
op.setLeft(left);
op.setRight(right);
}
else{ // sin ou cos
op.setLeft(right);
}
valueStack.push(op);
} | 5 |
private static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bufferedImage = (BufferedImage) image;
return bufferedImage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pixelGrabber.grabPixels();
} catch (InterruptedException e) {
// fail quietly
}
// Get the image's color model
ColorModel cm = pixelGrabber.getColorModel();
return cm == null || cm.hasAlpha();
} | 3 |
public void exec(ILineConsumer out, ILineConsumer err) throws IOException{
logger.info("Command to execute :" + iCmd);
iSession = iConnection.getSession();
iSession.execCommand(iCmd);
// conditions for processing the streams. Such processing will not exit the call execution.
int conditions = ChannelCondition.EXIT_STATUS|ChannelCondition.STDOUT_DATA|ChannelCondition.STDERR_DATA;
// condition for exiting the call processing
int conditionsExit = ChannelCondition.EXIT_STATUS;
int status;
BufferedReader stdbr = null;
BufferedReader errbr = null;
Timer timer = new Timer();
iStatus = new StatusWrapper();
iStatus.isRunning = true;
// if iTo is specified, then we will create timer task to terminate the call by closing session.
if( iTo != 0 ){
timer.schedule((new TimerTask() {
@Override
public void run() {
if(null!=iSession ){
iSession.close();
iStatus.isRunning = false;
}
}
}), iTo);
}
// start the stream processing
do{
status = iSession.waitForCondition(conditions, iTo*2);
if( (status&ChannelCondition.STDOUT_DATA) != 0 ){
stdbr = reopenBR(stdbr, iSession.getStdout());
readStream(out, stdbr);
}
if( (status&ChannelCondition.STDERR_DATA) != 0 ){
errbr = reopenBR(errbr, iSession.getStderr());
readStream(err, errbr);
}
}
while((((conditionsExit)&status)==0)&&iStatus.isRunning);
// processing has ended, we try to clean up the streams, that are stil open.
try{
stdbr.close();
}catch(Exception ex){
// consume exception
}
try{
errbr.close();
}catch(Exception ex){
// consume exception
}
out.eos();
err.eos();
// at this point we check if the execution has exited due to timeout or normaly.
if( !iStatus.isRunning ){
throw new IOException("Command timed out at "+ iTo);
}
// calling interrupt to close the session
interrupt();
} | 9 |
public SearchLayer(Dimension dim, GridLayer roadsLayer) {
setSize(dim);
this.roads = roadsLayer;
visInfo = VisInfo.getInstance();
initComponents();
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
node = visInfo.findNode(me.getX(), me.getY(), getSize());
if (node != null) {
if (ctx != null) {
if (searchFinished) {
updateLayer(); //clean canvas
searchFinished = false;
} else {
stopSearch();
}
}
final Node n = node;
highlightPoint(n, startPoint);
repaint();
} else {
return;
}
if (from == null || (from != null && to != null)) {
from = node;
to = null;
} else {
to = node;
if (node != null) {
node = null;
runSearch(from, to, alg);
}
}
}
});
} | 7 |
public String getValue(String key)
{
for(int i = 0; i < MAX_PROPS; i++)
{
if(keys_[i].equals(key))
{
return values_[i];
}
}
return "";
} | 2 |
private void btnSwitchProfileMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSwitchProfileMousePressed
if (currentProfile.getUsername().compareTo("andersonmaaron") == 0) {
currentProfile = manager.getProfiles().get("orsobianco");
} else {
currentProfile = manager.getProfiles().get("andersonmaaron");
}
updateProfile();
}//GEN-LAST:event_btnSwitchProfileMousePressed | 1 |
public final void free() {
// reset the linkage between this edge and the edge in the other direction, if it exists
if(oppositeEdge != null) {
if(oppositeEdge.oppositeEdge == this) {
oppositeEdge.oppositeEdge = null;
}
oppositeEdge = null;
}
this.startNode = null;
this.endNode = null;
this.defaultColor = null;
this.sendingColor = null;
this.oppositeEdge = null;
numEdgesOnTheFly --;
freeEdges.add(this);
} | 2 |
public void moveIndexes(int i) {
index = i + 1;
if (nextElement == null) {
return;
} else {
nextElement.moveIndexes(index);
}
} | 1 |
public static List<Persona> consultaLicPer(ObjectContainer em) {
ObjectSet<Persona> listaPer = em.query(new Predicate<Persona>() {
private Map<String, List<LicenciaConductor>> licenciasPorCategoria = new HashMap<>();
private Set<Departamento> deptos = new HashSet<>();
@Override
public boolean match(Persona p) {
licenciasPorCategoria.clear();
for (LicenciaConductor l : p.getLicenciasDeConducir()) {
if (!licenciasPorCategoria.containsKey(l.getCategoria())) {
licenciasPorCategoria.put(l.getCategoria(), new ArrayList<LicenciaConductor>());
}
licenciasPorCategoria.get(l.getCategoria()).add(l);
}
deptos.clear();
for (List<LicenciaConductor> list : licenciasPorCategoria.values()) {
for (LicenciaConductor licenciaConductor : list) {
deptos.add(licenciaConductor.getDepartamento());
}
if (deptos.size() > 1) {
return true;
}
}
return false;
}
});
return Arrays.asList(listaPer.toArray(new Persona[]{}));
} | 5 |
@Override
public void run() {
System.out.println("TCP Thread started.");
// falls Connection fehlschlägt, dann brich ab.
if (!connectionToServerSuceeded()) return;
// ask for name (mutltiple times).
// wird erfolgreich, oder bricht mit storageService.stop() ab.
registerName();
//
while (storageServices.isRunning()) {
try {
println(info()); // send the server an info command
List<String> tokens = readFromServer(); // get response
updateLocalUserList(tokens);
guiServices.refreshUserList();
if(storageServices.isRunning())Thread.sleep(CLIENT_INFO_WAIT_MS); // wait a few seconds
} catch (Exception e) { // if anything goes wrong. safe-kill the app.
e.printStackTrace();
storageServices.stop();
}
}
// if the app is supposed to stop, then close the resources
sendByeToServer();
closeAll();
} | 4 |
public int getY() {
return y;
} | 0 |
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
CommunityDAO dao = CommunityDAO.get();
long id = Long.parseLong(request.getParameter("id"));
PublishedSwarm swarm = CommunityDAO.get().getSwarm(id);
Principal p = request.getUserPrincipal();
CommunityAccount acct = null;
if( p != null ) {
acct = dao.getAccountForName(p.getName());
}
if( dao.hasPermissions(acct, swarm) == false ) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
response.setContentType("application/x-oneswarm");
byte [] b = CommunityDAO.get().getSwarmBytes(id);
if( b == null ) {
logger.warning("Problem during swarm download: null swarm bytes");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
response.setContentLength(b.length);
response.setHeader("Content-Disposition", "attachment; filename=" + swarm.getName() + ".oneswarm");
response.getOutputStream().write(b);
} catch( Exception e ) {
logger.warning("Problem during swarm download: " + e.toString());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
e.printStackTrace();
}
} | 4 |
public static int countMatches(String str, String sub)
{
if (isEmpty(str) || isEmpty(sub))
{
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1)
{
count++;
idx += sub.length();
}
return count;
} | 3 |
public static List<File> getFolderInList(String path) {
List<File> list = null;
File file = new File(path);
if (file.isDirectory()) {
list = new LinkedList<File>();
File[] ary = file.listFiles();
for (int i = 0; i < StringUtil.size(ary); i++)
if (ary[i].isDirectory())
list.add(ary[i]);
}
return list;
} | 3 |
public static void main(String[] args) {
Game.Builder b = new Game.Builder();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Welcome to the game 'The Traveler Problem'");
System.out.println("First, create the players");
createPlayers(b);
System.out.println("Second, set the rolls");
System.out.println("Insert number of rolls");
int opt;
while (true) {
try {
opt = Integer.parseInt(br.readLine());
break;
} catch (Exception e) {
System.out.println("Introduce valid option");
}
}
b.setRolls(new NormalRollFactory(), opt);
System.out.println("Finally, add the observers");
addObservers(b);
Game joc = b.build();
joc.play();
} | 2 |
public int getID() {
System.out.println("test2");
this.waitForTurn = true;
while (!doneTurn) {
try {
Thread.sleep(200);
//System.out.println("waiting");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
doneTurn = false;
return this.clickedId;
} | 2 |
@Override
public boolean execute(CommandSender sender, String[] args) {
if(!(sender instanceof CommandSender)
|| (sender instanceof Player && !sender.isOp())) {
sender.sendMessage("You don't have permission to perform this command");
return true;
}
Collection<Group> groups = groupManager.getAllGroups();
if(groups.size() == 0) {
sender.sendMessage("No data");
return true;
}
for(Group group : groups) {
sender.sendMessage(group.getName());
}
return true;
} | 5 |
public void send() {
String msg = msg_box.getText();
if (msg == null || msg.equals("") || msg.equals("\n")){
msg_box.setText("");
return;
}
if(enterIsSend){
msg = msg.substring(0, msg.length()-1);
}
if (msg.startsWith("@")) {
String to = msg.split(" ")[0].substring(1);
msg = msg.substring(to.length()+2);
update("["+name+"] > ["+to+"] "+msg);
client.sendWhisper(to, msg);
} else {
client.sendBroadcast(msg);
}
msg_box.setText("");
msg_box.grabFocus();
} | 5 |
static void emitStringConstant(String str, PrintStream s) {
ascii = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '\n':
asciiMode(s);
s.print("\\n");
break;
case '\t':
asciiMode(s);
s.print("\\t");
break;
case '\\':
byteMode(s);
s.println("\t.byte\t" + (byte) '\\');
break;
case '"':
asciiMode(s);
s.print("\\\"");
break;
default:
if (c >= 0x20 && c <= 0x7f) {
asciiMode(s);
s.print(c);
} else {
byteMode(s);
s.println("\t.byte\t" + (byte) c);
}
}
}
byteMode(s);
s.println("\t.byte\t0\t");
} | 7 |
private void put(JsonElement value) {
if (pendingName != null) {
if (!value.isJsonNull() || getSerializeNulls()) {
JsonObject object = (JsonObject) peek();
object.add(pendingName, value);
}
pendingName = null;
} else if (stack.isEmpty()) {
product = value;
} else {
JsonElement element = peek();
if (element instanceof JsonArray) {
((JsonArray) element).add(value);
} else {
throw new IllegalStateException();
}
}
} | 5 |
@Override
public Result getRevision () {
List<Integer> parents = getParentsImpl();
if (parents.size() == 0) {
// new repository
return new Result(0, null);
}
final String branch = getBranchImpl();
// get all revisions that are not ancestors of the parent revisions
// i.e. all revisions not yet integrated into current revision
List<String> lines;
if (parents.size() == 1) {
int p0 = parents.get(0);
lines = runHg("log", "-b", branch, "-P", "" + p0, "--template", "{rev},{files}\\n");
} else {
int p0 = parents.get(0);
int p1 = parents.get(1);
lines = runHg("log", "-b", branch, "-P", "" + p0, "-P", "" + p1, "--template", "{rev},{files}\\n");
}
int aborts = countStartsWith(lines, ABORT_PREFIX);
if (aborts > 0) {
return new Result("abort", firstStartsWith(lines, ABORT_PREFIX), true);
}
final Set<Integer> changesets = new TreeSet<>();
final Set<String> files = new TreeSet<>();
for (String line : lines) {
String[] a = line.split(",");
int r = Integer.parseInt(a[0]);
changesets.add(r);
// may not be any files
if (a.length > 1) {
String[] f = a[1].split(" ");
files.addAll(Arrays.asList(f));
}
}
if (changesets.size() > 0) {
String msg = String.format("%d changesets and %d files not up to date", changesets.size(), files.size());
return new Result(-changesets.size(), msg, true);
} else {
return new Result(0, null);
}
} | 6 |
public void set(final long i, final Object value)
{
if (value instanceof Boolean) {
setBoolean(i, (Boolean) value);
} else if (value instanceof Byte) {
setByte(i, (Byte) value);
} else if (value instanceof Short) {
setShort(i, (Short) value);
} else if (value instanceof Integer) {
setInt(i, (Integer) value);
} else if (value instanceof Long) {
setLong(i, (Long) value);
} else if (value instanceof Float) {
setFloat(i, (Float) value);
} else if (value instanceof Double) {
setDouble(i, (Double) value);
} else {
throw new IllegalArgumentException("Unsupported type.");
}
} | 7 |
public static NamedDescription getDescription(Stella_Object self) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_NAMED_DESCRIPTION)) {
{ NamedDescription self000 = ((NamedDescription)(self));
return (self000);
}
}
else if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate self000 = ((Surrogate)(self));
return (Logic.surrogateDgetDescription(self000));
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol self000 = ((Symbol)(self));
return (Logic.getDescription(Symbol.symbolToSurrogate(self000)));
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper self000 = ((StringWrapper)(self));
return (Logic.stringDgetDescription(self000.wrapperValue));
}
}
else if (Surrogate.subtypeOfClassP(testValue000)) {
{ Stella_Class self000 = ((Stella_Class)(self));
return (Logic.classDgetDescription(self000));
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_SLOT)) {
{ Slot self000 = ((Slot)(self));
return (Logic.slotDgetDescription(self000));
}
}
else {
return (null);
}
}
} | 6 |
public static void withMeta(Response resp, JSONObject rootJsonObj) {
try {
resp.version = String.valueOf(rootJsonObj.get(Constants.VERSION));
resp.status = rootJsonObj.getString(Constants.STATUS);
if(rootJsonObj.has(Constants.RESPONSE)) {
JSONObject respJson = rootJsonObj.getJSONObject(Constants.RESPONSE);
if(respJson.has(Constants.TOTAL_ROW_COUNT)) {
resp.totalRowCount = respJson.getInt(Constants.TOTAL_ROW_COUNT);
}
if(respJson.has(Constants.INCLUDED_ROWS)) {
resp.includedRows = respJson.getInt(Constants.INCLUDED_ROWS);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
} | 4 |
public synchronized void holdFinalMeeting(Employee em){
while(lastMeeting.size() < 13 && timer.getTimeOfDay() < 4950){
try {
em.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String meetingTime = timer.getCurrentTime();
System.out.println(meetingTime + " The Manager is giving the final daily meeting with everyone.");
while(timer.getTimeOfDay() < 5100){
try {
em.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
meetingTime = timer.getCurrentTime();
System.out.println(meetingTime + " The final daily meeting is done.");
} | 5 |
private byte[] decrypt(byte[] data) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
if (data.length > MAX_ENC_SIZE) {
System.err
.println("Data to long to decrypt. Reason: Possible cheating! Fix: Exit");
System.exit(1);
}
RSAKeyParameters kp = new RSAKeyParameters(true, n, d);
RSAEngine engine = new RSAEngine();
engine.init(false, kp);
byte[] dText = engine.processBlock(data, 0, data.length);
return dText;
} | 1 |
public static int executer_update(String requete) {
int key = 0;
if (BD_MySQL.debug){
System.out.println("DEBUG : REQUETE : "+requete);
}
try {
BD_MySQL.stmt.executeUpdate(requete, Statement.RETURN_GENERATED_KEYS);
} catch (SQLException ex) {
Logger.getLogger(BD_MySQL.class.getName())
.log(Level.SEVERE, null, ex);
}
ResultSet rs;
try {
rs = BD_MySQL.stmt.getGeneratedKeys();
if(rs.next()){
key = rs.getInt(1);
}
} catch (SQLException ex) {
Logger.getLogger(BD_MySQL.class.getName()).log(Level.SEVERE, null, ex);
}
return key;
} | 4 |
public static int spiralOrderHelper(int[][] matrix, int x, int y,
int[][] matrixHelper, int count) {
// if(x > matrix[0].length/2 || y> matrix.length/2 ){
// return newList;
// }
// top
for (int i = x; i < matrix[0].length - x; i++) {
if (matrixHelper[y][i] == 1)
return count;
matrix[y][i] = count;
count++;
matrixHelper[y][i] = 1;
}
// right
for (int i = y + 1; i < matrix.length - y; i++) {
if (matrixHelper[i][matrix[0].length - x - 1] == 1)
return count;
matrix[i][matrix[0].length - x - 1] = count;
count++;
matrixHelper[i][matrix[0].length - x - 1] = 1;
}
// bot
for (int i = matrix[0].length - x - 1 - 1; i > x - 1; i--) {
if (matrixHelper[matrix.length - y - 1][i] == 1)
return count;
matrix[matrix.length - y - 1][i] = count;
count++;
matrixHelper[matrix.length - y - 1][i] = 1;
}
// left
for (int i = matrix.length - y - 1 - 1; i > y; i--) {
if (matrixHelper[i][x] == 1)
return count;
matrix[i][x] = count;
count++;
matrixHelper[i][x] = 1;
}
return count;
} | 8 |
public void createGUI() {
//initializing the game grid
gameButtonGrid = new JPanel();
gameButtonGrid.setLayout(new GridLayout(mmg.getMaxGuessAmt(),4));
gameButtonGrid.setPreferredSize(new Dimension(320,320));
Integer i = 1;
Integer x = 0;
Integer y = 0;
hintPanel = new JPanel();
hintPanel.setLayout(new GridLayout(mmg.getMaxGuessAmt()*2,2));
hintPanel.setPreferredSize(new Dimension (80,320));
for(int k = 0; k < mmg.getMaxGuessAmt() * 4; k++) {
//int m = mmg.getMaxGuessAmt()*4-k;
int mod = mmg.getMaxGuessAmt() - k/4;
button = new JButton();
button.setName("" + mod);
button.setPreferredSize(new Dimension(10,10)); //was 40, 40
hintPanel.add(button, k);
button.setText(button.getName());
button.setEnabled(false);
button.setToolTipText("Hint for guess " + mod);
}
GridHandler gridButtonHandler = new GridHandler(mmg, this);
HotkeyHandler hotkey = new HotkeyHandler(this);
//adding the buttons to the grid
while (i <= mmg.getMaxGuessAmt() * 4) {
button = new JButton();
//Dummy used to make sure user doesn't double click
button.setText("clear");
button.setForeground(Color.gray);
button.setBackground(Color.gray);
//Give them a label?
String label = "";
label = label.concat(x.toString());
label = label.concat(y.toString());
button.setName(label);
//button.setText(label);
//Set size
button.setPreferredSize(new Dimension(30, 30));
button.addActionListener(gridButtonHandler);
button.addKeyListener(hotkey);
gameButtonGrid.add(button);
i++;
//Lock buttons above the guess row
if (i < (mmg.getMaxGuessAmt() * 4 - 2)) {
button.setEnabled(false);
}
if (x < 3) {
x++;
} else {
x = 0;
y++;
}
}
inputLabel = new JPanel();
//making room for the input label
inputLabel.setLayout(new FlowLayout());
inputLabel.setForeground(Color.white);
//creating label to indicate selected input
JPanel inputLabel = new JPanel();
JLabel title = new JLabel("Selected Input:");
title.setForeground(Color.black);
JLabel input = new JLabel("None");
input.setForeground(Color.black);
this.inputIndicator = input;
//Make timer
//creating label to indicate selected input
JPanel timerPanel = new JPanel();
JLabel timerLabel = new JLabel("Time is: ");
timerLabel.setForeground(Color.black);
inputTimer = new JLabel("0 sec passed");
//Only instantiate timer once
if (timerSet == false) {
setupTimer();
timerSet = true;
} else {
resetTimer();
}
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, BorderLayout.NORTH);
timerPanel.add(inputTimer, BorderLayout.SOUTH);
//Add all the stuff onto the input label
inputLabel.add(title, BorderLayout.NORTH);
inputLabel.add(input, BorderLayout.SOUTH);
inputLabel.add(timerPanel, BorderLayout.EAST);
//Making the input grid
JPanel inputGrid = new JPanel();
inputGrid.setLayout(new GridLayout(3,3));
inputGrid.setPreferredSize(new Dimension(200,200));
inputGrid.setOpaque(false);
InputColourHandler inputHandler = new InputColourHandler(this);
//Set up inputs
button = new JButton();
button.setName("red");
button.setText("RED");
button.setBackground(Color.red);
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
button = new JButton();
button.setName("green");
button.setText("GREEN");
button.setBackground(Color.green);
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
button = new JButton();
button.setName("blue");
button.setBackground(Color.blue);
button.setText("BLUE");
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
button = new JButton();
button.setName("yellow");
button.setText("YELLOW");
button.setBackground(Color.yellow);
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
button = new JButton();
button.setName("white");
button.setText("WHITE");
button.setBackground(Color.white);
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
button = new JButton();
button.setName("pink");
button.setText("PINK");
button.setBackground(Color.pink);
button.setOpaque(true);
button.setPreferredSize(new Dimension(40, 40));
button.addActionListener(inputHandler);
button.addKeyListener(hotkey);
button.setToolTipText("Click on this button then on the grid to change the colour!");
inputGrid.add(button);
//input panel consists of the input grid and the input label
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BorderLayout());
inputPanel.add(inputLabel, BorderLayout.NORTH);
inputPanel.add(inputGrid, BorderLayout.CENTER);
//Move timer here
//making miscellaneous buttons
JPanel miscButtons = new JPanel();
MiscHandler miscButtonHandler = null;
//Check if versing ai
if (ai != null) {
miscButtonHandler = new MiscHandler(mmg, this, ai);
} else {
miscButtonHandler = new MiscHandler(mmg, this, null);
}
miscButtons.setLayout(new GridLayout(5,1));
miscButtons.setPreferredSize(new Dimension(100, 180));
button = new JButton("Check");
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(miscButtonHandler);
button.setToolTipText("Click on this button to check if you are correct!");
button.addKeyListener(hotkey);
miscButtons.add(button);
button = new JButton("Clear");
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(miscButtonHandler);
button.setToolTipText("Click on this button to clear your current guess!");
button.addKeyListener(hotkey);
miscButtons.add(button);
//Check if multiplayer
if (this.getClient() == null) {
button = new JButton("Reset");
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(miscButtonHandler);
button.setToolTipText("Click on this button to reset the whole puzzle!");
button.addKeyListener(hotkey);
miscButtons.add(button);
}
button = new JButton("Exit");
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(miscButtonHandler);
button.setToolTipText("Click on this button to go back to start menu!");
button.addKeyListener(hotkey);
miscButtons.add(button);
//Add instructions button
button = new JButton("Rules");
button.setPreferredSize(new Dimension(100, 50));
button.addActionListener(miscButtonHandler);
button.setToolTipText("Click on this button to look at instructions!");
button.addKeyListener(hotkey);
miscButtons.add(button);
//Duplicate here!!!
//checkBox = new JCheckBox("Allow duplicates");
//miscButtons.add(checkBox);
//miscButtons.setPreferredSize(new Dimension(230, 150));
//creating label to indicate selected input
JPanel player1Panel = new JPanel();
JLabel playerLabel = new JLabel("Player 1");
playerLabel.setForeground(Color.black);
player1Panel.setLayout(new FlowLayout());
player1Panel.add(playerLabel);
//inputTimer = new JLabel("0 sec passed");
//Only instantiate timer once
// //if (timerSet == false) {
// // setupTimer();
// timerSet = true;
// } else {
// resetTimer();
// }
// timerLabel.setForeground(Color.black);
// timerPanel.add(timerLabel, BorderLayout.NORTH);
// timerPanel.add(inputTimer, BorderLayout.SOUTH);
//initializing the final frame
JPanel finalFrame = new JPanel();
gameButtonGrid.setOpaque(false);
inputPanel.setOpaque(false);
miscButtons.setOpaque(false);
inputIndicator.setOpaque(false);
finalFrame.setLayout(new BorderLayout());
//adding panels to the window
finalFrame.add(gameButtonGrid, BorderLayout.CENTER);
finalFrame.add(inputPanel, BorderLayout.SOUTH);
finalFrame.add(hintPanel, BorderLayout.EAST);
finalFrame.add(miscButtons, BorderLayout.WEST);
finalFrame.add(player1Panel, BorderLayout.NORTH);
finalFrame.setSize(700,700);
//Creating label to waste space
//Only created if more than 1 player
if (player == 2) {
JPanel player2Panel = new JPanel();
JLabel name = new JLabel("Player");
name.setForeground(Color.black);
JLabel label = new JLabel("2");
label.setForeground(Color.black);
player2Panel.add(name, BorderLayout.NORTH);
player2Panel.add(label, BorderLayout.SOUTH);
//Create a space waster - no longer a space waster!!
JPanel turnIndicatorPanel = new JPanel();
JLabel turnIndicatorLabel = new JLabel(turnIndicator); //TODO Modify this label to show whos turn it is!!
turnIndicatorPanel.add(turnIndicatorLabel, BorderLayout.CENTER);
turnIndicatorPanel.setPreferredSize(new Dimension(200, 230));
//Create space waster
JPanel temp2 = new JPanel();
JLabel t2 = new JLabel();
temp2.add(t2, BorderLayout.CENTER);
temp2.setLayout(new GridLayout(3, 3));
temp2.setPreferredSize(new Dimension(50, 200));
//initialize player 2 frame
p2Panel = new JPanel();
initialisep2Grid();
p2gameButtonGrid.setOpaque(false);
p2hintPanel.setOpaque(false);
player2Panel.setOpaque(false);
turnIndicatorPanel.setOpaque(false);
temp2.setOpaque(false);
p2Panel.setLayout(new BorderLayout());
//Add to frame
p2Panel.add(p2gameButtonGrid, BorderLayout.CENTER);
p2Panel.add(p2hintPanel, BorderLayout.EAST);
p2Panel.add(player2Panel, BorderLayout.NORTH);
p2Panel.add(turnIndicatorPanel, BorderLayout.SOUTH);
p2Panel.add(temp2, BorderLayout.WEST);
p2Panel.setSize(700,700);
}
//Title for game
JPanel titlePanel = new JPanel();
JLabel titleOfGame = new JLabel();
titleOfGame.setText("Mastermind - The Game of Colours");
titleOfGame.setFont(new Font("TimesRoman", Font.BOLD, 28));
titlePanel.setLayout(new FlowLayout());
titlePanel.add(titleOfGame);
//Final frame
JFrame mastermindFrame = new JFrame("Mastermind");
mastermindFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mastermindFrame.setLayout(new BorderLayout());
if (player == 2) {
mastermindFrame.add(finalFrame, BorderLayout.WEST);
mastermindFrame.add(p2Panel, BorderLayout.CENTER);
} else {
mastermindFrame.add(finalFrame, BorderLayout.CENTER);
}
mastermindFrame.add(titlePanel, BorderLayout.NORTH);
mastermindFrame.pack();
mastermindFrame.setResizable(true);
mastermindFrame.setBackground(Color.orange);
this.gameGrid = mastermindFrame;
//Make the grid for mastermind
this.gameGrid.setVisible(true);
} | 9 |
public void setDynamicAdjustment(boolean isDynamicAdjustment)
{
// May need to add or remove the TableModelListener when changed
if (this.isDynamicAdjustment != isDynamicAdjustment)
{
if (isDynamicAdjustment)
{
table.addPropertyChangeListener( this );
table.getModel().addTableModelListener( this );
}
else
{
table.removePropertyChangeListener( this );
table.getModel().removeTableModelListener( this );
}
}
this.isDynamicAdjustment = isDynamicAdjustment;
} | 2 |
public void recursiveLight(float level, int[] loc, Color color)
{
if(level <= 0)
return;
int x = loc[0];
int y = loc[1];
if(x < 0 || x >= lightLevelGrid.length || y < 0 || y >= lightLevelGrid[x].length)
return;
if(lightLevelGrid[x][y].a > 1 - (Math.min(level, LightSource.maxStrength) / LightSource.maxStrength))
{
lightLevelGrid[x][y] = new Color(color.r, color.g, color.b, 1 - (Math.min(level, LightSource.maxStrength) / LightSource.maxStrength));
}
else return;
int[] loc1 = new int[] {x + 1, y};
int[] loc2 = new int[] {x - 1, y};
int[] loc3 = new int[] {x, y + 1};
int[] loc4 = new int[] {x, y - 1};
recursiveLight(level - LightSource.size, loc1, color);
recursiveLight(level - LightSource.size, loc2, color);
recursiveLight(level - LightSource.size, loc3, color);
recursiveLight(level - LightSource.size, loc4, color);
} | 6 |
public Polynomials(String str){
polynomial = new ArrayList<>();
Scanner scan = new Scanner(str);
for(Term t = Term.scanTerm(scan); t != null; t = Term.scanTerm(scan))
polynomial.add(t);
quickSortPolynomial(0, polynomial.size() - 1);
} | 1 |
public boolean kaufeGebaeude( int auswahl, int gold, Land freiesLand )
{
switch ( auswahl )
{
case 0: // kein Kauf -> zurück zum Gebäude bearbeiten
break;
case 1: // Feld kaufen
if ( gold >= this.preisGebaeude )
{
Feld neuesFeld = new Feld();
this.aktiverSpieler.besetzeLandMitGebaeude( neuesFeld,
freiesLand );
this.aktiverSpieler.saldiereGold( this.preisGebaeude * ( -1 ) ); // Gold
// beim
// Spieler
// abziehen
return true;
}
break;
case 2: // Muehle kaufen
if ( gold >= this.preisGebaeude )
{
Muehle neueMuehle = new Muehle();
this.aktiverSpieler.besetzeLandMitGebaeude( neueMuehle,
freiesLand );
this.aktiverSpieler.saldiereGold( this.preisGebaeude * ( -1 ) );
return true;
}
break;
case 3: // Kornkammer kaufen
if ( gold >= this.preisGebaeude )
{
Kornkammer neueKornkammer = new Kornkammer();
this.aktiverSpieler.besetzeLandMitGebaeude( neueKornkammer,
freiesLand );
this.aktiverSpieler.saldiereGold( this.preisGebaeude * ( -1 ) );
return true;
}
break;
default:
break;
}
return false;
} | 7 |
private boolean validAddress(String s) {
if (s != null && (s.length() > 26 && s.length() < 35) && (s.startsWith("1") || s.startsWith("3")) && !s.contains("0") && !s.contains("O") && !s.contains("I") && !s.contains("l")) return true;
else return false;
} | 9 |
public String text()
{
if(subObjects.size() == 1)
if(subObjects.get(0) instanceof String)
return (String)(subObjects.get(0));
return null;
} | 2 |
private boolean fireAttemptClientConnectEvent(AttemptClientConnectEvent evt) {
ISocketServerConnection ssc = evt.getSocketServerConnection();
logger.debug(getName() +
" attempt client: " + ssc.getRemoteAddress() +
" <idconnection=" + ssc.getIdConnection() + ">");
if (attemptClientConnect != null) {
return attemptClientConnect.OnAttemptClientConnectEvent(evt);
}
else {
return true;
}
} | 1 |
private String GetMessageToSend(){
String Message;
while(true){
if(!catalogue.MessageInUse){
Message = catalogue.GetClientMessage(Tabid);
break;
}
}
return Message;
} | 2 |
public void setIdElemento(int idElemento) {
this.idElemento = idElemento;
} | 0 |
public List<Utr5prime> get5primeUtrs() {
ArrayList<Utr5prime> list = new ArrayList<Utr5prime>();
for (Utr utr : utrs)
if (utr instanceof Utr5prime) list.add((Utr5prime) utr);
return list;
} | 2 |
public void soldatenVersorgen( int sold )
{
int benötigtesMehl = this.soldaten * 2;
int benötigtesGold = this.soldaten * sold;
int satteSoldaten = Integer.valueOf( Math.round( this.mehl / 2 ) );
int hungrigeSoldaten = this.soldaten - satteSoldaten;
int bezahlteSoldaten = Integer.valueOf( Math.round( this.gold / sold ) );
int unbezahlteSoldaten = this.soldaten - bezahlteSoldaten;
if ( ( benötigtesMehl > this.mehl ) || ( benötigtesGold > this.gold ) )
{
if ( hungrigeSoldaten > unbezahlteSoldaten )
{
this.soldaten = this.soldaten - hungrigeSoldaten;
this.mehl = 0;
this.gold = this.gold - benötigtesGold;
}
else if ( hungrigeSoldaten <= unbezahlteSoldaten )
{
this.soldaten = this.soldaten - unbezahlteSoldaten;
this.mehl = this.mehl - benötigtesMehl;
this.gold = 0;
}
}
else if ( ( benötigtesMehl <= this.mehl )
&& ( benötigtesGold <= this.gold ) )
{
this.mehl = this.mehl - benötigtesMehl;
this.gold = this.gold - benötigtesGold;
}
} | 6 |
public static Vertex at(Graph g, int x, int y) {
DynamicArray<Vertex> vertices = g.getVertices();
Vertex v = vertices.get(0);
Vertex closestVertex = v;
double closest = Integer.MAX_VALUE;
for (int i = 0; i < vertices.getSize(); i++) {
v = vertices.get(i);
double thisX = v.getX();
double thisY = v.getY();
if (Math.sqrt(Math.pow(Math.abs(thisX - x), 2) + Math.pow(Math.abs(thisY - y), 2)) < closest) {
closest = Math.sqrt(Math.pow(Math.abs(thisX - x), 2) + Math.pow(Math.abs(thisY - y), 2));
closestVertex = v;
}
}
if (closest < thresholdValue) {
return closestVertex;
} else {
return null;
}
} | 3 |
public static void setMap(){
jPanel1 = new JPanel(new GridLayout(19,48,0,0));
JLabel labels[] = new JLabel[(19*48)];
String bufferMap = carte.lire("./ressources/map.txt");
for (int i = 0,j = 0; i < bufferMap.length(); i++)
{
if(bufferMap.charAt(i) == '*' )
{
ImageIcon grassIcon = new ImageIcon("./images/mur.png");
labels[j] = new JLabel(grassIcon );
jPanel1.add(labels[j]);
j++;
}
if(bufferMap.charAt(i) == ' ' || bufferMap.charAt(i) == 'P' )
{
ImageIcon grassIcon = new ImageIcon("./images/sol.png");
labels[j] = new JLabel(grassIcon );
jPanel1.add(labels[j]);
j++;
}
if(bufferMap.charAt(i) == 'A' )
{
ImageIcon grassIcon = new ImageIcon("./images/arrive.png");
labels[j] = new JLabel(grassIcon );
jPanel1.add(labels[j]);
j++;
}
if(bufferMap.charAt(i) == 'G' )
{
ImageIcon grassIcon = new ImageIcon("./images/herbe.png");
labels[j] = new JLabel(grassIcon );
jPanel1.add(labels[j]);
j++;
}
if(bufferMap.charAt(i) == 'D' )
{
ImageIcon grassIcon = new ImageIcon("./images/porte.png");
labels[j] = new JLabel(grassIcon );
jPanel1.add(labels[j]);
j++;
}
}
} | 7 |
@Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
if(getValueAt(0, column)==null)
return String.class;
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
} | 3 |
public void deposit(BigInteger amount) throws IllegalArgumentException {
if ( (amount == null) || (amount.compareTo(BigInteger.ZERO) <= 0) )
throw new IllegalArgumentException();
setBalance(this.getBalance().add(amount));
} | 2 |
@Override
public void handlePeerChoked(SharingPeer peer) { /* Do nothing */ } | 0 |
@Override
public void caseAParaComando(AParaComando node)
{
inAParaComando(node);
{
List<PComando> copy = new ArrayList<PComando>(node.getComando());
Collections.reverse(copy);
for(PComando e : copy)
{
e.apply(this);
}
}
if(node.getAAte() != null)
{
node.getAAte().apply(this);
}
if(node.getADe() != null)
{
node.getADe().apply(this);
}
if(node.getVar() != null)
{
node.getVar().apply(this);
}
outAParaComando(node);
} | 4 |
void resetColorsAndFonts () {
Color oldColor = foregroundColor;
foregroundColor = null;
setExampleWidgetForeground ();
if (oldColor != null) oldColor.dispose();
oldColor = backgroundColor;
backgroundColor = null;
setExampleWidgetBackground ();
if (oldColor != null) oldColor.dispose();
Font oldFont = font;
font = null;
setExampleWidgetFont ();
setExampleWidgetSize ();
if (oldFont != null) oldFont.dispose();
} | 3 |
public static void main(java.lang.String args[]) throws NullPointerException, IOException {
/**
* Starting Up Server
*/
System.setOut(new Logger(System.out));
System.setErr(new Logger(System.err));
System.out.println("Running Warlords of Hell...");
/**
* Accepting Connections
*/
acceptor = new SocketAcceptor();
connectionHandler = new ConnectionHandler();
SocketAcceptorConfig sac = new SocketAcceptorConfig();
sac.getSessionConfig().setTcpNoDelay(false);
sac.setReuseAddress(true);
sac.setBacklog(100);
throttleFilter = new ConnectionThrottleFilter(Config.CONNECTION_DELAY);
sac.getFilterChain().addFirst("throttleFilter", throttleFilter);
acceptor.bind(new InetSocketAddress(serverlistenerPort), connectionHandler, sac);
/**
* Initialise Handlers
*/
EventManager.initialize();
Connection.initialize();
ObjectDef.loadConfig();
Region.load();
pJClans.initialize();
/**
* Server Successfully Loaded
*/
System.out.println("Accepting connections on port " + serverlistenerPort);
/**
* Main Server Tick
*/
try {
while (!Server.shutdownServer) {
if (sleepTime >= 0)
Thread.sleep(sleepTime);
else
Thread.sleep(600);
engineTimer.reset();
CycleEventHandler.getSingleton().process();
itemHandler.process();
playerHandler.process();
npcHandler.process();
pJClans.process();
shopHandler.process();
objectManager.process();
cycleTime = engineTimer.elapsed();
sleepTime = cycleRate - cycleTime;
totalCycleTime += cycleTime;
cycles++;
debug();
if (System.currentTimeMillis() - lastMassSave > 200000) {
for(Player p : PlayerHandler.players) {
if(p == null)
continue;
PlayerSave.saveGame((Client)p);
System.out.println("Saved game for " + p.playerName + ".");
lastMassSave = System.currentTimeMillis();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("A fatal exception has been thrown!");
for(Player p : PlayerHandler.players) {
if(p == null)
continue;
PlayerSave.saveGame((Client)p);
System.out.println("Saved game for " + p.playerName + ".");
}
}
acceptor = null;
connectionHandler = null;
sac = null;
System.exit(0);
} | 8 |
double getProfit(double predict, double result, double eps1, double eps2) {
if (Math.abs(predict - total) >= eps1) {
predict = -1;
} else if (Math.abs(predict - total) <= eps2) {
predict = 1;
} else {
return 0;
}
if (result == total) {
return 0;
}
if (result > total && predict > 0) {
return over - 1;
} else if (predict < 0 && result < total) {
return under - 1 ;
}
return -1;
} | 7 |
public List get(String alias) {
List result = new LinkedList();
for (Iterator it = entries.iterator(); it.hasNext(); ) {
Entry e = (Entry) it.next();
if (e instanceof EnvelopeEntry) {
if (!((EnvelopeEntry) e).containsAlias(alias)) {
continue;
}
if (e instanceof MaskableEnvelopeEntry) {
if (((MaskableEnvelopeEntry) e).isMasked()) {
result.add(e);
continue;
}
}
result.addAll(((EnvelopeEntry) e).get(alias));
} else if (e instanceof PrimitiveEntry) {
if (((PrimitiveEntry) e).getAlias().equals(alias)) {
result.add(e);
}
}
}
return result;
} | 7 |
public static void dumpXML(XMLStreamReader parser) throws XMLStreamException {
int depth = 0;
do {
switch(parser.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
for(int i = 1; i < depth; ++i) {
System.out.print(" ");
}
System.out.print("<");
System.out.print(parser.getLocalName());
for(int i = 0; i < parser.getAttributeCount(); ++i) {
System.out.print(" ");
System.out.print(parser.getAttributeLocalName(i));
System.out.print("=\"");
System.out.print(parser.getAttributeValue(i));
System.out.print("\"");
}
System.out.println(">");
++depth;
break;
case XMLStreamConstants.END_ELEMENT:
--depth;
for(int i = 1; i < depth; ++i) {
System.out.print(" ");
}
System.out.print("</");
System.out.print(parser.getLocalName());
System.out.println(">");
break;
case XMLStreamConstants.CHARACTERS:
for(int i = 1; i < depth; ++i) {
System.out.print(" ");
}
System.out.println(parser.getText());
break;
}
if(depth > 0) parser.next();
} while(depth > 0);
} | 9 |
@Override
public void run() {
if (state == GameState.WAITING_FOR_PLAYERS) {
if (getPlayers(PlayerState.WAITING).size() >= battleground.getMinPlayers()) {
//TODO: broadcast message
state = GameState.COUNTDOWN;
currentCounter = new Counter(30);//TODO: fix magic value
}
} else if (state == GameState.COUNTDOWN) {
if (currentCounter.isZero()) {
state = GameState.INGAME;
startGame();
} else {
currentCounter.countDown();
}
} else if (state == GameState.INGAME) {
} else if (state == GameState.POSTGAME) {
}
} | 6 |
public void addCatchPhi(final Block block) {
if (phis[cfg.preOrderIndex(block)] != null) {
return;
}
if (prototype instanceof LocalExpr) {
final LocalExpr target = (LocalExpr) prototype.clone();
final PhiCatchStmt phi = new PhiCatchStmt(target);
phis[cfg.preOrderIndex(block)] = phi;
if (SSA.DEBUG) {
System.out.println(" place " + phi + " in " + block);
}
}
} | 3 |
private void processRingNumberingAndIrregularities() throws StructureBuildingException {
for (Element group : groupsInFusedRing) {
Fragment ring = group.getFrag();
if (ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){
aromatiseCyclicAlkane(group);
}
processPartiallyUnsaturatedHWSystems(group, ring);
if (group == lastGroup) {
//perform a quick check that every atom in this group is infact cyclic. Fusion components are enumerated and hence all guaranteed to be purely cyclic
List<Atom> atomList = ring.getAtomList();
for (Atom atom : atomList) {
if (!atom.getAtomIsInACycle()) {
throw new StructureBuildingException("Inappropriate group used in fusion nomenclature. Only groups composed entirely of atoms in cycles may be used. i.e. not: " + group.getValue());
}
}
if (group.getAttribute(FUSEDRINGNUMBERING_ATR) != null) {
String[] standardNumbering = MATCH_SLASH.split(group.getAttributeValue(FUSEDRINGNUMBERING_ATR), -1);
for (int j = 0; j < standardNumbering.length; j++) {
atomList.get(j).replaceLocants(standardNumbering[j]);
}
} else {
ring.sortAtomListByLocant();//for those where the order the locants are in is sensible }
}
for (Atom atom : atomList) {
atom.clearLocants();//the parentRing does not have locants, letters are used to indicate the edges
}
} else if (group.getAttribute(FUSEDRINGNUMBERING_ATR) == null) {
ring.sortAtomListByLocant();//for those where the order the locants are in is sensible
}
}
} | 9 |
public void dehoist() {
// Shorthand
JoeTree tree = hoistedNode.getTree();
tree.setRootNodeCommentState(oldTreeCommentState);
hoistedNode.setHoisted(false);
// Prune things
tree.setRootNode(oldNodeSet);
tree.getVisibleNodes().clear();
hoistedNodeParent.insertChild(hoistedNode, hoistedNodeIndex);
hoistedNode.setDepthRecursively(hoistedNodeDepth);
for (int i = 0; i < oldNodeSet.numOfChildren(); i++) {
Node node = oldNodeSet.getChild(i);
tree.insertNode(node);
}
return;
} | 1 |
public boolean pass(int[] bowl, int bowlId, int round,
boolean canPick,
boolean musTake) {
double expected;
double offset;
// Calculate Bowl Size
bowlSize = 0;
for(int i=0; i<bowl.length; i++)
bowlSize += bowl[i];
// Total Fruits
n_fruits = n_players*bowlSize;
// Update fruit history as bowls come by
fruitHistory = history(bowl, bowlId, round);
//choosing between distribution and threshhold/offset based on bowlSize
if(bowlSize < 30){
//calculate distribution
bowls_seen[round]++;
estimateDistribution(bowl, bowlId, round, bowlSize);
}else{
//calculate distribution
estimateDistribution_orig();
}
//get expected score
expected = expectedValue(bowl, bowlId, round);
offset = linearOffset(round, expected);
if (musTake)
return true;
if (canPick && score(bowl, bowlId, round) >= expected + offset)
return true;
else
return false;
} | 5 |
static private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
if (tok != null) jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind) return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
return false;
} | 9 |
@Override
public Object execute(Object obj, Object[] args) {
// 获取实际的PreparedSQL和调用参数
String actualSql = definition.getActualSql(args);
List<Object[]> paramArrays = ReflectionUtils.generateBatchQueryArguments(args, definition);
KeyHolder keyHolder = null;
if (definition.isReturnId()) {
keyHolder = dataAccessor.getKeyHolder();
}
LOGGER.info("批量更新操作执行SQL[" + actualSql + "]");
int[] rows = dataAccessor.batchUpdate(actualSql, paramArrays, keyHolder);
if (keyHolder != null) {
List<Number> keys = getKeysFromKeyHolder(keyHolder);
return formatKeys(keys, definition);
} else {
return rows;
}
} | 2 |
public boolean mirarPal() {
int flush = 0;
for (int i=0; i < ma.size()-1; i++) {
if (ma.get(i).getPal().equals(ma.get(i+1).getPal())) {
flush++;
} else {
}
}
if (flush == 4) {
return true;
} else {
return false;
}
} | 3 |
public void write(JsonWriter out, Map<K, V> map) throws IOException {
if (map == null) {
out.nullValue();
return;
}
if (!complexMapKeySerialization) {
out.beginObject();
for (Map.Entry<K, V> entry : map.entrySet()) {
out.name(String.valueOf(entry.getKey()));
valueTypeAdapter.write(out, entry.getValue());
}
out.endObject();
return;
}
boolean hasComplexKeys = false;
List<JsonElement> keys = new ArrayList<JsonElement>(map.size());
List<V> values = new ArrayList<V>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
keys.add(keyElement);
values.add(entry.getValue());
hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject();
}
if (hasComplexKeys) {
out.beginArray();
for (int i = 0; i < keys.size(); i++) {
out.beginArray(); // entry array
Streams.write(keys.get(i), out);
valueTypeAdapter.write(out, values.get(i));
out.endArray();
}
out.endArray();
} else {
out.beginObject();
for (int i = 0; i < keys.size(); i++) {
JsonElement keyElement = keys.get(i);
out.name(keyToString(keyElement));
valueTypeAdapter.write(out, values.get(i));
}
out.endObject();
}
} | 8 |
public static Growth getGrowth(int i) {
switch (i) {
case 1:
return Slow;
case 2:
return Medium;
case 3:
return Fast;
case 4:
return Medium_slow;
case 5:
return Erratic;
case 6:
return Fluctuating;
}
return null;
} | 6 |
private static ServerJoinInfo getDetailsFromDirectUrl(final String url) {
if (url == null) {
throw new NullPointerException("url");
}
ServerJoinInfo result = new ServerJoinInfo();
final Matcher directUrlMatch = directUrlRegex.matcher(url);
if (directUrlMatch.matches()) {
try {
result.address = InetAddress.getByName(directUrlMatch.group(1));
} catch (final UnknownHostException ex) {
return null;
}
final String portNum = directUrlMatch.group(6);
if (portNum != null && portNum.length() > 0) {
try {
result.port = Integer.parseInt(portNum);
} catch (final NumberFormatException ex) {
return null;
}
} else {
result.port = 25565;
}
result.playerName = directUrlMatch.group(7);
final String mppass = directUrlMatch.group(9);
if (mppass != null && mppass.length() > 0) {
result.pass = mppass;
} else {
result.pass = BLANK_MPPASS;
}
return result;
}
return null;
} | 8 |
@Override
public void run() {
if (!stats)
return;
try {
ResultSet r = sql.query("SELECT * FROM ctt_stats");
HashMap<String, PlayerStats> p = new HashMap<String, PlayerStats>();
while (r.next()) {
p.put(r.getString("player"), new PlayerStats(r.getString("player"), r.getInt("wins"), r.getInt("losses"), r.getInt("kills"), r.getInt("deaths")));
}
for (Entry<String, PlayerStats> en : plugin.getPlayerStats().entrySet()) {
PlayerStats s = en.getValue();
if (p.get(s.getName()) != null) {
if (s.equals(p.get(s.getName()))) {
CTT.debug(en.getKey() + "'s stats haven't changed");
continue;
}
}
try {
ResultSet rs = sql.query("SELECT * FROM ctt_stats WHERE player='" + s.getName() + "'");
if (rs.next()) {
sql.query("UPDATE ctt_stats SET wins=" + s.getWins() + ", losses=" + s.getLosses() + ", kills=" + s.getKills() + ", deaths=" + s.getDeaths() + " WHERE player='" + s.getName() + "'");
} else {
sql.query("INSERT INTO ctt_stats (player, wins, losses, kills, deaths) VALUES ('" + s.getName() + "', " + s.getWins() + ", " + s.getLosses() + ", " + s.getKills() + ", " + s.getDeaths() + ")");
}
} catch (SQLException e) {
e.printStackTrace();
CTT.send("Failed to update stats for " + s.getName());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
updateTops();
} | 8 |
public RouterPacket GetRecentPacket()
{
return recentPacket;
} | 0 |
public static void showSearchResultsTable(ResultSet rs, String searchQuery,
List<String> inputs) {
int numCols;
ResultSetMetaData rsmd;
JTextArea tableTitle = null;
JTable table = null;
try {
rsmd = rs.getMetaData();
numCols = rsmd.getColumnCount() + 2;
String columnNames[] = new String[numCols];
for (int i = 0; i < numCols - 2; i++) {
columnNames[i] = rsmd.getColumnName(i + 1);
}
columnNames[numCols - 2] = "IN";
columnNames[numCols - 1] = "OUT";
// For creating the size of the table
PreparedStatement ps1 = Library.con.prepareStatement(searchQuery);
for (int i = 0; i < inputs.size(); i++) {
ps1.setString(i + 1, inputs.get(i));
}
ps1.executeQuery();
ResultSet count = ps1.getResultSet();
List<String> books = new ArrayList<String>();
while (count.next()) {
books.add(count.getString("callNumber"));
}
Object data[][] = new Object[books.size()][numCols];
count.close();
String callNumber;
String isbn;
String title;
String mainAuthor;
String publisher;
int copiesAvailable = 0;
int copiesOut = 0;
int year;
int j = 0;
// Fill table
while (rs.next()) {
callNumber = rs.getString("callNumber");
isbn = rs.getString("isbn");
title = rs.getString("title");
mainAuthor = rs.getString("mainAuthor");
publisher = rs.getString("publisher");
year = rs.getInt("year");
// Check the number of available copies for a book
PreparedStatement ps2 = Library.con
.prepareStatement("SELECT count(*) from BookCopy WHERE callNumber = ? and status LIKE 'in'");
ps2.setString(1, callNumber);
ps2.executeQuery();
ResultSet rs2 = ps2.getResultSet();
if (rs2.next()) {
copiesAvailable = rs2.getInt(1);
}
PreparedStatement ps3 = Library.con
.prepareStatement("SELECT count(*) from BookCopy WHERE callNumber = ? and status LIKE 'out'");
ps3.setString(1, callNumber);
ps3.executeQuery();
ResultSet rs3 = ps3.getResultSet();
if (rs3.next()) {
copiesOut = rs3.getInt(1);
}
Object tuple[] = { callNumber, title, mainAuthor, publisher,
year, isbn, copiesAvailable, copiesOut };
data[j] = tuple;
j++;
}
rs.close();
tableTitle = new JTextArea("Search Results");
table = new JTable(data, columnNames);
if (data.length == 0) {
new ErrorMessage("No books found.");
}
table.setEnabled(false);
JScrollPane scrollPane = new JScrollPane(table);
table.setAutoCreateRowSorter(true);
// Display table
table.setFillsViewportHeight(false);
tablePane.removeAll();
tablePane.updateUI();
tableTitle.setEditable(false);
tablePane.add(tableTitle);
tablePane.add(scrollPane);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 8 |
protected boolean objectShouldBeDrawn(DrawnObject d)
{
// If the drawnobject is collidingdrawnobject, checks the drawing more
// carefully
if (d instanceof CollidingDrawnObject)
{
CollidingDrawnObject cd = (CollidingDrawnObject) d;
DoublePoint[] collisionpoints = cd.getCollisionPoints();
// Does NOT check if the object is solid or not! (used for drawing
// so the visible-status is used instead)
// Invisible objects are never drawn
if (!cd.isVisible())
return false;
// Returns true if any of the collisionpoints collides
for (int i = 0; i < collisionpoints.length; i++)
{
if (pointCollides((int) collisionpoints[i].getX(),
(int) collisionpoints[i].getY()) != null)
return true;
}
return false;
}
// Dimensionalobjects are drawn if they are near the camera
// Draws a bit more objects than necessary
else if (d instanceof DimensionalDrawnObject)
{
DimensionalDrawnObject dd = (DimensionalDrawnObject) d;
// Checks if it's possible that any point of the object would be shown
double maxrange = dd.getMaxRangeFromOrigin() + getMaxRangeFromOrigin();
return HelpMath.pointDistance(-getX(), -getY(), dd.getX(), dd.getY())
< maxrange;
}
// Other objects are always drawn
return true;
} | 5 |
public static void main(String[] args) throws EnrycherException, MalformedURLException {
// input document
String docString = "Tiger Woods emerged from a traffic jam of his " +
"own making to thrill thousands of fans with a six-under 66 at " +
"the $1.4 million Australian Masters on Thursday.";
// URL of Enrycher web service
URL pipelineUrl = new URL("http://enrycher.ijs.si/run");
// convert input document to input stream
InputStream docStream = new ByteArrayInputStream(docString.getBytes());
// call Enrycher web service
Document doc = EnrycherWebExecuter.processSync(pipelineUrl, docStream);
// iterate over all the annotations
for (Annotation ann : doc.getAnnotations()) {
// list all persons
if (ann.isPerson()) {
System.out.println("Person: " + ann.getDisplayName());
// get sentences in which it occurs
for (Instance inst : ann.getInstances()) {
int sentenceId = inst.getSentenceId(0);
Paragraph paragraph = doc.getParagraph(sentenceId);
Sentence sentence = paragraph.getSentence(sentenceId);
System.out.println(inst.getDisplayName() + ": '" + sentence.getPlainText() + "'");
}
// list all attributes
for (Attribute attr : ann.getAttributes()) {
if (attr.isLiteral()) {
System.out.println(" - " + attr.getType() + " : " + attr.getLiteral());
} else if (attr.isResource()){
System.out.println(" - " + attr.getType() + " : " + attr.getResource());
}
}
}
}
} | 6 |
public List<BranchLeader> getBranchLeaderList() {
return branchLeaderList;
} | 0 |
public int assignPlayer(String name)
{
for(int i = 1; i <=4 ; i++)
{
if(players.get(i).isEmpty())
{
players.add(i, new Player(new Bat(new Point2D.Float(50, 400), new Point2D.Double(5,100), 2,new Point2D.Float(0, -4)), 0, name));
return i;
}
}
return 0;
} | 2 |
public void run() {
while (!isInterrupted()) {
String input = new String();
char ch;
try {
do {
ch = (char) s.getInputStream().read();
input = input + ch;
} while (ch != '\n' && !isInterrupted());
} catch (IOException e) {
e.printStackTrace();
}
if (!isInterrupted())
System.out.print(input);
}
} | 5 |
public double frobeniusNorm(){
double norm=0.0D;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
norm=hypot(norm, Math.abs(matrix[i][j]));
}
}
return norm;
} | 2 |
public boolean isBorder() {
boolean borderWidth = false;
Object border = getObject(BORDER_KEY);
if (border != null && border instanceof Vector) {
Vector borderProps = (Vector) border;
if (borderProps.size() == 3) {
borderWidth = ((Number) borderProps.get(2)).floatValue() > 0;
}
}
return getBorderStyle() != null || borderWidth;
} | 4 |
public Vehicule requestVehicule() {
if (!vehicules.isEmpty()) {
Vehicule v = vehicules.get(0);
vehicules.remove(0);
return v;
} else return null;
} | 1 |
public void printSum(File dir) throws IOException {
PrintWriter w;
if (file != null) {
w = new PrintWriter(new FileWriter(new File(dir, file), true));
} else {
w = new PrintWriter(new OutputStreamWriter(System.out));
}
w.println(out.toString());
w.flush();
if (file != null) {
w.close();
}
} | 2 |
private StdImage getDisclosureControl(Row row) {
return row.isOpen() ? row == mRollRow ? mDownTriangleRoll : mDownTriangle : row == mRollRow ? mRightTriangleRoll : mRightTriangle;
} | 3 |
public void run()
{
try
{
init();
}
catch (Exception Stacktrace)
{
Stacktrace.printStackTrace();
}
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double nanoSeconds = 1000000000 / amountOfTicks;
double Delta = 0;
long Timer = System.currentTimeMillis();
while(isRunning == true)
{
long currentTime = System.nanoTime();
Delta += (currentTime - lastTime) / nanoSeconds;
lastTime = currentTime;
if(Delta >= 1)
{
try
{
tick();
}
catch (Exception Stacktrace)
{
Stacktrace.printStackTrace();
}
Delta--;
Ticks++;
}
render();
Frames++;
if(System.currentTimeMillis() - Timer > 1000)
{
Timer += 1000;
absoluteFrames = Frames;
absoluteTicks = Ticks;
Ticks = 0;
Frames = 0;
}
}
stop();
} | 5 |
public void fillObject(Credit credit, ResultSet result) {
//Заполняем кредит
try {
credit.setId(result.getInt("ID"));
credit.setDate(result.getDate("CREDITDATE"));
credit.setSum(result.getDouble("CREDITSUM"));
credit.setStatus(result.getInt("CREDITSTATUS"));
credit.setClientId(result.getInt("CLIENTSID"));
credit.setCreditProgramId(result.getInt("CREDITPROGRAMID"));
} catch (SQLException exc) {
JOptionPane.showMessageDialog(null, "Ошибка при извлечении обьекта из базы");
}
} | 1 |
public static int min(int[] element)
throws IllegalArgumentException{
if (element.length == 0){
throw new IllegalArgumentException ("tom samling");
}
int[] sekvens = element;
int antaletPar = sekvens.length / 2;
int antaletOparadeElement = sekvens.length % 2;
int antaletTankbaraElement = antaletPar + antaletOparadeElement;
int[] delsekvens = new int[antaletTankbaraElement];
int i = 0;
int j = 0;
System.out.println(Arrays.toString(sekvens));
while (sekvens.length > 1)
{
// skilj ur en delsekvens med de tänkbara elementen
j = 0;
i = 0;
while (j < antaletPar)
{
delsekvens[j++] = (sekvens[i] < sekvens[i + 1]) ? sekvens[i] : sekvens[i + 1];
i += 2;
}
if (antaletOparadeElement == 1)
delsekvens[j] = sekvens[sekvens.length - 1];
// utgå nu ifrån delsekvensen
sekvens = delsekvens;
antaletPar = antaletTankbaraElement / 2;
antaletOparadeElement = antaletTankbaraElement % 2;
antaletTankbaraElement = antaletPar + antaletOparadeElement;
delsekvens = new int[antaletTankbaraElement];
System.out.println(Arrays.toString(sekvens));
}
// sekvens[0] är det enda återstående tänkbara elementet
// - det är det minsta elementet
return sekvens[0];
} | 5 |
public ClassAnalyzer getClassAnalyzer(ClassInfo cinfo) {
if (cinfo == getClazz())
return this;
if (parent == null)
return null;
return getParent().getClassAnalyzer(cinfo);
} | 2 |
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(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Loading.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 Loading().setVisible(true);
}
});
} | 6 |
public TimeSlotHelper(long startOfDay, int nDay)
{
this.startOfDay = startOfDay;
this.nDay = nDay;
this.nSlot = nDaySlot * nDay;
this.aIsAvailable = new boolean[this.nSlot];
Arrays.fill(this.aIsAvailable, true);
} | 0 |
public void gravity(Collection<GameObject> objects){
for(GameObject gameObject : objects){
if(gameObject.getEffectedByGravity()){
applyForce(gameObject, 0, 1);
}
}
} | 2 |
public static ArrayList<PokerHandEvaluation> getWinners(ArrayList<PokerHandEvaluation> potentialWinners) {
//we have a tie and we need the rank of the first player (the rank is the same for all players TIE)
PokerHandEvaluation firstPlayerEvaluation = potentialWinners.get(0);
int rank = firstPlayerEvaluation.getRank();
ArrayList<PokerHandEvaluation> winners = new ArrayList<PokerHandEvaluation>();
for(int i = 0; i < potentialWinners.size() -1; i++) {
PokerHandEvaluation firstPotentialWinner = potentialWinners.get(i);
PokerHandEvaluation secondPotentialWinner = potentialWinners.get(i + 1);
ArrayList<PokerCard> firstPotentialWinnerBestHand = firstPotentialWinner.getBestHand();
ArrayList<PokerCard> secondPotentialWinnerBestHand = secondPotentialWinner.getBestHand();
PokerHandComparer handComparer = PokerHandTieEvaluator.resolveTieHand(firstPotentialWinnerBestHand, secondPotentialWinnerBestHand, rank);
if (handComparer == PokerHandComparer.FirstHandIsBetter && !winners.contains(firstPotentialWinner)) {
winners = new ArrayList<PokerHandEvaluation>();
winners.add(firstPotentialWinner);
}
else if (handComparer == PokerHandComparer.SecondHandIsBetter && !winners.contains(secondPotentialWinner)) {
winners = new ArrayList<PokerHandEvaluation>();
winners.add(secondPotentialWinner);
}
else if (handComparer == PokerHandComparer.BothAreEqual) {
if (!winners.contains(firstPotentialWinner)) {
winners.add(firstPotentialWinner);
}
if (!winners.contains(secondPotentialWinner)) {
winners.add(secondPotentialWinner);
}
}
}
return winners;
} | 8 |
public void setorderBy(int column)
{
/* if the users clicks on the same column again, flip the order */
if(lastClickedColumn == column)
{
order = !order;
}
lastClickedColumn = column;
switch(column)
{
case 0:
orderby = "Title";
break;
case 1:
orderby = "Artist";
break;
case 2:
orderby = "Album";
break;
case 3:
orderby = "Genre";
break;
case 4:
orderby = "Duration";
break;
case 5:
orderby = "Release";
break;
case 6:
orderby = "Comment";
break;
default:
orderby = "Title";
}
updateUI(currentTableView);
} | 8 |
public SMTPHostAuth(String unparsedServerInfo)
{
final List<String> info=CMParms.parseCommas(unparsedServerInfo,false);
if(info.size()==0)
return;
host = info.remove(0);
if((info.size()==0)||(host.length()==0))
return;
final String s=info.get(0);
if(s.equalsIgnoreCase("plain")||s.equalsIgnoreCase("login"))
authType=info.remove(0).toUpperCase().trim();
else
authType="PLAIN";
if(info.size()==0)
{
authType="";
return;
}
login=info.remove(0);
if(info.size()==0)
return;
password=info.remove(0);
} | 7 |
@Override
public boolean evaluate(T t) {
if(firstSearchString.evaluate(t) || secondSearchString.evaluate(t)){
return true;
}
else{
return false;
}
} | 2 |
public Audience updateAudience(String userName, String password, String firstName, String lastName,String email) {
Audience viewer = manager.find(Audience.class, userName);
if (viewer != null) {
viewer.setUserName(userName);
viewer.setPassword(password);
viewer.setFirstName(firstName);
viewer.setLastName(lastName);
viewer.setEmail(email);
}
return viewer;
} | 1 |
public static Double getPrejudice(AllocationInfo allocationToTake,
AllocationInfo allocationToWin, List<AllocationInfo> allAllocations,
final Map<String, Double> balances) {
double totalAllocations = 0;
double totalPeerBalance = 0;
for (AllocationInfo info : allAllocations) {
totalAllocations += info.getAllocations().size();
totalPeerBalance += getPeerBalance(info.getConsumer(), balances);
}
if (allocationToTake != null && allocationToWin == null) {
totalAllocations--;
}
double totalPrejudice = 0;
for (AllocationInfo info : allAllocations) {
double balance = (totalPeerBalance > 0) ? getPeerBalance(info.getConsumer(), balances) / totalPeerBalance : totalPeerBalance;
double allocations = info.getAllocations().size();
if (info == allocationToTake) {
allocations--;
} else if (info == allocationToWin) {
allocations++;
}
totalPrejudice += Math.abs(balance - (allocations / totalAllocations));
}
return round(totalPrejudice);
} | 7 |
public static int createStudent() {
System.out.println("=== Creation of a student ===");
Scanner scId = new Scanner(System.in);
System.out.print("Give a name: ");
String name = "";
while (name.equals("")) {
Scanner scName = new Scanner(System.in);
name = scName.nextLine();
}
System.out.print("Give a first name: ");
String forename = "";
while (forename.equals("")) {
Scanner scForename = new Scanner(System.in);
forename = scForename.nextLine();
}
System.out.print("Give an id: ");
try {
int id = scId.nextInt();
Student student = new Student(name, forename, id);
// We check if the student doesn't still exist in the Student List.
boolean exist = false;
for (int i = 0; i < sList.size(); i++) {
if (sList.get(i).equals(student)) {
exist = true;
}
}
if (!exist) {
sList.add(student);
System.out.println("Student " + student.displayNames()
+ " created.");
} else {
System.out.println("This student still exist !");
}
System.out.println();
} catch (InputMismatchException e) {
System.out.println("Enter a valid number !");
return 0;
}
return 1;
} | 6 |
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.