method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
a69fbc1d-52fc-4d75-8654-883bfb1b0243
6
private void processAsXML(ByteArrayOutputStream bytes) { ByteArrayInputStream input = new ByteArrayInputStream(bytes.toByteArray()); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer xformer = factory.newTransformer(); Source source = new StreamSource(input); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument(); Result result = new DOMResult(doc); xformer.transform(source, result); NodeList root = doc.getElementsByTagName(CommunityConstants.RESPONSE_ROOT); Node response = root.item(0); String refreshInterval; NodeList firstLevel = response.getChildNodes(); for( int i=0; i<firstLevel.getLength(); i++ ) { Node kid = firstLevel.item(i); if( kid.getLocalName().equals(CommunityConstants.REFRESH_INTERVAL) ) { refreshInterval = kid.getTextContent(); System.out.println("got refresh interval: " + refreshInterval); } else if( kid.getLocalName().equals(CommunityConstants.FRIEND_LIST) ) { parseFriendList(kid); } } } catch (ParserConfigurationException e) { // couldn't even create an empty doc } catch (TransformerException e) { ; } catch( NullPointerException e ) { // basically means the file had bad structure e.printStackTrace(); } }
0314c12b-c68b-4164-b0d3-7166ea1587fa
6
public void undo(){ Command commande = commandeCourante.commande; commande.undo(); //Actualisation du modèle puis de la vue. if(commande instanceof LirePlanCommand){ zone = ((LirePlanCommand)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof LireLivraisonsCommand){ zone = ((LireLivraisonsCommand)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof AjoutLivraisonCommande){ zone = ((AjoutLivraisonCommande)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof SuppressionLivraisonCommande){ zone = ((SuppressionLivraisonCommande)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof CalculerTourneeCommand){ zone.getTournee().setCheminsResultats(((CalculerTourneeCommand)commande).getChemins()); Fenetre.getInstance().actualiserPlan(); } commandeCourante = commandeCourante.previous; Fenetre.getInstance().setRedoable(true); if(commandeCourante.previous==null){ Fenetre.getInstance().setUndoable(false); } }
4cce219d-cd2c-42a4-a7c5-5b823bfac94a
8
private boolean verfiyeTextField(){ boolean r = true; if (lectureName.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "Lecture text is empty", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tag.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "Tag text is empty", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tagEndTime.compareTo(lectureStartTime) == 0 && tagEndDate.compareTo(lectureStartDate)==0){ JOptionPane.showMessageDialog(mainForm, "Start date and time are equal to end date and time\n Can not get any tweets ", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tagStartDate.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "Start date is empty ", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tagStartTime.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "Start time is missing", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tagEndDate.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "End date is missing", "Error", JOptionPane.ERROR_MESSAGE); return false; } else if (tagEndTime.isEmpty()){ JOptionPane.showMessageDialog(mainForm, "end time is missing", "Error", JOptionPane.ERROR_MESSAGE); return false; } return r; }
ed283155-b174-4e04-845d-78a0ccaebfa5
2
public static String shortName(final Class c) { final String n = c.getName(); final int i = n.lastIndexOf("."); return i == -1 || i == n.length() ? n : n.substring(i+1); }
bf15e7a6-7972-4a1f-9272-a7c97cc296a6
8
public final Level loadOnline(String var1, String var2, int var3) { if(this.progressBar != null) { this.progressBar.setTitle("Loading level"); } try { if(this.progressBar != null) { this.progressBar.setText("Connecting.."); } HttpURLConnection var6; (var6 = (HttpURLConnection)(new URL("http://" + var1 + "/level/load.html?id=" + var3 + "&user=" + var2)).openConnection()).setDoInput(true); if(this.progressBar != null) { this.progressBar.setText("Loading.."); } DataInputStream var7; if((var7 = new DataInputStream(var6.getInputStream())).readUTF().equalsIgnoreCase("ok")) { return this.load((InputStream)var7); } else { if(this.progressBar != null) { this.progressBar.setText("Failed: " + var7.readUTF()); } var7.close(); Thread.sleep(1000L); return null; } } catch (Exception var5) { var5.printStackTrace(); if(this.progressBar != null) { this.progressBar.setText("Failed!"); } try { Thread.sleep(3000L); } catch (InterruptedException var4) { ; } return null; } }
4beb4fff-c9a0-4c51-9394-a0fe5335e6e9
4
public void move() { // Controls wrap around in the x-axis if (x >= fWidth) { double temp = middleX - x; x = -1 * image.getWidth(null); middleX = x + temp; } else if (x <= -image.getWidth(null)) { double temp = middleX - x; x = fWidth; middleX = x + temp; } // Controls wrap around in the y-axis if (y >= fHeight) //Right side of screen { double temp = middleY - y; y = -1 * image.getHeight(null); middleY = y + temp; } else if (y <= -image.getHeight(null)) //Left side of screen { double temp = middleY - y; y = fHeight; middleY = y + temp; } // Update the x,y values to actually move the bullet object x += xVelocity; y += yVelocity; //Update the midde x,y coordinates of the object that shoots the bullets. middleX += xVelocity; middleY += yVelocity; // Calculates the distance traveled for each time the bullet moves. double dX = Math.abs(xVelocity); double dY = Math.abs(yVelocity); distance += Math.sqrt((dX * dX) + (dY * dY)); }
8210f3aa-9742-4a37-b037-f87f48e10281
6
public boolean growPumpkins(Player player, String[] args, int radius) { Block playerCenter = player.getLocation().getBlock(); // Get Centrepoint (Player) int pumpkins = 0; for (int x = -radius; x < radius; x++) { for (int y = -radius; y < radius; y++) { for (int z = -radius; z < radius; z++) { Block b = playerCenter.getRelative(x,y,z); if (playerCenter.getRelative(x,y,z).getType() == Material.PUMPKIN_STEM) { int dataValue = b.getData(); if (dataValue != 7) { b.setData((byte) 7); pumpkins++; } else if (dataValue == (byte) 7) { // DO NOTHING } } } } } player.sendMessage(ChatColor.GREEN+"Grown "+pumpkins+" pumpkins"); return true; }
41424252-f126-4b86-804a-fba259fee9ac
5
public void insertarDespuesDeX(T dato, T x){ Nodo<T> nodoQ = this.inicio; Nodo<T> nodoT = null; boolean bandera = true; if(this.inicio == null){ this.inicio = new Nodo<T>(dato); }else{ while(nodoQ.getInfo() != x && bandera){ if(nodoQ.getLiga() != null){ nodoQ = nodoQ.getLiga(); }else{ bandera = false; } } if(bandera){ nodoT = new Nodo<T>(dato); nodoT.setLiga(nodoQ.getLiga()); nodoQ.setLiga(nodoT); }else{ System.out.println("Nodo de referencia no se ha encontrado"); } } }
c68c733a-380e-42dd-94a5-d1d4831b4793
5
public Date nextTimePeriod(){ String c = sdf.format(periodStartDate); int month = Integer.parseInt(c.substring(5,7)); int day = Integer.parseInt(c.substring(8,10)); int year = Integer.parseInt(c.substring(0,4)); if(day == 1){ day = 16; }else{ day = 1; month++; if(month > 12){ month %= 12; year++; } } String extraZeroForMonth = "0"; String extraZeroForDay = "0"; if(month > 9){ extraZeroForMonth = ""; } if(day > 9){ extraZeroForDay = ""; } String newDate = year + "-" + extraZeroForMonth + month + "-" + extraZeroForDay + day; try{ periodStartDate = sdf.parse(newDate); }catch(Exception ex){ System.out.println(ex); } return periodStartDate; }
c8afd305-1492-43a4-a5da-284733d0e0ab
4
private void checkFull(Node node) { for (Node n : node.children) { if (n == null) return; // not full, nothing to do else if (n.full == false) return; // not full, nothing to do } // all children are full, flag and check recursively upwards node.full = true; if (node != root) checkFull(node.parent); }
71c77173-3945-4a1f-8bec-be9d2f5c55f5
7
public static Grandeur getGrandeurFromString(String grandeur) { Grandeur ret; switch (grandeur.toUpperCase()) { case "LONGUEUR": ret = Grandeur.LONGUEUR; break; case "TEMPS": ret = Grandeur.TEMPS; break; case "COURANT_ELECTRIQUE": ret = Grandeur.COURANT_ELECTRIQUE; break; case "INTENSITE_LUMINEUSE": ret = Grandeur.INTENSITE_LUMINEUSE; break; case "MASSE": ret = Grandeur.MASSE; break; case "MATIERE": ret = Grandeur.MATIERE; break; case "TEMPERATURE": ret = Grandeur.TEMPERATURE; break; default: throw new IllegalArgumentException("La grandeur demandée est inconnue"); } return ret; }
fcdd8207-04f3-4ce6-9eee-2aecc0196c01
7
public void piirraRobotti(Pelaaja pelaaja, Graphics g){; Robotti robo=pelaaja.getRobotti(); switch (pelaaja.getMones()){ case 1:g.setColor(Color.blue); break; case 2:g.setColor(Color.red); break; case 3:g.setColor(Color.GREEN); break; case 4: g.setColor(Color.magenta); break; } int y=robo.getRuutu().getY(); int x=robo.getRuutu().getX(); if (robo.getSuunta()==0) { int [] xpisteet={(x-1)*ruudunkoko+5,(x-1)*ruudunkoko+33,(x-1)*ruudunkoko+18}; int [] ypisteet={koko-y*ruudunkoko+30,koko-y*ruudunkoko+30,koko-y*ruudunkoko+10}; g.drawPolygon(xpisteet, ypisteet, 3); g.setColor(Color.black); g.drawString(pelaaja.getMones()+"", (x-1)*ruudunkoko+ruudunkoko/2-3, koko-y*ruudunkoko+28); } else if (robo.getSuunta()==2){ int [] xpisteet={(x-1)*ruudunkoko+5,(x-1)*ruudunkoko+33,(x-1)*ruudunkoko+18}; int [] ypisteet={koko-y*ruudunkoko+8,koko-y*ruudunkoko+8,koko-y*ruudunkoko+28}; g.drawPolygon(xpisteet, ypisteet, 3); g.setColor(Color.black); g.drawString(pelaaja.getMones()+"", (x-1)*ruudunkoko+ruudunkoko/2-3, koko-y*ruudunkoko+20); } else if (robo.getSuunta()==1){ int [] xpisteet={(x-1)*ruudunkoko+8,(x-1)*ruudunkoko+8,(x-1)*ruudunkoko+28}; int [] ypisteet={koko-y*ruudunkoko+5,koko-y*ruudunkoko+33,koko-y*ruudunkoko+19}; g.drawPolygon(xpisteet, ypisteet, 3); g.drawString(pelaaja.getMones()+"", (x-1)*ruudunkoko+ruudunkoko/2-6, koko-y*ruudunkoko+23); } else { int [] xpisteet={(x-1)*ruudunkoko+30,(x-1)*ruudunkoko+30,(x-1)*ruudunkoko+10}; int [] ypisteet={koko-y*ruudunkoko+5,koko-y*ruudunkoko+33,koko-y*ruudunkoko+19}; g.drawPolygon(xpisteet, ypisteet, 3); g.drawString(pelaaja.getMones()+"", (x-1)*ruudunkoko+ruudunkoko/2+2, koko-y*ruudunkoko+23); } }
c7f6d9e5-0286-4d8b-91da-340fcf315780
8
public GrahamScan(Point2D[] pts) { // defensive copy int N = pts.length; Point2D[] points = new Point2D[N]; for (int i = 0; i < N; i++) points[i] = pts[i]; // preprocess so that points[0] has lowest y-coordinate; break ties by x-coordinate // points[0] is an extreme point of the convex hull // (alternatively, could do easily in linear time) Arrays.sort(points); // sort by polar angle with respect to base point points[0], // breaking ties by distance to points[0] Arrays.sort(points, 1, N, points[0].POLAR_ORDER); hull.push(points[0]); // p[0] is first extreme point // find index k1 of first point not equal to points[0] int k1; for (k1 = 1; k1 < N; k1++) if (!points[0].equals(points[k1])) break; if (k1 == N) return; // all points equal // find index k2 of first point not collinear with points[0] and points[k1] int k2; for (k2 = k1 + 1; k2 < N; k2++) if (Point2D.ccw(points[0], points[k1], points[k2]) != 0) break; hull.push(points[k2-1]); // points[k2-1] is second extreme point // Graham scan; note that points[N-1] is extreme point different from points[0] for (int i = k2; i < N; i++) { Point2D top = hull.pop(); while (Point2D.ccw(hull.peek(), top, points[i]) <= 0) { top = hull.pop(); } hull.push(top); hull.push(points[i]); } assert isConvex(); }
3746f47e-1aa0-4113-a2b4-24116b498d30
2
public static String getMacBytesAsString(byte[] data, int startOffset) { StringBuilder sb = new StringBuilder(18); for (int i = startOffset; i < startOffset + 6; i++) { byte b = data[i]; if (sb.length() > 0) sb.append(':'); sb.append(String.format("%02x", b)); } return sb.toString(); }
acde7817-97b0-40af-8145-d42484f66b81
3
public static void main(String[] args) { double c1,c2,c3; int exp; double a,b,xr,fa,fb,fxr,error,eact; double eaux=0; Scanner lector = new Scanner(System.in); System.out.println("Dame el coeficiente del termino cuadratico"); c1=lector.nextDouble(); System.out.println("Dame el exponente del termino cuadratico"); exp=lector.nextInt(); System.out.println("Dame el coeficiente del segundo termino, si no existe, teclea '0'(Cero)"); c2=lector.nextDouble(); System.out.println("Dame el termino lineal,si no existe, teclea '0'(Cero)"); c3=lector.nextDouble(); System.out.println("Ingerse el intervalo a"); a=lector.nextDouble(); System.out.println("Ingerse el intervalo b"); b=lector.nextDouble(); System.out.println("Ingrese el error minimo deseado"); error=lector.nextDouble(); int cont=0; eact=1; do{ cont++; fa=Funcion(exp,c1,c2,c3,a); fb=Funcion(exp,c1,c2,c3,b); xr=a-((fa*(b-a)/(fb-fa))); fxr=Funcion(exp,c1,c2,c3,xr); System.out.println(cont+" "+"fa= "+fa+" fb="+fb+" xr="+xr+" Error="+eact); if((fa*fxr)<0){ b=xr; } else{ a=xr; } eact=Math.abs((xr-eaux)/xr); eaux=Math.abs(xr); if(fxr==0){ System.out.println("Raiz exacta es: "+xr); System.exit(0); } }while (eact>error); System.out.println("Ultima aproximacion encontrada: "+xr); }
b01cfd17-6377-4946-ac22-107e2dc8feef
1
public static void clearInventory(InventoryItem[] targetInventory) { for(int i = 0; i<getInventorySize(targetInventory); i++) { targetInventory[i] = Parasite.items.EmptyItem; } }
8b43cc03-bf50-4fbc-8b21-39a1b09ade70
3
public static void killMeIfIGetStuck() { final Thread threadToKill = Thread.currentThread(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); if (threadToKill.getState().equals(State.RUNNABLE) && "binarySearch".equals(threadToKill.getStackTrace()[0].getMethodName())) { // every time you do this Barekov gets another vote! threadToKill.stop(); } } catch (final InterruptedException e) { e.printStackTrace(); } } }).start(); }
6dff2bfb-b6ab-481f-b6b1-6a46c133fafe
8
protected void onGuiEvent(GuiEvent ev) { // ---------------------------------------- command = ev.getType(); if (command == QUIT) { try { home.kill(); for (int i = 0; i < container.length; i++) container[i].kill(); } catch (Exception e) { e.printStackTrace(); } myGui.setVisible(false); myGui.dispose(); doDelete(); System.exit(0); } if (command == NEW_AGENT) { jade.wrapper.AgentController a = null; try { Object[] args = new Object[2]; args[0] = getAID(); String name = "Agent"+agentCnt++; a = home.createNewAgent(name, MobileAgent.class.getName(), args); a.start(); agents.add(name); myGui.updateList(agents); } catch (Exception ex) { System.out.println("Controller: Problem creating new agent"); } return; } String agentName = (String)ev.getParameter(0); AID aid = new AID(agentName, AID.ISLOCALNAME); if (command == MOVE_AGENT) { //String destName = "C"; String destName = (String)ev.getParameter(1); Location dest = (Location)locations.get(destName); MobileAgentDescription mad = new MobileAgentDescription(); mad.setName(aid); mad.setDestination(dest); MoveAction ma = new MoveAction(); ma.setMobileAgentDescription(mad); sendRequest(new Action(aid, ma)); } else if (command == CLONE_AGENT) { String destName = (String)ev.getParameter(1); Location dest = (Location)locations.get(destName); MobileAgentDescription mad = new MobileAgentDescription(); mad.setName(aid); mad.setDestination(dest); String newName = "Clone-"+agentName; CloneAction ca = new CloneAction(); ca.setNewName(newName); ca.setMobileAgentDescription(mad); sendRequest(new Action(aid, ca)); agents.add(newName); myGui.updateList(agents); } else if (command == KILL_AGENT) { KillAgent ka = new KillAgent(); ka.setAgent(aid); sendRequest(new Action(aid, ka)); agents.remove(agentName); myGui.updateList(agents); } }
17403772-0d8d-40ec-b034-b048e8d1ea55
7
private Token scanTag () { char ch = peek(1); String handle = null; String suffix = null; if (ch == '<') { forward(2); suffix = scanTagUri("tag"); if (peek() != '>') throw new TokenizerException("While scanning a tag, expected '>' but found: " + ch(peek())); forward(); } else if (NULL_BL_T_LINEBR.indexOf(ch) != -1) { suffix = "!"; forward(); } else { int length = 1; boolean useHandle = false; while (NULL_BL_T_LINEBR.indexOf(ch) == -1) { if (ch == '!') { useHandle = true; break; } length++; ch = peek(length); } handle = "!"; if (useHandle) handle = scanTagHandle("tag"); else { handle = "!"; forward(); } suffix = scanTagUri("tag"); } if (NULL_BL_LINEBR.indexOf(peek()) == -1) throw new TokenizerException("While scanning a tag, expected ' ' but found: " + ch(peek())); return new TagToken(handle, suffix); }
81ce3cba-c5a7-4c4c-979a-d0b571551bef
8
@Override protected AcceptStatus accept(final BytesRef term) { if (commonSuffixRef == null || StringHelper.endsWith(term, commonSuffixRef)) { if (runAutomaton.run(term.bytes, term.offset, term.length)) return linear ? AcceptStatus.YES : AcceptStatus.YES_AND_SEEK; else return (linear && term.compareTo(linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } else { return (linear && term.compareTo(linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK; } }
24162320-e731-4c30-b1a0-d1afbdcb40f5
8
public static void unifyTypes(Proposition prop, Skolem term1, Stella_Object term2) { { Surrogate type1 = Logic.logicalType(term1); Surrogate type2 = Logic.logicalType(term2); if ((type1 == type2) || (Logic.logicalSubtypeOfP(type1, type2) || Logic.logicalSubtypeOfP(type2, type1))) { } else if (type1 == Logic.SGT_STELLA_THING) { if (Stella_Object.isaP(term1, Logic.SGT_LOGIC_SKOLEM)) { } ((Skolem)(term1)).skolemType = type2; } else if (type2 == Logic.SGT_STELLA_THING) { if (Stella_Object.isaP(term2, Logic.SGT_LOGIC_SKOLEM)) { ((Skolem)(term2)).skolemType = type1; } } else { if (Logic.bottomP(term2)) { return; } Proposition.signalUnificationClash(prop, term1, term2); } } }
47c12c3c-8d71-46c0-aad2-45472c8fdf33
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinate that = (Coordinate) o; if (x != that.x) return false; if (y != that.y) return false; return true; }
be1d1a5f-20bb-4833-9190-4368a9652a6c
7
@Override public String getWeaponLimitDesc() { final StringBuffer str=new StringBuffer(""); if((disallowedWeaponClasses(null)!=null)&&(disallowedWeaponClasses(null).size()>0)) { str.append(L("The following weapon types may not be used: ")); for(final Iterator i=disallowedWeaponClasses(null).iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMStrings.capitalizeAndLower(Weapon.CLASS_DESCS[I.intValue()])+" "); } str.append(". "); } if((requiredWeaponMaterials()!=null)&&(requiredWeaponMaterials().size()>0)) { str.append(L("Requires using weapons made of the following materials: ")); for(final Iterator i=requiredWeaponMaterials().iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMStrings.capitalizeAndLower(CMLib.materials().getMaterialDesc(I.intValue()))+" "); } str.append(". "); } if(str.length()==0) str.append(L("No limitations.")); return str.toString().trim(); }
60aa4454-0dd4-4cd7-9138-70c7ac261259
8
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url; request.setAttribute("active", "manageUsers"); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String username = request.getParameter("username"); String password1 = request.getParameter("password1"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); String userType = request.getParameter("userType"); String status = request.getParameter("status"); if(!firstName.isEmpty() && !lastName.isEmpty() && !username.isEmpty() && !password1.isEmpty() && !email.isEmpty()) { if(password1.equals(password2)) { try { String encPassword = AeSimpleMD5.MD5(password1); int success = UserDB.insert(firstName, lastName, username, encPassword, userType, email, status); if(success==1) request.setAttribute("successMessage", "User successfully created"); else request.setAttribute("errorMessage", "Couldn't create merchant. Please try" + "again later or contact support."); //Retrieve all users from database ArrayList<User> users = UserDB.getUsers(); request.setAttribute("users", users); } catch (Exception ex) { Logger.getLogger(NewUserServlet.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("errorMessage", "Couldn't create merchant. Please try " + "again later or contact support. (Exception thrown)"); } url = "/manage/manageUsers.jsp"; } else { request.setAttribute("firstName", firstName); request.setAttribute("lastName", lastName); request.setAttribute("username", firstName); request.setAttribute("email", email); request.setAttribute("errorMessage", "Passwords don't match"); url = "/new/newUser.jsp"; } } else { request.setAttribute("firstName", firstName); request.setAttribute("lastName", lastName); request.setAttribute("username", firstName); request.setAttribute("email", email); request.setAttribute("errorMessage", "Please fill all fields"); url = "/new/newUser.jsp"; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); }
9ed6487a-4e6b-4d9a-be02-c0fa0fbf6e1f
4
public void go_top() { if(order.length()>0) { if(Idx!=null) { Idx.goTop(); go_recno( Idx.found ? Idx.sRecno : 0 ); } else { Cdx.goTop(); go_recno( Cdx.found ? Cdx.sRecno : 0 ); } } else go_recno(1); }
125b947c-8f5c-4e90-b32d-d173f5053c96
3
private void fixParent(Node parent, Node alipuu, Node p) { // p on poistetun vanhempi if (parent == null) { this.root = alipuu; } else if (parent.left == p) { parent.left = alipuu; } else { parent.right = alipuu; } if (parent != null) { parent.height = kumpiKorkeampi(laskeKorkeus(parent.left), laskeKorkeus(parent.right)) + 1; } }
0a4198fb-6595-4cef-84de-1e37469dbacb
2
private static void displayConfiguration() { logger.info("Configuration loaded:"); Enumeration<?> e = properties.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); logger.info("\"" + key + "\":\"" + properties.getProperty(key) + "\""); } }
0ae72c46-36f9-4005-b596-67393ed702ab
2
private boolean isLeave(TreeNode node) { if(node.left == null && node.right == null) return true; return false; }
954498ca-9973-46d8-9a59-1368d4abb36d
1
@Test public void setNextFigure() { HashMap<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(KING.getFigureAsString(), 1); FiguresChain figuresChain = new Bishop(figureQuantityMap); FiguresChain figuresChain1 = new Queen(figureQuantityMap); figuresChain.setNextFigure(figuresChain1); assertThat("object is null", Objects.nonNull(figuresChain.getChain()), is(true)); assertThat("object is null", Objects.nonNull(figuresChain.getChain()), is(true)); if(!Objects.isNull(figuresChain.getFigureQuantityMap())) { assertThat("key is not present", figuresChain.getFigureQuantityMap().containsKey(KING.getFigureAsString()), is(true)); assertThat("value is not present", figuresChain.getFigureQuantityMap().containsValue(1), is(true)); } assertThat("object is of different type", figuresChain.placementBehavior instanceof BishopsPlacement, is(true)); }
9c808690-ec11-486c-9509-3908453b9815
3
protected final static String createSignature(String className, Method method) { String signature = className + "." + method.getName() + "("; Class<?> types[] = method.getParameterTypes(); if(types.length > 0) { for(int i = 0; i < types.length - 1; i++) signature += types[i].getName() + ","; signature += types[types.length - 1].getName(); } signature += ")"; return signature; }
2aa78094-4e9d-4949-a9a9-cf3a04f39b0d
3
public static void main(String args[]) { Digraph G = null; try { G = new Digraph(new In(args[0])); System.out.println(args[0] + "\n" + G); } catch (Exception e) { System.out.println(e); System.exit(1); } OrderDirectedDFS order = new OrderDirectedDFS(G); System.out.println("Post order of G"); for (int v : order.postOrder()) System.out.print(v + " "); OrderDirectedDFS reverse = new OrderDirectedDFS(G.reverse()); System.out.println("\nReverse post order of R"); for (int v : reverse.reversePostOrder()) System.out.print(v + " "); }
11856e0f-2a25-4ee4-9a76-713ef2b04c4f
5
@Override public Class<?> getColumnClass(int columnIndex) { switch(columnIndex){ case 0 : return Integer.class; case 1 : return String.class; case 2 : return Integer.class; case 3 : return Integer.class; default: return null; } }
f2584f92-f5be-4f59-b5cc-3d7b6eda852b
9
public static ArrayList<Device> getDevicesList(String in){ try{ FileInputStream input = new FileInputStream(in); XMLDecoder decoder = new XMLDecoder(input); while(result.size() < 3){ Object obj = decoder.readObject(); int option = getDeviceCode(obj); switch (option) { case 1: if (containsClass(Smartphone.class)){ result.add((Smartphone) obj); } break; case 2: if (containsClass(DesktopComputer.class)){ result.add((DesktopComputer) obj); } break; case 3: if (containsClass(TabletComputer.class)){ result.add((TabletComputer) obj); } default: break; } } return result; } catch(ArrayIndexOutOfBoundsException e){ System.out.println("XML doesnt consist nessesary classes"); System.exit(1); } catch (FileNotFoundException e){ System.out.println("File not found"); System.exit(1); } return null; }
9ceb2a58-d767-4853-80b2-446d3b83abaa
3
public QueryDefinition createQuerty(String name, Class<? extends JPanel> panel, Environment env) throws Exception { Node node = null; try { Element queryElem = getOrCreateCollection("queries"); node = Utilities.selectSingleNode(queryElem, "./c:query[@c:name='" + name + "']", this.namespaces); if(node == null) { node = this.doc.createElementNS(Settings.DEFAULT_NAMESPACE, "query"); Utilities.setAttribute(node, "c", "contentType", QueryDefinition.DEFAULT_CONTENT_TYPE, this.namespaces); Utilities.setAttribute(node, "c", "environment", env.getName(), this.namespaces); Utilities.setAttribute(node, "c", "name", name, this.namespaces); Utilities.setAttribute(node, "c", "queryId", "", this.namespaces); Utilities.setAttribute(node, "c", "transform", "", this.namespaces); Utilities.setAttribute(node, "c", "type", panel.getName(), this.namespaces); queryElem.appendChild(node); } } catch(Exception e) { logger.warn("Unable to create query: " + name, e); } return new QueryDefinition(node); }
fbcca847-7e75-4b52-be51-e721be9a5b94
7
private JSONArray readArray(boolean stringy) throws JSONException { JSONArray jsonarray = new JSONArray(); jsonarray.put(stringy ? read(this.stringhuff, this.stringhuffext, this.stringkeep) : readValue()); while (true) { if (probe) { log(); } if (!bit()) { if (!bit()) { return jsonarray; } jsonarray.put(stringy ? readValue() : read(this.stringhuff, this.stringhuffext, this.stringkeep)); } else { jsonarray.put(stringy ? read(this.stringhuff, this.stringhuffext, this.stringkeep) : readValue()); } } }
b7b763a7-9ae9-47b3-84cd-08ab5d5b05d6
1
protected static String processURL(String txt) { int index = txt.indexOf(" "); String url = txt; String label = txt; if (index != -1) { url = txt.substring(0, index); label = txt.substring(index + 1); } return "<a href=\"" + url + "\">" + label + "</a>"; }
776cf1b6-2612-4e2d-b2f0-dd4156a5c1d3
1
private void mapTasksToFile(List<String> tasks, IFile file) { //first remove existing mappings for this file // List<String> keysToRemove = new ArrayList<String>(); // for (Entry<String, IFile> entry : taskToFileMap.entrySet()) { // if (entry.getValue().equals(file)) { // keysToRemove.add(entry.getKey()); // } // } // for (String key : keysToRemove) { // this.taskToFileMap.remove(key); // } for (String task : tasks) { this.taskToFileMap.put(task, file); } }
65f1934f-9682-46ef-bbf8-d3de42f5b3e9
6
public static void printSymbol(Symbol self, PrintableStringWriter stream) { { boolean visibleP = self == Symbol.lookupSymbolInModule(self.symbolName, ((Module)(Stella.$MODULE$.get())), false); Module module = ((Module)(self.homeContext)); if (!visibleP) { if (self.symbolId == -1) { stream.print("<<UNINTERNED>>/"); } else { if (module != null) { if (((Boolean)(Stella.$PRINTREADABLYp$.get())).booleanValue() && (module == Stella.$COMMON_LISP_MODULE$)) { { stream.print("CL:" + self.symbolName); return; } } else { stream.print(module.moduleFullName + "/"); } } } } if (((Boolean)(Stella.$PRINTREADABLYp$.get())).booleanValue()) { Stella.printSymbolNameReadably(self.symbolName, stream, ((Module)(Stella.$MODULE$.get())).caseSensitiveP); } else { stream.print(self.symbolName); } } }
f962ee3d-a150-4fdc-810e-e83633900b12
9
public void paint(Graphics g, TicTacToePlayer playerObj) { Graphics2D g2 = (Graphics2D) g; Font scoreFont = new Font("monospaced", Font.BOLD, 18); Font numberFont = new Font("consolas", Font.PLAIN, 18); Font gameOverFont = new Font("monospaced", Font.BOLD, 25); Color backgroundColor = new Color(129, 133, 193); Color tileColor = new Color(130, 194, 189); Color winColor = new Color(134, 216, 129); cleanUpIcons(g2); createBackground(g, backgroundColor); //load board for (int y = 0; y < grid.length; y++) { for (int x = 0; x < grid[y].length; x++) { //box - shadow g.setColor(Color.black); g.fillRect(x * (tileWidth + 5), y * (tileHeight + 5), tileWidth + 2, tileHeight + 2); highlightWin(g, tileColor, x, y); if (gameOver) { if (this.whoWin(1)) { if (grid2[y][x] == 1) { highlightWin(g, winColor, x, y); } } else if (this.whoWin(2)) { if (grid2[y][x] == 2) { highlightWin(g, winColor, x, y); } } } } }// end of main for loop drawScoreBox(g2, backgroundColor, g, scoreFont, numberFont, playerObj); //turn box if (!gameOver) { drawTurnBox(g2, backgroundColor, g); drawTurn(g2, playerObj, g); } if (gameOver) { displayGameOver(g, gameOverFont); //displays "Game Over" above buttons drawNewGameButton(g, scoreFont, g2, backgroundColor, winColor); //new game button } //clear game button drawClearGameButton(g, scoreFont, backgroundColor, g2); }
f3122b98-aff7-4c0d-a56a-130dab27f887
5
public Integer[][] paintFill(int x, int y, int color, Integer[][] grid){ if(grid[x][y] == color){ return grid; } else{ grid[x][y] = color; if(x<grid.length-1){ paintFill(x+1, y, color, grid); } if(x>0){ paintFill(x-1, y, color, grid); } if(y>0){ paintFill(x, y-1, color, grid); } if(y<grid[x].length - 1){ paintFill(x, y+1, color, grid); } } return grid; }
4854d6d6-6db3-4be2-8303-5de4a97765c9
2
public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case CMD_START: game.startGame(); break; case CMD_CONTINUE: game.continueGame(); break; } }
957d23f8-586b-43e8-8cb8-ba7c76d1b7db
8
@Override public void run() { ArrayList<Meld> play, trivialPlay; Boolean playMade; try { startNewGame(); while (!game.isGameOver()) { updateRound(); playMade = false; System.out.println(game.displayGame()); printStatus("Current Hand : " + hand.toString()); if(initialMeld){ trivialPlay = hand.getMeldsFromHand(); if(trivialPlay.size() > 0){ game.addMelds(trivialPlay); game.setHand(playerIndex, hand.getNumTiles()); playMade = true; } play = game.getAdjacentPlay(hand, playerIndex); if(play != null){ playMade = true; } else if (trivialPlay.size() > 0) play = trivialPlay; } else{ play = hand.getInitialMeld(); if(play != null){ game.addMelds(play); game.setHand(playerIndex, hand.getNumTiles()); initialMeld = true; playMade = true; } } if(!playMade){ printStatus("Could not make a meld"); drawTile(); } else{ playMelds(play); } // Wait for it to be your turn again game = new GameInfo(client.getMessage()); } } catch (Exception e) { printStatus("The server disconnected me?"); e.printStackTrace(); } this.endGame(); }
f921ff40-b457-46c6-bc63-0ce83d00eb34
1
public void removeAllInferenceListeners() { synchronized (inferenceListeners) { Object[] listenerArray = inferenceListeners.getListenerList(); for (int i = 0, size = listenerArray.length; i < size; i += 2) { inferenceListeners.remove((Class) listenerArray[i], (EventListener) listenerArray[i + 1]); } } }
b7beecda-decf-4912-a50c-cec1cb406364
0
protected void onRemoveChannelKey(String channel, String sourceNick, String sourceLogin, String sourceHostname, String key) {}
4afdac29-4f13-452d-818f-281cdecf8b3a
4
private int intTupleToInt(TupleExpression msg) { if (msg.getTupleType().equals("Z")) { return 0; } else if (msg.getTupleType().equals("I") && msg.getElements().size() == 1 && msg.getElements().get(0) instanceof TupleExpression) { return 1 + intTupleToInt((TupleExpression)msg.getElements().get(0)); } else { return 0; } }
ca9898b5-d055-47dd-ba30-92d1073024b5
2
public void fillRect(int x, int y, int w, int h, int pix) { assert data instanceof int[]; for (int ry = y; ry < y + h; ry++) for (int rx = x; rx < x + w; rx++) ((int[])data)[ry * width_ + rx] = pix; }
bcded768-399c-4a5c-9df6-30df4a95b276
9
protected final boolean needReload(String shop, int id, int data) { if (cacheTimeout > 0 && data >= 0) { if (id <= 0) { id = data = 0; } if (shop == null) { if (id == 0) { // full db return System.currentTimeMillis() - lastReload > cacheTimeout; } else { // global shop shop = GLOBAL_IDENTIFIER; } } else { shop = safeShopName(shop); } if (!lastRead.containsKey(shop)) { if (!prices.containsKey(shop)) { // no such shop return false; } else { lastRead.put(shop, new HashMap<Integer, Long>()); } } else { Long last = lastRead.get(shop).get((id << DATA_BYTE_LEN) + data); if (last != null && lastReload > last) { return System.currentTimeMillis() - last > cacheTimeout; } } return System.currentTimeMillis() - lastReload > cacheTimeout; } return false; }
73f93ab7-324f-4627-ae2a-b032bb269bd5
6
public static URL getURL(String link) { if(link == null || link.equals("")) return null; URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { if(!link.startsWith("http://") && !(link.startsWith("https://"))) { link = "http://" + link; } try { url = new URL(link); } catch (MalformedURLException e1) { // LOGGER.severe("Could not get URL from " + link + " " + e.getMessage()); } } return url; }
11debf58-8500-4f7e-9c44-a78e81e57dfa
6
public static void saveGraph(Component apane, JComponent c, String description, String format){ if (apane instanceof EditorPane){ apane = ((EditorPane)apane).getAutomatonPane(); } Image canvasimage = apane.createImage(apane.getWidth(),apane.getHeight()); Graphics imgG = canvasimage.getGraphics(); apane.paint(imgG); BufferedImage bimg = new BufferedImage(canvasimage.getWidth(null), canvasimage.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = bimg.createGraphics(); g.drawImage(canvasimage, null, null); Universe.CHOOSER.resetChoosableFileFilters(); Universe.CHOOSER.setAcceptAllFileFilterUsed(false); FileFilter spec = new FileNameExtensionFilter(description, format.split(",")); Universe.CHOOSER.addChoosableFileFilter(spec); Universe.CHOOSER.addChoosableFileFilter(new AcceptAllFileFilter()); Universe.CHOOSER.setFileFilter(spec); int result = Universe.CHOOSER.showSaveDialog(c); while (result == JFileChooser.APPROVE_OPTION) { File file = Universe.CHOOSER.getSelectedFile(); if (!new FileNameExtensionFilter(description, format.split(",")).accept(file)) //only append if the chosen name is not acceptable file = new File(file.getAbsolutePath() + "." + format.split(",")[0]); if (file.exists()) { int confirm = JOptionPane.showConfirmDialog(Universe.CHOOSER, "File exists. Shall I overwrite?", "FILE OVERWRITE ATTEMPTED", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.NO_OPTION){ result = Universe.CHOOSER.showSaveDialog(c); continue; } } try { ImageIO.write(bimg, format.split(",")[0], file); return; } catch (IOException ioe) { JOptionPane.showMessageDialog(c, "Save failed with error:\n"+ioe.getMessage(), "Save failed", JOptionPane.ERROR_MESSAGE); return; } } }
bcc0afc7-c059-45d5-812d-57089f14ef04
1
public String toString() { try { return this.toJSON().toString(4); } catch (JSONException e) { return "Error"; } }
de595ea4-43db-441a-a572-b900a32f301b
3
private HashMap<String,HashSet<String>> BuildGraph(){ HashMap<String,HashSet<String>> g = new HashMap<String,HashSet<String>>(); for(String str : m_nonterminals){ g.put(str,new HashSet<String>()); } for(Rule cur_rule : m_rules){ if(m_nonterminals.contains(cur_rule.GetRightPart().get(0))){ g.get(cur_rule.GetLeftPart()).add(cur_rule.GetRightPart().get(0)); } } return g; }
f305459b-6c23-4f3e-8c9c-971e48039c4f
5
public void setElementConflictConditionToAll(AbstractElement e, Condition c) { if (e == null) throw new NullPointerException("The element is null."); if (c == null) throw new NullPointerException("The condition is null."); RETW(defaultEngineLock, () -> { elementConflictConditions.keySet().forEach(p -> { if (p.first.equals(p.last) && (p.first.equals(e.getID()) || p.last.equals(e.getID()))) elementConflictConditions.put(p, c); }); }); }
2496bb0f-1ee8-4af2-9325-31d4068ae9c0
9
private static boolean checkAll(int arrIdx, int ch, int charIdx) { int errCnt = 0; for (int j = 0; j < cts.length; j++) { if (j == arrIdx || ct[j].length <= charIdx) continue; int x = (ch ^ ct[j][charIdx]); if (x == 0) continue; if (!((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z'))) { errCnt++; if (errCnt > 2) return false; } } return true; }
2a863608-6b0d-4f8a-9249-7fbe5680192d
4
private String readLine() { String line = null; do { if (this.currentThread.isInterrupted()) { this.log.info("MessageReceiver thread is Interrupted"); finishFileReceiverThread(); return null; } try { if (this.inputMessageReceiver.ready()) line = this.inputMessageReceiver.readLine(); else line = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); line = null; this.log.info("readLine from inputMessageReceiver: fail"); } } while (line == null); return line; }
597e1215-8907-434d-b9ae-3e80903527cf
6
static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; }
8b2858e7-9068-4161-8bf7-aa064963b760
8
final void method3770(int i, Interface11 interface11) { do { try { anInt7598++; if (((OpenGlToolkit) this).aBoolean7815) { method3805(8387, interface11); method3764(-17083, interface11); } else { if (anInt7746 < 0 || anInterface11Array7743[anInt7746] != interface11) throw new RuntimeException(); anInterface11Array7743[anInt7746--] = null; interface11.method48(46); if ((anInt7746 ^ 0xffffffff) > -1) anInterface11_7745 = anInterface11_7740 = null; else { anInterface11_7745 = anInterface11_7740 = anInterface11Array7743[anInt7746]; anInterface11_7745.method46(-11762); } } if (i == -422613672) break; ((OpenGlToolkit) this).anInt7788 = 30; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("qo.FD(" + i + ',' + (interface11 != null ? "{...}" : "null") + ')')); } break; } while (false); }
0637e854-f193-47cf-bc02-e60a67799497
2
public boolean getLinhaVenda(int id)throws ExceptionGerenteVendas { for (LinhaVenda v : linhas) { if (v.getId()==(id)) { return true; } } throw new ExceptionGerenteVendas("Linha de venda n�o existe!"); }
e035cd9d-d0df-4881-901a-6d2992b1077c
4
public void update(int base, int comp) { if ((base == this.base) && (comp == this.comp)) return; int delta = (this.base > 0) ? base - this.base : 0; if(delta > 0) { UI.instance.cons.out.println("Your "+nm.toUpperCase()+" raised by "+delta+" points"); } this.base = base; this.comp = comp; setChanged(); notifyObservers(null); }
aa59dda7-af75-4d6a-adf5-4eafc4ed5ed7
6
public static void main( String[] args ) throws LWJGLException { Controllers.create(); Controllers.poll(); for ( int i = 0; i < Controllers.getControllerCount(); i++ ) { controller = Controllers.getController( i ); System.out.println( "(" + i + ") " + controller.getName() ); } System.out.println(); // blank line Scanner scanner = new Scanner( System.in ); System.out.print( "Which controller index? " ); int answer = scanner.nextInt(); scanner.close(); System.out.println(); controller = Controllers.getController( answer ); for ( int i = 0; i < controller.getAxisCount(); i++ ) { System.out.println( "Axis detected: (" + i + ") " + controller.getAxisName( i ) ); } for ( int i = 0; i < controller.getButtonCount(); i++ ) { System.out.println( "Button detected: (" + i + ") " + controller.getButtonName( i ) ); } System.out.println( "Detected " + controller.getRumblerCount() + " rumbler(s)" ); setup(); while ( !Display.isCloseRequested() ) { controller.poll(); update(); for ( int i = 0; i < controller.getRumblerCount(); i++ ) { controller.setRumblerStrength( i, 1f ); } if ( controller.getAxisValue( 4 ) != 0 ) { System.out.println( controller.getAxisValue( 4 ) ); // right trigger is [-1,0), left (0,1] } Display.update(); Display.sync( 60 ); } destroy(); }
9960ae1d-773d-465b-ba81-99b347ab1ff5
3
public static boolean isRedirectCode(int statusCode) { return (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT); }
fd5c7b1e-d820-4d5a-a376-98bd715b0776
0
public void setComments(List<String> comments) { this.comments = comments; }
024411d4-5973-4cd6-9acf-d06d6cda0a06
1
public boolean equals (Month m) { if (m.getNum()==this.getNum()) return true; else return false; }
cd6d2179-53a5-4870-b5c8-4ead08805ce8
8
@Override public void paintComponent(Graphics g) { super.paintComponent(g); if (screen != null) result = screen.screen; for (int x = 0; x < cellsX; x++) { for (int y = 0; y < cellsY; y++) { switch (result[x][y]) { case 0: g.setColor(Color.BLACK); g.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); break; case 1: g.setColor(Color.WHITE); g.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); break; case 2: g.setColor(Color.LIGHT_GRAY); g.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); break; case 3: g.setColor(Color.GRAY); g.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); break; case 4: g.setColor(Color.DARK_GRAY); g.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); break; } } } }
ac18582f-117d-4302-9140-da3d455a804b
4
public void input(InputRouter.Interaction action) { if (isAlive()) inputAlive(action); else { RespawnMenu.setRespawnOpen(true); switch(action) { case MENU_UP: RespawnMenu.selectionUp(); break; case MENU_DOWN: RespawnMenu.selectionDown(); break; case MENU_SELECT: shipPreference = RespawnMenu.getSelection(); respawn(); RespawnMenu.setRespawnOpen(false); break; default: System.err.println("Player: unhandled input: " + action); } } }
fc992e8c-0b75-4b94-8d39-f5fe52d5c062
4
public static void diffStuff() { // Get the path of current directory Path currentDir = Paths.get(System.getProperty("user.dir")); // Manipulate the paths to point to specific files. Path pathToFileA = currentDir.resolve("../src/DemoMain.java"); Path pathToFileB = currentDir.resolve("../src/DemoDbManager.java"); // Note in the logger that we called normalize() so that we'd get something // like "util/demo/src" and not "util/demo/build/../src". Same path, but // one is easier for a human to read. logger.debug("Path to file A: " + pathToFileA.normalize()); logger.debug("Path to file B: " + pathToFileB.normalize()); System.out.println("\nCreating diffs and patching."); // Create a diff (note that it takes in lists of Strings) List<String> fileA = DemoDiff.fileToList(pathToFileA); List<String> fileB = DemoDiff.fileToList(pathToFileB); Patch<String> patch = DiffUtils.diff(fileA, fileB); try { // Create a PrintWriter for writing to a file PrintWriter writer = new PrintWriter("difference.patch", "UTF-8"); // And loop through the diff to get all lines and print them to the patch file for(Delta<String> delta : patch.getDeltas()) { writer.println(delta); } writer.close(); } catch(IOException e) { logger.error(e); } try { // And apply the patch to File A to recover file B List<String> result = DiffUtils.patch(fileA, patch); // And write the recreated file to a physical file PrintWriter writer = new PrintWriter("recreated.java", "UTF-8"); for(String line : result) { writer.println(line); } writer.close(); } catch(Exception e) { logger.error(e); } }
012aef8f-7b73-4310-96c4-6d129582f0a9
2
public static List<Fournisseur> selectFournisseur() throws SQLException { String query = null; List<Fournisseur> fournisseurs = new ArrayList<Fournisseur>(); ResultSet resultat; try { query = "SELECT * from FOURNISSEUR "; PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query); resultat = pStatement.executeQuery(query); while (resultat.next()) { Fournisseur ff = new Fournisseur(resultat.getInt("ID_FOURNISSEUR"), resultat.getInt("ID_VILLE"), resultat.getString("FOUNOM"), resultat.getString("FOUADRESSE1"), resultat.getString("FOUADRESSE2")); fournisseurs.add(ff); } } catch (SQLException ex) { Logger.getLogger(RequetesFournisseur.class.getName()).log(Level.SEVERE, null, ex); } return fournisseurs; }
7683a98e-add4-4b2a-b355-a14b0bee5010
3
double purity(String codon, String around) { String pre = around.substring(0, CODONS_SIZE * CODONS_AROUND); String post = around.substring(around.length() - CODONS_SIZE * CODONS_AROUND); if( debug ) Gpr.debug("codon: '" + codon + "'\tAround: '" + around + "'\tpre: '" + pre + "'\tpost: '" + post + "'"); // Count all codons HashMap<String, Integer> count = new HashMap<String, Integer>(); // First use 'codons' int maxSyms = codon.length() / CODONS_SIZE; for( int i = 0; i < maxSyms; i++ ) { String sym = getCodon(codon, i); addAa(count, sym, 1); } // Now count codons 'around' (pre and post) for( int i = 0; i < CODONS_AROUND; i++ ) { String cod = getCodon(pre, i); addAa(count, cod, 1); cod = getCodon(post, i); addAa(count, cod, 1); } // Find AA-codon purity return maxPurity(count); }
13a33136-97ac-45a5-a6b0-cbcf8614ff28
2
private void fillConceptTable(Bill r, Student s, JTable table) { DefaultTableModel dtm = (DefaultTableModel) table.getModel(); for (int i = 0; i < dtm.getRowCount(); i++) { dtm.removeRow(i); } Set<BillLine> billLines = billService.getBillLinesByStudent(r, s); for (BillLine rl : billLines) { Object[] data = { rl.getConcept(), rl.getUnitPrice(), rl.getUnits() }; dtm.addRow(data); } //table.updateUI(); }
53a90da7-6624-4b2a-b163-1c918a32081b
0
public boolean parkIsNull() { return this.park == null; }
83f39946-7402-413f-a7eb-1c6abeb21a37
6
public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("Cut")) { if (tf != null) { tf.cut(); } else { ta.cut(); } } if (actionEvent.getActionCommand().equals("Copy")) { if (tf != null) { tf.copy(); } else { ta.copy(); } } if (actionEvent.getActionCommand().equals("Paste")) { if (tf != null) { tf.paste(); } else { ta.paste(); } } }
6730a9e6-761c-4f16-8830-8efab385eeca
8
public void SemanticOperationDistribute(int id){ //功能: //根据Id调用对应语义推理模块的处理程序 if(id>=1 && id<100){ reiMainSpace.Process(id); } else if(id>=101 && id<200){ reiImageSpace.Process(id); } else if(id>=201 && id<500){ reiAttributeSpace.Process(id); } else if(id>=1001){ Process(id); } else if(id==0){ answer+=reiImageSpace.theStateOfImageSpace; answer+=reiAttributeSpace.theStateOfColorSpace; answer+=reiAttributeSpace.theStateOfForceSpace; iffinished=true; } }
fa5b2ffa-c641-4111-8e55-f7344286291d
0
public void setPcaSubgru(Integer pcaSubgru) { this.pcaSubgru = pcaSubgru; }
7cb3297a-fce8-4811-a8d5-e41623bccf06
8
public void renderProjectile(int xp, int yp, Projectile p) { xp -= xOffset; yp -= yOffset; for (int y = 0; y < p.getSpriteSize(); y++) { int ya = y + yp; int ys = y; for (int x = 0; x < p.getSpriteSize(); x++) { int xa = x + xp; int xs = x; if (xa < -p.getSpriteSize() || xa >= width || ya < 0 || ya >= height) break; if (xa < 0) xa = 0; int col = p.getSprite().pixels[xs + ys * p.getSprite().SIZE]; if (col != 0xffff00ff) pixels[xa + ya * width] = col; } } }
ee266be6-fb2a-44e3-a518-a36de2a8bd2a
9
@EventHandler public void onSignInteract(PlayerInteractEvent e){ Player player = e.getPlayer(); if(e.getAction() == Action.RIGHT_CLICK_BLOCK && e.hasBlock() && e.getClickedBlock().getState() instanceof Sign){ Sign sign = (Sign) e.getClickedBlock().getState(); if(sign.getLine(0).equalsIgnoreCase(ChatColor.DARK_GRAY + "[" + ChatColor.AQUA.toString() + ChatColor.BOLD.toString() + "OITC" + ChatColor.DARK_GRAY + "]")) { sign.update(); if(Arenas.isInArena(player)){ player.sendMessage(ChatColor.RED + "You are already in an Arena!"); player.sendMessage(ChatColor.GRAY + "If you would like to leave the current arena you are in, do /oitc leave"); return; } for(Arena arena : Arenas.getArenas()){ if(sign.getLine(1).equalsIgnoreCase( ChatColor.BOLD + arena.getName() )){ if(!arena.hasPlayer(player)){ //if(!arena.isOn()){ if(arena.getMaxPlayers() > arena.getPlayers().size()){ arena.addPlayer(player); }else{ player.sendMessage(ChatColor.RED + "Sorry! That Arena is full!"); } //}else{ //player.sendMessage(ChatColor.RED + "Sorry! That Arena is " + arena.getState().toString()); //} } break; } } } } }
768da15f-54c4-4c4d-86e3-4f068b3b21a5
4
public String giveRandomCard() { String nameOfCard = null; int w = random.nextInt(52); if (deck[w].cardValue == 1) { nameOfCard = "A" + deck[w].suit; } else if (deck[w].cardValue == 11) { nameOfCard = "J" + deck[w].suit; } else if (deck[w].cardValue == 12) { nameOfCard = "Q" + deck[w].suit; } else if(deck[w].cardValue == 13) { nameOfCard = "K" + deck[w].suit; } else { nameOfCard = deck[w].cardValue + deck[w].suit; } return nameOfCard; }
98351d4b-839d-4a45-a8b0-72802a467ee3
3
private SongLogger() throws LogException { SongLogger.log= Logger.getLogger(SongLogger.class.getName()); FileHandler fh= null; try { fh = new FileHandler("LogSong " + new Date().toString()); SongLogger.log.addHandler(fh); SongLogger.log.setUseParentHandlers(false); } catch (SecurityException e) { throw new LogException(e.getMessage(), e); } catch (IOException e) { throw new LogException(e.getMessage(), e); } catch (Exception e) { throw new LogException(e.getMessage(), e); } }
e3d3bd6b-bdce-4f90-b4a6-8610cb5ad9ea
2
private static double getDScale(int factor) { if (factor < SCALES.length) { return SCALES[factor]; } else if (factor < 2 * SCALES.length) { return SCALES[factor - SCALES.length] * (double) SCALES[SCALES.length - 1]; } else { throw new IllegalArgumentException("Too high factor"); } }
850f14c4-c7a0-4276-879e-189fad5f7a60
2
public void updateLayerBox() { int j = 0; removeAll(); MainImagePanel mip = MainImagePanel.getInstance(); for (BufferedImage i : mip.getLayers()) { BufferedImage newi = new BufferedImage(LAYER_ICON_SIZE, LAYER_ICON_SIZE, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = newi.createGraphics(); g2d.drawImage(i, 0, 0, LAYER_ICON_SIZE, LAYER_ICON_SIZE, Color.WHITE, null); LayerBoxButton newButton = new LayerBoxButton(j, new ImageIcon(newi)); if (j == mip.getLayerIndex()) newButton.setBackground(new Color(0.7f, 0.7f, 0.7f)); add(newButton); j++; } repaint(); }
a87ddf88-c0b1-4e7a-97bd-3265f63190e9
9
@SuppressWarnings("unchecked") public static double mean(Function w, HashSet<Integer> id, boolean inclusion, double threshold, boolean above) { double result = 0.0; int counter = 0; for (Feature f : (LinearFunction<Feature,FeatureVector>) w) { if (((inclusion && id.contains(f.identifier())) || (!inclusion && !id.contains(f.identifier()))) && ((above && (f.strength() > threshold)) || (!above && (f.strength() < threshold)))) { result += f.strength(); counter++; } } return result / counter; }
91581e48-5cc4-49c2-b37e-1550c10af251
4
public ArrayList<Object> getInfoFromPDB(ArrayList<String> pdbFile) { //empty at beginning ArrayList<Atom> atomList = new ArrayList<Atom>(); CartesianCoord coords; String atomType, pdbResNum; //default double value is 0 double tempFact, meanBFactor, std, totalBFactor=0, totalSquaredBFactor=0; //default boolean value is false boolean backbone=false, nTerm=false, cTerm=false, nextIsNTerm = false; for (int i = 0; i<pdbFile.size(); ++i) { // if it is an Atom if(pdbFile.get(i).substring(0,6).trim().equals("ATOM")) { //splits the data according to customPDBSplit() String[] strs = customPDBSplit(pdbFile.get(i)); // gets all necessary information for an Atom // coords, atomType, resNum, bFactor, backbone, nTerm, cTerm coords = getCoordinates(strs); atomType = strs[1].trim(); nTerm = nextIsNTerm; nextIsNTerm = false; String[] atomTypeArray = {"N","CA","C","O","OXT","OT1","OT2"}; if(multiEquals(atomType, atomTypeArray)) { backbone = true; } pdbResNum = strs[3].trim(); tempFact = Double.parseDouble(strs[7].trim()); totalBFactor += tempFact; totalSquaredBFactor += Math.pow(tempFact, 2); atomList.add(new Atom(atomType, pdbResNum, backbone, nTerm, cTerm, tempFact, coords)); } // extra information on whether or not it is a terminus // one previous is a cTerm // next one is an nTerm if(pdbFile.get(i).substring(0,6).trim().equals("TER")) { nextIsNTerm = true; atomList.get(atomList.size()-1).setCTerm(true); } }// end of for meanBFactor = totalBFactor / (atomList.size() - 1); std = calcStdDev(totalBFactor, totalSquaredBFactor, atomList.size() - 1); ArrayList<Object> retMe = new ArrayList<Object>(); retMe.add(atomList); retMe.add(meanBFactor); retMe.add(std); return retMe; }
4006cfc2-a589-4d3c-b7bd-1899ba817534
1
@Override public synchronized boolean saveResult(ProgressReporter reporter) throws IOException, InterruptedException { Path p = Paths.get(saveTo, getFSSafeName(getTitle())); Files.createDirectories(p); if (WebDownloader.fetchWebFile(coverUrl, getCoverSavePath(), reporter) != 0) { reporter.report("cover image downloaded", 1); return true; } else return false; }
4b0a46fd-1329-4622-a122-4791801ba7bd
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FileReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FileReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FileReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FileReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new FileReceiver().setVisible(true); } }); }
a315512e-fc6c-4e1e-a777-2b36767520b4
6
public synchronized void forward(int gameID, String data) { // hier wird der String in seine Einzelteile zerlegt // (Zieladresse, Name, Nachricht) try { StringTokenizer ST = new StringTokenizer(data); String player = ST.nextToken(); String name = ST.nextToken(); String msg = data.substring(name.length() + player.length() + 2); int target = Integer.parseInt(player); // suche passendes Game-Objekt und sende die Nachricht an den Empfaenger for (int i = 0; i < games.size(); i++) { Game game = (Game) games.elementAt(i); if (game.getNameOfTheGame().equals(name) && gameID == game.getGameID()) { if (target != -1) { ServerThread recipient = ((ServerThread) game.getPlayers().elementAt(target)); recipient.send("1" + msg); } else { // falls nachricht an server gerichtet ist (player "-1", nachricht "go"), // teile mit, dass das Spiel gestartet werden kann if (msg.equals("go")) { game.start(); } } } } } catch (NoSuchElementException e) { String log = "server: corrupt message in method forward!\n"; System.out.print(log); log(log, port); } }
29a37de7-c464-4f4b-b1a0-df5fa8e4ccc5
7
private void loadAvalibleData() { // fill cbKompetens cbKompetens.removeAllItems(); try { ArrayList<String> komptemp = DB.fetchColumn("select kid from kompetensdoman"); ArrayList<Kompetensdoman> komp = new ArrayList<>(); for (String k : komptemp) { komp.add(new Kompetensdoman(Integer.parseInt(k))); } for (Kompetensdoman k : komp) { cbKompetens.addItem(k); } } catch (InfException e) { e.getMessage(); } // fill cbNiva cbNiva.removeAllItems(); for (int i = 1; i <= 4; i++) { cbNiva.addItem("Nivå " + i); } // fill cbPlattform cbPlattform.removeAllItems(); try { ArrayList<String> platttemp = DB.fetchColumn("select pid from plattform"); ArrayList<Plattform> platt = new ArrayList<>(); for (String s : platttemp) { platt.add(new Plattform(Integer.parseInt(s))); } for (Plattform p : platt) { cbPlattform.addItem(p); } } catch (InfException e) { e.getMessage(); } }
ba8bf082-6bff-490f-b327-fd65e6e4b134
7
public MacroCreation() { temp_body = new ArrayList<Code>(1); add(pB, BorderLayout.SOUTH); add(pL, BorderLayout.CENTER); add(mBL, BorderLayout.WEST); add(mN, BorderLayout.NORTH); // When user clicks Save Button mN.ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Make sure user enters a name for macro if (mN.tx.getText().trim().equalsIgnoreCase("")) { JOptionPane.showMessageDialog(null, "You left the Macro Name field blank.", "Macro must have a name.", JOptionPane.ERROR_MESSAGE); return; } // Make sure there is not already a macro with this name if (Util.cntrl.getMacroMap().containsKey(mN.tx.getText().trim())) { JOptionPane.showMessageDialog(null, "Macro name is in use.", "Macro name in use.", JOptionPane.ERROR_MESSAGE); return; } if (temp_body.isEmpty() ||temp_body == null || temp_body.get(0) == null) { JOptionPane.showMessageDialog(null, "The Macro does not have any code in it.", "Empty Macro", JOptionPane.ERROR_MESSAGE); return; } //delete System.out.println("On Save: Printing what is in the list:"); for(int i = 0; i < temp_body.size(); i++){ System.out.println(temp_body.get(i).getClass().toString()); } String name = mN.tx.getText().trim(); CustomCode cc = new CustomCode(name, temp_body); Util.cntrl.getMacroMap().put(cc.getName(), cc); // Save to list if (Customs.model.get(0).equals("No Custom Actions created")) { Customs.model.remove(0); } Customs.model.addElement(cc.getName()); CustomButtons.delete.setEnabled(true); // Explicitly tell class that there is a switch between pseudocodes PseudocodeList.isMacro = false; // Enable create macro button in Customs/CustomButtons panel CustomButtons.create.setEnabled(true); // Make this dialog disappear setVisible(false); dispose(); return; } }); }
f3352634-e3c7-4ed1-9fa9-0ebdf35d8b2d
3
@Override public void stop(boolean success) { if (connection != null) { try { if (success) { connection.commit(); } else { connection.rollback(); } } catch (SQLException e) { System.out.println("Could not end transaction"); e.printStackTrace(); } finally { safeClose(connection); connection = null; } } }
77b44495-4f9e-4e2e-8b29-f82e1b85f530
6
public void subscribeUsersFinished(int type) throws InvalidSubscriptionException, IOException { usersHaveData = 1; String tmp; final int nonce; if (type == FINISHED_DEC_HAND) { tmp = HAVE_MY_HAND; nonce = SigService.HAVE_HAND_NONCE; } else if (type == FINISHED_DEC_COM_CARDS) { tmp = REQUEST_RAW_COMMUNITY_CARDS; nonce = SigService.REQUEST_COM_CARDS_NONCE; } else { tmp = RAW_COMMUNITY_CARDS_VERIFIED; nonce = SigService.VERIFY_COM_CARDS_NONCE; } waiterSub = elvin.subscribe(NOT_TYPE + " == '" + tmp + "' && " + GAME_ID + " == '" + gameHost.getID() + "'"); waiterSub.addListener(new NotificationListener() { public void notificationReceived(NotificationEvent e) { String userid = e.notification.getString(SOURCE_USER); User tmpUser = findUserByID(userid); if (tmpUser == null) { // not in our list so return return; } try { if (sigServ.validateVerifiedSignature( (byte[]) e.notification.get(SIGNATURE), tmpUser.getPublicKey(), nonce)) { // signature validated so this is a real cheat // notification usersHaveData++; if (usersHaveData >= currentGameMembers.size()) { // remove subscription and return waiterSub.remove(); return; } } else { // call cheat } } catch (Exception e1) { // call cheat } } }); return; }
7a5d711b-85b9-45da-babb-b456fb2d3144
0
@Override public void run() { plateau1.run(); plateau2.run(); }
a9be9712-fae3-428a-ba36-b2d447856b05
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DepositarCuenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DepositarCuenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DepositarCuenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DepositarCuenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DepositarCuenta().setVisible(true); } }); }
4fe7c955-2feb-4ac3-a06e-c44e28af2dfa
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BigramModel<T,K> other = (BigramModel<T,K>) obj; if (key == null) { if (other.key != null) { return false; } } else if (!key.equals(other.key)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; }
33b43ba5-bd7b-4d27-9dbd-fdc827fee8eb
0
public void setStep(int step) { this.step = step; }
f6cf1267-e0c3-42f4-8375-3c042c724160
2
public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; int n = numbers.length; for(int i = 0; i< numbers.length; i++ ){ if(map.containsKey(target-numbers[i])){ result[0] = map.get(target-numbers[i]) +1; result[1] = i +1; } else{ map.put(numbers[i],i); } } return result; }
a2e2c00a-0387-46fc-b2f3-d0d82a5a04e1
7
public static void main (String[] argv){ System.out.println("Starting mapfold controller system"); try{ String workerConfPath = "conf/server_conf.json"; String jobConfPath = "conf/job.json"; if(argv.length > 0){ workerConfPath = argv[0]; } System.out.println("Reading config: " + workerConfPath); Config config = new Config(workerConfPath); if(argv.length > 1){ jobConfPath = argv[1]; } System.out.println("Reading config: " + jobConfPath); Set<String> ips = ServerHelpers.getIPs(); ips.add("127.0.0.1"); ips.add("localhost"); System.out.println("All IP addresses:"); for(String addr : ips ){ System.out.println(addr); } System.out.println(); for( int i = 0; i < config.getNcontrollers(); i++){ Config.ControllerConfig controllerConfig = config.getController(i); if(ips.contains(controllerConfig.getIpAddr())){ System.out.print("Starting controller "); System.out.print(i); System.out.print(" "); System.out.println(controllerConfig.getAddr()); ControllerNode controller = new ControllerNode(i,config, jobConfPath); if(controller.isPrimary()){ System.out.println("Starting as master"); controller.startMaster(); } Registry registry = LocateRegistry.createRegistry(Integer.parseInt(controllerConfig.getPort())); registry.bind("Controller", controller); System.out.println("Controller is ready"); } } System.out.println("System Ready"); }catch(Exception e){ System.out.println ("Worker startup failed: " + e); e.printStackTrace(); } }
e8a4896e-394c-4754-8600-f1f35c4fef8b
1
public void shots(){ if (bullet.isShot()){ Bullet bullet1 = new Bullet(); bullet1.setX(paddle.getX() + (paddle.getWidth() - bullet1.getWidth()) / 2); bullet1.setY(paddle.getY() + (paddle.getHeight() - bullet1.getHeight()) / 2); bulletList.add(bullet1); } }
1abb8c64-07e0-421b-be27-9abed5d8150d
6
public static void validateDirection(Direction direction) throws TechnicalException { if (direction == null) { throw new TechnicalException(MSG_ERR_NULL_ENTITY); } if ( ! isStringValid(direction.getName(), DIRECT_NAME_SIZE)) { throw new TechnicalException(NAME_ERROR_MSG); } if ( ! isStringValid(direction.getPicture(), PICTURE_SIZE)) { throw new TechnicalException(PICTURE_ERROR_MSG); } if ( ! isStringValid(direction.getText(), TEXT_SIZE)) { throw new TechnicalException(TEXT_ERROR_MSG); } if ( ! isSelectedElem(direction.getTourType().getIdTourType())) { throw new TechnicalException(SELECT_TOURTYPE_ERROR_MSG); } if ( ! isSelectedElem(direction.getTransMode().getIdMode())) { throw new TechnicalException(SELECT_TRANSMODE_ERROR_MSG); } }
c9f5d4c7-44da-432f-b1f4-84a8f0b7f86c
1
@Override public Object fromMessage(Message message) throws MessageConversionException { try { Map data = converter.toMap(new String(message.getBody(), "UTF-8")); return new MyCustomEventApplicationEvent(this, data); } catch(IOException e) { throw new MessageConversionException("Unable to convert message: " + message, e); } }
cb206728-c809-46e9-a213-accb03a0d0c5
9
private Method findActionMethod(Class<?> type, String methodName) { List<Method> methods = new ArrayList<Method>(); Action detail = null; for (Method method : type.getDeclaredMethods()) { if (!isMethodValid(method, methodName)) { continue; } Action annotation = method.getAnnotation(Action.class); if (detail == null) { if (annotation != null) { methods.clear(); detail = annotation; } methods.add(method); } else if (annotation != null) { methods.add(method); } } if (methods.isEmpty()) { if (Object.class.equals(type.getSuperclass())) { throw new IllegalArgumentException("No method '" + methodName + "' for class " + actionBean.getClass().getName()); } return findActionMethod(type.getSuperclass(), methodName); } else if (methods.size() > 1) { throw new IllegalArgumentException("Too many method '" + methodName + "' for class " + actionBean.getClass().getName()); } return methods.get(0); }
cc4d7d75-a945-434b-b40b-55efc5e45bcd
0
public ParkException(String msg) { super(msg); }
6ad317b3-961f-457d-8641-8560c36d7ad9
5
private void endGame(int i) { isInGamePlay = false; for (Cell[] cellArray : cells) { for (Cell cell : cellArray) { cell.reveal(); } } if (listener != null) { if (i == -1) listener.gameFinished(false); else if (i == 1) listener.gameFinished(true); } }
b374cb57-6db2-47d8-ae5e-9c5d1f4557dd
9
public boolean processXML(File file,Document doc,boolean forceRefresh) throws Exception { Element root=doc.getDocumentElement(); List<FragmentDirective> fragments=new ArrayList<FragmentDirective>(); scanComments(root,fragments); MessageDigest digest=MessageDigest.getInstance("SHA-1"); boolean modified=false; for(FragmentDirective frag:fragments) { DocumentFragment fragmentDoc=loadFragment(frag.fileName); digest.reset(); digestFragment(digest,fragmentDoc); String hash=tostr(digest.digest()); if(frag instanceof FragmentContent) { FragmentContent fc=(FragmentContent)frag; // Check if the fragment needs to be replaced // First compute the real hash of the fragment digest.reset(); digest(digest,fc.nodes); String fragmentHash=tostr(digest.digest()); if(fragmentHash.equals(fc.hash)||forceRefresh) { // Fragment was not modified, so we can replace it if(!fragmentHash.equals(hash)||forceRefresh) { // The replacement content is modified. We need to replace // Remove all nodes except the first and last int n=fc.nodes.size(); Node lastNode=fc.nodes.get(n-1); int i=0; for(Node node:fc.nodes) { if(i>0&&node!=lastNode) { node.getParentNode().removeChild(node); } i++; } // Insert the fragment after the first comment node importFragment(fc.nodes.get(n-1),fragmentDoc,doc); // Modify the comment node text to reflect the new hash ((Comment)fc.nodes.get(0)).setData("Fragment Begin: "+fc.fileName+" "+hash); modified=true; } } else System.out.println(file.toString()+": Fragment for "+frag.fileName+ " was modified in file, cannot replace (fragment file hash:"+hash+" hash in file:"+fragmentHash+" has in comment:"+fc.hash+")"); } else { // This will be the fragment end comment node frag.node.setData("Fragment End: "+frag.fileName); Comment c=doc.createComment("Fragment Begin: "+frag.fileName+" "+hash); frag.node.getParentNode().insertBefore(c,frag.node); // Import the fragment here importFragment(frag.node,fragmentDoc,doc); modified=true; } } return modified; }