text
stringlengths
14
410k
label
int32
0
9
private void paintInfo(Graphics2D g2) { g2.setColor(Color.BLACK); int x = MARGIN_X; int y = WAVE_INFO_SPACE_TO_TOP; g2.drawString("Current WaveNr: " + enemyGroups.getCurrentGroupNr() + " Time to next Wave " + stringConverter((int) board.getCountdownToNextWave()), x, y); y += SMALL_SPACING; g2.setColor(Color.BLACK); g2.drawString("main/tower", x, y); x += TOP_MARGIN_X; for (Tower currentTower : board.getAllTowers()) { g2.drawString(currentTower.getPrice() + ", ", x, y); x += SMALL_SPACING; } y += SMALL_SPACING; g2.drawString("Gold: "+ stringConverter(board.getPlayer().getGold()), MARGIN_X, y); y += SMALL_SPACING; g2.drawString("Lives: "+ stringConverter(board.getPlayer().getLives()), MARGIN_X, y); }
1
public void setPrivate(final boolean flag) { if (this.isDeleted) { final String s = "Cannot change a field once it has been marked " + "for deletion"; throw new IllegalStateException(s); } int mod = methodInfo.modifiers(); if (flag) { mod |= Modifiers.PRIVATE; } else { mod &= ~Modifiers.PRIVATE; } methodInfo.setModifiers(mod); this.setDirty(true); }
2
int getScheduleFitness(Schedule s){ int scheduleFitness = 0; for (RoomScheme[] schedule : s.schedule) { for (RoomScheme sch: schedule) { scheduleFitness += sch.getFitness(); } } return scheduleFitness; }
2
private synchronized void resize(int newSizeColumns, int newSizeRows) { TerminalCharacter [][]newCharacterMap = new TerminalCharacter[newSizeRows][newSizeColumns]; for(int y = 0; y < newSizeRows; y++) for(int x = 0; x < newSizeColumns; x++) newCharacterMap[y][x] = new TerminalCharacter( ' ', new CharacterANSIColor(Color.WHITE), new CharacterANSIColor(Color.BLACK), false, false, false); synchronized(resizeMutex) { for(int y = 0; y < size().getRows() && y < newSizeRows; y++) { for(int x = 0; x < size().getColumns() && x < newSizeColumns; x++) { newCharacterMap[y][x] = this.characterMap[y][x]; } } this.characterMap = newCharacterMap; SwingUtilities.invokeLater(new Runnable() { public void run() { if(terminalFrame != null) { terminalFrame.pack(); } } }); onResized(newSizeColumns, newSizeRows); } }
7
public void checkFields (LYNXsys system) { // check textfields method for (int i = 0; i < system.getUsers().size(); i++) { // loop through all users if (system.getUsers().get(i).getFirstName().equalsIgnoreCase(getFirstName().getTextField().getText()) && // if user exists (all fields match) system.getUsers().get(i).getLastName().equalsIgnoreCase(getLastName().getTextField().getText()) && system.getUsers().get(i).getID().equalsIgnoreCase((getID().getTextField().getText()))) { system.removeStudent(system.getUsers().get(i)); // remove dis guy } } }
4
private Map<CustomEnchantment, Integer> getValidEnchantments(ArrayList<ItemStack> items) { Map<CustomEnchantment, Integer> validEnchantments = new HashMap<CustomEnchantment, Integer>(); for (ItemStack item : items) { ItemMeta meta = item.getItemMeta(); if (meta == null) continue; if (!meta.hasLore()) continue; for (String lore : meta.getLore()) { String name = ENameParser.parseName(lore); int level = ENameParser.parseLevel(lore); if (name == null) continue; if (level == 0) continue; if (EnchantAPI.isRegistered(name)) { validEnchantments.put(EnchantAPI.getEnchantment(name), level); } } } return validEnchantments; }
7
public eOrientation getOrientation() { if (rdbHorizontal.isSelected()) { return eOrientation.Horizontal; } return eOrientation.Vertical; }
1
public boolean isHurdle(int positionX, int positionY) { boolean hasHurdle = false; for (int i = 0; i < hurdleFactory.getQuantityOfHurdles(); i++) { if (hurdleFactory.getHurdle(i).position.getX() == positionX && hurdleFactory.getHurdle(i).position.getY() == positionY) { hasHurdle = true; } } return hasHurdle; }
3
public void saveStats(GameState gameState) { queryLock.lock(); try { for (Player player: gameState.players) { if (player.username.equals("guest")) continue; String command = "UPDATE players " + "SET total_games = total_games + 1," + "num_kills = num_kills + ?," + "num_deaths = num_deaths + ?," + "num_shots = num_shots + ?," + "num_hits = num_hits + ?," + "wins = wins + ?, " + "brains_destroyed = brains_destroyed + ? " + "WHERE name = ?"; PreparedStatement stmt = connection.prepareStatement(command); stmt.setInt(1, player.numKills); stmt.setInt(2, player.numDeaths); stmt.setInt(3, player.numShots); stmt.setInt(4, player.numHits); int won = (gameState.winningTeam == player.team.num)? 1 : 0; stmt.setInt(5, won); int destroyedBrain = (player.destroyedBrain)? 1 : 0; stmt.setInt(6, destroyedBrain); stmt.setString(7, player.username); stmt.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } queryLock.unlock(); }
5
public boolean checkValidate() { boolean coma = false, parallel = false, openTok_brace = false, first = true; int outNum = 0, inNum = 0; // while(lex.nextToken() != null) { while(!lex.End()) { lex.nextToken(); Token token = lex.currentToken(); if (openTok_brace) { inNum = token.getInt(); if (!parallel && inNum != outNum && !first) return false; openTok_brace = false; parallel = false; outNum = inNum = 0; first = false; } if (coma) { outNum = token.getInt(); coma = false; } if (token.getType() == typeToken.comma) coma = true; if (token.getType() == typeToken.ParallelSign) parallel = true; if (token.getType() == typeToken.openTok_brace) openTok_brace = true; } return true; }
9
public static int checkField(int luaState, Object obj, String fieldName) throws LuaException { LuaState L = LuaStateFactory.getExistingState(luaState); synchronized (L) { Field field = null; Class objClass; if (obj instanceof Class) { objClass = (Class) obj; } else { objClass = obj.getClass(); } try { field = objClass.getField(fieldName); } catch (Exception e) { return 0; } if (field == null) { return 0; } Object ret = null; try { ret = field.get(obj); } catch (Exception e1) { return 0; } if (obj == null) { return 0; } L.pushObjectValue(ret); return 1; } }
5
public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder( ); int caso = 1; for(String line; (line = in.readLine())!=null; caso++){ if(line.equals("0 0")) break; StringTokenizer st = new StringTokenizer(line); int n = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); for (int i = 0; i < n; i++) in.readLine(); names = new String[p]; proposals = new int[p]; prices = new double[p]; for (int i = 0; i < p; i++) { names[i] = in.readLine(); st = new StringTokenizer(in.readLine()); prices[i] = Double.parseDouble(st.nextToken()); proposals[i] = Integer.parseInt(st.nextToken()); for (int j = 0; j < proposals[i]; j++) { in.readLine(); } } int indexMajor = 0; double compliance = Double.MIN_VALUE; for (int i = 0; i < proposals.length; i++) { double calc = (double)((double)proposals[i]/(double)n); if( calc > compliance ){ indexMajor = i; compliance = calc; }else if(calc == compliance){ if( prices[i] < prices[indexMajor] ){ indexMajor = i; } } } sb.append("RFP #"+caso+"\n").append(names[indexMajor]).append("\n").append("\n"); } System.out.print(new String(sb.substring(0, sb.length()-1))); }
9
int zeller(final int year, final int month, final int day) { /* * 蔡勒(Zeller)公式: 用于推算某个日期为星期几 * * 仅适用于1582年10月5日以及之后 * 参考:格里高利历 * * w = ([c/4] - 2c + y + [y/4] + [13(m+1)/5] + d - 1) mod 7 * * c = (int) (year / 100) * y = year % 100 * m = month (3<=m<=14) * 2013-01 => 2012-13; * 2012-02 => 2011-14; * 2014-05 => 2014-05. * d = day * */ if (year < 1582) { return -1; } if (year == 1582 && month < 10) { return -1; } if (year == 1582 && month == 10 && day < 5) { return -1; } int yearTmp = year; int m = month; if (month == 1 || month == 2) { yearTmp--; m += 12; } int c = yearTmp / 100; int y = yearTmp % 100; final int weak = ((c / 4) - (2 * c) + y + (y / 4) + (13 * (m + 1) / 5) + day - 1) % 7; return weak; }
8
public void UpdateProjeto(Projeto projeto) throws SQLException, ExcecaoprojetoExistente { ProjetoDAO projetDAO = new ProjetoDAO(); Projeto projet = new Projeto(); projet = projetDAO.selectUmProjeto(projeto.getNome()); if (projet == null || projet.getIdProjeto() == projeto.getIdProjeto()) { projetDAO.AtualizarProjeto(projeto); } else { throw new ExcecaoprojetoExistente(); } }
2
public void setFormula(String[] formula) { int dim = 1; if (formula != null) dim = formula.length; else formula = new String[] { "0" }; if (numSpinner != null) numSpinner.setCrt(dim); if (numField != null) numField.setText("" + dim); this.formula = formula; display(); }
3
private void updateObservers() { setChanged(); notifyObservers(); }
0
public static <T, ID> MappedCreate<T, ID> build(DatabaseType databaseType, TableInfo<T, ID> tableInfo) { StringBuilder sb = new StringBuilder(128); appendTableName(databaseType, sb, "INSERT INTO ", tableInfo.getTableName()); sb.append('('); int argFieldC = 0; int versionFieldTypeIndex = -1; // first we count up how many arguments we are going to have for (FieldType fieldType : tableInfo.getFieldTypes()) { if (isFieldCreatable(databaseType, fieldType)) { if (fieldType.isVersion()) { versionFieldTypeIndex = argFieldC; } argFieldC++; } } FieldType[] argFieldTypes = new FieldType[argFieldC]; argFieldC = 0; boolean first = true; for (FieldType fieldType : tableInfo.getFieldTypes()) { if (!isFieldCreatable(databaseType, fieldType)) { continue; } if (first) { first = false; } else { sb.append(","); } appendFieldColumnName(databaseType, sb, fieldType, null); argFieldTypes[argFieldC++] = fieldType; } sb.append(") VALUES ("); first = true; for (FieldType fieldType : tableInfo.getFieldTypes()) { if (!isFieldCreatable(databaseType, fieldType)) { continue; } if (first) { first = false; } else { sb.append(","); } sb.append("?"); } sb.append(")"); FieldType idField = tableInfo.getIdField(); String queryNext = buildQueryNextSequence(databaseType, idField); return new MappedCreate<T, ID>(tableInfo, sb.toString(), argFieldTypes, queryNext, versionFieldTypeIndex); }
9
public void var_read(String path) throws IOException { FileInputStream is = null; DataInputStream dis = null; try{ is = new FileInputStream(path); dis = new DataInputStream(new BufferedInputStream(is)); senones = (int)dis.readFloat(); gaussian = (int)dis.readFloat(); var = new float[senones][gaussian][39]; for(int i = 0; i < senones; i++) for(int j = 0; j < gaussian; j++) for(int k = 0 ; k < 39; k++) var[i][j][k] = dis.readFloat(); }catch(Exception e){ System.out.println(path + " file missing"); e.printStackTrace(); } finally{ if(is != null)is.close(); if(dis != null)dis.close(); } }
6
@Override public AttributeValue getExampleAttributeValue(Example e) { int playerToken = e.getResult().currentTurn; int opponentToken = 3 - playerToken; int height = e.getBoard().height; // 6 int width = e.getBoard().width; // 7 int center = width / 2; int playerScore = 0; int opponentScore = 0; // bottom index is (5, 0) for (int i = height - 1; i > -1; i--) { for (int j = 0; j < width; j++) { if (e.getBoard().boardArray[i][j] == playerToken) { // current // player's // tokens playerScore += center - Math.abs(j - center); } else if(e.getBoard().boardArray[i][j] == opponentToken){ opponentScore += center - Math.abs(j - center); } } } if (playerScore >= opponentScore) { return affirm; } else { return nega; } }
5
public int getSearchJumpLength() { _read.lock(); try { return _searchJumpLength; } finally { _read.unlock(); } }
0
public int longestConsecutive(int[] num) { int result = 0; HashMap<Integer, Integer> h = new HashMap<Integer, Integer>(); //put all number into the hashmap for (int i = 0; i < num.length; i++) { h.put(num[i], null); } //check the longest consecutive list number for (int i = 0; i < num.length; i++) { //at first, get one number num[i] int count = 1; //check less than num[i] int x = num[i] - 1; while (h.containsKey(x)) { h.remove(x); count++; x--; } //check bigger than num[i] int y = num[i] + 1; while (h.containsKey(y)) { h.remove(y); count++; y++; } //sum all possible consecutive sequence if (count > result) { result = count; } } return result; }
5
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public int total() { int result = 0; String separator = ""; for (Object operando : operators) { if (operando != null) { System.out.print(separator + operando.toString()); if (operando.getClass().getSimpleName().equals("Summation")) { result += ((Summation) operando).sum(); } else { result += ((Subtraction) operando).subtract(); } } separator = "+"; } System.out.print(">>> "); return result; }
3
public void setPositionName(String positionName) { this.positionName = positionName; }
0
private String decodePapPassword(byte[] encryptedPass, byte[] sharedSecret) throws RadiusException { if (encryptedPass == null || encryptedPass.length < 16) { // PAP passwords require at least 16 bytes logger.warn("invalid Radius packet: User-Password attribute with malformed PAP password, length = " + (encryptedPass == null ? 0 : encryptedPass.length) + ", but length must be greater than 15"); throw new RadiusException("malformed User-Password attribute"); } MessageDigest md5 = getMd5Digest(); byte[] lastBlock = new byte[16]; for (int i = 0; i < encryptedPass.length; i += 16) { md5.reset(); md5.update(sharedSecret); md5.update(i == 0 ? getAuthenticator() : lastBlock); byte bn[] = md5.digest(); System.arraycopy(encryptedPass, i, lastBlock, 0, 16); // perform the XOR as specified by RFC 2865. for (int j = 0; j < 16; j++) encryptedPass[i + j] = (byte) (bn[j] ^ encryptedPass[i + j]); } // remove trailing zeros int len = encryptedPass.length; while (len > 0 && encryptedPass[len - 1] == 0) len--; byte[] passtrunc = new byte[len]; System.arraycopy(encryptedPass, 0, passtrunc, 0, len); // convert to string return RadiusUtil.getStringFromUtf8(passtrunc); }
8
//@Test(expected=ReaderException.class) public void testTooManyArgumentsFail() throws ReaderException { ConfigurationManager.init("src/test/resources/test.json"); // No key is given, the method should throw an error ConfigurationManager.read.getItem("test_2", "doesntexist"); }
0
public void sort(int[] intArray,int left,int right){ System.out.println("您调用的算法:快速排序"); //设置关键字 int key=intArray[left]; int leftFlag=left; int rightFlag=right; int swapTemp; while(leftFlag != rightFlag){ //左移操作 while(intArray[rightFlag] >= key && rightFlag > 0) rightFlag--; swapTemp=intArray[rightFlag]; intArray[rightFlag]=key; intArray[leftFlag]=intArray[rightFlag]; //右移操作 while(intArray[leftFlag] <= key && leftFlag <intArray.length-1) leftFlag++; swapTemp=intArray[leftFlag]; intArray[leftFlag]=key; intArray[rightFlag]=intArray[leftFlag]; } if(left < rightFlag) sort(intArray,left,rightFlag); if(right > leftFlag) sort(intArray, leftFlag, right); }
7
public ButtonList() { super(); this.setLayout(new FlowLayout(FlowLayout.LEFT)); this.add(reset); this.add(output); this.add(help); }
0
public void moveUp() { if (y - v > 0) { y -= v; } else { y = 0; } }
1
public List<String> getmenuItemsCategory() { List<String> menuItemsCategory = new ArrayList<String>() { private static final long serialVersionUID = 3109256773218160485L; { try { //Connect to database conn = DriverManager.getConnection(url, userName, password); stmt = conn.createStatement(); ResultSet rset = null; PreparedStatement pstmt = null; pstmt = conn.prepareStatement("select distinct category from Course order by category asc"); rset = pstmt.executeQuery(); while (rset.next()) { add(rset.getString("category")); } } catch (SQLException e) { response = "SQLException: " + e.getMessage(); while ((e = e.getNextException()) != null) { response = e.getMessage(); } } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { response = "SQLException: " + e.getMessage(); while ((e = e.getNextException()) != null) { response = e.getMessage(); } } } } }; return menuItemsCategory; }
7
@Override public boolean isQuestionAlreadyAnswered(String userId, Long qId) { try { pm = PMF.get().getPersistenceManager(); Query query = pm.newQuery(User.class, ":p.contains(userId)"); List<User> result = (List<User>) query.execute(userId); if (result.size() > 0) { List<Long> userActivity = result.get(0).getUserActivity(); pm.close(); if (userActivity != null) { for (int i = 0; i < userActivity.size(); i++) { if (userActivity.get(i) != null) { Long activityId = userActivity.get(i); Long DBqId = getQuestionIdFromActivityId(activityId); if (DBqId.equals(qId)) { return true; } } } } } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage()); return false; } finally { pm.close(); } return false; }
6
@Override public void doMedianBlur() { if (imageManager.getBufferedImage() == null) return; WritableRaster raster = imageManager.getBufferedImage().getRaster(); double[][] newPixels = new double[raster.getWidth()][raster.getHeight()]; for (int x = 1; x < raster.getWidth() - 1; x++) { for (int y = 1; y < raster.getHeight() - 1; y++) { List<Double> mr_rogers = new ArrayList<Double>(); mr_rogers.add(raster.getPixel(x+1, y+1, new double[3])[0]); mr_rogers.add(raster.getPixel(x+1, y-1, new double[3])[0]); mr_rogers.add(raster.getPixel(x, y+1, new double[3])[0]); mr_rogers.add(raster.getPixel(x, y-1, new double[3])[0]); mr_rogers.add(raster.getPixel(x-1, y+1, new double[3])[0]); mr_rogers.add(raster.getPixel(x-1, y-1, new double[3])[0]); mr_rogers.add(raster.getPixel(x, y, new double[3])[0]); mr_rogers.add(raster.getPixel(x+1, y, new double[3])[0]); mr_rogers.add(raster.getPixel(x-1, y, new double[3])[0]); Collections.sort(mr_rogers); double[] pixel = new double[3]; pixel[0] = mr_rogers.get(mr_rogers.size()/2); if (pixel[0] > 255) pixel[0] = 255; else if (pixel[0] < 0) pixel[0] = 0; newPixels[x][y] = pixel[0]; } } for (int x = 1; x < raster.getWidth() - 1; x++) { for (int y = 1; y < raster.getHeight() - 1; y++) { double[] pixel = new double[3]; pixel[0] = pixel[1] = pixel[2] = newPixels[x][y]; raster.setPixel(x, y, pixel); } } GUIFunctions.refresh(); }
7
public void doClick(int btn, int mod) { if(!isActual()) return; if (UI.instance.mapview != null) { Coord sz = UI.instance.mapview.sz; Coord sc = new Coord((int) Math.round(Math.random() * 200 + sz.x / 2 - 100), (int) Math.round(Math.random() * 200 + sz.y / 2 - 100)); Coord oc = position(); UI.instance.mapview.wdgmsg("click", sc, oc, btn, mod, gob_id, oc); } }
2
@SuppressWarnings("unchecked") @Override public void onResponseReceived(Request request, Response response) { if( response.getStatusCode() == HTTP_OK ) { try { JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject(); if( jsonObject != null ) { callback.onSuccess((T)deserialize(jsonObject.get("result"))); } } catch (IllegalArgumentException e) { callback.onFailure(new JSONRPCEmptyResponseException()); } } else { // Handle all other statusCodes the same way callback.onFailure(new JSONRPCEmptyResponseException()); } }
3
void move() { System.out.println("A goose is flying"); }
0
@Override public boolean connect(String host, int port) { log.fine("Connecting to:"+host+" on Port:"+port); if(side == Side.CLIENT) { if(SERVER != null) { disconnect(SERVER); try { SERVER.stop(); } catch(Throwable e) { e.printStackTrace(); } SERVER = null; } socket = new ConnectionEstablishment(host, port).getSocket(); if(socket != null) { try { SERVER = new BasicIOHandler(socket.getInputStream(), socket.getOutputStream(), this, true); SERVER.start(); } catch(IOException e) { e.printStackTrace(); return false; } } else { return false; } return true; } else { return true; } }
5
public boolean AIorPlayer(){ if (getHold()>21) AI=true; else AI=false; return AI; }
1
public void runAcceptor(){ while(!Thread.interrupted()){ Socket clientSocket; try { clientSocket = serverSocket.accept(); } catch (IOException e) { LOG.severe("Error while waiting for client-connection! " + e.getMessage()); break; } clientHandlers.put(clientSocket.getRemoteSocketAddress(), new ClientHandler(clientSocket, protocol, protocolConnection)); } try { serverSocket.close(); } catch (IOException e) { LOG.severe("Error while closing serverSocket! " + e.getMessage()); } }
3
public int namespace(String title) throws IOException { // sanitise title = title.replace('_', ' '); if (!title.contains(":")) return MAIN_NAMESPACE; String namespace = title.substring(0, title.indexOf(':')); // all wiki namespace test if (namespace.equals("Project talk")) return PROJECT_TALK_NAMESPACE; if (namespace.equals("Project")) return PROJECT_NAMESPACE; // cache this, as it will be called often if (namespaces == null) { String line = fetch(query + "action=query&meta=siteinfo&siprop=namespaces", "namespace", false); namespaces = new HashMap<String, Integer>(30); while (line.contains("<ns")) { int x = line.indexOf("<ns id="); if (line.charAt(x + 8) == '0') // skip main, it's a little different { line = line.substring(13); continue; } int y = line.indexOf("</ns>"); String working = line.substring(x + 8, y); int ns = Integer.parseInt(working.substring(0, working.indexOf('"'))); String name = working.substring(working.indexOf('>') + 1); namespaces.put(name, new Integer(ns)); line = line.substring(y + 5); } log(Level.INFO, "Successfully retrieved namespace list (" + (namespaces.size() + 1) + " namespaces)", "namespace"); } // look up the namespace of the page in the namespace cache if (!namespaces.containsKey(namespace)) return MAIN_NAMESPACE; // For titles like UN:NRV else return namespaces.get(namespace).intValue(); }
7
public void basicSetWorkout(Workout myWorkout) { if (this.workout != myWorkout) { if (myWorkout != null){ if (this.workout != myWorkout) { Workout oldworkout = this.workout; this.workout = myWorkout; if (oldworkout != null) oldworkout.unsetParcours(); } } } }
4
protected void mapChildrenKeys(Set<String> output, ConfigurationSection section, boolean deep) { if (section instanceof MemorySection) { MemorySection sec = (MemorySection) section; for (Map.Entry<String, Object> entry : sec.map.entrySet()) { output.add(createPath(section, entry.getKey(), this)); if ((deep) && (entry.getValue() instanceof ConfigurationSection)) { ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); mapChildrenKeys(output, subsection, deep); } } } else { Set<String> keys = section.getKeys(deep); for (String key : keys) { output.add(createPath(section, key, this)); } } }
5
public EquationsHard() { this.multiply = getRandomBool(); x = randomNumber(1, Game.getHardness().getMaxNumb()); y = x * randomNumber(1, Game.getHardness().getMaxNumb() / 2); // result * x = y; -> result = y / x; if (multiply) result = y / x; // result / x = y; -> result = x * y; else result = x * y; score = Game.getHardness().getRatio() * StatementType.EQUATIONS_EASY.getScore(); }
1
public int getRandomNumber(int min, int max) { return (int) Math.floor(Math.random() * (max - min + 1)) + min; }
0
@Override public boolean equals(Object obj) { boolean res = false; if (obj instanceof TableEntry) { TableEntry other = (TableEntry) obj; if(other.tableName.equals(tableName)) { if(other.dbId.equals(dbId)) { res = true; } } } return res; }
3
private static Image getImage(String filename) { // to read from file ImageIcon icon = new ImageIcon(filename); // try to read from URL if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { try { URL url = new URL(filename); icon = new ImageIcon(url); } catch (Exception e) { /* not a url */ } } // in case file is inside a .jar if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { URL url = StdDraw.class.getResource(filename); if (url == null) throw new RuntimeException("image " + filename + " not found"); icon = new ImageIcon(url); } return icon.getImage(); }
6
protected static void formatTimeDifference(long diff, StringBuilder b){ //--Get Values int mili = (int) diff % 1000; long rest = diff / 1000; int sec = (int) rest % 60; rest = rest / 60; int min = (int) rest % 60; rest = rest / 60; int hr = (int) rest % 24; rest = rest / 24; int day = (int) rest; //--Make String if(day > 0) b.append(day).append(day > 1 ? " days, " : " day, "); if(hr > 0) b.append(hr).append(hr > 1 ? " hours, " : " hour, "); if(min > 0) { if(min < 10){ b.append("0"); } b.append(min).append(":"); } if(min > 0 && sec < 10){ b.append("0"); } b.append(sec).append(".").append(mili); if(min > 0) b.append(" minutes"); else b.append(" seconds"); }
9
public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { JCheckBox editor = null; filter = getFilterOut(value); if (filter != null) { node = (DefaultMutableTreeNode) value; editor = (JCheckBox) (super.getComponent()); editor.setText(filter.getName()); editor.setSelected(filter.isActive()); option = null; } else { option = getDescOut(value); if (option != null) { filter = getFilterOut(((DefaultMutableTreeNode) value) .getParent()); if (filter != null) { editor = (JCheckBox) (super.getComponent()); editor.setText(filter.getDescription(option)); editor.setSelected(filter.isSelected(option)); } else { option = null; filter = null; } } } return editor; }
3
public List<Venda> listarTodas() throws Exception{ try{ PreparedStatement comando = conexao .getConexao().prepareStatement("SELECT * FROM vendas WHERE ativo = 1"); ResultSet consulta = comando.executeQuery(); comando.getConnection().commit(); List<Venda> listaVendas = new LinkedList<>(); while(consulta.next()){ Venda tmpVenda = new Venda(); Cliente tmpCliente; FormasPagamento tmpFormaPagamento; UsuarioSistema tmpusuario; List<ItemVenda> listaDeItens; UsuarioSistemaDAO daoUsuario = new UsuarioSistemaDAO(); ClienteDAO daoCliente = new ClienteDAO(); FormasPagamentoDAO daoFormasPagamento = new FormasPagamentoDAO(); ItemVendaDAO daoItemVenda = new ItemVendaDAO(); // Listando os usuarios da venda tmpusuario = daoUsuario.Abrir(consulta.getInt("id_usuario")); tmpFormaPagamento = daoFormasPagamento.Abrir(consulta.getInt("id_tipo_pagamento")); tmpCliente = daoCliente.Abrir(consulta.getInt("id_cliente")); listaDeItens = daoItemVenda.listarTodos(consulta.getInt("id")); //System.out.print(tmpCliente); tmpVenda.setId(consulta.getInt("id")); tmpVenda.setHorario(consulta.getDate("horario")); tmpVenda.setValor(consulta.getFloat("valor_total")); tmpVenda.setCliente(tmpCliente); tmpVenda.setFormaPagamento(tmpFormaPagamento); tmpVenda.setUsuario(tmpusuario); tmpVenda.setItens(listaDeItens); listaVendas.add(tmpVenda); } return listaVendas; }catch(SQLException ex){ ex.printStackTrace(); return null; } }
2
public void insert(String table, ArrayList<String> fields, ArrayList<String> values) { if(fields != null) if(fields.size() != values.size()) throw new IllegalArgumentException("The number of fields and values must correspond."); String tableString = "`" + table + "`"; String fieldsString = fields == null ? "" : " (" + StringUtils.join(fields, ", ") + ")"; String valuesString = "?"; for(int i = 1; i<values.size(); i++){ valuesString += ", ?"; } String insertSQL = "INSERT INTO " + tableString + fieldsString + " VALUES (" + valuesString + ");"; connection.execute(insertSQL, values, false); }
4
protected Automaton getAutomaton() { return automaton; }
0
public Game() { board = new Board(2,4,4, new Random().nextInt(4), new Random().nextInt(4)); }
0
private String checkType(Nodo chk){ String res=new String(); switch(chk.getToken()){ case Identificador: res+=this.genCode(Nodo.KindToken.ID,((Nodo)chk.getNodo().iterator().next()),chk.getDato()); break; case PalabraReservada: if(chk.getDato().equals("if")){ res+=this.genCode(Nodo.KindToken.IF, chk, chk.getDato()); }else if(chk.getDato().equals("while")){ res+=this.genCode(Nodo.KindToken.WHILE, chk, chk.getDato()); }else if(chk.getDato().equals("do")){ res+=this.genCode(Nodo.KindToken.DO, chk, chk.getDato()); }else if(chk.getDato().equals("int")){ res+=this.genCode(Nodo.KindToken.INT, chk, chk.getDato()); }else if(chk.getDato().equals("float")){ res+=this.genCode(Nodo.KindToken.FLOAT, chk, chk.getDato()); }else if(chk.getDato().equals("write")){ res+=this.genCode(Nodo.KindToken.WRITE, chk, chk.getDato()); }else if(chk.getDato().equals("read")){ res+=this.genCode(Nodo.KindToken.READ, chk, chk.getDato()); } } return res; }
9
public static boolean validCastle(int myXCoor, int myYCoor, int targXCoor, int targYCoor){ if (myYCoor != targYCoor) return false; else{ if (myXCoor < targXCoor){ for (int i = myXCoor+1;i<targXCoor;i++){ if ( !(board.isEmpty(i,myYCoor)) ){ return false; } } return true; } else if (myXCoor > targXCoor){ for (int i = myXCoor-1;i>targXCoor;i--){ if ( !(board.isEmpty(i,myYCoor)) ){ return false; } } return true; } else{ return false; } } }
7
public List<V> put(K key, List<V> value) { return this.map.put(key, value); }
0
protected void stepFWDCalc(boolean showSteps) { if (m_currentStep == 0) { m_btnSetOne.setEnabled(false); m_btnSetTwo.setEnabled(false); m_btnSetGapOne.setEnabled(false); m_btnSetGapTwo.setEnabled(false); m_btnPrev.setEnabled(true); m_btnBeginning.setEnabled(true); } Point realD = getCoordsByStep(m_currentStep); Point D = new Point(realD.x - 1, realD.y - 1); int p = 1; m_l1Choiche.setBackground(m_mainPane.getBackground()); m_l2Choiche.setBackground(m_mainPane.getBackground()); m_l3Choiche.setBackground(m_mainPane.getBackground()); CellElement leftCell = m_dpTable.getCell(realD.x - 1, realD.y); CellElement topCell = m_dpTable.getCell(realD.x, realD.y - 1); CellElement topLeftCell = m_dpTable.getCell(realD.x - 1, realD.y - 1); CellElement currentCell = m_dpTable.getCell(realD.x, realD.y); if (m_s2.charAt(realD.x - 2) == m_s1.charAt(realD.y - 2)) { p = 0; } if (showSteps) { String DEqual = "D(" + (D.y) + ", " + (D.x) + ") = Min"; String DLeft = "D(" + (D.y) + ", " + (D.x-1) + ") + 1 = " + leftCell.getVal() + " + 1 = " + (leftCell.getIntVal() + 1); String DTop = "D(" + (D.y-1) + ", " + (D.x) + ") + 1 = " + topCell.getVal() + " + 1 = " + (topCell.getIntVal() + 1); ////DUMB BUG // String DLeft = "D(" + (D.y - 1) + ", " + (D.x) + ") + 1 = " + // leftCell.getVal() + " + 1 = " + (leftCell.getIntVal() + 1); // String DTop = "D(" + (D.y) + ", " + (D.x - 1) + ") + 1 = " + // topCell.getVal() + " + 1 = " + (topCell.getIntVal() + 1); String DTopLeft = "D(" + (D.y - 1) + ", " + (D.x - 1) + ") + " + p + " = " + topLeftCell.getVal() + " + " + p + " = " + (topLeftCell.getIntVal() + p); m_lDEqual.setText(DEqual); m_l1Choiche.setText(DLeft); m_l2Choiche.setText(DTop); m_l3Choiche.setText(DTopLeft); } int fromLeftVal = leftCell.getIntVal() + 1; int fromTopVal = topCell.getIntVal() + 1; int fromTopLeftVal = topLeftCell.getIntVal() + p; int min = Math.min(fromLeftVal, Math.min(fromTopVal, fromTopLeftVal)); // Init choosen array LinkedList highlightList = new LinkedList(); if (fromLeftVal == min) { m_l1Choiche.setBackground(Color.yellow); currentCell.addLeftPointer(leftCell); highlightList.add(leftCell); } if (fromTopVal == min) { m_l2Choiche.setBackground(Color.yellow); currentCell.addTopPointer(topCell); highlightList.add(topCell); } if (fromTopLeftVal == min) { m_l3Choiche.setBackground(Color.yellow); currentCell.addDiagPointer(topLeftCell); highlightList.add(topLeftCell); } currentCell.setIntVal(min); if (showSteps) { if (p == 0) { // the two characters are equal: RED m_dpTable.setSideHighlight(currentCell, Color.red); } else { // the two characters are not equal: m_dpTable.setSideHighlight(currentCell, new Color(0, 255, 255)); } m_dpTable.setTriArrows(currentCell, true); m_dpTable.setMultipleCellHighlight(highlightList); m_dpTable.paint(m_dpTable.getGraphics()); } m_currentStep++; }
8
public static Dimension resizeToArea(int width, int height, long newArea) { double x1 = (double) width; double y1 = (double) height; double a1 = (double) (x1 * y1); double a2 = (double) newArea; double s = (float) Math.sqrt((a2/a1)); double x2 = x1 * s; double y2 = y1 * s; int newX = (int) Math.round(x2); int newY = (int) Math.round(y2); return new Dimension(newX, newY); }
0
public String GetCurrentLine(int pindex) { int tindex = pindex; if (pindex >= length) { tindex = length - 1; } while ((tindex > 0 )&& (iExpr.toCharArray()[tindex] != '\n')) { tindex--; } if (iExpr.toCharArray()[tindex] == '\n') { tindex++; } String CurrentLine = ""; while ((tindex < length) && (iExpr.toCharArray()[tindex] != '\n')) { CurrentLine = CurrentLine + iExpr.toCharArray()[tindex]; tindex++; } return CurrentLine + "\n"; }
6
public void pokupiPodatke() { if(rdbtnOracle.isSelected()) { tip = textField_Host.getText() + " - Oracle"; kon = new OracleKonekcija(textField_User.getText(), textField_Pass.getText(), textField_Host.getText(), textField_Port.getText(), textField_dbName.getText()); } else if(rdbtnPostgresql.isSelected()) { tip = textField_Host.getText() + " - PostgreSQL"; kon = new PostgreKonekcija(textField_User.getText(), textField_Pass.getText(), textField_Host.getText(), textField_Port.getText(), textField_dbName.getText()); } else if(rdbtnMssql.isSelected()) { tip = textField_Host.getText() + " - MSSQL"; kon = new MssqlKonekcija(textField_User.getText(), textField_Pass.getText(), textField_Host.getText(), textField_Port.getText(), textField_dbName.getText()); } else { tip = textField_Host.getText() + " - MySQL"; kon = new MysqlKonekcija(textField_User.getText(), textField_Pass.getText(), textField_Host.getText(), textField_Port.getText(), textField_dbName.getText()); } }
3
public static void main(String[] args) { //first, let's populate the list of primes. int a = 0, b = 2; while (a < 1000) { if (isPrime(b)) some_primes[a++] = b; b++; } // -------------------------------------- // double noverphi = 0; int n = 0; for (int i = 2; i < 1000000; i++) { //System.out.println(i); double phi = phi(i); if (noverphi < i / phi) { System.out.println("new n @ " + i); n = i; noverphi = i / phi; } } System.out.println("final n: " + n); }
4
public ConvertPDAToGrammarAction(AutomatonEnvironment environment) { super(environment); }
0
public void setDayBordersVisible(boolean dayBordersVisible) { this.dayBordersVisible = dayBordersVisible; if (initialized) { for (int x = 7; x < 49; x++) { if ("Windows".equals(UIManager.getLookAndFeel().getID())) { days[x].setContentAreaFilled(dayBordersVisible); } else { days[x].setContentAreaFilled(true); } days[x].setBorderPainted(dayBordersVisible); } } }
3
private void editorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_editorKeyTyped if ((evt.isControlDown() && (evt.getKeyChar() == (char) 24 || evt.getKeyChar() == (char) 22)) || (!evt.isActionKey() && !evt.isControlDown() && !evt.isAltDown())) { updateLineNum(); if (saved) { saved = false; updateTab(); } updateUndoRedo(); } }//GEN-LAST:event_editorKeyTyped
7
public int[][] getImagePixels(BufferedImage image) { int w = image.getWidth(null); int h = image.getHeight(null); int[] tmpPixels = new int[w * h]; image.getRGB(0, 0, w, h, tmpPixels, 0, w); int[][] pixels = new int[w][h]; for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { pixels[x][h-1-y] = tmpPixels[x+y*w] & Integer.parseInt("FFFFFF", 16); } } return pixels; }
2
public void setResolution(Dimension res) { this.res = res; if (res != null) resolution.setText(res.width+"x"+res.height); else resolution.setText(" "); }
1
public static Direction getByMovement(int xa, int ya) { if (xa < 0) return LEFT; if (xa > 0) return RIGHT; if (ya < 0) return UP; if (ya > 0) return DOWN; return NONE; }
4
private boolean checkIsCreate(String stype, GameDescription game, ArrayList<SpriteData> allSprites){ for(SpriteData sprite:allSprites){ if(spawnerTypes.contains(sprite.type) && sprite.sprites.contains(stype)){ return true; } for(SpriteData sprite2:allSprites){ ArrayList<InteractionData> data = game.getInteraction(sprite.name, sprite2.name); for (InteractionData d:data){ if(spawnInteractions.contains(d.type) && d.sprites.contains(stype)){ return true; } } } } return false; }
7
private void selectFire() { squareSelector.reset(); squareSelector.setCriteria(new SquareCriteria() { private final String desc = "Select: Fire"; public String getDescription() { return desc; } public boolean isSquareValid( SquareSelector squareSelector, int roomId, int squareId ) { if ( roomId < 0 || squareId < 0 ) return false; for (FireSprite fireSprite : fireSprites) { if ( fireSprite.getRoomId() == roomId && fireSprite.getSquareId() == squareId ) { return true; } } return false; } }); squareSelector.setCallback(new SquareSelectionCallback() { public boolean squareSelected( SquareSelector squareSelector, int roomId, int squareId ) { for (FireSprite fireSprite : fireSprites) { if ( fireSprite.getRoomId() == roomId && fireSprite.getSquareId() == squareId ) { showFireEditor( fireSprite ); break; } } return true; } }); squareSelector.setVisible(true); }
8
public ResultSet searchEngineInfo(String patient_info){ try{ if(Helper.isInteger(patient_info)){ String testRecordQuery = "SELECT p.name, p.health_care_no, t.patient_no, t.employee_no, " + "t.test_id, t.type_id, tt.type_id, tt.test_name, t.test_date, t.result " + "FROM patient p, test_record t, test_type tt " + "WHERE " + " p.health_care_no = " + Integer.parseInt(patient_info) + " AND t.patient_no = p.health_care_no " + "AND t.type_id = tt.type_id"; rs = stmt.executeQuery(testRecordQuery); }else { String testRecordQuery = "SELECT p.name, p.health_care_no, t.patient_no, t.employee_no, t.test_id, "+ "t.type_id, tt.type_id, tt.test_name, t.result, t.test_date " + "FROM patient p, test_record t, test_type tt " + "WHERE t.patient_no = p.health_care_no " + "AND UPPER(p.name) = UPPER('" + patient_info + "')" + " AND t.type_id = tt.type_id"; rs = stmt.executeQuery(testRecordQuery); } } catch(SQLException e){ } return rs; }
2
public void setId(Integer id) { this.id = id; }
0
private boolean isValidInput(final String s) { return s.matches("[1-9]{1}"); }
0
public static MultiSearcher wrapSearcher(final Searcher s, final int edge) throws IOException { // we can't put deleted docs before the nested reader, because // it will through off the docIds Searcher[] searchers = new Searcher[] { edge < 0 ? s : new IndexSearcher(makeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(makeEmptyIndex(edge < 0 ? 65 : 0), true), new IndexSearcher(makeEmptyIndex(0), true), 0 == edge ? s : new IndexSearcher(makeEmptyIndex(0), true) }), new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 3), true), new IndexSearcher(makeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 5), true), new IndexSearcher(makeEmptyIndex(0), true), 0 < edge ? s : new IndexSearcher(makeEmptyIndex(0), true) }) }; MultiSearcher out = new MultiSearcher(searchers); out.setSimilarity(s.getSimilarity()); return out; }
6
public void addPatient(Patient newPatient) { if (this.nextPatient == null) { this.nextPatient = newPatient; } else { this.nextPatient.addPatient(newPatient); } }
1
public void Eliminar(String pArchivo) throws Exception { try { //Se elimina el archivo File fichero = new File(pArchivo); if (!fichero.delete()) //Si no encuentra el archivo se muestra la excepcion throw new Exception("El fichero " + pArchivo + " no puede ser borrado!"); } catch (Exception e) { throw new Exception(e); } }
2
public boolean authenticate(String email, String hash) { initConnection(); //Check password matches for given email String preparedString = null; PreparedStatement preparedQuery = null; try { //Prepare Statement preparedString = "SELECT email,password FROM users WHERE email = ? AND password = ?;"; preparedQuery = (PreparedStatement) connection.prepareStatement(preparedString); preparedQuery.setString(1, email); preparedQuery.setString(2, hash); //Execute Statement ResultSet resultSet = preparedQuery.executeQuery(); //TODO: Remove debug System.out.println("resultset for [" + preparedQuery.toString() + "] " + ((resultSet == null) ? "== null" : "!= null")); //Handle Result return resultSet.first(); } catch(Exception ex) { System.out.println("Problem executing SQL Query [" + preparedQuery.toString() + "] in LoginService.java"); ex.printStackTrace(); } finally { try { //Finally close stuff to return connection to pool for reuse preparedQuery.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return false; }
3
boolean showDialog(final ImagePlus imp, final String[] list) { final int fileCount = list.length; String name = imp.getTitle(); if (name.length() > 4 && (name.substring(name.length() - 4, name.length())) .equalsIgnoreCase(".tif")) { name = name.substring(0, name.length() - 4); } int i = name.length() - 1; while (i > 1 && name.charAt(i) >= '0' && name.charAt(i) <= '9') { name = name.substring(0, i); i--; } final HypervolumeOpenerDialog gd = new HypervolumeOpenerDialog("Sequence Options", imp, list); gd.addNumericField("Number of Images: ", fileCount, 0); gd.addNumericField("Starting Image: ", 1, 0); gd.addNumericField("Increment: ", 1, 0); gd.addStringField("File Name Contains: ", name); gd.addNumericField("Scale Images", scale, 0, 4, "%"); gd.addCheckbox("Convert to 8-bit Grayscale", grayscale); gd.addMessage("10000 x 10000 x 1000 (100.3MB)"); gd.showDialog(); if (gd.wasCanceled()) return false; n = (int) gd.getNextNumber(); start = (int) gd.getNextNumber(); increment = (int) gd.getNextNumber(); if (increment < 1) increment = 1; scale = gd.getNextNumber(); if (scale < 5.0) scale = 5.0; if (scale > 100.0) scale = 100.0; filter = gd.getNextString(); grayscale = gd.getNextBoolean(); return true; }
9
public Object tooltip(Coord c, boolean again) { long now = System.currentTimeMillis(); if (!again) hoverstart = now; if ((now - hoverstart) < 1000) { if (shorttip == null) { String tip = shrtTip(); if (tip == null) return null; shorttip = RichText.render(tip, 200); } return (shorttip); } else { if (longtip == null) { String tip = lngTip(); if (tip == null) return null; longtip = RichText.render(tip, 200); } return (longtip); } }
6
public SharedTorrent getTorrent() { return this.torrent; }
0
static List<String> splitCSVLine(List<String> buf, String line){ Stream.of(line.split(";")).map(String::trim).forEach(buf::add); if (line.endsWith(";")) { buf.add(""); } return buf; }
1
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, Case__typeInfo)) { setCase((com.sforce.soap.enterprise.sobject.Case)__typeMapper.readObject(__in, Case__typeInfo, com.sforce.soap.enterprise.sobject.Case.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CaseAccessLevel__typeInfo)) { setCaseAccessLevel(__typeMapper.readString(__in, CaseAccessLevel__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CaseId__typeInfo)) { setCaseId(__typeMapper.readString(__in, CaseId__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, LastModifiedBy__typeInfo)) { setLastModifiedBy((com.sforce.soap.enterprise.sobject.User)__typeMapper.readObject(__in, LastModifiedBy__typeInfo, com.sforce.soap.enterprise.sobject.User.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, LastModifiedById__typeInfo)) { setLastModifiedById(__typeMapper.readString(__in, LastModifiedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, LastModifiedDate__typeInfo)) { setLastModifiedDate((java.util.Calendar)__typeMapper.readObject(__in, LastModifiedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, RowCause__typeInfo)) { setRowCause(__typeMapper.readString(__in, RowCause__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, UserOrGroupId__typeInfo)) { setUserOrGroupId(__typeMapper.readString(__in, UserOrGroupId__typeInfo, java.lang.String.class)); } }
9
@Override protected void onReceive(String message) { System.out.println("Received message: \"" + message + "\""); Message msg = Message.parse(message); switch(msg.getType()) { case ID_RESPONSE: //TODO handle id break; case SPAWN: //TODO spawn entity break; case DESPAWN: //TODO despawn entity break; case MOVE: //TODO move entity break; case BUMP: //TODO bump entity back break; case SYNC: //TODO sync entity break; } }
6
@Override public boolean onCommand(final CommandSender sender,final Command command,final String label,final String[] args) { if (args.length <= 1) { return false; } final OfflinePlayer player = this.plugin.getServer().getOfflinePlayer(args[0]); if (player == null) { sender.sendMessage(ChatColor.RED + "Unknown player."); return true; } if (this.plugin.isBanned(player.getName())) { sender.sendMessage(ChatColor.RED + player.getName() + " is already banned."); return true; } // Ban, no reason. if (args.length == 2) { Event event = this.plugin.tempBanPlayer( player.getName(), sender.getName(), args[1] ); if (event != null) { this.plugin.broadcast(event); } return true; } // Ban Event event = this.plugin.tempBanPlayer( player.getName(), sender.getName(), StringUtils.join(args," ",2,args.length), args[1] ); if (event != null) { this.plugin.broadcast(event); } return true; }
6
@Override public List<AssemblyLine> generate(Context context) { final List<AssemblyLine> lines = Lists.newLinkedList(); if (Compiler.debug) { lines.add(new Comment("Start condition term")); } if (children.size() == 1) { context.setValue("condFactorInstruction", context.getValue("condTermInstruction")); AbstractSyntaxNode factor = children.get(0); lines.addAll(factor.generate(context)); } else { boolean first = true; String falseLabel = context.getUniqueId("and-chain-false"); for (int i = 0; i < children.size(); i++) { AbstractSyntaxNode child = children.get(i); if (child instanceof Operation) { Operation op = (Operation) child; if (i == 0 || i == children.size() - 1) { Context.error("Unexpected &&"); } if (op.getOpType() != Token.AND) { Context.error("Unexpected op " + op.getOpType()); } if (first) { String aTrueLabel = context.getUniqueId("a-true"); String bTrueLabel = context.getUniqueId("b-true"); AbstractSyntaxNode a = children.get(i - 1); AbstractSyntaxNode b = children.get(i + 1); context.setValue("condFactorInstruction", new Instruction(Opcode.SET, new RegisterAccess( "PC"), new LabelCall(aTrueLabel))); lines.addAll(a.generate(context)); lines.add(new Instruction(Opcode.SET, new RegisterAccess("PC"), new LabelCall( falseLabel))); lines.add(new Label(aTrueLabel)); context.setValue("condFactorInstruction", new Instruction(Opcode.SET, new RegisterAccess( "PC"), new LabelCall(bTrueLabel))); lines.addAll(b.generate(context)); lines.add(new Instruction(Opcode.SET, new RegisterAccess("PC"), new LabelCall( falseLabel))); lines.add(new Label(bTrueLabel)); first = false; } else { String cTrueLabel = context.getUniqueId("c-true"); AbstractSyntaxNode c = children.get(i + 1); context.setValue("condFactorInstruction", new Instruction(Opcode.SET, new RegisterAccess( "PC"), new LabelCall(cTrueLabel))); lines.addAll(c.generate(context)); lines.add(new Instruction(Opcode.SET, new RegisterAccess("PC"), new LabelCall( falseLabel))); lines.add(new Label(cTrueLabel)); } lines.add((AssemblyLine) context .getValue("condTermInstruction")); lines.add(new Label(falseLabel)); } } } return lines; }
8
@RequestMapping(value = "/event-branch-room-event-list/{eventBranchId}", method = RequestMethod.GET) @ResponseBody public RoomEventListResponse eventBranchRoomEventList( @PathVariable(value = "eventBranchId") final String eventBranchIdStr ) { Boolean success = true; String errorMessage = null; List<RoomEvent> roomEventList = null; Long eventBranchId = null; try { eventBranchId = controllerUtils.convertStringToLong(eventBranchIdStr, true); roomEventList = roomEventPresenter.findRoomEventsByEventBranchId(eventBranchId); } catch (UrlParameterException e) { success = false; errorMessage = "Event branch ID is wrong or empty"; } return new RoomEventListResponse(success, errorMessage, roomEventList); }
1
public static void chplft_draw_bg(osd_bitmap bitmap, int priority) { int sx, sy, offs; int choplifter_scroll_x_on = (system1_scrollx_ram.read(0) == 0xE5 && system1_scrollx_ram.read(1) == 0xFF) ? 0 : 1; if (priority == -1) { /* optimized far background */ /* for every character in the background video RAM, check if it has * been modified since last time and update it accordingly. */ for (offs = 0; offs < system1_backgroundram_size[0]; offs += 2) { if (bg_dirtybuffer[offs / 2] != 0) { int code, color; bg_dirtybuffer[offs / 2] = 0; code = (system1_backgroundram.read(offs) | (system1_backgroundram.read(offs + 1) << 8)); code = ((code >> 4) & 0x800) | (code & 0x7ff); /* Heavy Metal only */ color = ((code >> 5) & 0x3f) + 0x40; sx = (offs / 2) % 32; sy = (offs / 2) / 32; drawgfx(bitmap1, Machine.gfx[0], code, color, 0, 0, 8 * sx, 8 * sy, null, TRANSPARENCY_NONE, 0); } } /* copy the temporary bitmap to the screen */ if (choplifter_scroll_x_on != 0) { copyscrollbitmap(bitmap, bitmap1, 32, scrollx_row, 0, null, Machine.drv.visible_area, TRANSPARENCY_NONE, 0); } else { copybitmap(bitmap, bitmap1, 0, 0, 0, 0, Machine.drv.visible_area, TRANSPARENCY_NONE, 0); } } else { priority <<= 3; for (offs = 0; offs < system1_backgroundram_size[0]; offs += 2) { if ((system1_backgroundram.read(offs + 1) & 0x08) == priority) { int code, color; code = (system1_backgroundram.read(offs) | (system1_backgroundram.read(offs + 1) << 8)); code = ((code >> 4) & 0x800) | (code & 0x7ff); /* Heavy Metal only */ color = ((code >> 5) & 0x3f) + 0x40; sx = 8 * ((offs / 2) % 32); sy = (offs / 2) / 32; if (choplifter_scroll_x_on != 0) { sx = (sx + scrollx_row[sy]) & 0xff; } sy = 8 * sy; drawgfx(bitmap, Machine.gfx[0], code, color, 0, 0, sx, sy, Machine.drv.visible_area, TRANSPARENCY_PEN, 0); } } } }
9
public static void displayURL(String url) { if (url == null || url.length() == 0) { url = "http://www.google.com"; } boolean windows = isWindowsPlatform(); String cmd = null; try { if (windows) { // cmd = 'rundll32 url.dll,FileProtocolHandler http://...' /* * Rundll32 doesn't like .htm or .html files, which is why .ht%6D or .ht%6D%6C works, %6D is the * hexidecimal code for m. %6C is the hexidecimal code for l. */ if (url.toUpperCase().endsWith(".HTM")) { url = url.substring(0, url.length() - 1) + "%6D"; } if (url.toUpperCase().endsWith(".HTML")) { url = url.substring(0, url.length() - 2) + "%6D%6C"; } cmd = WIN_PATH + " " + WIN_FLAG + " " + url; Runtime.getRuntime().exec(cmd); } else { // Under Unix, Netscape has to be running for the "-remote" // command to work. So, we try sending the command and // check for an exit value. If the exit command is 0, // it worked, otherwise we need to start the browser. // cmd = 'netscape -remote openURL(http://www.javaworld.com)' cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")"; Process p = Runtime.getRuntime().exec(cmd); try { // wait for exit code -- if it's 0, command worked, // otherwise we need to start the browser up. int exitCode = p.waitFor(); if (exitCode != 0) { // Command failed, start up the browser // cmd = 'netscape http://www.javaworld.com' cmd = UNIX_PATH + " " + url; p = Runtime.getRuntime().exec(cmd); } } catch (InterruptedException x) { System.err.println("Error bringing up browser, cmd='" + cmd + "'"); System.err.println("Caught: " + x); } } } catch (IOException x) { // couldn't exec browser System.err.println("Could not invoke browser, command=" + cmd); System.err.println("Caught: " + x); } }
8
@Override public String toString() { StringBuffer stringBuffer = new StringBuffer(); for(int row = 0; row < getRowSize(); row++) { for(int column = 0; column < getColumnSize(); column++) { Integer move = getMoveAt(row, column); String moveToPrint = ""; if (move == null) { moveToPrint = " "; } else { moveToPrint = move.toString(); } stringBuffer.append("|").append(moveToPrint); } stringBuffer.append("|\n"); } return stringBuffer.toString(); }
3
public static ComponentUI createUI(JComponent c) { return new MetalScrollBarUI(); }
0
public static boolean isSpecialTrainer(Trainer t) { switch(t.type) { case JAVA: if(t.name.equals("BOSS")) return true; else return false; case BABB: case ELITE: case GYM_LEADER: case RIVAL: return true; default: return false; } }
6
public boolean smartClick(){ boolean isClicked=isEnabled(); if(isClicked){ click(); } return isClicked; }
1
public void removeAll() { for (int i = 0; i < items.size(); i++) { items.remove(i); } for (int i = 0; i < backgroundParticles.size(); i++) { backgroundParticles.remove(i); } for (int i = 0; i < entities.size(); i++) { entities.remove(i); } for (int i = 0; i < projectiles.size(); i++) { projectiles.remove(i); } for (int i = 0; i < particles.size(); i++) { particles.remove(i); } for (int i = 0; i < spriteParticles.size(); i++) { spriteParticles.remove(i); } }
6
public String getType() { if (this instanceof ItemCoupon) return "Item"; if (this instanceof EconomyCoupon) return "Economy"; if (this instanceof RankCoupon) return "Rank"; if (this instanceof XpCoupon) return "Xp"; else return null; }
4
public void calcPhaseDeviation() { // saves the result of the FFT in an object that contains the spectrum, // real and imaginary part. FFTComponents components = this.nextPhase(); double[] phase = new double[components.real.length]; double[] previousPhase = new double[components.real.length]; double[] antePreviousPhase = new double[components.real.length]; do { /* * get the phase from the components object */ phase = calcPhaseFromComponents(components); double phaseDeviation = 0; /** * used to normalize */ float totalSpectrum = 0; /** * prepare the data for the next iteration */ /* * iterate though the bins and sum the modulus of the phase * deviation. deltaPhi = Phi(n)-2Phi(n-1)+Phi(n-2) If using * weighting, each deltaphi has to be multiplied by the * correspondent spectrum magnitude. Note: One uses the formulas (8) * and (9) of Bello "A tutorial on onset detection in music signals" * and, for the weighting, the formula 2.4 in Simon Dixon * "Onset Detection Revisited" */ for (int i = 0; i < components.spectrum.length; i++) { if (!useWeighting) { phaseDeviation += Math.abs(phase[i] - 2 * previousPhase[i] + antePreviousPhase[i]); } else { phaseDeviation += Math .abs(components.spectrum[i] * (phase[i] - 2 * previousPhase[i] + antePreviousPhase[i])); } if (useNormalization) { totalSpectrum += Math.abs(components.spectrum[i]); } } /* * Adds the phase deviation to the list, dividing the result * obtained with the number of bins or doing the normalization */ if (!useNormalization) { PD.add((float) phaseDeviation / components.spectrum.length); } else { //to avoid division by zero if(totalSpectrum == 0) { totalSpectrum = 1; } PD.add((float) phaseDeviation / totalSpectrum); } /** * prepare the data for the next iteration */ // the antepreviousphase in the next iteration is the previous phase // in this iteration if (previousPhase != null) { System.arraycopy(previousPhase, 0, antePreviousPhase, 0, phase.length); } // the previous phase in the following iteration is the // current phase of this iteration System.arraycopy(phase, 0, previousPhase, 0, phase.length); } while ((components = this.nextPhase()) != null); }
7
@Override public void update(Observable o, Object value) { if (o instanceof RecordManager) { updateLastNames(RecordManager.getInstance().getUniqueLastNames()); final GivingRecord selectedRecord = RecordManager.getInstance().getSelectedRecord(); if (selectedRecord != null) { try { picker.setDate(SDF.parse(selectedRecord.getDateString())); } catch (PropertyVetoException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } lastNameCombo.setSelectedItem(selectedRecord.getLastName()); firstNameCombo.setSelectedItem(selectedRecord.getFirstName()); if (!selectedRecord.getFundType().isEmpty()) { fundType.setSelectedItem(selectedRecord.getFundType()); } else { fundType.setSelectedIndex(0); } checkNumberText.setText(selectedRecord.getCheckNumber()); if (fundType.getSelectedItem().equals("Check")) { checkNumberLabel.setEnabled(true); checkNumberText.setEnabled(true); } else { checkNumberLabel.setEnabled(false); checkNumberText.setText(""); checkNumberText.setEnabled(false); } for (CategoryInputPair input : categoryInputs) { final String category = input.getLabel().getText(); final Double amountForCategory = selectedRecord.getAmountForCategory(category); final String amountText = simpleCurrencyFormat.format(amountForCategory); input.getInputField().setText(amountText); } addUpdateButton.setText("Update"); } else { lastNameCombo.setSelectedIndex(0); fundType.setSelectedIndex(0); checkNumberText.setText(""); for (CategoryInputPair input : categoryInputs) { input.getInputField().setText(""); } addUpdateButton.setText("Add"); } } else if (o instanceof Settings) { initComponents(); } }
9
private static String loadSiteUID(){ String uid = DEFAULT_SITE_USER_ID; try{ FileInputStream fis = new FileInputStream(workingDir + SITE_UID_FILE_NAME); try{ BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); try { uid = reader.readLine(); } catch (IOException e) {} reader.close(); } catch (Exception e){} fis.close(); } catch (Exception e){} return uid; }
3
public void run(){ // If we have a list of replies from a previous repetition // calculate suspected processes if (lastHeartbeat != 0) { for(int i = 0; i <= p.getNo(); i++) { if (i != 0 && i != p.pid) { if (!successfulReplies[i-1] && !suspectedProcesses[i-1]) { Utils.out(p.pid,"Process " + i + " is now suspected"); suspectedProcesses[i-1] = true; isSuspected(i); } //clear the slot for next time successfulReplies[i-1] = false; } } } lastHeartbeat = System.currentTimeMillis(); //Utils.out(p.pid,""+lastHeartbeat); p.broadcast(Utils.HEARTBEAT,"" + lastHeartbeat); }
6
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // totaal hoeveelheid van alle kleuren int total = 0; int startAngle = 0; int arcAngle = 0; for (Color color: stats.keySet()) { // teller van alle kleuren worden bij elkaar opgeteld total += stats.get(color).getCount(); } // kleurt de piechart for (Color color : stats.keySet()) { if (stats.get(color).getCount() > 0) { // teller van een kleeur delen door de totaal en keer 360 graden arcAngle = (stats.get(color).getCount() * 360/ total) ; g.setColor(color); // draw de piechart g.fillArc(50, 50, width, height, startAngle, arcAngle); // start angle van de volgende kleur startAngle += arcAngle + 1; } } // paint de outline van de piechart g.setColor(Color.BLACK); g.drawArc(50, 50, width, height, 0, 360); }
3
private ConcatExpr parseConcatExpr(Vector<String> tokens, int lo, int hi) { ConcatExpr expr = new ConcatExpr(); for (int i = lo; i < hi; i++) { String v = tokens.get(i); if (v.length() >= 2 && v.charAt(0) == '<' && v.charAt(v.length() - 1) == '>') { expr.addItem(v.substring(1, v.length() - 1), false); //symbol } else { expr.addItem(v, true); //literal value } } return expr; }
4
public RealDistribution realisedDemand(int t, int k) throws ConvolutionNotDefinedException{ //check if k is lower or equal than t-l_max, then all orders will be open if (k <= t-getMaxOrderLeadTime()) return new RealSinglePointDistribution(0.0); //check if k is bigger than t, then all orders will be realised if (k > t) return totalDemand(); //in all other cases, get the corresponding sub array and fold it int numberOfRealizedOrders = k-t+getMaxOrderLeadTime(); RealDistribution[] orderDistributions = getOrderDistributions(); RealDistribution[] ordersToConvolute = new RealDistribution[numberOfRealizedOrders]; for (int i = 0; i < numberOfRealizedOrders; i++){ ordersToConvolute[i] = orderDistributions[getMaxOrderLeadTime()-i]; } return Convoluter.convolute(ordersToConvolute); }
3
Message getMessage(double x, double y) { Message result = null; for (Edge edge : edges) for (Message message : edge.queue.getMessages()) { if (message.isOnPoint(x, y) && (result == null || message.position < result.position)) result = message; } return result; }
5
private static int getAttribute(Node node, String attribname, int def) { final String attr = getAttributeValue(node, attribname); if (attr != null) { return Integer.parseInt(attr); } else { return def; } }
1