method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0e4db545-214f-45e6-9eb0-50d74a9bb974
4
public Object next() { if(this.selection.size() == 0 || this.weight.size() == 0 || this.weightsum.size() == 0) return null; Integer j = r.nextInt(this.weightsum.get(this.weightsum.size()-1)); Integer i; for(i = 0; j > this.weightsum.get(i); i++); return this.selection.get(i); }
97b5e769-9910-4b09-992e-91586c0cbf6c
3
public static void benchmarkByteLargeArrayInANewThread() { System.out.println("Benchmarking ByteLargeArray in a new thread."); final long length = (long) Math.pow(2, 32); long start = System.nanoTime(); final ByteLargeArray array = new ByteLargeArray(length); System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec"); final int iters = 5; final byte one = 1; for (int it = 0; it < iters; it++) { start = System.nanoTime(); Thread thread = new Thread(new Runnable() { public void run() { for (long k = 0; k < length; k++) { array.setByte(k, one); array.setByte(k, (byte) (array.getByte(k) + one)); } } }); thread.start(); try { thread.join(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 + " sec"); } }
fc8189b0-caad-4c72-8e25-71078ff03fec
2
public byte[] toByteArray(){ try{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; out = new ObjectOutputStream(bos); out.writeObject(this); byte[] yourBytes = bos.toByteArray(); try{ bos.close(); out.close(); }catch(Exception e){System.out.println("A Memory Leak Has Happened!");e.printStackTrace();} return yourBytes; }catch(Exception e){ return null; } }
5701109c-b729-47b6-9604-4325d3f38ed7
8
static int[] f(int N){ int a=(int)sqrt(N); if(abs(a-sqrt(N))<1e-10)return new int[]{a%2==0?a:1,a%2==0?1:a}; if(a%2==0)return new int[]{N-a*a<=a+1?a+1:(a+1)*(a+1)-N+1,N-a*a<=a+1?N-a*a:a+1}; return new int[]{N-a*a<=a+1?N-a*a:a+1,N-a*a<=a+1?a+1:(a+1)*(a+1)-N+1}; }
690b9ffa-a33c-4d51-a6bd-1c2aec40edb9
6
* @param password Character-array containing the password * @return true if the login-data is correct, false otherwise */ private boolean checkLogIn(String accountname, char[] password) { if (accountname.equals(_adminName) & new String(password).equals(_adminPass)) { adminLogin(); return false; } if (accountname.equals("")) { label_lErr.setText("Falscher Benutzername oder falsches Passwort!"); return false; } String userlist = ""; try { userlist = CSVHandling.readCSVString(Sims_1._usersFileName); } catch (Exception e) { e.printStackTrace(); } if (userlist.contains(accountname)) { String userPw = ""; try { userPw = CSVHandling.readCSVStringArr(Sims_1._dataFolderName + "/" + accountname + "/" + Sims_1._profileFileName)[1]; //loggedinas.setText("Eingeloggt als: " + accountname); // by nadir , currentuser } catch (Exception e) { e.printStackTrace(); } if (userPw.contentEquals(new String(password))) { return true; } } label_lErr.setText("Falscher Benutzername oder falsches Passwort!"); return false; }
0103bcd0-9a86-432f-a81c-855c7ab6e3a5
8
@Override public boolean onCommand(CommandSender sender, Command cmd, String arg2, String[] args) { if (args.length < 1) { // No args, display list sender.sendMessage(ChatColor.YELLOW + "Muted players:"); String plrs = ""; for (String plr : plugin.mutedplrs.keySet()) { plrs += plr + ", "; } sender.sendMessage(ChatColor.YELLOW + plrs); sender.sendMessage(ChatColor.YELLOW + "Use /mute <player> to mute someone."); return true; } else if (args.length == 1) { // One argument, mute the player String tomute; Player todeafen = Bukkit.getServer().getPlayer(args[0]); if (todeafen != null) { tomute = todeafen.getName(); } else { sender.sendMessage(ChatColor.RED + args[0] + " is not online. Make sure name is exactly right"); tomute = args[0]; } if (sender.hasPermission("warhub.moderator")) { if (plugin.mutedplrs.containsKey(tomute)) { plugin.mutedplrs.remove(tomute); sender.sendMessage(ChatColor.YELLOW + tomute + " has been unmuted."); if (PlayerInfo.isPlayer(tomute)) PlayerInfo.toPlayer(tomute).sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { plugin.mutedplrs.put(tomute, 1); sender.sendMessage(ChatColor.YELLOW + tomute + " has been muted."); if (PlayerInfo.isPlayer(tomute)) PlayerInfo.toPlayer(tomute).sendMessage(ChatColor.YELLOW + "You have been muted."); } } else { sender.sendMessage(ChatColor.RED + "You do not have permissions to mute players."); } return true; } return false; }
e07226b8-b672-41e5-9efe-2ac71f212aa2
2
public void omniRandSet(){ rover = head; while(rover != null){ int a = 0; while(a < 25){ rover.randlist[a] = randlist[a]; a++; } rover = rover.next; } }
8cd7bea3-79be-476c-b419-76f92482afd6
3
private static void readDataFile(String fname) { Scanner inFile; File readIn=new File(fname); try { inFile = new Scanner(readIn); int i=0; while(inFile.hasNextLine()){ inFile.nextLine(); i++;//just counting number of lines in file } sequences=new String[i]; i=0; inFile.close(); inFile = new Scanner(readIn); while(inFile.hasNextLine()){ sequences[i]=inFile.nextLine(); i++; } inFile.close(); } catch (FileNotFoundException e) { System.err.println("E:File not found. Exiting..."); System.exit(1); } }
0c594c14-6dea-4647-aed7-c8d55ab34184
5
public static int maxDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); currentLevel.add(root); int count = 0; while (!currentLevel.isEmpty()) { Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); while (!currentLevel.isEmpty()) { TreeNode cur = currentLevel.poll(); if (cur.left != null) nextLevel.add(cur.left); if (cur.right != null) nextLevel.add(cur.right); } currentLevel = nextLevel; count++; } return count; }
2f66631a-4e3f-4f08-a500-b34bdd74dd4e
8
static int process(String line) { int cases = Integer.parseInt(line.trim()); int[][] data = { {21, 0}, {20, 1}, {21, 2}, {21, 3}, {22, 4}, {22, 5}, {23, 6}, {22, 7}, {24, 8}, {24, 9}, {23, 10}, {23, 11} }; String[] sign= {"Aquarius", "Pisces", "Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn"}; for(int c = 1; c <= cases; c++) { String str = readLine().trim(); int month = Integer.parseInt(str.substring(0, 2)); int day = Integer.parseInt(str.substring(2, 4)); int year = Integer.parseInt(str.substring(4)); Calendar gc = new GregorianCalendar(year, month - 1, day); gc.add(Calendar.WEEK_OF_MONTH, 40); month = gc.get(gc.MONTH); day = gc.get(gc.DAY_OF_MONTH); year = gc.get(gc.YEAR); String s = sign[sign.length - 1]; for(int i = 0; i < data.length; i++) { int n = (i + 1)%data.length; if((month == data[i][1] && day >= data[i][0]) || month > data[i][1]) if(month < data[n][1] || (month == data[n][1] && day < data[n][0])) { s = sign[i]; break; } } System.out.println(c+" "+twoPlaces(month+1)+"/"+twoPlaces(day) + "/" +fourPlaces(year)+" "+s.toLowerCase()); } return 0; }
c89f5a2d-cc63-4015-8c35-8c23151b1299
7
public ArrayList<Proveedores> obtenerProveedores(String Identificacion , String nombreIn) { String selection[] = {"Identificacion", "nombre","ID"}; String selection_type[] = {"varchar", "varchar","int"}; String table = "Proveedores"; boolean nombreVacio = !nombreIn.equals(""); boolean identificacionVacia = !Identificacion.equals(""); String restriction = ""; if (nombreVacio && identificacionVacia) { restriction = " where nombre like \"%" + nombreIn + "%\" and Identificacion like \"%" + Identificacion + "%\""; } if (!nombreVacio && identificacionVacia) { restriction = " where Identificacion like \"%" + Identificacion + "%\""; } if (nombreVacio && !identificacionVacia) { restriction = " where nombre like \"%" + nombreIn + "%\""; } ArrayList<String[]> resultadoSet = sQLManager.select_query(selection, selection_type, table, restriction); ArrayList<Proveedores> listaDeProveedores = new ArrayList<>(); for (int i = 0; i < resultadoSet.size(); i++) { String[] resultado = resultadoSet.get(i); String ident = resultado[0]; String nombre = resultado[1]; String ID = resultado[2]; Proveedores proveedor = new Proveedores(ident, nombre , Integer.parseInt(ID)); proveedor.setID(Integer.parseInt(ID)); listaDeProveedores.add(proveedor); } return listaDeProveedores; }
6b82329e-6c94-46cf-b672-acbb44c0c214
6
public boolean pickAndExecuteAnAction() { if(!paused) { // if(orderFood) { // OrderFoodThatIsLow(); // return true; // } // for(Food f : foods.values()) // if(f.state == FoodState.Rejected) { // OrderRejectedFood(f); // return true; // } synchronized(orders) { for(Order o : orders) if(o.state == OrderState.Done) { PlateFood(o); return true; } } synchronized(orders) { for(Order o : orders) if(o.state == OrderState.Pending) { TryToCookFood(o); return true; } } if(checkRevolvingStand) { CheckRevolvingStand(); return true; } } return false; }
af9836f3-a88f-4b31-9c05-1eb80f852449
1
static public void add(String name, GameState gs) { if (!states.containsKey(name)) { states.put(name,gs); } }
e0e5191b-6832-4773-b47a-41f7a19fc834
4
@Test public void testContainsOnlyAdd() { ArrayList<String> operations = new ArrayList<String>(); ArrayList<Integer> vals = new ArrayList<Integer>(); // Add a bunch of values for (int i = 0; i < 100; i++) { int rand = random.nextInt(200); vals.add(rand); operations.add("ints.add(" + rand + ")"); ints.add(rand); } // for i // Make sure that they are all there. for (Integer val : vals) { if (!ints.contains(val)) { System.err.println("contains(" + val + ") failed"); for (String op : operations) System.err.println(op + ";"); dump(ints); fail(val + " is not in the sortedlist"); } // if (!ints.contains(val)) } // for val } // testContainsOnlyAdd()
64187248-2178-4cbd-a082-202cee7beae5
8
public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int contador = 10; int seccion; int asiento; boolean[] asientos = new boolean[10]; for(int i=0;i<10;i++) asientos[i] = false; do{ System.out.printf("\nBienvenido al sistema de reservaciones.\n"); System.out.printf("\nPor favor escriba 1 para Primera Clase.\nPor favor escriba 2 para Economico.\n"); seccion = entrada.nextInt(); if(seccion == 1){ if(asientoDisponible(asientos, 0, 5)){ asiento = asignaAsiento(asientos, 0, 5); contador -= 1; imprimePase(asiento); } else{ System.out.printf("\nLa seccion de Primera Clase esta llena. ¿Desea ser puesto en la seccion Economico?\n"); System.out.printf("\n1)SI\n2)NO\n"); seccion = entrada.nextInt(); if(seccion == 1){ asiento = asignaAsiento(asientos, 5, 10); contador -= 1; imprimePase(asiento); } else{ System.out.printf("\nEl proximo vuelo sale en 3 horas.\n"); } } } else if(seccion == 2){ if(asientoDisponible(asientos, 5, 10)){ asiento = asignaAsiento(asientos, 5, 10); contador -= 1; imprimePase(asiento); } else{ System.out.printf("\nLa seccion Economico esta llena. ¿Desea ser puesto en la seccion de Primera Clase?\n"); System.out.printf("\n1)SI\n2)NO\n"); seccion = entrada.nextInt(); if(seccion == 1){ asiento = asignaAsiento(asientos, 0, 5); contador -= 1; imprimePase(asiento); } else{ System.out.printf("\nEl proximo vuelo sale en 3 horas.\n"); } } } }while(contador > 0); System.out.printf("\nVuelo completo. El proximo vuelo sale en 3 horas.\n"); }
2a94dfda-4770-4e46-8394-d842c8d80fff
2
public void rotate(int[][] matrix) { int n = matrix.length; int tmp; for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { tmp = matrix[i][j]; matrix[i][j] = matrix[n - j - 1][i]; matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; matrix[j][n - i - 1] = tmp; } } }
1bc6d79a-fdd7-4b2e-8d72-8731167aab85
2
@EventHandler public void onPostLogin(PostLoginEvent event) { if (!IRC.sock.isConnected()) return; ProxiedPlayer p = event.getPlayer(); Util.sendUserConnect(p); Util.incrementUid(); String chan = BungeeRelay.getConfig().getString("server.channel"); if (!chan.isEmpty()) Util.sendChannelJoin(p, chan); }
eebb104f-4b11-41b5-a949-0cba5725fa70
3
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(super.toString()); buffer.append('\n'); /** print variables. */ buffer.append("V: "); String[] variables = getVariables(); for (int v = 0; v < variables.length; v++) { buffer.append(variables[v]); buffer.append(" "); } buffer.append('\n'); /** print terminals. */ buffer.append("T: "); String[] terminals = getTerminals(); for (int t = 0; t < terminals.length; t++) { buffer.append(terminals[t]); buffer.append(" "); } buffer.append('\n'); /** print start variable. */ buffer.append("S: "); buffer.append(getStartVariable()); buffer.append('\n'); /** print production rules. */ buffer.append("P: "); buffer.append('\n'); Production[] productions = getProductions(); for (int p = 0; p < productions.length; p++) { buffer.append(productions[p].toString()); buffer.append('\n'); } return buffer.toString(); }
29b2250a-0d22-4d19-9501-40092c3ea1f5
9
public static boolean isValid(Position start, Position temp, ChessBoard board) { Coin c = board.getCoinAt(start); int tem = (c.getColor() == CoinColor.WHITE) ? 1 : -1; if (c instanceof Pawn && ((Pawn) c).readyForPromote()) { if (start.getFile() == temp.getFile()) { return (start.getRank() + tem == (temp.getRank())) && board.getCoinAt(temp) == Coin.Empty; } else if (start.getFile() == temp.getFile() - 1) { return (start.getRank() + tem == (temp.getRank())) && board.getCoinAt(temp) != Coin.Empty; } else if (start.getFile() == temp.getFile() + 1) { return (start.getRank() + tem == (temp.getRank())) && board.getCoinAt(temp) != Coin.Empty; } return false; } return false; }
db15a9b6-1252-466e-b942-4c4666066811
6
private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException { int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile() pw.print("Content-Length: "+pending+"\r\n"); pw.print("\r\n"); pw.flush(); if (requestMethod != Method.HEAD && data != null) { int BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[BUFFER_SIZE]; while (pending > 0) { int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); if (read <= 0) { break; } outputStream.write(buff, 0, read); pending -= read; } } }
187bf637-c921-491e-ac82-b4311abb6ee2
8
public void run() { Socket socket=null; ObjectOutputStream toClient; MazewarPacket packetToClient; MazewarPacket headPacketFromQueue; try{ synchronized(ClientList){ ClientList.wait(); } //System.out.println("Sending STR to..."); synchronized(ClientList){ for(int i=0;i<ClientList.size();i++){ for (int j=0; j<ClientList.size(); j++) { packetToClient = new MazewarPacket(); packetToClient.type=MazewarPacket.MAZEWAR_INITIALIZE_PLAYERS; packetToClient.pointx = ClientList.get(j).pointx; packetToClient.pointy = ClientList.get(j).pointy; packetToClient.name = ClientList.get(j).name; //packetToClient.direction = ClientList.get(j).direction; ClientList.get(i).toClient.writeObject(packetToClient); //System.out.println("...to "+ClientList.get(i).name); } } } synchronized(ClientList){ for(int i=0;i<ClientList.size();i++){ packetToClient = new MazewarPacket(); packetToClient.type=MazewarPacket.MAZEWAR_STR; ClientList.get(i).toClient.writeObject(packetToClient); } } while(game_start){ /*This is no good*/ headPacketFromQueue=QueueList.poll(); if(headPacketFromQueue!=null){ packetToClient = new MazewarPacket(); packetToClient = headPacketFromQueue; //System.out.println("Sending BRC by "+packetToClient.name+"..."); synchronized(ClientList){ for(int i=0;i<ClientList.size();i++){ ClientList.get(i).toClient.writeObject(packetToClient); //System.out.println("...to "+ClientList.get(i).name); } } } } }catch (IOException e) { e.printStackTrace(); } catch(InterruptedException e){ //return; } }
43ccfb57-b579-43a5-b3e8-35c99c802ad1
9
@Override public boolean suspendAccount(String pAdminUsername, String pAdminPassword, String pIPAddress, String pUsernameToSuspend) { if(!pAdminUsername.equals("Admin")) { aLog.info("Error Suspending Account : Incorrect Administrator Username"); return false; } if(!pAdminPassword.equals("Admin")) { aLog.info("Error Suspending Account : Incorrect Administrator Password"); return false; } if(!validate(pIPAddress)) { aLog.info("Error Suspending Account : Invalid IP-address"); return false; } if((pUsernameToSuspend.charAt(0) > 'Z' && pUsernameToSuspend.charAt(0) < 'a') || pUsernameToSuspend.charAt(0) < 'A' || pUsernameToSuspend.charAt(0) > 'z') { aLog.info("Error Suspending Account : Username cannot start with " + pUsernameToSuspend.charAt(0)); return false; } Account tmpAccount = getAccount(pUsernameToSuspend); if(tmpAccount == null) { aLog.info("Error Suspending Account : Username Was Not Found"); tmpAccount = null; return false; } boolean bSuccess = false; synchronized(this) { bSuccess = aDatabase.get(String.valueOf(pUsernameToSuspend.toUpperCase().charAt(0))).remove(tmpAccount); } if(bSuccess) { aLog.info("Player Account suspended :\nUsername \"" + pUsernameToSuspend + "\", Password \"" + tmpAccount.getPassword() + "\", IP-address \"" + tmpAccount.getIPAddress() + "\""); return true; } else { aLog.info("Error Suspending Account : suspension faild"); return false; } }
d8ed5acc-2fa3-4497-a40a-3490a93d87dd
3
public void visitInitStmt(final InitStmt stmt) { final LocalExpr[] targets = stmt.targets(); for (int i = 0; i < targets.length; i++) { if (targets[i] == previous) { if (i > 0) { check(targets[i - 1]); } else { break; } } } }
abc37182-cde0-4b74-8616-7d8d5b4ebc46
3
public static void filter() { splitString = ConfigFileReader.text.split("I:"); for (int i = 1; i < 141; ++i) { //splitString[i] = splitString[i].replaceAll( "[^\\d]", "" ); splitString[i] = splitString[i].replaceFirst(".*?(?=[a-z]?=)", ""); splitString[i] = splitString[i].replace("=", ""); splitString[i] = splitString[i].replace(" ", ""); splitString[i] = splitString[i] + " -> "; } splitString[1] = splitString[1] + "1948"; splitString[2] = splitString[2] + "1962"; splitString[3] = splitString[3] + "1933"; splitString[4] = splitString[4] + "1947"; splitString[5] = splitString[5] + "1938"; splitString[6] = splitString[6] + "1949"; splitString[7] = splitString[7] + "1952"; splitString[8] = splitString[8] + "1925"; splitString[9] = splitString[9] + "1942"; splitString[10] = splitString[10] + "1921:9"; splitString[11] = splitString[11] + "1926:3"; splitString[12] = splitString[12] + "1937"; splitString[13] = splitString[13] + "1927"; splitString[14] = splitString[14] + "1923:1"; splitString[15] = splitString[15] + "1937:2"; splitString[16] = splitString[16] + "1947:10"; splitString[17] = splitString[17] + "1920:6"; splitString[18] = splitString[18] + "1942:1"; splitString[19] = splitString[19] + "1925:4"; splitString[20] = splitString[20] + "1920:7"; splitString[21] = splitString[21] + "1948:1"; splitString[22] = splitString[22] + "1933:1"; splitString[23] = splitString[23] + "1947:1"; splitString[24] = splitString[24] + "1949:1"; splitString[25] = splitString[25] + "1953"; splitString[26] = splitString[26] + "1921"; splitString[27] = splitString[27] + "1921:5"; splitString[28] = splitString[28] + "1948:2"; splitString[29] = splitString[29] + "1923:3"; splitString[30] = splitString[30] + "1933:2"; splitString[31] = splitString[31] + "1947:2"; splitString[32] = splitString[32] + "1937:4"; splitString[33] = splitString[33] + "1949:2"; splitString[34] = splitString[34] + "1954"; splitString[35] = splitString[35] + "1920"; splitString[36] = splitString[36] + "1935:2"; splitString[37] = splitString[37] + "1921:2"; splitString[38] = splitString[38] + "1920:1"; splitString[39] = splitString[39] + "1920:2"; splitString[40] = splitString[40] + "1920:3"; splitString[41] = splitString[41] + "1920:3"; splitString[42] = splitString[42] + "1923:4"; splitString[43] = splitString[43] + "1937:5"; splitString[44] = splitString[44] + "1948:3"; splitString[45] = splitString[45] + "1923:5"; splitString[46] = splitString[46] + "1947:3"; splitString[47] = splitString[47] + "1937:6"; splitString[48] = splitString[48] + "1949:3"; splitString[49] = splitString[49] + "1926"; splitString[51] = splitString[51] + "1935:3"; splitString[52] = splitString[52] + "1936"; splitString[53] = splitString[53] + "1936:1"; splitString[54] = splitString[54] + "1921:3"; splitString[55] = splitString[55] + "1925:3"; splitString[56] = splitString[56] + "1925:6"; splitString[57] = splitString[57] + "1948:4"; splitString[58] = splitString[58] + "1923:6"; splitString[59] = splitString[59] + "1934"; splitString[60] = splitString[60] + "1947:4"; splitString[61] = splitString[61] + "1937:7"; splitString[62] = splitString[62] + "1949:4"; splitString[63] = splitString[63] + "1956"; splitString[64] = splitString[64] + "1920:4"; splitString[65] = splitString[65] + "1921:4"; splitString[66] = splitString[66] + "1948:5"; splitString[67] = splitString[67] + "1923:2"; splitString[68] = splitString[68] + "1934:1"; splitString[69] = splitString[69] + "1947:5"; splitString[70] = splitString[70] + "1937:3"; splitString[71] = splitString[71] + "1949:5"; splitString[72] = splitString[72] + "1957"; splitString[73] = splitString[73] + "1948:6"; splitString[74] = splitString[74] + "1962:1"; splitString[75] = splitString[75] + "1934:2"; splitString[76] = splitString[76] + "1947:6"; splitString[77] = splitString[77] + "1938:1"; splitString[78] = splitString[78] + "1949:6"; splitString[79] = splitString[79] + "1958"; //Correct splitString[80] = splitString[80] + "1924:2"; splitString[81] = splitString[81] + "1937:11"; splitString[82] = splitString[82] + "1925:2"; splitString[83] = splitString[83] + "4095"; splitString[84] = splitString[84] + "1930:2"; splitString[85] = splitString[85] + "1931:2"; splitString[86] = splitString[86] + "1929"; splitString[87] = splitString[87] + "1928"; splitString[88] = splitString[88] + "1923:7"; splitString[89] = splitString[89] + "1937:8"; splitString[90] = splitString[90] + "1924"; splitString[91] = splitString[91] + "1937:9"; splitString[92] = splitString[92] + "1948:7"; splitString[93] = splitString[93] + "1962:2"; splitString[94] = splitString[94] + "1934:3"; splitString[95] = splitString[95] + "1947:7"; splitString[96] = splitString[96] + "1938:2"; splitString[97] = splitString[97] + "1949:7"; splitString[98] = splitString[98] + "1959"; splitString[99] = splitString[99] + "1924:1"; splitString[100] = splitString[100] + "1937:10"; splitString[101] = splitString[101] + "1921:6"; splitString[102] = splitString[102] + "1941"; splitString[103] = splitString[103] + "160:1"; splitString[104] = splitString[104] + "1930:1"; splitString[105] = splitString[105] + "1931:1"; splitString[106] = splitString[106] + "1940"; splitString[107] = splitString[107] + "162:2"; splitString[108] = splitString[108] + "1930"; splitString[109] = splitString[109] + "162:1"; splitString[110] = splitString[110] + "1931"; splitString[111] = splitString[111] + "1939"; splitString[112] = splitString[112] + "1950"; splitString[113] = splitString[113] + "1962:3"; splitString[114] = splitString[114] + "1935"; splitString[115] = splitString[115] + "1947:8"; splitString[116] = splitString[116] + "1938:3"; splitString[117] = splitString[117] + "1951"; splitString[118] = splitString[118] + "1960"; splitString[119] = splitString[119] + "1925:1"; splitString[120] = splitString[120] + "169:1"; splitString[121] = splitString[121] + "1925:5"; splitString[122] = splitString[122] + "1921:1"; splitString[123] = splitString[123] + "1920:5"; splitString[124] = splitString[124] + "1921:11"; splitString[125] = splitString[125] + "1921:10"; splitString[126] = splitString[126] + "1932"; splitString[127] = splitString[127] + "1921:8"; splitString[128] = splitString[128] + "1924:3"; splitString[129] = splitString[129] + "1937:12"; splitString[130] = splitString[130] + "1921:7"; splitString[131] = splitString[131] + "1950:1"; splitString[132] = splitString[132] + "1922"; splitString[133] = splitString[133] + "1962:4"; splitString[134] = splitString[134] + "1935:1"; splitString[135] = splitString[135] + "1947:9"; splitString[136] = splitString[136] + "1938:4"; splitString[137] = splitString[137] + "1951:1"; splitString[138] = splitString[138] + "1961"; splitString[139] = splitString[139] + "1923"; splitString[140] = splitString[140] + "1937:1"; for (int i = 1; i < 141; ++i) { System.out.println(splitString[i]); } try { Gui.progressBar.setValue(68); TextFileWriter.write(); } catch (Exception e) { e.printStackTrace(); } }
b4296bf4-4604-4035-974d-f243ebb8a330
9
public Solution dumbCrossover(Solution s1, Solution s2) { int numLectures = environment.getLectureList().size(); int numFixed = environment.getFixedAssignments().size(); // Determine which solution is better Solution better, worse; if (s1.getPenalty() < s2.getPenalty()) { better = s1; worse = s2; } else { better = s2; worse = s1; } // Create a new solution Solution combination = new Solution(environment); long total = worse.getPenalty() + better.getPenalty(); int numWorse = (int)(((float)better.getPenalty() / (float)total) * (numLectures - numFixed)); int numBetter = (numLectures - numFixed) - numWorse; // Get the best n from the better solution that aren't fixed assignments TreeSet<Assign> bestAssignments = better.extractBest(numBetter, new TreeSet<Assign>()); // Add them to our new solution // Every member of this set should be added without problems for (Assign assign : bestAssignments) { if (combination.dumbAddAssign(assign) == false) { //assert false : "Error - Failed to add " + assign.toString() + " during crossever"; } } // Now get the best m from the worse solution that aren't fixed assignments bestAssignments = worse.extractBest(numWorse, bestAssignments); // Attempt to add them to our new solution for (Assign assign : bestAssignments) { if (combination.dumbAddAssign(assign) == false) { //System.out.println("Failed to add " + assign.toString() + " during crossever"); } } // Attempt to complete any incomplete solutions, return false if we are unable to do so if (!combination.isComplete()) { combination = generator.buildDown(combination, new Random()); if (combination == null) return null; } // Calculate the new solution's penalty combination.calculatePenalty(); combination.rankAssignments(); if (combination.getPenalty() < bestSolution.getPenalty()) { bestSolution = combination; } if (worse != bestSolution) { solutions.remove(worse); } return combination; }
fad8aa2d-440a-4974-bade-664e7bbd2e6b
8
public void putAll( Map<? extends Short, ? extends Float> map ) { Iterator<? extends Entry<? extends Short,? extends Float>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Short,? extends Float> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
41957dc5-3a93-49b9-9586-0b7e3c523e13
8
public List<NewsItem> getPage(int page){ String baseURL = "https://www.kettering.edu"; List<NewsItem> newsPage = new ArrayList<NewsItem>(); if(page < 2) return newsPage; try{ DefaultHttpClient client = new DefaultHttpClient(); HttpGet newsGet = new HttpGet("https://www.kettering.edu/news/current-news?page=" + --page); HttpResponse response = client.execute(newsGet); String html = HTMLParser.parse(response); // Write to file PrintWriter printer = new PrintWriter("artifacts/news/newsPage" + page + ".html"); printer.print(html); printer.close(); System.out.println("Successfully stored \"newsPage" + page + ".html\"."); Elements articles = Jsoup.parse(html).getElementsByClass("more"); for(Element article : articles){ if(article.attr("href") != null){ // Execute response = client.execute(new HttpGet(baseURL + article.attr("href"))); Document doc = Jsoup.parse(HTMLParser.parse(response)); // Correct format ? if(doc.getElementsByClass("news").size() > 0 && doc.getElementsByClass("info").size() > 0 && doc.getElementsByClass("intro").size() > 0 && doc.getElementsByClass("intro").get(0).nextElementSibling() != null){ // Set properties String title = doc.getElementsByClass("news").get(0).text(); String headline = doc.getElementsByClass("intro").get(0).text(); String date = doc.getElementsByClass("date").get(0).text(); String body = doc.getElementsByClass("intro").get(0).nextElementSibling().toString(); // Add newsPage.add(new NewsItem(title, headline, date, body)); } } } return newsPage; } catch(Exception e){ return new ArrayList<NewsItem>(); } }
6df76a3f-251c-4402-8f7b-dcb852e8e896
0
public hasChosenItemsState(GameMachine gumballMachine) { this.gumballMachine = gumballMachine; }
47908029-1daf-475c-ba67-127cb71a5376
4
public static void main(String[] args) { try { System.out.println("[开始执行]"); logger.info("[开始执行]"); initBloomFilter(); ReadConfig readConfig = new ReadConfig(); List<?> configList = readConfig.readConfig(); GetData getData = new GetData(); for (Object configObj : configList) { try { ReadConfig.Config config = (ReadConfig.Config) configObj; getData.getData(config); }catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); NewsEyeSpider.logger.debug(baos.toString()); } } saveBloomFilter(); System.out.println("[执行完毕]"); logger.info("[执行完毕]"); }catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); NewsEyeSpider.logger.debug(baos.toString()); } }
416a3e8e-941a-4c1b-99cc-c434e91c7f31
9
private void printToFiles(){ try { BufferedWriter writer = new BufferedWriter(new FileWriter(("Data/TagTableData/tagFrequencies.txt"))); BufferedWriter writer2 = new BufferedWriter(new FileWriter("Data/TagTableData/wordTagFrequencies.txt")); BufferedWriter writer3 = new BufferedWriter(new FileWriter("Data/TagTableData/precedingPosFrequencies.txt")); BufferedWriter writer4 = new BufferedWriter(new FileWriter("Data/TagTableData/precedingTwoPosFrequencies.txt")); for(PartOfSpeechTag tag : tagFrequencies.keySet()){ writer.write("Tag:" + tag.name() + ", Frequency:" + tagFrequencies.get(tag)+"\n"); totalFrequency += tagFrequencies.get(tag); } writer.close(); for(String word: wordTagFrequencies.keySet()){ writer2.write(word+"{"); for(PartOfSpeechTag tag : wordTagFrequencies.get(word).keySet()){ writer2.write(" Tag:"+tag.name()+", Frequency:"+wordTagFrequencies.get(word).get(tag)+";"); } writer2.write("}\n"); } writer2.close(); for(PartOfSpeechTag tag : precedingPosFrequencies.keySet()){ writer3.write(tag.name()+"{"); for(PartOfSpeechTag preceding : precedingPosFrequencies.get(tag).keySet()){ writer3.write(" Tag:"+preceding.name()+", Frequency:"+precedingPosFrequencies.get(tag).get(preceding)+";"); } writer3.write("}\n"); } writer3.close(); for(PartOfSpeechTag tag : precedingTwoPosFrequencies.keySet()){ writer4.write(tag.name()+"{"); for(List<PartOfSpeechTag> preceding : precedingTwoPosFrequencies.get(tag).keySet()){ writer4.write(" Tags: "); for(PartOfSpeechTag pos : preceding){ writer4.write(pos.name()+" "); } writer4.write(", Frequency:" + precedingTwoPosFrequencies.get(tag).get(preceding)+";"); } writer4.write("}\n"); } writer4.close(); } catch (IOException e) { e.printStackTrace(); } }
c6c74bb0-329b-4c7e-9108-9e422c0ac9b2
9
public static void main(String[] args) { String a = "aaa"; Class<?> processor = null; Object obj = null; try { processor = Class.forName("common.reflection.LineDistributorExample"); Method method = processor.getMethod("distribute", String.class); obj = method.invoke(processor.newInstance(), a); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } Integer b = (Integer) obj; if ( b == null ) System.out.println("NULL"); else { System.out.println(b); } }
eee0f0f3-b395-45f8-9e92-13e9d8ec480d
7
private static List<Element> merge(List<Element> left, List<Element> right) { List<Element> merged = new ArrayList<Element>(); int temp; while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { // Update Comparison when if condition is true temp = left.get(0).getNumberOfComparison(); left.get(0).setNumberOfComparison(++temp); temp = right.get(0).getNumberOfComparison(); left.get(0).setNumberOfComparison(++temp); if (left.get(0).getValue() < right.get(0).getValue()) { merged.add(left.get(0)); left.remove(0); } else { merged.add(right.get(0)); right.remove(0); } } else if (left.size() > 0) { merged.add(left.get(0)); left.remove(0); } else if (right.size() > 0) { merged.add(right.get(0)); right.remove(0); } } return merged; }
a3171d25-f4a9-45c8-b2c4-6b58cdf36c50
9
private static Date cvtDate(String s, String fmt) { Date d = null; Calendar cal = null; int year = 0; int month = 0; int day = 0; // Organize logic for faster decisions, so most common // things up front... if(fmt == null || fmt.equals("YYYY-MM-DD")) { year = Utils.buildNumber(s, 0, 4); month = Utils.buildNumber(s, 5, 2); day = Utils.buildNumber(s, 8, 2); } else if(fmt.equals("YYYYMMDD")) { year = Utils.buildNumber(s, 0, 4); month = Utils.buildNumber(s, 4, 2); day = Utils.buildNumber(s, 6, 2); } else if(fmt.equals("YYMMDD")) { year = Utils.buildNumber(s, 0, 2); if(year < 70) { year += 2000; // 140203, 650203 -> 3-Feb-2014, 3-Feb-2065 } else { year += 1900; // 700203, 960203 -> 3-Feb-1970, 3-Feb-1996 } month = Utils.buildNumber(s, 2, 2); day = Utils.buildNumber(s, 4, 2); } else if(fmt.equals("YYYYMM")) { // 201405 becomes 1-May-2014 year = Utils.buildNumber(s, 0, 4); month = Utils.buildNumber(s, 4, 2); day = 1; // YOW! } if(year != 0) { cal = Calendar.getInstance(); cal.clear(); cal.set( Calendar.YEAR, year ); cal.set( Calendar.MONTH, month - 1); cal.set( Calendar.DATE, day ); d = cal.getTime(); } else if(fmt != null && fmt.equals("ISO8601")) { d = Utils.cvtISODateToDate(s); } return d; }
efa49fd3-874d-439e-a13a-708202eb83e7
0
private static void createAndSendInitialMessageToAllBots(Match m, IBomber[] bombers) throws IOException { // Lets give initial details to bombers: String initialMessage = "BEGIN MSG\n" + "map width: " + m.getMapWidth() + "\n" + "map height: " + m.getMapHeight() + "\n" + "bombersCount " + bombersCount + "\n" + "POINTS_PER_TREASURE " + POINTS_PER_TREASURE + "\n" + "POINTS_LOST_FOR_DYING " + POINTS_LOST_FOR_DYING + "\n" + "DYING_COOL_DOWN " + DYING_COOL_DOWN + "\n" + "BOMB_TIMER_DICE " + BOMB_TIMER_DICE + "\n" + "BOMB_TIMER_SIDES " + BOMB_TIMER_SIDES + "\n" + "BOMB_FORCE " + BOMB_FORCE + "\n" + "TURNS " + TURNS + "\n" + "TREASURE_CHANGE " + TREASURE_CHANCE + "\n" + "INITIAL_COUNT_OF_BOMBS " + INITIAL_COUNT_OF_BOMBS + "\n" + "MAP: \n" + m.getMapString() + "END MSG\n\n"; sendToAllBots(bombers, initialMessage); }
8ec5cd71-ad02-445f-a958-e0d3a4606b11
1
public double[] getY(double[] result, double x) { double v = Math.sqrt((r + x - a) * (r - x + a)); if (result == null) { result = new double[2]; } result[0] = v + b; result[1] = v - b; return result; }
58da5233-62b4-4052-9eae-42ef2ffb2b5d
1
public void moveToEnd(Board board, Direction dir) { while (tryMove(board, dir)); }
7ba411f5-3ece-4a52-8f98-a7f7b8b65b9f
3
public void checkDeclaration(Set declareSet) { if (initInstr instanceof StoreInstruction && (((StoreInstruction) initInstr).getLValue() instanceof LocalStoreOperator)) { StoreInstruction storeOp = (StoreInstruction) initInstr; LocalInfo local = ((LocalStoreOperator) storeOp.getLValue()) .getLocalInfo(); if (declareSet.contains(local)) { /* * Special case: This is a variable assignment, and the variable * has not been declared before. We can change this to a * initializing variable declaration. */ isDeclaration = true; declareSet.remove(local); } } }
c3ebfb32-e3a5-45c1-958a-bc357661acdf
1
private void testEmptyCycListAdd() { UnsupportedOperationException x = null; try { CycList.EMPTY_CYC_LIST.add(4); } catch (UnsupportedOperationException e) { x = e; } assertNotNull(x); }
4ae3d0e8-cde1-43b3-88be-3744f2808506
4
@Deprecated public void setLocation(Location location) { if(location == null) throw new IllegalArgumentException("Null location sent to setLocation"); if(dead) return; if(this.location != null) { heading = this.location.getDirectionToLocation(location); this.location = location; } else { this.location = location; game.sendEvent(new AppearedEvent(game, this)); if(this.getImageURL() != null) game.sendEvent(new IconUpdateEvent(game, this)); } }
3d5e3c0e-97d9-404f-b5ce-86efc4dd224d
4
private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, e); return false; } }
4d09427f-bc61-45b9-be9f-3b770e9c1d17
5
public void setLayout(int pos){ switch(pos){ case 0: labels[INDEX_ZERO] = projectile; labels[INDEX_ONE] = pendulum; labels[INDEX_TWO] = thirdChoice; labels[INDEX_THREE] = back; temporaryButtonSet = mechanicsButtonSet; break; case 1: labels[INDEX_ZERO] = oscillation; labels[INDEX_ONE] = doppler; labels[INDEX_TWO] = thirdChoice; labels[INDEX_THREE] = back; temporaryButtonSet = wavesButtonSet; break; case 2: labels[INDEX_ZERO] = coulombs; labels[INDEX_ONE] = circuit; labels[INDEX_TWO] = thirdChoice; labels[INDEX_THREE] = back; temporaryButtonSet = electricityButtonSet; break; default: labels[INDEX_ZERO] = mechanics; labels[INDEX_ONE] = waves; labels[INDEX_TWO] = electricity; labels[INDEX_THREE] = exit; temporaryButtonSet = mainPageButtonSet; break; } for(int i=0; i<temporaryButtonSet.length; i++){ temporaryButtonSet[i].setPrefSize(300, 50); temporaryButtonSet[i].setText(labels[i]); } buttonGroup[pos].getChildren().addAll(temporaryButtonSet); buttonGroup[pos].setAlignment(Pos.CENTER); buttonGroup[pos].setSpacing(30); buttonGroup[pos].setPadding(new Insets(275,0,0,0)); title[0] = new Text("Mechanics"); title[1] = new Text("Waves and Modern Physics"); title[2] = new Text("Electricity & magnetism"); title[3] = new Text("Physics Animations"); for(int i = 0; i < 4; i++){ title[i].setFont(Font.loadFont("file:resources/fonts/title.ttf", 60)); mainPages[i].setPadding(new Insets(50,0,50,0)); mainPages[i].setAlignment(title[i], Pos.TOP_CENTER); mainPages[i].setTop(title[i]); } mainPages[pos].setCenter(buttonGroup[pos]); }
bae212aa-f835-4cc8-b81e-a9e565e6e60c
9
static CharTrie ahoCorasickBuild(String[] pats) { CharTrie root = new CharTrie(); for (int i = 0; i < pats.length; i++) { CharTrie cur = root; for (int j = 0; j < pats[i].length(); j++) { char c = pats[i].charAt(j); if (cur.children[c] == null) cur.children[c] = new CharTrie(); cur = cur.children[c]; } cur.matches.add(i); } Queue<CharTrie> queue = new LinkedList<CharTrie>(); // Java5 for (int i = 0; i < root.children.length; i++) { if (root.children[i] == null) root.children[i] = root; else { root.children[i].fail = root; queue.add(root.children[i]); } } while (!queue.isEmpty()) { CharTrie par = queue.poll(); for (int i = 0; i < par.children.length; i++) { CharTrie child = par.children[i]; if (child == null) continue; queue.add(child); CharTrie fail = par.fail; while (fail.children[i] == null) // 子の失敗遷移は、親の失敗遷移先からその文字で進めるところ fail = fail.fail; child.fail = fail.children[i]; child.matches.addAll(child.fail.matches); } } return root; }
ec80a962-8518-4326-9806-8243a866866f
5
public void run() { ServerSocket serversocket = null; Socket s; InputStreamReader input; BufferedReader b; String message = null; boolean done = false; try { serversocket = new ServerSocket(process.getPort(), 1); serversocket.setSoTimeout(0); } catch (IOException e) { String msg = String.format("Error: failed to launch Listener at %s.", process.getInfo()); System.err.println(msg); System.err.println(e.getMessage()); System.exit(1); } while (! done) { s = null; try { s = serversocket.accept(); } catch (IOException e) { String msg = String.format("Error: failed to accept connection at %s.", process.getInfo()); System.err.println(msg); System.err.println(e.getMessage()); System.exit(1); } /* Accepted connection from a MessageHandler. */ try { input = new InputStreamReader(s.getInputStream()); b = new BufferedReader(input); while((message = b.readLine()) != null) { Message m = Message.parse(message); /* Notify process */ process.receive(m); } /* Close connection */ b.close(); s.close(); } catch (IOException e) { String msg = String.format("Error: failed to read() at %s.", process.getInfo()); System.err.println(msg); System.err.println(e.getMessage()); System.exit(1); } } }
cfbf5549-1364-45fc-a5d7-b946d27affbc
8
public Box getAdjacentBox(Direction d, Box b) { Pair<Integer> position = getBoxPosition(b); int w = position.getFirst(); int h = position.getSecond(); switch (d) { case North: if (h + 1 < height) { return chart[w][h+1]; } else { return null; } case South: if (h - 1 >= 0) { return chart[w][h-1]; } else { return null; } case East: if (w + 1 < width) { return chart[w+1][h]; } else { return null; } case West: if (w - 1 >= 0) { return chart[w-1][h]; } else { return null; } default: return null; } }
ce7ff9b4-a5f4-44c2-b50c-c546ec1392a7
7
public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;integratedSecurity=true;"; // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl); // Create and execute an SQL statement that returns a // set of data and then display it. String SQL = "SELECT * FROM Production.Product;"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); displayRow("PRODUCTS", rs); } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) try { stmt.close(); } catch(Exception e) {} if (con != null) try { con.close(); } catch(Exception e) {} } }
d24cf9f0-01f3-40bb-88cf-1ec04d5b0676
6
public RPChromosomeRegion getExtremes(RPChromosomeRegion testRegion) { RPChromosomeRegion newRegion = new RPChromosomeRegion(this); // update node bounds if (testRegion.startChromID < newRegion.startChromID || (testRegion.startChromID == newRegion.startChromID && testRegion.startBase < newRegion.startBase)) { newRegion.startChromID = testRegion.startChromID; newRegion.startBase = testRegion.startBase; } if (testRegion.endChromID > newRegion.endChromID || (testRegion.endChromID == newRegion.endChromID && testRegion.endBase > newRegion.endBase)) { newRegion.endChromID = testRegion.endChromID; newRegion.endBase = testRegion.endBase; } return newRegion; }
972daf0b-7479-41b6-b1f9-41ebb115a19f
5
public String strStr(String haystack, String needle) { if (needle.isEmpty()) return haystack; if (haystack.isEmpty()) return null; int m = 0; // the beginning of the current match in haystack int i = 0; // the position of the current character in needle int[] T = kmpTable(needle); while (m + i < haystack.length()) { if (needle.charAt(i) == haystack.charAt(m + i)) { if (i == needle.length() - 1) return haystack.substring(m); else i++; } else { m = m + i - T[i]; // it is good to set T[0] = -1; if (T[i] > -1) i = T[i]; else i = 0; } } return null; }
ddbec188-7ecb-4612-847a-f4c467771a95
4
public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean left = true; while (input.hasNext()) { String line = input.nextLine(); for (int i = 0; i < line.length(); ++i) { char c = line.charAt(i); if (c == '\"') { if (left) { System.out.print("``"); left = false; } else { System.out.print("\'\'"); left = true; } } else System.out.print(c); } System.out.println(); } }
c4110183-9df1-4754-b618-d90e304b61b7
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TradingData other = (TradingData) obj; if (planets == null) { if (other.planets != null) return false; } else if (!planets.equals(other.planets)) return false; if (resourceTypes == null) { if (other.resourceTypes != null) return false; } else if (!resourceTypes.equals(other.resourceTypes)) return false; return true; }
f1b988b4-a103-45a4-8357-950b99fdc710
3
public static void removeConnectedClient(String btN) { for(int i = 0;i<=5;i++) { if(clientsTable.getModel().getValueAt(i, 0) != null) { if(clientsTable.getModel().getValueAt(i, 0).toString().equals(btN)) { //Clear Device clientsTable.getModel().setValueAt(null, i, 0); clientsTable.getModel().setValueAt(null, i, 1); numConnected--; //Make Sure Table has no Breaks cleanUpTable(); } } } }
c5fb6653-e9ed-45ff-93c3-e547c64e75d6
2
public void popularCB() { ArrayList<String> Departamentos = new ArrayList<>(); DepartamentoBO depBO = new DepartamentoBO(); try { Departamentos = depBO.CMBDepartamento(usuarioLogado.getDepartamento().getCodigo()); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao popular o departamento", "Departamento", JOptionPane.ERROR_MESSAGE); } cbDepartamentos.removeAllItems(); cbDepartamentos.addItem("Selecione"); for (String item : Departamentos) { cbDepartamentos.addItem(item); } }
a21208c9-7687-4b59-a9bd-b6d087eff5ad
7
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JenkinsServer that = (JenkinsServer) o; if (name != null ? !name.equals(that.name) : that.name != null) { return false; } if (url != null ? !url.equals(that.url) : that.url != null) { return false; } return true; }
570f0ea8-4619-4531-b3fc-f43b64147752
6
public static void main(String[] args){ _port = initParser(args); try { try { _server = new ServerTCP(_port); } catch (SocketException e) { System.err.println(Errors.SOCKET_PROBLEM); System.exit(-1); } catch (IOException e) { System.err.println(Errors.IO_PROBLEM); System.exit(-1); } while(true){ try { _server.waitConnection(); } catch (IOException e) { System.err.println(Errors.WAITING_PROBLEM); System.exit(-1); } try { Thread t = new Thread(new Server()); t.start(); } catch (NullPointerException e) { System.err.println(Errors.NO_CLIENT_SOCKET); System.exit(-1); } } } catch(Exception e){ System.err.println(Errors.UNKNOWN_ERROR); System.exit(-1); } }
7c00d346-6871-4cad-b83b-c6b3b8f83f43
6
public Rectangle getEditorBounds(mxCellState state, double scale) { mxIGraphModel model = state.getView().getGraph().getModel(); Rectangle bounds = null; if (useLabelBounds(state)) { bounds = state.getLabelBounds().getRectangle(); bounds.height += 10; } else { bounds = state.getRectangle(); } // Applies the horizontal and vertical label positions if (model.isVertex(state.getCell())) { String horizontal = mxUtils.getString(state.getStyle(), mxConstants.STYLE_LABEL_POSITION, mxConstants.ALIGN_CENTER); if (horizontal.equals(mxConstants.ALIGN_LEFT)) { bounds.x -= state.getWidth(); } else if (horizontal.equals(mxConstants.ALIGN_RIGHT)) { bounds.x += state.getWidth(); } String vertical = mxUtils.getString(state.getStyle(), mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.ALIGN_MIDDLE); if (vertical.equals(mxConstants.ALIGN_TOP)) { bounds.y -= state.getHeight(); } else if (vertical.equals(mxConstants.ALIGN_BOTTOM)) { bounds.y += state.getHeight(); } } bounds.setSize( (int) Math.max(bounds.getWidth(), Math.round(minimumWidth * scale)), (int) Math.max(bounds.getHeight(), Math.round(minimumHeight * scale))); return bounds; }
5e9c707e-eae6-40e4-90c5-3d201ec9d3e4
9
public static String decrypt(String hash){ // The hash for the password that was generated by the encryption program String rands = ""; // Houses the concatenated random values from the encryption program String unencrypted = ""; // The returned, unencrypted password in String form int passwordlength = Integer.parseInt(hash.substring(0,2)); // From the first two numbers of the seed, it gets the length of the password. //int counter = 0; int innercounter = 0; /* Setting up parts of the password to be broken into chunks */ int[] lengthofencryptedchars = new int[passwordlength]; int[] unsortedrandoms = new int[passwordlength * 3]; int[] randoms = new int[(passwordlength * 3) - 2]; int[] encryptedchars = new int[passwordlength]; int[] asciivalues = new int[passwordlength]; char[] unencryptedchars = new char[passwordlength]; String withoutlen = hash.substring(2,hash.length()); // Creates a string without the first two digits, which are the length of the user's password char[] passarr = withoutlen.toCharArray(); // Converts the string to character array /* Handles getting length of encrypted values. Stores them in keys1[i] */ for(int i = 0; i < passwordlength; i++){ // Loop for concatenating the next passwordlength worth of characters (numbers in the hash) into its own array so we know the values we're working with later String placeholder = "" + passarr[i]; // In the hash above, you see 5555555555, which is (Ascii value of user pass character * random-three-digit-value).length() for each character. lengthofencryptedchars[i] = Integer.parseInt(placeholder); // Throws it into Array of ints to use in a loop later } String withoutkeys1 = withoutlen.substring(passwordlength, withoutlen.length()); // Removes keys1 from the hash. char[] nolengthofchars = withoutkeys1.toCharArray(); // Converts the new hash to Character array (minus lengthofencryptedchars) /* Handles getting the randoms thrown into one string called rands */ for (int i = 0; i < passwordlength * 3; i++){ // Since there are 3 numbers per random number, and passwordlength characters, it runs passwordlength * 3 times to separate the randoms into array. String placeholder = "" + nolengthofchars[i]; // Concatenating randoms to int array called unsortedrandoms unsortedrandoms[i] = Integer.parseInt(placeholder); rands = rands + unsortedrandoms[i]; // Makes string rands = a concatenation of all the unsorted randoms together } char[] unsortedrandschar = rands.toCharArray(); // Makes a new char array of the randoms so they're easy to concatenate below for (int i = 0; i < rands.length(); i = i+3){ String placeholder = Character.toString(unsortedrandschar[i]) + Character.toString(unsortedrandschar[i+1]) + Character.toString(unsortedrandschar[i+2]); // Concatenates three characters in unsortedrandomchars to string placeholder int placeholderint = Integer.parseInt(placeholder); // This and the line below it convert the string to int and throw it into the array of proper randoms randoms[i] = placeholderint; } String withoutrands = withoutkeys1.substring(passwordlength * 3, withoutkeys1.length()); // Breaks up the rest of the hash to no longer include the random values char[] hashwithoutrands = withoutrands.toCharArray(); // Creates array of numbers in the hash without the randoms now int[] passwordhash = new int[hashwithoutrands.length]; // Sets up an array of ints to break up the rest of the hash with /* Breaks down the rest of the hash into an array of ints */ for(int i = 0; i < hashwithoutrands.length; i++){ String placeholder = "" + Character.toString(hashwithoutrands[i]); passwordhash[i] = Integer.parseInt(placeholder); } /* Variables used for loop below */ int x = 0; String loop = ""; // Will house the string of the number as it is being concatenated for(int i = 0; i < passwordlength; i++){ // This runs 10 times in the example. Once for each character in the original password (passwordlength times) for(x = 0; x < lengthofencryptedchars[i]; x++){ // I threw the lengths of the encrypted chars in an array earlier. Now the loop will run that number of times to change the unsorted numbers in val(passwordlength) numbers loop = loop + passwordhash[innercounter]; // Concatenate the number innercounter = innercounter + 1; // Advance the innercounter by 1 to get next number } encryptedchars[i] = Integer.parseInt(loop); // Add now correct encrypted password character to array with type int loop = ""; // Clear loop to be used in next cycle of getting numbers } int randomscounter = 0; // Used to increment the randoms by 3 due to having to set them to[0,3,6,9...] /* Converts encrypted chars to ascii values */ for(int i = 0; i < encryptedchars.length; i++){ asciivalues[i] = encryptedchars[i] / randoms[randomscounter]; // Sets the values of encrypted / random = asciivalue randomscounter = randomscounter + 3; // Increments randomscounter by three (See line 146) } /* Converts Ascii characters to string */ for(int i = 0; i < passwordlength; i++){ int r = asciivalues[i]; // r = ascii value of character char f = (char) r; // Creates f as a casted char of r (Converts from ascii number to character) unencryptedchars[i] = f; // Stores character in array } /* Assigns the unencrypted password to a string */ for(int i = 0; i < unencryptedchars.length; i++){ unencrypted = unencrypted + unencryptedchars[i]; } System.out.println(unencrypted); return unencrypted; }
dfa40331-4a19-4fb1-9280-ca9351bdce22
4
@SuppressWarnings({ "unchecked", "rawtypes" }) public final void prune() { onl = new ArrayList[this.m]; for (int i=0; i<this.m; i++) { onl[i] = new ArrayList<Entry<K,V>>(1); } cam = new Hashtable<K,Entry<K,V>>(); for (int i=0; i<off.length; i++) { for (Entry<K,V> e : off[i]) { final HashCounter hc = new HashCounter(e.getK()); if (i==hc.mli) { e.setH(i); insertOnline(e); } } } Hashtable<Short,Integer> dist = cbf.getDistribution(); Short[] filter = cbf.getFilter(); cbf = (AbstractCountingBloomFilter)new HuffmanCountingBloomFilter(dist, filter, (short)word); this.pruned = true; }
2c8f5282-d592-4502-ae04-d84556033044
6
public void firstArrayOrdering() { // set whichOrder in order to sort the RefereeClass array // by match allocations RefereeClass.setWhichOrder("matches"); Arrays.sort(refereeProgram.getrefereeClassArray()); // create new array arrayFirstOrdering = new RefereeClass[refereeProgram.getelementsInArray()]; // count to hold the amount of array entries already added int newArrayElementsAdded = 0; // add RefereeClass objects which are in the main area for (int x = 0; x < refereeProgram.getelementsInArray(); x++) { RefereeClass refAtX = refereeProgram.getRefereeClassAtX(x); if (refAtX.getHomeLocality().equals(mainArea)) { arrayFirstOrdering[newArrayElementsAdded] = refAtX; newArrayElementsAdded++; } } // add RefereeClass objects which are in the adjacent area for (int x = 0; x < refereeProgram.getelementsInArray(); x++) { RefereeClass refAtX = refereeProgram.getRefereeClassAtX(x); if (refAtX.getHomeLocality().equals(otherArea1)) { arrayFirstOrdering[newArrayElementsAdded] = refAtX; newArrayElementsAdded++; } } // add RefereeClass objects which are in the non-adjacent or // second adjacent area for (int x = 0; x < refereeProgram.getelementsInArray(); x++) { RefereeClass refAtX = refereeProgram.getRefereeClassAtX(x); if (refAtX.getHomeLocality().equals(otherArea2)) { arrayFirstOrdering[newArrayElementsAdded] = refAtX; newArrayElementsAdded++; } } }
5a8954b2-47a7-4eaf-886b-5ca2f01fedb2
9
private void algorithmLine(int max, int min) { // Let's use the other algorithm to approximate the tiles that we need to check. algorithmWrap(max, min); // After calling the above function, the approximation is stored in this.result // These variables are explained when they are first set. // They are declared in advance only for optimisation. Tile tile; ArrayList<Tile> path; int source_x = this.origin.getGridX(), source_y = this.origin.getGridY(), target_x, target_y; int x, y, sign_x, sign_y; boolean steep; float d, dx, dy; tileLoop: //Simply a marker to be used later by the continue keyword. // This is necessary because we have nested loops. for (Tile current : this.validTargetPaths.keySet()) { //loop through the approximated targets // And then inside the loop we check to see if that approximation is a valid target. path = new ArrayList<Tile>(); //This variable is used to track the tiles that have to be cross to reach the "current" tile. target_x = current.getGridX(); //the X position of the target that is currently being considered. target_y = current.getGridY(); //the Y position of the target that is currently being considered. steep = false; //This variable is used to track whether the slope from the origin to the target is greater than 1 dx = Math.abs(target_x - source_x); //The distance between the target and origin, on the X axis. if (target_x - source_x > 0) { sign_x = 1; //Indicates that we are operating in one of the right 2 quadrants. (In a grid that is split along the X and Y axis at 0) } else { sign_x = -1; //Indicates that we are operating in one of the left 2 quadrants. } dy = Math.abs(target_y - source_y); //The distance between the target and origin, on the X axis. if (target_y - source_y > 0) { sign_y = 1; //Indicates that we are operating in one of the top 2 quadrants. } else { sign_y = -1; //Indicates that we are operating in one of the bottom 2 quadrants. } // Using sign_x and sign_y we can determine exactly which quadrant the target tile is in, relative to the origin. /* * As we loop through the path from the origin tile to the target tile, * the x and y variables will track which tile we are currently checking. * We start at the origin and move towards the target. */ x = source_x; y = source_y; if (dy > dx) { /* * If operating in an environment where the slope from the origin to the target is greater than 1. * ie. steep * We need to reverse all our x and y coordinates. * I can't give you a good explanation of why, * but this is definitely this keeps the code a lot lighter than special casing for steep and not steep. */ steep = true; x = y; y = x; dx = dy; dy = dx; sign_x = sign_y; sign_y = sign_x; } /* * Now we start looping through each tile from the origin to the target * As we look at each tile we check to see if it blocks the range finding or not. * * This is the point where we really use the Bresenham Line Algorithm * To understand this fully you should read this, * http://www.oocities.org/temerra/los_rays.html */ d = (2 * dy) - dx; for (int i = 0; i < dx; i++) { if (steep) { /* * Since the slope from the origin to the target is greater than 1, * we previously reversed x and y to simplify our calculations, * however we did not reverse the board's grid system, so we should swap the x and y * back to their original values just for this call. */ tile = this.match.getBoard().getTile(y, x); } else { tile = this.match.getBoard().getTile(x, y); } if (tile == null || tile.isOfType(ability.getBlockingType(), match.getCurrentPlayer(), match.getTileOwner(tile))) { // If the tile we are checking at the moment is null, or would block this range search. // Then remove "current" target that we are considering from the list of results, // and skip back to the beginning of the first loop so we can consider the next potential target. this.validTargetPaths.remove(current); continue tileLoop; // Jump back to where we set the "tileLoop:" marker } else { // If the tile is valid, then add it to the path, // which is the list of tiles that you have to cross to reach the "current" target. path.add(tile); } // START BRESENHAM ALGORITHM /* This is the core of the algorithm. * Basically the point of this code is to determine precisely the next tile * in the path from the origin to the target that we have to check. * Once again, this site http://www.oocities.org/temerra/los_rays.html * does a good job of explaining why and how. */ while (d >= 0) { y = y + sign_y; d = d - (2 * dx); } x = x + sign_x; d = d + (2 * dy); // END BRESENHAM ALGORITHM } // Since the current target made it this far, that means it's valid. // Store it in the results list, along with the path to reach it. this.validTargetPaths.put(current, path); } }
326d83f6-ae7c-4a64-a3da-006d6f4519c9
4
public static int getAbilityPower(AbilityType type) { //How much the ability deals/heals/etc switch (type) { case abil_tar_heal: break; case abil_aim_fire: return 10; case abil_dir_cleave: break; case abil_inv_melee: break; } return 0; }
e51c5184-2e55-49f0-b0c8-b74d6afaca0e
2
public static Account unchecked_narrow (org.omg.CORBA.Object obj) { if (obj == null) return null; else if (obj instanceof Account) return (Account)obj; else { org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); _AccountStub stub = new _AccountStub (); stub._set_delegate(delegate); return stub; } }
8723d080-3fad-4b5c-b92c-80edd62bca2d
9
public boolean addDialog(DialogCategory category, Dialog dialog){ if(editor.controller.dialogs.containsKey(dialog.id)){ String[] buttons = {"Overwrite", "Increment", "Cancel"}; int result = JOptionPane.showOptionDialog(this, dialog + "\nDialog found with the same id", "Conflict warning", JOptionPane.WARNING_MESSAGE, 0, null, buttons, buttons[1]); if(result == 0) editor.controller.removeDialog(editor.controller.dialogs.get(dialog.id)); if(result == 1) dialog.id = editor.controller.getUniqueDialogID(); if(result == 2) return false; } if(editor.controller.containsDialogName(category, dialog, dialog.getTitle())){ String[] buttons = {"Overwrite", "Change", "Cancel"}; int result = JOptionPane.showOptionDialog(this, dialog + "\nDialog found with the same name in this category", "Conflict warning", JOptionPane.WARNING_MESSAGE, 0, null, buttons, buttons[1]); if(result == 0) editor.controller.removeDialog(editor.controller.getDialogFromName(category, dialog, dialog.getTitle())); if(result == 1){ while(editor.controller.containsDialogName(category, dialog, dialog.getTitle())) dialog.setTitle(dialog.getTitle() + "_"); } if(result == 2) return false; } DialogController.instance.saveDialog(category.getID(), dialog); return true; }
5f87219a-f376-49d0-8e50-69d8aadab14c
1
public void addPropertyChangeListener(PropertyChangeListener listener) { this.rosterChangeSupport.addPropertyChangeListener(listener); for (Roster r: rosters) { r.addPropertyChangeListener(this); } }
6c94de28-1c9e-4700-8ad9-6020fb513c52
9
private boolean iscontainsDuplicate(int[] nums, int i, int j) { int length = j - i + 1; if (length == 1) return false; if (length == 2 && nums[i] == nums[j]) return true; if (length == 2 && nums[i] != nums[j]) return false; int mid = (i + j) / 2; HashSet<Integer> set = new HashSet<>(); for (int k = i; k < mid; k++) { set.add(nums[k]); } for (int k = mid; k <= j; k++) { if (set.contains(nums[k])) return true; } return iscontainsDuplicate(nums, i, mid) || iscontainsDuplicate(nums, mid + 1, j); }
18abf80d-2262-4f59-9f00-18b6261492f0
9
protected void onChannelOpen(Message msg) throws IOException { String type = msg.readString(); int remoteid = (int) msg.readInt(); // #ifdef DEBUG if(log.isDebugEnabled()) log.debug("Open channel '" + type + "' [" + remoteid + "]"); // #endif int remotepacket = (int) msg.readInt(); int remotewindow = (int) msg.readInt(); byte[] data = null; if(msg.available() > 0) { data = new byte[msg.available()]; msg.read(data); } if (factory == null) { sendChannelOpenFailure(remoteid, "This connection does not support the opening of channels"); return; } Channel channel = null; try { channel = factory.createChannel(this, type); if (channel == null) { sendChannelOpenFailure(remoteid, "Failed to create channel of type " + type); return; } } catch(ChannelOpenException coe) { sendChannelOpenFailure(remoteid, coe.getMessage() == null ? ( "Failed to create channel of type " + type + ". Reason " + coe.getReason()) : coe.getMessage() ); return; } channel.init(this, remoteid, remotepacket, remotewindow); if (allocateChannel(channel) == -1) { sendChannelOpenFailure(remoteid, "Too many channels already open"); } else { try { data = channel.open(data); sendChannelOpenConfirmation(channel, data); } catch(ChannelOpenException coe) { sendChannelOpenFailure(remoteid, coe.getMessage() == null ? ( "Failed to open channel. Reason " + coe.getReason()) : coe.getMessage() ); return; } } channel.fireChannelOpen(data); }
937e38cc-8d63-441d-97eb-3b4e03e4cc65
8
public void CheckFile(String temp, String GlobalName){ String line; int noLine = 0; int flag = 0; GlobalCont = 0; ReadFile(); //######### SET FIRST CONTLOC TO 0000 ########## /*Formatter fmt = new Formatter(); fmt.format("%04d",GlobalCont); String fmtPass = fmt.toString(); //System.out.print(fmtPass);*/ //contLoc.add("0000"); //############################################# //System.out.print(temp); ALL THE TEXT THAT WAS INTO THE TEXT AREA IS SENDED AS A STRING try{ FileWriter Done = new FileWriter("temp.data"); Done.write(temp); Done.close(); }catch(IOException Err){} try { BufferedReader br = new BufferedReader (new FileReader("temp.data")); while((line = br.readLine()) != null) { StringTokenizer token = new StringTokenizer(line); int top = token.countTokens(); if(line.startsWith(";") == true) StartComment(line, noLine); else if (line.contains(";") == true) Comment(line, noLine, top, token); else if(line.startsWith(" ") || line.startsWith("\t") == true ) TabCheck(line, token, noLine, top); else PerfectCase(line, token, noLine, top); flag = flag + 1; //System.out.println(line); //System.out.println("Numero de Tokens = " + top); } br.close(); }catch(FileNotFoundException f){System.out.println("No existe Archivo....");} catch(IOException ioe){System.out.println("Error de Archivo....");} /*/########################### TEST ######################## String hexB = Integer.toHexString(GlobalCont); int size = hexB.length(); if (size == 1) contLoc.add(flag - 1,"000" + hexB); else if (size == 2) contLoc.add(flag - 1,"00" + hexB); else if (size == 3) contLoc.add(flag - 1,"0" + hexB); else contLoc.add(flag - 1, hexB); //#########################################################*/ addEmpty( noLine ); SetText(); WriteLST(GlobalName); WriteLST1(GlobalName); WriteTBS(GlobalName); WriteS19(GlobalName); }
137a5522-065a-41e9-8ec9-5569fad5f8ec
6
public int compareTo(MACPacket p) { int seconds = 0; int pSeconds = 0; int milliSeconds = 0; int pMilliSeconds = 0; int microSeconds = 0; int pMicroSeconds = 0; for(int i = 0 ; i < this.seconds.length ; i++){ seconds += (this.seconds[i] << ((this.seconds.length-1-i)*8)) & 0xFF; } for(int i = 0 ; i < p.getSeconds().length ; i++){ pSeconds += (p.getSeconds()[i] << ((p.getSeconds().length-1-i)*8)) & 0xFF; } for(int i = 0 ; i < this.milliSeconds.length ; i++){ milliSeconds += (this.milliSeconds[i] << ((this.milliSeconds.length-1-i)*8)) & 0xFF; } for(int i = 0 ; i < p.getMilliSeconds().length ; i++){ pMilliSeconds += (p.getMilliSeconds()[i] << ((p.getMilliSeconds().length-1-i)*8)) & 0xFF; } for(int i = 0 ; i < this.microSeconds.length ; i++){ microSeconds += (this.microSeconds[i] << ((this.microSeconds.length-1-i)*8)) & 0xFF; } for(int i = 0 ; i < p.getMicroSeconds().length ; i++){ pMicroSeconds += (p.getMicroSeconds()[i] << ((p.getMicroSeconds().length-1-i)*8)) & 0xFF; } //get all seconds into one time of long and after subtraction back to int long time = (seconds*1000)*1000 + milliSeconds*1000 + microSeconds; long pTime = (pSeconds*1000)*1000 + pMilliSeconds*1000 + pMicroSeconds; time = time -pTime; int intTime = (int)time; return intTime; }
dd945e2e-0694-4b6d-9b90-e7bf2761a259
2
public void setRemoveSurroundingSpaces(String tagList) { if(tagList != null && tagList.length() == 0) { tagList = null; } this.removeSurroundingSpaces = tagList; }
c73ffd6f-2c0d-4d11-b5f7-d38f23d8354b
2
@Override public void run() { try { while (true) { mServer.send(new ConduitMessage(mClientInput)); } } catch (Exception exception) { // An exception here can be ignored, as its just the connection // going away, which we deal with later. } shutdown(); }
c9b2d024-fe01-411f-90aa-e47ad0be2f43
6
public static EquipmentType getEquipmentType(ItemStack is) { if (ArrayUtils.contains(mats.get(EquipmentType.HELM), is.getType())) return EquipmentType.HELM; else if (ArrayUtils.contains(mats.get(EquipmentType.CHESTPLATE), is.getType())) return EquipmentType.CHESTPLATE; else if (ArrayUtils.contains(mats.get(EquipmentType.LEGGINGS), is.getType())) return EquipmentType.LEGGINGS; else if (ArrayUtils.contains(mats.get(EquipmentType.BOOTS), is.getType())) return EquipmentType.BOOTS; else if (ArrayUtils.contains(mats.get(EquipmentType.WEAPON), is.getType())) return EquipmentType.WEAPON; else if (is.getType() == Material.BOW) return EquipmentType.BOW; return null; }
a652f057-3380-47e0-b228-1a0d9f7c2452
6
private boolean isCode(String sourceString) { if (sourceString.isEmpty()) { return false; } else if (sourceString.contains("{") && !sourceString.contains("}")) { braceCount++; return true; } else if (sourceString.contains("}") && !sourceString.contains("{")) { braceCount--; return true; } else if (braceCount != 0) { return true; } return false; }
8b82b78a-d667-43f6-b53f-d6c49b15d7f8
9
protected void updatePersonnel(int numUpdates) { if (numUpdates % REFRESH_INTERVAL == 0) { final Base base = employs.base() ; // // Clear out the office for anyone dead- for (Actor a : workers ) if (a.destroyed()) setWorker(a, false) ; for (Actor a : residents) if (a.destroyed()) setResident(a, false) ; // // If there's an unfilled opening, look for someone to fill it. // TODO: This should really be handled more from the Commerce class? if (employs.careers() == null) return ; for (Background v : employs.careers()) { final int numOpenings = employs.numOpenings(v) ; if (numOpenings > 0) { if (GameSettings.hireFree) { final Human citizen = new Human(v, employs.base()) ; citizen.mind.setWork(employs) ; final Boardable t = employs.canBoard(null)[0] ; citizen.enterWorldAt(t, base.world) ; } else { base.commerce.incDemand(v, numOpenings, REFRESH_INTERVAL) ; } } } } }
d1d32aab-9c36-42c9-bb7d-42d566233655
5
public Block(int blockID) { if(blockID == World.AIR || blockID == World.STONE || blockID == World.DIRT || blockID == World.WOOD || blockID == World.LEAF) { this.blockID = blockID; } else { blockID = World.INVALID; } }
d4f2c0df-60e3-45a3-9813-29c641692cc7
2
public SignalStructure(Class<?>[] params, List<Slot> arrayList, Class<?> returnParam) { this.invokerParameters = params; this.registeredListeners = arrayList; this.returnParam = returnParam; }
69433f24-5e19-41f2-a964-79528c5b2e72
2
public Production[] getProductionsToAddToGrammar(Grammar grammar, Set lambdaSet) { ArrayList list = new ArrayList(); Production[] productions = grammar.getProductions(); for (int k = 0; k < productions.length; k++) { Production[] prods = getProductionsToAddForProduction( productions[k], lambdaSet); for (int j = 0; j < prods.length; j++) { list.add(prods[j]); } } return (Production[]) list.toArray(new Production[0]); }
84873fb9-cb20-46e2-9d0e-4f802a9f2d75
0
@Override public void endSetup(Attributes atts) {}
302292ce-32eb-4cc4-bbb8-b5e89e4453e4
8
private void refill() throws IOException { final int token = in.readByte() & 0xFF; final boolean minEquals0 = (token & MIN_VALUE_EQUALS_0) != 0; final int bitsPerValue = token >>> BPV_SHIFT; if (bitsPerValue > 64) { throw new IOException("Corrupted"); } final long minValue = minEquals0 ? 0L : zigZagDecode(1L + readVLong(in)); assert minEquals0 || minValue != 0; if (bitsPerValue == 0) { Arrays.fill(values, minValue); } else { final PackedInts.Decoder decoder = PackedInts.getDecoder(PackedInts.Format.PACKED, packedIntsVersion, bitsPerValue); final int iterations = blockSize / decoder.byteValueCount(); final int blocksSize = iterations * decoder.byteBlockCount(); if (blocks == null || blocks.length < blocksSize) { blocks = new byte[blocksSize]; } final int valueCount = (int) Math.min(this.valueCount - ord, blockSize); final int blocksCount = (int) PackedInts.Format.PACKED.byteCount(packedIntsVersion, valueCount, bitsPerValue); in.readBytes(blocks, 0, blocksCount); decoder.decode(blocks, 0, values, 0, iterations); if (minValue != 0) { for (int i = 0; i < valueCount; ++i) { values[i] += minValue; } } } off = 0; }
453cea1b-7e0a-4806-9e98-c16c5283616a
7
private void drawPaths(Graphics g) { for (VortexSpace space : vortexes) { double[] location = space.getLocation(); ArrayList<Integer> neighbors = space.getNeighbors(); ArrayList<Integer> paths = space.getPaths(); for (int i=0; i<neighbors.size(); i++) { int corridor = paths.get(i); g.setColor(new Color(150, 150, 160)); if (dijkstraPath.contains(corridor)) { g.setColor(Color.RED); } double[] neighborLocation = vortexes.getSpace(neighbors.get(i)).getLocation(); int x1 = sphereConverter.giveWindowXCoordinate(location[0], location[1]); int y1 = sphereConverter.giveWindowYCoordinate(location[0], location[1]); int x2 = sphereConverter.giveWindowXCoordinate(neighborLocation[0], neighborLocation[1]); int y2 = sphereConverter.giveWindowYCoordinate(neighborLocation[0], neighborLocation[1]); if (x1>0 && y1>0 && x2>0 && y2>0) { g.drawLine(x1, y1, x2, y2); } } } }
57b9ca0b-518f-42a9-80e0-912373039bb2
2
public boolean setJumpheight(int jumpheight) { if (jumpheight > 0 && jumpheight < 4) { this.jumpheight = jumpheight; return true; } else { return false; } }
ef685972-e828-4c03-bb07-5519f52e0fd2
7
static void set_ordinals_in_plausible_commit_order(Map<String, Set<String>> graph, OrdinalMapper ordinals) { // Make a list of all parent to child edges. // Each edge represents the constraint "the ordinal of this parent is less // than the ordinal of this child". List<GraphEdge> edges = new ArrayList<GraphEdge>(); Set<String> leaf_nodes = new HashSet<String>(); for (Map.Entry<String, Set<String>> entry : graph.entrySet()) { String child = entry.getKey(); Set<String> parents = entry.getValue(); if (parents.size() == 0) { leaf_nodes.add(child); continue; } for (String parent : parents) { edges.add(new GraphEdge(parent, child)); } } while (!edges.isEmpty()) { // Find edges to vertices that no other edges reference. Set<String> candidates = new HashSet<String>(); Set<String> referenced = new HashSet<String>(); for (GraphEdge edge : edges) { candidates.add(edge.mFrom); referenced.add(edge.mTo); } // i.e. "the parents which no remaining children reference." // Implies must have lower ordinals than all unprocessed children. candidates.removeAll(referenced); assert_(candidates.size() > 0); List<String> sorted = new ArrayList<String>(candidates); Collections.sort(sorted); for (String candidate : sorted) { // Set the ordinal. ordinals.ordinal(candidate); // Remove any unreferenced edges from the list. // LATER: fix crappy code. do in one pass outside loop. remove_edges(edges, candidate); } } // Tweak here to order by date? or some other metric? // Set the ordinals for nodes which have no children. List<String> sorted_leaf_nodes = new ArrayList<String>(leaf_nodes); Collections.sort(sorted_leaf_nodes); for (String leaf_node : sorted_leaf_nodes) { ordinals.ordinal(leaf_node); } }
0bafcb78-7cf8-4a4f-9a24-35b4576981e4
4
/* */ @EventHandler(priority=EventPriority.HIGHEST) /* */ public void onFoodLevelChange(FoodLevelChangeEvent event) /* */ { /* 252 */ if ((event.getEntity() instanceof Player)) /* */ { /* 254 */ Player player = (Player)event.getEntity(); /* */ /* 256 */ if (!event.isCancelled()) /* */ { /* 258 */ if (Main.getAPI().isBeingSpectated(player)) /* */ { /* 260 */ for (Player p : Main.getAPI().getSpectators(player)) /* */ { /* 262 */ p.setFoodLevel(event.getFoodLevel()); /* */ } /* */ } /* */ } /* */ } /* */ }
4b6b3d32-cf1a-4d5a-8635-e60cc70b901c
8
@Override public boolean keyup(KeyEvent ev) { if (ev.getKeyCode() == KeyEvent.VK_UP) APXUtils.wPressed = false; if (ev.getKeyCode() == KeyEvent.VK_LEFT) APXUtils.aPressed = false; if (ev.getKeyCode() == KeyEvent.VK_DOWN) APXUtils.sPressed = false; if (ev.getKeyCode() == KeyEvent.VK_RIGHT) APXUtils.dPressed = false; 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; }
7be89cd4-302f-434d-9132-b7e5a48191cb
7
@Override public void mouseDragged (MouseEvent e) { if (alg.isProcess()) { return; } int i = getRowByMouseX(e.getX()); int j = getColumnByMouseY(e.getY()); if (e.getModifiersEx() == MouseEvent.BUTTON1_DOWN_MASK) { if (draggedCell != null) { dragCell(i, j); } else { if (alg.getCell(i, j) instanceof EmptyCell) { alg.setCell(i, j, new Wall()); } } } else if (e.getModifiersEx() == MouseEvent.BUTTON3_DOWN_MASK) { if (draggedCell != null) { dragCell(i, j); } else { if (alg.getCell(i, j) instanceof Wall) { alg.setCell(i, j, new EmptyCell()); } } } mouseMoved(e); }
74df93a3-fc92-4d05-8850-2cc14752c4e9
2
public double rawAverageCorrelationCoefficients(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients(); return this.rawMeanRhoWithoutTotals; }
95dc77e9-b310-415f-9934-c003435cd273
6
public String addUser() throws Exception { DBConnection dbcon = new DBConnection(); Connection con = dbcon.connect(); String check = "failure"; String result=null; String query="SELECT COUNT(username) FROM users WHERE username='"+username+"';"; PreparedStatement statement = con.prepareStatement(query); ResultSet rs = statement.executeQuery(); if(rs.first()){ result = rs.getString(1); } if(password.equals(confirmpassword) && email.equals(confirmemail) && result.equals("0")){ query= "INSERT INTO users(username,password,firstname,lastname,email,address) VALUES('" + username + "','" + password + "'," + "'" + firstname + "','" + lastname + "','" + email + "','" + address + "')"; statement.executeUpdate(query); check = "success"; } if (check.equals("success")) { addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "User Registration Successful!!!", null)); } else if (check.equals("failure")) { addMessage(new FacesMessage(FacesMessage.SEVERITY_ERROR, "User Registration Failed!!!", null)); } return check; }
5bde05b1-be4d-4e32-8d5e-836c6da37667
2
public void imprimirTable(JTable table) { for (int i = 0; i < table.getRowCount(); i++) { for (int j = 1; j < table.getColumnCount(); j++) { System.out.print(table.getValueAt(i, j) + " "); } System.out.println(""); } }
b00da76e-5957-4de6-b183-389e71f47f2c
1
@Override public void logicUpdate(GameTime gameTime) { // Call any 'startUps' required updateGameQueue(gameTime); for (IHudItem item : hudItemQueue) { item.logicUpdate(gameTime); } }
d2035223-959c-477a-b009-da5b9678fa82
2
boolean contains(int[] arr, int x) { for (int i : arr) if (x == i) return true; return false; }
0af1f1e9-6048-4673-adc7-cf997e9b3c5e
5
@Override public Object getValueAt(int rowIndex, int columnIndex) { Customer customer = customers.get(rowIndex); switch (columnIndex) { case 0: return customer.getId(); case 1: return customer.getFirstname(); case 2: return customer.getLastname(); case 3: return customer.getBirth(); case 4: return customer.getEmail(); default: throw new IllegalArgumentException("columnIndex"); } }
57325617-e9d6-4110-a162-0cf38ac3e5a5
2
public void loadImage(String key, String path) { File sourceImage = new File(path); Image image = null; try { image = ImageIO.read(sourceImage); } catch (IOException e) { e.printStackTrace(); } if(image != null) { loadedImages.put(key, image); } }
5af95385-b681-42ff-b8e1-0819a10d98d3
3
public void updateFinderBounds(Rectangle bounds, boolean repaint) { if (bounds != null && !bounds.equals(finderBounds)) { Rectangle old = new Rectangle(finderBounds); finderBounds = bounds; // LATER: Fix repaint region to be smaller if (repaint) { old = old.union(finderBounds); old.grow(3, 3); repaint(old); } } }
66ff229b-b650-409c-af30-43a90bf7184e
0
public MusicLoudness getMusicLoudness() { return musicLoudness; }
1368e5c8-a9b4-4d6e-9ba1-060fcd1f5993
0
@Override public void setRank(int newRank) { rank = newRank; }
0f20a4b3-4046-4921-9ef7-c26f089a6cdf
5
private JSONObject getModel(String format){ JSONObject models = null, model = null; ArrayList<String> keyList = new ArrayList<String>(); try{ models = new JSONObject(getModelFileData()); if(format.equals("random") || format.length() <= 0){ Iterator<?> keys = models.keys(); while(keys.hasNext()){ keyList.add(keys.next().toString()); } String key = keyList.get(new Util().getRandomArrayNumber(keyList.size())); model = models.getJSONObject(key); }else{ model = models.getJSONObject(format); } } catch (JSONException e){ e.printStackTrace(); } return model; }
db26ea91-3bc9-40dd-a0b9-75836a9eb25c
9
public boolean input(Instance instance) { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } Instances outputFormat = outputFormatPeek(); double[] vals = new double[outputFormat.numAttributes()]; boolean inRange = false; double lastVal = Utils.missingValue(); int i, j; for(i = 0, j = 0; j < outputFormat.numAttributes(); i++) { if (m_DeltaCols.isInRange(i) && (i != instance.classIndex())) { if (inRange) { if (Utils.isMissingValue(lastVal) || instance.isMissing(i)) { vals[j++] = Utils.missingValue(); } else { vals[j++] = instance.value(i) - lastVal; } } else { inRange = true; } lastVal = instance.value(i); } else { vals[j++] = instance.value(i); } } Instance inst = null; if (instance instanceof SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new DenseInstance(instance.weight(), vals); } inst.setDataset(getOutputFormat()); copyValues(inst, false, instance.dataset(), getOutputFormat()); inst.setDataset(getOutputFormat()); push(inst); return true; }
9225087b-3346-4538-9edc-2dab7a1223f2
2
public void sendMessage(Message message) { try{ writer.writeObject(message); writer.flush(); } catch(NullPointerException e) { ServerHelper.log(LogType.ERROR, "Kein Outputstream für " + ip + ":" + port + " vorhanden"); } catch(IOException e) { ServerHelper.log(LogType.ERROR, "Fehler beim Senden einer Nachricht"); } }
5ae4a02e-977e-4e27-a16f-1c917fb0c0db
0
public String showList(){ List<Problem> list = problemDAO.findPage(page, size); problemList = new ProblemList(); problemList.setList(list); return SUCCESS; }
8a3ddb1f-2fe0-456f-8e70-03b6bedef429
3
public void checkReady() { if ((points==0) && (ground != null) && (name != null)) { status = "Nomad"; } }
d54094aa-2ef0-441d-9fe3-62dcd767c231
3
@Override public boolean onMouseDown(int mX, int mY, int button) { if(super.onMouseDown(mX, mY, button)) { return true; } for(ResearchItemButton rib : itemSlots) { if(rib.onMouseDown(mX, mY, button)) { researchDone = true; return true; } } return false; }
6b9fbc88-d9c0-4970-91ef-9dab7de10b24
2
public void run() { try { // populate warehouse with goodies populateWarehouse(); System.out.println("==========================="); System.out.println("= Sales System ="); System.out.println("==========================="); printUsage(); BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); String command = ""; while (true) { System.out.print("> "); command = in.readLine(); processCommand(command.trim().toLowerCase()); System.out.println("Done. "); } } catch (IOException e) { log.error(e.getMessage()); } }
984fc934-b8e2-473b-99d0-7442f2b5e2ee
0
@Override public String toString() { return name; }