method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e5a79860-fea8-420e-b673-5437811a4cf9
1
public static String escapeDoubleQuotes(String string) { if (string == null) { return null; } String result = string.replaceAll("\\\\", "\\\\\\\\"); return result.replaceAll("\\\"", "\\\\\\\""); }
b22d4538-ab61-4b37-b021-ac96b6ee51df
7
public void languageAndWordlistCheckMain() { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("Options.dat"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int count =0; while ((strLine = br.readLine()) != null) { // Print the content on the console if(count == 0){ wordbook = strLine; }else if(count == 1){ language = strLine; } count++; } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } //prepare the language selected: if(Integer.parseInt(language) == 0){ jButton1.setText("Nächstes Wort>>"); jButton2.setText("<< Zurück"); jButton3.setText("der Artikel"); jButton4.setText("der Plural"); jMenu1.setText("Hilfe"); jMenu2.setText("Geräte"); jMenuItem1.setText("Optionen"); jMenuItem2.setText("Wortliste Verwaltung"); jMenuItem3.setText("Über"); }else if(Integer.parseInt(language) == 1){ jButton1.setText("Sıradaki Kelime >>"); jButton2.setText("<< Geri"); jButton3.setText("Artikel"); jButton4.setText("Çoğul"); jMenu1.setText("Yardım"); jMenu2.setText("Ayarlar"); jMenuItem1.setText("Seçenekler"); jMenuItem2.setText("Kelime Listesini Yönet"); jMenuItem3.setText("Hakkında"); }else if(Integer.parseInt(language) == 2){ jButton1.setText("Next Word >>"); jButton2.setText("<< Back"); jButton3.setText("The Article"); jButton4.setText("The Plural"); jMenu1.setText("Help"); jMenu2.setText("Tools"); jMenuItem1.setText("Options"); jMenuItem2.setText("Edit Word List"); jMenuItem3.setText("About"); } }
be81fdd2-7b73-4c5e-8b50-77746defe7d0
5
private int knapsack(int n, int capacity, int w[], int v[]) { // dynamic programming if (vKnapsack[capacity] != Integer.MIN_VALUE) return vKnapsack[capacity]; // Find the optimal value that can carried in a knapsack of given // capacity // The optimal value that can be carried is the maximum of the optimal // subproblem solutions. // Each subproblem here represents a choice of including one of the // items in the knapsack and optimally packing into the rest of the // knapsack int max = 0; for (int i = 0; i < n; i++) { // remove this to get a solution for the unbounded problem if (inKnapsack[i]) continue; // Is there space(non-negative) in the knapsack to add item i int space = capacity - w[i]; if (space < 0) continue; // Result of optimally packing in the remaining space int t = knapsack(n, space, w, v); // optimal solution is the max of all subproblems. if (v[i] + t > max) { max = v[i] + t; contentsKnapsack[capacity] = w[i] + " " + contentsKnapsack[space]; inKnapsack[i] = true; } } vKnapsack[capacity] = max; return vKnapsack[capacity]; }
dbd0d22a-011d-4d83-903d-67cddcbb64f2
4
@EventHandler public void onTarget(EntityTargetLivingEntityEvent e) { if (e.getTarget().getType() == EntityType.PLAYER) { if (e.getTarget().isInsideVehicle()) { if (e.getEntity().getEntityId() == e.getTarget().getVehicle() .getEntityId()) { e.setCancelled(true); e.setTarget(null); if (e.getEntity() instanceof Creature) { Creature c = (Creature) e; c.setTarget(null); } } } } }
bea040ad-8874-44b6-8b2f-30865d3295cb
7
private void updateAsteroids() { ArrayList<Asteroid> deadAsteroid = new ArrayList<Asteroid>(); for(int i = 0; i < asteroids.size(); i++) { Asteroid a = asteroids.get(i); a.move(); if(CollisionDetector.isColliding(sc, a)) { if(!sc.isShieldActive()) sc.damaged(a.getStrength()); else score += a.getScore(); a.damaged(sc.getStrength()); } if(!a.isOnScreen()) deadAsteroid.add(a); } for(int i = 0; i < deadAsteroid.size(); i++) { Asteroid a = deadAsteroid.get(i); asteroids.remove(a); } asteroidItr = (asteroidItr + 1) % (ASTEROIDS_RATE_LIMITER - RATE_OF_ASTEROIDS); if(asteroidItr == 0 && asteroidsPresence) { asteroids.add(new Asteroid()); } }
7cac7489-6cd1-412d-9815-2b5b5aeb8504
4
public SimpleSparqlSimulator(String endpoint) throws MalformedURLException { // read the list of files of queries sparql_queries = new ArrayList<File>(); URL url = getClass().getResource("/"); LOGGER.info("Reading queries (txt files) from " + url.getPath() + SimpleSparqlSimulator.class.getName()); File dir = new File(url.getPath() + SimpleSparqlSimulator.class.getName()); if (dir.isDirectory()) { for (final File fileEntry : dir.listFiles()) { if (fileEntry.isFile()) if (fileEntry.getName().endsWith(".txt")) sparql_queries.add(fileEntry); } } else LOGGER.error("Not a directory"); this.endpoint = new URL(endpoint); }
929d1492-f53c-44c6-8715-6fbd6ec30db0
3
public static BasicBlock find(BasicBlock[] blocks, int pos) throws BadBytecode { for (int i = 0; i < blocks.length; i++) { int iPos = blocks[i].position; if (iPos <= pos && pos < iPos + blocks[i].length) return blocks[i]; } throw new BadBytecode("no basic block at " + pos); }
cd287bdc-a0a4-4f3a-9804-6b25b31c0940
1
public int atualizar(String sql) { Connection conn = this.getConn(); try { Statement stm = conn.createStatement(); return stm.executeUpdate(sql); } catch (SQLException ex) { Logger.getLogger(ConectorMySql.class.getName()).log(Level.SEVERE, null, ex); } return -1; }
a8d06867-2be1-432e-ab0c-abed8f1b6a38
1
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { if (isSelected) { int vDifference = (int) (boldFontMetrics.getStringBounds(title, g).getWidth()) - textRect.width; textRect.x -= (vDifference / 2); super.paintText(g, tabPlacement, boldFont, boldFontMetrics, tabIndex, title, textRect, isSelected); } else { super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected); } }
bd818420-83e3-49b1-9d13-fd2db0694b11
5
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain) throws IOException, ServletException { if (_request instanceof HttpServletRequest && _response instanceof HttpServletResponse) { HttpServletRequest request = (HttpServletRequest) _request; HttpServletResponse response = (HttpServletResponse) _response; request = new MapHttpServletRequest(request); processPath((MapHttpServletRequest) request); request.setAttribute(AttributeNames.REQUEST_URI, request.getRequestURI()); request.setAttribute(AttributeNames.REQUEST_URL, request.getRequestURL().toString()); String path = request.getRequestURI().substring(request.getContextPath().length()); Object target = pages.resolve((MapHttpServletRequest) request, path, HttpMethods.getMethod(request.getMethod())); request.setAttribute(AttributeNames.PATH, path); if (target instanceof ServletAction) { ((ServletAction) target).invoke(request, response); return; } else if (target instanceof Page) { request.setAttribute(AttributeNames.PATH_SET, lookupPaths(target.getClass())); request.setAttribute(AttributeNames.PAGE, target); if (dispatchServlet == null) { ((Page) target).service(servletContext, request, response); } else { request.getRequestDispatcher(dispatchServlet).forward(request, response); } return; } } chain.doFilter(_request, _response); }
a420c614-a08d-4142-a524-eec522c2fe18
6
private static void printGame(JSONObject jo) { try { JSONArray champs = Champion.getAllChamps(false); long champId = jo.getLong("championId"); System.out.println("Game " + jo.getLong("gameId")); System.out.println("-----------------------------"); System.out.println("Champion: " + champId + " (" + Champion.getChampName(champs, champId) + ")"); System.out.println("Create Date: " + Util.getFriendlyDate(jo.getLong("createDate"))); System.out.println("Fellow Players:\n"); JSONArray players = jo.getJSONArray("fellowPlayers"); String ids = ""; for(int i = 0; i < players.length(); i++) { JSONObject o = players.getJSONObject(i); ids += o.getLong("summonerId") + ","; } ids = ids.substring(0, ids.lastIndexOf(",")); JSONObject names = Summoner.getSummonersById(ids); for(int i = 0; i < players.length(); i++) { JSONObject o = players.getJSONObject(i); champId = o.getLong("championId"); System.out.println(" " + names.getJSONObject(o.getLong("summonerId") + "").getString("name")); System.out.println(" -----------------------------"); System.out.println(" Champion: " + champId + "(" + Champion.getChampName(champs, champId) + ")"); System.out.println(" Team: " + (o.getInt("teamId") == 100 ? "Blue" : "Purple/Red")); System.out.println(); } int mapId = jo.getInt("mapId"); System.out.println("Map: " + mapId + " [" + GameConstants.getMapName(mapId) + "]"); System.out.println("Game Mode: " + jo.getString("gameMode")); System.out.println("Game Type: " + jo.getString("gameType")); System.out.println("Game Sub-Type: " + jo.getString("subType")); // System.out.println("Invalid " + jo.getBoolean("invalid")); System.out.println("Level: " + jo.getInt("level")); System.out.println("Spell 1: " + jo.getInt("spell1")); System.out.println("Spell 2: " + jo.getInt("spell2")); System.out.println("Team: " + (jo.getInt("teamId") == 100 ? "Blue" : "Purple/Red") + "\n"); JSONObject stats = jo.getJSONObject("stats"); System.out.println(" Stats"); System.out.println(" -----------------------------"); System.out.println(" Win: " + stats.getBoolean("win")); System.out.println(" Nexus Final Blow: " + stats.optBoolean("nexusKilled", false)); System.out.println(" K/D/A/CS: " + stats.optInt("championsKilled") + "/" + stats.optInt("numDeaths") + "/" + stats.optInt("assists") + "/" + stats.optInt("minionsKilled")); System.out.println(" Gold Earned: " + Util.getFriendlyNum(stats.getLong("goldEarned"))); System.out.println(" Spent: " + Util.getFriendlyNum(stats.getLong("goldSpent"))); System.out.println(" Time: " + Util.getTime(stats.getInt("timePlayed"))); System.out.println(); System.out.println(" Items"); System.out.println(" ============================="); System.out.println(" Items: " + stats.optInt("item0") + "/" + stats.optInt("item1") + "/" + stats.optInt("item2") + "/" + stats.optInt("item3") + "/" + stats.optInt("item4") + "/" + stats.optInt("item5") + "/" + stats.optInt("item6")); System.out.println(" Items Purchased: " + stats.optInt("itemsPurchased")); System.out.println(" Consumables Purchased: " + stats.optInt("consumablesPurchased")); System.out.println(" Legendary Items Built: " + stats.optInt("lengendaryItemsCreated")); System.out.println(" VisionWards Bought: " + stats.optInt("visionWardsBought")); System.out.println(" SightWards Bought: " + stats.optInt("sightWardsBought")); System.out.println(" Wards Placed: " + stats.optInt("wardPlaced")); System.out.println(" Wards Killed: " + stats.optInt("wardKilled")); System.out.println(); System.out.println(" Damage"); System.out.println(" ============================="); System.out.println(" Killing Sprees: " + stats.optInt("killingSprees")); System.out.println(" Double Kills: " + stats.optInt("doubleKills")); System.out.println(" Triple Kills: " + stats.optInt("tripleKills")); System.out.println(" Quadra Kills: " + stats.optInt("quadraKills")); System.out.println(" Penta Kills: " + stats.optInt("pentaKills")); System.out.println(" Unreal Kills: " + stats.optInt("unrealKills")); System.out.println(" Largest Killing Spree: " + stats.optInt("largestKillingSpree")); System.out.println(" Largest MultiKill: " + stats.optInt("largestMultiKill")); System.out.println(" Largest Critical Strike: " + Util.getFriendlyNum(stats.optInt("largestCriticalStrike"))); System.out.println(" Magic Damage Dealt: " + Util.getFriendlyNum(stats.optInt("magicDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("magicDamageDealtToChampions"))); System.out.println(" Magic Damage Taken: " + Util.getFriendlyNum(stats.optInt("magicDamageTaken"))); System.out.println(" Minions Killed: " + stats.optInt("minionsKilled")); System.out.println(" Denied: " + stats.optInt("minionsDenied")); System.out.println(" Neutral Minions Killed: " + stats.optInt("neutralMinionsKilled")); System.out.println(" Your Jungle: " + stats.optInt("neutralMinionsKilledYourJungle")); System.out.println(" Enemy Jungle: " + stats.optInt("neutralMinionsKilledEnemyJungle")); System.out.println(" Physical Damage Dealt: " + Util.getFriendlyNum(stats.optInt("physicalDamageDealt"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("physicalDamageDealtToChampions"))); System.out.println(" Physical Damage Taken: " + Util.getFriendlyNum(stats.optInt("physicalDamageTaken"))); System.out.println(" Super Monsters Killed: " + stats.optInt("superMonsterKilled")); System.out.println(" Total Damage Dealt: " + Util.getFriendlyNum(stats.optInt("totalDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("totalDamageDealtToChampions"))); System.out.println(" Total Damage Taken: " + Util.getFriendlyNum(stats.optInt("totalDamageTaken"))); System.out.println(" Total Heal: " + Util.getFriendlyNum(stats.optInt("totalHeal"))); System.out.println(" Total CC Time Dealt: " + Util.getTime(stats.optInt("totalCrowdControlTimeDealt"))); System.out.println(" Total Units Killed: " + stats.optInt("totalUnitsKilled")); System.out.println(" True Damage Dealt: " + Util.getFriendlyNum(stats.optInt("trueDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("trueDamageDealtToChampions"))); System.out.println(" True Damage Taken: " + Util.getFriendlyNum(stats.optInt("trueDamageTaken"))); System.out.println(" Turrets Killed: " + stats.optInt("turretsKilled")); System.out.println(); System.out.println(" Spells"); System.out.println(" ============================="); System.out.println(" Q/W/E/R Casts: " + stats.optInt("spell1Cast") + "/" + stats.optInt("spell2Cast") + "/" + stats.optInt("spell3Cast") + "/" + stats.optInt("spell4Cast")); System.out.println(" D/F Casts: " + stats.optInt("summonSpell1Cast") + "/" + stats.optInt("summonSpell2Cast")); System.out.println(); if(jo.getString("gameType").equalsIgnoreCase("ODIN")) { System.out.println(" Dominion"); System.out.println(" ============================="); System.out.println(" Barracks Killed: " + stats.getInt("barracksKilled")); System.out.println(" CombatPlayerScore: " + Util.getFriendlyNum(stats.getInt("combatPlayerScore"))); System.out.println(" Nodes Captured: " + stats.getInt("nodeCapture")); System.out.println(" Assists: " + stats.getInt("nodeCaptureAssist")); System.out.println(" Nodes Neutralized: " + stats.getInt("nodeNeutralize")); System.out.println(" Assists: " + stats.getInt("nodeNeutralizeAssist")); System.out.println(" Objective Score: " + Util.getFriendlyNum(stats.getInt("objectivePlayerScore"))); System.out.println(" Total Player Score: " + Util.getFriendlyNum(stats.getInt("totalPlayerScore"))); System.out.println(" Total Score Rank: " + Util.getFriendlyNum(stats.getInt("totalScoreRank"))); System.out.println(" Victory Point Total: " + Util.getFriendlyNum(stats.getInt("victoryPointTotal"))); } } catch (JSONException e) { e.printStackTrace(); } }
5aa07a78-1d93-4efd-8614-8de5c6357ab7
0
private void setSelected(SingleScorePanel singleScorePanel) { singleScorePanel.setSelected(true); }
17e7a771-0633-4ccf-819f-062a446b40e2
7
public static void main(String args[]) { String test = args[0]; int up = 0; int down = 0; int left = 0; int right = 0; for(int i = 0; i < test.length(); i++) { switch(test.charAt(i)) { case 'U': up++; break; case 'D': down++; break; case 'L': left++; break; case 'R': right++; break; } } if( (up == down) && (left == right)) { System.out.println("ALL OKAY"); } }
aa9b001d-4cf0-4e7c-826d-4ef5c490afd4
7
@Override public boolean equals( Object obj ){ if (this == obj){ return true; } if (obj == null){ return false; } if (obj instanceof PassengerCar ){ PassengerCar temp = (PassengerCar) obj; return ( this.baggageWeight == temp.getBaggageWeight())&& ( this.passengersCount == temp.getPassengersCount() )&& ( this.getComfortPercent() == temp.getComfortPercent())&& ( this.getHeight() == temp.getHeight() )&& ( this.getTonsWeight() == temp.getTonsWeight() ); } else { return false; } }
627e2055-d030-4fa6-930e-7aa5c5d3560e
4
public static int[] getRandomOrdering(int Size){ double[] randArray = new double[Size]; for(int n = 0; n < Size; n++){ randArray[n] = Math.random(); } int[] randOrder = new int[Size]; double lowestRand = 1; for(int i = 0; i < Size; i++){ for(int n = 0; n < Size; n++){ if(randArray[n] < lowestRand) { randOrder[i] = n; lowestRand = randArray[n]; } } randArray[randOrder[i]] = 1; lowestRand = 1; } return randOrder; }
b88f32a8-5988-4145-9b6a-ad33ae0ca405
0
public void timeAndComputeValue(){ }
1ccb7b48-3b36-4433-b5ec-b2235a0de05e
9
public String rotate(String plainText) { char[] plainTextChars = plainText.toCharArray(); StringBuilder rotatedChars = new StringBuilder(); for (char plainTextChar : plainTextChars) { if ((plainTextChar >= 'a' && plainTextChar <= 'm') || (plainTextChar >= 'A' && plainTextChar <= 'M')) { plainTextChar += ROT13; } else if ((plainTextChar >= 'm' && plainTextChar <= 'z') || (plainTextChar >= 'M' && plainTextChar <= 'Z')) { plainTextChar -= ROT13; } rotatedChars.append(plainTextChar); } return rotatedChars.toString(); }
3aa00801-c5f6-4886-87ba-cace8a50673f
2
public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP && !principal.getSalta()){ principal.setSalta(); tiempoCaida = 0; } }
aee1693d-00d9-421b-b975-ed6b749d2c05
3
public void removeOpinion(DataRow row) { boolean result = DataVector.getInstance().dbManager.remove(row); if(!result) { ErrorDialog errorDialog = new ErrorDialog(true, "Nastąpił błąd w usuwaniu opinii: " + row.getName() + ".", "AbstractManager", "Method: removeOpinion(DataRow row)", "row"); errorDialog.setVisible(true); return; } for(AbstractOpinion a : opinions) { if(a.getName().equals(row.getName())) { opinions.remove(a); refreshData(); return; } } }
38914963-8fed-487c-8a2e-918c4298cd6d
1
public String udp2String(Packet packet) { UDPPacket udpPacket = (UDPPacket) packet; //Creates a udp packet out of the packet EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink; //Creates and ethernet packet for layer 2 information methodData += src_macInEnglish = ethernetPacket.getSourceAddress(); //Gets the string value of the src mac address methodData += dst_macInEnglish = ethernetPacket.getDestinationAddress(); //Gets the string value of the dst mac address methodData += src_UDPPort = udpPacket.src_port; //Gets the src udp port methodData += sourcePortUDP = String.valueOf(src_UDPPort); //creates a string using the port to place in the dataArray methodData += dst_UDPPort = udpPacket.dst_port; //Gets the dst port from the packet methodData += destinationPortUDP = String.valueOf(dst_UDPPort); //Creates a string from dst_UDPPport methodData += src_ip = udpPacket.src_ip; //Gets the inet address from the packet methodData += srcIPString = src_ip.toString(); //Converts the InetAddress to a string methodData += dst_ip = udpPacket.dst_ip; //Gets the inet dst Ip address from udppacket methodData += dstIPString = dst_ip.toString(); //Converts that to a string protocol = udpPacket.protocol; //Grabs the protocol methodData += protocolName = "UDP"; //Since this is udp we don't have to worry about other protocols for(int i = 0; i < udpPacket.data.length; i++) { //Runs through the array containing packet data data += String.valueOf((char) udpPacket.data[i]); //Creates a string from every part of that array } methodData += data; return methodData; }
42d48e07-ad79-4db7-9899-5c7588c8baea
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(); }
02e4f113-9f44-4085-8c76-9275d77e190b
0
public String getPassword() { return password; }
8dee17b7-2f86-420e-b327-ef59e049c303
0
public void add(String line) { graph.append(line); }
5910b552-37e3-47d3-b8f5-4b2b4d728124
1
public static boolean isOptionPresent(String cmdLineArg, char option) { boolean result = false; // avoid "--abc" if (cmdLineArg.lastIndexOf('-') == 0) { result = cmdLineArg.indexOf(option) >= 1; } return result; }
171354f1-4315-426b-bd8b-c4474addfe92
0
public long getSeatType() { return this._seatType; }
3e2fc6aa-1744-4148-8956-f9e06c3cdb15
4
public static boolean isOnScreen(Entity paramEntity) { if (paramEntity.getXpos() > ScreenHelper.widthNeg(paramEntity) && paramEntity.getXpos() < ScreenHelper.widthPos(paramEntity)) { if (paramEntity.getYpos() > ScreenHelper.heightNeg(paramEntity) && paramEntity.getYpos() < ScreenHelper.heightPos(paramEntity)) { return true; } } return false; }
dcea5c20-384d-400f-8943-78dc2256a68a
2
public ListNode rotateRight(ListNode head, int n) { if(null == head || null == head.next) return head; int length = getLengthOfList(head); ListNode tail = getTailOfNode(head); tail.next = head; ListNode pivot = getRotateNode(head, length - n % length); return pivot; }
190edb77-5745-4283-bae5-cc5c7f560dff
1
public ArrayList<Record> getNewsfeed() { ArrayList<User> myfriends = getFriendList(); ArrayList<Record> newsFeeds = new ArrayList<Record>(); for (int i = 0; i < myfriends.size(); i++) { User friend = myfriends.get(i); newsFeeds.addAll(QuizTakenRecord.getQuizHistoryByUserID(friend.userID)); newsFeeds.addAll(QuizCreatedRecord.getCreatedQuizByUserID(friend.userID)); newsFeeds.addAll(AchievementRecord.getAchievementRecordByUserID(friend.userID)); } Collections.sort(newsFeeds, new RecordSortByTime()); return newsFeeds; }
b6a9c6da-d3fe-48b3-950d-f2aea06649e4
5
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); String password = req.getParameter("password"); if (id == null || id.length() == 0 || password == null || password.length() == 0) { resp.sendError(400, "incomplete parameter"); return; } AccountService service = (AccountService) context.getBean("accountService"); try { service.login(id, password); resp.getWriter().print("Login Successful!"); } catch (AccountServiceException e) { resp.sendError(400, e.getMessage()); } }
eb20446a-7317-41f1-8dd0-6d1d59542824
6
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; int heightMover = 0; for (int tetIndex = 0; tetIndex<upcoming.size(); tetIndex++){ g2.setColor(controller.getBlankColor()); g2.fillRect(0, heightMover*size, size*6, size); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); heightMover++; int[][] visualMap = upcoming.get(tetIndex).getVisual(); for (int i = 0; i<visualMap.length; i++){ //draw black block to the left g2.setColor(controller.getBlankColor()); g2.fillRect(0, (i+heightMover)*size, size, size); //draw the tetromino for(int j = 0; j<visualMap[0].length; j++){ if(visualMap[i][j] == Board.VISUAL_MANA_ORB){ g2.setColor(controller.getBlankColor()); g2.fillRect((j+1)*size, (i+heightMover)*size, size, size); g2.setColor(Color.MAGENTA); g2.fillOval((j+1)*size, (i+heightMover)*size, size, size); } else { Color color; if (visualMap[i][j] == Board.VISUAL_EMPTY_AREA){ color = controller.getBlankColor(); } else { color = controller.getColor(visualMap[i][j]); } g2.setColor(color); g2.fill3DRect((j+1)*size, (i+heightMover)*size, size, size, true); } } //fill in remaining gap with black for (int l = visualMap[0].length+1; l<6; l++){ g2.setColor(controller.getBlankColor()); g2.fillRect(l*size, (i+heightMover)*size, size, size); } } heightMover += visualMap.length; } //add bottom black bar g2.setColor(controller.getBlankColor()); g2.fillRect(0, heightMover*size, size*6, size); }
303df892-b09b-42e4-a9cd-0bcd866dc54a
4
@Override public void deserialize(Buffer buf) { elementId = buf.readInt(); if (elementId < 0) throw new RuntimeException("Forbidden value on elementId = " + elementId + ", it doesn't respect the following condition : elementId < 0"); elementCellId = buf.readShort(); if (elementCellId < 0 || elementCellId > 559) throw new RuntimeException("Forbidden value on elementCellId = " + elementCellId + ", it doesn't respect the following condition : elementCellId < 0 || elementCellId > 559"); elementState = buf.readInt(); if (elementState < 0) throw new RuntimeException("Forbidden value on elementState = " + elementState + ", it doesn't respect the following condition : elementState < 0"); }
f1e75e2a-3da1-4837-9799-25142219d00b
3
@Override public void doAction(Player player) throws InvalidActionException { if (player == null) throw new IllegalArgumentException("Player can't be null!"); if (player.getRemainingActions() <= 0) throw new InvalidActionException("The player has no turns left!"); Position currentPos = player.getPosition(); Position newPos = movement.newPosition(currentPos); if (!grid.canMove(player, movement)) throw new InvalidActionException("The player can't move to the desired position!"); player.setPosition(newPos); player.setMovedDuringTurn(true); player.getLightTrail().addPosition(currentPos); player.decrementAction(); //doCollide(player); }
fbd0a61c-6351-450f-a132-65d023356f9b
1
void toss(){ Random rand=new Random(); if(rand.nextInt(9)<5){ this.setHeadSide(true); }else{ this.setTailSide(true); } }
365fa54b-ffc6-414b-8bc4-cd6d830153fa
5
private long ticklessTimer() { // Calculate tickless timer, up to 1 hour long tickless = System.currentTimeMillis() + 1000 * 3600; for (STimer timer : timers) { if (timer.when == -1) timer.when = timer.delay + System.currentTimeMillis(); if (tickless > timer.when) tickless = timer.when; } long timeout = tickless - System.currentTimeMillis(); if (timeout < 0) timeout = 0; if (verbose) System.out.printf("I: zloop: polling for %d msec\n", timeout); return timeout; }
6d3c9243-11d5-432f-b51c-11ce0bced97d
2
@SuppressWarnings({ "rawtypes", "unchecked" }) public void getAllInGroup(String group, Map target){ try{ String key; ObjectInputStream objStr; Serializable obj; PreparedStatement prep = this.conn.prepareStatement("SELECT key, value FROM keyval WHERE collection = ?"); prep.setString(1, group); ResultSet rs = prep.executeQuery(); while(rs.next()){ key = rs.getString(1); objStr = new ObjectInputStream(new ByteArrayInputStream(rs.getBytes(2))); obj = (Serializable)objStr.readObject(); target.put(key, obj); } rs.close(); }catch(Exception e){ e.printStackTrace(); } }
9c939cbb-7e32-4474-972e-3d47e30de5ae
3
public String getConsulDefMap(String arg_dt1) throws SQLException, ClassNotFoundException { ResultSet rs; String sts = ""; Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("SELECT distinct tb_tp_defeito.str_defeito" + " FROM public.tb_defeito, public.tb_tp_defeito WHERE " + " tb_tp_defeito.cod_tp_defeito = tb_defeito.cod_tp_defeito AND" + " date_trunc('month', datahora) = TO_timestamp(?,'MM/YYYY')" + " order by tb_tp_defeito.str_defeito"); call.setString(1, arg_dt1); rs = call.executeQuery(); while (rs.next()) { sts = sts + "[\"" + rs.getString(1).replace(" ", "_") + "\",\"Defeitos\",0,0], \n"; } call.close(); } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
3a17ee1a-7750-426b-ab3e-44d9364f0564
3
private void btnValiderMembreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValiderMembreActionPerformed if(jRadioButton1.isSelected()){ jTable1.setModel(new ListMembreNomController(jTextField1.getText())); } if(jRadioButton2.isSelected()){ jTable1.setModel(new ListMembreMailController(jTextField1.getText())); } if(jRadioButton3.isSelected()){ jTable1.setModel(new supprimer_membre_controler()); } }//GEN-LAST:event_btnValiderMembreActionPerformed
35233eab-ff71-4500-a9da-45898410a5d0
1
public void fillStocks() { pnlDashboardCenter.removeAll(); stocks = new ArrayList<Stock>(Service.getAllStocks()); Collections.sort(stocks); squareGraphicList = new ArrayList<SquareGraphic>(); selectedSquare = null; for (Stock stock : stocks) { SquareGraphic sq = new SquareGraphic(); sq.addMouseListener(selectStockLisneter); sq.setPreferredSize(new Dimension(85, 85)); sq.setStock(stock); sq.setState(Service.getWorstState(stock)); pnlDashboardCenter.add(sq); squareGraphicList.add(sq); } this.repaint(); this.validate(); }
c4b9fb02-e20f-4c01-87cf-b6454b634824
7
private boolean isStudentInOneLectureAtTheTime(Teacher teacher, List<Group> teachersGroups, Group group, int lectureNumber, LinkedHashMap<String, LinkedHashMap> dayTimeTable) { boolean mandatoryConditionsMet = true; if (group != null) { // System.out.println("Grupe idejimui: " + group.getGroupName()); List<Student> groupStudents = group.getStudents(); Collection<LinkedHashMap> teachersTimeTables = dayTimeTable.values(); // System.out.println("teachersTimeTables before if: " + teachersTimeTables); for (LinkedHashMap<String, String> teachersTimeTable : teachersTimeTables) { // System.out.println("Iskviete fore"); if (teachersTimeTable.isEmpty()) { mandatoryConditionsMet = true; continue; } // System.out.println("teachersTimeTable: " + teachersTimeTable); String groupNameToSplit = teachersTimeTable.get(String.valueOf(lectureNumber)); if (groupNameToSplit == null) { mandatoryConditionsMet = true; continue; } String[] splittedGroupNames = groupNameToSplit.split(":"); String groupName = splittedGroupNames[1].trim(); // System.out.println("Group name: " + groupName); Group groupToCheck = studentsMockDataFiller.getGroups().get(groupName); // System.out.println("groupToCheck: " + groupToCheck); boolean contains = true; if (StringUtils.equals(groupName, "-----")) { contains = false; } if (groupToCheck != null) { // System.out.println("Group to check: " + groupToCheck.getGroupName()); contains = CollectionUtils.containsAny(groupStudents, groupToCheck.getStudents()); // System.out.println("Contains: " + contains); } if (contains == false) { mandatoryConditionsMet = true; } else { mandatoryConditionsMet = false; return mandatoryConditionsMet; } } } else { mandatoryConditionsMet = false; } return mandatoryConditionsMet; }
6cf8a078-b6c9-4d18-8df7-9c70ba3c1b46
8
public void paintComponent(Graphics g){ int x = this.getWidth(); int y = this.getHeight(); g.setColor(Color.GRAY); if(n==0) {g.setColor(Color.blue);} if(n==1) {g.setColor(Color.red);} if(n==2) {g.setColor(Color.green);} g.fillRect(0, 0, this.getWidth(), this.getHeight()); if(p>0){ g.setColor(Color.yellow); g.fillOval(x/2-x/16, y/8, x/8, x/8); g.fillRect(x/2-x/8, x/8+y/8, x/4,3*y/8 ); g.fillRect(x/2-x/8,x/8+y/8+3*y/8, x/12, y/4); g.fillRect(13*x/24,x/8+y/8+3*y/8, x/12, y/4); g.setColor(Color.blue); if(p==1){g.drawString("E", x/2-x/16, y/2+y/8);} if(p==2){g.drawString("V", x/2-x/16, y/2+y/8);} if(p==3){g.drawString("C", x/2-x/16, y/2+y/8);} if(p==4){g.drawString("L", x/2-x/16, y/2+y/8);} } }
8b1d1250-dc18-4ab8-b9b0-0752afbddc60
0
public static int chooseFile() { Scanner in = new Scanner(System.in); String[] files = FileLister.getFilesArrayString(); FileLister.listFiles(files); System.out.println(">Enter a file number"); int selection = in.nextInt() - 1; return selection; }
bfcab2a8-fd27-4568-9644-7c9d6cda1ac4
8
public void buildClassifier(Instances instances) throws Exception { // can classifier handle the data? getCapabilities().testWithFail(instances); // remove instances with missing class instances = new Instances(instances); instances.deleteWithMissingClass(); double sumOfWeights = 0; m_Class = instances.classAttribute(); m_ClassValue = 0; switch (instances.classAttribute().type()) { case Attribute.NUMERIC: m_Counts = null; break; case Attribute.NOMINAL: m_Counts = new double [instances.numClasses()]; for (int i = 0; i < m_Counts.length; i++) { m_Counts[i] = 1; } sumOfWeights = instances.numClasses(); break; } Enumeration enu = instances.enumerateInstances(); while (enu.hasMoreElements()) { Instance instance = (Instance) enu.nextElement(); if (!instance.classIsMissing()) { if (instances.classAttribute().isNominal()) { m_Counts[(int)instance.classValue()] += instance.weight(); } else { m_ClassValue += instance.weight() * instance.classValue(); } sumOfWeights += instance.weight(); } } if (instances.classAttribute().isNumeric()) { if (Utils.gr(sumOfWeights, 0)) { m_ClassValue /= sumOfWeights; } } else { m_ClassValue = Utils.maxIndex(m_Counts); Utils.normalize(m_Counts, sumOfWeights); } }
1044a308-8f09-484f-bc72-07a9f86571ec
6
public List<String> summaryRanges1(int[] nums) { List<String> result = new ArrayList<String>(); if(nums.length<1) return result; int start = nums[0]; int end = 0; int i = 0; while(i<=nums.length-1){ if(i+1 == nums.length || nums[i+1] != nums[i]+1 ){ end = nums[i]; if(end == start){ result.add(Integer.toString(start)); }else{ String s = Integer.toString(start) + "->" + Integer.toString(end); result.add(s); } if(i <nums.length-1) start = nums[i+1]; } i++; } return result; }
20b252df-0da5-4097-800f-b163722ad9f4
3
public String toString() { ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append("username", this.username) .append("enabled", this.enabled) .append("accountExpired", this.accountExpired) .append("credentialsExpired", this.credentialsExpired) .append("accountLocked", this.accountLocked); if (roles != null) { sb.append("Granted Authorities: "); int i = 0; for (Role role : roles) { if (i > 0) { sb.append(", "); } sb.append(role.toString()); i++; } } else { sb.append("No Granted Authorities"); } return sb.toString(); }
7bed44a0-566d-4d95-a04e-f862328e9892
7
public int getAxisWidth(Graphics g) { int i; width = 0; if (minimum == maximum) return 0; if (dataset.size() == 0) return 0; calculateGridLabels(); exponent.setText(null); if (label_exponent != 0) { exponent.copyState(label); exponent.setText("x10^" + String.valueOf(label_exponent)); } if (orientation == HORIZONTAL) { width = label.getRHeight(g) + label.getLeading(g); width += Math.max(title.getRHeight(g), exponent.getRHeight(g)); } else { for (i = 0; i < label_string.length; i++) { label.setText(" " + label_string[i]); width = Math.max(label.getRWidth(g), width); } max_label_width = width; width = 0; if (!title.isNull()) { width = Math.max(width, title.getRWidth(g) + title.charWidth(g, ' ')); } if (!exponent.isNull()) { width = Math.max(width, exponent.getRWidth(g) + exponent.charWidth(g, ' ')); } width += max_label_width; } return width; }
dbc53f3e-35af-42b0-b217-d75b281db3e7
4
Acceptor(TerminateSignaller terminateSignaller, ServerSocket serverSocket, ThreadModelType threadModelType, ExecutorService executorService, Serializer serializer, Class<T> serviceInterface, Class<V> serviceObjectClass, ThreadPoolOverflowPolicy threadPoolOverflowPolicy) throws ServerStartupException { this.terminateSignaller = terminateSignaller; this.serverSocket = serverSocket; this.executorService = executorService; this.serializer = serializer; this.serviceObjectClass = serviceObjectClass; this.reflectionCache = new ReflectionCache(serviceInterface); this.serviceObjectSingleton = null; this.threadModelType = threadModelType; this.threadPoolOverflowPolicy = threadPoolOverflowPolicy; switch (this.threadModelType) { case Singleton: try { serviceObjectSingleton = serviceObjectClass.newInstance(); } catch (InstantiationException e) { throw new ServerStartupException("Cannot create service object singleton instance!", e); } catch (IllegalAccessException e) { throw new ServerStartupException("Cannot create service object singleton instance!", e); } break; case InstancePerThread: serviceObjectSingleton = null; break; default: throw new ServerStartupException("Unknown threading model!"); } }
0f43cdfb-111c-4032-9244-dfaf2496abdb
0
@Override public int getColumnCount() { return columnNames.length; }
124a25b1-c44f-43ee-b4ea-ab8696ca70d2
3
public static boolean isGetter(Method method) { if(!method.getName().startsWith("get")) return false; if(method.getParameterTypes().length != 0) return false; if(void.class.equals(method.getReturnType())) return false; return true; }
689a6ae0-3763-4451-ae10-328450d4c598
4
private String postRequest(String URL, String request) throws IOException { HttpPost hp = new HttpPost(URL); //StringEntity ent = new StringEntity(request, "UTF-8"); StringEntity ent = new StringEntity(request, HTTP.UTF_8); hp.setEntity(ent); hp.addHeader("Authorization", "Basic " + authdata); if (sessionId != null) { hp.addHeader("X-Transmission-Session-Id", sessionId); } //HttpResponse response = httpclient.execute(targetHost, hp, localcontext); HttpResponse response = httpclient.execute(targetHost, hp); if (response.getStatusLine().getStatusCode() == 409) { EntityUtils.consume(response.getEntity()); //le kell záratni a korábbi kapcsolatot különben: //HIBA: Invalid use of BasicClientConnManager: connection still allocated. sessionId = response.getFirstHeader("X-Transmission-Session-Id").getValue(); hp.addHeader("X-Transmission-Session-Id", sessionId); //response = httpclient.execute(targetHost, hp, localcontext); response = httpclient.execute(targetHost, hp); } TGetResponse r = null; HttpEntity respEnt = response.getEntity(); StringBuilder sb = new StringBuilder(); if (respEnt != null) { String line; //Scanner sc = new Scanner(respent.getContent()).useDelimiter("\\A"); //BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent())); BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent(), "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } return sb.toString(); }
469a7d9c-1e34-4879-b044-99adf831d735
5
private GenericConverter getRegisteredConverter(Class<?> sourceType, Class<?> targetType, Class<?> sourceCandidate, Class<?> targetCandidate) { ConvertersForPair convertersForPair = converters.get(new ConvertiblePair(sourceCandidate, targetCandidate)); return convertersForPair == null ? null : convertersForPair.getConverter(sourceType, targetType); }
03d502fd-730d-425b-9cfd-4478c9af7aae
9
public int process() { Stack<Character> stack=new Stack<Character>(); InputReader in=new InputReader(getClass().getResourceAsStream("/balexp.txt")); String line=in.readLine(); for(int i=0;i<line.length();i++) { char ch=line.charAt(i); switch(ch) { case '(': case '[': case '{':stack.push(ch); break; case ']': case '}': case ')':if(!stack.isEmpty()) { char top=stack.pop(); if(!doesMatch(top,ch)) return -1; break; } else { return -1; } default:break; } } return 0; }
fbc0dd67-20c1-491b-85fc-5bf6bb831d0a
6
public void executeLookupAction(String base, String sourceLocale, String targetLocale){ log("lookup in base \"" + base + "\" from locale \"" + sourceLocale + "\" to locale \"" + targetLocale + "\":"); log(); log("reading target word storage from disk..."); WordStorage sourceWordStorage = (WordStorage)WordStorage.loadFromFile(WordStorage.getFileName(base, sourceLocale)); if(sourceWordStorage == null) err("could not read target word storage!"); log("reading target word storage from disk..."); WordStorage targetWordStorage = (WordStorage)WordStorage.loadFromFile(WordStorage.getFileName(base, targetLocale)); if(targetWordStorage == null) err("could not read target word storage!"); log(); log("reading dictionary from disk..."); Dictionary dictionary = (Dictionary)Dictionary.loadFromFile(Dictionary.getFileName(base, sourceLocale, targetLocale)); if(dictionary == null) err("could not read dictionary data!"); log(); log("listening on stdin... (type words here)\n"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; try { while ((s = in.readLine()) != null && s.length() != 0){ lookup(s, sourceWordStorage, targetWordStorage, dictionary); log(); } } catch (IOException ex) { err("could not read from stdin!"); } log("lookup in base \"" + base + "\" from locale \"" + sourceLocale + "\" to locale \"" + targetLocale + "\" done."); }
fa41a8e8-6a9f-4129-9bbe-c3c24f975fb1
9
public BadNetwork(Channel leftIn, Channel leftOut, Channel rightIn, Channel rightOut) { leftIn_ = leftIn; leftOut_ = leftOut; rightIn_ = rightIn; rightOut_ = rightOut; currentState = Status.NOMSG; /* Swing */ netLbl = new JLabel("Network"); netBtnFail = new JButton("Failure"); netBtnSuccess = new JButton("Success"); netBtnTimeout = new JButton("Timeout"); disableButtons(); add(netLbl); add(netBtnSuccess); add(netBtnFail); add(netBtnTimeout); netLbl.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnFail.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnSuccess.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnTimeout.setAlignmentX(Component.CENTER_ALIGNMENT); setPreferredSize(Config.NET_SIZE); setLayout(new GridLayout(4,3)); //setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createMatteBorder(1, 2, 1, 1,Color.black)); /* The Java implementation has to keep track of "happens-before" events * in order to execute the correct sequence of events according to specific input events */ /* In the event that FAILURE occurs */ netBtnFail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: leftOut_.send(new Message(Message.Type.FAILURE)); break; case MSGRIGHT: rightOut_.send(new Message(Message.Type.FAILURE)); break; } } catch (InterruptedException ie) {} } }); /* In the event that SUCCESS occurs */ netBtnSuccess.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: rightOut_.send(transitionLeftMsg); break; case MSGRIGHT: leftOut_.send(transitionRightMsg); break; } } catch (InterruptedException ie) {} } }); /* In the event that TIMEOUT occurs */ netBtnTimeout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: leftOut_.send(new Message(Message.Type.TIMEOUT)); break; case MSGRIGHT: rightOut_.send(new Message(Message.Type.TIMEOUT)); break; } } catch (InterruptedException ie) {} } }); }
142682aa-1dcb-4887-a50f-c151b7275535
3
private static void printCharacters(ArrayList<Character> characters) { Comparator<Character> chars = new Comparator<Character>() { // TODO compares Characters by level, strength and armour // note that this soln isn't quite correct, // find the bug and fix it @Override public int compare(Character char1, Character char2) { int retval = Integer.valueOf(char1.getLevel()).compareTo(char2.getLevel()); if (retval == 0) { retval = Integer.valueOf(char1.getStrength()).compareTo(char2.getStrength()); if (retval == 0) { retval = Integer.valueOf(char1.getArmour()).compareTo(char2.getArmour()); } } return retval; } }; Collections.sort(characters, chars); for (Character character : characters) { //TODO how do I print out the character's armour? System.out.println("Level: " + character.getLevel() + ", Strength " + character.getStrength() + ", Armour: " + character.getArmour() + ", Race: " + character.getRace()); } }
4e73f744-b772-4cbf-b284-1df67ff809cf
5
private boolean containsEnemyWool(TeamPlayer p, CTFTeam team) { Wool w = new Wool(this.GoalTeam.getColor()); //Check for wool for (ItemStack m : p.getPlayer().getInventory()) { //If item in inventory is wool if (m != null && m.getType().equals(Material.WOOL)) { System.out.println("Got some wool"); for (CTFTeam t: ((EditTeam)this.GoalTeam).session.getTeams()){ if (t.getColor().getWoolData() == m.getData().getData()){ t.resetFlag(); } } p.getPlayer().getInventory().remove(m); return true; } } return false; }
b39cc7be-83f4-49ba-b43f-bf14593383b5
7
protected void calculateAverageContingencyMatrix() { // Initialize the matrix double[][] newMatrix = new double[super.classesNumber()][super.classesNumber()]; for(int i = 0; i < newMatrix.length; ++i) for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] = 0.0; // Sum all the performances matrixes Iterator<PType> iter = this.performances.iterator(); while( iter.hasNext()) { PType perf = iter.next(); double[][] matrix = perf.getContingencyMatrix(); for(int i = 0; i < newMatrix.length; ++i) { String valI = super.indexToValue(i); for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] += matrix[perf.valueToIndex(valI)][perf.valueToIndex(super.indexToValue(j))]; } } // Make the average for(int i = 0; i < newMatrix.length; ++i) for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] /= this.performances.size(); super.setContingencyMatrix(newMatrix); this.contincencyMatrixSet = true; }
14ebea22-6b09-47e5-946b-a0b7ae93e27c
0
public String getShopUrl() { return shopUrl; }
3e3df11e-fe91-403c-b7d5-995fb1295a72
9
protected static void createDescriptor() { try { InputStream descriptorStream = ResultParserParseControllerGenerated.class.getResourceAsStream(DESCRIPTOR); InputStream table = ResultParserParseControllerGenerated.class.getResourceAsStream(TABLE); boolean filesystem = false; if(descriptorStream == null && new File("./" + DESCRIPTOR).exists()) { descriptorStream = new FileInputStream("./" + DESCRIPTOR); filesystem = true; } if(table == null && new File("./" + TABLE).exists()) { table = new FileInputStream("./" + TABLE); filesystem = true; } if(descriptorStream == null) throw new BadDescriptorException("Could not load descriptor file from " + DESCRIPTOR + " (not found in plugin: " + getPluginLocation() + ")"); if(table == null) throw new BadDescriptorException("Could not load parse table from " + TABLE + " (not found in plugin: " + getPluginLocation() + ")"); descriptor = DescriptorFactory.load(descriptorStream, table, filesystem ? Path.fromPortableString("./") : null); descriptor.setAttachmentProvider(ResultParserParseControllerGenerated.class); } catch(BadDescriptorException exc) { notLoadingCause = exc; Environment.logException("Bad descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("Bad descriptor for " + LANGUAGE + " plugin", exc); } catch(IOException exc) { notLoadingCause = exc; Environment.logException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); } }
623fea8b-dc20-4157-8084-cf1cd27be20b
1
@Override public int compare(StopRange arg0, StopRange arg1) { int stops1 = arg0.end - arg1.start; int stops2 = arg1.end - arg1.start; int rs = Integer.compare(stops1, stops2); if(rs == 0) { rs = Integer.compare(arg0.start, arg1.start); } return rs; }
ee6a1e15-ea94-4492-83ad-ea840412887a
0
public void update() { value = neighbours.size(); }
0eaf84f6-20f8-4f1e-a0b0-178d910e3eeb
1
public boolean EliminarAfecta(Afecta p){ if (p!=null) { cx.Eliminar(p); return true; }else { return false; } }
0b3bd67a-3bb5-44ee-8df8-14cda4344e70
4
public static int maxProfit(int[] prices) { int profit=0; if(prices.length <=0) return profit; int minPrice=prices[0]; for(int i=0;i<prices.length;i++){ profit=prices[i]-minPrice>profit?prices[i]-minPrice:profit; minPrice=prices[i]<minPrice?prices[i]:minPrice; } return profit; }
c6e14828-cccd-4819-8f52-262e3d54c319
2
public void set(String seqStr) { if( seqStr == null ) { length = 0; nmer = 0; } else { nmer = 0; setLength(seqStr.length()); // Create binary sequence char seqChar[] = seqStr.toCharArray(); int i; for( i = 0; i < length; i++ ) rol(seqChar[i]); } }
d46ca780-069e-443b-8eb1-6266c0447d8f
4
public double value(StateObservation a_gameState) { boolean gameOver = a_gameState.isGameOver(); Types.WINNER win = a_gameState.getGameWinner(); double rawScore = a_gameState.getGameScore(); if(gameOver && win == Types.WINNER.PLAYER_LOSES) rawScore += HUGE_NEGATIVE; if(gameOver && win == Types.WINNER.PLAYER_WINS) rawScore += HUGE_POSITIVE; return rawScore; }
8d4efed2-bfa7-4e12-a064-b9aaca43c8e3
2
public ZElement chercheElement(int x, int y) { for (int i = zelements.size() - 1; i >= 0; i--) if (getElement(i).isSelected(x, y)) return getElement(i); return null; }
3be76cc9-ddb5-490e-bdfe-5f03b1d9f88b
3
public void draw(int windowX, int windowY, int xStart, int yStart){ for (int x = 0; x < Standards.MAP_TILES_TO_DRAW; x++){ for (int y = 0; y < Standards.MAP_TILES_TO_DRAW; y++){ int cx = x + xStart; int cy = y + yStart; if (isOnMap(cx, cy)){ int drawX = x * Standards.TILE_SIZE; int drawY = y * Standards.TILE_SIZE; getTileAtCoords(cx, cy).draw(drawX, drawY); } } } }
84475a6a-a5a1-41c8-b8e6-6c2ad80a826c
4
public void notifyAdd(UpdateTag... tags) { if (updateExec == null || updateExec.done) { updateExec = new UpdateCall(); SwingUtilities.invokeLater(updateExec); } for (UpdateTag ut : tags) { if (!updateExec.mods.contains(ut)) updateExec.mods.add(ut); } }
692fb200-0348-4e82-8ba8-86600ff2912d
7
@Override public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); MultipartRequest multi = null; int sizeLimit = 10 * 1024 * 1024 ; @SuppressWarnings("deprecation") String savePath = request.getRealPath("/upload"); try{ multi=new MultipartRequest(request, savePath, sizeLimit, "utf-8", new DefaultFileRenamePolicy()); }catch (Exception e) { e.printStackTrace(); } String filename = multi.getFilesystemName("filename"); String title = multi.getParameter("title"); String writer = multi.getParameter("writer"); int count=0; String content = multi.getParameter("content"); String regip = request.getRemoteAddr(); if(title ==""||title==null) System.out.println("title is null"); if(writer==""||writer==null) System.out.println("writer is null"); if(content==""||content==null) System.out.println("content is null"); Board article = new Board(); article.setRegip(regip); article.setTitle(title); article.setWriter(writer); article.setContent(content); article.setCount(count); article.setFilename(filename); BoardDao.getInstance().insertArticle(article); return "insert.jsp"; }
a423f063-020f-4952-a13a-1c7fcdfb1991
0
@Override public String getName() { return NAME; }
8be7dff9-0460-4c9e-9995-1948549389ec
3
public Base(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "href": href = Href.parse(this, v); break; case "target": target = Target.parse(this, v); break; } } }
15561e20-8a0f-46b5-9e0f-5acca2ce3240
7
@Override protected void doAction(int option) { switch (option) { case 1: listAllSongs(); //lister alle sange op break; case 2: songSearch(); //søger en bestemt sang break; case 3: addSong(); //tilføjer en sang break; case 4: updateSong(); break; case 5: removeSong(); //fjerner en sang break; case 6: checkSongs(); break; case EXIT_VALUE: doActionExit(); } }
a81ebef1-fc7d-4b30-956a-3a5327a63cc4
8
static public List<Class<?>> getMapTypes(String str_className, String str_fieldName) { List<Class<?>> lcla_types = new ArrayList<Class<?>>(); try { Class<?> lcl_class = Class.forName(str_className); Field lcl_f = lcl_class.getDeclaredField(str_fieldName); Type lcl_type = lcl_f.getGenericType(); if (lcl_type instanceof ParameterizedType) { ParameterizedType lcl_pType = (ParameterizedType) lcl_type; // Type lcl_rawType = lcl_pType.getRawType(); // Class lcl_argType = // (Class)lcl_pType.getActualTypeArguments()[0]; for (Type lcl_classT : lcl_pType.getActualTypeArguments()) { lcla_types.add((Class<?>) lcl_classT); } return lcla_types; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
f29cdc5b-a001-4299-9044-bfea0bef5fb4
7
private void moveToNextParam() { JTextComponent tc = ac.getTextComponent(); int dot = tc.getCaretPosition(); int tagCount = tags.size(); if (tagCount==0) { tc.setCaretPosition(maxPos.getOffset()); deactivate(); } Highlight currentNext = null; int pos = -1; List<Highlight> highlights = getParameterHighlights(); for (int i=0; i<highlights.size(); i++) { Highlight hl = highlights.get(i); // Check "< dot", not "<= dot" as OutlineHighlightPainter paints // starting at one char AFTER the highlight starts, to work around // Java issue. Thanks to Matthew Adereth! if (currentNext==null || currentNext.getStartOffset()</*=*/dot || (hl.getStartOffset()>dot && hl.getStartOffset()<=currentNext.getStartOffset())) { currentNext = hl; pos = i; } } // No params after caret - go to first one if (currentNext.getStartOffset()+1<=dot) { int nextIndex = getFirstHighlight(highlights); currentNext = highlights.get(nextIndex); pos = 0; } // "+1" is a workaround for Java Highlight issues. tc.setSelectionStart(currentNext.getStartOffset()+1); tc.setSelectionEnd(currentNext.getEndOffset()); updateToolTipText(pos); }
0077f2c8-b5d8-4690-9b44-85d1cb933447
8
public SetDeck() { try { Gson g = new Gson(); URL url = new URL("http://128.199.235.83/icw/?q=icw/service/all_ic_of&user=624"); try { HashMap<String, ArrayList<Double>> temp = g.fromJson(new InputStreamReader(url.openStream()), HashMap.class ); ArrayList<Double> cardString = temp.get("data"); try { wallpaper2 = ImageIO.read(new File("wallpaper2.png")); } catch (IOException e1) { e1.printStackTrace(); } cardHolder = new CardHolder(CardHolder.DECK, false); deckHolder = new CardHolder(CardHolder.DECK, false); /* { public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(wallpaper2, 0 , 0 ,this.getWidth(), this.getHeight(), this); } }; */ for(int i = 0; i < cardString.size(); i++) { cardHolder.add(new Card(cardString.get(i).intValue())); } url = new URL("http://128.199.235.83/icw/?q=icw/service/get_deck&user=624"); temp = g.fromJson(new InputStreamReader(url.openStream()), HashMap.class); ArrayList<Double> deckString = temp.get("data"); if(deckString != null) { for(int i = 0; i < deckString.size(); i++) { deckHolder.add(new Card(deckString.get(i).intValue())); } } DropHandler handler = new DropHandler(); DropTarget dropTarget = new DropTarget(cardHolder, DnDConstants.ACTION_MOVE, handler, true); cardHolder.setPreferredSize(new Dimension(328, 768)); cardHolder.setLayout(new WrapLayout(FlowLayout.LEFT, 5, 5)); deckHolder.setPreferredSize(new Dimension(328, 768)); deckHolder.setLayout(new WrapLayout(FlowLayout.LEFT, 5, 5)); this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); this.add(new JScrollPane(cardHolder)); this.add(new JScrollPane(deckHolder)); JButton submit = new JButton("Submit"); submit.setFont(new Font("Tahoma", Font.BOLD, 14)); submit.setForeground(Color.BLACK); submit.setBackground(Color.PINK); submit.setBounds(600,200,200,200 ); submit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub JButton b = (JButton) arg0.getSource(); JPanel panel = (JPanel) b.getParent(); SetDeck s = (SetDeck) panel.getParent(); Component [] c = s.deckHolder.getComponents(); int [] card = new int[c.length]; for(int i = 0; i < card.length; i++) { Card cd = (Card) c[i]; System.out.println(cd.getSize()); card[i] = cd.ic_id; } System.out.println(Arrays.toString(card)); try { String URLString = "http://128.199.235.83/icw/?q=icw/service/set_deck&user=624&pass=90408&deck="+Arrays.toString(card); URLString = URLString.replace(" ", ""); URL dest = new URL(URLString); InputStream is = dest.openStream(); // is = new URL(url).openStream(); Gson gs = new Gson(); JsonObject job = gs.fromJson(new InputStreamReader(is), JsonObject.class); System.out.println("STATUS: "+job.get("status").getAsInt()); System.out.println("MSG: "+job.get("msg").getAsString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); JPanel display = new JPanel(){ public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(wallpaper2, 0 , 0 ,this.getWidth(), this.getHeight(), this); } }; display.setPreferredSize(new Dimension(400, 768)); display.add(submit); JButton back = new JButton("Back"); back.setFont(new Font("Tahoma", Font.BOLD, 14)); back.setForeground(Color.BLACK); back.setBackground(Color.PINK); back.setBounds(600,450,200,200 ); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { MainMenu.setDeck.dispose(); Main.main.setVisible(true); } }); display.add(back); this.add(display); } catch (JsonSyntaxException | JsonIOException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
12c459b0-ac65-4062-8f4e-56be324ae1f4
6
public void generateHorizontalCorridor(MapRegion room1, MapRegion room2, String[][] dungeon) { // Etäisyys lähekkäimpien seinien välillä int distance = room2.getX1() - room1.getX2(); // Valitaan alku- ja loppukoordinaatit siten, että polku ei koskaan kulje huoneen kulmasta int startY = Main.rand.nextInt(room1.getY2() - room1.getY1() - 2) + room1.getY1() + 1; int endY = Main.rand.nextInt(room2.getY2() - room2.getY1() - 2) + room2.getY1() + 1; int x = room1.getX2(), y = startY; // Kuljetaan ensin puoleen väliin vaakasuunnassa for(int i = 0; i < distance/2; i++) dungeon[x++][y] = "."; // Jos tarvii, siirrytään pystysuunnassa endY:n määrittämään y-koordinaattiin if (startY < endY) while (y != endY) dungeon[x][y++] = "."; else if (startY > endY) while (y != endY) dungeon[x][y--] = "."; // Siirrytään loppuun asti vaakasuunnassa while(x != room2.getX1()) dungeon[x++][y] = "."; }
209982d3-1a86-4900-be82-b58d8e2159a8
4
private String pickMobSpawner(Random var1) { int var2 = var1.nextInt(4); return var2 == 0?"Skeleton":(var2 == 1?"Zombie":(var2 == 2?"Zombie":(var2 == 3?"Spider":""))); }
8d7a019e-d840-45ba-ac90-2d8e8474577e
0
public Type getType() { return this.type; }
36d81adc-33ec-4ff9-8a3f-0c87f64b69c6
1
public boolean isStore(Chest chest){ if(chest==null) return false; return stores.containsKey(chest); }
1ad8f53b-e30e-4e1a-9823-26c585d2df26
8
public void remove(Object removedObject) { Object[] tempArray; int numberOfFindElements = 0; if (object == null||object.length==0) { throw new IllegalArgumentException( "There is no elements in Arraylist! Nothing could be deleted!"); } for (int i = 0; i < object.length; i++) { if (object[i].equals(removedObject)) { numberOfFindElements++; } } tempArray = new Object[object.length - numberOfFindElements]; for (int i = 0, j = 0; i < tempArray.length && j < object.length; j++) { if (object[j].equals(removedObject)) { continue; } tempArray[i] = object[j]; i++; } if (numberOfFindElements == 0) { System.out.println("No such elements!"); return; } object = tempArray; }
bc77054a-0897-4b38-a40c-68c7245ae64a
3
private String login(String username,String password,String randCode) throws IOException{ URL url = new URL("https://kyfw.12306.cn/otn/login/loginAysnSuggest?loginUserDTO.user_name="+username+"&userDTO.password="+password+"&randCode="+randCode); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(Utils.getSsf()); try { InputStream is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); String res = br.readLine(); if(res==null)return null; String tmp = res.split("\"messages\":")[1]; String message = tmp.substring(0,tmp.lastIndexOf(",\"validateMessages\":")); if(message!=null && !message.equals("")){ return "0:"+message; } return getSessionId(con); } finally{ con.disconnect(); } }
644e0c73-1d19-40fd-b706-589b15a3c795
2
@Override public void update(){ if(hitPoints <= 0) die(); super.update(); for(Shield shield : shields) shield.update(); }
bd19657b-9091-4157-85ad-4088ddbe8743
4
public GridCell cell(int row, int col) { if (row < rows && col < cols) { if (row < 0 || col < 0) { return null; } return gridCells[row][col]; } return null; }
048d5916-98a8-4c98-9bc8-7b561a7730b5
0
@Test public void shouldReturnAreaOfTenForTwoByFiveRectangle(){ Rectangle rectangle = new Rectangle(5, 2, 0, 0); assertEquals(10, rectangle.area()); }
ab784abe-2d8a-45bb-9070-3928f949b5fa
2
* @param active Whether or not the active version of the color is needed. * @return The background color. */ public static Color getListBackground(boolean selected, boolean active) { if (selected) { Color color = UIManager.getColor("List.selectionBackground"); //$NON-NLS-1$ if (!active) { color = Colors.adjustSaturation(color, -0.5f); } return color; } return Color.WHITE; }
40261a74-fb3c-485f-8b36-045dae74a4e2
9
public static boolean ananlysisNJCM(AnalysisOutput o, List<AnalysisOutput> candidates) throws MorphException { int strlen = o.getStem().length(); boolean success = false; if(strlen>3&&(o.getStem().endsWith("에서이")||o.getStem().endsWith("부터이"))) { o.addElist(o.getStem().substring(strlen-1)); o.setJosa(o.getStem().substring(strlen-3,strlen-1)); o.setStem(o.getStem().substring(0,strlen-3)); success = true; }else if(strlen>5&&(o.getStem().endsWith("에서부터이"))) { o.addElist(o.getStem().substring(strlen-1)); o.setJosa(o.getStem().substring(strlen-5,strlen-1)); o.setStem(o.getStem().substring(0,strlen-5)); success = true; } if(!success) return false; WordEntry entry = null; if(success&&(entry=DictionaryUtil.getAllNoun(o.getStem()))!=null) { if(entry.getFeature(WordEntry.IDX_NOUN)=='2') { o.setCNoun(entry.getCompounds()); } o.setScore(AnalysisOutput.SCORE_CORRECT); } o.setPatn(PatternConstants.PTN_NJCM); o.setPos(PatternConstants.POS_NOUN); candidates.add(o); return true; }
337f5c5f-d51d-47aa-8c32-c18dc351470f
1
public void removePreviousGlied() { SchlangenGlied oldPreviousGlied = previousGlied; previousGlied = null; if (oldPreviousGlied != null) { previousGlied.removeNextGlied(); } }
79f18a1e-cb85-4586-8961-8da9b228576e
6
private void escribirTeam(Piloto pilot) { int lectura = 0; String cadenainicio = ""; String cadenamedio = ""; String cadenafinal = ""; String nuevoarchivo = ""; Scanner s; try { s = new Scanner(pilot.getFile()); while (s.hasNext()) { String texto = s.nextLine(); if (texto.contains("Number")) { lectura = 1; } else { if (lectura == 0) { cadenainicio = cadenainicio.concat(texto + '\n'); } } if (texto.contains("Engine")) { lectura = 2; } if (lectura == 2) { cadenafinal = cadenafinal.concat(texto + '\n'); } } s.close(); cadenamedio = ("Number=" + pilot.getNumber() + '\n' + "Team=" + "\"" + pilot.getTeam() + "\"" + '\n' + "PitGroup=" + "\"" + pilot.getPitgroup() + "\"" + '\n' + "Driver=" + "\"" + pilot.getName() + "\"" + '\n' + "Description=" + "\"" + pilot.getNumber() + "-" + pilot.getName() + "\"" + '\n'); nuevoarchivo = pilot.getFile().getPath(); pilot.getFile().delete(); Escribrlineas(cadenainicio, nuevoarchivo); Escribrlineas(cadenamedio, nuevoarchivo); Escribrlineas(cadenafinal, nuevoarchivo); } catch (Exception e) { ImageIcon icon = new ImageIcon(getClass().getResource("Elementos/Imagenes/PitStopErrorIcon.png")); JOptionPane.showMessageDialog(null, "Error Archivo no encontrado", "Editar Equipo - ERROR AL ESCRIBIR", JOptionPane.ERROR_MESSAGE, icon); } }
ba96067d-e7df-4879-90e9-42f6836d0c90
3
@Override public int observed(String sequence) { char seq[] = sequence.toUpperCase().toCharArray(); int cpg = 0; for( int pos = 0; pos < (seq.length - 1); pos++ ) if( (seq[pos] == 'C') && (seq[pos + 1] == 'G') ) cpg++; return cpg; }
2d27ba1d-f487-46e2-8643-f8c0a12a76e0
3
@Override public UserDTO getUserByLogin(String login, String pass) throws SQLException { Session session = null; UserDTO user = null; try { session = HibernateUtil.getSessionFactory().openSession(); user = (UserDTO) session.createCriteria(UserDTO.class) .add(Restrictions.and( Restrictions.like("login", login), Restrictions.like("pass", pass) )) .setMaxResults(1).uniqueResult(); } catch (Exception e) { System.err.println("Error while getting user by login and password!"); } finally { if (session != null && session.isOpen()) { session.close(); } } return user; }
f9c95030-0a51-4a56-b25f-6a1266c8b087
2
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String data; try { if (request.getParameter("id") == null) { data = "{\"error\":\"id is mandatory\"}"; } else { ClienteDao_Mysql oClienteDAO = new ClienteDao_Mysql(Conexion.getConection()); ClienteBean oCliente = new ClienteBean(); oCliente.setId(Integer.parseInt(request.getParameter("id"))); oClienteDAO.get(oCliente); data = new Gson().toJson(oCliente); } return data; } catch (Exception e) { throw new ServletException("ClienteGetJson: View Error: " + e.getMessage()); } }
1f46f124-c302-469f-8162-8b0cd48e9b85
7
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length < 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.setWarp + " (name) [private]"); return; } String name = arg1[0]; // sends plugin message to BungeeSuiteBukkit to get player pos ProxiedPlayer player = (ProxiedPlayer) sender; ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(b); try { out.writeUTF("SetWarp"); out.writeUTF(sender.getName()); out.writeUTF(name); } catch (IOException e) { e.printStackTrace(); } if (arg1.length > 1 && arg1[1].equalsIgnoreCase("private")) { try { out.writeBoolean(false); } catch (IOException e) { e.printStackTrace(); } } else { try { out.writeBoolean(true); } catch (IOException e) { e.printStackTrace(); } } player.getServer().sendData("BungeeSuiteMC", b.toByteArray()); }
b65af617-8c70-4a59-b74d-c3f1216024a2
3
public boolean load(String audiofile) { try { setFilename(audiofile); sample = AudioSystem.getAudioInputStream(getURL(filename)); clip.open(sample); return true; } catch (IOException e) { return false; } catch (UnsupportedAudioFileException e) { return false; } catch (LineUnavailableException e) { return false; } }
f8fd0415-b8f2-4097-bb66-3c6d1895e920
5
@Override public void processEvent(Event event) { if(event.getHeader().getEventType().equals(LogEventType.ROTATE)) { try{ processRotateEvent(event); } catch (SQLException ex) { } } else if(event.getData() instanceof RowsIEventData) { if(EoiContext.isEoi(((RowsIEventData) event.getData()).getTableId())) { processRowEvent(event); } } else if(event.getHeader().getEventType().equals(LogEventType.TABLE_MAP)) { processTableMapEvent(event); } }
8530ad90-cf54-429f-9aad-d745ea56ae45
9
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
eedc4b08-0a67-4762-92fb-f63e6d9ca5e5
4
public JsonObject toJSON() { JsonObject obj = new JsonObject(); Gson gson = new Gson(); obj.addProperty("title", title); obj.addProperty("project", project); // Add contributors for(String key: contributors.keySet()) { if(!contributors.get(key).isEmpty()) obj.add(key, gson.toJsonTree(contributors.get(key))); } JsonArray jsonPages = new JsonArray(); obj.add("pages", jsonPages); for(Page page: pages) { jsonPages.add(page.toJSON()); } JsonArray jsonImages = new JsonArray(); obj.add("images", jsonImages); for(Image image: images) { jsonImages.add(image.toJSON()); } return obj; }
c6b1b139-006f-4dfe-ae5e-a6949ab97c43
0
private void initView() { super.setLayout(new BorderLayout()); initGrammarTable(); JPanel rightPanel = initRightPanel(); JSplitPane mainSplit = SplitPaneFactory.createSplit(environment, true, 0.4, new JScrollPane(grammarTable), rightPanel); add(mainSplit, BorderLayout.CENTER); }
2175f529-a726-4ee1-9c13-64aaa57c8975
5
public static List<Actor> getActors(String urlString) throws TvDbException { List<Actor> results = new ArrayList<>(); Actor actor; Document doc; NodeList nlActor; Node nActor; Element eActor; try { doc = DOMHelper.getEventDocFromUrl(urlString); if (doc == null) { return results; } } catch (WebServiceException ex) { LOG.trace(ERROR_GET_XML, ex); return results; } nlActor = doc.getElementsByTagName("Actor"); for (int loop = 0; loop < nlActor.getLength(); loop++) { nActor = nlActor.item(loop); if (nActor.getNodeType() == Node.ELEMENT_NODE) { eActor = (Element) nActor; actor = new Actor(); actor.setId(DOMHelper.getValueFromElement(eActor, "id")); String image = DOMHelper.getValueFromElement(eActor, "Image"); if (!image.isEmpty()) { actor.setImage(URL_BANNER + image); } actor.setName(DOMHelper.getValueFromElement(eActor, "Name")); actor.setRole(DOMHelper.getValueFromElement(eActor, "Role")); actor.setSortOrder(DOMHelper.getValueFromElement(eActor, "SortOrder")); results.add(actor); } } Collections.sort(results); return results; }
d9300bf6-101c-4751-a52a-96bbae633001
0
public static String createPath(String folderName, String fileName) { return folderName + System.getProperties().getProperty("file.separator") + fileName; }
9a8ba1c9-4017-4c94-80c9-820b3927fe86
9
private void removeDataNode(DFSNode dataNode){ ///// System.out.println("dataNode is " + dataNode.getIp() + ":" + dataNode.getPort()); ///// for(DFSBlkDataNode dbdn : this.dataNodes){ if(dbdn.getIp().equals(dataNode.getIp()) && dbdn.getPort() == dataNode.getPort()){ this.dataNodes.remove(dbdn); break; } } for(String s : this.blkName2dataNodesMap.keySet()){ List<DFSNode> blkDataNodes = this.blkName2dataNodesMap.get(s); for(DFSNode dn : blkDataNodes){ if(dn.getIp().equals(dataNode.getIp()) && dn.getPort() == dataNode.getPort()){ blkDataNodes.remove(dn); /* Copy the block originally on dataNode to other DataNode */ DFSNode newDataNode = this.assignLocation(s); DFSNode srcDataNode = this.assignSource(s); List<DFSNode> destAndSrc = new ArrayList<DFSNode>(2); destAndSrc.add(newDataNode); destAndSrc.add(srcDataNode); DFSMessage copyBlkNameNodeReq = new DFSMessage(DFSMessageType.CopyBlkNameNodeReqMsg, s, destAndSrc); DFSMessage copyBlkDataNodeResp = DFSMessageSender.sendMessage(copyBlkNameNodeReq, newDataNode); if(copyBlkDataNodeResp == null || copyBlkDataNodeResp.getType() != DFSMessageType.CopyBlkDataNodeRespMsg){ System.out.println("Failed to send Copy-Block-Request (Block: " + s + ") to DataNode (" + newDataNode.getIp() + ":" + newDataNode.getPort() + ")"); }else{ System.out.println("Sent Copy-Block-Request (Block: " + s + ") to DataNode (" + newDataNode.getIp() + ":" + newDataNode.getPort() + ")"); } break; } } } return; }
292daf4a-17b7-45ea-9347-e5d7bcc8e7f6
0
public float getK() { return k; }