method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5651b8fd-986c-4920-a76f-361805f812a0
1
@Override public Member getMemberByEmailId(String emailId) { Session session = this.sessionFactory.getCurrentSession(); Query query = session.createQuery("from Member where EmailId = :emailId "); query.setParameter("emailId", emailId); List list = query.list(); if (list.isEmpty()) { return null; } return (Member) list.get(0); }
7ace2e2d-6ffd-4348-9f70-6c28221f6b24
7
public void compFinalResult() { do { iStage++; compAllocation(); if (compDistribution()) { /* deadline can not be satisfied */ if (!bDeadline) { System.out.println("CostSufferage: THE DEADLINE CAN NOT BE SATISFIED!"); return; } else { System.out.println("\nNEW ROUND WITHOUT CHECKING:"); dEval = 1; } } else { compExecTime(); } // System.out.println("Evaluation Value =========="+dEval); } while (dEval > 0); // while (evaluateResults()); // System.out.println("==================Distribution====================="); for (int i = 0; i < iClass; i++) { // System.out.print("FinalDistribution[" + i + "] "); for (int j = 0; j < iSite; j++) { dmDist[i][j] = Math.round(dmDist[i][j]); // System.out.print(dmDistribution[i][j] + ","); } // System.out.println(); } // System.out.println("==================Allocation====================="); for (int i = 0; i < iClass; i++) { System.out.print("FinalAllocation[" + i + "] "); for (int j = 0; j < iSite; j++) { dmAlloc[i][j] = Math.round(dmAlloc[i][j]); // System.out.print(dmAllocation[i][j] + ","); } // System.out.println(); } // System.out.println("Stage = " + iStage); }
e5e74471-7003-4f41-90f8-ad865b3abfaa
5
@Override public long[] run(String query) { FUNCTION_NAME = "TJSGM"; query = query.toUpperCase(); boolean state = true; SQLParser parser = new SQLParser(); state &= parser.parse(query + ".txt"); // file name wrieteGlobalInfoToHDFS(parser); long[] time = new long[4]; long startTime = new Date().getTime(); if (state) { if (state) { // init conf Configuration conf = new Configuration(); state &= doFirstPhase(query, conf, PATH_OUTPUT_FIRST, parser.getFilterTables()); time[0] = new Date().getTime() - startTime; startTime = new Date().getTime(); } if (state) { // init conf Configuration conf = new Configuration(); state &= doSecondPhase(query, conf, PATH_OUTPUT_SECOND, parser.getTables(), parser.getFilterTables(), (parser.getTables().length - 1)*reduceScale); time[1] = new Date().getTime() - startTime; startTime = new Date().getTime(); } if (state) { Configuration conf = new Configuration(); state &= doThirdPhase(query.toUpperCase(), conf, PATH_OUTPUT_THIRD); time[2] = new Date().getTime() - startTime; startTime = new Date().getTime(); } if (state) { Configuration conf = new Configuration(); state &= doForthPhase(query.toUpperCase(), conf, PATH_OUTPUT_FINAL); time[3] = new Date().getTime() - startTime; startTime = time[3]; } } return time; }
f6766729-308e-4c2e-9e2d-dc6b59618ffa
1
public void notifyPeersPieceCompleted(int index) { byte[] m = Message.haveBuilder(index); for(Peer p : this.peerList){ p.sendMessage(m); } }
34168755-ffef-4a8c-ae5e-21a2f8927a80
9
private Object number() { int length = 0; boolean isFloatingPoint = false; buf.setLength(0); if (c == '-') { add(); } length += addDigits(); if (c == '.') { add(); length += addDigits(); isFloatingPoint = true; } if (c == 'e' || c == 'E') { add(); if (c == '+' || c == '-') { add(); } addDigits(); isFloatingPoint = true; } String s = buf.toString(); return isFloatingPoint ? (length < 17) ? (Object)Double.valueOf(s) : new BigDecimal(s) : (length < 19) ? (Object)Long.valueOf(s) : new BigInteger(s); }
97d26e63-94ea-4683-8a80-3e7ea61461a2
8
@Override public void execute() { SceneObject rock = SceneEntities.getNearest(Main.getRockIDs()); if (Inventory.isFull()) { if (BANK_AREA.contains(Players.getLocal().getLocation())) { if (Bank.isOpen()) { Bank.deposit(Main.oreID, 28); } else { Bank.open(); } } else if (MINE_AREA.contains(Players.getLocal().getLocation())) { Path path = Walking.findPath(BANK_TILE); path.traverse(); } } else { if (BANK_AREA.contains(Players.getLocal().getLocation())) { Path path = Walking.findPath(MINE_TILE); path.traverse(); } else if (MINE_AREA.contains(Players.getLocal().getLocation())) { if (rock != null) { if (rock.isOnScreen()) { rock.interact("Mine"); } else { Camera.turnTo(rock); } } } } }
424062ac-003d-4cd4-93b6-a5107fd56819
4
public static void main(String[] args) { long res = 0; int save = 0; int runs = 0; int tempRuns = 0; for(int i = 1; i < 1000000; i++) { res = i; tempRuns = 0; while(res != 1) { tempRuns++; if(res % 2 == 0) res = res / 2; else res = (res * 3) + 1; } if(tempRuns > runs) { runs = tempRuns; save = i; } } System.out.println(save); }
538e28b3-0c5a-4a51-ad95-9e5e315c105e
9
public int solution(int A, int B, int K) { if (B != 0 && B<K) { return 0; } else if (A == B) { return (A%K == 0) ? 1 : 0; } else if (A != 0 && A < K) { A = K; } int from = (A % K == 0) ? A : A + (K-(A % K)); int range = (B-from); int diff = 0; if (B % K == 0) diff++; return (range / K) + (range % K == 0 ? 0 : 1) + diff; }
43679d26-348c-40de-b553-f90386295fd5
8
@Override public final void Paint(Graphics PanelGraphics) { Graphics2D Graphics = this.GameImage.createGraphics(); GeneralHelper.DrawBackground(Graphics, this.GetPanelWidth(), this.GetPanelHeight(), this.GameSize, this.GameStopped); if (!this.GameStopped) { if (this.GameStarted) { if (this.Direction == GameDirection.UP) this.Location.MinY(); if (this.Direction == GameDirection.RIGHT) this.Location.PlusX(); if (this.Direction == GameDirection.DOWN) this.Location.PlusY(); if (this.Direction == GameDirection.LEFT) this.Location.MinX(); if (this.GameField.IsOutside(this.Location)) this.Location = this.GameField.GetReversedVector(this.Location); this.DrawImage(Graphics, this.Location); this.PushData(new SneekDataPlayer(new NetworkVectorPlayer(this.Location))); } } else { if (!this.GameOver) { new Thread(new ServerGameOverFrame(this.Winner, this)).start(); this.GameOver = true; } this.DrawRandomImage(Graphics, ImageHelper.GetCoolFace(), 50, 50); } PanelGraphics.drawImage(this.GameImage, 0, 0, this.GetPanelWidth(), this.GetPanelHeight(), null); }
0825f233-21ae-40de-b5fa-62dfb73bd9a1
8
public static List<List<Integer>> getAllPolygonals() { List<List<Integer>> polygonals = new ArrayList<List<Integer>>(); for(int i = 0; i < 6; i++) polygonals.add(new ArrayList<Integer>()); for(int i = 1000; i <= 9999; i++) { if(isTriangle(i)) polygonals.get(0).add(i); if(isSquare(i)) polygonals.get(1).add(i); if(isPentagonal(i)) polygonals.get(2).add(i); if(isHexagonal(i)) polygonals.get(3).add(i); if(isHeptagonal(i)) polygonals.get(4).add(i); if(isOctagonal(i)) polygonals.get(5).add(i); } return polygonals; }
75ef7c97-6192-4220-a152-aba0c235fe71
1
private void editFile(File file) { try { Runtime.getRuntime().exec(DEFAULT_EDITOR + " " + file.getAbsolutePath()); } catch (IOException e){ noteEditorFrame.showMessage("I/O Error", "Open editor error", JOptionPane.ERROR_MESSAGE); } }
fe272e9c-4915-4bce-be54-cbf377b6a22e
9
private boolean jj_3R_34() { Token xsp; xsp = jj_scanpos; if (jj_3R_37()) { jj_scanpos = xsp; if (jj_3R_38()) { jj_scanpos = xsp; if (jj_3R_39()) { jj_scanpos = xsp; if (jj_3R_40()) { jj_scanpos = xsp; if (jj_3R_41()) { jj_scanpos = xsp; if (jj_3R_42()) { jj_scanpos = xsp; if (jj_3R_43()) { jj_scanpos = xsp; if (jj_3R_44()) { jj_scanpos = xsp; if (jj_3R_45()) return true; } } } } } } } } return false; }
a09a2d9b-326c-4232-9805-3606f1196a56
8
public static <T extends DC> Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> getAllPairs(Set<Pair<PT<Integer>,T>> baseSetA, Set<Pair<PT<Integer>,T>> baseSetB) { Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> res; if(baseSetA==null||baseSetB==null) { return null; } else//baseSetA!=null&&baseSetB!=null { if(baseSetA.getNext()==null && baseSetB.getNext()==null) { res=new Set(new Pair(baseSetA.getFst(),baseSetB.getFst()),null); } else if(baseSetA.getNext()!=null && baseSetB.getNext()==null) { res=new Set(new Pair(baseSetA.getFst(),baseSetB.getFst()),getAllPairs(baseSetA.getNext(), baseSetB)); } else if(baseSetA.getNext()==null && baseSetB.getNext()!=null) { res=new Set(new Pair(baseSetA.getFst(),baseSetB.getFst()),getAllPairs(baseSetA,baseSetB.getNext())); } else { res=getAllPairs(new Set(baseSetA.getFst(),null),baseSetB).concat(getAllPairs(baseSetA.getNext(),baseSetB)); } return res; } }
04f0b6a0-0653-4384-83f9-97ab27e20f58
2
private void calculateSizes() { if (!mDirty) { return; } mDirty = false; mSize.width = 0; mSize.height = 0; Enumeration e = mComponents.keys(); while (e.hasMoreElements()) { Component c = (Component) e.nextElement(); Point p = (Point) mComponents.get(c); mSize.width = Math.max(mSize.width, c.getPreferredSize().width + p.x); mSize.height = Math.max(mSize.height, c.getPreferredSize().height + p.y); } }
7c6ceff3-ddb8-4c90-b46f-40dadc957626
2
@Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; CashOffice otherCashOffice = (CashOffice) other; return this.number == otherCashOffice.number; }
53a3ce70-e4b2-4347-a121-44b5df2f3d19
4
public String getTranslation( int langID ) { if ( ( langID >= 0 ) && ( langID < numberOfTranslations ) ) { TValueEntry dummy = values[langID] ; if ( dummy != null ) { return dummy.value ; } } // no translation but a default value if ( defValue != null ) { return defValue.value ; } // no default and translation found return this.getKey() ; }
1ecc96a6-ed58-4634-a16f-10e82af6d6bd
8
public void method390(int x, int alpha, String text, int seed, int y) { if (text == null) { return; } random.setSeed(seed); int color = 192 + (random.nextInt() & 0x1f); y -= trimHeight; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '@' && i + 4 < text.length() && text.charAt(i + 4) == '@') { int col = getColorByName(text.substring(i + 1, i + 4)); if (col != -1) { alpha = col; } i += 4; } else { char c = text.charAt(i); if (c != ' ') { drawChar(192, x + horizontalKerning[c] + 1, pixels[c], width[c], y + verticalKerning[c] + 1, height[c], 0); drawChar(color, x + horizontalKerning[c], pixels[c], width[c], y + verticalKerning[c], height[c], alpha); } x += charWidths[c]; if ((random.nextInt() & 3) == 0) { x++; } } } }
bed8a995-e25a-4863-a68d-6d95d5dd1bcf
8
public DrawableNode findCommonAncestor(ArrayList<DrawableNode> sample) { if (sample.size()==0) //shouldn't happen, but just in case return null; DrawableNode newroot = (DrawableNode)root; ArrayList<Node> containsSample = new ArrayList<Node>(); for(Node kid : newroot.getOffspring()) { if (subtreeContainsNodes( (DrawableNode)kid, sample)) containsSample.add(kid); } while(containsSample.size()==1) { newroot = (DrawableNode)containsSample.get(0); containsSample.clear(); for(Node kid : newroot.getOffspring()) { if (subtreeContainsNodes( (DrawableNode)kid, sample)) containsSample.add(kid); } } if (containsSample.size()==0) //This should never happen either return null; if (containsSample.size()>1) { System.out.println("Found common ancestor : " + newroot.getLabel()); return newroot; } //We should never get here System.out.println("Error in finding common ancestor, returning null node"); return null; }
fc7fc3b3-4366-4d7c-aac3-a4956c0b4a0f
9
public String toString(){ StringBuffer strbuf = new StringBuffer(); strbuf.append(this.getBeginPosition()).append("-").append(this.getEndPosition()); strbuf.append(" : ").append(this.lexemeText).append(" : \t"); switch(lexemeType) { case TYPE_UNKNOWN : strbuf.append("UNKONW"); break; case TYPE_ENGLISH : strbuf.append("ENGLISH"); break; case TYPE_ARABIC : strbuf.append("ARABIC"); break; case TYPE_LETTER : strbuf.append("LETTER"); break; case TYPE_CNWORD : strbuf.append("CN_WORD"); break; case TYPE_OTHER_CJK : strbuf.append("OTHER_CJK"); break; case TYPE_COUNT : strbuf.append("COUNT"); break; case TYPE_CNUM : strbuf.append("CN_NUM"); break; case TYPE_CQUAN: strbuf.append("CN_QUAN"); break; } return strbuf.toString(); }
27979ec5-a665-4656-8e61-48b2ec5cd47a
2
public void moveSide(Direction d) { if(d == Direction.RIGHT) { blockCol++; updateBoard(); } else if (d == Direction.LEFT) { blockCol--; updateBoard(); } else { System.out.println("UNEXPECTED ERROR, UNABLE TO MOVE"); } }
bf05d0e8-64e8-4c6c-8730-2a3ea5f28f2c
9
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); //由context parameter取得JDBC需要的資訊 ServletContext sc = this.getServletConfig().getServletContext(); String dbUrl = sc.getInitParameter("ottzDBurl"); String ottzUser = sc.getInitParameter("ottzUser"); String ottzPassword = sc.getInitParameter("ottzPassword"); String jdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; if("addFilterTrain".equals(action)){ //取得qureyString的bestN與bestK String bestN_temp = request.getParameter("bestN"); String bestK_temp = request.getParameter("bestK"); String trainStartDate = request.getParameter("trainStartDate"); String trainEndDate = request.getParameter("trainEndDate"); String trainStockSymbol = request.getParameter("trainStockSymbol"); //建立寫入FilterTrain物件 FilterDAO daoFT_insert = null; String sResultInsert =""; try{ daoFT_insert = new FilterDAO(jdbcDriver, dbUrl,ottzUser,ottzPassword); sResultInsert = daoFT_insert.insertTraining(bestN_temp, bestK_temp,trainStartDate, trainEndDate, trainStockSymbol); }catch(Exception e){ sResultInsert = "取消寫入紀錄: " + e; }finally{ if(daoFT_insert != null) try { daoFT_insert.closeConn(); } catch (SQLException ex) { throw new ServletException("關閉sql connection階段發生例外:<br/> " + ex); } } //輸出結果 request.setAttribute("bestn", bestN_temp); request.setAttribute("bestk", bestK_temp); request.setAttribute("ResultInsert", sResultInsert); request.getRequestDispatcher("/WEB-INF/FilterPages/training/ShowDdTradeResult.jsp").forward(request, response); } if("addFilterTest".equals(action)){ List<TradeRecord> listTrade = (List<TradeRecord>)request.getSession().getAttribute("trade"); String bestN = request.getParameter("bestN"); String bestK = request.getParameter("bestK"); String testStockSymbol = request.getParameter("testStockSymbol"); String testStartDatetime = request.getParameter("testStartDatetime"); String testEndDatetime = request.getParameter("testEndDatetime"); String RplotUrl = request.getParameter("RplotUrl"); String revenue = request.getParameter("revenue"); String testingCode = request.getParameter("testingCode"); String hasTrade = request.getParameter("hasTrade"); FilterDAO daoFT_insert = null; String resultInsertTesting = ""; String resultInsertTestingTrade=""; try{ daoFT_insert = new FilterDAO(jdbcDriver, dbUrl,ottzUser,ottzPassword); //note: insertTestingTrade因為沒有pk, 此處無法用例外排除重複寫入 故放在insertTesting下方 //當insertTesting失敗即會跳過insertTestingTrade進入例外處理 resultInsertTesting = daoFT_insert.insertTesting(bestN,bestK,testStartDatetime,testEndDatetime,testStockSymbol,revenue,testingCode,RplotUrl); if("true".equals(hasTrade)) resultInsertTestingTrade = daoFT_insert.insertTestingTrade(listTrade, testingCode); }catch(Exception e){ resultInsertTesting = "取消寫入紀錄: " + e; }finally{ if(daoFT_insert != null) try { daoFT_insert.closeConn(); } catch (SQLException ex) { throw new ServletException("關閉sql connection階段發生例外:<br/> " + ex); } } //輸出結果 request.setAttribute("resultInsertTesting", resultInsertTesting); request.setAttribute("resultInsertTestingTrade", resultInsertTestingTrade); RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/FilterPages/testing/ShowDbTradeResult.jsp"); rd.forward(request, response); System.out.println(resultInsertTesting); } }
d98c5364-7f4a-475b-8fdf-31552d59645f
3
private int calcDef() { if (leadership > 92) { // For high Leadership commanders return Math.round(leadership * 8 / 10 + intelligence * 2 / 10); } else if (combatPower > 92) { // For high combatPower commanders return Math.round(combatPower * 6 / 10 + leadership * 4 / 10); } else if (intelligence > 92) { // For high intelligence commanders return Math.round(leadership * 6 / 10 + intelligence * 4 / 10); } else { // For everyone else return Math.round(leadership * 6 / 10 + combatPower * 4 / 10); } }
27b1a53e-2bc0-4dae-a9eb-8840d000aa49
0
public FireSword(){ this.name = Constants.FIRE_SWORD; this.attackScore = 20; this.attackSpeed = 15; this.money = 1500; }
8cf3dd3c-d6e9-438b-8f33-6ce79bcc6370
3
public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) { String fileToRead = (String)comboBox.getSelectedItem(); if (!comboBox.getSelectedItem().equals(Files.REVERT)) fileToRead += Files.PRESET_EXTENSION; if (FileParser.readFile(fileToRead)) FileParser.writeFile(Files.CONFIG); } }
e2a13317-00ab-467c-9353-11b1566031df
5
private static void check14() { if (!checked14) { checked14 = true; StringTokenizer st = new StringTokenizer(System.getProperty("java.specification.version"), "."); try { int major = Integer.parseInt(st.nextToken()); int minor = Integer.parseInt(st.nextToken()); is14 = major > 1 || (major == 1 && minor >= 4); } catch (Exception e) { e.printStackTrace(); } } if (!is14) throw new UnsupportedOperationException("this operation requires Java 1.4 or higher"); }
2a8a37fb-66d3-4a80-83dc-3444c04e2695
0
public void onQuestionChange(Question question) { setQuestion(question); }
e4242ec5-a402-4174-8bf8-a480193ca7f6
4
private ArrayList<Position> findBoxes(ArrayList<String> board) { ArrayList<Position> boxes = new ArrayList<Position>(); for (int y = 0; y < board.size(); ++y) { for (int x = 0; x < board.get(y).length(); ++x) { char c = board.get(y).charAt(x); if (c == '$' || c == '*') boxes.add(new Position(x, y)); } } return boxes; }
02ba6d3c-5178-4b56-ae48-646c095084de
2
public void run() { while(true) { try { receiveData(); } catch (Exception e) { e.printStackTrace(); } } }
7058c3d3-dbae-4e33-8f3c-cd47d9a44e70
0
public void setFoo1(T1 foo1) { this.foo1 = foo1; }
a7c9308b-35e5-41e1-8493-684d272d7fcd
5
public void mouseInteract() { int mouseX = MouseInfo.getPointerInfo().getLocation().x; int mouseY = MouseInfo.getPointerInfo().getLocation().y; if (!holdingItem && !inventoryOpen) { interact(); } if (holdingItem && !inventoryOpen) { placeItemHeld(direction); } if (inventoryOpen) { inventoryInteract(-mouseX, -mouseY); } }
77996c1b-4d49-4223-8a66-641e9ab696e0
1
@Override public void mouseExited(MouseEvent e) { if(e.getComponent().getName().equals("globeMenu")) parent.getTitlePanel().hoverGlobe(); }
26b11fdf-304a-4508-9754-2eb82450d35e
5
public static void main(String[] args) { ElevensBoard board = new ElevensBoard(); int wins = 0; for (int k = 0; k < GAMES_TO_PLAY; k++) { if (I_AM_DEBUGGING) { System.out.println(board); } while (board.playIfPossible()) { if (I_AM_DEBUGGING) { System.out.println(board); } } if (board.gameIsWon()) { wins++; } board.newGame(); } double percentWon = (int)(1000.0 * wins / GAMES_TO_PLAY + 0.5) / 10.0; System.out.println("Games won: " + wins); System.out.println("Games played: " + GAMES_TO_PLAY); System.out.println("Percent won: " + percentWon + "%"); }
b7f1a057-bab8-45a2-b2e3-e34bf441347c
4
public String[] split(String message) { char[] array = message.toCharArray(); String toadd = ""; ArrayList<String> temp = new ArrayList<String>(); for (int i = 0; i < array.length; i++) { toadd += "" + array[i]; if (i % 64 == 0 && i != 0) { temp.add(toadd); toadd = ""; } } if (!toadd.equals("")) temp.add(toadd); return temp.toArray(new String[temp.size()]); }
5e474700-dcd3-4d59-a2f2-d9910ddc4b70
5
public String interpret(Symtab st) { String result = ""; if (oa != null) { //SymtabEntry id1Entry = st.lookup(oa.getID1().toString()); //struct interpretation if (!oa.getObjectType(st).equals("message")) { result += oa.toString() + " = "; result += parlist.interpret(); result += ";\n"; //message interpretation } else { if (oa.oa == null) { result += oa.getID1() + " = " + oa.getID1() + "." + "replace(\"*" + oa.getID2() + "*\", "; result += parlist.interpretWC(st); result += ");\n"; } else { result += oa.oa.toString() + " = " + oa.oa.toString() + "." + "replace(\"*" + oa.getID2() + "*\", "; result += parlist.interpretWC(st); result += ");\n"; } } } else { String type = st.lookup(ident.toString()).getType(); if (parlist != null) { if (st.lookup(type.toString()) == null) { result += ident.toString() + " = "; result += parlist.interpret(); result += ";\n"; } else { result += ident.toString() + " = new " + type.toString() + "("; result += parlist.interpret(); result += ");\n"; } } } return result; }
cd08febb-d588-48d6-a771-71803954836d
0
public void setDate(Date date) { this.date = date; }
cddaec80-c6c0-4403-ad36-b61e9222f8ee
0
public Villager() { this.setAdult(true); this.setAlive(true); this.setProffession(null); this.setHealth(initHealth); this.setHunger(initHunger); this.setThirst(initThirst); this.setTool(null); this.setArmor(0); pos = new Point2D.Double(); }
8819478e-e3db-4b57-8f99-d84d67cdab66
5
public static void main(String[] args) { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); initCards(); Mat AdAs = Highgui.imread(getAbsoluteFilePath("AcesHand.png")); for (Card card : deck) { if (isCardInImage(card, AdAs)) { System.out.println("*" + card.name + " is in AdAs"); } else { System.out.println(card.name + " is NOT in AdAs"); } } System.out.println(""); Mat KhKs = Highgui.imread(getAbsoluteFilePath("KhKs.png")); for (Card card : deck) { if (isCardInImage(card, KhKs)) { System.out.println("*" + card.name + " is in KhKs"); } else { System.out.println(card.name + " is NOT in KhKs"); } } // // Robot robot = new Robot(getGraphicsDevice()); // // //907,596 // //1006,643 // // Rectangle rect = new Rectangle(907, 596, 100, 50); // // BufferedImage image = robot.createScreenCapture(rect); // // File outFile = new File("C:/eclipse/My Junk/test.jpg"); // ImageIO.write(image, "jpg", outFile); } catch (Throwable t) { System.out.println("Error: " + t + ", " + t.getMessage()); System.out.println(t.getStackTrace()); } }
828f79d6-af51-4ec1-ac56-7104f20a942c
6
public static ClassInfo forName(String name) { if (name == null || name.indexOf(';') != -1 || name.indexOf('[') != -1 || name.indexOf('/') != -1) throw new IllegalArgumentException("Illegal class name: " + name); int hash = name.hashCode(); Iterator iter = classes.iterateHashCode(hash); while (iter.hasNext()) { ClassInfo clazz = (ClassInfo) iter.next(); if (clazz.name.equals(name)) return clazz; } ClassInfo clazz = new ClassInfo(name); classes.put(hash, clazz); return clazz; }
1f97b038-0a69-4c64-b15e-a6b89ceb27d4
7
@Override public void update(long delta) { if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { InputController.keyDown(delta, Keyboard.KEY_UP); } if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { InputController.keyDown(delta, Keyboard.KEY_DOWN); } if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { InputController.keyDown(delta, Keyboard.KEY_LEFT); } if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { InputController.keyDown(delta, Keyboard.KEY_RIGHT); } for (StaticEntity e : StaticEntity.entities) { e.update(delta); } if(StaticEntity.newEntities.size() > 0) { StaticEntity.entities.addAll(StaticEntity.newEntities); StaticEntity.newEntities.clear(); } if(StaticEntity.obsoleteEntities.size() > 0) { StaticEntity.entities.removeAll(StaticEntity.obsoleteEntities); StaticEntity.obsoleteEntities.clear(); } }
685ac99f-d397-42a3-bb37-21e1656c84e4
7
private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } }
b18ff711-8c01-4990-9ce7-8d94910c0f66
3
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = ConfigurationManager.getProperty("path.page.countries"); try { Criteria criteria = new Criteria(); Country currCountry = (Country) request.getSessionAttribute(JSP_CURRENT_COUNTRY); if (currCountry == null) { throw new TechnicalException("message.errorNullEntity"); } criteria.addParam(DAO_ID_COUNTRY, currCountry.getIdCountry()); User user = (User) request.getSessionAttribute(JSP_USER); if (user != null) { ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName()); criteria.addParam(DAO_ROLE_NAME, type); } else { criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE)); } AbstractLogic countryLogic = LogicFactory.getInctance(LogicType.COUNTRYLOGIC); countryLogic.doDeleteEntity(criteria); page = new GoShowCountry().execute(request); } catch (TechnicalException ex) { request.setAttribute("errorDeleteReason", ex.getMessage()); request.setAttribute("errorDelete", "message.errorDeleteData"); request.setSessionAttribute(JSP_PAGE, page); } return page; }
fe13b83c-5831-4fe0-872a-6666de45eb85
1
public void dumpInstruction(TabbedPrintWriter writer) throws java.io.IOException { writer.println("break" + (label == null ? "" : " " + label) + ";"); }
aac4e9e3-77d2-4b50-9af3-17a1f428e0ce
3
public void visitFiles(ArrayList<String> fileNames) { // Treat all other command line arguments as files to be read and evaluated FileReader freader; for (String file : fileNames) { try { System.out.println("Reading from: " + file + "..."); freader = new FileReader(new File(file)); parseVisitShow(interp, freader); System.out.println("Done! Press ENTER to continue"); System.in.read(); } catch (FileNotFoundException fnfe) { System.err.println(fnfe.getMessage()); System.err.println("Skipping it"); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } }
09f47b2d-bcf3-4ee2-be69-37232e567961
1
public void testConstructorEx_Type_int_Chrono() throws Throwable { try { new Partial(null, 4, ISO_UTC); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } }
3a21bbf5-39f7-412c-9d67-9dff08038c00
8
public void run(){ try { //System.out.println("Dwonload Incomming Connection from IP: " + clientsocket.getInetAddress().getHostAddress()+ " PORT: "+clientsocket.getPort()); ObjectInputStream in = new ObjectInputStream(clientsocket.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(clientsocket.getOutputStream()); while (true) { Object b=in.readObject(); String clientMessage = (String)b; System.out.println("Download Server: Input from Client"); System.out.println(clientMessage); if(clientMessage.startsWith("GET")){ String filename=clientMessage.substring(clientMessage.indexOf("/", 9+1)+1, clientMessage.indexOf("HTTP/1.1")-2); //System.out.println("File is :"+filename+":"); String fullpath=client.sharedDirectory + "\\"+filename; //System.out.println("Full path:"+fullpath+":"); File file=new File(fullpath); if(file.exists()&&file.isFile()){ String outToClient=""+"HTTP/1.1 200 OK\r\nServer: Simpella0.6\r\nContent-type: application/binary\r\nContent-length: "+file.length()+"\r\n\r\n"; out.writeObject(outToClient); System.out.println("Download Server: Begin Download"); BufferedInputStream inpFromFile=new BufferedInputStream(new FileInputStream(file),1024); BufferedOutputStream outToSock=new BufferedOutputStream(clientsocket.getOutputStream(),1024); byte[] data = new byte[1024]; while(inpFromFile.read(data,0,1024)>-1) { outToSock.write(data, 0, data.length); } System.out.println("Download SERVER= Transfer Complete"); inpFromFile.close(); outToSock.flush(); outToSock.close(); break; } else{ out.writeObject(new String("HTTP/1.1 503 File not found.\r\n\r\n")); System.out.println("Rejected Connection: File not found"); break; } } } }catch (EOFException e){ System.out.println("Disconnected to IP: " + clientsocket.getInetAddress().getHostAddress()+ " PORT: "+clientsocket.getPort()); //this.stop(); } catch (IOException e) { System.out.println("Disconnected to IP: " + clientsocket.getInetAddress().getHostAddress()+ " PORT: "+clientsocket.getPort()); //this.stop(); } catch (Exception e) { System.out.println("Disconnected to IP: " + clientsocket.getInetAddress().getHostAddress()+ " PORT: "+clientsocket.getPort()); //this.stop(); } }
be591729-4b2b-4544-80e7-6d7d1a386070
3
private boolean isOk() { lblError.setVisible(false); boolean res = false; boolean checkDates = Validate.startdateBeforeReleasedate(calStartDate.getDate(), calReleaseDate.getDate()); if (checkDates) { res = true; } else { if (calStartDate.getDate() != null && calReleaseDate.getDate() != null) { lblError.setText("Sätt ett releasedatum som är senare i tid än startdatumet."); lblError.setVisible(true); } else { lblError.setText("Var god välj ett datum för både start och releasedatum"); lblError.setVisible(true); } } return res; }
c2340f21-dec3-4d92-b4d7-b1e7a7250c25
5
public static Map<String,String> getPluginFileMap() { Map<String,String> pluginList = new HashMap<String,String>(); try { File jarLocation = new File(ControllerEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); String parentDirName = jarLocation.getParent(); // to get the parent dir name File folder = new File(parentDirName + "/plugins"); if(folder.exists()) { File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { //System.out.println("Found Plugin: " + listOfFiles[i].getName()); //<pluginName>=<pluginVersion>, String pluginPath = listOfFiles[i].getAbsolutePath(); //pluginList.add(ControllerEngine.commandExec.getPluginName(pluginPath) + "=" + ControllerEngine.commandExec.getPluginVersion(pluginPath)); String pluginKey = ControllerEngine.commandExec.getPluginName(pluginPath) + "=" + ControllerEngine.commandExec.getPluginVersion(pluginPath); String pluginValue = listOfFiles[i].getName(); pluginList.put(pluginKey, pluginValue); //pluginList = pluginList + getPluginName(pluginPath) + "=" + getPluginVersion(pluginPath) + ","; //pluginList = pluginList + listOfFiles[i].getName() + ","; } } if(pluginList.size() > 0) { return pluginList; } } } catch(Exception ex) { System.out.println(ex.toString()); } return null; }
31d01c66-cbe4-4a75-b488-0f7ea98f8f36
2
public void score(Paddle paddle, Player player) { if (collision(paddle)) { paddle.catchPowerUp(type); player.catchPowerUp(type); switch (type) { case 0: toCenter(); break; default: isExpired = true; break; } } }
97ba3659-a6da-4699-b9da-7fa61376e52e
8
public static void main(String[] args) { GameMachine gameMachine = new GameMachine(); ArrayList<MainMenuHeroSlot> heroies = new ArrayList<MainMenuHeroSlot>(); //System.out.println(gameMachine); Scanner scanchoice = new Scanner(System.in); int choiceentry = 0; do { //Print out menu System.out.println("Please press: " + "\n1). Display the hint of what you need to do at the given moment" + "\n2). Choose characters that you would like to play with" + "\n3). Choose the characters skills" + "\n4). Play the game!" + "\n5). Exit the program."); //For Testing purposes //System.out.println(gameMachine); //try taking the input try{ choiceentry = Integer.parseInt(scanchoice.nextLine()); }catch(Exception e){ System.out.println("Please enter a valid menu choice."); } //do something if it's a valid input switch (choiceentry) { case 1: gameMachine.clickTutorial(); break; case 2: gameMachine.clickChooseCharacters(scanchoice, heroies); break; case 3: gameMachine.clickChooseCharacterSkills(scanchoice, heroies); break; case 4: gameMachine.clickPlayGame(heroies); break; case 99: //for testing of the arraylist of heroes for(int p = 0; p< heroies.size(); p++) { MainMenuHeroSlot temp = (MainMenuHeroSlot) heroies.get(p); System.out.println(temp.getcharacter().toString()); } break; } } while (choiceentry != 5); //Closing Scanner scanchoice.close(); }
f7bcadb5-16e0-4bc4-9951-66201e7f51ab
9
public String wraplineword (int columns) { int n=N,good=N; String s=""; while (n<L) { if (C[n]=='\n') { s=new String(C,N,n-N); N=n+1; break; } n++; if (n>=L) { if (n>N) s=new String(C,N,n-N); N=n; break; } if (n-N>=columns && good>N) { s=new String(C,N,good-N); N=good+1; if (N<L && C[N]!='\n') s=s+"\\"; break; } } if (N>=L) Error=true; return s; }
a42cae25-fd50-4e16-9cfb-9ad30cc301a3
3
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed String tempPath = txtPath.getText(); if(tempPath.isEmpty()){ JOptionPane.showMessageDialog(this, "You have to select a XML File first", "Missing Value",JOptionPane.WARNING_MESSAGE); return; } File tempFile = new File(tempPath); if(!tempFile.exists() || tempFile.isDirectory()){ JOptionPane.showMessageDialog(this, "The current selected path is invalid.", "Invalid Path", JOptionPane.ERROR_MESSAGE); return; } parseXMLFile(tempFile); }//GEN-LAST:event_btnLoadActionPerformed
c5d203e6-ac07-4779-81ef-f43d4a6bea7e
9
private Map.Entry<Integer, Integer> traverseTree(String curIDRef, ArrayList<String> pathFromRoot) throws IDrefNotInSentenceException { String parentIdRef = ""; Node curNode = getNode(curIDRef); if (curNode.getHeadIDref() == null && !curNode.isHeadChecked()) { Node newHead = calculateHeadWord(Arrays.asList(curIDRef)); if (newHead != null) curNode.setHeadIDref(newHead.getId()); } if (pathFromRoot.size() > 0) parentIdRef = pathFromRoot.get(pathFromRoot.size() - 1); curNode.addPathFromRoot(pathFromRoot); if (pathFromRoot.size() > 0) curNode.addParentIDref(parentIdRef); Map.Entry<Integer, Integer> lastFirstIDref; if (curNode.isTerminal()) { //pathFromRoot.add(curIDRef); lastFirstIDref = new AbstractMap.SimpleEntry<Integer, Integer>(Helper.getPosFromID(curIDRef), Helper.getPosFromID(curIDRef)); } else { int firstPos = Integer.MAX_VALUE; int lastPos = 0; pathFromRoot.add(curIDRef); for (String childIdRef : curNode.getEdges().keySet()) { lastFirstIDref = traverseTree(childIdRef, (ArrayList<String>) pathFromRoot.clone()); if (lastFirstIDref.getKey() < firstPos) firstPos = lastFirstIDref.getKey(); if (lastFirstIDref.getValue() > lastPos) lastPos = lastFirstIDref.getValue(); } curNode.setFirstWordPos(firstPos); curNode.setLastWordPos(lastPos); lastFirstIDref = new AbstractMap.SimpleEntry<Integer, Integer>(firstPos, lastPos); } return lastFirstIDref; }
b643114e-3763-4cd5-a7aa-b939eeabae0e
6
public static void startupHtmlPprint() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/ONTOSAURUS", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { OntosaurusUtil.SGT_STELLA_GENERALIZED_SYMBOL = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("GENERALIZED-SYMBOL", Stella.getStellaModule("/STELLA", true), 1))); OntosaurusUtil.SYM_ONTOSAURUS_STARTUP_HTML_PPRINT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-HTML-PPRINT", null, 0))); } if (Stella.currentStartupTimePhaseP(4)) { OntosaurusUtil.$ONTOSAURUS_URL_ACTION$.setDefaultValue("show"); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("PPRINT-ATOMIC-OBJECT-FOR-HTML-DEFINITION", "(DEFUN PPRINT-ATOMIC-OBJECT-FOR-HTML-DEFINITION ((SELF OBJECT) (STREAM NATIVE-OUTPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "pprintAtomicObjectForHtmlDefinition", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("PPRINT-ATOMIC-OBJECT-FOR-HTML", "(DEFUN PPRINT-ATOMIC-OBJECT-FOR-HTML ((SELF OBJECT) (STREAM NATIVE-OUTPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "pprintAtomicObjectForHtml", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("PPRINT-LITERAL-WRAPPER-FOR-HTML", "(DEFUN PPRINT-LITERAL-WRAPPER-FOR-HTML ((SELF LITERAL-WRAPPER) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "pprintLiteralWrapperForHtml", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.LiteralWrapper"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("LOGIC-OBJECT-DISPLAY-TYPE", "(DEFUN (LOGIC-OBJECT-DISPLAY-TYPE STRING) ((OBJ LOGIC-OBJECT)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "logicObjectDisplayType", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.LogicObject")}), null); Stella.defineFunctionObject("PRINT-ONTOSAURUS-URL", "(DEFUN PRINT-ONTOSAURUS-URL ((THE-OBJECT LOGIC-OBJECT) (NATIVESTREAM NATIVE-OUTPUT-STREAM)) :PUBLIC? TRUE :DOCUMENTATION \"Prints a URL following PowerLoom Ontosaurus conventions.\")", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "printOntosaurusUrl", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.LogicObject"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("STARTUP-HTML-PPRINT", "(DEFUN STARTUP-HTML-PPRINT () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.ontosaurus._StartupHtmlPprint", "startupHtmlPprint", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(OntosaurusUtil.SYM_ONTOSAURUS_STARTUP_HTML_PPRINT); KeyValueList.setDynamicSlotValue(function.dynamicSlots, OntosaurusUtil.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupHtmlPprint"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("ONTOSAURUS"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *ONTOSAURUS-URL-ACTION* STRING \"show\" :DOCUMENTATION \"The action parameter for URL printing\" :PUBLIC? TRUE)"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
872718c8-4e30-4cb7-a2da-01cc75e30ae7
4
private boolean onCloseButton(int x, int y) { int xStart = getWidth() / 3; int xEnd = xStart + width(); int yStart = getWidth() / 3; int yEnd = yStart + SLOT_SIZE / 2; if (x > xStart && x < xEnd && y > yStart && y < yEnd) { return true; } return false; }
5f4806d9-dfff-4568-b019-1746c05a8c26
3
public String inCar(String carID) { String txt=""; if(isFull()) { txt="对不起,停车场已满。"; return txt; } if(carID.equals("")){ txt="请输入你停的车的车牌号:"; return txt; } if(contain(new Ticket(carID))) { txt="你要停的车已经停在我们的停车场里了。"; return txt; } Ticket ticket = in(new Car(carID)); txt = "OK,请记住你的取车票据号[" + ticket.getCode() + "],"; return txt; }
1a817150-339b-4b8e-8017-3dbf67b70d08
3
public void selectionSort() { int maxCompare = a.length - 1; int smallestIndex = 0; int numSteps = 0; // loop from 0 to one before last item for (int i = 0; i < maxCompare; i++) { // set smallest index to the one at i smallestIndex = i; numSteps = 0; // loop from i+1 to end of the array for (int j = i + 1; j < a.length; j++) { numSteps++; if (a[j] < a[smallestIndex]) { smallestIndex = j; } } System.out.println("#steps:"+numSteps); // swap the one at i with the one at smallest index swap(i,smallestIndex); this.printArray("after loop body when i = " + i); } }
6382d6d2-6e93-4b84-a684-f4fd122d009c
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(MedicineUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MedicineUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MedicineUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MedicineUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MedicineUpdate dialog = new MedicineUpdate(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
9e4d43e4-427d-4d35-8e67-85aa51f69a63
9
@Override public void task(int tId) { try { int nRow, nCol; int[][] mat; int[] vec; int[] product; File file; BufferedReader reader; PrintWriter printWriter; String line; String[] elements; //read the shared matrix file file = new File("fs/example/matrix.txt"); reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); //the first line is dimension elements = line.split(" "); nRow = Integer.parseInt(elements[0]); nCol = Integer.parseInt(elements[1]); mat = new int[nRow][nCol]; for(int i=0; i<nRow; i++) { line = reader.readLine(); elements = line.split(" "); for(int j=0; j<nCol; j++) { mat[i][j] = Integer.parseInt(elements[j]); } } reader.close(); //read specific vector file based on task ID file = new File("fs/example/vector"+tId+".txt"); reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); elements = line.split(" "); if(Integer.parseInt(elements[0]) != nCol || Integer.parseInt(elements[1]) != 1) throw new Exception("dimension error"); vec = new int[nCol]; for(int i=0; i<nCol; i++) { line = reader.readLine(); vec[i] = Integer.parseInt(line); } reader.close(); //calculate the produc product = new int[nRow]; for(int i=0; i<nRow; i++) { product[i] = 0; for(int j=0; j<nCol; j++) { product[i] += mat[i][j] * vec[j]; } } //write output file file = new File("fs/example/out"+tId+".txt"); printWriter = new PrintWriter(file); printWriter.println(nRow+" 1"); for(int i=0; i<nRow; i++) { printWriter.println(product[i]); } printWriter.close(); } catch(Exception e) { e.printStackTrace(); } }
a283f63b-6fab-43df-9096-d6f09df8328c
1
public static boolean addNewPatient(NewPatientPage newPatient){ Date dob = HelperMethods.getDate(newPatient.getDob()); Patient newPat = new Patient(); newPat.setFirstName(newPatient.getfName().getText()); newPat.setLastName(newPatient.getlName().getText()); newPat.setPhone(newPatient.getPhone().getText()); newPat.setPrimaryDoc(newPatient.getDoctor().getText()); newPat.setAddress(newPatient.getAddress().getText()); newPat.setDob(dob); newPat.setCity(newPatient.getCity().getText()); newPat.setState(newPatient.getState().getText()); newPat.setZip(newPatient.getZip().getText()); newPat.setCoPay(new BigDecimal(9)); if(DatabaseProcess.insert(newPat)){ Gui.setCurrentPatient(newPat); return true; } return false; }
51859c69-9539-441a-82bc-e3329b69f38b
0
private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents dialogPane = new JPanel(); contentPanel = new JPanel(); label1 = new JLabel(); txtInterval = new JTextField(); label2 = new JLabel(); txtTimeout = new JTextField(); label3 = new JLabel(); chkSendResponse = new JCheckBox(); label4 = new JLabel(); txtResponse = new JTextField(); buttonBar = new JPanel(); okButton = new JButton(); //======== this ======== setModal(true); setTitle("Router Application Settings"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== dialogPane ======== { dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12)); dialogPane.setLayout(new BorderLayout()); //======== contentPanel ======== { contentPanel.setLayout(new GridBagLayout()); ((GridBagLayout)contentPanel.getLayout()).columnWidths = new int[] {0, 0, 0}; ((GridBagLayout)contentPanel.getLayout()).rowHeights = new int[] {0, 0, 0, 0, 0, 0}; ((GridBagLayout)contentPanel.getLayout()).columnWeights = new double[] {0.0, 1.0, 1.0E-4}; ((GridBagLayout)contentPanel.getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 1.0, 1.0E-4}; //---- label1 ---- label1.setText("Routing Service Update Interval (secs)"); contentPanel.add(label1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); //---- txtInterval ---- txtInterval.setText("30"); contentPanel.add(txtInterval, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); //---- label2 ---- label2.setText("Routing Service Dead Timeout (secs)"); contentPanel.add(label2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); //---- txtTimeout ---- txtTimeout.setText("90"); contentPanel.add(txtTimeout, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); //---- label3 ---- label3.setText("Send KeepAlive Response"); contentPanel.add(label3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); //---- chkSendResponse ---- chkSendResponse.setText("Send Response"); contentPanel.add(chkSendResponse, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); //---- label4 ---- label4.setText("KeepAlive Response Header"); contentPanel.add(label4, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0)); //---- txtResponse ---- txtResponse.setText("WELCOME"); contentPanel.add(txtResponse, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); } dialogPane.add(contentPanel, BorderLayout.CENTER); //======== buttonBar ======== { buttonBar.setBorder(new EmptyBorder(12, 0, 0, 0)); buttonBar.setLayout(new GridBagLayout()); ((GridBagLayout)buttonBar.getLayout()).columnWidths = new int[] {80}; //---- okButton ---- okButton.setText("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { okButtonActionPerformed(e); } }); buttonBar.add(okButton, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } dialogPane.add(buttonBar, BorderLayout.SOUTH); } contentPane.add(dialogPane, BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); // JFormDesigner - End of component initialization //GEN-END:initComponents }
af46f88e-8418-441c-b2e1-2e7eff15c973
9
public static void main(String [] args) throws Throwable { if (args.length < 2) { usage(); return; } Class stemClass = Class.forName("org.tartarus.snowball.ext." + args[0] + "Stemmer"); SnowballStemmer stemmer = (SnowballStemmer) stemClass.newInstance(); Reader reader; reader = new InputStreamReader(new FileInputStream(args[1])); reader = new BufferedReader(reader); StringBuffer input = new StringBuffer(); OutputStream outstream; if (args.length > 2) { if (args.length >= 4 && args[2].equals("-o")) { outstream = new FileOutputStream(args[3]); } else { usage(); return; } } else { outstream = System.out; } Writer output = new OutputStreamWriter(outstream); output = new BufferedWriter(output); int repeat = 1; if (args.length > 4) { repeat = Integer.parseInt(args[4]); } Object [] emptyArgs = new Object[0]; int character; while ((character = reader.read()) != -1) { char ch = (char) character; if (Character.isWhitespace((char) ch)) { if (input.length() > 0) { stemmer.setCurrent(input.toString()); for (int i = repeat; i != 0; i--) { stemmer.stem(); } output.write(stemmer.getCurrent()); output.write('\n'); input.delete(0, input.length()); } } else { input.append(Character.toLowerCase(ch)); } } output.flush(); }
c4df2224-419c-43a7-863e-ab4dc93ec67b
2
public void run() { if (validArgs) { runCrawler(); } else { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
de33b601-b808-4894-ab4a-451b9860b657
7
public String[] readFromAdjacencyMatrix(String file){ ArrayList<Node> nodes = new ArrayList<Node>(); try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; String[] parts; line = in.readLine(); parts = line.split(" "); String p; String[] res = new String[parts.length]; for(int i=0;i<res.length;i++) { res[i] = ""; } int s =0; int d; for(int i=0;i<parts.length; i++) { p = parts[i]; d = Integer.parseInt(p); if(d == 1) { res[s] += i + " "; } } while((line = in.readLine())!= null) { s++; parts = line.split(" "); for(int i=0;i<parts.length; i++) { p = parts[i]; d = Integer.parseInt(p); if(d == 1) { res[s] += i + " "; } } } in.close(); return res; } catch (Exception ex) { Logger.getLogger(NetworkGenerator.class.getName()).log(Level.SEVERE, null, ex); } return null; }
dd5f45b8-03c8-4785-83c1-7307787d7f91
1
public synchronized static GameSocketServer getServerSingleton() { if (instance == null) { instance = new GameSocketServer(); } return instance; }
2db3e29c-5833-4be5-b6d6-0c8e48be9b24
9
private static int getId(String functionName) { if (functionName.equals(NAME_REGEXP_STRING_MATCH)) return ID_REGEXP_STRING_MATCH; else if (functionName.equals(NAME_X500NAME_MATCH)) return ID_X500NAME_MATCH; else if (functionName.equals(NAME_RFC822NAME_MATCH)) return ID_RFC822NAME_MATCH; else if (functionName.equals(NAME_STRING_REGEXP_MATCH)) return ID_STRING_REGEXP_MATCH; else if (functionName.equals(NAME_ANYURI_REGEXP_MATCH)) return ID_ANYURI_REGEXP_MATCH; else if (functionName.equals(NAME_IPADDRESS_REGEXP_MATCH)) return ID_IPADDRESS_REGEXP_MATCH; else if (functionName.equals(NAME_DNSNAME_REGEXP_MATCH)) return ID_DNSNAME_REGEXP_MATCH; else if (functionName.equals(NAME_RFC822NAME_REGEXP_MATCH)) return ID_RFC822NAME_REGEXP_MATCH; else if (functionName.equals(NAME_X500NAME_REGEXP_MATCH)) return ID_X500NAME_REGEXP_MATCH; throw new IllegalArgumentException("unknown match function: " + functionName); }
0db824a8-8a51-42d9-a513-f762b6ce8f5f
7
public int[][] generateMatrix(int n) { // Start typing your Java solution below // DO NOT write main() function int[][] res = new int[n][]; int i = 0, j = 0; for (i = 0; i < n; i++) res[i] = new int[n]; int round = (n + 1) / 2; int k = 1; for (i = 0; i < round; i++) { // FULL for (j = i; j <= n - i - 1; j++) { res[i][j] = k++; } // PART for (j = i + 1; j < n - i - 1; j++) { res[j][n - i - 1] = k++; } if (n - i - 1 > i) { // FULL for (j = n - i - 1; j >= i; j--) { res[n - i - 1][j] = k++; } // PART for (j = n - i - 2; j > i; j--) { res[j][i] = k++; } } } return res; }
6830fd2e-57d9-4a10-bc86-a33fa821c6a5
4
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = 1; int max = 1; String input = sc.nextLine(); String[] strArr = input.split(" "); String largest = strArr[0]; for (int i = 1; i < strArr.length; i++) { if (strArr[i].equals(strArr[i - 1])) { count++; if (count > max) { max = count; largest = strArr[i]; } } else { count = 1; } } for (int i = 0; i < max; i++) { System.out.print(largest + " "); } }
ec423c9d-5da5-4369-a72d-49a0c53e7978
2
public void compose(Position singleNodePos){ singleNodePosition = singleNodePos; JPanel cp = new JPanel(); cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS)); cp.setBorder(BorderFactory.createEmptyBorder(3,3,3,3)); JPanel dist = new JPanel(); dist.setBorder(BorderFactory.createTitledBorder("Node Distribution")); dist.setLayout(new BoxLayout(dist, BoxLayout.Y_AXIS)); if(singleNodePos == null) { cp.add(dist); } JPanel distSel = new JPanel(); distSel.setBorder(BorderFactory.createEmptyBorder(0,3,3,3)); distSel.setLayout(new NonRegularGridLayout(2, 3, 5, 2)); // Number of nodes // ---------------------------- UnborderedJTextField numSelLabel = new UnborderedJTextField("Number of Nodes:", Font.BOLD); distSel.add(numSelLabel); distSel.add(number); JTextField dummy = new JTextField(); dummy.setVisible(false); distSel.add(dummy); // the available distrubutions // ---------------------------- UnborderedJTextField distSelLabel = new UnborderedJTextField("Distribution Model:", Font.BOLD); distSel.add(distSelLabel); fillChoice(distributionModelComboBox, "models/distributionModels", distributionSel); distSel.add(distributionModelComboBox); distributionParam.setText(distributionParamDefString); distSel.add(distributionParam); dist.add(distSel); JPanel propertyPanel = new JPanel(); propertyPanel.setBorder(BorderFactory.createTitledBorder("Node Properties")); propertyPanel.setLayout(new BoxLayout(propertyPanel, BoxLayout.Y_AXIS)); cp.add(propertyPanel); JPanel props = new JPanel(); props.setBorder(BorderFactory.createEmptyBorder(0,3,3,3)); props.setLayout(new NonRegularGridLayout(5,3, 5, 2)); propertyPanel.add(props); // the available node implementations // ---------------------------- UnborderedJTextField propSelLabel = new UnborderedJTextField("Node Implementation:", Font.BOLD); props.add(propSelLabel); fillChoice(nodeTypeComboBox, "nodes/nodeImplementations", nodeTypeSel); props.add(nodeTypeComboBox); nodeTypeParam.setEditable(false); nodeTypeParam.setVisible(false); props.add(nodeTypeParam); //the available connectivities // ---------------------------- UnborderedJTextField connSelLabel = new UnborderedJTextField("Connectivity Model:", Font.BOLD); props.add(connSelLabel); fillChoice(connectivityModelComboBox, "models/connectivityModels", connectivitySel); props.add(connectivityModelComboBox); connectivityParam.setText(connectivityDefString); props.add(connectivityParam); //the available interferences // ---------------------------- UnborderedJTextField interSelLabel = new UnborderedJTextField("Interference Model:", Font.BOLD); props.add(interSelLabel); fillChoice(interferenceModelComboBox, "models/interferenceModels", interferenceSel); props.add(interferenceModelComboBox); interferenceParam.setText(interferenceDefString); props.add(interferenceParam); //the available mobility // ---------------------------- UnborderedJTextField mobSelLabel = new UnborderedJTextField("Mobility Model:", Font.BOLD); props.add(mobSelLabel); fillChoice(mobilityModelComboBox, "models/mobilityModels", mobilitySel); props.add(mobilityModelComboBox); mobilityParam.setText(mobilityDefString); props.add(mobilityParam); //the available reliability models // ---------------------------- UnborderedJTextField reliSelLabel = new UnborderedJTextField("Reliability Model:", Font.BOLD); props.add(reliSelLabel); fillChoice(reliabilityModelComboBox, "models/reliabilityModels", reliabilitySel); props.add(reliabilityModelComboBox); reliabilityParam.setText(reliabilityDefString); props.add(reliabilityParam); // add a button to change whether all implementations are contained in the drop down fields JPanel allModelsPanel = new JPanel(); allModelsPanel.setLayout(new BorderLayout()); allModelsCheckBox = new JCheckBox("Show all implementations"); allModelsCheckBox.setSelected(Configuration.showModelsOfAllProjects); allModelsCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if(Configuration.showModelsOfAllProjects != allModelsCheckBox.isSelected()) { Configuration.showModelsOfAllProjects = allModelsCheckBox.isSelected(); // reload the contents of the drop down fields fillChoice(distributionModelComboBox, "models/distributionModels", distributionSel); fillChoice(nodeTypeComboBox, "nodes/nodeImplementations", nodeTypeSel); fillChoice(connectivityModelComboBox, "models/connectivityModels", connectivitySel); fillChoice(interferenceModelComboBox, "models/interferenceModels", interferenceSel); fillChoice(mobilityModelComboBox, "models/mobilityModels", mobilitySel); fillChoice(reliabilityModelComboBox, "models/reliabilityModels", reliabilitySel); GenerateNodesDialog.this.pack(); } } }); allModelsPanel.add(allModelsCheckBox); cp.add(allModelsPanel); // the buttons OK / CANCEL JPanel buttons = new JPanel(); ok.setMnemonic(java.awt.event.KeyEvent.VK_O); buttons.add(ok); cancel.setMnemonic(java.awt.event.KeyEvent.VK_C); buttons.add(cancel); cp.add(buttons); this.setContentPane(cp); //this.setResizable(false); this.getRootPane().setDefaultButton(ok); this.pack(); this.setLocationRelativeTo(parent); number.grabFocus(); this.setVisible(true); }
6243faf8-74cf-4126-bd5c-742a74f0298d
7
public boolean check(String attempt, String wordtype, boolean testtype){ if (testtype){ if (!wordtype.equals(type)){ return false; } } if (attempt != null){ if (attempt == "") { return false; } if (attempt.equals(romaji) || attempt.equals(kana) || attempt.equals(kanji)){ return true; }else{ return false; } }else{ return false; } }
f5a86a50-44ad-49ec-81a3-e038eacd993e
1
public static boolean isMagic(byte[] peerid) throws java.security.NoSuchAlgorithmException { if (peerid==null) return false; MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(peerid); byte[] digest = md.digest(); int magic = (digest[digest.length-2] << Byte.SIZE) | digest[digest.length-1]; return (magic & 0xFFFF) != 0; }
fbe2fda1-88fb-49cf-b0af-7b563fec325c
0
@Basic @Column(name = "CTR_MOA_CONSEC") public int getCtrMoaConsec() { return ctrMoaConsec; }
9840951c-5137-4bfb-916e-ca2f816b1254
4
private void retry(String query) { Boolean passed = false; while (!passed) { try { Connection connection = getConnection(); Statement statement = connection.createStatement(); statement.executeQuery(query); passed = true; return; } catch (SQLException ex) { if (ex.getMessage().toLowerCase().contains("locking") || ex.getMessage().toLowerCase().contains("locked") ) { passed = false; }else{ core.writeError("Error at SQL Query: " + ex.getMessage(), false); } } } return; }
4b292d88-d45a-4e16-b74b-2e40fbb424fd
9
public void runGameTimedSpeedOptimised(Controller<MOVE> pacManController,Controller<EnumMap<GHOST,MOVE>> ghostController,boolean fixedTime,boolean visual) { Game game=new Game(0); GameView gv=null; if(visual) gv=new GameView(game).showGame(); if(pacManController instanceof HumanController) gv.getFrame().addKeyListener(((HumanController)pacManController).getKeyboardInput()); new Thread(pacManController).start(); new Thread(ghostController).start(); while(!game.gameOver()) { pacManController.update(game.copy(),System.currentTimeMillis()+DELAY); ghostController.update(game.copy(),System.currentTimeMillis()+DELAY); try { int waited=DELAY/INTERVAL_WAIT; for(int j=0;j<DELAY/INTERVAL_WAIT;j++) { Thread.sleep(INTERVAL_WAIT); if(pacManController.hasComputed() && ghostController.hasComputed()) { waited=j; break; } } if(fixedTime) Thread.sleep(((DELAY/INTERVAL_WAIT)-waited)*INTERVAL_WAIT); game.advanceGame(pacManController.getMove(),ghostController.getMove()); } catch(InterruptedException e) { e.printStackTrace(); } if(visual) gv.repaint(); } pacManController.terminate(); ghostController.terminate(); }
7c6dbb4c-073b-429c-8743-b5397700741a
6
private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed int opc = -1; int row = -1; if (row == -1) { row = jTable16.getSelectedRow(); opc = 1; } if (row == -1) { row = jTable17.getSelectedRow(); opc = 2; } System.out.println("" + row); if (opc == 1) { try { AvVenda av = (AvVenda) avaliacoes_vendas.get(row); String cpf = av.getCpf_cliente(); c = new Cliente(); c.buscarCliente(cpf); av.setNome_cliente(c.getNome()); new UIVisAvVenda(c, av).setVisible(true); } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(UIFMenu.class.getName()).log(Level.SEVERE, null, ex); } } else if (opc == 2) { try { AvAtendimento av = (AvAtendimento) avaliacoes_atendimentos.get(row); String cpf = av.getCpf_cliente(); c = new Cliente(); c.buscarCliente(cpf); c.buscarCliente(av.getCpf_cliente()); av.setNome_cliente(c.getNome()); new UIVisAvAtendimento(c, av).setVisible(true); } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(UIFMenu.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButton21ActionPerformed
03f7dcff-c3b4-427a-b1f1-e405244135a1
5
private boolean logoutCommand(CommandSender sender, String[] args) { if (!xPermissions.has(sender, "xauth.admin.logout")) { plugin.getMsgHndlr().sendMessage("admin.permission", sender); return true; } else if (args.length < 2) { plugin.getMsgHndlr().sendMessage("admin.logout.usage", sender); return true; } String targetName = args[1]; xAuthPlayer xp = plugin.getPlyrMngr().getPlayer(targetName); if (!xp.isAuthenticated()) { plugin.getMsgHndlr().sendMessage("admin.logout.error.logged", sender, targetName); return true; } boolean success = plugin.getPlyrMngr().deleteSession(xp.getAccountId()); if (success) { xp.setStatus(Status.Registered); plugin.getAuthClass(xp).offline(xp.getPlayerName()); plugin.getMsgHndlr().sendMessage("admin.logout.success.player", sender, targetName); Player target = xp.getPlayer(); if (target != null) { plugin.getPlyrMngr().protect(xp); plugin.getMsgHndlr().sendMessage("admin.logout.success.target", target); } } else plugin.getMsgHndlr().sendMessage("admin.logout.error.general", sender); return true; }
29654f08-a1ee-4c3f-97b5-ec5f19b3bad1
2
@Override public ServerModel buildRoad(BuildRoadRequest request, CookieParams cookie) throws InvalidMovesRequest { if(request == null) { throw new InvalidMovesRequest("Error: invalid build city request"); } ServerModel serverGameModel = serverModels.get(cookie.getGameID()); //execute int playerIndex = request.getPlayerIndex(); Player player = serverGameModel.getPlayers().get(playerIndex); int x = request.getRoadLocation().getX(); int y = request.getRoadLocation().getY(); String direction = request.getRoadLocation().getDirectionStr(); Road road = new Road(playerIndex, x, y , direction); serverGameModel.getMap().getRoads().add(road); serverGameModel.incrementVersion(); player.decrementRoads(); if (!request.isFree()) { player.decrementBrick(); player.decrementWood(); serverGameModel.getBank().brick += 1; serverGameModel.getBank().wood += 1; } checkForLongestRoad(serverGameModel, playerIndex); return serverGameModel; }
bb9683c5-8451-4801-b4a2-6faa116da03b
8
private BitSet selectTBonds(String str) { int n = model.tBonds.size(); if (n == 0) return null; BitSet bs = new BitSet(n); if ("selected".equalsIgnoreCase(str)) { synchronized (model.tBonds) { for (int i = 0; i < n; i++) { if (model.getTBond(i).isSelected()) bs.set(i); } } return bs; } String strLC = str.toLowerCase(); if (strLC.indexOf("involve") != -1) { str = str.substring(7).trim(); strLC = str.toLowerCase(); if (strLC.indexOf("atom") != -1) { str = str.substring(4).trim(); if (selectTbondsInvolving(str, bs)) { model.setTBondSelectionSet(bs); return bs; } } else { out(ScriptEvent.FAILED, "Unrecognized expression: " + str); return null; } } if (selectFromCollection(str, n, bs)) { model.setTBondSelectionSet(bs); return bs; } out(ScriptEvent.FAILED, "Unrecognized expression: " + str); return null; }
7f220bb2-7f53-46ed-b644-bc997b56bd64
5
public void deplacerUnite(Matrice matrice) { Chemin chemin = matrice.getChemin();; Deplacement[] deplacement = matrice.getChemin().getTabDeplacements(); switch (deplacement[chemin.getIndiceDeplacement()]) { case BAS: Coordonnees pos_bas = new Coordonnees(this.getPos().getX(), this.getPos().getY() + 1); this.setPos(pos_bas); break; case HAUT: Coordonnees pos_haut = new Coordonnees(this.getPos().getX(), this.getPos().getY() - 1); this.setPos(pos_haut); break; case DROITE: Coordonnees pos_droite = new Coordonnees(this.getPos().getX() + 1, this.getPos().getY()); this.setPos(pos_droite); break; case GAUCHE: Coordonnees pos_gauche = new Coordonnees(this.getPos().getX() - 1, this.getPos().getY()); this.setPos(pos_gauche); break; case QG: Coordonnees pos_base = new Coordonnees(-1, -1); this.setPos(pos_base); break; } chemin.setIndiceDeplacement(chemin.getIndiceDeplacement() + 1); }
81753c08-7e96-4662-94f4-a0c2687e2971
8
int readCorner4(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 3, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 2, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(2, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(3, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; }
d404dd79-18fb-473f-bddc-f6ad2027c5ca
1
private boolean jj_3_24() { if (jj_3R_41()) return true; return false; }
a891dd28-a86c-4be6-9ad3-b62c7b65ece7
3
public void closePosition(java.lang.String positionID) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[7]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("ClosePosition"); _call.setEncodingStyle(null); _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("", "ClosePosition")); setRequestHeaders(_call); setAttachments(_call); try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {positionID}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } extractAttachments(_call); } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } }
a05daee8-4ed5-4c86-b160-1ce3b291b6ce
8
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String s; for(int i=0;i<N;i++){ s = sc.next(); if(s.length() == 4){ System.out.println("3"); } else{ if((s.trim().contains("u") && s.contains("n")) || (s.contains("u") && s.contains("o")) || (s.contains("o") && s.contains("n"))){ System.out.println("1"); } else{ System.out.println("2"); } } } }
932bffea-c501-450b-ac66-922b111e29c5
7
public String convertHTMLCode2Unicode(String text) { StringBuffer newString = new StringBuffer(); int textLen = text.length(); for (int i = 0; i < textLen; i++) { char charAtI = text.charAt(i); if (i + 2 < textLen && charAtI == '&' && text.charAt(i + 1) == '#' && text.charAt(i + 2) == '7') { int indexOfSemiColon = text.indexOf(';', i); String aHTMLCode = text.substring(i, indexOfSemiColon + 1); aHTMLCode = (String) HTML_CODE_TABLE.get(aHTMLCode); if (aHTMLCode != null) { newString.append(aHTMLCode); i = indexOfSemiColon; } else { newString.append(charAtI); } } else { String returnStr = (String) UNICODE_TABLE.get(new Character(charAtI)); if (returnStr != null) { newString.append(returnStr); } else { newString.append(charAtI); } } } return newString.toString(); }
6dbb8447-eaac-4d39-9892-62aaa1c34822
3
public boolean setHigherReplicaCatalogue(String rcName) { // if a local RC already exists, then exit if (localRC_ == null) { System.out.println(super.get_name() + ".setHigherReplicaCatalogue(): Warning - a local " + "Replica Catalogue entity doesn't exist."); return false; } if (rcName == null || GridSim.getEntityId(rcName) == -1) { return false; } localRC_.setHigherLevelRCid( GridSim.getEntityId(rcName) ); return true; }
f9dd3cd1-c354-47a2-aafe-4b87f2e221b5
7
protected static int makeBody0(CtClass clazz, ClassFile classfile, CtMethod wrappedBody, boolean isStatic, CtClass[] parameters, CtClass returnType, ConstParameter cparam, Bytecode code) throws CannotCompileException { if (!(clazz instanceof CtClassType)) throw new CannotCompileException("bad declaring class" + clazz.getName()); if (!isStatic) code.addAload(0); int stacksize = compileParameterList(code, parameters, (isStatic ? 0 : 1)); int stacksize2; String desc; if (cparam == null) { stacksize2 = 0; desc = ConstParameter.defaultDescriptor(); } else { stacksize2 = cparam.compile(code); desc = cparam.descriptor(); } checkSignature(wrappedBody, desc); String bodyname; try { bodyname = addBodyMethod((CtClassType)clazz, classfile, wrappedBody); /* if an exception is thrown below, the method added above * should be removed. (future work :<) */ } catch (BadBytecode e) { throw new CannotCompileException(e); } if (isStatic) code.addInvokestatic(Bytecode.THIS, bodyname, desc); else code.addInvokespecial(Bytecode.THIS, bodyname, desc); compileReturn(code, returnType); // consumes 2 stack entries if (stacksize < stacksize2 + 2) stacksize = stacksize2 + 2; return stacksize; }
65a5b74a-e015-43ea-8011-8e2f75891eaa
7
private void orderPath(Path path) { if (path.isMarked) return; path.isMarked = true; Segment segment = null; Vertex vertex = null; for (int v = 0; v < path.grownSegments.size() - 1; v++) { segment = (Segment) path.grownSegments.get(v); vertex = segment.end; double thisAngle = ((Double) vertex.cachedCosines.get(path)) .doubleValue(); if (path.isInverted) thisAngle = -thisAngle; for (int i = 0; i < vertex.paths.size(); i++) { Path vPath = (Path) vertex.paths.get(i); if (!vPath.isMarked) { double otherAngle = ((Double) vertex.cachedCosines .get(vPath)).doubleValue(); if (vPath.isInverted) otherAngle = -otherAngle; if (otherAngle < thisAngle) orderPath(vPath); } } } orderedPaths.add(path); }
c8819c91-8bb4-4732-a20c-ee44f9dd62b7
7
private static String getClassNumByInt(int i) { switch (i) { case 1: return "G06Q10/00"; case 2: return "G06Q20/00"; case 3: return "G06Q30/00"; case 4: return "G06Q40/00"; case 5: return "G06Q50/00"; case 6: return "G06Q90/00"; case 7: return "G06Q99/00"; } return ""; }
9508cc2d-4da5-4a5a-a7bc-7c7c8f078bf9
1
public void printInventory(){ for(Block i : inv){ System.out.print(i.type + " "); } System.out.println(); }
8d937450-1ab5-407d-b35b-0efabc04bea6
2
public BigDecimal getStudentExpenses(Student s) { BigDecimal amount = new BigDecimal(0.0); // 1º Get activities prize Set<Activity> activities = s.getActivities(); for (Activity a : activities) { amount = amount.add(a.getPrize()); } // 2º Get bookings prize Set<Booking> bookings = s.getBookings(); for (Booking b : bookings) { amount = amount.add(b.getDiningHall().getPrice()); } return amount; }
ea439e61-ef42-4ae8-9af7-a36d163098b2
6
private MoveAndCost findBestMoveInternal(int[][] board, int allowedCallCnt) { allowedCallCnt--; //this call int n = board.length; int m = board[0].length; double minCost = Double.POSITIVE_INFINITY; int[][] bestBoard = null; Move bestMove = null; int[][][] newBoards = getNewBoards(board); int needCalls = getNeedCallsForNextDepth(newBoards); if(needCalls == 0) { return new MoveAndCost(null, evaluator.getFailCost()); } int nextLevelCalls = allowedCallCnt / needCalls; //todo proper rounding? for (int dir = 0; dir < 4; dir++) { int[][] newBoard = newBoards[dir]; if(newBoard == null) { continue; } double cost = 0; if (nextLevelCalls == 0) { cost = evaluator.evaluate(newBoard); } else { cost = getCost(n, m, nextLevelCalls, newBoard, cost); } if (cost < minCost) { minCost = cost; bestMove = Move.ALL[dir]; bestBoard = newBoard; } } if (allowedCallCnt+1 == maxCallCnt) { copyBoard(board, bestBoard); } return new MoveAndCost(bestMove, minCost); }
4057e60e-a444-4a73-a646-fe503559e047
9
public Photos getNotInSet(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, JinxConstants.PrivacyFilter privacyFilter, JinxConstants.MediaType mediaType, EnumSet<JinxConstants.PhotoExtras> extras, int perPage, int page) throws JinxException { Map<String, String> params = new TreeMap<String, String>(); params.put("method", "flickr.photos.getNotInSet"); if (minUploadDate != null) { params.put("min_upload_date", JinxUtils.formatDateAsUnixTimestamp(minUploadDate)); } if (maxUploadDate != null) { params.put("max_upload_date", JinxUtils.formatDateAsUnixTimestamp(maxUploadDate)); } if (minTakenDate != null) { params.put("min_taken_date", JinxUtils.formatDateAsUnixTimestamp(minTakenDate)); } if (maxTakenDate != null) { params.put("max_taken_date", JinxUtils.formatDateAsUnixTimestamp(maxTakenDate)); } if (privacyFilter != null) { params.put("privacy_filter", Integer.toString(JinxUtils.privacyFilterToFlickrPrivacyFilterId(privacyFilter))); } if (mediaType != null) { params.put("media", mediaType.toString()); } if (!JinxUtils.isNullOrEmpty(extras)) { params.put("extras", JinxUtils.buildCommaDelimitedList(extras)); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } if (page > 0) { params.put("page", Integer.toString(page)); } return jinx.flickrGet(params, Photos.class); }
c12f9333-fc7a-4591-870e-e2a8d3de12f7
7
public void addMaps(int noToAdd) { for (int i = 0; i < noToAdd; i++) { Map newMap = myGen.generateMap(0); sampleMaps.add(newMap); } int noMaps = sampleMaps.size(); for (int x = 0; x < mapWidth; x++) for (int y = 0; y < mapHeight; y++) { for (int t = 0; t < converter.numOfTileTypes(); t++) { double v; v = tileTypeAverages[t][x][y]; v *= (double) (noMaps - noToAdd) / (double) noMaps; tileTypeAverages[t][x][y] = v; } } for (int m = sampleMaps.size() - noToAdd; m < sampleMaps.size(); m++) { Map map = sampleMaps.get(m); for (int x = 0; x < mapWidth; x++) { for (int y = 0; y < mapHeight; y++) { tileTypeAverages[map.getTerrain(x, y)][x][y] += (double) 1 / noMaps; } } } repaint(); }
27802a29-1d0e-4413-b963-8dc000c354c3
5
public boolean loadCalendar(String filename) { BufferedReader bis = null; try { try { // open file bis = new BufferedReader(new FileReader(filename)); String s=null; s = bis.readLine(); //while we still have events to read while (s != null) { Event ev; String name=null,loc=null,desc=null; Date start=null,end=null; Repetition rep=null; Reminder rem=null; //String categories=null; //Time startTime=null,endTime=null; //repetition,reminder name=bis.readLine(); loc = bis.readLine(); desc = bis.readLine(); //date has '/' as a delimiter Scanner sc = new Scanner(bis.readLine()); sc = sc.useDelimiter("/"); start = new Date(sc.nextInt(), sc.nextInt(),sc.nextInt()); sc = new Scanner(bis.readLine()); sc = sc.useDelimiter("/"); end = new Date(sc.nextInt(), sc.nextInt(),sc.nextInt()); sc = new Scanner(bis.readLine()); if(sc.hasNextInt()) rep = new Repetition("",sc.nextInt()); else rep = new Repetition(sc.next(),sc.nextInt()); sc = new Scanner(bis.readLine()); sc = sc.useDelimiter("[/|:]"); rem = new Reminder(new Date(sc.nextInt(), sc.nextInt(), sc.nextInt()), new Time(sc.nextInt(), sc.nextInt())); //push event ev = new Event(name,loc,desc,start,end,rep,rem); this.events.push(ev); //read delimiters bis.readLine(); s = bis.readLine(); } bis.close(); return true; // in case the file does not exist, create it } catch (FileNotFoundException e) { System.err.println("File not found, "+ "creating file ..."); FileOutputStream out; PrintStream p; try { out = new FileOutputStream(filename); p = new PrintStream(out); p.close(); out.close(); return true; } catch (Exception e2) { System.err.println ("Error "+ "writing file: "+ e2.getStackTrace()); return false; } } } catch(IOException e) { e.printStackTrace(); } return false; }
218ee703-bae8-42b0-9f95-fad7750d08ed
9
public static String getBiomeName(int biome) { if (biome == -1) return "Sea"; else if (biome == 0) return "Ice"; else if (biome == 1) return "Taiga"; else if (biome == 2) return "Desert"; else if (biome == 3) return "Steppe"; else if (biome == 4) return "Dry Forest"; else if (biome == 5) return "Forest"; else if (biome == 6) return "Rainforest"; else if (biome == 8) return "Oasis"; System.err.println("Invalid biome"); return null; }
66c5e93e-2b40-4806-99fc-ae7f60d3c341
7
static final void method909(int i) { anInt1598++; if (Class348_Sub40_Sub30.aBoolean9403 && i == 3553) { while ((Class65.lobbyWorlds.length ^ 0xffffffff) < (Class215.anInt2834 ^ 0xffffffff)) { LobbyWorld class110_sub1 = Class65.lobbyWorlds[Class215.anInt2834]; if (class110_sub1 == null || ((LobbyWorld) class110_sub1).anInt5788 != -1) Class215.anInt2834++; else { if (Class176.aClass348_Sub26_2332 == null) Class176.aClass348_Sub26_2332 = (Class76.aClass169_1286.method1302 (i ^ ~0x1967, ((LobbyWorld) class110_sub1).ipAddress)); int i_29_ = (((Class348_Sub26) Class176.aClass348_Sub26_2332) .anInt6887); if (i_29_ == -1) break; ((LobbyWorld) class110_sub1).anInt5788 = i_29_; Class215.anInt2834++; Class176.aClass348_Sub26_2332 = null; } } } }
26710c29-f4dc-40c9-9bfb-c2e1e15e3ba4
9
protected Set<Resource> findPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException { URLConnection con = rootDirResource.getURL().openConnection(); JarFile jarFile = null; String jarFileUrl = null; String rootEntryPath = null; boolean newJarFile = false; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; jarCon.setUseCaches(false); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" prefix. String urlFile = rootDirResource.getURL().getFile(); int separatorIndex = urlFile.indexOf(getJarUrlSeparator()); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + getJarUrlSeparator().length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } try { if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith(File.separator)) { // Root entry path must end with slash to allow for proper matching. // The Sun JRE does not return a slash here, but BEA JRockit does. rootEntryPath = rootEntryPath + File.separator; } Set<Resource> result = new LinkedHashSet<Resource>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = (JarEntry) entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (match(subPattern, relativePath, true)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { jarFile.close(); } } }
181e8be6-531b-425f-bf72-1b04c148d0d6
7
public Dimension minimumLayoutSize(Container parent) { ToolBarPanel panel = (ToolBarPanel) parent; boolean isHorizontal = panel.getOrientation() == SwingConstants.HORIZONTAL; synchronized(parent.getTreeLock()) { Dimension dim = new Dimension(0, 0); int majorCount = getMajorCount(); for(int i = 0; i < majorCount; i++) { Dimension minorDim = new Dimension(0, 0); ArrayList minorList = getMinorComponents(i); for(int j = 0; j < minorList.size(); j++) { ComponentInfo ci = (ComponentInfo) minorList.get(j); Dimension d = ci.comp.getPreferredSize(); if(ci.comp.isVisible()) { if(isHorizontal) { minorDim.width += d.width; minorDim.height = Math.max(minorDim.height, d.height); if(j > 0) { minorDim.width += gap; } } else { minorDim.width = Math.max(minorDim.width, d.width); minorDim.height += d.height; if(j > 0) { minorDim.height += gap; } } } } if(isHorizontal) { dim.width = Math.max(dim.width, minorDim.width); dim.height += minorDim.height; } else { dim.width += minorDim.width; dim.height = Math.max(dim.height, minorDim.height); } } Insets insets = parent.getInsets(); dim.width += insets.left + insets.right; dim.height += insets.top + insets.bottom; return dim; } }
dbd94d47-c602-48f9-b1a5-425fd8768e53
2
public static void genererTablesDeTest() throws Exception { System.out.println("Début création des tables de tests...."); try { getEntityManager().getTransaction().begin(); // Créer utilisateurs System.out.println("Utilisateurs"); Utilisateur u1 = new Utilisateur(); Utilisateur u2 = new Utilisateur(); Utilisateur u3 = new Utilisateur(); u1.setPseudo("admin"); u2.setPseudo("moderateur"); u3.setPseudo("utilisateur"); u1.setMotDePasse("admin"); u2.setMotDePasse("moderateur"); u3.setMotDePasse("utilisateur"); u1.setRole(Role.Administrateur); u2.setRole(Role.Moderateur); u3.setRole(Role.Utilisateur); u1.setAdresseCourriel("lord_darky_vador@hotmail.com"); u2.setAdresseCourriel("lord_darky_vador@hotmail.com"); u3.setAdresseCourriel("lord_darky_vador@hotmail.com"); u1.setCompteActive(true); u2.setCompteActive(true); u3.setCompteActive(true); UtilisateurRepo.get().creer(u1); UtilisateurRepo.get().creer(u2); UtilisateurRepo.get().creer(u3); // Créer publications System.out.println("Publications"); Sujet p1 = new Sujet(); Sujet p2 = new Sujet(); p1.setSujet("Un gros test pour vérifier"); p2.setSujet("Aujourd'hui plein de choses se produisent"); p1.setCreateur(u1); p2.setCreateur(u1); p1.setCategorie(CategorieRepo.get().nouvelles()); p2.setCategorie(CategorieRepo.get().nouvelles()); System.out.println("Réponses"); Reponse r1 = new Reponse(); Reponse r2 = new Reponse(); r1.setSujet(p1); r2.setSujet(p2); r1.setMessage("Un gros test pour vérifier...\nque ça fonctionne bel et bien."); r2.setMessage("Un autre test qui devrait apparaître en premier.\nÇa marche?"); r1.setAuteur(u1); r2.setAuteur(u2); r1.setDateCreation(new Date()); Date date = new Date(); date.setTime(date.getTime() + 10000); r2.setDateCreation(date); r1.setSujet(p1); r2.setSujet(p2); SujetRepo.get().creer(p1); SujetRepo.get().creer(p2); ReponseRepo.get().creer(r1); ReponseRepo.get().creer(r2); // Genre System.out.println("Genres"); Genre g1 = new Genre(); Genre g2 = new Genre(); Genre g3 = new Genre(); Genre g4 = new Genre(); g1.setNom("Action"); g2.setNom("Stratégie en temps réel"); g3.setNom("Aventure"); g4.setNom("Course"); GenreRepo.get().creer(g1); GenreRepo.get().creer(g2); GenreRepo.get().creer(g3); GenreRepo.get().creer(g4); // Créer jeux System.out.println("Jeux"); Jeu j1 = new Jeu(); Jeu j2 = new Jeu(); j1.setNom("Cossin Lette 3"); j2.setNom("La grosse patate"); j1.setDescription( "Un jeu comme vous n'avez jamais vu...\n" + "Un jeu sans pareille, avec de fous revirements...\n" + "Il s'agit bel et bien de COSSIN LETTE 3!"); j2.setDescription("Une grosse patate qui mange ben des patates."); j1.setCreateur(u1); j2.setCreateur(u2); JeuRepo.get().creer(j1); JeuRepo.get().creer(j2); j1.creerForum(); j2.creerForum(); getEntityManager().getTransaction().commit(); System.out.println("Complétion de la création des tables de tests"); } catch (Exception e) { if (getEntityManager().getTransaction().isActive()) getEntityManager().getTransaction().rollback(); throw e; } }
3be8f2bd-7f6a-4441-bc95-37c2bb69249d
8
@Override public boolean keydown(KeyEvent ev) { if (ev.getKeyCode() == KeyEvent.VK_UP) APXUtils.wPressed = true; if (ev.getKeyCode() == KeyEvent.VK_LEFT) APXUtils.aPressed = true; if (ev.getKeyCode() == KeyEvent.VK_DOWN) APXUtils.sPressed = true; if (ev.getKeyCode() == KeyEvent.VK_RIGHT) APXUtils.dPressed = true; if (ev.getKeyCode() == KeyEvent.VK_RIGHT || ev.getKeyCode() == KeyEvent.VK_DOWN || ev.getKeyCode() == KeyEvent.VK_LEFT || ev.getKeyCode() == KeyEvent.VK_UP) return true; else return false; }
fee0baa4-340f-45da-900d-76e8b9c94ba0
2
public static void main(String[] args) { ItemTest i = new ItemTest(); InventoryWindow iw1 = new InventoryWindow(); iw1.openInventory(State.BATTLE); while (iw1.visible) { try { Thread.sleep(15); } catch(Exception ignored) { } } System.exit(-1); }