method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
1e3c20d7-bea1-4d8c-acb3-b8f8535d31b5
6
public void tick(int par1) { this.tickCounter = par1; this.removeDeadAndOutOfRangeDoors(); this.removeDeadAndOldAgressors(); if (par1 % 20 == 0) { this.updateNumVillagers(); } if (par1 % 30 == 0) { this.updateNumIronGolems(); } int var2 = this.numVillagers / 16; if (this.numIronGolems < var2 && this.villageDoorInfoList.size() > 20 && this.worldObj.rand.nextInt(7000) == 0) { Vec3D var3 = this.tryGetIronGolemSpawningLocation(MathHelper.floor_float((float)this.center.posX), MathHelper.floor_float((float)this.center.posY), MathHelper.floor_float((float)this.center.posZ), 2, 4, 2); if (var3 != null) { EntityIronGolem var4 = new EntityIronGolem(this.worldObj); var4.setPosition(var3.xCoord, var3.yCoord, var3.zCoord); this.worldObj.spawnEntityInWorld(var4); ++this.numIronGolems; } } }
9c31338e-4fb1-4611-9472-aebf1c48f84d
4
public String getAmount(){ String result = ""; if(amount < 1000) result = Integer.toString(amount); if(amount >= 1000) result = Integer.toString(amount / 1000) + "k"; if(amount >= 1000000) result = Integer.toString(amount / 1000000) + "m"; if(amount >= 1000000000) result = Integer.toString(amount / 1000000000) + "b"; return result; }
29d25c40-0752-4d43-aa45-da9cdb3efd1b
2
public static String calculate(String expression,boolean useDegree,int decimalPlaces){ useDegrees = useDegree; try { //Parse Vector<Token> tokens = Parser.tokenize(expression); tokens = Parser.convertToPostfixTokens(tokens); double result = Parser.calculatePostfixTokens(tokens); //Round to the second decimal place BigDecimal bigDecimal = new BigDecimal(result); bigDecimal = bigDecimal.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); result = bigDecimal.doubleValue(); //System.out.println("Result: "+result); return result+""; } catch( Exception e) { String errorMessage = e.getMessage(); if(errorMessage!=null) { return errorMessage; } return "Calculator Error: \""+e.getClass().getName()+"\""; } }
70affb29-389a-4e73-9fff-e84451b31c7a
2
private void clearProjectiles() { for (int i = 0; i < projectiles.size(); i++) { Projectile p = projectiles.get(i); if (p.isRemoved()) { projectiles.remove(i); } } }
e6e0e9ee-8573-4c5c-aa6a-0825abee6092
1
public void updateCollisionShape(Polygon col){ theEnemies = new CopyOnWriteArrayList<Enemy>(enemylist); for(Enemy e : theEnemies){ e.collisionshape=col; } }
8e438d84-8668-4fbc-81e5-767c0c523c7d
4
public Image getTile(int x, int y) { if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight()) { return null; } else { return tiles[x][y]; } }
9dc81bdb-60b4-4137-bbb7-9456a20d3d93
4
public static int sqrt(int x) { long start=0; long end=x; long middle=0; long temp=0; while(start < end){ middle = (start+end)/2; temp=middle*middle; if(temp < x) start=middle+1; else if(temp == x) return (int)middle; else { end=middle-1; } } if(end*end >x) end-=1; return (int)end; }
b19eada5-6f27-4928-b4cb-4c5e074955f7
0
public JDialog getDialog() { return dialog; }
88d7ff70-94c6-4949-99a1-55f4055cf31e
8
public void removeWalls(double accuracy) { for (int x = 0; x < vWalls.length; x++) for (int y = 0; y < vWalls[0].length; y++) { if (vWalls[x][y] && Math.random() < accuracy) vWalls[x][y] = false; } for (int x = 0; x < hWalls.length; x++) for (int y = 0; y < hWalls[0].length; y++) { if (hWalls[x][y] && Math.random() < accuracy) hWalls[x][y] = false; } }
151e4ef6-0296-42c4-b5c6-590766ded0ad
4
public static Adress getAdressByID(int adressID){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM Addresses WHERE address_id = ?"); stmnt.setInt(1, adressID); ResultSet res = stmnt.executeQuery(); res.next(); adress = new Adress(res.getString("bus"),res.getString("street"),res.getString("city"),res.getString("number"),res.getInt("postal_code"),res.getInt("address_id")); } catch(SQLException e) { } return adress; }
3a88cd4d-c8b5-4755-87c4-b0717d8c461e
5
@Override public int hashCode() { int hash = 0; hash += (a == null ? 0 : a.hashCode()); hash += (b == null ? 0 : b.hashCode()); hash += (c == null ? 0 : c.hashCode()); hash += (d == null ? 0 : d.hashCode()); hash += (e == null ? 0 : e.hashCode()); return hash; }
58c67100-1f30-489f-b1d7-2f4c0d105a15
3
@Override public TexInfo getTexInfo(int data){ switch(data){ default: case 0: return normal; case 1: return mud; case 2: return whiteFlowers; } }
e0ce2d98-2f0c-4090-9219-47eb69477e33
5
public void checkDown(Node node) { this.down = -1; // reset value to -1 // Prevent out of bounds if((node.getX()+1) < this.size.getX()) { if(checkWall(new Node( (node.getX()+1), (node.getY()) ))) { if(this.closedNodes.size()==0) this.down = 1; else { for(int i = 0; i < this.closedNodes.size(); i++) { // Check with closed nodes to differenciate explored or not if(new Node(node.getX()+1, node.getY()).compareTo(this.closedNodes.get(i))==1) { this.down = 2; // explored node break; } else this.down = 1; // empty } } } else { this.down = 0; // set 0 to specify as wall } } }
c3fb631e-36bc-413b-a416-552427f3c077
4
public static void registerTileImage(Class<?extends Game> gameClass, char symbol, URL imageURL) { tileImageURLs.put(new T2<Class<?extends Game>, Character>(gameClass,symbol), imageURL); BufferedImage img = null; try { img = ImageIO.read(imageURL); } catch (IOException e) {} tileImages.put(new T2<Class<?extends Game>, Character>(gameClass,symbol), img); }
69a67b04-8b2f-4534-984a-f82e02a187d3
1
public void link(Fibonaccinode y, Fibonaccinode x) { y.left.right = y.right; y.right.left = y.left; y.parent = x; if (x.child == null) { x.child = y; y.right = y; y.left = y; } else { y.left = x.child; y.right = x.child.right; x.child.right = y; y.right.left = y; } x.degree++; y.mark = false; }
06ac9bdf-aae3-4b4f-b437-6b63c0ecc8e9
0
public String getEmptyString(){ return emptyString; }
1198516f-8488-4bb2-871d-a3536cf3129c
9
private void jComboBox3actionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3actionPerformed // TODO add your handling code here: if (this.jComboBox3.getSelectedIndex() == 0) { return; } int ptr = this.jComboBox3.getSelectedIndex() - 1; String str = "The select event --- "+ "code index = "+ptr+"\n"+this.getCodeDispt(ptr); double[] tempGamma=new double[this.CRSM.gamma.length]; System.arraycopy(this.CRSM.gamma, 0, tempGamma, 0, this.CRSM.gamma.length); CRSM.gamma=new double[]{(double) 1, (double)0}; double[][] inPattern=new double[this.CRSM.numSpace][]; for (int k=0;k<CRSM.numSpace;k++) { inPattern[k] = new double [CRSM.len[k]]; } System.arraycopy(resetStatus(inPattern[0]), 0, inPattern[0], 0, inPattern[0].length); System.arraycopy(resetStatus(inPattern[1]), 0, inPattern[1], 0, inPattern[1].length); inPattern[0][ptr*2]=1; inPattern[0][ptr*2+1]=0; System.out.println("Test for previuos event patter in:"); String test_str="IF current siuation is : "; int[] preCode=this.getEventIdx(inPattern[0]); int[] curCode=this.getEventIdx(inPattern[1]); for(int i=0;i<curCode.length;i++){ test_str+=curCode[i]+"\t"; } test_str+="THEN previous siuation is : "; for(int i=0;i<preCode.length;i++){ test_str+=preCode[i]+"\t"; } System.out.println(test_str); int[] winners = this.CRSM.findWinnerK(inPattern, CRSM.FUZZYART,1,0.99); str+="**********************\n"; str+="*Next event generated*\n"; str+="**********************\n"; if(winners==null){ System.out.println("Unsuccessful retrieve!!!!"); this.jTextArea1.setText(str+"N.A."); return; } for(int i=0;i<winners.length;i++){ if(winners[winners.length-1]==this.CRSM.numCode-1){ System.out.println("enters!!"); int[] rewinners=new int[winners.length-1]; System.arraycopy(winners, 0, rewinners, 0, rewinners.length); winners=new int[winners.length-1]; winners=rewinners; } else{ System.out.println("winner @ code "+winners[i]+": pattern consistent? "+this.isSamePattern(inPattern[0], CRSM.weight[winners[i]][0])); winners[i]=this.getEventIdx(CRSM.weight[winners[i]][1])[0]; } } for(int i=0;i<winners.length;i++){ if(winners[i]<this.episodic.eventLearner.numCode){ str +=i+ ". "+ "code index = "+winners[i]+"\n"+this.getCodeDispt(winners[i])+"\n"; } } this.jTextArea1.setText(str); System.arraycopy(tempGamma, 0, this.CRSM.gamma, 0, this.CRSM.gamma.length); }//GEN-LAST:event_jComboBox3actionPerformed
3a5da1e2-bc09-45bb-9498-0826da7e7781
2
public static void generateRandomFile(String path, int size) throws IOException{ size *= 1024; Process p = Runtime.getRuntime().exec("dd if=/dev/urandom of="+path+" count=1 bs="+size); boolean finish = false; while (!finish) { try { p.exitValue(); finish = true; } catch (IllegalThreadStateException ex) { } } }
ea10d869-4e08-4d22-b875-8726db435687
8
public void actionPerformed(ActionEvent e) { String c = e.getActionCommand(); String commandPlus = ""; String commandMinus = ""; for (int i = 0; i < numberOfGroups; ++i) { commandPlus = String.format("%d+", i); commandMinus = String.format("%d-", i); if (c.equals(commandPlus)) { UpdateTicketValue(i, "+"); break; } else if (c.equals(commandMinus)) { UpdateTicketValue(i, "-"); break; } else if (c.equals("save")) { FileManager fileManager = new FileManager(); if (fileManager.Write(groups)) currentGroup.setText("Saved"); return; } else if (c.equals("invalid")) { ++invalidTicket; break; } else if (c.equals("cancel")) { if (invalidTicket == 0) return; --invalidTicket; break; } } infoArea.setText( VoteInfo() ); VoteStat.setText( VoteInfo() ); }
c5382ba4-f485-4c57-913c-5cc0c094298d
4
private boolean zIntersects(Vec3D var1) { return var1 == null?false:var1.x >= this.x1 && var1.x <= this.x2 && var1.y >= this.y1 && var1.y <= this.y2; }
a5266010-5bd5-4878-94d1-b01bb66f37a5
5
public double getCorrectPercentage(long incorrect, long correct) { if (correct < 0) { System.out.println("Invalid number of correct answers"); return -1; } if (correct > 81) { System.out.println("Invalid number of correct answers"); return -1; } if (incorrect < 0) { System.out.println("Invalid number of incorrect answers"); return -1; } if (incorrect > 81) { System.out.println("Invalid number of correct answers"); return -1; } double totalChoices = correct + incorrect; if (totalChoices == 0) { return 0; } double completePercent = (correct / totalChoices) *100; return completePercent; }
bf80fcd7-1104-4791-bf2f-f034a4d52aa9
0
public ValidableEntitiesList getEntityList() { return entityList; }
346535fe-5e77-4971-8255-7750f66b2daf
6
private void processSelectFile(APDU apdu) { byte[] buffer = apdu.getBuffer(); byte p1 = buffer[OFFSET_P1]; byte p2 = buffer[OFFSET_P2]; if(p1 != (byte)0x02 || p2 != (byte)0x0C) { ISOException.throwIt(SW_INCORRECT_P1P2); } short lc = (short) (buffer[OFFSET_LC] & 0x00FF); if (lc != 2) ISOException.throwIt(SW_WRONG_LENGTH); if (apdu.getCurrentState() == APDU.STATE_INITIAL) { apdu.setIncomingAndReceive(); } if (apdu.getCurrentState() < APDU.STATE_FULL_INCOMING) { // need all data in one APDU. ISOException.throwIt(SW_INTERNAL_ERROR); } short fid = Util.getShort(buffer, OFFSET_CDATA); if (fileSystem.getFile(fid) != null) { selectedFile = fid; volatileState[0] |= FILE_SELECTED; return; } setNoFileSelected(); ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); }
68e9d7d6-d4cd-4013-ba2d-b02986da8b35
6
public ICodec getInstance() { if( iCodecClass == null ) return null; Object o = null; try { o = iCodecClass.newInstance(); } catch( InstantiationException ie ) { instantiationErrorMessage(); return null; } catch( IllegalAccessException iae ) { instantiationErrorMessage(); return null; } catch( ExceptionInInitializerError eiie ) { instantiationErrorMessage(); return null; } catch( SecurityException se ) { instantiationErrorMessage(); return null; } if( o == null ) { instantiationErrorMessage(); return null; } return (ICodec) o; }
e1066a9c-3eab-44e6-aa37-ad9c10e09b0f
0
@Override public void execute(VirtualMachine vm) { vm.newFrameAtRunTimeStack(numberOfArguments); }
72ec17d4-6390-43c3-b18c-d152894b6076
2
void callAnnotated(Class<? extends Annotation> ann, boolean lazy) { for (ComponentAccess p : oMap.values()) { p.callAnnotatedMethod(ann, lazy); } }
c1ad0d16-7e1e-41ec-9869-e2717cc20a76
1
private void doAfterProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) { log("FiltradoSesion:DoAfterProcessing"); } // Write code here to process the request and/or response after // the rest of the filter chain is invoked. // For example, a logging filter might log the attributes on the // request object after the request has been processed. /* for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) { String name = (String)en.nextElement(); Object value = request.getAttribute(name); log("attribute: " + name + "=" + value.toString()); } */ // For example, a filter might append something to the response. /* PrintWriter respOut = new PrintWriter(response.getWriter()); respOut.println("<P><B>This has been appended by an intrusive filter.</B>"); */ }
04c03ceb-45ae-4844-8637-e01bbdb25b87
8
public void putObjectOnBorder(Point inpNeighbourPoint, FieldObject inpObject) throws NoSuchPositionException { if (inpNeighbourPoint.x < 0 || inpNeighbourPoint.y < 0 || inpNeighbourPoint.x > rowSizeForUser - 1 || inpNeighbourPoint.y > colSizeForUser - 1) { throw new NoSuchPositionException("There is no position (" + inpNeighbourPoint.x + "," + inpNeighbourPoint.y + ") on field."); } else { if (inpNeighbourPoint.x == 0) { this.cellAt(inpNeighbourPoint.x, inpNeighbourPoint.y + 1).putObject(inpObject); } else if (inpNeighbourPoint.x == rowSizeForUser - 1) { this.cellAt(inpNeighbourPoint.x + 2, inpNeighbourPoint.y + 1).putObject(inpObject); } else if (inpNeighbourPoint.y == 0) { this.cellAt(inpNeighbourPoint.x + 1, inpNeighbourPoint.y).putObject(inpObject); } else if (inpNeighbourPoint.y == colSizeForUser - 1) { this.cellAt(inpNeighbourPoint.x + 1, inpNeighbourPoint.y + 2).putObject(inpObject); } } }
0270500c-319f-429f-8f03-1cd275cca006
0
@Override public void paintComponent(Graphics g){ game.setSize(getSize()); game.draw(g); }
ff531860-efbc-4706-a7a6-f9ff33a75aa7
1
public synchronized void adicionar() { try { new InstituicaoSubmissaoView(this); } catch (Exception e) { } }
fc71654a-52bd-4cf7-9fc0-0399947cd137
4
public synchronized void removePlayer(String player, byte id) { Player temp = new Player(player, id); for (Player p : players) { if (p.equals(temp)) { temp = p; } } if (temp != null) { //With this, at least it shouldn't break. players.remove(temp); players.add(new Player("Disconnected",id)); numPlayersRemoved++; if (numPlayersRemoved >= numPlayers) { gameRunning = false; } } pcs.firePropertyChange("removed", false, true); }
7a097c10-76cc-4e7d-86d9-4c356dbd0388
8
public final void update(ResultData results[]) { if(results == null) { return; } if(!_onlineModus) { for(int i = 0; i < results.length; ++i) { if(results[i] != null) { DataDescription dataDescription = results[i].getDataDescription(); if(dataDescription != null) { if(!_simAttributeGroup.equals(dataDescription.getAttributeGroup())) { continue; } if(!_simAspect.equals(dataDescription.getAspect())) { continue; } final Data data = results[i].getData(); if(data != null) { _time = data.getTimeValue("Zeit").getMillis(); } } } } synchronized(_timeNotification) { _timeNotification.notifyAll(); } } }
4f61946b-b1ae-48d7-b26d-3c0d70eb4375
5
public static int LongestCommonSubsequence(char[] a, char[] b){ int m=a.length; int n=b.length; int[][] c=new int[m+1][n+1]; for (int i=0;i<=m;i++){ c[i][0]=0; } for (int j=0;j<=n;j++){ c[0][j]=0; } for (int i=1;i<=m;i++){ for (int j=1;j<=n;j++){ if (a[i-1]==b[j-1]){ c[i][j]=1+c[i-1][j-1]; }else{ c[i][j]=Math.max(c[i-1][j], c[i][j-1]); } } } return c[m][n]; }
a8a97aa9-56b2-4059-9d8e-2c52b90a9392
5
private static byte[] deCompress(byte[] comprMsg){ PDU compressedPDU = new PDU(comprMsg, comprMsg.length); int algorithm = compressedPDU.getByte(0); int checksum = compressedPDU.getByte(1); int compLength = compressedPDU.getShort(2); int unCompLength = compressedPDU.getShort(4); byte[] retArr = null; if(comprMsg.length < 9){ retArr = ("Compression faulty length: " + Message.div4(compLength)).getBytes(); }else { byte[] compMsg = compressedPDU.getSubrange(8, comprMsg.length - 8); if (algorithm == 0) { try { Inflater inf = new java.util.zip.Inflater(); ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(compMsg); GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein); ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream(); int res = 0; byte buf[] = new byte[65000]; while (res >= 0) { res = gzin.read(buf, 0, buf.length); if (res > 0) { byteout.write(buf, 0, res); } } retArr = byteout.toByteArray(); } catch (Exception e) { //e.printStackTrace(); System.out.println("Someone compressed a message wrong"); retArr = "Compressed message not in GZIP format".getBytes(); } } else { System.out.println("unknown compression method"); } } return retArr; }
d021d3cd-4b0d-46d8-b650-e15a4b47c084
1
private Session getSession() { if (_currentSession == null) { _currentSession = getSessionFactory().openSession(); } return _currentSession; }
ab5bf423-90d1-4ecb-bc65-40900cc8f2ac
6
public double[] getIntersection(Line l){ double [] retArr = new double[2]; if ((_x == l.getSlope() && _y == l.getYCoefficient()) || (_y == 0 && l.getYCoefficient() == 0)){ return null; } else{ convertToSlopeIntersect(); l.convertToSlopeIntersect(); if (l.getYCoefficient() == 0){ retArr[0] = -1 * l.getConstant(); retArr[1] = _x * retArr[0] + _c; return retArr; } else if (_y == 0){ retArr[0] = -1 * _c; retArr[1] = l.getSlope() * retArr[0] + l.getConstant(); return retArr; } double xOfLHS = _x; double cOfLHS = _c; double xOfRHS = l.getSlope(); double cOfRHS = l.getConstant(); xOfLHS -= xOfRHS; // Move all x terms to LHS xOfRHS = 0; // Move all x terms to LHS cOfRHS -= cOfLHS; // Move all constant terms to RHS cOfLHS = 0; // Move all constant terms to RHS cOfRHS /= xOfLHS; // Solve for x by dividing on both sides xOfLHS = 1; // x coordinate of intersection is found retArr[0] = cOfRHS; retArr[1] = _x * cOfRHS + _c; } return retArr; }
842b59ca-65ee-407e-bf13-86325b8fc0a7
2
@Override public boolean delete(Object item) { conn = new SQLconnect().getConnection(); String sqlcommand = "UPDATE `Timeline_Database`.`Eventnodes` SET `display`='false' WHERE `id`='%s';"; if(item instanceof Eventnode) { Eventnode newitem = new Eventnode(); newitem = (Eventnode)item; try { String sql = String.format(sqlcommand,newitem.getId()); Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象 System.out.println(sql); int count = st.executeUpdate(sql); // 执行插入操作的sql语句,并返回插入数据的个数 System.out.println("delete " + count + " entries"); //输出插入操作的处理结果 conn.close(); return true; }catch (SQLException e) { System.out.println("删除数据失败 " + e.getMessage()); return false; } } return false; }
8f4db7b4-364e-4e3e-b9f6-fbb5f388a24f
8
@Override public Component getListCellRendererComponent(JList<? extends T> list, T value, int index, boolean isSelected, boolean cellHasFocus) { int i = getIndexFromData(list.getModel(), value); JLabel cell = new JLabel(entries.get(i), icons.get(i), SwingConstants.LEFT); if (index > -1) cell.setBorder(MARGIN); if (index > -1 && (isSelected || cellHasFocus)) { cell.setOpaque(true); cell.setForeground(SELECTION_FOREGROUND); cell.setBackground(SELECTION_BACKGROUND); } else if (isGTK) { cell.setBackground(Color.WHITE); } // else // { // cell.setForeground(FOREGROUND); // cell.setBackground(BACKGROUND); // } if (isGTK && index == -1) { cell.setBorder(GTK_BORDER); } return cell; }
d8b9ec29-737f-415c-b909-fbbe93cf193c
0
public Parser (String gridString){ this.gridString = gridString; }
72b36c14-4c4e-4b5f-bb1d-0fdd851dc809
2
public static void executeInstance(NanoHTTPD server) { try { server.start(); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); System.exit(-1); } System.out.println("Server started, Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable ignored) { } server.stop(); System.out.println("Server stopped.\n"); }
3f9ea74f-aaee-4ed7-a8a7-a092bf272804
2
public static void scan(InputStream source, InputStream format) throws IOException{ Scanner scanner = new Scanner(source); SimpleFormat sf = JAXB.unmarshal(format, SimpleFormat.class); ColumnIndexParser parser = new ColumnIndexParser(sf); Integer r = 0; while (scanner.hasNext()) { r++; String line = scanner.nextLine(); // Parse line and return a Map of column index values pairs Map<Integer,Object> columns = parser.parse(line); for(Integer col: columns.keySet()){ System.out.println("row["+ r +"," + col + "]:=" + columns.get(col)); } } scanner.close(); }
841271d5-fca6-4ae6-a5fb-1a0cd499f720
8
public void setPosicionJugador1(int x,int y){ if(x>=0&&x<8&&y<8&&y>0){ switch (pd.mapa_jugador1[x][y]) { case "DT": case "PA": case "AZ": System.out.print("POSICION OCUPADA"); System.out.println("OTRA CORDENADA"); System.out.println("cordenada en x"); x=sc.nextInt(); System.out.println("coordenada en y "); setPosicionJugador1(x, y); case "": pd.mapa_jugador1[x][y]=codigo; break; } } System.out.println("Las coordenadas estan fuera de limite"); }
ccf9775d-b126-479f-95c3-9b73c3b29be0
9
public JFreeChart MakeChart() { DefaultCategoryDataset areaDataset = new DefaultCategoryDataset(); Object[] column1Data = super.getDataset().GetColumnData( super.getAttribute1()); Object[] column2Data = super.getDataset().GetColumnData( super.getAttribute2()); String column2Header = super.getDataset().GetAttributeName( super.getAttribute2()); boolean addDataset = true; String errors = ""; int errorCounter = 0; for (int i=0; i<super.getDataset().GetNoOfEntrys();i++) { Comparable<Object> nextValue1; //First value can have be any comparable object. nextValue1 = (Comparable<Object>) column1Data[i]; Double nextValue2 = null; boolean addThis = true; //Second value can only be integer, double or boolean. try { int intNextValue2 = Integer.parseInt(column2Data[i].toString()); nextValue2 = (Double) ((double) intNextValue2); } catch (NumberFormatException nfe) { try { double doubleNextValue2 = Double.parseDouble( column2Data[i].toString()); nextValue2 = (Double) doubleNextValue2; } catch (NumberFormatException nfe2) { String strNextValue2 = column2Data[i].toString(); if (strNextValue2.equalsIgnoreCase("True")) { nextValue2 = TRUE; } else if (strNextValue2.equalsIgnoreCase("False")) { nextValue2 = FALSE; } else { addThis = false; } } } catch (Exception e) { addThis = false; } if (addThis == true) { areaDataset.addValue( nextValue2, column2Header, nextValue1 ); } else { addDataset = false; if (errorCounter < MAX_ERROR_LENGTH) { errors = errors + "\n" + column2Data[i].toString(); errorCounter++; } } } if (addDataset == false) { areaDataset = new DefaultCategoryDataset(); //Reset JOptionPane.showMessageDialog(null, "Your selected y-axis has data in the wrong format" + "\n" + "The following data needs to be a number in order to be" + " represented." + errors); } JFreeChart chart = ChartFactory.createAreaChart( super.getHeader(), super.getxAxis(), super.getyAxis(), areaDataset, PlotOrientation.VERTICAL, true, //include legend true, false ); return chart; }
2adba832-76b9-4198-b9a1-aa4fe4ebc597
9
public static void printCorInfEventsToLLInterCount(){ int startTime = 0; int incTime = 5*(60*60*24); int endTime = 100*60*60*24; int estNumLocs = 100000; HashMap<Integer,Integer> aggPop = new HashMap<Integer,Integer>(estNumLocs); HashMap<Integer,Integer> numInfected = new HashMap<Integer,Integer>(estNumLocs); // HashMap<Integer,Double> xs = new HashMap<Integer,Double>(estNumLocs); // HashMap<Integer,Double> ys = new HashMap<Integer,Double>(estNumLocs); int time = startTime; try { Connection con = dbConnect(); PreparedStatement getInfEvents = con.prepareStatement( "SELECT locationID FROM "+EpiSimUtil.dendroTbl+" WHERE time > ? AND time <= ?"); PreparedStatement getLLInterCount = con.prepareStatement( "SELECT tally FROM "+EpiSimUtil.llInterCountTbl+ " WHERE location1ID = ? AND location2ID = ?"); PreparedStatement getAggPop = con.prepareStatement( "SELECT aggregatePop FROM "+EpiSimUtil.locTbl+" WHERE locationID = ?"); while (time <= endTime) { getInfEvents.setInt(1, time); getInfEvents.setInt(2, time+incTime); ResultSet getInfEventsQ = getInfEvents.executeQuery(); while (getInfEventsQ.next()) { Integer location = new Integer(getInfEventsQ.getInt("locationID")); if (numInfected.containsKey(location)) { numInfected.put(location, numInfected.get(location) + 1); } else { numInfected.put(location, new Integer(1)); } if (!aggPop.containsKey(location)) { getAggPop.setInt(1, location.intValue()); ResultSet getAggPopQ = getAggPop.executeQuery(); if (getAggPopQ.first()) { Integer pop = new Integer(getAggPopQ.getInt("aggregatePop")); aggPop.put(location, pop); } } } int day = time / (60*60*24); FileWriter fw = new FileWriter(day+".dat"); Iterator<Integer> itr = numInfected.keySet().iterator(); while (itr.hasNext()) { Integer location = itr.next(); Iterator<Integer> itr2 = numInfected.keySet().iterator(); while (itr2.hasNext()) { Integer location2 = itr2.next(); getLLInterCount.setInt(1, location.intValue()); getLLInterCount.setInt(2, location2.intValue()); ResultSet getLLInterCountQ = getLLInterCount.executeQuery(); if (getLLInterCountQ.first()) { int tally = getLLInterCountQ.getInt("tally"); double del = Math.abs( numInfected.get(location).doubleValue()/aggPop.get(location).doubleValue() - numInfected.get(location2).doubleValue()/aggPop.get(location2).doubleValue()); fw.write(tally+"\t"+del+"\n"); } } // double x,y; // if (!xs.containsKey(location)) { // xs.put(location, getX(location.intValue())); // ys.put(location, getY(location.intValue())); // } // x = xs.get(location); // y = ys.get(location); // fw.write(x+"\t"+y+"\t"+numInfected.get(location)+"\n"); } fw.close(); time += incTime; } con.close(); } catch (Exception e) { System.out.println(e); } }
59cd17f8-5500-47e4-95a8-226f34743ba4
5
public float priorityFor(Actor actor) { /* final Venue work = (Venue) actor.mind.work() ; if (work.personnel.shiftFor(actor) != Venue.SECONDARY_SHIFT) { if (! actor.isDoing("actionEquipYard", null)) return 0 ; } //*/ // // TODO: You can't drill if you lack an appropriate device type! float impetus = 0 ; // // TODO: Relevant traits might vary depending on type. final float pacifism = 0 - actor.traits.traitLevel(AGGRESSIVE) ; switch (yard.drillType()) { case (DrillYard.DRILL_MELEE) : case (DrillYard.DRILL_RANGED) : impetus -= (pacifism > 0) ? pacifism : (pacifism / 2f) ; break ; case (DrillYard.DRILL_AID) : impetus += pacifism / 2f ; break ; } impetus += actor.traits.traitLevel(DUTIFUL) ; impetus -= actor.traits.traitLevel(INDOLENT) ; if (actor.vocation().guild == Background.GUILD_MILITANT) { impetus += CASUAL ; } else { impetus = (impetus + IDLE) / 2 ; } // // TODO: Modify by importance of associated skills- impetus -= Plan.rangePenalty(actor, yard) ; impetus -= Plan.dangerPenalty(yard, actor) ; return Visit.clamp(impetus, 0, ROUTINE) ; }
4033e4eb-69f2-4813-bcf2-e445b015a06e
5
private String read() { StringBuffer buffer = new StringBuffer(); int codePoint; boolean zeroByteRead = false; try { do { codePoint = this.socketIn.read(); if (codePoint == 0) { zeroByteRead = true; } else if (Character.isValidCodePoint(codePoint)) { buffer.appendCodePoint(codePoint); } } while (!zeroByteRead && buffer.length() < 200); } catch (Exception e) { debug("Exception (read): " + e.getMessage()); } return buffer.toString(); }
20d3e88b-ecda-414b-b9fa-1c9a69d6cc6e
6
private byte fromOpcode(Opcode opcode) { if (opcode == Opcode.CONTINIOUS) return 0; else if (opcode == Opcode.TEXT) return 1; else if (opcode == Opcode.BINARY) return 2; else if (opcode == Opcode.CLOSING) return 8; else if (opcode == Opcode.PING) return 9; else if (opcode == Opcode.PONG) return 10; throw new RuntimeException("Don't know how to handle " + opcode.toString()); }
ba3c3f1b-2f36-4fa6-b92b-de59db983be8
8
public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (pass == 0 && dataset instanceof IntervalXYDataset) { IntervalXYDataset ixyd = (IntervalXYDataset) dataset; PlotOrientation orientation = plot.getOrientation(); if (drawXError) { // draw the error bar for the x-interval double x0 = ixyd.getStartXValue(series, item); double x1 = ixyd.getEndXValue(series, item); double y = ixyd.getYValue(series, item); RectangleEdge edge = plot.getDomainAxisEdge(); double xx0 = domainAxis.valueToJava2D(x0, dataArea, edge); double xx1 = domainAxis.valueToJava2D(x1, dataArea, edge); double yy = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); Line2D line; Line2D cap1 = null; Line2D cap2 = null; double adj = this.capLength / 2.0; if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx0, yy, xx1, yy); cap1 = new Line2D.Double(xx0, yy - adj, xx0, yy + adj); cap2 = new Line2D.Double(xx1, yy - adj, xx1, yy + adj); } else { // PlotOrientation.HORIZONTAL line = new Line2D.Double(yy, xx0, yy, xx1); cap1 = new Line2D.Double(yy - adj, xx0, yy + adj, xx0); cap2 = new Line2D.Double(yy - adj, xx1, yy + adj, xx1); } g2.setStroke(new BasicStroke(1.0f)); if (this.errorPaint != null) { g2.setPaint(this.errorPaint); } else { g2.setPaint(getItemPaint(series, item)); } g2.draw(line); g2.draw(cap1); g2.draw(cap2); } if (drawYError) { // draw the error bar for the y-interval double y0 = ixyd.getStartYValue(series, item); double y1 = ixyd.getEndYValue(series, item); double x = ixyd.getXValue(series, item); RectangleEdge edge = plot.getRangeAxisEdge(); double yy0 = rangeAxis.valueToJava2D(y0, dataArea, edge); double yy1 = rangeAxis.valueToJava2D(y1, dataArea, edge); double xx = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); Line2D line; Line2D cap1 = null; Line2D cap2 = null; double adj = this.capLength / 2.0; if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx, yy0, xx, yy1); cap1 = new Line2D.Double(xx - adj, yy0, xx + adj, yy0); cap2 = new Line2D.Double(xx - adj, yy1, xx + adj, yy1); } else { // PlotOrientation.HORIZONTAL line = new Line2D.Double(yy0, xx, yy1, xx); cap1 = new Line2D.Double(yy0, xx - adj, yy0, xx + adj); cap2 = new Line2D.Double(yy1, xx - adj, yy1, xx + adj); } g2.setStroke(new BasicStroke(1.0f)); if (this.errorPaint != null) { g2.setPaint(this.errorPaint); } else { g2.setPaint(getItemPaint(series, item)); } g2.draw(line); g2.draw(cap1); g2.draw(cap2); } } super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); }
7239ab53-d82f-4900-aa8d-b088f1bf2de6
6
public void loadPlaymodes(){ try { Playmode[] playmodes = dbCon.getPlaymodes(); alstPlaymodePanels.clear(); playmodePanel.removeAll(); if(playmodes != null){ for (Playmode playmode : playmodes) { PlaymodePanel playmodepanel = new PlaymodePanel(playmode); alstPlaymodePanels.add(playmodepanel); playmodePanel.add(playmodepanel); } setPlaymodeSelection(!searching); } } catch (SocketTimeoutException | SocketException e ) { jlblMessage.setText("Connection timed out"); } catch (UnknownHostException e) { jlblMessage.setText("Server not found"); } catch (ClassNotFoundException e) { jlblMessage.setText("Internal Error: Missing Class"); } catch (IOException e) { e.printStackTrace(); jlblMessage.setText("Internal Error: IO"); } }
484efded-3916-4e70-9c67-aab1574377ac
1
public boolean saveWindowSize() { Preferences prefs = Preferences.userNodeForPackage(Joculus.class); // window preferences prefs.putInt(WINDOW_SIZE_DEFAULT_W_PROPERTY_NAME, window_size_last.width); prefs.putInt(WINDOW_SIZE_DEFAULT_H_PROPERTY_NAME, window_size_last.height); try { prefs.flush(); } catch (BackingStoreException ex) { Joculus.showError(UIStrings.ERROR_WRITE_SETTINGS_FAILED + "\n" + ex.getMessage()); } return true; }
90b03bce-f614-46f4-846f-8d4d6e942aa0
7
public void startEngine(){ try { // Default localhost host and default port 1099 is used by RMI Registry engineRegistry = LocateRegistry.createRegistry(1100); Registry generatorRegistry = LocateRegistry.getRegistry(1099); // Getting the RMI object to interact with map on generator server IEngineRMIObject iEngineRMIObject = (IEngineRMIObject) generatorRegistry.lookup("IEngineRMIObject"); // Callback doesn't not need to be exported because it extends UnicastRemoteObject IEngineRMICallback iEngineRMICallback = new EngineRMICallback(); engineRegistry.rebind("IEngineRMICallback", iEngineRMICallback); // Wait for the client to start and sending a message byte[] b = new byte[2000]; DatagramPacket datagramPacket = new DatagramPacket(b, b.length); try { DatagramSocket datagramSocket = new DatagramSocket(8080); datagramSocket.receive(datagramPacket); System.out.println("New message from client : " + new String(datagramPacket.getData())); datagramSocket.close(); } catch (IOException e) { e.printStackTrace(); } MAP_SIZE = iEngineRMIObject.getRemoteMap().getMapParameters().get(ParameterEnum.MAP_SIZE_INTEGER); if (MAP_SIZE == null) { MAP_SIZE = 10; } while (!iEngineRMIObject.isGameOver()) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } Position deplacement = null; do { deplacement = new Position(); deplacement.setPosition(Utils.generateRandomPosition(MAP_SIZE - 1), Utils.generateRandomPosition(MAP_SIZE - 1)); } while (iEngineRMIObject.getRemoteMap().isVisitedPosition(deplacement)); String notification = iEngineRMIObject.moveCharacter(deplacement); ((EngineRMICallback) iEngineRMICallback).getClient().sendNotifications(notification); } // Game is now over ((EngineRMICallback) iEngineRMICallback).getClient().sendNotifications("GAME OVER"); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } }
49199e84-e061-452b-a085-50300d2bf0f9
3
public boolean registrarSeriales(entidadPrestamo datosPrestmo) { conectarse(); boolean retornarObj = false; String regser = "insert into tbl_dtlls_prestamo (Id_prestamo,Seriales) values(?,?)"; ArrayList seriales_recorrer = datosPrestmo.getSeriales(); String estado = datosPrestmo.getEstado(); try { int cont = 0; for (int i = 0; i < seriales_recorrer.size(); i++) { Stmp(); statement = conector.prepareStatement(regser); statement.setInt(1, datosPrestmo.getId_prestamo()); statement.setString(2, seriales_recorrer.get(i).toString().trim()); cont = statement.executeUpdate(); } if (cont > 0) { retornarObj = true; } } catch (Exception e) { } return retornarObj; }
8bf6ced0-04ef-4662-b38a-2070c4d06521
5
protected void update() { double val = Math.sqrt(movX * movX + movY * movY); if (val > 0) { posX += movX * speed / val; posY += movY * speed / val; } if (posX < Main.EDGE) { // posX = Main.FRAME_X - Main.EDGE; // posX = Main.FRAME_X / 2; // posX += 1; life.kill(); } if (posY < Main.EDGE) { // posY = Main.FRAME_Y - Main.EDGE; life.kill(); // posX = Main.FRAME_Y / 2; // posY += 1; } if (posX > Main.FRAME_X - Main.EDGE) { // posX = Main.EDGE; // posX = Main.FRAME_X / 2; life.kill(); // posX -= 1; } if (posY > Main.FRAME_Y - Main.EDGE) { // posY = Main.EDGE; // posX = Main.FRAME_Y / 2; life.kill(); // posY -= 1; } movX = 0; movY = 0; action(1); }
3c6d4c16-e213-450f-84a2-6e564e354920
8
private void requestQuotes(TACConnection conn, boolean flightQuotes, boolean hotelQuotes) { // This should be changed so that it will only request those quotes // that are old enough... if (flightQuotes) { for (int i = MIN_FLIGHT; i <= MAX_FLIGHT ; i++) { if (!quotes[i].isAuctionClosed()) { requestQuote(quotes[i], conn, false); } } } for (int i = MIN_ENTERTAINMENT; i <= MAX_ENTERTAINMENT ; i++) { if (!quotes[i].isAuctionClosed()) { requestQuote(quotes[i], conn, false); } } if (hotelQuotes) { for (int i = MIN_HOTEL; i <= MAX_HOTEL ; i++) { if (!quotes[i].isAuctionClosed()) { lastHotelAuction = i; requestQuote(quotes[i], conn, false); } } } }
5e066a88-636f-4a60-ba54-225a8eea4d49
1
private static boolean isRotation(String a, String b) { // both must be of the same length && one can find second string in concatenation of the first string to itself ( if it is rotated ) return(a.length()==b.length() && (a+a).indexOf(b)!=-1); }
dc1901e4-d330-4996-bee4-b6c162335612
1
public CacheableNode getFront() { CacheableNode cacheableNode = head.nextNode; if (cacheableNode == head) { current = null; return null; } else { current = cacheableNode.nextNode; return cacheableNode; } }
84dcd1cf-0747-4fd6-b56e-992324190a97
0
public String getBuildingId() { return buildingId; }
5f879d07-4a4f-4d22-af17-94610fc5dab2
7
private synchronized void sendUpdates() { _dataGenerator.generateUpdatedEntries(); Set<Token> deletedTokens = new HashSet<Token>(); Iterator<Token> iter = _pendingStreamItems.keySet().iterator(); while (iter.hasNext()) { Token rq = (Token)(iter.next()); DataStreamItem streamItem = (DataStreamItem)_pendingStreamItems.get(rq); if (streamItem == null) { continue; } if (streamItem.isClosed() || streamItem.sendUpdate()) { deletedTokens.add(rq); } } iter = deletedTokens.iterator(); while (iter.hasNext()) { Token tk = (Token)iter.next(); DataStreamItem streamItem = (DataStreamItem)_pendingStreamItems.remove(tk); if (streamItem != null && !streamItem.isClosed()) { streamItem.close(); } } }
08092799-36aa-43a5-ba56-daa62837a94c
0
public DataStructures getArrData(){ return arrData; }
8761ed21-e750-4bd3-bd0c-9501526098ce
5
public static void insertionSort (int[] array) { if (array == null || array.length <= 1) { return ; } int insertNum; int i, j; for (i = 1; i < array.length; i++) { insertNum = array[i]; for (j = i - 1; j >= 0 && array[j] > insertNum; j--) { array[j + 1] = array[j]; } array[j + 1] = insertNum; } }
dcda9bfb-e688-4d07-858b-9f33fb5d2e64
1
public void prependVarPhi(final PhiJoinStmt stmt) { final List v = varphis[cfg.preOrderIndex(stmt.block())]; if (!v.contains(stmt)) { v.add(0, stmt); } }
dc4240d6-1252-4dda-8a25-019f48275699
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LogEntry logEntry = (LogEntry) o; if (text != null ? !text.equals(logEntry.text) : logEntry.text != null) return false; return true; }
4591a329-e21e-4c19-aa1f-a57c779e909f
2
public synchronized void removeListener(final CycLeaseManagerListener cycLeaseManagerListener) { //// Preconditions if (cycLeaseManagerListener == null) { throw new InvalidParameterException("cycLeaseManagerListener must not be null"); } assert listeners != null : "listeners must not be null"; if (cycAccess.getCycConnection() instanceof CycConnection) { assert cycAccess.getCycLeaseManager().isAlive() : "the CycLeaseManager thread has died because a lease timed-out, errored or was denied"; } // otherwise, this is a SOAP client connection and leasing is never started listeners.remove(cycLeaseManagerListener); }
e85f277e-278b-47de-9d74-ce2f9885fc16
6
private String getPageHtml(WikiContext context, String name, String action) throws IOException { StringBuilder buffer = new StringBuilder(); String escapedName = escapeHTML(titlePrefix(action) + unescapedTitleFromName(name)); addHeader(context, escapedName, getTalkPage(context, name), buffer); if ((action.equals("view") && context.getStorage().hasPage(name)) || (action.equals("viewparent") && context.getStorage().hasUnmodifiedPage(name)) || (action.equals("viewrebase") && context.getRemoteChanges().hasChange(name))) { buffer.append(renderXHTML(context, getPageWikiText(context, name, action))); } else { addHtmlForNonExistantPage(context, name, buffer); } addFooter(context, name, !action.equals("view"), buffer); return buffer.toString(); }
736ee003-52f8-416b-9326-87590b1fcb57
0
public void desconectar(){ connection = null; }
b2fa8915-aa28-45d2-b8e4-757f0a933878
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
58f23a54-c6b6-4f37-8489-d56a294b1555
2
private void updateComboBox() { if (arrayDirty == true) { insertionSort(); } jEmployeeComboBox.removeAllItems(); int count = employees.size(); for(int x = 0;x<count;x++) { jEmployeeComboBox.addItem(employees.get(x).getFullName()); } }
a83dbd6e-02de-4ad4-8adc-2e9d4b5a45d8
9
public boolean deleteFourInRowHorizontal(int i,int j){ if(i < gridRows - 3 && tileGrid[i+1][j] != null && tileGrid[i+2][j] != null && tileGrid[i+3][j] != null && tileGrid[i][j].getTileType().equals(tileGrid[i+1][j].getTileType()) && tileGrid[i][j].getTileType().equals(tileGrid[i+2][j].getTileType()) && tileGrid[i][j].getTileType().equals(tileGrid[i+3][j].getTileType())) {//4 IN A ROW tileGrid[i][j] = null; tileGrid[i+1][j] = null; tileGrid[i+2][j] = null; tileGrid[i+3][j] = null; if(!data.getInitializingGrid()){ jellyGrid[i][j] = null; jellyGrid[i+1][j] = null; jellyGrid[i+2][j] = null; jellyGrid[i+3][j] = null; } activateNumbersHorizontal(i,j,4,TILE_TYPE_TWENTY_FIVE_POINTS); CrushSagaTile specialTile; if(data.getInitializingGrid()){ specialTile = createTypeFourHorizontalTile(calculateTileXInGrid(i+1),unassignedTilesY + (TILE_IMAGE_HEIGHT*j),0,0,VISIBLE_STATE); }else{ specialTile = createTypeFourHorizontalTile(calculateTileXInGrid(i+1),calculateTileYInGrid(j),0,0,VISIBLE_STATE); } specialTile.setGridCell(i+1,j); tileGrid[i+1][j] = specialTile; return true; } return false; }
0b6914a4-53a0-49fe-8eb0-818815070814
3
private boolean isFileValid(File file, String methodName) { // check if the file is invalid or not if (file == null) { System.out.println(name_ + "." + methodName + ": Warning - the given file is null."); return false; } String fileName = file.getName(); if (fileName == null || fileName.length() == 0) { System.out.println(name_ + "." + methodName + ": Warning - invalid file name."); return false; } return true; }
19319db3-4b6e-4114-a55e-ccfa78ca6bbf
6
public void Parse(String inputPacket, Memory InfoMem) { // Remove outer parentheses inputPacket = inputPacket.substring(1, inputPacket.length() - 1); // Split inputPacket into tokens by "(" and ")" delimiters String[] splitPacket = (inputPacket.split("[()]")); // Parse the first element into packet type and time String[] packetType = (splitPacket[0].split(" ")); // We only proceed if it is a (see), (sense_body), or (hear) message if((packetType[0].compareTo("see") == 0) || (packetType[0].compareTo("sense_body") == 0) || (packetType[0].compareTo("hear") == 0)) { // the time from the message int time = Integer.parseInt(packetType[1]); // Call parse method based on packet type in position [0] (either see, sense_body, or hear) if(packetType[0].compareTo("see") == 0) { ArrayList<ObjInfo> seeArray = new ArrayList<ObjInfo>(); seeParse(seeArray, splitPacket); ObjMemory newObjMem = new ObjMemory(seeArray, time); InfoMem.ObjMem = newObjMem; InfoMem.setCurrent(); } else if(packetType[0].compareTo("sense_body") == 0) { SenseMemory newSenMem = new SenseMemory(time); senseParse(newSenMem, splitPacket); InfoMem.SenMem = newSenMem; } else if(packetType[0].compareTo("hear") == 0) { hearParse(InfoMem, splitPacket); } } }
a47e40eb-2cfb-4968-90de-107cd21be165
3
@Override protected void read(InputBuffer b) throws IOException, ParsingException { VariableLengthIntegerMessage length = getMessageFactory().parseVariableLengthIntegerMessage(b); b = b.getSubBuffer(length.length()); long l = length.getLong(); if (l > MAX_LENGTH || l < 0) { throw new ParsingException("List is to long. Maximum is 50,000"); } ints = new long[(int) l]; for (int i = 0; i < l; i++) { VariableLengthIntegerMessage v = getMessageFactory().parseVariableLengthIntegerMessage(b); b = b.getSubBuffer(v.length()); ints[i] = v.getLong(); } }
2872d864-f6d3-4efd-87fc-80c34cbfcd54
9
public boolean isPalindrome(String s) { if(s == null || s.length() == 0) return true; else{ int i=0; int j = s.length()-1; while(!isAlphanumeric(s.charAt(i))){ i++; if(i == s.length() ) return true; } while(!isAlphanumeric(s.charAt(j))) j--; while(i< j){ if(toLowCase(s.charAt(i))!=toLowCase(s.charAt(j))) return false; i++; j--; while(!isAlphanumeric(s.charAt(i))) i++; while(!isAlphanumeric(s.charAt(j))) j--; } return true; } }
fd7f9124-b0db-4fa5-ab81-4d8998982035
9
public boolean checkForEnemyType(int a_xSrc, int a_xDest, int a_ySrc, int a_yDest, int a_type) { int min_x = Math.min(a_xSrc, a_xDest); int min_y = Math.min(a_ySrc, a_yDest); int max_x = Math.max(a_xSrc, a_xDest); int max_y = Math.max(a_ySrc, a_yDest); if(min_x < 0) min_x = 0; if(max_y >= 15) max_y = 14; if(min_y < 0) min_y = 0; for(int x = min_x; x <= max_x; ++x) { for(int y = min_y; y <= max_y; ++y) { if(m_enemyCollection.containsKey(x)) { Vector<Enemy> enemies = m_enemyCollection.get(x); for(int i = 0; i < enemies.size(); ++i) { Enemy en = enemies.elementAt(i); if(en.m_type == a_type && en.m_y == y) { return true; } } } } } return false; }
53a8d17d-f876-4a95-a620-a7740bc9a5c9
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Puzzle)) return false; Puzzle other = (Puzzle) obj; if (!Arrays.equals(image, other.image)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (puzzleID != other.puzzleID) return false; return true; }
b78db63e-bad8-41ed-8e7e-4783f63be814
4
public static Event parse(Event rawEvent) throws IOException { if(rawEvent.getHeader() == null) { return null; } if(rawEvent.getData() == null || !rawEvent.isRawData()) { return rawEvent; } IEventHeader header = rawEvent.getHeader(); BinaryIEventData rawData = (BinaryIEventData)rawEvent.getData(); ByteArrayInputStream bi = new ByteArrayInputStream(rawData.getData()); EventDataParser parser = parserMap.get(header.getEventType()); if(parser == null) { return rawEvent; } IEventData parsedData = parser.parse(bi); return new Event(header, parsedData); }
0d49c50a-8475-487e-9a9b-16fe364bca9f
8
public ArrayList<Vehicle> GetOneVehicle(int VID) throws UnauthorizedUserException, BadConnectionException, DoubleEntryException { /* Variable Section Start */ /* Database and Query Preperation */ PreparedStatement statment = null; ResultSet results = null; String statString = "SELECT * FROM 'Vehicle' WHERE 'VehicleID' = ?"; /* Return Parameter */ ArrayList<Vehicle> BPList = new ArrayList<Vehicle>(); /* Variable Section Stop */ /* TRY BLOCK START */ try { /* Preparing Statment Section Start */ statment = con.prepareStatement(statString); statment.setInt(1, VID); /* Preparing Statment Section Stop */ /* Query Section Start */ results = statment.executeQuery(); /* Query Section Stop */ /* Metadata Section Start*/ //ResultSetMetaData metaData = results.getMetaData(); /* Metadata Section Start*/ /* List Prepare Section Start */ while (results.next()) { Vehicle temp = new Vehicle(); //rs.getBigDecimal("AMOUNT") temp.setCapacity(results.getInt("Capacity")); temp.setCondition(results.getString("VCondition")); temp.setFranchiseNumber(results.getInt("FranchiseNumber")); temp.setMake(results.getString("Make")); temp.setMileage(results.getString("Mileage")); temp.setModel(results.getString("Model")); temp.setRate(results.getDouble("RentalPrice")); temp.setTablet(results.getString("Tablet")); temp.setVehicleID(results.getInt("VehicleID")); temp.setVin(results.getString("VIN")); temp.setYear(results.getInt("Year")); temp.setvIndex(results.getString("VIndex")); BPList.add(temp); } /* List Prepare Section Stop */ } catch(SQLException sqlE) { if(sqlE.getErrorCode() == 1142) throw(new UnauthorizedUserException("AccessDenied")); else if(sqlE.getErrorCode() == 1062) throw(new DoubleEntryException("DoubleEntry")); else throw(new BadConnectionException("BadConnection")); } finally { try { if (results != null) results.close(); } catch (Exception e) {}; try { if (statment != null) statment.close(); } catch (Exception e) {}; } /* Return to Buisness Section Start */ return BPList; /* Return to Buisness Section Start */ }
24348c8d-a8ee-49e5-a03e-f5bb4f47fb6f
8
public void Solve() { List<Integer> primes = Euler.GetPrimes(_max); for (Iterator<Integer> it = primes.iterator(); it.hasNext();) { Integer prime = it.next(); String primeString = prime.toString(); for (int numberOfDigits = 1; numberOfDigits < primeString.length(); numberOfDigits++) { List<String> enumeration = Enumerate(primeString, "", 0, numberOfDigits); for (Iterator<String> it1 = enumeration.iterator(); it1.hasNext();) { String candidate = it1.next(); String output = ""; int primeCount = 0; for (int digit = 0; digit < 10; digit++) { if (candidate.startsWith("x") && digit == 0) { continue; } int primeCandidate = Integer.parseInt(candidate.replaceAll("x", Integer.toString(digit))); if (0 <= Collections.binarySearch(primes, primeCandidate)) { primeCount++; output += primeCandidate + ", "; } } if (primeCount == _familyCount) { System.out.println("Result=" + output); return; } } } } }
1432334b-aa75-42c5-bd1e-760674989e0c
0
public Manufacturer getManufacturer() { return manufacturer; }
a3b80199-6787-47c1-8b55-ecc5afcd220b
5
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String localVersion = this.plugin.getDescription().getVersion(); if (title.split(delimiter).length == 2) { final String remoteVersion = title.split(delimiter)[1].split(" ")[0]; // Get the newest file's version number if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
413fb8a5-07ac-441b-a900-aca29dbbc201
8
private StateDist limitDfs(SearchState oldState, int curDist, int maxDist) { int estimatedCost = curDist + h.estimateCostToGoal(oldState); if (estimatedCost > maxDist) { if (estimatedCost >= OO) return null; Integer dist = statesWithUnexploredNodes.get(oldState.prevState); int prevDist = stateDistMap.get(oldState.prevState); if (dist == null || dist > prevDist) { if (dist != null) statesWithUnexploredNodes.remove(oldState.prevState); statesWithUnexploredNodes.put(oldState.prevState, prevDist); } return new StateDist(null, estimatedCost); } Integer dist = stateDistMap.get(oldState); if (dist != null && dist <= curDist) return null; stateDistMap.put(oldState, curDist); if (oldState.rowsToGo <= 0) return new StateDist(oldState, curDist); return expandChildren(oldState, curDist); }
76791199-fe50-4fe8-b9c5-b1f2576e1da3
0
@After public void tearDown() { }
f6c50717-cfa8-46a3-ba95-fe8a590986d6
8
@Override public void deploy(File zipFile, String targetPath) throws IOException, RemoteException { // TODO Auto-generated method stub if(!zipFile.exists()) { throw new RemoteException(zipFile+" is not exist."); } targetPath = pathStrConvert(targetPath); ArrayList<String> result = new ArrayList<String>(0); ArrayList<String> errorResult = new ArrayList<String>(0); // copy the local file zipFile to targetPath of remote host if (this.scopy(conncontroller, zipFile, targetPath) == true) { //System.out.println("222---"+targetPath+zipFile.getName().substring(0,zipFile.getName().toString().indexOf(".zip"))); boolean unzipflag=isUnzipAddDirectory(targetPath,zipFile.getName()); if (isExistedDirectory( targetPath, zipFile.getName().substring(0, zipFile.getName().toString().indexOf(".zip")))) { if (reDirName( targetPath, zipFile.getName().substring(0, zipFile.getName().toString().indexOf(".zip")), "_bak") == false) { throw new RemoteException(errorResult.toString()); } } //System.out.println(zipFile.getName()); result.clear(); errorResult.clear(); String cmd; if(unzipflag==false) { cmd="cd "+targetPath+" && unzip -q "+ zipFile.getName(); } else { cmd="cd "+targetPath+" && unzip -q -d "+ zipFile.getName().substring(0, zipFile.getName().toString().indexOf(".zip"))+" " + zipFile.getName(); } //System.out.println("333----"+cmd); this.reauthInfo.execCommand(conncontroller, cmd, result, errorResult); if (result.isEmpty() && errorResult.isEmpty()) { // System.out.println("Unzip successfully!"); if (deleteFile(targetPath, zipFile.getName()) == false) { throw new RemoteException("zipFile deleted failed."); } else { // System.out.println("zipFile deleted successfully!"); } } else throw new RemoteException("unzip failed"); } }
cd1064d4-e078-419b-aa84-13dc1a3ec76c
0
private void addPlayerButtonActionPerformed(java.awt.event.ActionEvent evt) { chooseBrain.showOpenDialog(controlFrame); }
bff60157-5cb4-458b-ae16-e2c287d5ab98
7
public int getSocketOption(byte option) throws IllegalArgumentException, IOException { switch(option){ case SocketConnection.DELAY: return socket.getTcpNoDelay() ? 0 : 1; case SocketConnection.KEEPALIVE: return socket.getKeepAlive() ? 1 : 0; case SocketConnection.LINGER: return socket.getSoLinger(); case SocketConnection.RCVBUF: return socket.getReceiveBufferSize(); case SocketConnection.SNDBUF: return socket.getSendBufferSize(); default: throw new IllegalArgumentException(); } }
46032059-79ce-426c-b7ff-38f49dc5e4e6
3
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child for(ListIterator<PComando> i = this._comando_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PComando) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
ac3edc6e-d418-4933-9927-1b48c722afc4
5
public static void generateMaze(int x, int y, long seed) { GRID_WIDTH = x; GRID_HEIGHT = y; stack = new ArrayList<Cell>(); remainingCells = new ArrayList<Cell>(); // Init array of cells maze = new Cell[x][y]; // Reset maze and add cells to remainingcell list for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) { maze[i][j] = new Cell(i, j); remainingCells.add((maze[i][j])); } // Starting the maze generating algorithm /* * TODO: Explanation */ // STARTING CELL currentCell = maze[0][0]; maze[currentCell.getX()][currentCell.getY()].visit(); stack.add(maze[currentCell.getX()][currentCell.getY()]); remainingCells.remove(maze[currentCell.getX()][currentCell.getY()]); // Initiating random with given seed r = new Random(seed); while (!remainingCells.isEmpty()) { if (checkForNeighbors(currentCell.getX(), currentCell.getY()).isEmpty()) { stack.remove(stack.size() - 1); currentCell = stack.get(stack.size() - 1); } else { currentCell = checkForNeighbors(currentCell.getX(), currentCell.getY()).get(Math.abs(r.nextInt()) % checkForNeighbors(currentCell.getX(), currentCell.getY()).size()); maze[currentCell.getX()][currentCell.getY()].visit(); remainingCells.remove(currentCell); maze[currentCell.getX()][currentCell.getY()].removeWall(wallToRemove(currentCell.getX(), currentCell.getY(), stack.get(stack.size() - 1).getX(), stack.get(stack.size() - 1).getY())); maze[stack.get(stack.size() - 1).getX()][stack.get(stack.size() - 1).getY()].removeWall(wallToRemove(stack.get(stack.size() - 1).getX(), stack.get(stack.size() - 1).getY(), currentCell.getX(), currentCell.getY())); stack.add(maze[currentCell.getX()][currentCell.getY()]); } } if (remainingCells.isEmpty()) { stack.removeAll(stack); } }
6297699f-52a7-42bc-9cdf-77240eb1df4a
4
private boolean handleSell(String[] parts) { if (parts.length < 3) { return false; } String id = parts[1]; Stock s = StockControl.queryStock(id); if (s == null) { return false; } int amount; try { amount = Integer.parseInt(parts[2]); } catch (IllegalArgumentException e) { return false; } if (UserControl.canSell(uid, id, amount)) { UserControl.sellStock(uid, id, amount); /* double balance = UserControl.getBalance(uid); balance += s.getPrice() * amount; UserControl.setBalance(uid, balance); */ int newInventory = s.getInventory() + amount; StockControl.setInventory(id, newInventory); return true; } return false; }
92275156-9a0c-4406-a53e-699e85267234
0
public void removeObserver() { // listObserver = new ArrayList<Observer>(); }
58536df1-ee2c-4cf5-87f8-50a6d58fb314
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FChat.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 FChat().setVisible(true); } }); }
8496a3e8-0284-4508-8220-ebf8f0ea3547
3
*/ public void updateRowHeightsIfNeeded(Collection<Column> columns) { if (dynamicRowHeight()) { for (Column column : columns) { if (column.getRowCell(null).participatesInDynamicRowLayout()) { updateRowHeights(); break; } } } }
66bd4645-19e3-4fa2-895a-e436e72213b1
2
public RoadList() { initComponents(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); RoadList.setAutoCreateRowSorter(true); Color c = new Color(63,70,73); TableRowSorter<TableModel> sorter = new TableRowSorter<>(RoadList.getModel()); jScrollPane1.setBorder(null); RoadList.setRowSorter(sorter); RoadList.setFillsViewportHeight(true); RoadList.setShowHorizontalLines(false); RoadList.setShowVerticalLines(true); JTableHeader header = RoadList.getTableHeader(); Color bgcolor = new Color(45,47,49); Color focolor = new Color(244,244,244); header.setBackground(bgcolor); header.setForeground(focolor); header.setBorder(null); getContentPane().setBackground(c); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(SwingConstants.CENTER); TableColumn AlignementCol; for(int i = 0; i < modele.getColumnCount(); i++) { AlignementCol= RoadList.getColumnModel().getColumn(i); AlignementCol.setCellRenderer(renderer); } for(int i = 0; i < modele.getColumnCount(); i++) { TableColumn column = RoadList.getColumnModel().getColumn(i); column.setHeaderRenderer(new CustomCellRender()); } //end set header border:disabled Color HeaderColorBackground = new Color(34,168,108); header.setBackground(HeaderColorBackground); RoadList.getColumnModel().getColumn(6).setCellRenderer(new Filtres()); }
c49dad0f-fcae-4fe6-b30e-412d9a47cf08
4
@Override public void onCoreRoomRequest(GetRoomRequest request) { String roomName = request.getRoomName(); if (!activeRooms.containsKey(roomName)) { try { if (validRoomName(roomName)) { if (!coreAdmin.destinationExists(roomName)) { coreAdmin.addDestination(roomName, false); System.out.println("Server created room: " + roomName); } activeRooms.put(roomName, new Room(roomName)); } } catch (JMSException e) { e.printStackTrace(); } } final GetRoomReply reply = new GetRoomReply(activeRooms.get(roomName)); serverCoreConnector.sendMessage(reply); activeRooms.get(roomName).setIsEmpty(false); }
e5b0d720-dd9f-4f5d-835f-8b8941c476b9
1
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File("C:/1.txt"); BufferedReader in = new BufferedReader(new FileReader(file)); String line; String subLine; while ((line = in.readLine()) != null) { char character = line.charAt(line.length() - 1); subLine = line.substring(0, line.length() - 2); System.out.println(subLine.lastIndexOf(character)); } in.close(); }
4e936567-b8ad-4db0-9868-03ab39bf6c91
5
@Override public boolean activate() { // Fam is !null, Has urns, and inv not full final boolean valid = workLeft(); if ((valid && (GraniteMiner.curState == GraniteMiner.Status.NONE))) { GraniteMiner.curState = THIS_STATE; } else if (!valid && (GraniteMiner.curState == THIS_STATE)) { GraniteMiner.curState = GraniteMiner.Status.NONE; } return ((GraniteMiner.curState == THIS_STATE) && valid); }
0b677914-501c-4cbd-8347-0939ea7971da
0
private void jButton0MouseMouseClicked(MouseEvent event) { this.dispose(); }
6c75cc9f-c049-4d33-89c7-3c4f5ae8425e
3
public void save() { if (poms != null) { try { init(); PrintWriter out = new PrintWriter(new FileWriter(poms)); out.println("# List of POM files for the package"); out.println("# Format of this file is:"); out.println("# <path to pom file> [option]*"); out.println("# where option can be:"); out.println("# --ignore: ignore this POM and its artifact if any"); out.println("# --ignore-pom: don't install the POM. To use on POM files that are created"); out.println("# temporarily for certain artifacts such as Javadoc jars. [mh_install, mh_installpoms]"); out.println("# --no-parent: remove the <parent> tag from the POM"); out.println("# --package=<package>: an alternative package to use when installing this POM"); out.println("# and its artifact"); out.println("# --has-package-version: to indicate that the original version of the POM is the same as the upstream part"); out.println("# of the version for the package."); out.println("# --keep-elements=<elem1,elem2>: a list of XML elements to keep in the POM"); out.println("# during a clean operation with mh_cleanpom or mh_installpom"); out.println("# --artifact=<path>: path to the build artifact associated with this POM,"); out.println("# it will be installed when using the command mh_install. [mh_install]"); out.println("# --java-lib: install the jar into /usr/share/java to comply with Debian"); out.println("# packaging guidelines"); out.println("# --usj-name=<name>: name to use when installing the library in /usr/share/java"); out.println("# --usj-version=<version>: version to use when installing the library in /usr/share/java"); out.println("# --no-usj-versionless: don't install the versionless link in /usr/share/java"); out.println("# --dest-jar=<path>: the destination for the real jar."); out.println("# It will be installed with mh_install. [mh_install]"); out.println("# --classifier=<classifier>: Optional, the classifier for the jar. Empty by default."); out.println("# --site-xml=<location>: Optional, the location for site.xml if it needs to be installed."); out.println("# Empty by default. [mh_install]"); out.println("#"); for (String pomPath: pomOptions.keySet()) { out.println(pomPath + getPOMOptions(pomPath)); } out.flush(); out.close(); } catch (Exception e) { log.log(Level.SEVERE, "Unable to write the list of poms " + poms, e); } } }
b072e299-6e2f-41c5-97d3-570dd1dbc8c5
1
public Object getCurrentElement() throws IteratorException { Object obj = null; // Will not advance iterator if (list != null) { int currIndex = listIterator.nextIndex(); obj = list.get(currIndex); } else { throw new IteratorException(); } return obj; }
eda0d5d2-8d6d-4471-af43-0592d30ae4a4
3
public boolean singleWord() { return (this.a==null || this.b == null) && !(this.a == null && this.b == null); }
50aeafb6-949a-4ee6-a0bc-3dbb7ea9485c
9
static private int jjMoveStringLiteralDfa4_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0); return 4; } switch(curChar) { case 97: return jjMoveStringLiteralDfa5_0(active0, 0x800L); case 105: return jjMoveStringLiteralDfa5_0(active0, 0x2000L); case 114: if ((active0 & 0x400L) != 0L) return jjStartNfaWithStates_0(4, 10, 3); break; case 116: if ((active0 & 0x10000L) != 0L) return jjStartNfaWithStates_0(4, 16, 3); break; case 118: return jjMoveStringLiteralDfa5_0(active0, 0x4000L); default : break; } return jjStartNfa_0(3, active0); }
d66b22c4-4782-498a-95e1-2a2be143b25f
8
private boolean recursive(Peg x, Peg y, Peg z, int n) { Action newAction = null; if (n > 0) { newAction = new Action(x, z, y, getCurrAction(), 1, n-1); actions.push(newAction); if (!TowersOfHanoi.repaintAndWait()) {return false;} // move n-1 disks from x to z recursive(x, z, y, n - 1); actions.pop(); if (!TowersOfHanoi.repaintAndWait()) {return false;} newAction = new Action(x, y, z, getCurrAction(), 2, -1); actions.push(newAction); if (!TowersOfHanoi.repaintAndWait()) {return false;} TowersOfHanoi.moveCount++; // move top disk from x to y TowersOfHanoi.addLog(String.format("%4d. Perkeliamas %d diskas nuo %s ant %s\n", TowersOfHanoi.moveCount, x.getTopDiskNo(), x.name, y.name)); y.disks.push(x.disks.pop()); if (!TowersOfHanoi.repaintAndWait()) {return false;} actions.pop(); if (!TowersOfHanoi.repaintAndWait()) {return false;} newAction = new Action(z, y, x, getCurrAction(), 3, n-1); actions.push(newAction); if (!TowersOfHanoi.repaintAndWait()) {return false;} // move n-1 disks from z to y recursive(z, y, x, n - 1); actions.pop(); if (!TowersOfHanoi.repaintAndWait()) {return false;} } return true; }