method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9dc0a8e4-3e98-45df-8d65-d58395b93431
0
private int segundos() { return hora * 3600 + minuto * 60 + segundo; }
533ad2dc-3cdf-45c6-9622-524387858923
6
public static List<Producto> buscar(Integer codigo, String nombre, String estado){ List<Producto> encontrados=new ArrayList<Producto>(); for(Producto p : productos){ if(p.getCodigo().equals(codigo) || (p.getNombre().contains(nombre) && !nombre.isEmpty()) || (p.getEstado().equals(estado) && !estado.equals("TODO")) ){ encontrados.add(p); } } return encontrados; }
de6aa92c-113e-4e30-ac23-95e62ae53475
6
public byte[] getImage(String exeName) { try { Process p = Runtime.getRuntime().exec("./res/getPrograms.bat " + exeName); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); int count = 0; while(true) { line = input.readLine(); if(line != null) { if(count == 4) { if(line.contains("Windows")) { return null; } System.out.println(line); break; } } count++; } p.destroy(); input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File file = new File(line); Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file); BufferedImage bim = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] by = null; try { ImageIO.write(bim, "jpg", baos); baos.flush(); by = baos.toByteArray(); baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return by; }
249fc28c-88a8-4221-970d-96725a194e30
7
public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java TestOneSimulation <test filename>"); System.exit(0); } boolean voters[] = Utility.setupVoters(args[0]); int steps = Opinion.doOneSimulation(voters); if (steps != Utility.numSteps) { System.out.printf("Error: expected %d steps, got %d steps\n", Utility.numSteps, steps); } else if (steps != Opinion.MAX_STEPS) { /* Does the output converge to the expected opinion? */ boolean c = (Utility.convergedTo == 'A') ? true : false; for (int i = 0; i < voters.length; i++) { if (voters[i] != c) { char d0 = (voters[i] ? 'A' : 'B'); System.out.printf("Error: expected convergence to %c, %c @ array location %d\n", Utility.convergedTo, d0, i); System.exit(0); } } System.out.println("Success!"); } else { System.out.println("Success!"); } }
3c92e81d-dcdb-41a9-8e26-2d60d555f8bd
2
@Override protected void inspectContents(File file, String contents) { if (checkType.equals(XMLChecker.VALID)) { System.out.println(" START VALIDATION FOR FILE: " + file.getPath()); doParse(contents); System.out.println(" END VALIDATION"); } else if (checkType.equals(XMLChecker.WELL_FORMED)) { System.out.println(" START WELL-FORMEDNESS CHECK FOR FILE: " + file.getPath()); doParse(contents); System.out.println(" END WELL-FORMEDNESS CHECK"); } System.out.println(""); }
6e405838-c0f4-42c0-ad49-4e00c87674de
3
@Override public boolean equals( Object obj ) { if( obj == this ) { return true; } if( obj == null || obj.getClass() != getClass() ) { return false; } ConnectionLabelConfiguration that = (ConnectionLabelConfiguration) obj; return that.id.equals( id ); }
49605048-4e40-4279-8127-bac749fab9cd
8
public static String HuffmanCode(String s) { if (s.length() <= 1) return "0"; //construct the map Map<Character,Integer> m = new HashMap<Character,Integer>(); for (int i = 0; i < s.length(); ++i) { if (!m.containsKey(s.charAt(i))) { m.put(s.charAt(i),1); } else { m.put(s.charAt(i),m.get(s.charAt(i))+1); } } //tree node class Node { char character; int times; Node left; Node right; String ns; public Node(char c,int i) { character = c; times = i; } } List<Node> l = new LinkedList<Node>(); Iterator<Map.Entry<Character,Integer>> iter = m.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Character,Integer> e = iter.next(); l.add(new Node(e.getKey(),e.getValue())); } Collections.sort(l,new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { return Integer.compare(o1.times, o2.times); //To change body of implemented methods use File | Settings | File Templates. } }); Node[] nonLeaf = new Node[l.size()-1]; int nonLeafIndex = l.size()-2; nonLeaf[nonLeafIndex] = new Node('a',l.get(0).times+l.get(1).times); nonLeaf[nonLeafIndex].left = l.get(0); nonLeaf[nonLeafIndex].right = l.get(1); nonLeafIndex--; int lIndex = 2; while (nonLeafIndex >= 0) { nonLeaf[nonLeafIndex] = new Node('a',l.get(lIndex).times+nonLeaf[nonLeafIndex+1].times); nonLeaf[nonLeafIndex].left = l.get(lIndex); nonLeaf[nonLeafIndex].right = nonLeaf[nonLeafIndex+1]; nonLeafIndex--; lIndex++; } nonLeaf[0].ns = ""; for (int i = 0; i < nonLeaf.length; ++i) { nonLeaf[i].left.ns = nonLeaf[i].ns+"0"; nonLeaf[i].right.ns = nonLeaf[i].ns +"1"; } Map<Character,String> char_To_Str = new HashMap<Character, String>(); for (Node n : l) { char_To_Str.put(n.character,n.ns); } String r = ""; for (int i = 0; i < s.length(); ++i) { r += char_To_Str.get(s.charAt(i)); } return r; }
55469176-5060-4798-a106-483309459318
4
public String[][] insertAndGetNewFields(String query) throws SQLException { checkConnection(); if(conn != null) { Statement stmt; try { stmt = conn.createStatement(); stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); ResultSet resSt = stmt.getGeneratedKeys(); ArrayList<String[]> al = new ArrayList<String[]>(); int rowCount = resSt.getMetaData().getColumnCount(); while(resSt.next()) { String[] s = new String[rowCount]; for(int i = 0; i < rowCount; i++) { s[i] = resSt.getString(i+1); } al.add(s); } String[][] ret = new String[al.size()][]; return al.toArray(ret); } catch(SQLException e) { throw e; } } else { throw new SQLException(); } }
104d4f44-582c-4f1e-be96-6142d8e493eb
0
@Test public void esteenTarkkaSijainti() { ArrayList<String> rivit = new ArrayList(); rivit.add("E 100 100 200 200"); Este e = new Este(100, 100 ,200, 200); Piste p = new Piste(); TasonLuonti tl = new TasonLuonti(rivit); Taso ta = tl.getTaso(); assertTrue("Esteitä oli väärissä paikoissa " + ta.toString(), ta.toString().equals(p.toString() + "\n" + e.toString()+"\n")); }
b13074c1-f6e8-4225-8198-523586a4ac1a
8
public static String replaceAll(String str, String thisStr, String withThisStr) { if ((str == null) || (thisStr == null) || (withThisStr == null) || (str.length() == 0) || (thisStr.length() == 0)) return str; for (int i = str.length() - 1; i >= 0; i--) { if (str.charAt(i) == thisStr.charAt(0)) { if (str.substring(i).startsWith(thisStr)) str = str.substring(0, i) + withThisStr + str.substring(i + thisStr.length()); } } return str; }
7cc5ab3f-dac3-4a1a-8c0e-d29a95627b01
1
public boolean isSitting() { if (rend != null) { return (rend.hasImage("body/sitting") == true); } else return false; }
d1baed83-c855-4ccc-a949-d0cf1506dd19
0
protected void end() {}
02b706a3-e963-4371-b472-1499be354779
1
@Override public JSONObject main(Map<String, String> params, Session session) throws Exception { JSONObject rtn = new JSONObject(); long uid = session.getActiveUserId(); // if no active user if(uid==0) { rtn.put("rtnCode", this.getRtnCode(201)); return rtn; } User activeUser = User.findById(uid); rtn.put("rtnCode", this.getRtnCode(200)); { JSONObject userJo = new JSONObject(); userJo.put("username", activeUser.username); userJo.put("id", activeUser.getId()); rtn.put("user", userJo); } return rtn; }
85676dcd-ef7e-4995-90a6-620a36bd560f
4
private void initComponents() { addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { if (!startPressed) { if (script != null) { script.ctx.controller.stop(); } } } }); for (String category : script.itemCategoriser.getCategorys()) { //tab0model.addElement(prettyName(category)); tab0model.addElement(category); } tabs.add(tab0 = new JList(tab0model)); tabs.add(tab1); tabs.add(tab2); tabs.add(tab3); tabs.add(tab4); tabs.add(tab5); tabs.add(tab6); tabs.add(tab7); tabs.add(tab8); for (int i = 0; i < tabs.size(); i++) { JList tab = tabs.get(i); tab.addMouseListener(new MenuAdapter(this, tab, tabs, i)); tab.setTransferHandler(new ListTransferHandler()); tab.setDropMode(DropMode.INSERT); tab.setDragEnabled(true); } tabbedPane = new JTabbedPane(); startButton = new JButton("Start Script"); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { start(); } }); loadButton = new JButton("Load Settings"); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { load(); } }); saveButton = new JButton("Save Settings"); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } }); categoryTab = getGeneralTab(); }
3a8ebaeb-04df-4580-9e9f-f5c495d2c972
9
public BoardFileBean getFileName(int idx) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; BoardFileBean fileBean = null; String sql = ""; String filename = ""; String fileTmp = ""; try{ conn = getConnection(); sql = "select * from boardfile where idx=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, idx); rs = pstmt.executeQuery(); fileBean = new BoardFileBean(); if(rs.next()){ fileBean.setFileid(rs.getInt("fileid")); fileTmp = rs.getString("filename"); StringTokenizer st = new StringTokenizer(fileTmp,"\\"); while(st.hasMoreElements()){ filename=st.nextToken(); } fileBean.setFilename(filename); fileBean.setRealpath("upload/"+filename); }else{ fileBean.setFilename("파일없음"); fileBean.setRealpath("파일없음"); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs!=null)try{rs.close();}catch(SQLException ex){} if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){} if(conn!=null)try{conn.close();}catch(SQLException ex){} } return fileBean; }
aaf2f392-f30f-44ae-bd50-8cc264895108
5
public static void main(String[] args) throws IOException { boolean quit = false; // main loop bool System.out.println("Welcome to C. Yotov's RSA implementation!"); // If there is a problem with the menu, use the commented code below /* final long startTimeKey = System.currentTimeMillis(); KeyGen.keyCreation(256); final long endTimeKey = System.currentTimeMillis(); final long startTimeEncr = System.currentTimeMillis(); Encryption encr = new Encryption("rsa_public_key.txt"); String fn = "pic", fex = ".jpg"; encr.encrypt(fn+fex, fn+"_fresh.encrypted"); final long endTimeEncr = System.currentTimeMillis(); final long startTimeDecr = System.currentTimeMillis(); Decryption decr = new Decryption("rsa_private_key.txt"); decr.decrypt(fn+"_fresh.encrypted", fn+"_fresh"+fex); final long endTimeDecr = System.currentTimeMillis(); System.out.println("Total encryption time: " + (endTimeEncr - startTimeEncr) ); System.out.println("Total decryption time: " + (endTimeDecr - startTimeDecr) ); System.out.println("Total key creation time: " + (endTimeKey - startTimeKey) ); */ do { // MAIN MENU System.out.println("\n\n\n+==+ MAIN MENU +==+\n\n"+ "-- 1 - Key Creation -- \n"+ "-- 2 - Encryption -- \n"+ "-- 3 - Decryption -- \n"+ "-- 4 - End -- \n\n"); layer_1 = user_input.next(); // request user input // go into the first layer of the menu switch(layer_1) { // KEY CREATION case "1": keyCreation(); break; // ENCRYPTION case "2": encryption(); break; // DECRYPTION case "3": decryption(); break; // exit case "4": quit = true; System.out.println("End."); break; default: System.out.println("Please choose a valid menu."); } } while (quit == false); }
fc87f905-bb2d-49f5-9f3f-daaac7b697f5
5
public String getAccountTypeString() { String toReturn = null; if(accountType == Type.SYSTEMADMIN) { toReturn = "System Administrator"; } else if(accountType == Type.ACADEMICADMIN) { toReturn = "Academic Administrator"; } else if(accountType == Type.ASSISTANTADMIN) { toReturn = "Assistant Academic Administrator"; } else if(accountType == Type.INSTRUCTOR) { toReturn = "Instructor"; } else if(accountType == Type.TATMMARKER) { toReturn = "TA/TM Marker"; } else { toReturn = "Error: invalid account type"; } return toReturn; }
e349c2de-1198-41b0-bba3-0974f704837e
7
@SuppressWarnings("static-access") public LinkedList<Human> readDatabase() { String noteType; TypeSwitch typeSwitcher = null; String line; try { while ((line = reader.readLine()) != null) { // Читаем до конца // файла while (!line.equals("-")) // Читаем до маркера разделителя { strings.add(line); line = reader.readLine(); } noteType = strings.get(0); // Блок сравнения if (noteType.equals("Teacher")) typeSwitcher = typeSwitcher.Teacher; if (noteType.equals("Student")) typeSwitcher = typeSwitcher.Student; switch (typeSwitcher) { case Teacher: people.add(new Teacher(strings)); break; case Student: people.add(new Student(strings)); break; default: throw new IllegalStateException(); } strings.clear(); // Чистим временный массив для построения // единичного объекта. } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return people; }
dc60b78b-714b-4dc0-9dcb-8445f95c5bcf
3
public byte[] compress(byte[] buf, int start, int[] len){ stream.next_in=buf; stream.next_in_index=start; stream.avail_in=len[0]-start; int status; int outputlen=start; byte[] outputbuf=buf; int tmp=0; do{ stream.next_out=tmpbuf; stream.next_out_index=0; stream.avail_out=BUF_SIZE; status=stream.deflate(JZlib.Z_PARTIAL_FLUSH); switch(status){ case JZlib.Z_OK: tmp=BUF_SIZE-stream.avail_out; if(outputbuf.length<outputlen+tmp+buffer_margin){ byte[] foo=new byte[(outputlen+tmp+buffer_margin)*2]; System.arraycopy(outputbuf, 0, foo, 0, outputbuf.length); outputbuf=foo; } System.arraycopy(tmpbuf, 0, outputbuf, outputlen, tmp); outputlen+=tmp; break; default: System.err.println("compress: deflate returnd "+status); } } while(stream.avail_out==0); len[0]=outputlen; return outputbuf; }
4434de87-aa3b-4b38-9b24-945f472d68ae
3
@RequestMapping(value = "/user/{userName}") public String getMainPage(Model model, @PathVariable String userName) { User user = userService.getUserName(userName); DAOExampleObject daoExampleObject = userService.getAttackFromDao(); if (user == null) { return "404"; } List<SlotInfo> slots = new ArrayList<SlotInfo>(); for (int i = 0; i < 7; i++) { SlotInfo s = new SlotInfo(); s.setSlotNumber(i); if (userService.getCreaturesByUserId(userName).get(i) != null) { s.setUrl(userService.getCreaturesByUserId(userName).get(i).getUrl()); s.setCreature(userService.getCreaturesByUserId(userName).get(i)); } else { s.setUrl(new EmptySlot().getUrl()); } slots.add(s); } model.addAttribute("slots", slots); model.addAttribute("user", user); model.addAttribute("DAOExampleObject", daoExampleObject.getAttack()); Map<Integer, Creature> creaturesByUserId = userService.getCreaturesByUserId(userName); model.addAttribute("creatures", creaturesByUserId.values()); return "User"; }
1c66aa19-756a-4698-a3fa-412f37016310
2
public boolean isServerTrusted(X509Certificate[] cert) { try { cert[0].checkValidity(); return true; } catch (CertificateExpiredException e) { return false; } catch (CertificateNotYetValidException e) { return false; } }
f85167b0-a40b-4ea3-aacb-e0a3bdbcf468
4
public static TreeMap<String, Integer> getItemID(ArrayList<String> id) { InputSource data; StringBuilder idList = new StringBuilder(); if (id.size() == 0 || id.size() > maxAPIRequest) { return null; } for (String s : id) { if (idList.length() == 0) { idList.append(s); } else { idList.append(','); idList.append(s); } } data = Download .getFromHTTPS("https://api.eveonline.com/eve/TypeName.xml.aspx?ids=" + idList); return XMLParser.getID(data).getSI(); }
604920d7-de30-45b9-8fca-fb1b7b20dfa9
1
public void send(Packet packet) { System.out.println("[Server] Sending to " + getRemoteAddress() + ": " + packet); try { socket.write(PacketCodecs.SERVER_CLIENT.write(packet)); } catch (IOException e) { e.printStackTrace(); } }
d5638b2f-791e-4b83-8e66-3542855faeba
6
@Override public String describeParameters(final Map<String, String> props) { final String task = props.get(DeployerConstants.SETTINGS_TASK); final String args = props.get(DeployerConstants.SETTINGS_ARGUMENTS); final String ant_target = props.get(DeployerConstants.SETTINGS_ANT_TARGET); final String ant_args = props.get(DeployerConstants.SETTINGS_ANT_ARGUMENTS); final String exec_command = props.get(DeployerConstants.SETTINGS_EXECUTE_COMMAND); StringBuilder sb = new StringBuilder(); sb.append(String.format("Task: %s", task)); if (task.equals(DeployerConstants.TASK_TYPE_EXECUTE)) { sb.append(String.format("\nCommand: %s", exec_command)); } else if (task.equals(DeployerConstants.TASK_TYPE_ANT)) { sb.append(String.format("\nTarget: %s", ant_target)); if (ant_args != null && ant_args.length() > 0) { sb.append(String.format("\nArgument(s): %s", ant_args)); } } else if (args != null && args.length() > 0) { sb.append(String.format("\nArgument(s): %s", args)); } return sb.toString(); }
886d3696-14cf-41e5-b5de-9467f5cc0277
3
@Override public void report() { final List<String> busiestActors = new ArrayList<>(); int highestCount = 0; for (final Map.Entry<String, Integer> actorYearToMovieCountEntry : actorYearToMovieCount.entrySet()) if (actorYearToMovieCountEntry.getValue() > highestCount) { busiestActors.clear(); busiestActors.add(actorYearToMovieCountEntry.getKey()); highestCount = actorYearToMovieCountEntry.getValue(); } else if (actorYearToMovieCountEntry.getValue() == highestCount) busiestActors.add(actorYearToMovieCountEntry.getKey()); System.out.println(String.format("Most prolific actor(s) in one year: %s with %d movies.", busiestActors, highestCount)); }
372a8f14-6960-46be-8d80-892f9a3b5865
5
public void removeADay(){ if(!timer.isRunning()){ if(buttonArray.size() > 2){ if(JOptionPane.showConfirmDialog(Main.mainPanel, "Do you want to remove a day?", "Remove a day", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION){ if(Main.selectedDay >= buttonArray.size()-1){ if(Main.isDay){ buttonArray.get(buttonArray.size()-2).getDay().doClick(); } else { buttonArray.get(buttonArray.size()-2).getNight().doClick(); } } this.removeDays(); timer.restart(); } } else { JOptionPane.showMessageDialog(Main.mainPanel, "You cannot have less than 1 day"); } } }
2b129817-dc94-4430-a281-457a1edd135c
5
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpSession session = ((HttpServletRequest) request).getSession(); if (session.getAttribute("profile") == null) { request.getRequestDispatcher("login.jsp").forward(request, response); return; } else { String[] actions = (String[]) request.getParameterMap().get("action"); if (actions != null && actions[0] != null && actionRoleMapping.get(actions[0]) != null) { Profile profile = (Profile) session.getAttribute("profile"); if (!profile.getRoles().contains(actionRoleMapping.get(actions[0]))) { request.getRequestDispatcher("/exam?action=view").forward(request, response); return; } } } filterChain.doFilter(request, response); }
70bc0bae-9f1f-49a4-91e6-01d548a1ea14
5
public static void modstat(String input) { String[] split = input.split(" ", 3); if(split[1].equalsIgnoreCase("health")) { Parasite.thePlayer.modifyHealth(Integer.parseInt(split[2])); } else if(split[1].equalsIgnoreCase("sanity")) { Parasite.thePlayer.modifySanity(Integer.parseInt(split[2])); } else if(split[1].equalsIgnoreCase("hunger")) { Parasite.thePlayer.modifyHunger(Integer.parseInt(split[2])); } else if(split[1].equalsIgnoreCase("fatigue")) { Parasite.thePlayer.modifyFatigue(Integer.parseInt(split[2])); } else if(split[1].equalsIgnoreCase("motivation")) { Parasite.thePlayer.modifyMotivation(Integer.parseInt(split[2])); } System.out.println("Attempted to modify " +split[1] +" by " +split[2] +" points."); }
cb706e4d-2adf-4537-99e0-f57790563f1f
2
private MigratableProcess getProcess(long id) { Iterator<MigratableProcess> it = processes.iterator(); while (it.hasNext()) { MigratableProcess process = it.next(); if (process.getId() == id) return process; } return null; }
4a92d4b5-f82f-4ca4-84a6-b02a7e85a383
2
static double[] toDoubleArray(float[] arr) { if (arr == null) return null; int n = arr.length; double[] ret = new double[n]; for (int i = 0; i < n; i++) { ret[i] = (double)arr[i]; } return ret; }
a1745d81-a1fa-487f-8f26-5b292000a8f4
1
@Override public void mouseMove(MouseEvent e) { if(this.getMouseListener() != null) { this.getMouseListener().MouseMove(this, e); } }
524c612b-0fb2-4d81-a987-c649a36f472b
2
public void deposit(BigInteger amount) throws IllegalArgumentException { if ( (amount == null) || (amount.compareTo(BigInteger.ZERO) <= 0) ) throw new IllegalArgumentException(); setBalance(this.getBalance().add(amount)); }
8c1216b0-ba67-403a-a298-e7ff20b7bddc
2
private StringBuffer internalReadStringBuffer(StringBuffer buf, int length) throws IOException { if ((byteBuffer == null) || (byteBuffer.length < length)) byteBuffer = new byte[length]; is.readFully(byteBuffer, 0, length); readUTF8Chars(buf, byteBuffer, 0, length); return buf; }
40a04964-e8d0-4cd2-b88a-334baff62938
7
public static Vector3 nearestPointOfIntersectionCylinder(Vector3 rayPosition, Vector3 rayDirection, Vector3 u, Vector3 v, double radius) { double uvLengthSquared = (v.subtract(u)).lengthSquared(); double a = rayDirection.lengthSquared() * uvLengthSquared - rayDirection.dotProduct(v.subtract(u)) * rayDirection.dotProduct(v.subtract(u)); double b = 2.0 * rayDirection.dotProduct(rayPosition.subtract(u)) * uvLengthSquared - 2.0 * rayDirection.dotProduct(v.subtract(u)) * (rayPosition.subtract(u)).dotProduct(v.subtract(u)); double c = uvLengthSquared * (rayPosition.subtract(u)).lengthSquared() - ((rayPosition.subtract(u)).dotProduct(v.subtract(u))) * ((rayPosition.subtract(u)).dotProduct(v.subtract(u))) - radius * radius * uvLengthSquared; // If the discriminant is less than zero, then no solution if (b * b - 4 * a * c < 0.0) { return null; } // Else, we need to find the two solutions, t0 and t1 and then return the minimum which is positive. double sqrtDiscriminant = Math.sqrt(b * b - 4 * a * c); double t0 = (-b - sqrtDiscriminant) / (2.0 * a); double t1 = (-b + sqrtDiscriminant) / (2.0 * a); double t; // t1 is the larger of the two solutions, so if it is negative, then there is no solution. if (t1 < 0.0) { return null; } // Now consider the points of intersection of the cylinder - we want them to lie on the cylindrical segment. Vector3 p0 = rayPosition.plus(rayDirection.scalarMultiply(t0)); Vector3 p1 = rayPosition.plus(rayDirection.scalarMultiply(t1)); double lambda0 = (p0.subtract(u)).dotProduct(v.subtract(u)); double lambda1 = (p1.subtract(u)).dotProduct(v.subtract(u)); // If t0 is positive, then this is the earliest point of intersection, else t1 is. if (t0 < 0.0 && lambda0 >= 0.0 && lambda0 <= uvLengthSquared) { t = t1; } else if (lambda1 >= 0.0 && lambda1 <= uvLengthSquared){ t = t0; } else { return null; } return rayPosition.plus(rayDirection.scalarMultiply(t)); }
1d89b41b-fed6-4152-a459-fa47dca7f3cc
0
public String getDescription() { return description; }
c04f8970-b9ca-4aca-b043-142ec49a4499
1
private int donneeSuivante( String chaine, int i ) { while (chaine.charAt(i) == this.separateur) i++; return i; }
2fd86af0-ff65-4cff-93c2-ccd70bfbb17a
2
@Override public Vector3d getForceAt(Vector3d position, Matrix3d rotation, Vector3d point) { Vector3d localPoint = new Vector3d(point); localPoint.sub(position); if (localPoint.lengthSquared() > outerRadius * outerRadius) { return new Vector3d(0, 0, 0); } Vector3d force = new Vector3d(localPoint); force.normalize(); force.scale(strength); if (localPoint.lengthSquared() < innerRadius * innerRadius) { return force; } double blast = 1 / (localPoint.length() - innerRadius); force.scale(blast); return force; }
ff17d906-5686-4d8a-8546-b2fa62da5a85
5
protected int addPoint(Vector3d p) { Vector3d q; int index = 0; boolean found = false; for (int i = 0; i < points.size(); i++) { q = points.elementAt(i); if ((q.x == p.x) && (q.y == p.y) && (q.z == p.z)) { index = i; found = true; break; } } if (found) return index; else { points.addElement(p); points_.addElement(new Vector3d()); inFOVs.addElement(false); return points.size() - 1; } }
f8ac9ff7-950f-406c-96fe-9fd51dc10692
3
public List<Integer> getTeams(URL url) { Document doc; Tidy tidy = new Tidy(); List<Integer> retVal = new ArrayList<Integer>(); try { doc = tidy.parseDOM(url.openStream(), null); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//tr[@bgcolor = '#FFFFFF']/td/a/text()"); NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); for(int i = 0; i < nodes.getLength(); i++) { retVal.add(Integer.parseInt(nodes.item(i).getNodeValue())); } } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return retVal; }
8e925fcf-db0e-4aab-8a9f-7450bf488356
0
public float getX() { return x; }
7b0d6455-a94b-4adc-830f-c1e100894eec
5
public Wave43(){ super(); MobBuilder m = super.mobBuilder; for(int i = 0; i < 2750; i++){ if(i % 8 == 0) add(m.buildMob(MobID.ONIX)); else if(i % 7 == 0) add(m.buildMob(MobID.MACHOP)); else if(i % 6 == 0) add(m.buildMob(MobID.GRAVELER)); else if(i % 5 == 0) add(m.buildMob(MobID.MAROWAK)); else add(m.buildMob(MobID.ZUBAT)); } }
444be56a-4781-4572-916f-94e01d13b136
6
public void addAvailablePositionForPawn(int row, int col, Board theBoard,ArrayList<Position> validMoves, boolean mustCapture) { Position newPosition = new Position(row, col); if(newPosition.isOnBoard() && ((mustCapture && theBoard.isPieceAtPosition(newPosition) && !theBoard.getPiece(newPosition).hasSameColor(this)) || (!mustCapture && !theBoard.isPieceAtPosition(newPosition)))){ validMoves.add(newPosition); } }
fa27aa00-1388-40fa-ad95-cdefba6fbac2
0
public static void main(String[] args) { ParcelInitialization p = new ParcelInitialization(); Destination d = p.destination("Tasmania"); }
025e012c-dfa7-49e8-a680-0ee8d6c89f3d
7
public static String timeIntervalToString(long millis) { StringBuffer sb = new StringBuffer(); if (millis < 10 * Constants.SECOND) { sb.append(millis); sb.append("ms"); } else { boolean force = false; String stop = null; for (int ix = 0; ix < units.length; ix++) { UD iu = units[ix]; long n = millis / iu.millis; if (force || n >= iu.threshold) { millis %= iu.millis; sb.append(n); sb.append(iu.str); force = true; if (stop == null) { if (iu.stop != null) { stop = iu.stop; } } else { if (stop.equals(iu.str)) { break; } } } } } return sb.toString(); }
11c3fbde-e852-4c7e-a2c5-e8290444196a
8
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { TabbedPanel tabbedPanel = TabbedUtils.getParentTabbedPanel(c); if (tabbedPanel != null) { Direction d = tabbedPanel.getProperties().getTabAreaOrientation(); g.setColor(color.getColor(c)); if (d == Direction.UP) { GraphicsUtil.drawOptimizedLine(g, x + 1, y, x + width - 2, y); GraphicsUtil.drawOptimizedLine(g, x, y, x, y + height - (openBorder ? 1 : 2)); } else if (d == Direction.LEFT) { GraphicsUtil.drawOptimizedLine(g, x + 1, y, x + width - (openBorder ? 1 : 2), y); GraphicsUtil.drawOptimizedLine(g, x, y, x, y + height - 2); } else if (d == Direction.DOWN) { if (!openBorder) GraphicsUtil.drawOptimizedLine(g, x + 1, y, x + width - 2, y); GraphicsUtil.drawOptimizedLine(g, x, y, x, y + height - 2); } else { if (openBorder) GraphicsUtil.drawOptimizedLine(g, x, y, x + width - 2, y); else { GraphicsUtil.drawOptimizedLine(g, x + 1, y, x + width - 2, y); GraphicsUtil.drawOptimizedLine(g, x, y, x, y + height - 2); } } } }
cc049404-f222-4979-bf27-01278708544e
1
public boolean _setSpriteImage(URL spriteSourceImageURL) { if(spriteSourceImageURL != null) { sprite._setSpriteImage(spriteSourceImageURL); return true; } else { return false; // Couldn't update sprite. Probably invalid sprite given. } }
08053aee-8d07-40e2-a0d4-98256c0d29f7
4
public void setRemainingFieldToMinSim(double min) { for (int i = 0; i < fieldSize; i++) { for (int j = 0; j < fieldSize; j++) { if (idealDistance[i][j] == 0 && i != j) { //not yet set idealDistance[i][j] = getDistance(min); //set to parameter idealDistance[j][i] = idealDistance[i][j]; forceRate[i][j] = WEAK_FORCE_MULT; //set inv spring k forceRate[j][i] = forceRate[i][j]; dataPresent[i][j] = true; dataPresent[j][i] = true; } } } }
a250c681-630d-4b4e-b801-c4f0298ffa9c
5
public ParticleSystem(float deltaT, boolean randomStart) { this.deltaT = deltaT; if (!randomStart) { for (int i = 3; i < 8; i++) { for (int j = 15; j < 250; j++) { for (int k = 3; k < 6; k++) { particles.add(new Particle(new Vector3(i, j, k), 1f)); } } } } else { for (int i = 0; i < 5000; i++) { particles.add(new Particle(new Vector3((float) Math.random() * rangex, (float) Math.random() * rangey, (float) Math.random() * rangez), 1)); } } // create cell grid grid = new CellGrid((int)rangex, (int)rangey, (int)rangez); // should be whatever the size of the box is }
21946dda-4281-4705-8818-47b744f92f01
5
public void setWrap(String d, boolean e){ int s; if(e){s = 1;}else{s = 0;} if(d == "X"){xwrap = e;bpol[2] = s; bpol[6] = s;} if(d == "Y"){ywrap = e;bpol[0] = s; bpol[4] = s;} if(xwrap && ywrap){bpol[1] = 1; bpol[3] = 1; bpol[5] = 1; bpol[7] = 1;} else{bpol[1] = 0; bpol[3] = 0; bpol[5] = 0; bpol[7] = 0;} }
86904ac9-6be6-4b88-a4fe-f4e7dafb4aa6
9
@Override public boolean isValidRoute(String route) { // TODO Auto-generated method stub if (route == null || route.equals("")) { return false; } String[] stations = route.split(DELIMITER_BETWEEN_STATIONS); if (stations == null || stations.length == 0) { return false; } // step1, validate all stations in the route int size = stations.length; for (int i = 0; i < size; i++) { String station = stations[i]; if (!isValidStation(station)) { return false; } } // setp2, validate the edge for (int i = 0, j = 1; i < size - 1 && j < size; i++, j++) { String fromStation = stations[i]; String toStation = stations[j]; int p1 = getPosition(fromStation); int p2 = getPosition(toStation); if (mMatrix[p1][p2] == 0) { return false; } } return true; }
03a22907-d73a-4e87-9c99-edfb2d56731c
7
public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Enter computer ID:"); id = Integer.parseInt(in.nextLine()); System.out.println("Enter port address for this computer:"); port = Integer.parseInt(in.nextLine()); server s = new server(); stateThread st = new stateThread(); s.setDaemon(true); st.setDaemon(true); s.start(); //Starts listening for client connections. st.start(); //Creates all necessary files that do not exist. try{ file = new File("file_"+id+".txt"); p2p_file = new File("p2p.txt"); if(!file.exists()) file.createNewFile(); if(!p2p_file.exists()) p2p_file.createNewFile(); } catch(Exception e){ e.printStackTrace(); } writeFileNames(); //Writes all files in sub-directory to the file_id.txt. readFileNames(); //Reads all lines from file_id.txt into file_list. joinP2PSystem(); //Initiates the process of joining P2P network. do{ System.out.println("What would you like to do? \n 1.Search and download a file." +"\n 2.Exit the P2P network. \n Enter your choice:"); choice = Integer.parseInt(in.nextLine()); if(choice==1) { System.out.println("Enter the file name or keyword:"); String file = in.nextLine(); new search(file); } else if(choice==2) { depart = true; if(neighbor_list.size()>0) new depart(); } else System.out.println("Invalid option."); }while(choice!=2); s.interrupt(); st.interrupt(); removeFromActiveP2PSystem(); in.close(); System.out.println("System has gone offline."); }
9670ebd9-7d9c-4dd4-885f-1eb7eb635670
3
public static void main(String[] args) { int age = 15; switch(age){ case 14: System.out.println("You're in 9th grade."); break; case 15: System.out.println("You're in 10th grade."); break; case 16: System.out.println("You're in 11th grade."); break; default: System.out.println("Are you sure you're in high school?"); break; } }
aca43301-ef8a-4532-b2f6-db6ffec9bbc8
8
public static boolean logReceivedLine(boolean directionIN, long threadID, String agentRegistrationID, String sender, String recipient, String senderIP, String recipientIP, String line) { try { if (!isLoggingEnabled) { return false; } if (alLoggingAgents == null) { alLoggingAgents = new ArrayList(); return false; } if (alLoggingAgents.size() < 1) { return false; } if ((line == null) || (line.trim().equals(""))) { return false; } for (int i = 0; i < alLoggingAgents.size(); i++) { terminal_log = (Thread_Terminal)alLoggingAgents.get(i); try { terminal_log.pwOut.println(directionIN + "@@@@@" + threadID + "@@@@@" + agentRegistrationID + "@@@@@" + sender + "@@@@@" + recipient + "@@@@@" + senderIP + "@@@@@" + recipientIP + "@@@@@" + line); terminal_log.pwOut.flush(); } catch (Exception localException1) { } } return true; } catch (Exception e) { eop("logReceivedLine", strMyClassName, e, "", false); } return false; }
20e25a6d-1ea6-4a12-8a31-a27ae41e32ee
7
private void addToCellGroup(ArrayList<AgentsGroup> cellGroups, BaseAgent agent) { AgentsGroup agentGroup; BaseAgent groupRepresentative; BaseInformation agentInformation, groupRepresentativeInformation; ArrayList<HumanAgent> humans; agentGroup = null; agentInformation = this.population.get(agent); if(!AgentsUtils.isHumanInformation(agentInformation) || ((HumanInformation)agentInformation).getHealthStatus() != HumanHealthStatus.Infected) { //Look for the group where the agent is placed for(AgentsGroup group: cellGroups) { //Take a representative of the group humans = group.getHumans(); if(!humans.isEmpty()) { groupRepresentative = humans.get(0); } else { groupRepresentative = group.getZombies().get(0); } //If there aren't any walls between the agent and the representative of the group, //this will be the agent's group groupRepresentativeInformation = this.population.get(groupRepresentative); if(!this.thereIsAWallBetween(agentInformation.getPosition(), groupRepresentativeInformation.getPosition())) { agentGroup = group; break; } } //If the agent doesn't belong to any of the given groups, a new group //is created if(agentGroup == null) { agentGroup = new AgentsGroup(); cellGroups.add(agentGroup); } //Add the agent to the group if(AgentsUtils.isHuman(agent)) { //The agent is human agentGroup.getHumans().add((HumanAgent)agent); } else { //The agent is zombie agentGroup.getZombies().add((ZombieAgent)agent); } } }
6caf1743-5a1a-46db-b125-9eb2de628b22
4
public int bestAction() { int selected = -1; double bestValue = -Double.MAX_VALUE; for (int i=0; i<children.length; i++) { if(children[i] != null) { double childValue = children[i].totValue / (children[i].nVisits + this.epsilon); childValue = Utils.noise(childValue, this.epsilon, this.m_rnd.nextDouble()); //break ties randomly if (childValue > bestValue) { bestValue = childValue; selected = i; } } } if (selected == -1) { System.out.println("Unexpected selection!"); selected = 0; } return selected; }
c72d71b3-03b0-4e26-be5a-553bf269b53e
6
public void populateRatingMap() { Connection connection = new DbConnection().getConnection(); ResultSet resultSet = null; Statement statement = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery(SELECT_ALL_RATINGS); while (resultSet.next()) { int ratingId = resultSet.getInt("ratingId"); String description = resultSet.getString("description"); ratingsMap.put(ratingId, description); } } catch (SQLException e) { m_logger.error(e.getMessage(), e); } finally { try { if (connection != null) connection.close(); if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } } }
880b0ed2-f980-4b6a-95f5-1401b6e3ffca
1
public String[] nextStrings(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; ++i) { res[i] = next(); } return res; }
ddda7ca5-3ba1-4fa3-9f9b-dd96724aea29
9
private String justify(ArrayList<String> line, int wordLength, int L, boolean lastLine) { int empties = line.size() - 1; if (empties == 0 || lastLine) { String result = ""; for (int i = 0; i < line.size(); i++) { result += line.get(i); if (i != line.size() - 1) { result += " "; } } for (int i = result.length(); i < L; i++) { result += " "; } return result; } else { int smallSpace = (L - wordLength) / empties; int bigSpaceCount = (L - wordLength) % empties; String space = ""; for (int i = 0; i < smallSpace; i++) { space += " "; } StringBuilder result = new StringBuilder(); for (int i = 0; i < line.size(); i++) { result.append(line.get(i)); if (i < bigSpaceCount) { result.append(" "); } if (i != line.size() - 1) { result.append(space); } } return result.toString(); } }
d5190d7a-b694-46f7-992c-267aef002408
5
public void update(int xPos, int yPos, boolean isDown) { if (contains(xPos, yPos)) { if (isDown && !oldIsDown) event.run(); if (isSelected < gradations - 1) isSelected++; } else if (isSelected > 0) isSelected--; oldIsDown = isDown; }
d687ef82-f217-4339-9e1f-7c38498e7fb5
7
public void DoAction() { Scanner sc = new Scanner(System.in); String action; boolean valid = false; while(!valid) { action = Input.getStringInput(sc, "Action: "); if(action.equalsIgnoreCase("EXPLORE")) { e.Traveling(); } else if(action.equalsIgnoreCase("SHELTER")) { s.Dialog(); } else if(action.equalsIgnoreCase("WATER")) { } else if(action.equalsIgnoreCase("FOOD")) { } else if(action.equalsIgnoreCase("FIRE")) { } else if(action.equalsIgnoreCase("ITEMS")) { } else { Dialog.message("I don't understand what that is. Try again."); sc.nextLine(); continue; } valid = true; } }
b0d00cd9-b401-4fe0-a95d-cc0200be38df
8
public int[] twoSum(int[] numbers, int target) { if (numbers == null || numbers.length == 0) return null; int[] result = new int[2]; //Put all numbers in a map with indexes as values Map<Integer, Integer> allNumbers = new HashMap<Integer, Integer>(); for (int i=0; i<numbers.length; i++) { allNumbers.put(numbers[i], i); } //Check diff against map for (int i=0; i<numbers.length; i++) { int diff = target - numbers[i]; if (allNumbers.containsKey(diff) && allNumbers.get(diff) != i) { int first = i; int second = findIndex(numbers, diff, -1); if (first == second) { int third =findIndex(numbers, diff, first); second = third; } first = ++first; second = ++second; if (first < second) { result[0] = first; result[1] = second; } else { result[0] = second; result[1] = first; } break; } } return result; }
c2e2130b-0838-4cdf-9f9b-c93c96f7d37a
7
private void handleGameInput() { while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { if (Keyboard.getEventKey() == KeyPress.PAUSE.getKeyID()) { GameState.pauseUnpause(); } } } boolean sprinting = KeyPress.SPRINT.isDown(); if (KeyPress.FORWARD.isDown()) { model.getPlayer().moveForward(sprinting); } if (KeyPress.BACKWARD.isDown()) { model.getPlayer().moveBackward(sprinting); } if (KeyPress.LEFT.isDown()) { model.getPlayer().moveLeft(sprinting); } if (KeyPress.RIGHT.isDown()) { model.getPlayer().moveRight(sprinting); } }
296fe0bc-467a-49a5-9b74-bf1aadec4bb5
3
protected void rehash() { capacity *= 2; Entry<K, V>[] old = bucket; bucket = (Entry<K, V>[]) new Entry[capacity]; setRandomScaleAndShift();// calling hash function index will be // different for (int i = 0; i < old.length; i++) { Entry<K, V> e = old[i]; if ((e != null) && (e != available)) { int j = -1 - findEntry(e.getKey()); bucket[j] = e; } } }
fd6e6ab9-26b7-4eab-93e1-4d5ffbf881ed
5
public void raiseUncharted() { Tile tile; for (int i = 0; i < uncharted.length; i++) { for (int j = 0; j < uncharted[0].length; j++) { tile = new Tile(i, j); if (((uncharted[i][j] + 5) < 30 && uncharted[i][j] > -1 && game.isVisible(tile))) { uncharted[i][j] += 5; } } } }
988b07d2-bb61-461d-9bd0-6d02fd97705d
3
public static List<Word> blur(int distance, String rawWord) { List<Word> returnList = new ArrayList<Word>(100000); String word = rawWord.toLowerCase().trim(); Set<Word> returnSet = new HashSet<Word>(100000); for (int i=1; i<= distance; i++) { List<String> alphabet = getAlphabetCombination(i); for (String junk: alphabet) { Set<Word> result = getVariants(junk.toCharArray(), word); returnSet.addAll(result); // System.out.println("Adding " + result.size()); // System.out.println("new size after " + junk + " : " + returnSet.size()); } } for (Word w: returnSet) { returnList.add(w); } Collections.sort(returnList); return returnList; }
9df7f87a-3b8f-48a3-bf5b-73a38355897a
2
public Match getMatch(int matchNumber) { for (Match match : matches) { if (match.getMatchNumber() == matchNumber) { return match; } } return null; }
b8dac88e-bdd6-44c0-aa23-cc724d2cbc82
8
private final void parseStartTag() throws IOException { read(); // < mName = readName(); mStack.add(mName); while (true) { String attrName; int ch; int pos; skip(); ch = mPeek0; if (ch == '/') { mIsEmptyElementTag = true; read(); skip(); read('>'); break; } if (ch == '>') { read(); break; } if (ch == -1) { fail(UNEXPECTED_EOF); } attrName = readName(); if (attrName.length() == 0) { fail("attribute name expected"); //$NON-NLS-1$ } skip(); read('='); skip(); ch = read(); if (ch != '\'' && ch != '"') { fail("<" + mName + ">: invalid delimiter: " + (char) ch); //$NON-NLS-1$ //$NON-NLS-2$ } pos = mTextPos; pushText(ch); mAttributeMap.put(attrName, pop(pos)); if (ch != ' ') { read(); // skip end quote } } }
f4e2b689-cf8a-4508-bda3-cd72a365870f
4
public void init(){ // 读取配置文件,根据配置文件创建配置信息 Properties props = new Properties(); try { InputStream fileInput = new FileInputStream(this.getClass().getResource("/").toString().replace("file:/", "") + CONFIG_FILE ); // 加载配置文件 props.load(fileInput); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("配置文件不存在,请仔细检查"); } catch (IOException e) { e.printStackTrace(); System.out.println("配置文件读取错误"); } Enumeration<String> names = (Enumeration<String>) props.propertyNames(); while(names.hasMoreElements()){ String key = names.nextElement(); String countStr = props.getProperty(key); String values[] = countStr.split(DOT_FLAG); Stock stockUrl = new Stock(); stockUrl.setName(key); if(values.length >= 2){ // 国内股指 stockUrl.setChina(true); stockUrl.setStockData(values[0]); }else{// 国外股指 stockUrl.setChina(false); stockUrl.setStockData(countStr); } this.stockUrl.add(stockUrl); } createStockCollectThread(Thread.NORM_PRIORITY);// 读取线程 }
3ae7d0de-4b2c-4c9b-81ac-fb4e9b336751
0
public void setVal(int i) { mySlider.setValue(i); refresh(); // getRootPane().repaint(); }
3732b62d-a72f-4162-b9b8-dab43056b8df
4
public SubGrid (Grid<E> _backing, int _x0, int _y0, int _w, int _h) { x0 = _x0; y0 = _y0; w = _w; h = _h; backing = _backing; if (x0 < 0 || y0 < 0 || x0 + w >= backing.width() || y0 + h >= backing.height()) throw new ArrayIndexOutOfBoundsException(); }
07462b7e-9012-4400-b41e-de732c3f923f
1
public static void main(String st[]) throws IOException { /*FileReader fr = new FileReader("http://kural.muthu.org/kural.php");*/ URL u = new URL ("http://kural.muthu.org/kural.php?pid=2"); // URL u = new URL ("http://cinekadal.blogspot.in/"); BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream())); DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("/Users/arun/Hack/temp/tamil-op.txt"))); String s; while( (s = br.readLine()) !=null) { System.out.println(s); dos.writeBytes(s); } }
3912c767-559c-4bec-82b8-81b937773f10
8
protected void addInstance(Element parent, Instance inst) { Element node; Element value; Element child; boolean sparse; int i; int n; int index; node = m_Document.createElement(TAG_INSTANCE); parent.appendChild(node); // sparse? sparse = (inst instanceof SparseInstance); if (sparse) node.setAttribute(ATT_TYPE, VAL_SPARSE); // weight if (inst.weight() != 1.0) node.setAttribute(ATT_WEIGHT, Utils.doubleToString(inst.weight(), m_Precision)); // values for (i = 0; i < inst.numValues(); i++) { index = inst.index(i); value = m_Document.createElement(TAG_VALUE); node.appendChild(value); if (inst.isMissing(index)) { value.setAttribute(ATT_MISSING, VAL_YES); } else { if (inst.attribute(index).isRelationValued()) { child = m_Document.createElement(TAG_INSTANCES); value.appendChild(child); for (n = 0; n < inst.relationalValue(i).numInstances(); n++) addInstance(child, inst.relationalValue(i).instance(n)); } else { if (inst.attribute(index).type() == Attribute.NUMERIC) value.appendChild(m_Document.createTextNode(Utils.doubleToString(inst.value(index), m_Precision))); else value.appendChild(m_Document.createTextNode(validContent(inst.stringValue(index)))); } } if (sparse) value.setAttribute(ATT_INDEX, "" + (index+1)); } }
3c72921f-f550-45e8-8497-85e2705833f8
8
private void consolodateLongs() { for(int i=0;i<longArray.length-1;i++) { if(((longArray[i]&NEXT_FLAGL)==0) &&(longArray[i]+1==(longArray[i+1]&LONG_BITS))) { if((longArray[i+1]&NEXT_FLAGL)>0) { if((i>0)&&((longArray[i-1]&NEXT_FLAGL)>0)) { shrinkLongArray(i,2); return; } shrinkLongArray(i,1); longArray[i]=((longArray[i]&LONG_BITS)-1)|NEXT_FLAGL; return; } if((i>0)&&((longArray[i-1]&NEXT_FLAGL)>0)) { shrinkLongArray(i+1,1); longArray[i]++; return; } longArray[i]=longArray[i]|NEXT_FLAGL; return; } } }
67ba0318-5de3-449f-ad96-604157d38eb2
9
private void paintExternalForce(Graphics2D g) { g.setColor(((MDView) model.getView()).contrastBackground()); double place1 = x + width; double place2 = place1 + 8.0; double place3 = y + height; double place4 = place3 + 8.0; int nx = (int) (width / delta); int ny = (int) (height / delta); int i; double half; if (tempLine == null) tempLine = new Line2D.Double(); g.setStroke(ViewAttribute.THIN); if (hx < -Particle.ZERO) { for (i = 0; i < ny; i++) { half = (i + 0.5) * delta; /* draw arrows on the right side */ tempLine.setLine(place1 + 4, y + half, place2 + 4, y + half); g.draw(tempLine); tempLine.setLine(place1 + 4, y + half, place1 + 6, y + half + 2); g.draw(tempLine); tempLine.setLine(place1 + 4, y + half, place1 + 6, y + half - 2); g.draw(tempLine); } } else if (hx > Particle.ZERO) { for (i = 0; i < ny; i++) { half = (i + 0.5) * delta; /* draw arrows on the left side */ tempLine.setLine(x - 12, y + half, x - 4, y + half); g.draw(tempLine); tempLine.setLine(x - 6, y + half + 2, x - 4, y + half); g.draw(tempLine); tempLine.setLine(x - 6, y + half - 2, x - 4, y + half); g.draw(tempLine); } } if (hy < -Particle.ZERO) { for (i = 0; i < nx; i++) { half = (i + 0.5) * delta; /* draw arrows on the lower side */ tempLine.setLine(x + half, place3 + 4, x + half, place4 + 4); g.draw(tempLine); tempLine.setLine(x + half, place3 + 4, x + half + 2, place3 + 6); g.draw(tempLine); tempLine.setLine(x + half, place3 + 4, x + half - 2, place3 + 6); g.draw(tempLine); } } else if (hy > Particle.ZERO) { for (i = 0; i < nx; i++) { half = (i + 0.5) * delta; /* draw arrows on the northern side */ tempLine.setLine(x + half, y - 12, x + half, y - 4); g.draw(tempLine); tempLine.setLine(x + half + 2, y - 6, x + half, y - 4); g.draw(tempLine); tempLine.setLine(x + half - 2, y - 6, x + half, y - 4); g.draw(tempLine); } } }
126b82fa-6723-4851-a979-be07e473010c
5
public boolean check_read() { if (!in_active || (state != State.active && state != State.pending)) return false; // Check if there's an item in the pipe. if (!inpipe.check_read ()) { in_active = false; return false; } // If the next item in the pipe is message delimiter, // initiate termination process. if (is_delimiter(inpipe.probe ())) { Msg msg = inpipe.read (); assert (msg != null); delimit (); return false; } return true; }
7af0d8f4-b543-45ae-9ac3-5b62a3871311
0
public String getStatus() { return status; }
f827359c-5e21-429b-8301-4659cdcb15a6
2
public void removeActionListener(ActionListener listener) { if (mActionListeners != null) { mActionListeners.remove(listener); if (mActionListeners.isEmpty()) { mActionListeners = null; } } }
7c76f834-f506-481a-ace8-c3d8d023685f
4
public void save(Course[][] courses, String fileName) { try { FileWriter output = new FileWriter(fileName); BufferedWriter out = new BufferedWriter(output); for (int x = 0; x < courses.length; x++) { for (int y = 0; y < courses[x].length; y++) { if (courses[x][y] != null) { String temp = courses[x][y].getSemester() + " " + courses[x][y].getCourse() + " " + courses[x][y].getDepartment() + " " + courses[x][y].getCourseNumber() + " " + courses[x][y].getCreditHours() + " " + courses[x][y].getGrade() + " " + courses[x][y].getCourseTitle(); out.write(temp + "\n"); } } } out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
e40cc813-dabb-4d4c-9a46-595359092f95
3
public User getUser(String email) { Connection connection = null; User user = new User(); String query = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); query = "SELECT username, bio FROM users WHERE email = ?;"; statement = (PreparedStatement)connection.prepareStatement(query); statement.setString(1, email); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { user.setEmail(email); user.setUsername(resultSet.getString("username")); user.setBio(resultSet.getString("bio")); } } catch (SQLException sqle) { sqle.printStackTrace(); } finally { try { statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return user; }
2d87a5d1-9fe6-43e8-9573-2d7affe5c77d
3
@Override public void collideWith(Element e) { if (isActive()) { if (e instanceof Destroyable) getGrid().permanentlyRemoveElement(e); if (e instanceof Player) { Player player = (Player) e; forceFieldConnection.incrementPlayerTrappedCount(player); } } }
8b0ab65c-c982-4c09-8db1-dbc269cca0ee
3
public void loadSoundpackList() { logger.debug("Loading all installed Soundpacks"); this.soundpacks.clear(); if (SOUNDPACKFOLDER.exists()) { for (File soundpackFolder : SOUNDPACKFOLDER.listFiles()) { if (soundpackFolder.isDirectory()) { soundpacks.add(soundpackFolder); logger.debug(soundpackFolder.getName() + " added to List"); } } } else { logger.error("Soundpack folder is missing"); } logger.info("Loaded " + soundpacks.size() + " Soundpacks."); }
43790e60-8007-4002-983d-d6e36367727a
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(L("You already healed by ice.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 for icey healing.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("An aura surrounds <S-NAME>.")); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for icey healing, but <S-HIS-HER> plea is not answered.",prayWord(mob))); // return whether it worked return success; }
b04c5b89-999c-45ff-ac5a-6cc704ba09ca
0
@Override public CheckResultMessage checkFileName() { return errorNameFormat(); }
234f3c69-79ad-4b30-b2eb-06a8e787f5e7
9
public void destroyProgress(String missileId, String type) { Iterator<String> keySetIterator = map.keySet().iterator(); Iterator<String> destructorsSetIterator = destructors.keySet() .iterator(); if (type == "missile") { while (keySetIterator.hasNext()) { String key = keySetIterator.next(); progressBar = map.get(key); if (key.equalsIgnoreCase(missileId)) { progressBar.setVisible(false); } } } else if (type == "destructor") { while (destructorsSetIterator.hasNext()) { String key = destructorsSetIterator.next(); progressBar = map.get(key); if (key.equalsIgnoreCase(missileId)) { progressBar.setVisible(false); } } } else if (type == "IronDome") { while (destructorsSetIterator.hasNext()) { String key = destructorsSetIterator.next(); progressBar = map.get(key); if (key.equalsIgnoreCase(missileId)) { progressBar.setVisible(false); } } } }
27ff396d-13ec-44fe-9e7c-64ead96b5a11
7
public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
4b76de9d-7b26-40cf-8af9-ca7e4559e5f5
0
public BranchLeaderListResponse( final Boolean success, final String errorMessage, final List<BranchLeader> branchLeaderList ) { super(success, errorMessage); this.branchLeaderList = branchLeaderList; }
3e5bb5e3-b929-49ee-b0d9-1b8620944661
4
public CourseRec getClassByLongNameAndUni(String name, String uni, Source source) { for (CourseRec cr : submodel[source.ordinal()].courses.values()) { if (name.equals(cr.getName())) { for (DescRec dr : cr.getUniversities()) if (uni.equals(dr.getId())) return cr; } } return null; }
6b8c43d7-26f3-4f0f-b572-bf74501d9fb2
1
public final boolean hasOriginalAccelerator() { KeyStroke ks = getAccelerator(); return ks == null ? mOriginalAccelerator == null : ks.equals(mOriginalAccelerator); }
93bde882-7872-4922-887b-596439a4cbf6
7
public static void printMinCutsToPartitionNCube(char[] str) { int len = str.length, j=0; int[][] c = new int[len][len]; //min cuts required to partition substring str[i...j] boolean[][] p = new boolean[len][len]; //p[i][j] is true if str[i...j] is palindrome. //c[i][j] is 0 if p[i][j] is true. for (int i = 0; i < len; i++) { c[i][i] = 0; p[i][i] = true; } // for substrings of length 2 to len for (int L = 2; L <= len; L++) { for (int i = 0; i < len-L+1; i++) { j = i+L-1; if(L == 2) { p[i][j] = (str[i] == str[j]); } else { p[i][j] = (str[i] == str[j]) && p[i+1][j-1]; } if(p[i][j]) { c[i][j] = 0; } else { c[i][j] = 1000; //some INT_MAX kind of value. for (int k = i; k < j; k++) { c[i][j] = min(c[i][j], c[i][k] + c[k+1][j] + 1); } } } } System.out.println("minimum cuts : " + c[0][len-1]); }
efd55505-d47b-427e-88e2-c6e198fc4dfc
9
public static void defaultCmdLineOptionHandler(CmdLineOption option, Stella_Object value) { { String property = option.configurationProperty; Stella_Object defaultvalue = option.defaultValue; if (property == null) { property = ""; { StringWrapper key = null; Cons iter000 = option.keys; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { key = ((StringWrapper)(iter000.value)); if ((StringWrapper.unwrapString(key)).length() > property.length()) { property = key.wrapperValue; } } } } if ((defaultvalue == null) && (option.valueType == Stella.SGT_STELLA_BOOLEAN)) { defaultvalue = Stella.TRUE_WRAPPER; } if (value == null) { value = defaultvalue; } if (option.multiValuedP) { if (Stella_Object.safePrimaryType(value) == Stella.SGT_STELLA_CONS) { { Cons value000 = ((Cons)(value)); { Stella_Object val = null; Cons iter001 = value000; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { val = iter001.value; Stella.addConfigurationProperty(property, val, null); } } } } else { Stella.addConfigurationProperty(property, value, null); } } else { Stella.setConfigurationProperty(property, value, null); } } }
58c88dc5-6519-418f-b0d5-326537116b3e
9
int evaluateState(Checker[][] state) { int whiteNumber = 0; int blackNumber = 0; for (int row = 0; row < 8; row++) { for (int col = 0; col < 4; col++) { if (state[row][col] != null) { if (state[row][col].getColor() == 1) { whiteNumber++; if (state[row][col].isKing()) { whiteNumber += 2; } } if (state[row][col].getColor() == -1) { blackNumber++; if (state[row][col].isKing()) { blackNumber += 2; } } } } } if (whiteNumber == 0) { return -100; } else if (blackNumber == 0) { return 100; } else { return whiteNumber - blackNumber; } }
7a22e0c1-2d7d-41f6-93c2-b62d2a64c60e
7
public Result bfs() { long startTime = System.currentTimeMillis(); Queue<Node> queue = new ArrayDeque<Node>(); Set<Node> set = new HashSet<Node>(); int nodesProcessed = 0; queue.add(initial); set.add(initial); while(!queue.isEmpty()) { Node temp = queue.poll(); nodesProcessed++; if(temp.getState().equals(finalState)) { long endTime = System.currentTimeMillis(); Deque<Grid.Direction> pathStack = new ArrayDeque<Grid.Direction>(); pathStack.add(temp.getDirection()); Node temp2 = temp.getParent(); while(temp2.getParent() != null) { pathStack.addFirst(temp2.getDirection()); temp2 = temp2.getParent(); } StringBuilder pathTaken = new StringBuilder(pathStack.size()); if(pathStack.peek().toString().equals(null)) { } else { while(!pathStack.isEmpty()) { pathTaken.append(pathStack.removeFirst().toString()); } } return new Result(pathTaken.toString(), nodesProcessed, startTime-endTime); } for(Node child : temp.successors()) { if(!(set.contains(child))) { set.add(child); queue.add(child); } } } return null; }
dba05835-eb87-4471-96c1-6d4fde59f83a
4
public static ArrayList<FriendRequestMessage> getMessagesByUserID(int userID) { ArrayList<FriendRequestMessage> FriendRequestMessageQueue = new ArrayList<FriendRequestMessage>(); try { String statement = new String("SELECT * FROM " + DBTable +" WHERE uid2 = ?"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, userID); ResultSet rs = DBConnection.DBQuery(stmt); rs.beforeFirst(); while(rs.next()) { FriendRequestMessage fm = new FriendRequestMessage( rs.getInt("mid"), rs.getInt("uid1"), rs.getInt("uid2"), rs.getTimestamp("time"), rs.getBoolean("isConfirmed"), rs.getBoolean("isRejected")); if (!fm.isConfirmed && !fm.isRejected) FriendRequestMessageQueue.add(fm); } } catch (SQLException e1) { e1.printStackTrace(); } return FriendRequestMessageQueue; }
c25da176-5c48-40c4-b7a7-fc1a6edd9a22
7
public void partitionDouble(FieldInfo fieldInfo, int partitions) { FieldIterator iter = getFieldIterator(fieldInfo); ArrayList<Double> values = new ArrayList<Double>(); ArrayList<Double> boundaries = new ArrayList<Double>(); // first pass, generate partition boundary while (iter.hasNext()) { Field f = iter.next(); values.add(Double.parseDouble(f.getRaw())); } Collections.sort(values); int interval = records.size() / partitions; assert(interval > 0); double endpoint = 0; for (int i = 0; i < partitions; i++) { if (i == partitions - 1) endpoint = values.get(values.size() - 1); else endpoint = values.get((i+1) * interval); boundaries.add(endpoint); } // second pass, generate mapping iter = getFieldIterator(fieldInfo); while (iter.hasNext()) { Field f = iter.next(); double v = Double.parseDouble(f.getRaw()); int idx = 0; while (boundaries.get(idx) < v) { idx++; } f.setRaw(Integer.toString(idx)); } try { BufferedWriter writer = new BufferedWriter(new FileWriter("data/" + fieldInfo.getName() + ".range")); writer.write(values.get(0).toString()); writer.newLine(); for (Double i : boundaries) { writer.write(i.toString()); writer.newLine(); } writer.close(); } catch (IOException e) { e.printStackTrace(); } }
859e32fa-bd47-4c02-b069-d67d993a76ec
0
public CountingBloomFilter(final int len) { super(); this.filter = new Short[len]; Arrays.fill(filter, (short)0); }
75222b8f-97fc-4d2c-8f2a-db579115688c
8
void generateLeafNodeList() { this.height = (int)((double)this.heightLimit * this.heightAttenuation); if (this.height >= this.heightLimit) { this.height = this.heightLimit - 1; } int var1 = (int)(1.382D + Math.pow(this.leafDensity * (double)this.heightLimit / 13.0D, 2.0D)); if (var1 < 1) { var1 = 1; } int[][] var2 = new int[var1 * this.heightLimit][4]; int var3 = this.basePos[1] + this.heightLimit - this.leafDistanceLimit; int var4 = 1; int var5 = this.basePos[1] + this.height; int var6 = var3 - this.basePos[1]; var2[0][0] = this.basePos[0]; var2[0][1] = var3; var2[0][2] = this.basePos[2]; var2[0][3] = var5; --var3; while (var6 >= 0) { int var7 = 0; float var8 = this.layerSize(var6); if (var8 < 0.0F) { --var3; --var6; } else { for (double var9 = 0.5D; var7 < var1; ++var7) { double var11 = this.scaleWidth * (double)var8 * ((double)this.rand.nextFloat() + 0.328D); double var13 = (double)this.rand.nextFloat() * 2.0D * Math.PI; int var15 = MathHelper.floor_double(var11 * Math.sin(var13) + (double)this.basePos[0] + var9); int var16 = MathHelper.floor_double(var11 * Math.cos(var13) + (double)this.basePos[2] + var9); int[] var17 = new int[] {var15, var3, var16}; int[] var18 = new int[] {var15, var3 + this.leafDistanceLimit, var16}; if (this.checkBlockLine(var17, var18) == -1) { int[] var19 = new int[] {this.basePos[0], this.basePos[1], this.basePos[2]}; double var20 = Math.sqrt(Math.pow((double)Math.abs(this.basePos[0] - var17[0]), 2.0D) + Math.pow((double)Math.abs(this.basePos[2] - var17[2]), 2.0D)); double var22 = var20 * this.branchSlope; if ((double)var17[1] - var22 > (double)var5) { var19[1] = var5; } else { var19[1] = (int)((double)var17[1] - var22); } if (this.checkBlockLine(var19, var17) == -1) { var2[var4][0] = var15; var2[var4][1] = var3; var2[var4][2] = var16; var2[var4][3] = var19[1]; ++var4; } } } --var3; --var6; } } this.leafNodes = new int[var4][4]; System.arraycopy(var2, 0, this.leafNodes, 0, var4); }
ea9bddfc-f6d6-4cfe-803d-683c79ac660b
4
public static <E> E sample(Counter<E> counter) { double total = counter.totalCount(); double rand = random.nextDouble(); double sum = 0.0; if (total <= 0.0) { throw new RuntimeException("Non-positive counter total: " + total); } for (E key: counter.keySet()) { double count = counter.getCount(key); if (count < 0.0) { throw new RuntimeException("Negative count in counter: " + key + " => " + count); } double prob = count / total; sum += prob; if (rand < sum) { return key; } } throw new RuntimeException("Shouldn't Reach Here"); }
31fd8e06-9897-41d1-9988-d29ad653d363
8
public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) {} if(DSSUpdater.getHighLight() != highlight) { highlight = DSSUpdater.getHighLight(); DSSUpdater.getHighPathAr(dsa); drawSomething = true; } if(DSSUpdater.getGraphName() != oldGN) { //repaint(); oldGN = DSSUpdater.getGraphName(); //repaint(); drawSomething = true; } if((DSSUpdater.getHighPath() != dsa[1] || DSSUpdater.getHighPathLength() != dsa.length) && DSSUpdater.getGraphName()>=2) { DSSUpdater.getHighPathAr(dsa); } if(drawSomething) { repaint(); drawSomething = false; } } }
5b5bbb6c-7096-4570-bf01-6d1976c87767
7
private int shiftKeys(int pos) { // Shift entries with the same hash. int last, slot; for (;;) { pos = ((last = pos) + 1) & mask; while (used[pos]) { slot = MurmurHash3.murmurhash3_x86_32(key, pos * sliceLength, sliceLength) & mask; if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break; pos = (pos + 1) & mask; } if (!used[pos]) break; copyKeys(pos, last); } used[last] = false; return last; }
9f4e51ed-087d-4744-9c46-1d4f8400ab0a
9
public static Class getOptionFormat(byte code) { OptionFormat format = _DHO_FORMATS.get(code); if (format == null) { return null; } switch (format) { case INET: return InetAddress.class; case INETS: return InetAddress[].class; case INT: return int.class; case SHORT: return short.class; case SHORTS: return short[].class; case BYTE: return byte.class; case BYTES: return byte[].class; case STRING: return String.class; default: return null; } }