text
stringlengths
14
410k
label
int32
0
9
public void set_safe(final long i, final Object value) { if (value instanceof Boolean) { setBoolean_safe(i, (Boolean) value); } else if (value instanceof Byte) { setByte_safe(i, (Byte) value); } else if (value instanceof Short) { setShort_safe(i, (Short) value); } else if (value instanceof Integer) { setInt_safe(i, (Integer) value); } else if (value instanceof Long) { setLong_safe(i, (Long) value); } else if (value instanceof Float) { setFloat_safe(i, (Float) value); } else if (value instanceof Double) { setDouble_safe(i, (Double) value); } else { throw new IllegalArgumentException("Unsupported type."); } }
7
public int candy2(int[] ratings) { int[] candies = new int[ratings.length]; // store the candies for (int i = 0; i < ratings.length; i++) { if (i == 0) candies[i] = 1; // base case else { if (ratings[i] > ratings[i-1]) { candies[i] = candies[i-1]+1; // plus one if bigger rate } else if (ratings[i] == ratings[i-1]) { candies[i] = 1; // if equal one is enough } else { candies[i] = 1; // default as minimum /*while (i-1 >= 0 && ratings[i] < ratings[i-1] && candies[i] >= candies[i-1]) { candies[i-1] += 1; i--; // decrement }*/ } } } for (int i = ratings.length-1; i >= 0; i--) { if (i-1 >= 0 && ratings[i-1] > ratings[i] && candies[i-1] <= candies[i]) { candies[i-1] = Math.max(candies[i-1], candies[i]+1); // choose the max one!! } //System.out.println(i+":"+Arrays.toString(candies)); } int sum = 0; for (int i = 0; i < candies.length; i++) { sum += candies[i]; } //System.out.println(Arrays.toString(candies)); return sum; }
9
public boolean pegIsAvailableToPlayer(int c, int r, int player) { if (player == 0) { if (c == 0 || c == boardSize_ - 1) return false; else return true; } else { if (r == 0 || r == boardSize_ - 1) return false; else return true; } }
5
public void run() { // While it's not stopped by internal error or external command while (runLoop){ // Wait for 5 seconds before actually refreshing // Get all peers from the database Table peer_address=db.getTableWithColumns("peer_address", new String[]{"peer_id", "address"}); @SuppressWarnings("unchecked") Column<String> peer_address_address_column=peer_address.getColumn("address"); // For each peer, try to connect and update list of peers here for (int i=0;i<peer_address_address_column.size();i++){ // Get address of this peer InetAddress peerAddress=new InetAddress(peer_address_address_column.getObjectAtRow(i)); SocketChannel test; try { System.out.printf("Trying to connect to %s:%d%n", peerAddress.adress, peerAddress.port); test=SocketChannel.open(); // I didn't figure out how to setup timeout test.socket().connect((new InetSocketAddress(peerAddress.adress, peerAddress.port))); // 2000 is a timeout specified in assignment instructions // At this point client is connected. // Get last sync date String peer_id=(String) peer_address.getColumn("peer_ID").getObjectAtRow(i); // Gets a peer_id. Since it should be the same, we can find this peer_id in peer table String lastSyncDate=db.getSingleField("SELECT last_sync_date FROM peer WHERE peer_id='"+peer_id+"'"); // Construct request // message example { 20130410202659.999Z, tables{ ... , ... }} Encoder ASNSyncRequest=new Encoder(); ASNSyncRequest.initSequence(); /* This is required request. Build it ASNSyncRequest ::= [APPLICATION 7] SEQUENCE { version UTF8String, -- currently 2 lastSnapshot GeneralizedTime OPTIONAL, tableNames [APPLICATION 0] SEQUENCE OF TableName OPTIONAL, -- orgFilter [APPLICATION 1] SEQUENCE OF OrgFilter OPTIONAL, -- address [APPLICATION 2] D_PeerAddress OPTIONAL, -- request [APPLICATION 3] SpecificRequest OPTIONAL, -- plugin_msg [APPLICATION 4] D_PluginData OPTIONAL, -- plugin_info [APPLICATION 6] SEQUENCE OF ASNPluginInfo OPTIONAL, -- pushChanges ASNSyncPayload OPTIONAL, signature NULLOCTETSTRING -- prior to version 2 it was [APPLICATION 5] } */ ASNSyncRequest.addToSequence(new Encoder("2")); // Version // We need a timestamp in Generalized Time ASNSyncRequest.addToSequence(new Encoder(db.getGeneralizedTime(lastSyncDate))); Encoder TableNames=new Encoder(); // Construct sequence of tables TableNames.initSequence(); TableNames.addToSequence(new Encoder("peer")); TableNames.addToSequence(new Encoder("peer_address")); ASNSyncRequest.addToSequence(TableNames); // Some lines are commented out, so I add signature ASNSyncRequest.addToSequence(new Encoder("NULL")); test.write(ByteBuffer.wrap(ASNSyncRequest.getBytes())); // Send Bytes over the network // Data sent, receive data, decode it and update database ByteBuffer serverResponse=ByteBuffer.allocate(4000); // Just cheat, read 1024 bytes, I'm tired and nothing works test.read(serverResponse); /* ASNDatabase ::= SEQUENCE { tables SEQUENCE OF Table, snapshot GeneralizedTime OPTIONAL } */ Decoder responseDecoder=(new Decoder(serverResponse.array())); if (LOG){ System.out.println("Recvd Data length: "+responseDecoder.getBytes().length); System.out.println("Recvd Data: "+responseDecoder.toString()); } responseDecoder=responseDecoder.getContent(); Decoder tablesDecoder=responseDecoder.getFirstObject(true).getContent(); // Decode peer and peer_address processEncodedTable(tablesDecoder.getFirstObject(true)); processEncodedTable(tablesDecoder.getFirstObject(true)); // String responseTime=responseDecoder.getFirstObject(true).getGeneralizedTime_(); if (LOG){ System.out.println("Response Time: "+responseTime); } // Process Database updateDB(); // For the current peer we should update Sync date db.executeSQL("UPDATE peer SET last_sync_date='"+Encoder.getGeneralizedTime(Calendar.getInstance())+"' WHERE peer_id='"+peer_id+"'"); //runLoop=false; // For the purposes of one-connection test, close the loop after first conneciton //runLoop=false; // Will throw an error when timeout is reached. Prints error. } catch (IOException e) { System.err.printf("[%s:%d Error]: Peer has timed out.", peerAddress.adress, peerAddress.port); //runLoop=false; }catch (Exception e) { System.err.println("Response Failed to decoded"); e.printStackTrace(); } } } // End of runLoop }
6
@Override public void setValueAt (Object val, int row, int column) { if ((column < 2) || (column > 2+ MainWindow.setupData.getEventLength ())) return; MainWindow.rosterDB.getRosters().get(row).setAvailability (MainWindow.setupData.getDateAt(column-2), val); fireTableDataChanged(); }
2
AbstractNode factor() { AbstractNode node = null; if (test(IDENT)) { if (testLookAhead(DOT) || testLookAhead(LBRAC)) { node = new ContentNode(selector()); } else { node = new ContentNode(constIdent()); } } else if (test(INT)) { node = integer(); } else if (test(STR)) { node = string(); } else if (test(READ)) { node = readParser(); } else if (test(LPAR)) { read(LPAR, "("); node = expr(); read(RPAR, ")"); } else { failExpectation("identifier, integer, string, read or (expression)"); } return node; }
7
public int numberVariables() { return (new HashSet(MAP.values())).size(); }
0
private void addLabyrinth(int height, int length) { for (int i = 1; i < height; i++) { for (int j = 1; j < length; j++) { if (border(i,j,length,height)) { super.addBricks(new Point(i, j)); } else if (centralBlock(i, j, length, height) && crossWithinCentralBlock(i, j, length, height)) { super.addBricks(new Point(i, j)); } } } }
5
private boolean setBooleanInitParameter(String parameterValue, boolean defaultValue) { if (null != parameterValue) { try { return "true".equalsIgnoreCase(parameterValue); } catch (Exception e) { return defaultValue; } } return defaultValue; }
2
public void onEnable() { inst = this; SkyQuest.onServer = true; qm = new QuestManager(); fm = new FileManager(); qlm = new QuestLogManager(this); if(!getDataFolder().exists()) { try { fm.saveData(getDataFolder(), qm); } catch (IOException e) { e.printStackTrace(); } } getServer().getPluginManager().registerEvents(new SkyQuestListener(this), this); getServer().getPluginManager().registerEvents(qlm, this); for(Player p:getServer().getOnlinePlayers()) { String name = p.getName(); if(qm.getQuestLog(name) == null) { PlayerQuestLog log = new PlayerQuestLog(name); qm.addQuestLog(log); } } getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){ public void run() { fm.loadData(getDataFolder(), qm); int ql = qm.getQuests().length; getLogger().info("Loaded " + ql + " quest" + (ql != 1 ? "s" : "")); int pl = qm.getQuestLogs().length; getLogger().info("Loaded " + pl + " player" + (pl != 1 ? "s" : "")); } }); getCommand("quest").setExecutor(new SkyQuestCmd(this)); questlog = new ItemStack(Material.WRITTEN_BOOK); BookMeta im = (BookMeta) questlog.getItemMeta(); im.setTitle(bookTitle); im.setAuthor(bookAuthor); questlog.setItemMeta(im); }
6
public List<Book> getBooksByBranch(int branch_id) { List<Book> list = new ArrayList<>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM book Inner Join bookstatus On bookstatus_id=bks_id WHERE branch_id= "+branch_id+" Order by bok_id"); while (rs.next()) { Book book = new Book(); book.setId(rs.getLong(1)); book.setTitle(rs.getString(2)); book.setSubtitle(rs.getString(3)); book.setIsbn(rs.getString(4)); book.setPublisher(rs.getString(5)); book.setPublishDate(rs.getDate(6)); book.setPagesNb(rs.getInt(7)); book.setBookCategory_id(rs.getLong(8)); book.setLanguage_id(rs.getLong(9)); book.setAuthor_id(rs.getLong(10)); book.setItem_id(rs.getLong(11)); book.setBookStatus_id(rs.getLong(12)); list.add(book); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } System.err.println(list.size()); return list; }
5
public double[] getNumberArrayProperty(String name) { int col = Util.findColumn(model, name); double[] a = new double[model.getRowCount()]; for (int i = 0; i < a.length; i++) { a[i] = ((Number) model.getValueAt(i, col)).doubleValue(); } return a; }
1
private static int countSlots(Expression[] exprs, int length) { int slots = 0; for (int i = 0; i < length; i++) slots += exprs[i].getType().stackSize(); return slots; }
1
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
public void renderSprite(int xp, int yp, Sprite sprite, boolean fixed) { if (!fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < sprite.getHeight(); y++) { int ya = y + yp; for (int x = 0; x < sprite.getWidth(); x++) { int xa = x + xp; if (xa < 0 || xa >= width || ya < 0 || ya >= height) continue; pixels[xa + ya * width] = sprite.pixels[x + y * sprite.getWidth()]; } } }
7
private static boolean propsEquals(Member member, Object o1, Object o2) { if (member == null) { throw new IllegalStateException("Member is null in propsEquals"); //return false; } try { if (member instanceof Field) { Field f = (Field)member; System.out.println(String.format("EqualsUtils.propsEquals(%s)", f.getName())); Object val1 = f.get(o1); Object val2 = f.get(o2); return val1.equals(val2); } else if (member instanceof Method) { Method m = (Method)member; String methodName = m.getName(); if (methodName.startsWith("set")) { // only test getters here - see TGS return true; } Object v1 = m.invoke(o1, new Object[0]); Object v2 = m.invoke(o2, new Object[0]); if (v1 == null && v2 == null) { return true; } if (v1 == null || v2 == null) { return false; } return v1.equals(v2); } else throw new IllegalArgumentException( "Internal error: member " + member + " neither Method nor Field"); } catch (Exception e) { e.printStackTrace(); return false; } /*NOTREACHED*/ }
9
public void setValue(String value) { this.value = value; }
0
private Integer[][] cross2(Integer[] t1, Integer[] t2, boolean randomCrossPosition) { int length = t1.length; int crossPosition1, crossPosition2; Integer[][] t = new Integer[6][length]; if (randomCrossPosition) { double d1, d2; d1 = Math.random() * length; d2 = Math.random() * length; crossPosition1 = (int) Math.min(d1, d2); crossPosition2 = (int) Math.max(d1, d2); } else { crossPosition1 = length / 3; crossPosition2 = crossPosition1 * 2; } for (int i = 0; i < length; ++i) { if (i < crossPosition1) { t[0][i] = t1[i]; t[1][i] = t1[i]; t[2][i] = t1[i]; t[3][i] = t2[i]; t[4][i] = t2[i]; t[5][i] = t2[i]; } else if (i >= crossPosition1 && i < crossPosition2) { t[0][i] = t1[i]; t[1][i] = t1[i]; t[2][i] = t2[i]; t[3][i] = t2[i]; t[4][i] = t1[i]; t[5][i] = t1[i]; } else { t[0][i] = t1[i]; t[1][i] = t2[i]; t[2][i] = t1[i]; t[3][i] = t2[i]; t[4][i] = t1[i]; t[5][i] = t2[i]; } } return t; }
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success && (target.phyStats().level() < ((mob.phyStats().level() + super.getXLEVELLevel(mob))/2))) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,L("^S<S-NAME> @x1 for <T-NAME> to die.^?",prayForWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); CMLib.combat().postDeath(target, target, null); DeadBody body=null; for(Enumeration<Item> i=mob.location().items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I instanceof DeadBody)&&(((DeadBody)I).getMobName().equals(target.Name()))) body=(DeadBody)I; } if(body==null) mob.tell(L("The death did not appear to create a body!")); else beneficialAffect(mob, body, asLevel, 0); } } else return maliciousFizzle(mob,target,L("^S<S-NAME> @x1 <T-NAME> to die, but nothing happens.^?",prayForWord(mob))); // return whether it worked return success; }
9
private int levelAuxPrefixFree(Node focusNode,int level, int usedLevel) { if (level==1){ if (usedLevel>0 & !focusNode.isUsed()) if (focusNode.setLUsed()) usedLevel--; //FIll 0 first if (usedLevel>0 & !focusNode.isUsed()) if (focusNode.setRUsed()) usedLevel--; } else{ if (usedLevel>0 & !focusNode.leftChild.isUsed() ){ usedLevel=levelAuxPrefixFree(focusNode.leftChild,level-1, usedLevel); } if (usedLevel>0 & !focusNode.rightChild.isUsed() ) { usedLevel=levelAuxPrefixFree(focusNode.rightChild,level-1, usedLevel); } } return usedLevel; }
7
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof ConsoleCommandSender) { sender.sendMessage("§cThis can only be run in game!"); return true; } if(args.length== 1) return false; if(args.length>= 3) { Player p = (Player) sender; String action = args[1]; String name = args[2]; if(action.equalsIgnoreCase("create")) { if(GameManager.isGame(name)) { p.sendMessage("§cA game with that name already exists!"); return true; } WorldEditPlugin we = Main.we; Selection selection = we.getSelection(p); if(selection!= null) { Location min = selection.getMinimumPoint(); Location max = selection.getMaximumPoint(); Game game = new Game(name, min, max); GameManager.addGame(game); p.sendMessage(Main.tag+"§aNew game called §3"+name+"§a created!"); } else p.sendMessage("§cPlease make a selection first!"); } else if(action.equalsIgnoreCase("delete")) { if(GameManager.isGame(name)) { Game game = GameManager.getGame(name); game.delete(); GameManager.removeGame(game); p.sendMessage(Main.tag+name+"§a deleted!"); } else { p.sendMessage("§cA game with that name could not be found!"); } } } return true; }
8
String reformatExpression(String exp) { int i = 0; char it; int itCount; boolean haveStar; StringBuffer buff = new StringBuffer(); int size = exp.length(); while (i < size) { it = exp.charAt(i); itCount = 1; haveStar = false; char next; if (i < size - 1) next = exp.charAt(i + 1); else next = '\0'; while ((next == it || next == '*') && (i < size - 1)) { if (next == it) itCount++; else { haveStar = true; itCount--; } i++; if (i < size - 1) next = exp.charAt(i + 1); else next = '\0'; } for (int j = 0; j < itCount; j++) buff.append(it); if (haveStar) { buff.append(it); buff.append('*'); } ; i++; } return buff.toString(); }
9
private static void displayMovesInVector(Vector<Move> v){ for(Move m:v){ m.display(); System.out.print(", "); } System.out.println(); }
1
public synchronized void deleteWay(int pos, long wayId) { if (ways.size() > pos) ways.get(pos).remove(wayId); }
1
public void setReleaseTime(Date time) { if (time == null) throw new IllegalArgumentException("Time cannot be null"); this.releaseTime = time; }
1
@Override public void display(int depth) { StringBuffer buff = new StringBuffer(); for (int i = 0; i < depth; i++) { buff.append('-'); } System.out.println(buff + " " + getName()); }
1
public List<CompositeInstance> getFilteredInstances(){ return this.instances; }
0
public int longestConsecutive(int[] num) { HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>(); int len = num.length; if(len < 2) { return len; } int max = 1; for(int i=0;i<len;i++) { map.put(num[i], true); } for(int i=0;i<len;i++) { int current = num[i]; int count = 1; int left = num[i]-1; int right = num[i] +1; while(map.containsKey(left) && map.get(left)) { count++; map.put(left, false); left--; } while(map.containsKey(right) && map.get(right)) { count++; map.put(right, false); right++; } if(count > max) { max = count; } } return max; }
8
public static void count_words(String s) { boolean wordStarted = false; int wCount = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); boolean letter = ch != ' ' && ch != ','; if (letter) { wordStarted = true; } else { if (wordStarted) { wCount++; } wordStarted = false; } } System.out.println(wCount); }
4
public void sendData(ObjectOutputStream[] streams, double time, int newPlayer){ for(int i=0;i<streams.length;i++){ if(streams[i] == null) continue; try { streams[i].writeDouble(time); streams[i].flush(); } catch (Exception e) { System.out.println("issue in GameMechanics.sendData"); e.printStackTrace(); } } }
3
public void initTokenClasses() { table.println("package lexer;"); table.println(" "); table.println("/**"); table.println(" * This file is automatically generated<br>"); table.println(" * it contains the table of mappings from token"); table.println(" * constants to their Symbols"); table.println("*/"); table.println("public class TokenType {"); table.println(" public static java.util.HashMap<Tokens,Symbol> tokens = new java.util.HashMap<Tokens,Symbol>();"); table.println(" public TokenType() {"); symbols.println("package lexer;"); symbols.println(" "); symbols.println("/**"); symbols.println(" * This file is automatically generated<br>"); symbols.println(" * - it contains the enumberation of all of the tokens"); symbols.println("*/"); symbols.println("public enum Tokens {"); symbols.print(" BogusToken"); while (true) { try { getNextToken(); } catch (IOException e) {break;} String symType = "Tokens." + type; table.println(" tokens.put(" + symType + ", Symbol.symbol(\"" + value + "\"," + symType + "));"); if (tokenCount % 5 == 0) { symbols.print(",\n "+ type); } else { symbols.print("," + type); } } table.println(" }"); table.println("}"); table.close(); symbols.println("\n}"); symbols.close(); try { in.close(); } catch (Exception e) {} }
4
public static void addSchool() { System.out.print("Connection add school ... "); //Connexion à la base BaseSetting bs = new BaseSetting(); if (bs.testerConnexion()) { System.out.println("success"); try (Scanner sc = new Scanner(System.in)) { //On récupère le nom de l'école voulu System.out.println("School's name"); String name = sc.nextLine(); //Insertion dans la base if (addSchoolWithName(bs, name)) { //Insertion success System.out.println(getColor(91) + "Add success !\n" + getColor(92) + "Run BMG Program now ? (Y/n)" + getColor(0)); String again = sc.nextLine(); //Lancemenent du programme if (again.equals("Y") || again.equals("y")) { BmgFrame frame = new BmgFrame("BMG 2014", 800, 600, true); } else { } } else { //Erreur lors de l'insertion System.out.println(getColor(91) + "Ohoh, error... Try again ? (Y/n)" + getColor(0)); String again = sc.nextLine(); if (again.equals("Y") || again.equals("y")) { addSchool(); } else { } } } } }
6
@Override public void setAttemptClientConnect(IAttemptClientConnect attemptClientConnect) { this.attemptClientConnect = attemptClientConnect; }
0
public int[] getTemplatePixels(int x0, int y0, int x1, int y1) { int retPixels[] = new int [735]; /* 21*35 */ int xLen, yLen, sX, sY, cX, cY, oX, oY; double xInc, yInc, nY, scale; xLen = x1 - x0; yLen = y1 - y0; /* distance between the eyes is 23 pixels from experiences */ xInc = (double)xLen / 23d; yInc = (double)yLen / 23d; /*scale factor */ scale = Math.sqrt(Math.pow(xLen,2)+Math.pow(yLen,2))/23d; /* 6 from (35 - 23) / 2 and 8 because the eyes are on the 8 row from experiments */ oX = x0 - (int)(6 * xInc) + (int)(8 * yInc); nY = (yLen != 0) ? ((8 * yInc) * xLen / yLen) : (8 * scale); oY = y0 - (int)nY; /* rotate the template to a horizontal position */ sX = oX; sY = oY; for (int y = 0; y < 21; y++) { cX = sX; cY = sY; for (int x = 0; x < 35; x++) { if ((cX >= 0) && (cX < width) && (cY < height) && (cY >= 0)) { retPixels[y * 35 + x]= pixels[cY * width + cX]; } cX = sX + (int)((x + 1) * xInc); cY = sY + (int)((x + 1) * yInc); } sX = oX - (int)((y + 1) * yInc); sY = oY + (int)((y + 1) * xInc); } return retPixels; }
7
public void put(K key, V value) { //if hashmap size is more than a certain load //its time to rehash the array if(size >= max_size*loadFactor ){ //double the max_size max_size *= 2; //temporarily copy the old array Entry []temp = new Entry[max_size]; System.arraycopy(store, 0, temp, 0, store.length); // create a clean copy of expanded old array store = new Entry[max_size]; //reset the size of old array size = 0; //iterate the temporary copy and put all the values back in expanded old array for(int i=0; i<max_size/2; i ++){ Entry<K,V> node = temp[i]; //there could be a linked list inside while(node!=null){ //recursively call put put(node.key, node.value); node = node.next; } } } //trick to avoid negative hash code and hash value more than Integer.MAX_VALUE int hashcode = key.hashCode(); int index = (hashcode & 0x7fffffff) % max_size; if(store[index]!=null){ Entry<K,V> target = store[index]; //update the value scenario while(target!=null){ if(target.key.equals(key) && target.hashcode == hashcode){ target.value = value; return; } target = target.next; } // create new entry Entry<K,V> newEntry = new Entry(hashcode,key,value,store[index]); store[index] = newEntry; size ++; } else { Entry<K,V> newEntry = new Entry(hashcode,key,value,null); store[index] = newEntry; size ++; } }
7
@Override public String getDescription() { // This description will be displayed in the dialog, // hard-coded = ugly, should be done via I18N return "Assembly files (*.asm)"; }
0
public Territory(GoGame game1) { game = game1; squares = new HashSet<Square>(); }
0
public static String getNick(String name) { if (name.startsWith(":")) name = name.substring(1); if (name.startsWith("#")) return name; else if (name.length() > 0 && name.indexOf('!') >= 0) { name = name.split("!")[0]; return name; } return name; }
4
public int recordReturnType(CtClass type, boolean useResultVar) throws CompileError { gen.recordType(type); return gen.recordReturnType(type, "$r", (useResultVar ? resultVarName : null), stable); }
1
public void generateObj() { try { Class<?> clazz = Class.forName("com.rock.reflect.User"); //默认调用无参构造器 Object u1 = clazz.newInstance(); System.out.println(u1); //获取构造方法,再调用 Constructor<?> constructor = clazz.getConstructor(int.class,String.class); Object u2 = (User) constructor.newInstance(1,"rock"); System.out.println(u2); System.out.println("username:"+((User)u2).getUserName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
9
public void closeChat() { if (cbtn != null) cbtn.click(); }
1
public static void main(String[] args) throws InterruptedException { final Random randomizer = new Random(); final Bank bank = new Bank("Native", Math.abs(randomizer.nextLong())); final Account[] accounts = new Account[ACCOUNTS_COUNT]; double totalAmount = 0.d; for (int i = 0; i < accounts.length; i++) { accounts[i] = new Account(i, randomizer.nextDouble() * 1200.d); totalAmount += accounts[i].getBalance(); } final CountDownLatch latch = new CountDownLatch(1); class Worker extends Thread { @Override public void run() { ThreadLocalRandom random = ThreadLocalRandom.current(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } bank.transfer(accounts[random.nextInt(0, ACCOUNTS_COUNT)], accounts[random.nextInt(0, ACCOUNTS_COUNT)], random.nextDouble(0, 320.d)); } } Thread[] threads = new Thread[THREADS_COUNT]; for (Thread thread : threads) { thread = new Worker(); thread.start(); } latch.countDown(); for (Thread thread : threads) { if (thread != null && thread.isAlive()) thread.join(); } double finalAmount = 0.d; for (int i = 0; i < accounts.length; i++) { finalAmount += accounts[i].getBalance(); } System.out.println("Initial bank balance was: " + String.format("%.6f", totalAmount)); System.out.println("Final bank balance is: " + String.format("%.6f", finalAmount)); }
6
public void mouseReleased(MouseEvent evt) { boolean orderChanged = false; for (int i=0; i<slotList.size(); ++i) { Slot slot = slotList.get(i); if (!slot.isDragged()) continue; if (insertBeforeSlotIndex >= 0) { orderChanged = true; animation.moveCell(i, insertBeforeSlotIndex); // TODO: do a command for this } } // relayout slots if (orderChanged) { setAnimation(animation); } for (int i=0; i<slotList.size(); ++i) { Slot slot = slotList.get(i); slot.setDragged(false); } if (orderChanged && insertBeforeSlotIndex < slotList.size()) slotList.get(insertBeforeSlotIndex).setSelected(true); insertBeforeSlotIndex = -1; }
7
private static boolean validTile(ITile[][] map, int x, int y) { return (x >= 0 && x < map.length) && (y >= 0 && y < map[0].length) && map[x][y].isPassable(); }
4
public boolean salvar(Usuario usuario) { if(usuario.getNome()==null || usuario.getNome().equals("")){ return false; } if(usuario.getLogin()==null || usuario.getLogin().equals("")){ return false; } usuariosBancoDeDados.put(usuario.getId(), usuario); return true; }
4
public void refreshSearches () { // refresh da search panel int pageSize = pages.size(); // holds total # of pages at the time this method is called for (int i = pageSize-1; i > 0; i --) { // loop through pages remove(pages.get(i)); // remove page from panel pages.remove(pages.get(i)); // remove page from arraylist } for (int i = 0; i < displayedSearchResults.size(); i ++) { // loop through search results remove(displayedSearchResults.get(i).getDisplayText()); // remove text from panel remove(displayedSearchResults.get(i).getUserButton()); // remove button from panel } displayedSearchResults.removeAll(displayedSearchResults); // empty search results }
2
public static void genTagOuput(TagletManager tagletManager, Doc doc, Taglet[] taglets, TagletWriter writer, Content output) { tagletManager.checkTags(doc, doc.tags(), false); tagletManager.checkTags(doc, doc.inlineTags(), true); Content currentOutput = null; for (int i = 0; i < taglets.length; i++) { currentOutput = null; if (doc instanceof ClassDoc && taglets[i] instanceof ParamTaglet) { //The type parameters are documented in a special section away //from the tag info, so skip here. continue; } if (taglets[i] instanceof DeprecatedTaglet) { //Deprecated information is documented "inline", not in tag info //section. continue; } try { currentOutput = taglets[i].getTagletOutput(doc, writer); } catch (IllegalArgumentException e) { //The taglet does not take a member as an argument. Let's try //a single tag. Tag[] tags = doc.tags(taglets[i].getName()); if (tags.length > 0) { currentOutput = taglets[i].getTagletOutput(tags[0], writer); } } if (currentOutput != null) { tagletManager.seenCustomTag(taglets[i].getName()); output.addContent(currentOutput); } } }
7
public void SaveFile(String path, String FileContent, boolean CleanFileContent, String type) { FileWriter file; BufferedWriter writer; Calendar calendar = new GregorianCalendar(); // Fecha y hora actuales. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss"); // Formato de la fecha. String dateS = dateFormat.format(calendar.getTime()); // Fecha y hora actuales formateadas. // Variable para captura ranking y variable para guardar el contenido en un archivo. path = path.substring(0, path.length() - 5) + "-" + type + "-" + dateS + ".txt"; try { file = new FileWriter(path, CleanFileContent); writer = new BufferedWriter(file); writer.write(FileContent, 0, FileContent.length()); writer.close(); file.close(); } catch (IOException ex) { ex.printStackTrace(); } }
1
public String addNewBook() { // on récupère les données du formulaire String bookTitle = book.getBookTitle(); String bookAuthor = book.getBookAuthor(); String bookSummary = book.getBookSummary(); Integer bookType = book.getBookType(); //Integer bookState = book.getBookState(); Integer bookState = 1; // 1 : libéré, 2 :capturé String bookLocation = book.getBookLocation(); Integer userId = bookRelease.getRlsUsrId(); if( bookTitle == null || bookTitle.isEmpty() ) { addActionError("Vous devez saisir un titre"); return INPUT; } else if( bookAuthor == null || bookAuthor.isEmpty() ) { addActionError("Vous devez saisir un auteur"); return INPUT; } else if( bookType == null || bookType < 1 ) { addActionError("Vous devez choisir un genre"); return INPUT; } else if( bookLocation == null || bookLocation.isEmpty() ) { addActionError("Vous devez choisir un lieu de dépôt"); return INPUT; } // Si il n'y a pas d'erreurs on créé un nouveau livre else { boolean creation = bookDAO.addBook(bookTitle, bookAuthor, bookSummary, bookType, bookState, bookLocation); // Si le livre est bien créé, on le libère if (creation) { this.book = bookDAO.getBook(); return releaseBook(userId, book.getBookId()); } else { addActionError("Le livre n'a pas pu être enregistré"); return INPUT; } } }
9
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(args.length == 1) { if(args[0].equalsIgnoreCase("help")) { // show help! showHelp(sender); return true; } } if(plugin.commands.containsKey(label)) { boolean hasPermission = true; if(sender instanceof Player) { hasPermission = plugin.hasPermission((Player)sender, plugin.commands.get(label).requiredPermission()); } if(hasPermission) { if(!plugin.commands.get(label).onCommand(sender, args)) returnMessage(sender, "&cInvalid command usage!"); } else { returnMessage(sender, "&cYou don't have permission for that!"); } } return true; }
6
public void display() { win2.pushMatrix(); // translate to coordinates of center of top of t1 int height; int h1 = myWall.getT1().getHeight(); int h2 = myWall.getT2().getHeight(); if (x < Animation.WALL_WID / 2) { height = h1; } else if (x > Animation.WALL_LEN + Animation.WALL_WID / 2) { height = h2; } else { height = h1 + (int)((h2 - h1) * (x - Animation.WALL_WID/2.0) / Animation.WALL_LEN); } win2.translate(myWall.getT1().getX() + Animation.WALL_WID/2, height, myWall.getT1().getZ() + Animation.WALL_WID/2); // rotate so current is running left to right. if (myWall.getT1().getZ() > myWall.getT2().getZ()) { win2.rotateY(win2.PI / 2); } else if (myWall.getT1().getX() > myWall.getT2().getX()) { win2.rotateY(win2.PI); } else if (myWall.getT1().getZ() < myWall.getT2().getZ()) { win2.rotateY(3 * win2.PI / 2); } // draw sphere at appropriate height (tower or wall height) win2.translate((float)x, -RADIUS, 0); win2.sphere(RADIUS); // draw Ski lifts to push balls through batteries if (myWall.getPosEnd() != null) // if this wall is a Battery... { //Draw elevator (box) behind sphere if ( myWall.getT2().equals(myWall.getPosEnd()) ) // if positive Terminal is on the right... { win2.translate(-RADIUS, 0, 0); } else // if positive terminal is on the left... { win2.translate(RADIUS, 0, 0); } win2.box( 5, (int)(1.5 * RADIUS), (int)(1.5 * RADIUS) ); } win2.popMatrix(); }
7
public boolean foundResult(Map<Variable, Term> result) { // Print the whole combination of variables that satisfies the evaluated query. Iterator<Map.Entry<Variable, Term>> bindings = result.entrySet().iterator(); while (bindings.hasNext()) { Map.Entry<Variable, Term> binding = bindings.next(); output.printf("%s = %s", binding.getKey().getName(), binding.getValue()); if (bindings.hasNext()) { output.println(); } } if (result.isEmpty()) { System.out.println("true"); // In this case, it doesn't make sense to continue. return false; } else { // .. and afterwards ask the user whether he wants to see another proof. char c = 0; while (c != ';' && c != ',') { try { c = (char) console.read(); } catch (IOException ex) { System.out.println("An I/O error occurred, please repeat."); } } // If the user enters ',', the evaluator looks for another way to prove the query. return c == ','; } }
6
@Test public void canDetermineTheColumnFitnessOfAGrid() { for (int sudokuPower = 1; sudokuPower < 10; sudokuPower++) { // all columns are valid but the first one for (int i = 0, size = sudoku.getGridLength(); i < size; i++) { if (i == 0) continue; sudoku.randomizeColumn(i); } assertThat(sudoku.determineColumnFitness()).isEqualTo((sudoku.getGridLength() - 1f) / sudoku.getGridLength()); } }
3
public static void removeRate(int rateId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("DELETE FROM Rates WHERE rate_id = ?"); stmnt.setInt(1, rateId); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); } catch(SQLException e){ System.out.println("Remove fail: " + e); } }
4
private void setListeners() { /* * The action listener for remove carriage button */ btnRemove.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { theTrain.removeCarriage(); } catch (TrainException e1) { e1.printStackTrace(); } reconfigure(); } }); /* * The action listener for add freight car button */ btnFreightcar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FreightCarChoice freiChoice = new FreightCarChoice( MainPage.this.frame, theTrain); freiChoice.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); freiChoice.setVisible(true); reconfigure(); } }); /* * The action listener for add passenger car button */ btnPassengercar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PassengerCarChoice passChoice = new PassengerCarChoice( MainPage.this.frame, theTrain); passChoice.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); passChoice.setVisible(true); reconfigure(); } }); /* * The action listener for add locomotive button */ btnLocomotive.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { LocomotiveChoice locoChoice = new LocomotiveChoice( MainPage.this.frame, theTrain); locoChoice.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); locoChoice.setVisible(true); reconfigure(); } }); /* * The action listener for reset button */ btnReset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { passengersOnBoard = 0; totalSeats = 0; power = 0; totalWeight = 0; passengersRefused = 0; theTrain = new DepartingTrain(); reconfigure(); } }); /* * The action listener for board button */ btnBoard.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int toBoard = Integer.parseInt((spinnerToBoard.getValue() .toString())); RollingStock r = theTrain.firstCarriage(); int remaining = (totalSeats - passengersOnBoard); // now, remaining == seats available remaining = remaining > toBoard ? toBoard : remaining; // now, remaining == number to board passengersRefused += toBoard - remaining; passengersOnBoard += remaining; r = theTrain.nextCarriage(); while (r != null && r.getClass().getName() == "asgn2RollingStock.PassengerCar" && remaining > 0) { if (remaining > ((PassengerCar) r).numberOfSeats() - ((PassengerCar) r).numberOnBoard()) { try { int tmpBoarding = ((PassengerCar) r) .numberOfSeats() - ((PassengerCar) r).numberOnBoard(); ((PassengerCar) r).board(tmpBoarding); remaining -= tmpBoarding; } catch (TrainException e1) { e1.printStackTrace(); } } else { try { ((PassengerCar) r).board(remaining); remaining = 0; } catch (TrainException e1) { e1.printStackTrace(); } } r = theTrain.nextCarriage(); } reconfigure(); } }); }
8
long findRecordStart(long pos) { try { raf.seek(pos); int len = 0; for (long p = pos; (len = raf.read(buffer)) > 0; p += len) { for (int idx = 0; idx >= 0;) { // Find '\n@' in this buffer idx = findNl(buffer, idx); if (idx >= 0) { idx++; if ((idx < buffer.length) && (buffer[idx] == '@')) { // Is there a '@\n'? => This is probably a record start // Note: It may be a quality line that has the first base quality of 31 (i.e. '@' in phred-33 coding) if (isRecordStart(buffer, idx)) { long recordStart = p + idx; return recordStart; } } } } } } catch (IOException e) { throw new RuntimeException(e); } return -1; }
7
@Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Point other = (Point) obj; if(!Arrays.equals(components, other.components)) return false; if(dimension != other.dimension) return false; return true; }
5
} // ----------------------------------------------------------------------- @Override public DateTimeValueRange range(DateTimeField field) { if (field instanceof ChronoField) { ChronoField f = (ChronoField) field; if (f.isDateField()) { switch (f) { case DAY_OF_MONTH: return DateTimeValueRange.of(1, lengthOfMonth()); case DAY_OF_YEAR: return DateTimeValueRange.of(1, lengthOfYear()); case ALIGNED_WEEK_OF_MONTH: return DateTimeValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5); case YEAR_OF_ERA: return (getYear() <= 0 ? DateTimeValueRange.of(1, MAX_YEAR + 1) : DateTimeValueRange.of(1, MAX_YEAR)); } return field.range(); } throw new DateTimeException("Unsupported field: " + field.getName()); }
9
public static String getAttributeName(int index) { switch (index) { case 0: return "STR"; case 1: return "DEX"; case 2: return "CON"; case 3: return "INT"; case 4: return "WIS"; case 5: return "CHA"; } return "BAD"; }
6
@Override public List<Integer> loadArrayFromFile(String path) { if (path == null) { throw new IllegalArgumentException("Path is not specified!"); } List<Integer> list = new ArrayList<Integer>(); String line; BufferedReader bufferedReader = null; try { FileInputStream fileInputStream = new FileInputStream(path); // reading the primitive data from the input stream DataInputStream dataInputStream = new DataInputStream(fileInputStream); // read data efficiently as characters bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream)); // processing the lines in file while ((line = bufferedReader.readLine()) != null) { processLine(line, list); } } catch (IOException e) { throw new RuntimeException("File not found!"); } finally { // closing bufferedReader try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ignored) { } } return list; }
5
static final public void repeticao() throws ParseException { trace_call("repeticao"); try { jj_consume_token(WHILE); jj_consume_token(A_PARENTESES); expressao(); jj_consume_token(F_PARENTESES); jj_consume_token(A_CHAVES); label_2: while (true) { comando(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NUMBER: case STRING: case IF: case WHILE: case OUTPUT: case INPUT: case VARIAVEL: ; break; default: jj_la1[8] = jj_gen; break label_2; } } jj_consume_token(F_CHAVES); } finally { trace_return("repeticao"); } }
9
public boolean checkBox (int row, int col) { int i = 0, j = 0, k = 0, count = 0; /* Uses nested for loops to check the entries */ for (k = 1; k < 10; k++) { for (i = row; i < row+4; i++) { for (j = col; j < col+4; j++) { count = 0; if (k == Integer.parseInt(entries[i][j].getText())){ count++; } if (count >= 2) { System.out.println("checkBox() returned false at i: " + i + " j: "+ j + " with " + entries[i][j].getText()); return false; } } } } return true; }
5
void getNewMessages(DateTime loopTime) throws Exception{ //Clean up of buffers goes here! Because we don't want to itterate over the new messages as we know //they are new! //1. First, we clean up. for (Vessel v: theVessels){ v.theTrackBuffer.cleanBuffer(theOptions.trackHistoryLength); } //2. We fetch messages in our time window //2.1 Setup a connection Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(theOptions.dbAISURL,theOptions.dbAISLogin,theOptions.dbAISPassword); Statement stmtIncomingMessages = con.createStatement(); Integer noMessages; String qryMessages = "SELECT * FROM `" + theOptions.dbAISName + "`.`" + theOptions.dbAISTableName + "`"; String minDate = loopTime.minusSeconds(theOptions.stepTime).toString("yyyy-MM-dd"); String maxDate = loopTime.toString("yyyy-MM-dd"); String minTime = loopTime.minusSeconds(theOptions.stepTime).toString("HH:mm:ss"); String maxTime = loopTime.toString("HH:mm:ss"); String filter = ""; //2.2 determine some filter settings for the query if (theOptions.filterVessel) { filter = " WHERE mmsi=" + theOptions.filterMMSI.toString() + " AND TIMESTAMPDIFF(SECOND, TIMESTAMP(date,time),'" + minDate + " " + minTime + "') <= 0" + " AND TIMESTAMPDIFF(SECOND, TIMESTAMP(date,time),'" + maxDate + " " + maxTime + "') >= 0" + ";"; } else { filter = " WHERE TIMESTAMPDIFF(SECOND, TIMESTAMP(date,time),'" + minDate + " " + minTime + "') <= 0" + " AND TIMESTAMPDIFF(SECOND, TIMESTAMP(date,time),'" + maxDate + " " + maxTime + "') >= 0" + ";"; } //2.3 fetch messages ResultSet newMessages = stmtIncomingMessages.executeQuery(qryMessages + filter); noMessages = 0; try { newMessages.last(); noMessages = newMessages.getRow(); newMessages.first(); } catch(Exception ex){ return; } //3. Process the messages into position reports if (noMessages > 0) { do { DateTime timeStamp; Double theLon, theLat, lat, lon, cog, sog; Integer navStatus, theMMSI; String msgDate, msgTime; theLat = newMessages.getDouble("latitude"); theLon = newMessages.getDouble("longtitude"); //don't ask if (theLon > 3.0 && theLon < 6.0){ if (theLat > 51.5 && theLat < 54.5){ theMMSI = newMessages.getInt("mmsi"); Vessel myVessel = addVessel(theMMSI, theVessels); msgDate = newMessages.getDate("date").toString(); msgTime = newMessages.getTime("time").toString(); timeStamp = parseDBDateTime(msgDate,msgTime); PositionReport newPoint = myVessel.theTrackBuffer.addPoint(timeStamp); newPoint.latitude = newMessages.getDouble("latitude"); newPoint.longitude = newMessages.getDouble("longtitude"); //don't ask newPoint.cog = newMessages.getDouble("cog"); newPoint.sog = newMessages.getDouble("sog"); newPoint.navigationStatus = newMessages.getInt("navigation_status"); newPoint.rot = newMessages.getInt("rot"); } } } while(newMessages.next()); } //4. close and cleanup newMessages.close(); stmtIncomingMessages.close(); con.close(); }
9
@Override public int compare(Device arg0, Device arg1) { if (arg1.getPrice() > arg0.getPrice()){ return 1; } else if(arg0.getPrice() > arg1.getPrice()){ return -1; } return 0; }
2
@Override public void freeze() { if(!used && global) { global = false; } }
2
private static List <File> directoryFiles(String path, String extension) { List <File> allFiles = new ArrayList <File> (); allFiles.add(new File(path)); int index = 0; while (index != allFiles.size()) { File currentFile = allFiles.get(index); if (currentFile.isDirectory()) { allFiles.remove(index); for (File newFile : currentFile.listFiles()) allFiles.add(newFile); } else if (!currentFile.getPath().endsWith(extension)) allFiles.remove(index); else index++; } return allFiles; }
4
@Override public void setData(ByteBuffer data) { setVersion(data.getShort()); short numberSubtables = data.getShort(); for (int i = 0; i < numberSubtables; i++) { short platformID = data.getShort(); short platformSpecificID = data.getShort(); int offset = data.getInt(); data.mark(); // get the position from the start of this buffer data.position(offset); ByteBuffer mapData = data.slice(); data.reset(); try { CMap cMap = CMap.getMap(mapData); if (cMap != null) { addCMap(platformID, platformSpecificID, cMap); } } catch (Exception ex) { System.out.println("Error reading map. PlatformID=" + platformID + ", PlatformSpecificID=" + platformSpecificID); System.out.println("Reason: " + ex); } } }
3
public ArrayList<File> find(String path, String mask) throws FileNotFoundException { ArrayList<File> result = new ArrayList<>(); File file = new File(path); if (!file.isDirectory()) { throw (new FileNotFoundException("it is not directory!")); } if (!MaskValidator.isValid(mask)) { throw (new RuntimeException("bad mask")); } File[] fileList = file.listFiles(); for (File f : fileList) { if (f.isFile()) { if (MaskValidator.isNameValid(mask, f.getName())) { result.add(f); System.out.println(f.getName()); } } if (f.isDirectory()) { ArrayList<File> temp = find(f.getAbsolutePath(), mask); result.addAll(temp); } } return result; }
6
public void draw() { if (texture != null) texture.bind(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0); glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 1); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); }
1
public boolean move (int direction, Client c) { // All moves are of one square, lets make sure // that the target square is fre if (c == null) return false; if (c.current == null) return false; Coordinate newLoc = null; switch (direction) { case Coordinate.NORTH: newLoc = new Coordinate(c.current.x+1, c.current.y); break; case Coordinate.EAST: newLoc = new Coordinate(c.current.x, c.current.y+1); break; case Coordinate.WEST: newLoc = new Coordinate(c.current.x, c.current.y-1); break; case Coordinate.SOUTH: newLoc = new Coordinate(c.current.x-1, c.current.y); break; default: break; } if (newLoc == null) return false; Coordinate placed = placePlayer(newLoc, c.current, c.uid, false); if (placed != null) { c.setLocation(placed); return true; } return false; }
8
public void run() { while (true) { // Create a buffer to read datagrams into byte[] buffer = new byte[1500]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); if (active) { try { byte[] outgoingPacket = ROPacketAssembler.getXmitBytes(joystickHandler, !enabled); DatagramPacket sendPacket = new DatagramPacket(outgoingPacket, outgoingPacket.length, ipAddr, port); serverSocket.send(sendPacket); try { serverSocket.receive(packet); // Process packet ROPacketParser.parsePacket(buffer, packet.getLength(), dashboardData); } catch (Exception SocketTimeoutException) { // Didn't get a packet back } // Reset the length of the packet packet.setLength(buffer.length); try { Thread.sleep(packetRate); } catch (InterruptedException e) { active = false; } } catch (Exception e) { active = false; System.out.println(e.toString()); } } else { try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } } }
6
@Override public void run() { while (Server.run) { try { stream.ping(); if (stream.isEOF()) { break; } while (stream.getAvailable() > 0) { Packet packet = Packet.readPacket(stream); if (packet != null) { packet.handle(); if (packet instanceof Packet_Login) { Packet_Login p = (Packet_Login) packet; if (p.getResponseCode() == Packet_Login.RESPONSE_ACCEPT) { verifyed = true; return; } } } } } catch (Exception e) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { } } Server.getServer().getNetworkManager().getLogger().info("Lost connection [" + stream.getIP() + "]"); }
8
public void clientHttp() { BufferedReader in = null; try { ListIterator<SearchHitMessage> it = Simpella.searchHitMsgList.listIterator(); String ipToConnect=""; String portToConnect=""; String fileName=""; String fileIndex=""; int flag = 0; while(it.hasNext()) { SearchHitMessage shm = it.next(); ListIterator<FileDetails> lit = shm.fDetails.listIterator(); while(lit.hasNext()) { FileDetails fd = lit.next(); if(fd.index == index) { flag = 1; ipToConnect = shm.msgFromIp; portToConnect = String.valueOf(shm.msgFromPort); fileName = fd.fileName; fileIndex = String.valueOf(fd.fileIndex); } } } if(flag == 1) { URL url = new URL("http://"+ipToConnect+":"+portToConnect+"/get/"+fileIndex+"/"+fileName); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", " Simpella 0.6"); connection.setRequestProperty("Range"," bytes=0-"); in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String s = in.readLine(); String res = s; //System.out.println(s); while(in.ready()) { s = in.readLine(); res = res+s; //System.out.println(s); if(s.trim().isEmpty()) break; } String temp = res.substring(res.indexOf("Content-length"),res.indexOf("Connection")); //System.out.println("temp is "+temp); String contentLength = temp.substring(temp.indexOf(": ")+2); //System.out.println("content Length is "+contentLength); int conLength = Integer.parseInt(contentLength); if(!res.contains("503 File not found")) httpProtocol(connection, fileName,ipToConnect,portToConnect,conLength); else if(res.contains("503 File not found")) System.out.println("File not Found: Try Again"); in.close(); }else { System.out.println("Error: Index Incorrect"); } }catch(IOException e) { System.out.println("Connection not possible at this point..try again"); } }
9
private Class<? extends Matrix> getClassFor(int rows, int cols) { if (cols==1) { switch (rows) { case 2: return Vector2.class; case 3: return Vector3.class; case 4: return Vector4.class; default: return Vector.class; } } else if (rows==2 && cols==2) return Matrix2.class; else if (rows==3 && cols==3) return Matrix3.class; else return Matrix.class; }
9
public HashMap<String,PDFObject> getDictionary() throws IOException { if (type == INDIRECT) { return dereference().getDictionary(); } else if (type == DICTIONARY || type == STREAM) { return (HashMap<String,PDFObject>) value; } // wrong type return new HashMap<String,PDFObject>(); }
3
public int modificarEnunciado(DTO.Enunciado en) { try { if (con.isClosed()) { con = bd.conexion(); } String consulta; Object ob = null; if(en.getDespuesDe().getCodigo() !=0){ ob =en.getDespuesDe().getCodigo(); } String des = en.getEnunciado().replace("\\", "\\\\"); consulta = "UPDATE enunciado SET orden = '" + en.getOrden() + "', autor = '" + en.getAutor().getCodigo() + "', area = '" + en.getArea().getCodigo() + "', despuesDeEnunciado =" + ob+ ", descripcionE ='"+des+"' WHERE codigo = '" + en.getCodigo() + "'"; Statement sta = con.createStatement(); int rs = sta.executeUpdate(consulta); if (rs == 1 || rs == 4) { return 1; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error modificando enunciado!. Error: " + ex); } finally { if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } return 0; }
7
protected void stateChanged() { if(lastState == ButtonState.ACTIVE && currentState == ButtonState.HOVER) { ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, this.text); for(ActionListener l : actionListeners) l.actionPerformed(e); } }
3
public void loadConfig() { while (!getDataFolder().exists()) { saveConfig(); } File file = getDataFolder(); String filename = file + "/config.cfg"; config = new Properties(); try { config.load(new FileInputStream(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } WIDTH = Integer.parseInt(config.getProperty("Width")); HEIGHT = Integer.parseInt(config.getProperty("Height")); setGameWidth(WIDTH); setGameHeight(HEIGHT); Console.log("Loaded configurations"); }
3
public User findUserByKey(String key) { Session session =null; User user; try { session= HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(User.class); user=(User)criteria.add(Restrictions.eq("key", key)).uniqueResult(); if(user!=null) { session.getTransaction().commit(); return user; } } catch (Exception exception) { } finally { if(session!=null && session.isOpen()) { session.close(); } } return null; }
4
@Override public void approveSelection() { File file = getSelectedFile(); if (this.dialogType == JFileChooser.OPEN_DIALOG) { // Alert if file does not exist. if (!file.exists()) { String msg = GUITreeLoader.reg.getText("error_file_not_found"); msg = Replace.replace(msg,GUITreeComponentRegistry.PLACEHOLDER_1, file.getPath()); JOptionPane.showMessageDialog(this, msg); return; } } else if (this.dialogType == JFileChooser.SAVE_DIALOG) { // Alert if file exists. if (file.exists()) { // Custom button text String yes = GUITreeLoader.reg.getText("yes"); String no = GUITreeLoader.reg.getText("no"); String confirm_replacement = GUITreeLoader.reg.getText("confirm_replacement"); String msg = GUITreeLoader.reg.getText("confirmation_replace_file"); msg = Replace.replace(msg,GUITreeComponentRegistry.PLACEHOLDER_1, file.getPath()); Object[] options = {yes, no}; int result = JOptionPane.showOptionDialog(this, msg, confirm_replacement, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1] ); if (result == JOptionPane.YES_OPTION) { // Proceed normally. } else if (result == JOptionPane.NO_OPTION) { return; } else { return; } } } super.approveSelection(); }
6
private boolean r_postlude() { int among_var; int v_1; // repeat, line 75 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 75 // [, line 77 bra = cursor; // substring, line 77 among_var = find_among(a_1, 4); if (among_var == 0) { break lab1; } // ], line 77 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 78 // <-, line 78 slice_from("i"); break; case 2: // (, line 79 // <-, line 79 slice_from("u"); break; case 3: // (, line 80 // <-, line 80 slice_from("y"); break; case 4: // (, line 81 // next, line 81 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
9
public HashMap<Integer, List<Integer>> constructAdjacencyList() throws IOException { HashMap<Integer, List<Integer>> adjacencyList = new HashMap<Integer, List<Integer>>(); List<String> sequence = new ArrayList<String>(); List<Integer> knotList = new ArrayList<Integer>(); BufferedReader br = new BufferedReader((new FileReader(pathToFile))); String line = br.readLine(); int knot = Integer.valueOf(line.substring(0, 1)); StringTokenizer stringTokenizer = new StringTokenizer(line.substring(5), ","); List<Integer> adjacent = new ArrayList<Integer>(); while (stringTokenizer.hasMoreElements()) { adjacent.add(Integer.valueOf((String) stringTokenizer.nextElement())); } adjacencyList.put(knot, adjacent); while (line != null) { line = br.readLine(); if (line != null) { knot = Integer.valueOf(line.substring(0, line.indexOf(" ->"))); knotList.add(knot); stringTokenizer = new StringTokenizer(line.substring(line.indexOf("-> ") + 3), ","); adjacent = new ArrayList<Integer>(); while (stringTokenizer.hasMoreElements()) { adjacent.add(Integer.valueOf((String) stringTokenizer.nextElement())); } adjacencyList.put(knot, adjacent); } } return adjacencyList; }
4
public static boolean isValidForename(String forename) { if (forename == null) return false; return forename.matches("[a-zA-Z]+") && forename.length() <= 32; }
2
@Override public void run() { threadRun = true; Simulator simulator = MainProgram.getSimulator(); while(threadRun && numSteps > 0 && simulator.getSimulatorView().isViable(simulator.getField())) { MainProgram.getSimulator().simulateOneStep(); numSteps--; while(infinite && numSteps == 0) { numSteps++; } try { Thread.sleep(simulator.getAnimationSpeed()); } catch (Exception e) { System.out.println("InterruptedException"); } } threadRun = false; }
6
private static void exportFrame(ExportDiagnoser d, Frame f, File baseDirectory) { Rectangle rect = f.properRectangle(); Point pivot = f.getPivot(); d.printSection(f.getName()); RelativeFile relativeImageFile = f.getImageFile(); if(relativeImageFile!=null) { File imageFile = relativeImageFile.getAbsoluteFile(); File imagePath = new File(""); try { imagePath = getRelativeFile(imageFile, baseDirectory); d.printKeyValue("Texture", imagePath.toString()); } catch (IOException e) { d.reportExternalError("There was a problem while exporting the texture of "+f.getName()); e.printStackTrace(); } } else d.reportExternalError(f.getName() + " has no texture"); if(rect!=null) { d.printKeyValue("TextureCorner","("+rect.x+ ", "+rect.y+ ", 0)"); d.printKeyValue("TextureSize","("+rect.width+", "+rect.height+", 0)"); } else d.reportExternalError(f.getName() + " does not have a rectangle defined"); if(pivot!=null) { pivot.x -= rect.x; pivot.y -= rect.y; d.printKeyValue("Pivot","("+pivot.x+ ", "+pivot.y+ ", 0)"); } else d.reportExternalError(f.getName() + " does not have a pivot defined"); if(f.getFlipX() || f.getFlipY()) { String flip = ""; if(f.getFlipX()) flip+="x"; if(f.getFlipY()) flip+="y"; d.printKeyValue("Flip",flip); } }
8
public final TLParser.whileStatement_return whileStatement() throws RecognitionException { TLParser.whileStatement_return retval = new TLParser.whileStatement_return(); retval.start = input.LT(1); Object root_0 = null; Token While91=null; Token Do93=null; Token End95=null; TLParser.expression_return expression92 = null; TLParser.block_return block94 = null; Object While91_tree=null; Object Do93_tree=null; Object End95_tree=null; RewriteRuleTokenStream stream_Do=new RewriteRuleTokenStream(adaptor,"token Do"); RewriteRuleTokenStream stream_End=new RewriteRuleTokenStream(adaptor,"token End"); RewriteRuleTokenStream stream_While=new RewriteRuleTokenStream(adaptor,"token While"); RewriteRuleSubtreeStream stream_expression=new RewriteRuleSubtreeStream(adaptor,"rule expression"); RewriteRuleSubtreeStream stream_block=new RewriteRuleSubtreeStream(adaptor,"rule block"); try { // src/grammar/TL.g:120:3: ( While expression Do block End -> ^( While expression block ) ) // src/grammar/TL.g:120:6: While expression Do block End { While91=(Token)match(input,While,FOLLOW_While_in_whileStatement811); stream_While.add(While91); pushFollow(FOLLOW_expression_in_whileStatement813); expression92=expression(); state._fsp--; stream_expression.add(expression92.getTree()); Do93=(Token)match(input,Do,FOLLOW_Do_in_whileStatement815); stream_Do.add(Do93); pushFollow(FOLLOW_block_in_whileStatement817); block94=block(); state._fsp--; stream_block.add(block94.getTree()); End95=(Token)match(input,End,FOLLOW_End_in_whileStatement819); stream_End.add(End95); // AST REWRITE // elements: While, expression, block // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (Object)adaptor.nil(); // 120:36: -> ^( While expression block ) { // src/grammar/TL.g:120:39: ^( While expression block ) { Object root_1 = (Object)adaptor.nil(); root_1 = (Object)adaptor.becomeRoot(stream_While.nextNode(), root_1); adaptor.addChild(root_1, stream_expression.nextTree()); adaptor.addChild(root_1, stream_block.nextTree()); adaptor.addChild(root_0, root_1); } } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; }
2
public Integer getId() { return id; }
0
@Override public V remove(K key) { int i = findEntry(key); if (i < 0)// key not in table return null; V value = bucket[i].getValue(); bucket[i] = available; size--; return value; }
1
@Override public void itemStateChanged(ItemEvent ie) { String name = displayLabel.getFont().getName(); Font font; if(styleItems[0].isSelected() && styleItems[1].isSelected()) font = new Font(name, Font.BOLD+Font.ITALIC, 72); else if(styleItems[0].isSelected()) font = new Font(name, Font.BOLD,72); else if(styleItems[1].isSelected()) font = new Font(name, Font.ITALIC, 72); else font = new Font(name, Font.PLAIN,72); displayLabel.setFont(font); repaint(); }
4
public void paintComponent(Graphics g) { BufferedImage spriteSheet = null,Thruster; BufferedImageLoader loader = new BufferedImageLoader(); try { spriteSheet = loader.loadImage("images/Ship_Shop/shipshopparts.png"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // the following two lines are needed because calling the paint overrides the background color this.setBackground(Color.black); g.fillRect(265, 200, 600, 300); g.setColor(Color.white); if(Main.ShipShopThrustersMenu.selectionOvalX == 340) { Thruster = spriteSheet.getSubimage(0, 39, 39, 29); g.drawImage(Thruster,475, 250, 156, 116,this); if(Main.Player1.Ship.Ship_Thrusters.check_purchased_Thrusters(0) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Thruster?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,44)); g.drawString("Confirm Your Thruster Purchase",275,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } } else if(Main.ShipShopThrustersMenu.selectionOvalX == 540) { if(Main.Player1.Ship.Ship_Thrusters.check_purchased_Thrusters(1) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Thruster?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,44)); g.drawString("Confirm Your Thruster Purchase",275,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } Thruster = spriteSheet.getSubimage(41, 38, 35, 31); g.drawImage(Thruster,485, 250, 140, 124,this); } else if(Main.ShipShopThrustersMenu.selectionOvalX == 740) { if(Main.Player1.Ship.Ship_Thrusters.check_purchased_Thrusters(2) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Thruster?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,44)); g.drawString("Confirm Your Thruster Purchase",275,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } Thruster = spriteSheet.getSubimage(76, 39, 32, 31); g.drawImage(Thruster,500, 250, 128, 124,this); } g.drawString("Cancel",750, 494); g.drawOval(selectionOvalX, selectionOvalY, selectionOvalHeight, selectionOvalWidth); }
7
public String getLastMessage() { return lastMessage; }
0
public boolean equals(Object o){ Production p = (Production)o; if( this.dot == p.dot && this.left.equals(p.getLeft())){ if( this.right.size() == p.right.size()){ for( int i = 0; i < this.right.size(); i++){ if( !this.right.get(i).equals(p.right.get(i))){ return false; } } }else{ return false; } return true; } return false; }
5
private long largest(final long number) { long result = 1; for (int p : Primes.primes) { if (number % p == 0) { result = p; } } return result; }
2
private void cycle2( int i, int k, WordInfo wf, Hand h, int cross_score, int word_score, int word_mult ) { if (WordFinder.killAllNow) { // Kill It } else if (this.BoardLetters[i][k] == ' ') // If open space { for (char cc : h.AvailableTiles) // Iterate through hand { if (cc == '?') // If hand is wild { for (char c : PossibleWilds) // Iterate through letters { this.cycle3( i, k, wf, h, cross_score, word_score, word_mult, cycle3.Wild, c); } } else // If hand not wild { this.cycle3( i, k, wf, h, cross_score, word_score, word_mult, cycle3.Hand, cc); } } } else // If Not Open Space { this.cycle3( i, k, wf, h, cross_score, word_score, word_mult, cycle3.Board, this.BoardLetters[i][k]); } }
5
public static CustomButton doHistoryViewButton() { final CustomButton a = new CustomButton("show my history"); a.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFrame searchResultFrame = new JFrame("my history"); searchResultFrame.setSize(1300, 650); searchResultFrame.setVisible(true); searchResultFrame .setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JScrollPanelledPane tickerScroll = new JScrollPanelledPane(); searchResultFrame.add(tickerScroll); ArrayList<String> bundle = new ArrayList<String>(); for (String ticker : EarningsTest.programSettings.myHistory .values()) { CustomButton tickerButton = JComponentFactory .doIndividualTickerButtonForPanel(bundle, ticker, a.getText(), searchResultFrame, NON_EARNINGS_REPORT); // tickerButton.setBackground(new // Color(100,140,255)); if (tickerButton != null) { tickerButton.setMinimumSize(new Dimension(300, 45)); tickerScroll.addComp((tickerButton)); } } doStatInfoForBundleVsMarket(new ArrayList<String>( EarningsTest.programSettings.myPortfolio.keySet())); } }); return a; }
2
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { if (player == null) { sender.sendMessage(ChatColor.RED+"This command can only be run by a player"); return true; } player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 1200, 2)); sender.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "Your Strength has been increased for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } target.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 1200, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been made Stronger for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "Your Strength has been increased for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 2 && player == null || player.hasPermission("simpleextras.strength.other")) { Player target = Bukkit.getPlayer(args[0]); // CHECK IF TARGET EXISTS if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } String min = args[1]; int mintemp = Integer.parseInt( min ); int mins = 1200 * mintemp; target.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, mins, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been made Stronger for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "Your Strength has been increased for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); return true; } return true; }
9
private void createButtons(){ java.net.URL buttonIcon = Paintimator.class.getResource("images/backPage.png"); backPage = new JButton(new ImageIcon(buttonIcon)); backPage.setToolTipText("Previous Page"); backPage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { centerPanel.remove(layeredPanelList.getSelected()); LayeredPanel tmp = layeredPanelList.getPrev(); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() +1); refreshDrawPanel(tmp); setCurrentCanvasListener(tmp); } }); buttonIcon = Paintimator.class.getResource("images/FwPage.png"); fwdPage = new JButton(new ImageIcon(buttonIcon)); fwdPage.setToolTipText("Next Page"); fwdPage.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(layeredPanelList.isAtEnd()){ int i = JOptionPane.showOptionDialog(context, "Would you like to add a next page?", "Next Page", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Yes, Blank Page", "Yes, Page Copy", "Cancel"}, "Yes, Blank Page"); switch (i) { case JOptionPane.NO_OPTION: centerPanel.remove(layeredPanelList.getSelected()); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel()+1); //Code to add previous image as background of new page BufferedImage bi = layeredPanel.paneToBufferedImg(); layeredPanel = new LayeredPanel(); layeredPanel.setBackground(bi); layeredPanel.addMouseListener(myListener); layeredPanel.addMouseMotionListener(myListener); setCurrentCanvasListener(layeredPanel); layeredPanel.setPreferredSize(new Dimension(width - 450, height - 300)); layeredPanelList.add(layeredPanel); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() + 1); refreshDrawPanel(layeredPanelList.getSelected()); toolPanel.resetState(); layeredPanelList.getSelected().clearRootPane(); break; case JOptionPane.YES_OPTION: centerPanel.remove(layeredPanelList.getSelected()); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel()+1); layeredPanel = new LayeredPanel(); layeredPanel.addMouseListener(myListener); layeredPanel.addMouseMotionListener(myListener); setCurrentCanvasListener(layeredPanel); layeredPanel.setPreferredSize(new Dimension(width - 450, height - 300)); layeredPanelList.add(layeredPanel); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() + 1); refreshDrawPanel(layeredPanelList.getSelected()); toolPanel.resetState(); layeredPanelList.getSelected().clearRootPane(); default : break; } }else{ centerPanel.remove(layeredPanelList.getSelected()); LayeredPanel tmp = layeredPanelList.getNext(); animationPane.updateAnimation(layeredPanelList, layeredPanelList.getIntSelectedPanel() +1); refreshDrawPanel(tmp); setCurrentCanvasListener(tmp); } } }); }
3
public void MoveModel() { if(win == GameStatus.VICTORY || lose == GameStatus.DEFEAT) pause = true; if(!pause) { CollideableObject q; int i = 0; win = GameStatus.VICTORY; lose = GameStatus.DEFEAT; while (i < data.size()) { q = data.get(i); if (q.color != Color.BLUE && q.color != Color.GRAY) //if q is a brick { if (q.Y < Brick.BRICK_OFFSET + 400) //q is an enemy brick win = GameStatus.ACTIVE; else //q is a friendly brick lose = GameStatus.ACTIVE; if (((Brick) q).hits == 0) //removes bricks without throwing NullPointerException { data.remove(q); i++; continue; } } q.move(this, width, height); i++; } } }
8
@Override public void onDraw(Graphics G, int viewX, int viewY) { if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300) { Graphics2D g = (Graphics2D)G; Composite c = g.getComposite(); // g.setComposite(new Additive()); g.setColor(new Color(255,r.nextInt(255),0,r.nextInt(255))); g.fillArc((int)(X-6)-viewX, (int)(Y-6)-viewY, 12,12, 0, 360); for (int i = 0; i < 4; i++) { int e1 = 6-r.nextInt(12), e2 = 6-r.nextInt(12); g.setColor(new Color(255,r.nextInt(255),0,r.nextInt(255))); g.fillArc((int)(X+e1)-viewX, (int)(Y+e2)-viewY, e1, e2, 0, 360); } g.setComposite(c); } }
5
private void lisaaKilpienergiaa(Pelihahmo h){ if (!h.getSuojakilpi()){ h.setKilpienergia(h.getKilpienergia() + LISAAMIS_VAKIO); } }
1