method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
95f63cd4-fd2b-4fd2-80a9-3d78650972a0
1
private void selectionDidChange() { if (mOwner != null) { mOwner.selectionDidChange(); } }
fc9d7c0e-4cbc-4d40-905c-d5d15c51c2d8
2
public boolean getKilpi(Pelihahmo h){ if (h == h1){ return getNappaimenTila(KILPI1); } else if (h == h2){ return getNappaimenTila(KILPI2); } else { return false; } }
f9eee122-6961-4d56-98ae-f954580298b4
7
public static void cast() { if (!Bank.isOpen()) { if (Widgets.get(1370, 0).validate()) { Widgets.get(1370, 20).click(true); Task.sleep(700, 800); Timer failSafe = new Timer(25000); while ((Inventory.getCount(Variables.leatherUsing) > 1 || Players .getLocal().getAnimation() != -1) && failSafe.isRunning()) { Task.sleep(50, 60); } } else { Item i = Inventory.getItem(Variables.leatherUsing); if (i != null) { if(!ActionBar.isReadyForInteract()) { ActionBar.makeReadyForInteract(); } ActionBar.useSlot(0); Task.sleep(400, 500); i.getWidgetChild().interact("Cast"); Task.sleep(1200, 1300); } } } else { Bank.close(); } }
c15a76e3-399b-4741-82d2-80e2dc126053
9
@Override protected List< ? extends Component> createBrickComponents() { ArrayList<Component> components = new ArrayList<Component>(); String tooltip = getTooltip(); // label if ( control.getLabel() != null ) { label = new JLabel(); label.setName(getName()+"/label"); label.setText( control.getLabel()); if ( tooltip != null ) label.setToolTipText( tooltip ); } // dropDownList dropDownList = new JComboBox(); dropDownList.setName(getName()+"/dropdownlist"); // set editable dropDownList.setEditable(control instanceof EditableDropDownListT); // dropDownList items List<ListItemT> listItems = ( control instanceof EditableDropDownListT ) ? ( (EditableDropDownListT) control ).getListItem() : ( (DropDownListT) control ).getListItem(); // TODO: throw error if there are no list items for ( ListItemT listItem : listItems ) dropDownList.addItem(listItem.getUiRep() != null ? listItem.getUiRep() : ""); // tooltip if ( tooltip != null ) dropDownList.setToolTipText( tooltip ); // default initializer dropDownList.setSelectedIndex(0); // select initValue if available String initValue = (String) ControlHelper.getInitValue( control, getAtdl4jOptions() ); if ( initValue != null ) setValue( initValue, true ); if (label != null){ components.add(label); } components.add( dropDownList); return components; }
0942110d-7e3b-4caa-8187-4d2522592f9c
6
public static String escapeJavaScriptString(String input) { StringBuilder retVal = new StringBuilder(input.length() + 10); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); switch (c) { case '"':case '\\': retVal.append('\\').append(c); break; case '\n': retVal.append("\\n"); break; case '\r': retVal.append("\\r"); break; case '\t': retVal.append("\\t"); break; default: retVal.append(c); } } return retVal.toString(); }
d017e533-b6fe-40a4-af87-17f6e7f5df21
8
private void changePosition() { float vSqrt = (float) (v * Math.sqrt(2)); if (BlinkTheGame.left) { if (BlinkTheGame.up) { setXY(x - v, y - v); } else if (BlinkTheGame.down) { setXY(x - v, y + v); } else { setXY(x - vSqrt, y); } } else if (BlinkTheGame.right) { if (BlinkTheGame.up) { setXY(x + v, y - v); } else if (BlinkTheGame.down) { setXY(x + v, y + v); } else { setXY(x + vSqrt, y); } } else if (BlinkTheGame.up) { setXY(x, y - vSqrt); } else if (BlinkTheGame.down) { setXY(x, y + vSqrt); } }
886f49e5-951d-4e50-8dc7-6788e246008d
3
public void flipV() { for (Connector c : connectors) { if (c.getPosition() == Position.top) c.setPosition(Component.Position.bottom); else if (c.getPosition() == Position.bottom) c.setPosition(Position.top); } }
de5c2baf-631e-4d46-83a3-dbfb1d7a877c
0
@Remove public void remove() { System.out.println("PersonAddressManagerBean:remove()"); }
57dd832b-0119-4b70-bfea-17765992ae28
0
public void setUserAgent(String userAgent) { this.userAgent = userAgent; }
8ebdd16f-9153-46fc-a2b8-62af3cab5a29
1
synchronized void shutdown() { try { mServerSocket.close(); } catch (Exception exception) { Log.error(exception); } }
48595250-5cf7-461d-bbee-dd88b17603e0
4
public ConvertiblePair(Class<?> sourceType, Class<?> targetType) { if (sourceType == null) { throw new IllegalArgumentException("Source type must not be null"); } else if (targetType == null) { throw new IllegalArgumentException("Target type must not be null"); } this.sourceType = sourceType; this.targetType = targetType; }
4bea320d-91fd-4cdc-81b1-f022efd0e994
9
@Test public void test() { // Test insertion order LRUCache<Integer, String> cache = new LRUCache<Integer, String>(10); int i; for (i = 0; i < keys.length; ++i) { cache.put(keys[i], values[i]); } i = 0; for (Iterator<Integer> iter = cache.keySet().iterator(); iter.hasNext();) { Integer key = iter.next(); Assert.assertEquals(keys[i], key); ++i; } i = 0; for (Iterator<String> iter = cache.values().iterator(); iter.hasNext();) { String value = iter.next(); Assert.assertEquals(values[i], value); ++i; } // Access in reverse order and check for (i = keys.length - 1; i >= 0; --i) { cache.get(keys[i]); } i = keys.length; for (Iterator<Integer> iter = cache.keySet().iterator(); iter.hasNext();) { --i; Integer key = iter.next(); Assert.assertEquals(keys[i], key); } i = keys.length; for (Iterator<String> iter = cache.values().iterator(); iter.hasNext();) { --i; String value = iter.next(); Assert.assertEquals(values[i], value); } // Access in forward order and check for (i = 0; i < keys.length; ++i) { cache.get(keys[i]); } i = 0; for (Iterator<Integer> iter = cache.keySet().iterator(); iter.hasNext();) { Integer key = iter.next(); Assert.assertEquals(keys[i], key); ++i; } i = 0; for (Iterator<String> iter = cache.values().iterator(); iter.hasNext();) { String value = iter.next(); Assert.assertEquals(values[i], value); ++i; } }
02125f63-d438-434a-b8f8-8bf04ca8b875
0
private void reduction(){ int gcd = getGCD(numerator, denominator); numerator = numerator / gcd; denominator = denominator / gcd; }
5ca5e716-8b4b-4d01-8f80-14dc08230889
4
private static void creerTblRegion() { if (!m_regInit) { try (BufferedReader br = new BufferedReader(new FileReader(Constant.m_regionList))) { String sCurrentLine; m_lstRegNom.clear(); m_tblRegions.clear(); while ((sCurrentLine = br.readLine()) != null) { // System.out.println("#####" + sCurrentLine + "\t#####line from regionlist.txt (NoyauReg)"); Region reg = new Region(sCurrentLine); String regnom = reg.getRegnom(); // avoid duplicates if (!m_tblRegions.containsKey(regnom)) { m_lstRegNom.add(regnom); } m_tblRegions.put(regnom, reg); // System.out.println("regTbl size:" + m_tblRegions.size() + " (NoyauReg)"); // System.out.println("regVec size:" + m_lstRegNom.size() + " (NoyauReg)"); } Collections.sort(m_lstRegNom); m_regInit = true; //DefaultComboBoxModel model = new DefaultComboBoxModel(m_lstRegNom); //cmbReg.setModel(model); } catch (IOException ee) { ee.printStackTrace(); } // System.out.println("region map:" + m_tblRegions + " (NoyauReg)"); } }
7c4308a4-15f6-4cc6-b6ac-3dc9d31099ce
3
@Override public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) throws InvalidHandshakeException { // Sec-WebSocket-Origin is only required for browser clients int v = readVersion( handshakedata ); if( v == 7 || v == 8 )// g return basicAccept( handshakedata ) ? HandshakeState.MATCHED : HandshakeState.NOT_MATCHED; return HandshakeState.NOT_MATCHED; }
8d8621c3-bf39-4396-a55f-0699f79a32be
6
public ArrayList<ArrayList> allMoves() { ArrayList<ArrayList> a = new ArrayList<ArrayList>(); for (int i = 0; i < pMoves().size(); i++) { a.add(pMoves().get(i)); } for (int i = 0; i < nMoves().size(); i++) { a.add(nMoves().get(i)); } for (int i = 0; i < bMoves().size(); i++) { a.add(bMoves().get(i)); } for (int i = 0; i < rMoves().size(); i++) { a.add(rMoves().get(i)); } for (int i = 0; i < qMoves().size(); i++) { a.add(qMoves().get(i)); } for (int i = 0; i < kMoves().size(); i++) { a.add(kMoves().get(i)); } return a; }
8247e8c0-1fd1-4b12-ac01-cbeba1c6cff9
2
public void render() { Graphics g = screen.getGraphics(); g.setColor(Color.black); g.fillRect(0, 0, pixel.width, pixel.height); //show the black screen with countdown if(swappingNow) { int secondsLeft = (int) ((timerPos / (1000/(tickTime*computerSpeed)) + 1)); String secString = " seconds"; if(secondsLeft == 1) secString = " second"; String str = secondsLeft + secString; g.setColor(Color.black); g.fillRect(0, 0, pixel.width, pixel.height); Font fontSave = g.getFont(); Font font = new Font("Verdana", Font.BOLD, 96); FontMetrics fm = g.getFontMetrics(font); int xText = pixel.width/2; int yText = pixel.height/2; xText += -(fm.stringWidth(str)/2) + 2; yText += fm.getAscent()/2; g.setColor(Color.white); g.setFont(font); g.drawString(str, xText, yText); g.setFont(fontSave); } else //render normally { game.render(g); //render the game } g = getGraphics(); g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null); g.dispose(); //throw it away to avoid lag from too many graphics objects }
5daf2b2e-3fdf-4563-8dd0-e492979a0df4
7
public void validate(FacesContext context, UIComponent component, Object toValidate) { boolean isValid = true; String value = null; if ((context == null) || (component == null)) { throw new NullPointerException(); } if (!(component instanceof UIInput)) { return; } if (null == toValidate) { return; } value = toValidate.toString(); int atIndex = value.indexOf('@'); if (atIndex < 0) { isValid = false; } else if (value.lastIndexOf('.') < atIndex) { isValid = false; } if (!isValid) { MessageFactory msg = new MessageFactory(); FacesMessage errMsg = new FacesMessage( msg.getMessage("errorEmailFormat")); throw new ValidatorException(errMsg); } }
a69725e9-06f9-4c63-bd3a-7613f3aceb87
9
public boolean hasNext() { // simple: check the current list for a successor if (listHasNext()) { return true; } // already reached the tree map iterator ? if (_mapIterator != null) { while (_mapIterator.hasNext()) { _currentList = (PropertyList)_mapIterator.next(); if (listHasNext()) { return true; } } // ... or still the direct index array ? } else { if (_parent._asciiArray != null) { while (++_currentIndex < DIRECT_INDEX_COUNT) { if ((_currentList = _parent._asciiArray[_currentIndex]) != null) { if (listHasNext()) { return true; } } } } if (_parent._nonASCIIMap != null) { _mapIterator = _parent._nonASCIIMap.values().iterator(); _currentList = null; return hasNext(); } } // no (more) sequences return false; }
db9a3515-0cb2-4c9e-bb7e-04b7367ac9c4
4
public void drawGameOption(Graphics g){ g.setFont(defaultFontSmall);//设置字体 for(int i = 0; i<gameOption.length; i++){ g.setColor(Colors.colorList[i]); g.fillRect(820 , 100 + i * 80, 75, 30); g.setColor(Color.white); g.drawString(gameOption[i], 825 , 120 + i * 80); if( i == this.gameOptionCursor){ g.setColor(Color.white); g.drawRect(820 , 100 + i * 80, 75, 30); g.drawRect(819 , 99 + i * 80, 77, 32); } } g.drawString("第" + Game.stage + "关", 822, 31); g.drawString("得分:" + (Game.enemy_killed * 100 + Game.propScore) , 822, 51); //返回按钮 if( returnBtnFlag == true ){ g.drawImage(returnBtn2, 850, 300, 40, 40, this); } else{ g.drawImage(returnBtn1, 850, 300, 40, 40, this); } //存档按钮 if( saveBtnFlag == true ){ g.drawImage(recordBtn2, 850, 350, 40, 40, this); }else{ g.drawImage(recordBtn1, 850, 350, 40, 40, this); } }
992487ef-b520-4831-8353-771c56f8dcc4
5
private Image createNoiseImage(final double WIDTH, final double HEIGHT, final Color DARK_COLOR, final Color BRIGHT_COLOR, final double ALPHA_VARIATION_IN_PERCENT) { int width = WIDTH <= 0 ? (int) PREFERRED_WIDTH : (int) WIDTH; int height = HEIGHT <= 0 ? (int) PREFERRED_HEIGHT : (int) HEIGHT; double alphaVariationInPercent = getSkinnable().clamp(0, 100, ALPHA_VARIATION_IN_PERCENT); final WritableImage IMAGE = new WritableImage(width, height); final PixelWriter PIXEL_WRITER = IMAGE.getPixelWriter(); final Random BW_RND = new Random(); final Random ALPHA_RND = new Random(); final double ALPHA_START = alphaVariationInPercent / 100 / 2; final double ALPHA_VARIATION = alphaVariationInPercent / 100; Color noiseColor; double noiseAlpha; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { noiseColor = BW_RND.nextBoolean() == true ? BRIGHT_COLOR : DARK_COLOR; noiseAlpha = getSkinnable().clamp(0, 1, ALPHA_START + ALPHA_RND.nextDouble() * ALPHA_VARIATION); PIXEL_WRITER.setColor(x, y, Color.color(noiseColor.getRed(), noiseColor.getGreen(), noiseColor.getBlue(), noiseAlpha)); } } return IMAGE; }
608f936d-c422-47c8-92d0-d4484448217d
2
public void Compile() { glLinkProgram(program); if (glGetProgrami(program, GL_LINK_STATUS) == 0) { System.err.println(glGetProgramInfoLog(program, 1024)); System.exit(-1); } glValidateProgram(program); if (glGetProgrami(program, GL_VALIDATE_STATUS) == 0) { System.err.println(glGetProgramInfoLog(program, 1024)); System.exit(-1); } }
2a64f9f9-2ceb-47c2-b356-ce0adfd4ad21
7
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String quizName = request.getParameter("Field1"); String quizCategory = request.getParameter("Field2"); String quizAuto = request.getParameter("Field3"); String quizOrder = request.getParameter("Field4"); boolean isRandom; String quizPaging = request.getParameter("Field5"); boolean isOnePage; String quizCorrection = request.getParameter("Field6"); boolean opFeedback; String quizPractice = request.getParameter("Field7"); boolean opPractice; String quizTag = request.getParameter("Field8"); String quizDescription = request.getParameter("Field9"); HttpSession session = request.getSession(); User homeUser = (User) session.getAttribute("user"); int userID = homeUser.userID; String quizURL = "none URL"; session.setAttribute("quizTag", quizTag); if(quizName.equals("") || quizCategory.equals("") || quizDescription.equals("")){ RequestDispatcher dispatch = request.getRequestDispatcher("createQuiz/new_quiz_settings.jsp"); dispatch.forward(request, response); }else{ if(quizOrder.equals("Yes")){ isRandom = true; }else{ isRandom = false; } if(quizCorrection.equals("Yes")){ opFeedback = true; }else{ opFeedback = false; } if(quizPractice.equals("Yes")){ opPractice = true; }else{ opPractice = false; } if(quizPaging.equals("Yes")){ isOnePage = true; }else{ isOnePage = false; } Quiz newQuiz = new Quiz(quizName,quizURL,quizDescription,quizCategory,userID,isRandom,isOnePage,opFeedback,opPractice); newQuiz.addQuizToDB(); QuizCreatedRecord record = new QuizCreatedRecord(newQuiz, homeUser); record.addRecordToDB(); session.setAttribute("newQuiz", newQuiz); session.setAttribute("questionPosition", 1); RequestDispatcher dispatch = request.getRequestDispatcher("createQuiz/chooseQuestionType.jsp"); dispatch.forward(request, response); } }
a6a0f18a-6e7b-42ea-9da3-f5b9ae026862
5
public static ArrayList<String> createListBody(String sender, String user_name, ResourceBundle domBundle) { ArrayList<String> body = new ArrayList<String>(); String select_query = createSelectQuery(sender, user_name); DatabaseDao dbdao = new DatabaseDaoImpl(domBundle); ResultSet rs; ArrayList<HashMap<String, String>> alist = new ArrayList<HashMap<String,String>>(); try { rs = dbdao.read(select_query, null); while(rs.next()) { HashMap<String, String> hmap = new HashMap<String, String>(); hmap.put("content", rs.getString(1)); hmap.put("dummy", rs.getString(2)); alist.add(hmap); } } catch (ClassNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (SQLException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (Exception e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } body.add("your service list."); for(int i=0;i<alist.size();i++) { body.add("content:"+alist.get(i).get("content")+"/dummy:"+alist.get(i).get("dummy")); } return body; }
654b1e7f-8cea-47e7-a216-6aa165b32898
8
static void P() { int S1 = 0; int S2 = 0; int S3 = 0; int SMax = 9; int OMax = 0; int OTemp = 0; int OCounter = 0; // code start OTemp = S1+S2+S3; // code end OMax = OTemp; OCounter = 1; S3 = S3 + 1; while (S1 <= SMax) { S2=0; while (S2 <= SMax) { S3=0; while (S3 <= SMax) { OTemp = S1+S2+S3; if (OTemp > OMax) { OMax = OTemp; OCounter = OCounter + 1; } if (S3 < SMax) S3 = S3 + 1; else break; } if (S2 < SMax) S2 = S2 + 1; else break; } if (S1 < SMax) S1 = S1 + 1; else break; } if (OCounter == 28) { System.out.println(OCounter); } }
75b18b5d-84a4-48df-8812-8edb9d47d159
2
private void nameChanged() { joinButton.setEnabled(false); joinChatPressed = false; String text = nameField.getText().trim(); name = text; if (text.compareTo("") == 0) { nameStatus.setText(""); return; } String message = null; if ((message = checkName(text)) == null) { name = text; nameStatus.setText(""); checkNameAvailability(name); } else nameStatus.setText(message); }
9f1b380f-2cac-455a-a5ba-988142d6f958
9
@Test public void computerSuggestion() { Player p = new ComputerPlayer(); p.seenAlmostEverything(1, game.getDeck()); ArrayList<String> ans = p.makeSuggestion(game.getDeck()); // Only one suggestion available Assert.assertTrue(ans.contains("The Hacker") && ans.contains("SQL Injection") && ans.contains("Hall") ); game = new ClueGame(); game.loadConfigFiles(); game.initGame(); // multiple suggestion available int choiceA = 0; int choiceB = 0; p.seenAlmostEverything(2, game.getDeck()); for (int i = 0; i < 50; i++) { ans = p.makeSuggestion(game.getDeck()); if(ans.contains("The Hacker") && ans.contains("SQL Injection") && ans.contains("Hall")) choiceA++; else if (ans.contains("Mr. Cuddles") && ans.contains("SQL Injection") && ans.contains("Hall")) choiceB++; } Assert.assertTrue(choiceA > 0); Assert.assertTrue(choiceB > 0); }
1982989e-f8a3-4d03-95de-23cc9d8748ff
7
protected static ArrayList<String> getNeighbors(String course){ String[] courseParts = course.split(" "); String detailedLevel = courseParts[courseParts.length - 1]; String courseName = ""; for (int i = 0; i < courseParts.length-1; i++){ courseName += courseParts[i]; if (i != courseParts.length-2){ courseName += " "; } } ArrayList<String> neighbors = new ArrayList<String>(); for (String artName : artNames){ if (artName.contains(courseName)){ int Level = Integer.parseInt(detailedLevel.replaceAll("[a-zA-Z]", "")); if (artName.contains(new Integer(Level).toString()) || artName.contains(new Integer(Level - 1).toString()) || artName.contains(new Integer(Level + 1).toString())){ neighbors.add(artName); } } } return neighbors; }
ee952584-eb0a-48cb-8055-51a2b35be7dc
1
public List<Product> getProductsForPage() { int firstProduct = (currentPage - 1) * NUM_PROD_PER_PAGE; int lastProduct = firstProduct + NUM_PROD_PER_PAGE; try { return products.subList(firstProduct, lastProduct); } catch (IndexOutOfBoundsException e) { return products.subList(firstProduct, products.size()); } }
89ecf3d2-112e-481f-8845-c2aee62ea7af
1
public int hashCode() { return (name != null ? name.hashCode() : 0); }
2ce8730d-3db9-4dd7-a8d5-150f07dd804e
8
public void coloringLadderByRandom(int startNum){ for(int i = 0; i < startNum; i++){ boolean leftColored = false, rightColored= false; Random random = new Random(); int randomX = random.nextInt(startNum-2);//전체 개수-1(0에서 시작하니까) -1(마지막줄 그으면 안되니까) int randomY = random.nextInt(startNum); boolean checkSelf = lines.get(randomX).getBoxLine().get(randomY).isColored(); if(checkSelf){//자기 자리에 이미 선 있는지 확인 i--; continue; } /** * lines.get(randomX-1).getBoxLine().get(randomY) 부분이 계속 중복되고 있다. * 중복을 제거해 본다. - javajigi */ if(randomX !=0){//엑스 축이 0이 아니면 그 왼쪽 박스에 선이 있는지 확인 leftColored= lines.get(randomX-1).checkBoxColored(randomY); } if(randomX <= startNum-2){//엑스 축이 제일 오른쪽에서 -1칸이면 그 오른쪽 박스가 선이 있는지 확인. rightColored = lines.get(randomX+1).checkBoxColored(randomY); } while(leftColored || rightColored){//둘 중 하나라도 선이 있으면 다시 선을 그을 박스를 확인한다. 여기 바꿀 방법을 코드 리뷰 받아야 할 randomX = random.nextInt(startNum-2); randomY = random.nextInt(startNum); if(randomX !=0){ leftColored= lines.get(randomX-1).checkBoxColored(randomY); } if(randomX <= startNum-2){ rightColored = lines.get(randomX+1).checkBoxColored(randomY); } } lines.get(randomX).setBoxColor(randomY); } }
ad94036d-72a5-41e2-b1a8-7447c427a21a
1
public void setPlayerFruit(Player p, int fruitId){ Fruit f = getFruitById(fruitId); if(!fruits.containsKey(p.getName())) { fruits.put(p.getName(), fruitId); applyPassiveFruitEffects(p,f); } else{ fruits.remove(p.getName()); fruits.put(p.getName(), fruitId); applyPassiveFruitEffects(p,f); } }
f2962c9d-c5f5-42c4-8902-e0e140e824e8
5
public void aproveTimesheetByTimesheetId(Time_Sheet t, ApprovalSheet approvalSheet) throws SQLServerException, SQLException { Connection con = null; con = getConnection(); con.setAutoCommit(false); con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); try { String sql = "INSERT INTO ApprovalSheet (firemanId, comment, approved, hours) VALUES (?, ?, ?, ?)"; PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setInt(1, approvalSheet.getFireman().getID()); ps.setString(2, approvalSheet.getComment()); ps.setBoolean(3, approvalSheet.isApproved()); ps.setInt(4, approvalSheet.getHours()); int affectedRows = ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); if (affectedRows == 0) { throw new SQLException("Problem with updating the ApprovalSheet"); } if(rs.next()){ approvalSheet.setId(rs.getInt(1)); String updateSql = "UPDATE Timesheet SET acceptedByTeamleader=? WHERE id = ?;"; PreparedStatement psUpdate = con.prepareStatement(updateSql); psUpdate.setInt(1, rs.getInt(1)); psUpdate.setInt(2, t.getId()); affectedRows = psUpdate.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Problem with updating the Timesheet "); } }else{ throw new SQLException("No key returned when adding ApprovalSheet"); } con.commit(); } catch (SQLException e) { con.rollback(); throw e; } finally { con.setAutoCommit(true); if(con != null) { con.close(); } } }
59a4c4db-c549-4906-9c99-1ebc4da6a55f
2
public static void loadPlayersHomes( BSPlayer player ) throws SQLException { ResultSet res = SQLManager.sqlQuery( "SELECT * FROM BungeeHomes WHERE player = '" + player.getName() + "'" ); while ( res.next() ) { String server = res.getString( "server" ); Location l = new Location( server, res.getString( "world" ), res.getDouble( "x" ), res.getDouble( "y" ), res.getDouble( "z" ), res.getFloat( "yaw" ), res.getFloat( "pitch" ) ); Home h = new Home( player.getName(), res.getString( "home_name" ), l ); if ( player.getHomes().get( server ) == null ) { ArrayList<Home> list = new ArrayList<>(); list.add( h ); player.getHomes().put( server, list ); } else { player.getHomes().get( server ).add( h ); } } res.close(); }
dcd6cde9-ac5c-4043-864b-41d854b34d36
8
public static APDU createAPDU(ServicesSupported services, ByteQueue queue) throws BACnetException { // Get the first byte. The 4 high-order bits will tell us the type of PDU this is. byte type = queue.peek(0); type = (byte) ((type & 0xff) >> 4); if (type == ConfirmedRequest.TYPE_ID) return new ConfirmedRequest(services, queue); if (type == UnconfirmedRequest.TYPE_ID) return new UnconfirmedRequest(services, queue); if (type == SimpleACK.TYPE_ID) return new SimpleACK(queue); if (type == ComplexACK.TYPE_ID) return new ComplexACK(queue); if (type == SegmentACK.TYPE_ID) return new SegmentACK(queue); if (type == Error.TYPE_ID) return new Error(queue); if (type == Reject.TYPE_ID) return new Reject(queue); if (type == Abort.TYPE_ID) return new Abort(queue); throw new IllegalPduTypeException(Byte.toString(type)); }
3c5ce2e4-d9a7-44a6-91ce-57fa13a23b07
5
private int [] combinar(int []left, int right[], int[] lista){ int nleft=left.length; int nright=right.length; int l=0,r=0,li=0; while(l<nleft && r<nright){ if(left[l]<=right[r]){ lista[li]=left[l]; l++; } else{ lista[li]=right[r]; r++; } li++; } while(l<nleft){ lista[li]=left[l]; l++; li++; } while(r<nright){ lista[li]=right[r]; r++; li++; } return lista; }
d7db0d41-2cbb-456f-8d61-0c55aac2f13b
7
private void writeRow(Object[] values) { Row row = sheet.getRow(rowIndex); if (row == null) { row = sheet.createRow(rowIndex); } rowIndex++; Cell cell = null; for (int cellIndex = 0; cellIndex < values.length ; cellIndex++) { cell = row.getCell(cellIndex); if (cell == null) { cell = row.createCell(cellIndex); } Object value = values[cellIndex]; if (value == null) continue; if (value instanceof Date) { cell.setCellValue((Date) value); } else if (value instanceof Number) { cell.setCellValue(((Number) value).doubleValue()); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } else { cell.setCellValue(value.toString()); } } }
281bc1ff-5a9a-4b96-ae30-99dfe692eaa5
9
* @param client the connecting client * @param newCharacter is this a new character */ public void init_conn(final Player player, final Client client, final boolean newCharacter) { if (player == null) { debug("ERROR!!!: Player Object is NULL!"); return; } if (use_cnames) { // generate generic name for unknown players based on their class // and the number of players with the same class presently on // logged on of a given class System.out.println("Generating generic name for player..."); // TODO deal with number of players online of stuff // TODO resolve where I get the numbers from // int temp = numPlayersOnlinePerClass.get( player.getPClass() ); int temp = objectDB.getNumPlayers(player.getPClass()); // TODO handle NPC control scenario that causes this to not produce // the desired result player.setCName(player.getPClass().toString() + temp); objectDB.addName(player, player.getCName()); cNames.put(player.getCName(), player); numPlayersOnlinePerClass.put(player.getPClass(), ++temp); System.out.println("Generated Name: " + player.getName()); System.out.println("Done"); debug("Number of players that share this player's class: " + objectDB.getNumPlayers(player.getPClass())); } // NOTE: I should probably add a mapping here somewhere that ties the // player to their account, if they have one if (newCharacter) { // if new, do some setup // send a welcome mail to them final int id = player.getMailBox().numMessages() + 1; final String msg = "Welcome to " + getName(); final String dateString = getDate().toString(); final Mail mail = new Mail(id, "System", player.getName(),"Welcome", msg, dateString, Mail.UNREAD); sendMail(mail, player); // TODO need an item creation factory and some method in GameModule // that handles starting equipment, perhaps this should be part of // character generation? } // get the time final Time time = getTime(); final Date date = getDate(); // account login state final Account account = acctMgr.getAccount(player); if (account != null) { debug("ACCOUNT EXISTS!"); account.setClient(client); account.setPlayer(player); account.setOnline(true); } /* */ sclients.put(client, player); player.setClient(client); // need this set so I can ask for it in various other places logConnect(player, time); // open a new session Session session = new Session(client, player); session.connect = new Tuple<Date, Time>(date, time); session.connected = true; sessionMap.put(player, session); debug("New session started!"); // tell the player that their connection was successful debug("\nConnected!\n"); send(colors("Connected!", "yellow"), client); //send(colors("Connected to " + serverName + " as " + player.getName(), "yellow"), client); /* load the player's mailbox */ loadMail(player); // indicate to the player how much mail/unread mail they have client.writeln("Checking for unread messages..."); int messages = player.getMailBox().numUnreadMessages(); if (messages == 0) client.writeln("You have no unread messages."); else client.writeln("You have " + String.valueOf(messages) + " unread messages."); // list the items in the player's inventory (located "in" the player) for (final Item item : player.getInventory()) { debug("Item -> " + item.getName() + " (#" + item.getDBRef() + ") @" + item.getLocation()); } debug(""); // TODO clean up the below, where we add players to channels, also we // should readd them to any channels they joined before /* ChatChannel Setup */ try { chan.add(player, OOC_CHANNEL); } catch(final NoSuchChannelException nsce) { debug("INIT_CONN: No such chat channel."); } // TODO decide how to handle channels where I want people auto-added // add player to the STAFF ChatChannel (testing), if they are staff{ try { chan.add(player, STAFF_CHANNEL); } catch(final NoSuchChannelException nsce) { debug("INIT_CONN: No such chat channel."); }
78910395-74fb-48ac-b242-ed224f34090a
0
public Coordinate getPosition() { return position; }
2346eca6-a758-4c26-921e-62fcdc32e900
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(administrateur_modification.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(administrateur_modification.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(administrateur_modification.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(administrateur_modification.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new administrateur_modification().setVisible(true); } }); }
4080d511-f59f-4489-ae7c-ed872455db71
5
private final void method3426(byte i) { anInt7219++; try { Field[] fields = this.getClass().getDeclaredFields(); if (i != 36) aClass199_7221 = null; Field[] fields_5_ = fields; for (int i_6_ = 0; (i_6_ ^ 0xffffffff) > (fields_5_.length ^ 0xffffffff); i_6_++) { Field field = fields_5_[i_6_]; if ((aClass7273 != null ? aClass7273 : (aClass7273 = method3431("Class239"))) .isAssignableFrom(field.getType())) { Class239 class239 = (Class239) field.get(this); class239.method1716(false); } } } catch (IllegalAccessException illegalaccessexception) { /* empty */ } }
98af9868-d1bf-4178-965e-ba76488418a2
5
public NewDialog(Artistry artistry) { this.artistry = artistry; contentPane = new JPanel(); setLayout(null); setSize(320, 240); setTitle("New"); contentPane.setLayout(null); JLabel widthLabel = new JLabel("Width: "); widthLabel.setBounds(16, 16, 128, 24); contentPane.add(widthLabel); final JSpinner widthSpinner = new JSpinner(); widthSpinner.setBounds(144, 16, 128, 24); contentPane.add(widthSpinner); JLabel heightLabel = new JLabel("Height: "); heightLabel.setBounds(16, 48, 128, 24); contentPane.add(heightLabel); final JSpinner heightSpinner = new JSpinner(); heightSpinner.setBounds(144, 48, 128, 24); contentPane.add(heightSpinner); JLabel colourSpaceLabel = new JLabel("Colour space: "); colourSpaceLabel.setBounds(16, 80, 128, 24); contentPane.add(colourSpaceLabel); final JComboBox<String> colourSpaceBox = new JComboBox<>(new String[] {"RGB", "Greyscale"}); colourSpaceBox.setBounds(144, 80, 128, 24); contentPane.add(colourSpaceBox); JLabel backgroundColourLabel = new JLabel("Background colour: "); backgroundColourLabel.setBounds(16, 112, 128, 24); contentPane.add(backgroundColourLabel); final JComboBox<String> backgroundColourBox = new JComboBox<>(new String[] {"Foreground colour", "Background colour", "White", "Black", "Transparency"}); backgroundColourBox.setBounds(144, 112, 128, 24); contentPane.add(backgroundColourBox); JButton submitButton = new JButton("OK"); submitButton.setBounds(16, 144, 256, 24); submitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { BufferedImage newImage = new BufferedImage((int) widthSpinner.getValue(), (int) heightSpinner.getValue(), colourSpaceBox.getSelectedItem().equals("RGB") ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_BYTE_GRAY); Graphics graphics = newImage.getGraphics(); if (backgroundColourBox.getSelectedItem().equals("Foreground colour") || backgroundColourBox.getSelectedItem().equals("Black")) { graphics.setColor(Color.BLACK); graphics.fillRect(0, 0, newImage.getWidth(), newImage.getHeight()); } if (backgroundColourBox.getSelectedItem().equals("Background colour") || backgroundColourBox.getSelectedItem().equals("White")) { graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, newImage.getWidth(), newImage.getHeight()); } NewDialog.this.artistry.setImage(newImage); NewDialog.this.dispose(); } }); contentPane.add(submitButton); setContentPane(contentPane); setResizable(false); setVisible(true); }
c325afe2-3117-4df2-9f1c-19c501f23122
3
public String extractBitSetasHex() { int a; StringBuilder out=new StringBuilder(); int idata[]=returnInts(); for (a=0;a<idata.length;a++) { // Ensure the number consists of two characters if (idata[a]<16) out.append("0"); out.append(Integer.toHexString(idata[a])); if (a<idata.length-1) out.append(","); } return out.toString(); }
0fa5dba5-7b7e-418f-94af-f2cace54dbd6
8
void menuComposeAlpha(int alpha_op) { if (image == null) return; animate = false; // stop any animation in progress Cursor waitCursor = display.getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); imageCanvas.setCursor(waitCursor); try { if (alpha_op == ALPHA_CONSTANT) { imageData.alpha = alpha; } else { imageData.alpha = -1; switch (alpha_op) { case ALPHA_X: for (int y = 0; y < imageData.height; y++) { for (int x = 0; x < imageData.width; x++) { imageData.setAlpha(x, y, (x + alpha) % 256); } } break; case ALPHA_Y: for (int y = 0; y < imageData.height; y++) { for (int x = 0; x < imageData.width; x++) { imageData.setAlpha(x, y, (y + alpha) % 256); } } break; default: break; } } displayImage(imageData); } finally { shell.setCursor(null); imageCanvas.setCursor(crossCursor); } }
f9533ae8-412e-43a1-b79c-c046770ab261
5
public ArrayList<Intersection> getNeighbors(Intersection intersection) { ArrayList<Intersection> neighbors = new ArrayList(); ArrayList<Road> roads = level.roads; int x = intersection.x; int y = intersection.y; for (int i = 0; i < roads.size(); i++) { if (roads.get(i).node1.x == x && roads.get(i).node1.y == y) { neighbors.add(roads.get(i).node2); } else if (roads.get(i).node2.x == x && roads.get(i).node2.y == y) { neighbors.add(roads.get(i).node1); } } return neighbors; }
054d9ded-db12-4f63-b066-487ee6b9774b
2
public void setAddress(InetAddress address) { if (address == null) { this.address = null; } else if (!(address instanceof Inet4Address)) { throw new IllegalArgumentException("only IPv4 addresses accepted"); } else { this.address = address; } }
dfb7a9a4-92c9-413e-bd75-d562603fce2e
0
public void setType(String value) { this.type = value; }
439803bf-9851-48ff-b557-7cc792c6e339
7
private static Alignment traceback(Sequence s1, Sequence s2, Matrix m, byte[][] pointers, Cell cell) { char[] array1 = s1.toArray(); char[] array2 = s2.toArray(); float[][] scores = m.getScores(); Alignment alignment = new Alignment(); alignment.setScore(cell.getScore()); // maximum length after the aligned sequences int maxlen = s1.length() + s2.length(); char[] reversed1 = new char[maxlen]; // reversed sequence #1 char[] reversed2 = new char[maxlen]; // reversed sequence #2 char[] reversed3 = new char[maxlen]; // reversed markup int len1 = 0; // length of sequence #1 after alignment int len2 = 0; // length of sequence #2 after alignment int len3 = 0; // length of the markup line int identity = 0; // count of identitcal pairs int similarity = 0; // count of similar pairs int gaps = 0; // count of gaps char c1, c2; int i = cell.getRow(); // traceback start row int j = cell.getCol(); // traceback start col // Traceback flag, where true => continue and false => stop boolean stillGoing = true; while (stillGoing) { switch (pointers[i][j]) { case Directions.UP: reversed1[len1++] = array1[--i]; reversed2[len2++] = Alignment.GAP; reversed3[len3++] = Markups.GAP; gaps++; break; case Directions.DIAGONAL: c1 = array1[--i]; c2 = array2[--j]; reversed1[len1++] = c1; reversed2[len2++] = c2; if (c1 == c2) { reversed3[len3++] = Markups.IDENTITY; identity++; similarity++; } else if (scores[c1][c2] > 0) { reversed3[len3++] = Markups.SIMILARITY; similarity++; } else { reversed3[len3++] = Markups.MISMATCH; } break; case Directions.LEFT: reversed1[len1++] = Alignment.GAP; reversed2[len2++] = array2[--j]; reversed3[len3++] = Markups.GAP; gaps++; break; case Directions.STOP: stillGoing = false; } } alignment.setSequence1(reverse(reversed1, len1)); alignment.setStart1(i); alignment.setSequence2(reverse(reversed2, len2)); alignment.setStart2(j); alignment.setMarkupLine(reverse(reversed3, len3)); alignment.setIdentity(identity); alignment.setGaps(gaps); alignment.setSimilarity(similarity); return alignment; }
72f4962c-2e0e-4fa1-aa45-eddfdc4d9865
7
private void postProcessPlotInfo(FastVector plotSize) { int maxpSize = 20; double maxErr = Double.NEGATIVE_INFINITY; double minErr = Double.POSITIVE_INFINITY; double err; for (int i = 0; i < plotSize.size(); i++) { Double errd = (Double)plotSize.elementAt(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (err < minErr) { minErr = err; } if (err > maxErr) { maxErr = err; } } } for (int i = 0; i < plotSize.size(); i++) { Double errd = (Double)plotSize.elementAt(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (maxErr - minErr > 0) { double temp = (((err - minErr) / (maxErr - minErr)) * maxpSize); plotSize.setElementAt(new Integer((int)temp), i); } else { plotSize.setElementAt(new Integer(1), i); } } else { plotSize.setElementAt(new Integer(1), i); } } }
41b473a1-6c97-40f6-9dd5-c0a9669811ad
4
public int listxattrsize(ByteBuffer path, FuseSizeSetter sizeSetter) { if (xattrSupport == null) { return handleErrno(Errno.ENOTSUPP); } String pathStr = cs.decode(path).toString(); if (log != null && log.isDebugEnabled()) { log.debug("listxattrsize: path=" + pathStr); } int errno; XattrSizeLister lister = new XattrSizeLister(); try { errno = xattrSupport.listxattr(pathStr, lister); } catch(Exception e) { return handleException(e); } sizeSetter.setSize(lister.size); return handleErrno(errno, sizeSetter); }
38f94286-8729-4cac-9429-9cb48d2666c7
1
public void dispose() { Iterator<Color> e = fColorTable.values().iterator(); while (e.hasNext()) ((Color) e.next()).dispose(); }
da633937-d82b-4776-87ef-bc3eb1cce9a1
7
private static void Move(IHI_PathfinderValues values) { values.tiles[values.X[values.binaryHeap[1]]][values.Y[values.binaryHeap[1]]] = 2; values.binaryHeap[1] = values.binaryHeap[values.count]; values.count--; short location = 1; while (true) { short high = location; if (2*high + 1 <= values.count) { if (values.F[values.binaryHeap[high]] >= values.F[values.binaryHeap[2*high]]) location = (short) (2*high); if (values.F[values.binaryHeap[location]] >= values.F[values.binaryHeap[2*high + 1]]) location = (short) (2*high + 1); } else if (2*high <= values.count) { if (values.F[values.binaryHeap[high]] >= values.F[values.binaryHeap[2*high]]) location = (short) (2*high); } if (high == location) break; short temp = values.binaryHeap[high]; values.binaryHeap[high] = values.binaryHeap[location]; values.binaryHeap[location] = temp; } }
a96b20f1-5c45-4e59-bbd2-579eac2c68ad
4
public Token expr() throws ParentesiParsingException, OperazioneNonValidaException, ExtraTokenException, OperatoreMissingException, OperandoMissingException { Token x = andExpr(); if(!(point>text.size()-1)) { while(peek().ritornaTipoToken().equals(Tok.OR)) { consume(); Token y = andExpr(); boolean b1 = (boolean)x.ritornaValore(); boolean b2 = (boolean)y.ritornaValore(); x = new Booleano(b1 || b2); if(point>text.size()-1) break; } } return x; }
04a60017-4f1e-427e-a762-ad08f7bc3670
6
public void insertTileArray(int pg, int index, int oam[], int wid, int hgt, CHRTile[] tiles) { if ((index % 32 + wid) > 32) { // adjust wid so we dont wrap around wid -= ((index % 32 + wid) - 32); } if ((index + (32 * hgt) > (30 * 32))) { // adjust hgt so we dont mess up hgt -= ((index + (32 * hgt)) / 32) - 30; } // the index is in tiles (32 wide) // TO DO: fix this so I can stamp across pages. int tileCounter = 0; for (int y = 0; y < hgt; y++) { for (int x = 0; x < wid; x++) { int ntOffset = index + x + y * 32; modelRef.setNameTableTileAndOAM(pg, ntOffset, (byte) _activeStamp.getInsertionPointAt(tileCounter), (byte) oam[tileCounter]); tileCounter++; } } int mw = wid/2; int mh = hgt/2; int mtIndex = (index/64 * 16) + ((index%64)/2); repairMetaTileArray(determineNumPages(), metaTile.length); //System.out.println("Inserting meta starting at page:" + pg + " and index:" + mtIndex ); // We also need to insert the metatile info into the metatile set and array. int metaCounter = _activeStamp.getMetaInsertionPoint(); for(int y=0;y<mh;y++){ for(int x=0;x<mw;x++){ int mtOffset = mtIndex + x + y*16; metaTile[pg][mtOffset] = metaCounter; metaCounter++; } } updateNameTable(pg); // add to the name table }
f53c91db-149d-4ca1-b008-43794225a5f1
6
public static int getPrice(int basePrice, int goldenNumber) { Random random = new Random(); int randomNumber = random.nextInt(85) + 1; int priceModifyer = (basePrice * randomNumber) / 100; int price = basePrice - priceModifyer; int goldenPrice; int goldenChance = random.nextInt(100) + 1; if (goldenChance > 0 && goldenChance < goldenNumber) { int chance = random.nextInt(2) + 1; if (chance < 2 && chance > 0) { goldenPrice = price / 10; return goldenPrice; } else if (chance < 3 && chance > 1) { goldenPrice = price * 10; return goldenPrice; } } return price; }
795f9e2e-313b-45b1-a8df-529762a4c580
2
@Override public void onKeyPress(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { player.jump(); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { player.duck(); } }
bbfe5227-1f84-4eec-b057-b8d2b3221810
6
public boolean intersectsRect(Rectangle rect) { // To save CPU, we can test if the rectangle intersects the entire // bounds of this label if ( (labelBounds != null && (!labelBounds.getRectangle().intersects(rect)) ) || labelGlyphs == null ) { return false; } for (int i = 0; i < labelGlyphs.length; i++) { if (labelGlyphs[i].visible && rect.intersects(labelGlyphs[i].drawingBounds .getRectangle())) { return true; } } return false; }
594125ad-895a-43c3-aee6-6ca3c7975bf9
9
@Override public void moveTowards(MapLocation mapLocation) { Direction direction = rc.getLocation().directionTo(mapLocation); if (canMakeProgress(direction)) { moveToDirection(rc, direction); stuck = false; return ; } else { stuck = true; stuckLocation = rc.getLocation(); } if (stuck) { int counter = 0; if (!direction.equals(Direction.OMNI) && !direction.equals(Direction.NONE)) { while (!canMakeProgress(direction)) { if (rotateRight) { direction = direction.rotateRight(); } else { direction = direction.rotateLeft(); } if (counter++ > MAX_DIRECTIONS) { break; } } } MapLocation movingTo = rc.getLocation().add(direction); if (movingTo.equals(stuckLocation)) { rotateRight = !rotateRight; return; } if (canMakeProgress(direction)) { moveToDirection(rc, direction); } } }
1324df66-89f4-41b6-a54a-a87492b81ef5
9
@Override public void actOnInput(int key) { switch(key) { case '1': this.activate(new PlaceLandTileController(this.game, this.view, this.gameController)); break; case '2': this.activate(new AddDeveloperController(this.game, this.view, this.gameController)); break; case '3': this.activate(new MoveDeveloperController(this.game, this.view, this.gameController)); break; case '4': this.activate(new BuildPalaceController(this.game, this.view, this.gameController)); break; case '5': this.activate(new EnlargePalaceController(this.game, this.view, this.gameController)); break; case '6': this.activate(new PlaceIrrigationController(this.game, this.view, this.gameController)); break; case '7': this.activate(new DrawPalaceCardController(this.game, this.view, this.gameController)); break; case '8': this.activate(new ArrangeFestivalController(this.game, this.view, this.gameController)); break; case '9': this.activate(new EndTurnController(this.game, this.view, this.gameController)); } }
69ceff86-ecbc-4746-ae0a-320a7490d09f
5
public void loadLevel() { SpriteSheet sprites = new SpriteSheet("/res/images/desk2.png", 1, 1); Image desk = sprites.getSprite(0); sprites = new SpriteSheet("/res/images/floorTile.png", 1, 1); Image floor = sprites.getSprite(0); for (int x = 0; x < WIDTH; x += 2) for (int y = 0; y < HEIGHT; y += 2) addObject((BufferedImage)floor, x, y, true); for (int x = 10; x < WIDTH - 20; x += 20) for (int y = 20; y <= 60; y += 20) addObject((BufferedImage)desk, x, y, false); sprites = new SpriteSheet("/res/images/back-wall.png", 1, 1); Image wall = sprites.getSprite(0); for (int x = 0; x < WIDTH; x += 8) addObject((BufferedImage)wall, x, 0, false); sprites = new SpriteSheet("/res/images/chalkboard.png", 1, 1); Image board = sprites.getSprite(0); addObject((BufferedImage)board, 50, 1, false); }
06c8bc39-c442-4e3e-b4f4-219fb119eb30
5
private void updatePlayers(int packetSize, Stream stream) { localEntityCount = 0; entityUpdateCount = 0; updateLocalPlayerMovement(stream); updatePlayerMovement(stream); updatePlayerList(stream, packetSize); // method91 parsePlayerUpdateFlags(stream); for (int id = 0; id < localEntityCount; id++) { int localPlayerId = localPlayerIndices[id]; if (localPlayers[localPlayerId].lastUpdate != Client.loopCycle) { localPlayers[localPlayerId] = null; } } if (stream.offset != packetSize) { Signlink.reporterror("Error packet size mismatch in getplayer pos:" + stream.offset + " psize:" + packetSize); throw new RuntimeException("eek"); } for (int id = 0; id < localPlayerCount; id++) { if (localPlayers[playerIndices[id]] == null) { Signlink.reporterror(myUsername + " null entry in pl list - pos:" + id + " size:" + localPlayerCount); throw new RuntimeException("eek"); } } }
8225335f-314f-4351-987a-4932e87af5b3
0
public OutlinerDocumentListener[] getOutlinerDocumentListeners() { return (OutlinerDocumentListener[]) outlinerDocumentListeners.toArray(); }
d4d099b7-ddca-4aea-bc2b-69153b98b4b4
3
private void updateInputArea() { String html; if (currentState == MasterMindGraphic.FEEDBACK){ String b = this.input.length() > 0 ? this.input.substring(0, 1):" " ; String w = this.input.length() > 1 ? this.input.substring(1, 2):" "; html = "<div id = 'inputArea'> "+constants.Input()+": " + b + "b" + w + "w" + "</div>"; } else { html = "<div id = 'inputArea'> "+constants.Input()+": " + this.input + "</div>"; } this.inputInfoArea.clear(); this.inputInfoArea.add(new HTMLPanel(html)); }
4dcc6d54-e4bb-4ca1-ab09-f2628a0e9d0e
9
public GridItem objectAt(int x, int y){ GridItem e = null; if(x >= 0 && y >= 0 && x < size.width && y < size.height) e= grid[x][y]; if(e == null) for(Player p : players) for(Bomb b : p.getBombs()) if((int)(b.getX()/ICON_SIZE) == x && (int)(b.getY()/ICON_SIZE) == y) return b; return e; }
c467208f-e17b-4acb-b438-8c7795c47fa0
7
public void paintComponent(Graphics g) { BufferedImage spriteSheet = null,Hull; 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.ShipShopHullsMenu.selectionOvalX == 340) { Hull = spriteSheet.getSubimage(121, 0, 15, 35); g.drawImage(Hull,515, 250, 60, 140,this); if(Main.Player1.Ship.Ship_Hull.check_purchased_Hulls(0) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Hull?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Confirm Your Hull Purchase",265,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } } else if(Main.ShipShopHullsMenu.selectionOvalX == 540) { if(Main.Player1.Ship.Ship_Hull.check_purchased_Hulls(1) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Hull?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Confirm Your Hull Purchase",265,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } Hull = spriteSheet.getSubimage(142, 0, 15, 35); g.drawImage(Hull,500, 250, 60, 140,this); } else if(Main.ShipShopHullsMenu.selectionOvalX == 740) { if(Main.Player1.Ship.Ship_Hull.check_purchased_Hulls(2) == 1) { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Equip This Hull?",400,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Equip Part", 315, 494); } else { g.setFont(new Font("Serif",Font.PLAIN,48)); g.drawString("Confirm Your Hull Purchase",265,235); g.setFont(new Font("Serif",Font.PLAIN,25)); g.drawString("Buy and Equip Part", 265, 494); } Hull = spriteSheet.getSubimage(158, 0, 15, 35); g.drawImage(Hull,515, 250, 60, 140,this); } g.drawString("Cancel",750, 494); g.drawOval(selectionOvalX, selectionOvalY, selectionOvalHeight, selectionOvalWidth); }
8de419df-acdf-4d05-93c8-f99f7b6fba03
2
public void organizeCards() { Tree<Card> organizedCards = new Tree<>(); for (int c = 0; c < this.getNumOrbitComponents(); c++) { organizedCards.insert(((CardComponent)this.getSubComponent(c)).getCard(), true); } Iterator<Card> ci = organizedCards.iterator(); CardComponent cardComponent; int globalVertexOffset = this.vertexBufferGlobalOffset + this.vertexBufferSize; int globalTextureCoordsOffset = this.textureCoordsBufferGlobalOffset + this.textureCoordsBufferSize; int globalColorOffset = this.colorBufferGlobalOffset + this.colorBufferSize; for (int c = 0; c < this.getNumOrbitComponents(); c++) { cardComponent = ci.next().getComponent(); this.setSubComponent(c, cardComponent); cardComponent.vertexBufferGlobalOffset = globalVertexOffset; cardComponent.textureCoordsBufferGlobalOffset = globalTextureCoordsOffset; cardComponent.colorBufferGlobalOffset = globalColorOffset; globalVertexOffset += cardComponent.vertexBufferSize; globalTextureCoordsOffset += cardComponent.textureCoordsBufferSize; globalColorOffset += cardComponent.colorBufferSize; this.getSlot(c).unSocket(); cardComponent.getTracker().setTrackPath(new OrbitTrackerPath(this.getOrbit(c / this.getOrbitComponentCount()))); cardComponent.getTracker().setTempPath(new LineTrackerPath()); cardComponent.trackTarget(this.getSlot(c)); } this.animateComponents(); }
181253c9-c3b8-46e7-9501-1f203a8b6f82
0
public Iterator keys() { return this.keySet().iterator(); }
2cf30b6b-4d03-4da7-85b0-c5cdb558dcea
8
@SuppressWarnings("deprecation") private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { if(ut.tc.speedFlag!=0) { int resultFlag=JOptionPane.showConfirmDialog(null,"Ѿ׹"+ut.tc.speedFlag+"ΣҪ "+(80+ut.tc.speedFlag*160)+"ңܹǷ" , "̳Ϣ",JOptionPane.YES_NO_OPTION ); if(resultFlag==JOptionPane.YES_OPTION){ if(ut.moneyNum.MoneyNumber>=(80+ut.tc.speedFlag*160)){ ut.addSpeed(); ut.moneyNum.MoneyNumber-=(80+ut.tc.speedFlag*160); jTextField1.setText(String.valueOf(ut.moneyNum.MoneyNumber)); ut.tc.speedFlag++; //JOptionPane.showMessageDialog(null,"׳ɹ","̳Ϣ",JOptionPane.YES_NO_CANCEL_OPTION); int result=JOptionPane.showConfirmDialog(null,"׳ɹǷף" , "̳Ϣ",JOptionPane.YES_NO_OPTION ); if(result==JOptionPane.NO_OPTION){ this.dispose(); ut.tc.threadRobot.resume(); ut.tc.threadRepaint.resume(); } //tc.threadRobot.resume(); } else{ int result2=JOptionPane.showConfirmDialog(null, "ǸĽҲ㣬δɹǷ˳̳ǣ", "̳Ϣ", JOptionPane.YES_NO_OPTION);// TODO add your handling code here: if(result2==JOptionPane.YES_OPTION){ this.dispose(); ut.tc.threadRobot.resume(); ut.tc.threadRepaint.resume(); } } } } else { if(ut.moneyNum.MoneyNumber>=(80+ut.tc.speedFlag*160)){ ut.addSpeed(); ut.moneyNum.MoneyNumber-=(80+ut.tc.speedFlag*160); jTextField1.setText(String.valueOf(ut.moneyNum.MoneyNumber)); ut.tc.speedFlag++; //JOptionPane.showMessageDialog(null,"׳ɹ","̳Ϣ",JOptionPane.YES_NO_CANCEL_OPTION); int result=JOptionPane.showConfirmDialog(null,"׳ɹǷף" , "̳Ϣ",JOptionPane.YES_NO_OPTION ); if(result==JOptionPane.NO_OPTION){ this.dispose(); ut.tc.threadRobot.resume(); ut.tc.threadRepaint.resume(); } //tc.threadRobot.resume(); } else{ int result2=JOptionPane.showConfirmDialog(null, "ǸĽҲ㣬δɹǷ˳̳ǣ", "̳Ϣ", JOptionPane.YES_NO_OPTION);// TODO add your handling code here: if(result2==JOptionPane.YES_OPTION){ this.dispose(); ut.tc.threadRobot.resume(); ut.tc.threadRepaint.resume(); } } } // TODO add your handling code here:// TODO add your handling code here: }
6d82c875-4930-4ede-9275-8379d643bbbb
5
private GameObjectDefinition getChildDefinition() { int child = -1; if (varBitId != -1) { VarBit varBit = VarBit.cache[varBitId]; int configId = varBit.configId; int lsb = varBit.leastSignificantBit; int msb = varBit.mostSignificantBit; int bit = Client.BITFIELD_MAX_VALUE[msb - lsb]; child = clientInstance.interfaceSettings[configId] >> lsb & bit; } else if (configId != -1) child = clientInstance.interfaceSettings[configId]; if (child < 0 || child >= childrenIds.length || childrenIds[child] == -1) return null; else return GameObjectDefinition.getDefinition(childrenIds[child]); }
3f3d08af-6a8a-4866-bd97-e93c9afcc470
4
public void validate() { if (currentZoom != documentViewModel.getViewZoom() || currentRotation != documentViewModel.getViewRotation()) { refreshDirtyBounds(); currentRotation = documentViewModel.getViewRotation(); currentZoom = documentViewModel.getViewZoom(); } if (resized) { refreshAnnotationRect(); if (getParent() != null) { ((JComponent) getParent()).revalidate(); getParent().repaint(); } resized = false; wasResized = true; } }
8e76ca3b-3b37-477d-b999-065a6151c652
2
public static void main(String args[]) { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); new Thread(new Runnable() { @Override public void run() { String event = "FOUR"; try { queue.put(event); // thread will block here System.out.printf("[%s] published event : %s %n", Thread.currentThread().getName(), event); } catch (InterruptedException e) { e.printStackTrace(); } } }, "PRODUCER").start(); new Thread(new Runnable() { @Override public void run() { try { String event = queue.take(); // thread will block here System.out.printf("[%s] consumed event : %s %n", Thread.currentThread().getName(), event); } catch (InterruptedException e) { e.printStackTrace(); } } }, "CONSUMER").start(); }
ca6ec73a-0a60-47d3-93ce-53064e94324f
4
@Override public boolean registerBuilder(Class<? extends IPacketBuilder> builder) { Object object = null; try { object = builder.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } BuildsPacket annotation = builder.getAnnotation(BuildsPacket.class); if (annotation != null) { builders.put(annotation.value(), (IPacketBuilder) object); return true; } return false; }
acb070a3-b5bf-4833-8be2-97b14efb6405
7
protected void doWrite(PrintWriter writer, String courseID, String nickname, String assignID) throws IOException { DietjeDatabase database = null; Connection connection = null; Map<String, Object> feedback = new LinkedHashMap<String, Object>(); try { database = new DietjeDatabase(); connection = database.connect(); PreparedStatement statement = connection.prepareStatement( "SELECT s.aid as tag, a.title, a.description, s.grade, s.attempts, s.feedback as motivation FROM submits s, assignment a WHERE s.aid = a.aid AND a.cid = ? AND s.sid = ? AND s.aid = ?"); statement.setString(1, courseID); statement.setString(2, nickname); statement.setString(3, assignID); ResultSet set = statement.executeQuery(); if (set.next()) { feedback.put("tag", set.getString("tag")); String description = set.getString("title"); if (description != null) { feedback.put("description", description); } Float grade = set.getFloat("grade"); if (grade != null && grade > 0.0) { feedback.put("grade", grade); } feedback.put("attempts", set.getInt("attempts")); String motivation = set.getString("motivation"); if (motivation != null) { motivation = motivation.replace("<", "&lt;").replace(">", "&gt;"); feedback.put("motivation", motivation); } } } catch (SQLException e) { throw new IOException(e); } finally { try { connection.close(); database.close(); } catch (SQLException e) { } } Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); resultMap.put("feedback", feedback); writer.print(JSONValue.toJSONString(resultMap)); }
ab5deb57-ca0b-4dd6-a41d-548828b7f142
2
private void jButton3ActionPerformed() { String nameOfStreamer = JOptionPane.showInputDialog(null, "Enter the streamer's name: "); if (nameOfStreamer == null || nameOfStreamer.isEmpty()) { return; } TwitchStream.removeStream(nameOfStreamer); TwitchStream.restartStreams(); }
fe713dbf-91e0-4652-83ea-49acfbf5d26d
9
public static OrbitalElements getOrbitalElements(int elementIndex, Calendar calendar) { Calendar reference = Calendar.getInstance(TimeZone.getTimeZone("GMT")); reference.set(2000, 0, 1, 0, 0, 0); reference.set(Calendar.MILLISECOND, 0); double d = (calendar.getTimeInMillis() - reference.getTimeInMillis()) / (86400f * 1000f) + 1; OrbitalElements o = null; switch (elementIndex) { case SUN: o = new OrbitalElements(0.0, 0.0, 282.9404 + 4.70935E-5 * d, 1.000000, 0.016709 - 1.151E-9 * d, 356.0470 + 0.9856002585 * d, 23.4393 - 3.563E-7 * d); break; case MOON: o = new OrbitalElements(125.1228 - 0.0529538083 * d, 5.1454, 318.0634 + 0.1643573223 * d, 60.2666, 0.054900, 115.3654 + 13.0649929509 * d, 23.4393 - 3.563E-7 * d); break; case MERCURY: o = new OrbitalElements(48.3313 + 3.24587E-5 * d, 7.0047 + 5.00E-8 * d, 29.1241 + 1.01444E-5 * d, 0.387098, 0.205635 + 5.59E-10 * d, 168.6562 + 4.0923344368 * d, 23.4393 - 3.563E-7 * d); break; case VENUS: o = new OrbitalElements(76.6799 + 2.46590E-5 * d, 3.3946 + 2.75E-8 * d, 54.8910 + 1.38374E-5 * d, 0.723330, 0.006773 - 1.302E-9 * d, 48.0052 + 1.6021302244 * d, 23.4393 - 3.563E-7 * d); break; case MARS: o = new OrbitalElements(49.5574 + 2.11081E-5 * d, 1.8497 - 1.78E-8 * d, 286.5016 + 2.92961E-5 * d, 1.523688, 0.093405 + 2.516E-9 * d, 18.6021 + 0.5240207766 * d, 23.4393 - 3.563E-7 * d); break; case JUPITER: o = new OrbitalElements(100.4542 + 2.76854E-5 * d, 1.3030 - 1.557E-7 * d, 273.8777 + 1.64505E-5 * d, 5.20256, 0.048498 + 4.469E-9 * d, 19.8950 + 0.0830853001 * d, 23.4393 - 3.563E-7 * d); break; case SATURN: o = new OrbitalElements(113.6634 + 2.38980E-5 * d, 2.4886 - 1.081E-7 * d, 339.3939 + 2.97661E-5 * d, 9.55475, 0.055546 - 9.499E-9 * d, 316.9670 + 0.0334442282 * d, 23.4393 - 3.563E-7 * d); break; case URANUS: o = new OrbitalElements(74.0005 + 1.3978E-5 * d, 0.7733 + 1.9E-8 * d, 96.6612 + 3.0565E-5 * d, 19.18171 - 1.55E-8 * d, 0.047318 + 7.45E-9 * d, 142.5905 + 0.011725806 * d, 23.4393 - 3.563E-7 * d); break; case NEPTUNE: o = new OrbitalElements(131.7806 + 3.0173E-5 * d, 1.7700 - 2.55E-7 * d, 272.8461 - 6.027E-6 * d, 30.05826 + 3.313E-8 * d, 0.008606 + 2.15E-9 * d, 260.2471 + 0.005995147 * d, 23.4393 - 3.563E-7 * d); break; default: return null; } return o; }
35811391-1026-4ebe-adfc-c67489f2c1c1
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewTaskInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewTaskInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewTaskInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewTaskInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewTaskInfo(gui).setVisible(true); } }); }
90c63f12-9ebb-4d6a-aaf1-6c78703b4773
2
public final Group createGameBoard() { flow = new Timeline(); Group group = new Group(); Image image = new Image(getClass(). getResourceAsStream("socialite.jpg")); int colCount = (int) (image.getWidth() / SlidingPuzzlePiece.getPuzzleSize()); int rowCount = (int) (image.getHeight() / SlidingPuzzlePiece.getPuzzleSize()); gameBoard = new SlidingPuzzleBoard(colCount, rowCount); for (int col = 0; col < colCount; col++) { for (int row = 0; row < rowCount; row++) { int rootX = col * SlidingPuzzlePiece.getPuzzleSize(); int rootY = row * SlidingPuzzlePiece.getPuzzleSize(); new SlidingPuzzlePiece(image, rootX, rootY, gameBoard.getWidth(), gameBoard.getHeight(), new SlidingPuzzleField(col, row, rootX, rootY)); } } gameBoard.getChildren().addAll(SlidingPuzzlePiece.getPuzzlePiece()); resetGameBoard(); mergePuzzlePieces(gameBoard, SlidingPuzzlePiece.getPuzzlePiece()); hideOneField(); activateFields(); final int i10 = 10; VBox displayField = new VBox(i10); displayField.setPadding(new Insets(i10, i10, i10, i10)); displayField.getChildren().addAll(createMenu(), gameBoard); group.getChildren().addAll(displayField); return group; }
1be79026-4998-4c05-b28a-0d3a5b417b0e
3
public static void getTraitStats(Tidy tidy, Document doc, Trait[] traits) { try { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//div[@id = 'bodyContent']/dl/dd/text() |" + "//div[@id = 'bodyContent']/dl/dd/a/text()"); NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); String modifiers = ""; for(int i = 1; i < nodes.getLength(); i++) { modifiers += nodes.item(i).getNodeValue() + nodes.item(i+1).getNodeValue() + "\n"; i += 2; } String[] listModifiers = modifiers.split("\n"); for(int i = 0; i < listModifiers.length; i++) { traits[i/2].setModifier1(listModifiers[i]); traits[i/2].setModifier2(listModifiers[++i]); } }catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3d6fdad8-a8b8-481e-a7ef-d3f709072863
2
private void table_ticketMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_ticketMouseClicked if (evt.getClickCount() == 2) { JTable target = (JTable) evt.getSource(); int row = target.getSelectedRow(); final DetalleRegistro a = new DetalleRegistro(tableTicketModel.getTicket(row), Inicio.getInstance(), true); a.addWindowListener(new DetalleWListener() { @Override public void windowClosed(WindowEvent e) { if (a.isModificado()) { btn_buscarActionPerformed(null); } } }); } }//GEN-LAST:event_table_ticketMouseClicked
53767efe-6d6d-4850-b93f-9eaec91f4284
8
private String[] parseLocalNames() throws IOException, LexerException, ParserException { Token token = this.nextToken(); if (!(token != null && token.getType()==TokenType.SEPARATOR && token.getValue().equals("|"))) { this.pushToken(token); return null; } List<String> names = new ArrayList<String>(); for (token = this.nextToken(); token != null && token.getType()==TokenType.ID; token = this.nextToken()) names.add(token.getValue()); if (token == null || token.getType() != TokenType.SEPARATOR || !token.getValue().equals("|")) throw new ParserException("Expected '|'"); String[] localnames = new String[names.size()]; return names.toArray(localnames); }
2d7fdefb-fa5b-4626-a8b1-349657d5a89f
1
private void addVertices(Vertex[] vertices, int[] indices, boolean calcNormals) { if(calcNormals) { calcNormals(vertices, indices); } size = indices.length; glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, Util.createFlippedBuffer(indices), GL_STATIC_DRAW); }
b56b4b07-6fd0-4c98-9167-d3e09c1e928e
6
@SuppressWarnings("unchecked") public String Write(String contents, String header, List<String> tags) throws Exception{ XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL(serverURL)); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); Map<String, String> result = (Map<String, String>) client.execute("LJ.XMLRPC.getchallenge", new Object[0]); String challenge = (String) result.get("challenge"); String response = PasswordEncrypt.MD5Hex(challenge+password); Calendar calendar = Calendar.getInstance(timeZone); HashMap<String,Object> postParams = new HashMap<String,Object>(); postParams.put("username", userName); postParams.put("auth_method", "challenge"); postParams.put("auth_challenge", challenge); postParams.put("auth_response", response); postParams.put("event", contents); postParams.put("subject", header) ; if (postPrivately) { postParams.put("security","private"); } postParams.put("year",calendar.get(Calendar.YEAR)); postParams.put("mon",calendar.get(Calendar.MONTH)+1); postParams.put("day",calendar.get(Calendar.DAY_OF_MONTH)); postParams.put("hour",calendar.get(Calendar.HOUR_OF_DAY)); postParams.put("min",calendar.get(Calendar.MINUTE)); HashMap<String,Object> options = new HashMap<String,Object>(); String tagsToUse = ""; for (String tag : tags) { if(tagsToUse.length()>0) { tagsToUse+=","; } tagsToUse +=tag; } options.put("taglist", tagsToUse); options.put("opt_preformatted", true); postParams.put("props",options); Object[] params = new Object[]{postParams}; try{ result = (Map<String, String>) client.execute("LJ.XMLRPC.postevent", params); } catch (XmlRpcException e){ if (e.getMessage().equals("Invalid password")){ return "Invalid Password"; } else{ throw e; } } if (result.get("success")=="FAIL"){ return result.get("errmsg"); } return "<A href=" + result.get("url")+ ">Link posted</A>"; }
c13310a9-f3a9-42f3-84a8-2514e75a9d07
5
public BigInteger genPrime(int pBits){ BigInteger p; do { p = new BigInteger(pBits,rnd); if (p.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) continue; if (p.mod(BigInteger.valueOf(3)).equals(BigInteger.ZERO)) continue; if (p.mod(BigInteger.valueOf(5)).equals(BigInteger.ZERO)) continue; if (p.mod(BigInteger.valueOf(7)).equals(BigInteger.ZERO)) continue; } while (!miller_rabin(p)); return p; }
94231eda-13d9-4cab-ad46-e4377df45117
9
public void mouseDragged(MouseEvent e) { //NIVEL 1............................................ if(bNivel1) { for(Object lnkProducto : lnkProductos1) { Producto proObjeto = (Producto) lnkProducto; if(proObjeto.getAgarrado()) { mPosX = e.getX(); mPosY= e.getY(); break; } } } //NIVEL 2............................................ if(bNivel2) { for(Object lnkProducto : lnkProductos2) { Producto proObjeto = (Producto) lnkProducto; if(proObjeto.getAgarrado()) { mPosX = e.getX(); mPosY= e.getY(); break; } } } //NIVEL 3............................................ if(bNivel3) { for(Object lnkProducto : lnkProductos3) { Producto proObjeto = (Producto) lnkProducto; if(proObjeto.getAgarrado()) { mPosX = e.getX(); mPosY= e.getY(); break; } } } }
b12f5e5f-18f5-42b1-a97b-4b6e19e4bb59
1
private static byte[] splitInSextets(byte[] block) { byte[] copy = block; final int nbBits = copy.length * 8; final int nbSextets = nbBits / 6; byte[] sextets = new byte[nbSextets]; for(int i = 0; i < nbSextets; i++) { // verplaats twee posities naar rechts en maak eerste twee bits 0 sextets[i] = (byte) ((copy[0] >> 2) & ~(3 << 6)); // zet volgende sextet vanvoor copy = shift6Left(copy); } return sextets; }
c59cc6d5-79e6-40b9-97ee-e01ac54467a4
0
public void setId(String id) { this.id = id; }
887d0861-451b-42c4-aa4a-d1f93d907681
2
@Override protected void onStart() { for(int i = 0; i < Settings.serversCount; i++){ final int i2 = i; MineOS.getDesktop().addLinkIcon(Resources.getImageIcon("mc.png"), Settings.serverNames[i], new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try{ //Узнаем путь до bin папки. String mc_bin_path = SystemUtil.getGameDirectory(i2) + File.separator + "bin" + File.separator; //Генерируем url-пути для 4х основных файлов //(я не стал ради 4х файлов делать цикл) URL[] urls = new URL[4]; urls[0] = new File(mc_bin_path, "minecraft.jar").toURI().toURL(); urls[1] = new File(mc_bin_path, "lwjgl.jar").toURI().toURL(); urls[2] = new File(mc_bin_path, "jinput.jar").toURI().toURL(); urls[3] = new File(mc_bin_path, "lwjgl_util.jar").toURI().toURL(); //Создаем класс-обёртку для net.minecraft.client.MinecraftApplet MinecraftApplet mineApplet = new MinecraftApplet(mc_bin_path, urls); //Указываем параметры(собственно из-за них и писалать обёртка) mineApplet.customParameters.put("stand-alone", "true"); mineApplet.customParameters.put("userName", MineOS.getLogin()); mineApplet.customParameters.put("server", Settings.serversIp[i2]); mineApplet.customParameters.put("port", new Integer(Settings.serversPorts[i2]).toString()); //Создаем фрейм JFrame frame = MineOS.getDesktop().getFrame(); frame.setTitle("Minecraft"); frame.setExtendedState(frame.getExtendedState() | frame.MAXIMIZED_BOTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.validate(); frame.setVisible(true); MineOS.getDesktop().removeAll(); MineOS.getDesktop().setNeedDraw(false); frame.remove(MineOS.getDesktop()); frame.removeWindowListener(frame.getWindowListeners()[0]); //Только после показа окна нужно инициализировать mineApplet //Связано это с тем, что до того как окно нарисуется, функции getWidth() и getHeight() у mineApplet возвращают 0 frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mineApplet, BorderLayout.CENTER); frame.setIconImage(Resources.getImageIcon("mc.png").getImage()); mineApplet.setSize(frame.getSize()); mineApplet.init(); mineApplet.start(); }catch(Exception e){ e.printStackTrace(); } } }); } }
13768025-8d20-4722-a08b-ee3595fa57f4
6
public void drawString(String str,int x,int y,int type,float scale){ if(str==null){ return; } for(int i=0;i<(str.length());i++){ Texture t = map.get("A"); try { t = map.get(str.charAt(i)+""); t.bind(); } catch (Exception e) { System.err.println("Image load crash on symbol \""+str.charAt(i)+"\""); t = map.get("?"); t.bind(); } int w = t.width; int h = t.height; int dw = w-tw; int dh = h-th; switch(type){ case LEFT: Molybdenum.GLQuad(x+((w-dw)*scale*i), y, w, h, scale); break; case CENTER: int xsize = (int) (w*scale*str.length())/2; int ysize = (h-dh); Molybdenum.GLQuad(x+((w)*scale*i)-xsize, y-ysize, w, h, scale); break; case RIGHT: int nw = (int) ((str.length()*tw*scale)); //int dh = (int) (Display.getHeight()-(h*scale)); Molybdenum.GLQuad(((w-dw)*scale*i)+x-nw, y, w, h, scale); break; } } }
143bc3e2-e055-4154-86d2-f1c8438dba61
7
private float addModifier(Modifier modifier, UnitType unitType, float result) { FreeColObject source = modifier.getSource(); String sourceName; if (source == null) { sourceName = "???"; } else { sourceName = Messages.getName(source); if (unitType != null && modifier.hasScope()) { for (Scope scope : modifier.getScopes()) { if (scope.appliesTo(unitType)) { sourceName += " (" + Messages.message(unitType.getNameKey()) + ")"; } } } } float value = modifier.getValue(turn); if (value == 0) { return result; } String[] bonus = getModifierStrings(value, modifier.getType()); add(new JLabel(sourceName), "newline"); add(new JLabel(bonus[0] + bonus[1])); if (bonus[2] != null) { add(new JLabel(bonus[2])); } return modifier.applyTo(result, turn); }
0fbad56b-1108-4532-bca3-cc7d7906b2e7
8
@Override public int attack(final NPC npc, final Entity target) { final NPCCombatDefinitions defs = npc.getCombatDefinitions(); npc.setNextAnimation(new Animation(defs.getAttackEmote())); switch (Utils.getRandom(5)) { case 0: npc.setNextForceTalk(new ForceTalk("Bwuk")); break; case 1: npc.setNextForceTalk(new ForceTalk("Bwuk bwuk bwuk")); break; case 2: String name = ""; if (target instanceof Player) name = ((Player) target).getDisplayName(); npc.setNextForceTalk(new ForceTalk("Flee from me, " + name)); break; case 3: name = ""; if (target instanceof Player) name = ((Player) target).getDisplayName(); npc.setNextForceTalk(new ForceTalk("Begone, " + name)); break; case 4: npc.setNextForceTalk(new ForceTalk("Bwaaaauuuuk bwuk bwuk")); break; case 5: npc.setNextForceTalk(new ForceTalk("MUAHAHAHAHAAA!")); break; } target.setNextGraphics(new Graphics(337)); delayHit( npc, 0, target, getMagicHit( npc, getRandomMaxHit(npc, defs.getMaxHit(), NPCCombatDefinitions.MAGE, target))); return defs.getAttackDelay(); }
10cc88a0-d600-4661-8280-fe04d35c97a5
8
public static AbstractNearByPlacesFacade getFacade(String publisher, String contextPath, int displaySize) throws CitysearchException { if (publisher == null) { throw new CitysearchException("NearByPlacesFacadeFactory", "getFacade", "Invalid Publisher Code."); } else if (publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_INSIDERPAGES)) { return new InsiderPagesNearByPlacesFacade(contextPath, displaySize); } else if (publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_PROJECT_YELLOW) || publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_CITYSEARCH) || publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_URBANSPOON)) { return new ConquestNearByPlacesFacade(contextPath, displaySize); } else if (publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_URBANSPOON) && displaySize == 3) { return new InsiderPagesNearByPlacesFacade(contextPath, displaySize); } else if (publisher.equalsIgnoreCase(CommonConstants.PUBLISHER_CBS)) { return new CBSNearbyPlacesFacade(contextPath, displaySize); } return null; }
f8f3c969-475f-4546-85f9-aa64af1d9979
2
public int findPosNode(T x) {//return position of node int pos=0; Node<T> ele = _head; while (ele != null) { if (ele.getData().equals(x)) return pos; else{ ele = ele.getNext(); pos+=1; } } return -1;//node is not int the list. }
77752913-9011-40fa-bdcd-50bb90141725
5
private void ParseOutElements(org.w3c.dom.Element parentElement) { Node child = parentElement.getFirstChild(); while (child != null) { if (! handleGeneralProperty(child)) { String nodeName = child.getNodeName(); // Container specific properties: accept[ ], item[ ] if (nodeName == "item") { containedItemNames.add(child.getFirstChild().getNodeValue()); } else if (nodeName == "accept") { acceptItemNames.add(child.getFirstChild().getNodeValue()); } else if (nodeName == "status") { status = child.getFirstChild().getNodeValue(); } } child = child.getNextSibling(); } }
33d10c0d-b2ad-46ad-8225-0f62d7ff1d4d
1
public void setVisible(boolean visible) { if(frame == null) buildGUI(); frame.setVisible(visible); log.exiting(getClass().getSimpleName(), "setVisible(boolean)"); }
bc7af0ba-4190-40ed-a3c0-cb9a63f05bea
8
public static String stringFor_cl_sampler_info(int n) { switch (n) { case CL_SAMPLER_REFERENCE_COUNT: return "CL_SAMPLER_REFERENCE_COUNT"; case CL_SAMPLER_CONTEXT: return "CL_SAMPLER_CONTEXT"; case CL_SAMPLER_NORMALIZED_COORDS: return "CL_SAMPLER_NORMALIZED_COORDS"; case CL_SAMPLER_ADDRESSING_MODE: return "CL_SAMPLER_ADDRESSING_MODE"; case CL_SAMPLER_FILTER_MODE: return "CL_SAMPLER_FILTER_MODE"; case CL_SAMPLER_MIP_FILTER_MODE: return "CL_SAMPLER_MIP_FILTER_MODE"; case CL_SAMPLER_LOD_MIN: return "CL_SAMPLER_LOD_MIN"; case CL_SAMPLER_LOD_MAX: return "CL_SAMPLER_LOD_MAX"; } return "INVALID cl_sampler_info: " + n; }
b2e6d00a-0c55-498c-888a-60c1e6d47ec8
7
public boolean saveSettings() { String line = null; BufferedWriter ini_file; try { //open file ini_file = new BufferedWriter( new FileWriter( JIPT_INI_PATH + JIPT_INI_FILENAME ) ); //write show Splash screen info ini_file.write( "SPLASHSCREEN= " + booleanToInt( this.showSplashScreen ) ); ini_file.newLine(); //write autoHistogram data ini_file.write( "AUTOHISTOGRAM= " + booleanToInt( this.autoHistogram ) ); ini_file.newLine(); //write autoFileInfo data ini_file.write( "AUTOINFO= " + booleanToInt( this.autoFileInfo ) ); ini_file.newLine(); //write saveWindowSettings data ini_file.write( "SAVEWINSETTINGS= " + booleanToInt( this.saveWindowSettings ) ); ini_file.newLine(); if( this.saveWindowSettings ) { //write Window Settings Sizes ini_file.write( "WINSIZEX= " + this.savedParentWidth ); ini_file.newLine(); ini_file.write( "WINSIZEY= " + this.savedParentHeight ); ini_file.newLine(); //write Window Settings Location ini_file.write( "WINPOSX= " + this.windowPositionX ); ini_file.newLine(); ini_file.write( "WINPOSY= " + this.windowPositionY ); ini_file.newLine(); } //write Image Load Path ini_file.write( "CURRENTPATH= " + this.current_path ); ini_file.newLine(); //write clear pixel color ini_file.write( "CLEARPIXEL= " + this.clearPixelColor ); ini_file.newLine(); //write max_undo_size ini_file.write( "NUMUNDO= " + this.max_undo_size ); ini_file.newLine(); //write number of recent files to save ini_file.write( "MAXRECENT= " + this.numRecentFiles ); ini_file.newLine(); //write recentFile array to store filenames for( int loop=0; loop < this.numRecentFiles; loop++ ) { String rf = this.recentFile[loop]; if( (rf != null) && (!rf.equalsIgnoreCase("null")) ) { ini_file.write( "RECENTFILE= " + rf ); ini_file.newLine(); } } //store background color ini_file.write( "BGCOLOR= " + this.bg_color ); ini_file.newLine(); //store custom colors for( int loop=0; loop < this.customColor.size(); loop++ ) { JIPTColor c = (JIPTColor)this.customColor.get( loop ); Color color = c.getColor(); ini_file.write( "CUSTOMCOLOR= " + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " " + c.getName() ); ini_file.newLine(); } //close file ini_file.close(); } catch( FileNotFoundException e ) { e.printStackTrace(); return false; } catch( IOException e ) { e.printStackTrace(); return false; } return true; }//end saveSettings
3da3b210-3125-4817-9788-1bae9c51a92d
4
@Override public boolean isAllowedToBorrow(Loan loan, StockController stockController) { if (stockController.numberOfLoans(this) < 4) { if (loan.getQuantity() < 25) { if (CalendarController.differenceDate(loan.getStart(), loan.getEnd()) < 8) { if (CalendarController.differenceDate( new GregorianCalendar(), loan.getStart()) < 15) { return true; } } } } return false; }
cb74122d-8a08-434d-835b-f84d33938704
0
public static void compare(String dna1, String dna2) { System.out.println("Difference = " + mss(dna1, dna2, true)); }
ddc2da0d-9fff-4820-bbd0-fab6f1ed84dc
7
public String createParsedURI (String searchTerm, String mediaType){ /* * Given a search term return the KAT URI. * example @param: "linkin park in the end/", "music" */ String baseURI = Constants.KAT_SEARCH_BASE; String parsedQuery = ""; String URI; if (mediaType.toLowerCase().equals("movie") || mediaType.toLowerCase().equals("movies")) URI = Constants.KAT_SEARCH_MOVIE_SUFFIX; else URI = Constants.KAT_SEARCH_MUSIC_SUFFIX; for (int i = 0; i < searchTerm.length(); i++){ if (searchTerm.charAt(i) == ' ') parsedQuery = parsedQuery + "%20"; else if ( (int) searchTerm.charAt(i) == 39 || (int) searchTerm.charAt(i) == 145 || (int) searchTerm.charAt(i) == 146 ){ parsedQuery = parsedQuery + "%27"; } else parsedQuery = parsedQuery + searchTerm.charAt(i); } return baseURI + parsedQuery + URI; //returns the search }
d75798e5-f621-4561-a525-71766e96485f
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TermStatus)) return false; TermStatus other = (TermStatus) obj; if (average == null) { if (other.average != null) return false; } else if (!average.equals(other.average)) return false; if (prerequisitesDone != other.prerequisitesDone) return false; if (unitsLeft != other.unitsLeft) return false; return true; }