method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2b600598-c9c0-44bf-8f8b-5037832e6f83
0
@Test public void testRemoveBlackMarker() { System.out.println("removeBlackMarker"); Cell instance = new Cell(0,0); instance.addBlackMarker(0); instance.addBlackMarker(1); instance.addBlackMarker(2); instance.addBlackMarker(3); instance.addBlackMarker(4); instance.addBlackMarker(5); boolean[] result = instance.getMarkers(true); assertEquals(true, result[0]); assertEquals(true, result[1]); assertEquals(true, result[2]); assertEquals(true, result[3]); assertEquals(true, result[4]); assertEquals(true, result[5]); instance.removeBlackMarker(0); instance.removeBlackMarker(1); instance.removeBlackMarker(2); instance.removeBlackMarker(3); instance.removeBlackMarker(4); instance.removeBlackMarker(5); result = instance.getMarkers(true); assertEquals(false, result[0]); assertEquals(false, result[1]); assertEquals(false, result[2]); assertEquals(false, result[3]); assertEquals(false, result[4]); assertEquals(false, result[5]); }
46c5df15-61fd-4a28-bac3-e05e0037f5f3
6
public boolean studentFulfillsDegreeRequirements(int studentId, int degreeId) { if(!isValidId(studentId) || !isValidId(degreeId)) { return false; } Student student = studentDao.getStudent(studentId); Degree degree = degreeDao.getDegree(degreeId); if (student != null && degree != null) { for (Course course : degree.getRequiredCourses()) { if (student.getCourses().contains(course) == false) { return false; } } return true; } return false; }
d9868f63-a4a6-4e4b-bab2-8cb09479d33b
8
private ArrayList<Cell> getVisitedNeighbors(Cell curCell) { ArrayList<Cell> neighbors = new ArrayList<Cell>(); //Look at top... if(curCell.getX() - 1 >= 0 && !cellMaze[curCell.getX() - 1][curCell.getY()].isVisited()) neighbors.add(cellMaze[curCell.getX() - 1][curCell.getY()]); //Look at bottom... if(curCell.getX() + 1 < rows && !cellMaze[curCell.getX() + 1][curCell.getY()].isVisited()) neighbors.add(cellMaze[curCell.getX() + 1][curCell.getY()]); //Look at right... if(curCell.getY() + 1 < cols && !cellMaze[curCell.getX()][curCell.getY() + 1].isVisited()) neighbors.add(cellMaze[curCell.getX()][curCell.getY() + 1]); //Look at right... if(curCell.getY() - 1 >= 0 && !cellMaze[curCell.getX()][curCell.getY() - 1].isVisited()) neighbors.add(cellMaze[curCell.getX()][curCell.getY() - 1]); neighbors.trimToSize(); return neighbors; }//end getVisitedNeighbors
157d4b3f-6c7b-431f-b810-512a7829ac36
0
public void setServeurBd(String serveurBd) { this.serveurBd = serveurBd; }
b16fad51-0a40-4285-818f-1f3e1864ec3b
3
@Override public <T> Invoker<T> select(List<Invoker<T>> invokers, TpURL tpURL, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return null; } if (invokers.size() == 1) { return invokers.get(0); } return doSelect(invokers, tpURL, invocation); }
e86de740-e9f8-470e-bc97-b57ad8b1366a
4
private boolean patternSame( byte[] pattern ) { if ( this.pattern != null && this.pattern.length == pattern.length ) { for ( int i=0;i<pattern.length;i++ ) if ( pattern[i] != this.pattern[i] ) return false; return true; } else return false; }
cf567fa0-df52-42b8-92a4-01b5ca1bca34
1
@Test public void testPutTracking()throws Exception{ Tracking tracking = new Tracking("RC328021065CN"); tracking.setSlug("canada-post"); tracking.setTitle("another title"); Tracking tracking2 = connection.putTracking(tracking); Assert.assertEquals("Should be equals title", "another title", tracking2.getTitle()); //test post tracking number doesn't exist Tracking tracking3 = new Tracking(trackingNumberToDetectError); tracking3.setTitle("another title"); try{ connection.putTracking(tracking3); //always should give an exception before this assertTrue("This never should be executed",false); }catch (Exception e){ assertEquals("It should return a exception if the tracking number doesn't matching any courier you have defined" , "{\"meta\":{\"code\":4005,\"message\":\"The value of `tracking_number` is invalid.\",\"type\":\"BadRequest\"},\"data\":{\"tracking\":{\"title\":\"another title\"}}}", e.getMessage()); } }
7d6eebe7-8b76-4117-8c90-a87c61e07e5e
5
public void cmdBids(CommandSender sender, String[] args) { if( args.length < 2 ) { sender.sendMessage(Conf.colorMain + "Usage:"); sender.sendMessage(Conf.colorAccent + "/ee bids <material name>"); return; } Material material = materials.get(args[1]); if( material == null ) { sender.sendMessage(Conf.colorWarning + "Invalid material"); return; } Market market = markets.get(material); int totalQuantity = 0; double totalPrice = 0; sender.sendMessage(Conf.colorMain + "" + market.getBidsQuantity() + " " + args[1] + " wanted"); //Don't bother with the table if there's nothing to put in it. if(market.getBidsQuantity() == 0) return; sender.sendMessage(Conf.colorMain + "Quantity " + Conf.colorAccent + "Price " + Conf.colorMain + "Price Each " + Conf.colorAccent + "Total Qty " + Conf.colorMain + "Total Price"); int remaining = 5; for( Object object : market.getBids()) { if(remaining > 0) remaining--; else break; Order order = (Order)object; totalQuantity += order.getQuantity(); totalPrice += order.getPrice(); sender.sendMessage(Conf.colorMain + " " + order.getQuantity() + Conf.colorAccent + " " + order.getPrice() + Conf.colorMain + " " + (order.getPrice() / order.getQuantity()) + Conf.colorAccent + " " + totalQuantity + Conf.colorMain + " " + totalPrice); } }
b1603a03-df0d-47ac-9746-57b204c95293
4
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, InterruptedException, ExecutionException { System.out.println("Running benchmark. Press any key to continue."); System.in.read(); Map<Class<?>, Map<String, String>> keyLookupClasses = new LinkedHashMap<Class<?>, Map<String, String>>(); //Map<String, String> hashMapKeyValueConfiguration = new HashMap<String, String>(); //keyLookupClasses.put(HashMapKeyValueLookup.class, // hashMapKeyValueConfiguration); Map<String, String> concurrentHashMapKeyValueConfiguration = new HashMap<String, String>(); keyLookupClasses.put(ConcurrentHashMapKeyValueLookup.class, concurrentHashMapKeyValueConfiguration); Map<String, String> memcachedKeyValueConfiguration = new HashMap<String, String>(); keyLookupClasses.put(MemcachedKeyValueLookup.class, memcachedKeyValueConfiguration); Map<String, String> mySQLKeyValueLookupConfiguration = new HashMap<String, String>(); keyLookupClasses.put(MySQLKeyValueLookup.class, mySQLKeyValueLookupConfiguration); ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); for (Entry<Class<?>, Map<String, String>> clazzEntry : keyLookupClasses .entrySet()) { final KeyValueLookup keyValueLookup = (KeyValueLookup) clazzEntry .getKey().newInstance(); keyValueLookup.init(clazzEntry.getValue()); benchmark(keyValueLookup, executor); keyValueLookup.cleanup(); } executor.shutdown(); }
e9febcb1-1e31-41b5-948e-8361fe59cc63
2
private synchronized static void cleanUpAllExpiredSession() { Iterator it = sessions.entrySet().iterator(); long currTime = new Date().getTime(); while(it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); Session iSession = (Session)pair.getValue(); if(iSession.isExpired(currTime)) { it.remove(); } } }
85f30710-28fc-4ba3-8ca4-a96d695f40bc
8
private String sendRequest(String endpoint, Map<String, String> params) { try { StringBuffer paramBuffer = new StringBuffer(); Iterator<Map.Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); paramBuffer.append(URLEncoder.encode(pair.getKey(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8")); if (it.hasNext()) paramBuffer.append("&"); } String urlString = "http://yboss.yahooapis.com/ysearch/" + endpoint + "?" + paramBuffer; URL url = new URL(urlString); HttpURLConnection request = (HttpURLConnection) url.openConnection(); consumer.sign(request); BufferedReader in = new BufferedReader( new InputStreamReader(request.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } return response.toString(); } catch (MalformedURLException ex) { //Should never happen } catch (IOException e) { throw new BossException("IOException: " + e.getMessage()); } catch (OAuthMessageSignerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OAuthExpectationFailedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OAuthCommunicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } throw new BossException("Unspecified error"); }
af33cdcc-fa2d-4d40-8452-6f36408264d6
3
public void Mstep(List<Instance> instances) { int insIndex = 0; List <Double> counts = new ArrayList<Double>(); List <FeatureVector> newClusters = new ArrayList<FeatureVector>(); // init the counts and new clusters. for (int i = 0 ; i < clusters.size() ; i++ ) { counts.add(0.0); newClusters.add(new FeatureVector()); } // accumulate new clusters for (Instance instance : instances) { int assignment = assignments.get(insIndex); newClusters.get(assignment).add(instance); counts.set(assignment, counts.get(assignment)+1.0); insIndex ++; } int feaIndex = 0; for (FeatureVector cluster : newClusters) { cluster.scalarDivide(counts.get(feaIndex)); feaIndex ++; } this.clusters = newClusters; }
3078191d-485b-4c17-8336-eff4f33dac68
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<CompRequest> comp = new ArrayList<CompRequest>(); ArrayList<PaidRequest> paid = new ArrayList<PaidRequest>(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Employee emp = (Employee) request.getSession().getAttribute("emp"); String type = request.getParameter("type"); String url="/Main.jsp"; String message = ""; String dbURL = "jdbc:mysql://localhost:3306/itrs"; String username = "root"; String dbpassword = "sesame"; if(!(emp.getLoggedIn() && emp.getAdmin())) { url="/index.jsp"; } try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e){} try { if(type.equalsIgnoreCase("comprequest")) { url = "/ViewComp.jsp"; Connection conn = DriverManager.getConnection(dbURL,username,dbpassword); Statement s = conn.createStatement(); String qry = "SELECT * FROM " + type + " NATURAL JOIN department" + " NATURAL JOIN games NATURAL JOIN seating NATURAL JOIN employee ORDER BY dep_name"; ResultSet r = s.executeQuery(qry); while (r.next()) { CompRequest c = new CompRequest(); c.setRequest(r); comp.add(c); } r.close(); r = null; s.close(); s = null; } else { url = "/ViewPaid.jsp"; Connection conn = DriverManager.getConnection(dbURL,username,dbpassword); Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); String qry = "SELECT * FROM " + type + " NATURAL JOIN department" + " NATURAL JOIN games NATURAL JOIN seating NATURAL JOIN employee ORDER BY dep_name"; ResultSet r = s.executeQuery(qry); while (r.next()) { PaidRequest p = new PaidRequest(); p.setRequest(r); paid.add(p); } } } catch (SQLException e) { message = "SQL Error: " + e.getMessage(); } request.getSession().setAttribute("paid", paid); request.getSession().setAttribute("comp", comp); request.setAttribute("message", message); request.setAttribute("emp", emp); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); }
0bf05541-ab02-4b5d-afe9-1785e6ff160a
1
final public CycList nonAtomicSentenceDenotingDenotationalTerm(boolean requireEOF) throws ParseException, java.io.IOException, UnsupportedVocabularyException { CycList val; val = nonAtomicDenotationalTerm(false); eof(requireEOF); {if (true) return val;} throw new Error("Missing return statement in function"); }
3e3ecb03-ea8d-4598-bbb0-d498fce2f8e3
5
Object[] parameterForType(String typeName, String value, Widget widget) { if (typeName.equals("org.eclipse.swt.widgets.TreeItem")) { TreeItem item = findItem(value, ((Tree) widget).getItems()); if (item != null) return new Object[] {item}; } if (typeName.equals("[Lorg.eclipse.swt.widgets.TreeItem;")) { String[] values = split(value, ','); TreeItem[] items = new TreeItem[values.length]; for (int i = 0; i < values.length; i++) { TreeItem item = findItem(values[i], ((Tree) widget).getItems()); if (item == null) break; items[i] = item; } return new Object[] {items}; } return super.parameterForType(typeName, value, widget); }
9ca62851-1d31-454d-9030-8949d4ff56dd
0
private void initialize() { this.history = new DefaultComboBoxModel(); // Setup North Panel JPanel north_panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); north_panel.setLayout(gridbag); LOCATION = "Location"; // GUITreeLoader.reg.getText("location"); this.location_label = new JLabel(LOCATION + ":"); c.weightx = 0.0; c.fill = GridBagConstraints.NONE; c.insets = new Insets(0,4,0,4); gridbag.setConstraints(this.location_label, c); north_panel.add(this.location_label); c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(0,0,0,0); this.location = new JComboBox(); this.location.setModel(this.history); this.location.setActionCommand(LOCATION); this.location.setEditable(true); this.location.addActionListener(this); gridbag.setConstraints(this.location, c); north_panel.add(this.location); c.weightx = 0.0; c.fill = GridBagConstraints.NONE; this.prevButton = new MyButton(); this.prevButton.setMargin(new Insets(5,7,5,9)); ImageIcon prevImage = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("graphics/prev.gif")); this.prevButton.setIcon(prevImage); this.prevButton.setToolTipText("Back"); this.prevButton.setActionCommand(PREV); this.prevButton.addActionListener(this); gridbag.setConstraints(this.prevButton, c); north_panel.add(this.prevButton); this.nextButton = new MyButton(); this.nextButton.setMargin(new Insets(5,8,5,8)); ImageIcon nextImage = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("graphics/next.gif")); this.nextButton.setIcon(nextImage); this.nextButton.setToolTipText("Forward"); this.nextButton.setActionCommand(NEXT); this.nextButton.addActionListener(this); gridbag.setConstraints(this.nextButton, c); north_panel.add(this.nextButton); getContentPane().add(north_panel, BorderLayout.NORTH); // Setup Center Panel this.viewer = new JEditorPane(); this.viewer.setEditable(false); HTMLEditorKit htmlKit = new HTMLEditorKit(); this.viewer.setEditorKit(htmlKit); this.viewer.addHyperlinkListener(this); this.viewer.addPropertyChangeListener(this); this.jsp = new JScrollPane(this.viewer); getContentPane().add(this.jsp, BorderLayout.CENTER); setHistoryLocation(-1); this.initialized = true; }
3c1a3fc0-296b-4694-90bf-6d9d7014e43a
4
private void moveSnakeHeadToTheOtherSideOfTheWorld(SnakePiece head) { int x = head.getX(); int y = head.getY(); if (x < 0) { head.setX(width); } else if (x > width) { head.setX(0); } if (y < 0) { head.setY(height); } else if (y > height) { head.setY(0); } }
90e3880b-992a-41ec-b9fd-67fe8d2a90ae
5
public void rotateRight(RBNode x) { // pushing node x down and to the Right to balance the tree. x's Left child (y) // replaces x (since x < y), and y's Right child becomes x's Left child // (since it's < x but > y). RBNode y = x.getLeft(); // get x's Left node, this becomes y // set x's Right link x.setLeft(y.getRight()); // y's Right child becomes x's Left child // modify parents if(y.getRight() != sentinelNode) y.getRight().setParent(x); // sets y's Right Parent to x if(y != sentinelNode) y.setParent(x.getParent()); // set y's Parent to x's Parent if(x.getParent() != null) // null=root, could also have used root { // determine which side of its Parent x was on if(x == x.getParent().getRight()) x.getParent().setRight(y); // set Right Parent to y else x.getParent().setLeft(y); // set Left Parent to y } else setRoot(y); // at root, set it to y // link x and y y.setRight(x); // put x on y's Right if(x != sentinelNode) // set y as x's Parent x.setParent(y); }
e039b114-05c5-4403-ab6f-fd464215e110
8
* @Post: Queries the user for what type to upgrade the pawn to, and does so * @Return: None */ private void upgradePawn(Piece thePiece) { int whatToUpgradeTo=-1; Object answer = null; Object[] possibilities = {"Queen", "Knight", "Rook", "Bishop"}; if(isAI(isWhitesTurn()))//then it is the AI of the current turn { whatToUpgradeTo= myFrame.getAI(isWhitesTurn()).chooseUpgrade(thePiece.myLocation); }else { while(answer ==null) { answer = JOptionPane.showInputDialog(null, "Your pawn can now be upgraded. What would you like it to be?", "Upgrade", JOptionPane.PLAIN_MESSAGE, null, possibilities, "Queen"); } } Piece newPiece; if(answer==possibilities[0]||whatToUpgradeTo==0) { newPiece=new Queen(thePiece.isWhite, new Point(thePiece.getX(),thePiece.getY()), this.getBoard()); }else if(answer == possibilities[1]||whatToUpgradeTo==1) { newPiece = new Knight(thePiece.isWhite, new Point(thePiece.getX(),thePiece.getY()), this.getBoard()); }else if (answer == possibilities[2]||whatToUpgradeTo==2 ) { newPiece = new Rook(thePiece.isWhite, new Point(thePiece.getX(),thePiece.getY()), this.getBoard()); }else { newPiece=new Bishop(thePiece.isWhite, new Point(thePiece.getX(),thePiece.getY()), this.getBoard()); } myBoard.upgradePawn(thePiece.myLocation, newPiece); }
fe2a07e6-840e-49ec-8460-1f6019694ff5
0
public String toString() { return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; }
23405934-243a-43cf-b3bf-5e7514c62d3b
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,auto?L("<T-NAME> <T-IS-ARE> cursed!"):L("^S<S-NAME> curse(s) <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(msg.value()<=0) { final Item I=getSomething(mob,true); if(I!=null) { endLowerBlessings(I,CMLib.ableMapper().lowestQualifyingLevel(ID())); I.recoverPhyStats(); } endLowerBlessings(target,CMLib.ableMapper().lowestQualifyingLevel(ID())); success=maliciousAffect(mob,target,asLevel,0,-1)!=null; target.recoverPhyStats(); } } } else return maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to curse <T-NAMESELF>, but nothing happens.")); // return whether it worked return success; }
265de792-d8e9-4bb5-a62d-857ea2d54434
7
public static void main(String[] args) { int port = 8888; Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); out.println("QUERY TIME"); System.out.println(in.readLine()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { out.close(); } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
31d9cf55-3e90-405e-927d-1dca5de15986
6
private String moveCardOntoTopRow(List<Card> from, int boardIndexTo, int listIndexFrom) { List<Card> pile = topRow.get(boardIndexTo); Card fromTop = from.get(listIndexFrom); if (pile.size() == 0) { if (fromTop.getRank() == Card.Rank.ACE) { pile.add(from.get(listIndexFrom)); return ""; } else { return "Can only move an Ace to an empty pile."; } } else { Card pileTop = pile.get(pile.size() - 1); //Want reference equality if (pileTop == fromTop) { //Don't want to move onto self, nor display warning return "ONTO_SELF"; } if (listIndexFrom != from.size() - 1) { return "Can only move the bottom card to the top row."; } if (fromTop.getSuit().ordinal() == pileTop.getSuit().ordinal()) { if (fromTop.getRank().ordinal() == pileTop.getRank().ordinal() + 1) { pile.add(from.get(listIndexFrom)); return ""; } else { return fromTop.getRank().name() + " is not one higher than " + pileTop.getRank().name(); } } else { return "Can only move to a pile of the same suit"; } } }
d5e2db3b-06b3-4291-af67-3ba0de82647e
5
public void blackTurn(int sx, int sy, int ex, int ey) { int piece = board.getPiece(sx, sy); board.blackTurn(sx, sy, ex, ey); if (board.getMoveB()) { setInfo(0); turns++; if (cm.canAttackKing(board.getBoard(), piece, ex, ey)) { setInfo(1); cm.addSquares(); if (!cm.canKingMove() && !cm.canTakeDownAttacker(ex, ey)) { setInfo(3); } } } if (board.getWhite(12) == 99) { setInfo(3); } }
f9e720af-bcf6-45a7-8ba9-56c2994588bc
1
private static final double getPositionNearSource( int amountOfPixelsAway, TextStrategyParameters parameters ) { double length = parameters.getPath().getTotalLength(); if( length == 0 ) { return 0; } double position = amountOfPixelsAway / length; return Math.max( 0, Math.min( 0.5, position ) ); }
ef7706b5-2210-4a02-b866-47d3e892abed
0
public GameChrono(GameCanvas gc, ProBotGame game) { this.gc = gc; this.game = game; }
31a9b915-fc45-4e27-bbbc-110b41e1ea80
9
public Object calculate(GraphModel g) { ZagrebIndexFunctions zif = new ZagrebIndexFunctions(g); ZagrebIndexFunctions zifL = new ZagrebIndexFunctions(LineGraph.createLineGraph(g)); RenderTable ret = new RenderTable(); Vector<String> titles = new Vector<>(); titles.add(" p "); double maxDeg = 0; double maxDeg2 = 0; double minDeg = Integer.MAX_VALUE; double minDeg2 = Utils.getMinNonPendentDegree(g); ArrayList<Integer> al = AlgorithmUtils.getDegreesList(g); Collections.sort(al); maxDeg = al.get(al.size()-1); if(al.size()-2>=0) maxDeg2 = al.get(al.size()-2); else maxDeg2 = maxDeg; minDeg = al.get(0); if(maxDeg2 == 0) maxDeg2=maxDeg; double a=0; double b=0; double c=0; double d=0; int p = NumOfVerticesWithDegK.numOfVerticesWithDegK(g, 1); for(Vertex v : g) { if(g.getDegree(v)==maxDeg) a++; if(g.getDegree(v)==minDeg) b++; if(g.getDegree(v)==maxDeg2) c++; if(g.getDegree(v)==minDeg2) d++; } if(maxDeg==minDeg) b=0; if(maxDeg==maxDeg2) c=0; double m = g.getEdgesCount(); double n = g.getVerticesCount(); double M12=zif.getSecondZagreb(1); double M21=zif.getFirstZagreb(1); double M31=zif.getFirstZagreb(2); double M41=zif.getFirstZagreb(3); double M22=zif.getSecondZagreb(2); double Mm31=zif.getFirstZagreb(-4); double Mm11=zif.getFirstZagreb(-2); Vector<Object> v = new Vector<>(); v.add(p); ret.add(v); // v.add(2*M12+(a*maxDeg*maxDeg*maxDeg)+(c*maxDeg2*maxDeg2*maxDeg2) // +((maxDeg+maxDeg2)*(M21-a*maxDeg*maxDeg-c*maxDeg2*maxDeg2)) // +((maxDeg-maxDeg2-1-maxDeg*maxDeg2)*(2*m-a*maxDeg-c*maxDeg2))); // v.add(zif.getFirstZagreb(1)); // v.add((2*m*(maxDeg+minDeg)) // - (n*minDeg*maxDeg) // - (n-a-b)*(maxDeg-minDeg-1)); return ret; }
a27ade8d-14b2-42b6-87a4-2bd218e63c49
4
@Override public void caseAVetorVar(AVetorVar node) { inAVetorVar(node); if(node.getIdentificador() != null) { node.getIdentificador().apply(this); } if(node.getColcheteE() != null) { node.getColcheteE().apply(this); } if(node.getNumeroInt() != null) { node.getNumeroInt().apply(this); } if(node.getColcheteD() != null) { node.getColcheteD().apply(this); } outAVetorVar(node); }
facb6590-45f8-44e9-94c0-837d9c08052c
3
public final boolean postSync( Message event ){ int dispatchedCount = 0; MessageType type = event.getType(); for( MListener listener : ELIST ){ if( listener.isSupported( type ) ){ listener.update( event ); ++dispatchedCount; } } if( dispatchedCount == 0 ){ adminListener.update( event ); return false; } messageCounter.incrementAndGet(); return true; }
1264e805-fb0a-4e07-8b87-fd7f4a52af13
0
private void recordActive() { this.activeSince = new Date().getTime(); }
3e615326-7d18-46c1-a045-1ed56552dd24
6
public String diff_toDelta(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: try { text.append("+").append(URLEncoder.encode(aDiff.text, "UTF-8") .replace('+', ' ')).append("\t"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } break; case DELETE: text.append("-").append(aDiff.text.length()).append("\t"); break; case EQUAL: text.append("=").append(aDiff.text.length()).append("\t"); break; } } String delta = text.toString(); if (delta.length() != 0) { // Strip off trailing tab character. delta = delta.substring(0, delta.length() - 1); delta = unescapeForEncodeUriCompatability(delta); } return delta; }
167a1dc5-bb0c-4b33-a664-dac76b09bc44
6
public void method464(Model model, boolean flag) { anInt1626 = model.anInt1626; anInt1630 = model.anInt1630; anInt1642 = model.anInt1642; if(anIntArray1622.length < anInt1626) { anIntArray1622 = new int[anInt1626 + 100]; anIntArray1623 = new int[anInt1626 + 100]; anIntArray1624 = new int[anInt1626 + 100]; } anIntArray1627 = anIntArray1622; anIntArray1628 = anIntArray1623; anIntArray1629 = anIntArray1624; for(int k = 0; k < anInt1626; k++) { anIntArray1627[k] = model.anIntArray1627[k]; anIntArray1628[k] = model.anIntArray1628[k]; anIntArray1629[k] = model.anIntArray1629[k]; } if(flag) { anIntArray1639 = model.anIntArray1639; } else { if(anIntArray1625.length < anInt1630) anIntArray1625 = new int[anInt1630 + 100]; anIntArray1639 = anIntArray1625; if(model.anIntArray1639 == null) { for(int l = 0; l < anInt1630; l++) anIntArray1639[l] = 0; } else { System.arraycopy(model.anIntArray1639, 0, anIntArray1639, 0, anInt1630); } } anIntArray1637 = model.anIntArray1637; anIntArray1640 = model.anIntArray1640; anIntArray1638 = model.anIntArray1638; anInt1641 = model.anInt1641; anIntArrayArray1658 = model.anIntArrayArray1658; anIntArrayArray1657 = model.anIntArrayArray1657; anIntArray1631 = model.anIntArray1631; anIntArray1632 = model.anIntArray1632; anIntArray1633 = model.anIntArray1633; anIntArray1634 = model.anIntArray1634; anIntArray1635 = model.anIntArray1635; anIntArray1636 = model.anIntArray1636; anIntArray1643 = model.anIntArray1643; anIntArray1644 = model.anIntArray1644; anIntArray1645 = model.anIntArray1645; }
6f9ca9ed-9230-4141-aa94-74c5ed253d28
4
private String md5Encode(String plainText) { String re_md5 = new String(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } re_md5 = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return re_md5; }
51bb5e28-528e-4324-a00c-656cea5b3d74
7
@Override public void write(File file) throws IOException { FileOutputStream fout = new FileOutputStream(file); DataOutputStream dout = new DataOutputStream(fout); //check if charFrequencies should be stored as a byte, short, or int byte dataType = 0; for(int i : charFrequencies) { if(i > Short.MAX_VALUE) dataType = 2; else if(i > Byte.MAX_VALUE) dataType = 1; } dout.writeByte(dataType); dout.writeInt(stringLength); dout.writeInt(numZeroes); for(int i : charFrequencies) { if(dataType == 0) dout.writeByte(i); else if(dataType == 1) dout.writeShort(i); else if(dataType == 2) dout.writeShort(i); } dout.write(encodedMessage.toByteArray()); }
0f26ace6-08fa-4631-b72d-4a25237008e0
0
public void setCheckinDate(Date checkinDate) { this.checkinDate = checkinDate; }
07e27054-689c-4433-8132-8b3b1619b3d1
9
public void create(PypAdmAgend pypAdmAgend) { if (pypAdmAgend.getPypAdmAsistConList() == null) { pypAdmAgend.setPypAdmAsistConList(new ArrayList<PypAdmAsistCon>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); InfoPaciente idPaciente = pypAdmAgend.getIdPaciente(); if (idPaciente != null) { idPaciente = em.getReference(idPaciente.getClass(), idPaciente.getId()); pypAdmAgend.setIdPaciente(idPaciente); } PypAdmProgramas idPrograma = pypAdmAgend.getIdPrograma(); if (idPrograma != null) { idPrograma = em.getReference(idPrograma.getClass(), idPrograma.getId()); pypAdmAgend.setIdPrograma(idPrograma); } List<PypAdmAsistCon> attachedPypAdmAsistConList = new ArrayList<PypAdmAsistCon>(); for (PypAdmAsistCon pypAdmAsistConListPypAdmAsistConToAttach : pypAdmAgend.getPypAdmAsistConList()) { pypAdmAsistConListPypAdmAsistConToAttach = em.getReference(pypAdmAsistConListPypAdmAsistConToAttach.getClass(), pypAdmAsistConListPypAdmAsistConToAttach.getId()); attachedPypAdmAsistConList.add(pypAdmAsistConListPypAdmAsistConToAttach); } pypAdmAgend.setPypAdmAsistConList(attachedPypAdmAsistConList); em.persist(pypAdmAgend); if (idPaciente != null) { idPaciente.getPypAdmAgendList().add(pypAdmAgend); idPaciente = em.merge(idPaciente); } if (idPrograma != null) { idPrograma.getPypAdmAgendList().add(pypAdmAgend); idPrograma = em.merge(idPrograma); } for (PypAdmAsistCon pypAdmAsistConListPypAdmAsistCon : pypAdmAgend.getPypAdmAsistConList()) { PypAdmAgend oldIdAgendOfPypAdmAsistConListPypAdmAsistCon = pypAdmAsistConListPypAdmAsistCon.getIdAgend(); pypAdmAsistConListPypAdmAsistCon.setIdAgend(pypAdmAgend); pypAdmAsistConListPypAdmAsistCon = em.merge(pypAdmAsistConListPypAdmAsistCon); if (oldIdAgendOfPypAdmAsistConListPypAdmAsistCon != null) { oldIdAgendOfPypAdmAsistConListPypAdmAsistCon.getPypAdmAsistConList().remove(pypAdmAsistConListPypAdmAsistCon); oldIdAgendOfPypAdmAsistConListPypAdmAsistCon = em.merge(oldIdAgendOfPypAdmAsistConListPypAdmAsistCon); } } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
01056162-5540-4153-9018-60b737469f9f
0
public void setText(String s) { myText = s; refresh(); }
319bdd7d-d3ff-45ab-8b62-c329723f2c65
4
private File searchOtherFiles(File folder, String searchFile) { File retVal = null; for (File file : reverseArray(folder.listFiles())) { if (file.isDirectory()) { retVal = searchOtherFiles(file, searchFile); if (retVal != null) { return retVal; } } else { if (file.getName().equals(searchFile)) { retVal = file; break; } } } return retVal; }
6936454d-a6ce-4eef-bdfe-452acb4a5c26
7
public Enumeration listOptions() { Vector result; Enumeration enm; String param; SelectedTag tag; int i; result = new Vector(); enm = super.listOptions(); while (enm.hasMoreElements()) result.addElement(enm.nextElement()); param = ""; for (i = 0; i < TAGS_ALGORITHM.length; i++) { if (i > 0) param += "|"; tag = new SelectedTag(TAGS_ALGORITHM[i].getID(), TAGS_ALGORITHM); param += tag.getSelectedTag().getReadable(); } result.addElement(new Option( "\tThe algorithm to use.\n" + "\t(default: HAAR)", "A", 1, "-A <" + param + ">")); param = ""; for (i = 0; i < TAGS_PADDING.length; i++) { if (i > 0) param += "|"; tag = new SelectedTag(TAGS_PADDING[i].getID(), TAGS_PADDING); param += tag.getSelectedTag().getReadable(); } result.addElement(new Option( "\tThe padding to use.\n" + "\t(default: ZERO)", "P", 1, "-P <" + param + ">")); result.addElement(new Option( "\tThe filter to use as preprocessing step (classname and options).\n" + "\t(default: MultiFilter with ReplaceMissingValues and Normalize)", "F", 1, "-F <filter specification>")); if (getFilter() instanceof OptionHandler) { result.addElement(new Option( "", "", 0, "\nOptions specific to filter " + getFilter().getClass().getName() + " ('-F'):")); enm = ((OptionHandler) getFilter()).listOptions(); while (enm.hasMoreElements()) result.addElement(enm.nextElement()); } return result.elements(); }
010ff8dd-0546-4fa3-befa-295f48be870d
3
public void loadSound(String fileName) { AudioInputStream audioIn = null; try { URL url = Main.class.getResource(fileName); audioIn = AudioSystem.getAudioInputStream(url); Clip player = AudioSystem.getClip(); player.open(audioIn); sounds.put(fileName, player); }// <editor-fold defaultstate="collapsed" desc="catch and try blocks"> catch (LineUnavailableException ex) { Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedAudioFileException ex) { Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); }// </editor-fold> }
99a788b7-3809-4149-a016-ae0230248826
4
public void limitMaximumSpeed() { // prevent speed from getting to fast if (xOffset > MAX_SPEED) xOffset = MAX_SPEED; if (xOffset < -MAX_SPEED) xOffset = -MAX_SPEED; if (yOffset > MAX_SPEED) yOffset = MAX_SPEED; if (yOffset < -MAX_SPEED) yOffset = -MAX_SPEED; }
f1a0c854-267c-4b7e-a349-dd2564a027dd
3
public static Quiz[] getQuizzesbyUser(int UserId, boolean Completed) { try { String query = String.format("SELECT * FROM QUIZ\n" + "where quizid %s in (select quizid from quizresult where \n" + "userid = %d)", Completed? " " : "not", UserId); ResultSet rs = getQueryResults(query); List<Quiz> quizzes = new ArrayList<Quiz>(); while (rs.next()) { Quiz q = new Quiz(rs.getString("QUIZTITLE"), rs.getInt("QUIZID")); q.timeLimit = rs.getInt("TimeAllowed"); q.available = rs.getBoolean("Available"); q.feedbackAvailable = rs.getBoolean("FeedbackAvailable"); q.timeOutBehaviour = rs.getInt("TimeOutBehaviour"); q.showPracticeQuestion = rs.getBoolean("ShowPracticeQuestion"); q.navigationEnabled = rs.getBoolean("NAVIGATIONENABLED"); q.randomiseQuestions = rs.getBoolean("RANDOMISEQUESTIONS"); quizzes.add(q); } return quizzes.toArray(new Quiz[quizzes.size()]); } catch(SQLException se) { return null; } }
c71f6de1-c0ea-4e04-b531-c1d62a36edd4
9
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = new ListNode(0); ListNode current = head; ListNode previous = null; int carry = 0; while (l1 != null && l2 != null) { int sum = l1.val + l2.val + carry; current.val = sum % 10; carry = sum > 9 ? 1 : 0; current.next = new ListNode(0); previous = current; current = current.next; l1 = l1.next; l2 = l2.next; } if (l1 == null) l1 = l2; while (l1 != null) { int sum = l1.val + carry; current.val = sum % 10; carry = sum > 9 ? 1 : 0; current.next = new ListNode(0); previous = current; current = current.next; l1 = l1.next; } if (carry == 1) current.val = 1; else previous.next = null; return head; }
95ea9236-e378-45db-93b9-c5d9f6372ad6
9
public static void main(String[] args) { try { Tools[] rtss = new Tools[]{new RepositoryTools("repo"), new CLIEntryTools("entry"), new MacroTools("macro"), new CLIRoutineTools("routine"), new CLIUtilityTools("util")}; CLIParams params = getCommandLineParamaters(args); if (params == null) return; String runTypeOption = params.getPositional(0, null); if (runTypeOption == null) { logErrorWithOptions("A run type option needs to be specified as the first positional argument.", rtss); return; } params.popPositional(); for (int i=0; i<rtss.length; ++i) { Tools tools = rtss[i]; String toolsName = tools.getName(); if (runTypeOption.equals(toolsName)) { if (params.positionals.size() == 0) { logErrorWithOptions("An addditional run type option needs to be specified following \"" + runTypeOption + "\".", tools); return; } String runTypeOptionAddl = params.positionals.get(0); params.popPositional(); if (run(rtss[i], runTypeOptionAddl , params)) return; logErrorWithOptions("Specified run type option " + runTypeOptionAddl + " is not known.", tools); return; } } logErrorWithOptions("Invalid run type option " + runTypeOption + ".", rtss); return; } catch (ToolErrorException e) { MRALogger.logError("Error running tool", e); } catch (IOException e) { MRALogger.logError("File error", e); } catch (Throwable t) { MRALogger.logError("Unexpected error.", t); } }
babb86f7-a002-40c4-ac9f-6818508cc4cf
2
@Override public String toString() { StringBuffer ret = new StringBuffer(""); // Do the static stuff ret.append("#T#" + trackNumber + "~" + title + "~" + lengthInSeconds); // Do the personnel Iterator<Artist> pIt = personnel.iterator(); while (pIt.hasNext()) ret.append("~" + pIt.next()); ret.append("\n"); // Do the groups Iterator<LineUp> gIt = groops.iterator(); while (gIt.hasNext()) ret.append(gIt.next()); return ret.toString(); }
abada58b-b79a-449c-9c46-c6a99dcaef7f
2
public static void drawBufferedObject(BufferData bd) { GL2 gl = RobotPart.gl; gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); if(bd.getTextureId() != -1) gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, bd.getVertexId()); gl.glVertexPointer(3, GL2.GL_FLOAT, 0, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, bd.getElementId()); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, bd.getNormalId()); gl.glNormalPointer(GL2.GL_FLOAT, 0, 0); if(bd.getTextureId() != -1) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, bd.getTextureId()); // Implement 1D textures in BufferData gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0); } gl.glDrawElements(GL2.GL_QUADS, bd.getElementSize(), GL2.GL_UNSIGNED_SHORT, 0); gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); }
85b18b99-1cd9-4799-8400-a598f0e6a5e8
1
public DNode getNext(DNode v) throws IllegalStateException{ if(isEmpty()) throw new IllegalStateException("List is empty"); return v.getNext(); }
f948e764-a156-4bcb-8b9a-fa78ba55598c
1
public void getConnected() { cpds = new ComboPooledDataSource(); try { cpds.setDriverClass("com.mysqljdbc.Driver"); } catch (PropertyVetoException e) { e.printStackTrace(); } cpds.setJdbcUrl("jdbc:mysql://localhost:3456/bw_web"); cpds.setUser("cbw"); cpds.setPassword("test"); cpds.setMinPoolSize(1); cpds.setAcquireIncrement(3); cpds.setMaxPoolSize(10); // thisJdbc = new JdbcTemplate(cpds, false); }
66d29d77-474a-4fd4-8e1d-0a39722935dd
6
@Test public void testSetupFromOpenID() { CredentialConnection conn = CredentialConnection.getInstance(); conn.setDebug(true); try { conn.setupFromOpenID("hasdfttps://asldhlakjhs"); fail("Malformed URL!"); } catch (MalformedURLException e) { //ok } catch (IOException e) { e.printStackTrace(); fail("Unexpected Exception."); } try { conn.setupFromOpenID("https://albedo2.dkrz.de/myopenid/_$_$_$_$_$_$_$"); fail("Unexistent user!!"); } catch (MalformedURLException e) { e.printStackTrace(); fail("Unexpected Exception."); } catch (IOException e) { //ok } try { conn.setupFromOpenID("https://ipcc-ar5.dkrz.de/myopenid/dkrzpub1"); //ok } catch (MalformedURLException e) { e.printStackTrace(); fail("Unexpected Exception."); } catch (IOException e) { e.printStackTrace(); fail("Unexpected Exception."); } }
3529c11a-b338-4d7d-8922-d64e90306c66
9
private void checkNewPos() { if (Main.getGamestate().getMonster().awake) { Main.getGamestate().getMonster().move(Main.getGamestate().getPlayer()); } for (int i = 0; i <= 4; i++) { if (Main.getGamestate().getEntities().containsKey(RenderPriority.getRenderPriorityFromId(i))) { for (Entity entity : Main.getGamestate().getEntities().get(RenderPriority.getRenderPriorityFromId(i))) { if (entity.getX() == Main.getGamestate().getPlayer().getX() && entity.getY() == Main.getGamestate().getPlayer().getY()) { if (entity instanceof Trap && !((Trap) entity).sprung) { Main.getGamestate().getMonster().awake = true; ((Trap) entity).sprung = true; } else if (entity instanceof Flask) { Game.getInstance().toast.setData("You win!", 96, 0, 32); Game.getInstance().toast.show(); } } } } } }
8395a209-c424-4bc6-b4a5-a82dc98cf436
5
public void removeSelected() { if (getSelectionPath() != null) { Object o = getSelectionPath().getLastPathComponent(); if (o != null && o instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode n = (DefaultMutableTreeNode) o; if (n.getUserObject() != null && n.getUserObject() instanceof NodeLayer) { removeLayer((NodeLayer) n.getUserObject()); } } } }
7a569d6b-9989-40ee-98d9-60861449b4e9
7
@Override public void undo() throws CannotUndoException { super.undo(); if (selectedManipulable instanceof Part) { Shape shape = selectedManipulable.getShape(); if (shape instanceof TransformableShape) { TransformableShape s = (TransformableShape) shape; switch (scaleDirection) { case 0: s.scaleX(1.0f / scaleFactor); break; case 1: s.scaleY(1.0f / scaleFactor); break; case 2: s.scale(1.0f / scaleFactor); break; } if (s instanceof Blob2D) { ((Blob2D) s).update(); } model.refreshPowerArray(); model.refreshTemperatureBoundaryArray(); model.refreshMaterialPropertyArrays(); if (view.isViewFactorLinesOn()) model.generateViewFactorMesh(); } } view.setSelectedManipulable(selectedManipulable); view.repaint(); }
adfe49f2-434a-4a28-bc80-4b46f8b5ad61
3
public void encodeDirectBits(int v, int numTotalBits) throws IOException { for (int i = numTotalBits - 1; i >= 0; i--) { Range >>>= 1; if (((v >>> i) & 1) == 1) { Low += Range; } if ((Range & Encoder.kTopMask) == 0) { Range <<= 8; shiftLow(); } } }
81c2b22d-8dc9-4ca1-92b2-8f5790b6cb8f
7
void checkCommands1() { int i; Entity thnStore; String strStore=null; for (i=0;i<vctSide1.size();i++) { thnStore = (Entity)vctSide1.elementAt(i); if (!thnStore.vctCommands.isEmpty()) { strStore = (String)thnStore.vctCommands.elementAt(0); thnStore.vctCommands.removeElementAt(0); if (strStore.equalsIgnoreCase("flee")) { flee(thnStore); }else if (strStore.startsWith("cast ")) { strStore = strStore.substring(5,strStore.length()); thnStore.castSpell(strStore); }else if (strStore.startsWith("use ")) { strStore = strStore.substring(4,strStore.length()); thnStore.useItem(strStore,-1); }else if (strStore.startsWith("eat ")) { strStore = strStore.substring(4,strStore.length()); thnStore.useItem(strStore,Item.FOOD); }else if (strStore.startsWith("drink ")) { strStore = strStore.substring(6,strStore.length()); thnStore.useItem(strStore,Item.DRINK); } } } }
f540c80a-9cf1-41b6-939d-cffb23566495
1
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); final int rID = Integer.parseInt(request.getParameter("rID")); PrintWriter out = response.getWriter(); if (new Control(rID).startPlagiatsSearch(rID)) { out.print("true"); } else { out.print("false"); } out.close(); }
7aedbc5e-c575-45a2-9433-a979ceab59f8
3
public void act() { // This function handles all of an Agents' behavior in // any given step. // First, check if the Agent has enough energy to survive // the step, otherwise remove it. if (energy < metabolism) { remove(); } else { // Let the Agent know it has survived another step. age++; // 'Cost of living': Subtracting the metabolism from the // Agents' energy level. energy -= metabolism; // Generating a vector with the Sites that can be moved to, // and a vector with Sites suitable for offspring.. Vector<Site> freeSites = findFreeSites(); // Evaluating each of the possible Sites to move to. // YOU WILL NEED TO IMPLEMENT FINDBESTSITE YOURSELF. Site bestSite = findBestSite(freeSites); // Moving to the best possible Site, and reaping the energy // from it. // YOU WILL NEED TO IMPLEMENT MOVE AND REAP YOURSELF. move(bestSite); reap(bestSite); // Checking if the Agent is fertile and has a free neighboring // Site, and if so, producing offspring. if (energy > procreateReq) { Vector<Site> babySites = findBabySites(); if (babySites.size() > 0) { procreate(babySites); } } } }
4554a927-38df-47b5-8850-a232a829068a
3
Shard build(Config config) throws IOException { NestedShard root = new NestedShard(); for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { String key = entry.getKey(); Shard shard = EMPTY_SHARD; if (ConfigValueType.STRING.equals(entry.getValue().valueType())) { List<Schema.Player> players = this.createList(config.getString(key)); shard = new LeafShard(players); } if (ConfigValueType.OBJECT.equals(entry.getValue().valueType())) { shard = this.build( config.getConfig(key)); } root.add(key,shard); } return root; }
57befd42-2c56-4173-b72e-7efb12acfb8e
9
private void updateStateTellCountryFound(List<Keyword> keywords, List<String> terms) { //We came here due to a jump, so the Ingredient should have been passed, if not there's an error if (keywords != null && !keywords.isEmpty()) { for (Keyword kw : keywords) { if (kw.getKeywordData().getType().equals(KeywordType.COUNTRY)) { for (Recipe r : getRecipeDatabase()) { if (r.getRecipeData().getOriginalCountry() != null) { if (r.getRecipeData().getOriginalCountry().equalsIgnoreCase(kw.getWord())) { currRecipe = r; return; } } } getCurrentDialogState().setCurrentState(RecipeAssistance.RA_TELL_COUNTRY_NOT_FOUND); return; } } if (currRecipe == null || currRecipe.getRecipeData() == null) { DialogManager.giveDialogManager().setInErrorState(true); } } else { DialogManager.giveDialogManager().setInErrorState(true); } }
c8114d6d-9e9f-40f0-9236-ce53e0abcec1
5
static String locDesc(Description descr, Locale l) { if (l == null) { return descr.value(); } if (l.getLanguage().equals("en")) { return descr.en().isEmpty() ? descr.value() : descr.en(); } else if (l.getLanguage().equals("de")) { return descr.de().isEmpty() ? descr.value() : descr.de(); } return descr.value(); }
65a86f02-15d2-44f3-8a09-e5b2d913b4a2
7
public Screen createNew() { try { Constructor<? extends Screen> c = clazz.getDeclaredConstructor(new Class[] {}); return c.newInstance(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
b274f057-77c4-42f2-9751-5f91ce6a0b0e
4
public static String getBookID(){ try { ResultSet rs=DB.myConnection().createStatement().executeQuery("select max(BookID) from book"); while(rs.next()){ int ongoingId=(rs.getInt(1)); int nextId=ongoingId+1; maxid=Integer.toString(nextId); } }catch (NullPointerException exception1) { JOptionPane.showMessageDialog(null, "Error @ GenerateBookID Nullpointer exception "); return maxid="1"; } catch (ClassNotFoundException eexception2) { JOptionPane.showMessageDialog(null, "Error @ GenerateBookID class not found exception"); }catch(SQLException exception3){ JOptionPane.showMessageDialog(null, "Error @ GenerateBookID SQL exception"); } return maxid; }
3d4986cb-ac1d-4117-88af-236bc35f4284
4
public void run() { ///////////////////////////////////////////////////// // For ease of I/O (since we haven't yet discussed // binary packet data), convert the distance vector into // a String so it can be read using a Scanner: ///////////////////////////////////////////////////// String dvs = convert(from.getDv()); ///////////////////////////////////////////////////// // Make ten attempts to send the packet, then give up. The ten attempts // are separated by a one-second wait. This is simply to give the user // enough time to manually start up all the routers. ///////////////////////////////////////////////////// Socket sock = null; boolean done = false; int tries = 0; while (!done && tries < 10) { try { Thread.sleep(1000); // delay for manual start sock = BroadcastingService.getSocket(from, to); // obtener socket del pool Setup.println("[BroadcastingService.run] Notificando a " + to.getAddr().getHostAddress()); DataOutputStream out = new DataOutputStream(sock.getOutputStream()); if (keepalive){ String msg = getKeepAliveMsg(from); Setup.println(msg.replaceAll("^", "[BroadcastingService.run]\n")); out.writeBytes(msg); } else { Setup.println(dvs.replaceAll("^", "[BroadcastingService.run]\n")); out.writeBytes(dvs); } out.flush(); // sock.close(); done = true; } catch (Exception e) { tries = 10;//tries++; // if (tries >= 10) Setup.println("[BroadcastingService.run] No es posible enviar a " + to.getAddr().getHostAddress()); sockets.remove(to); } } }
48774d34-6736-4f38-b754-5cf9d17ede44
0
public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; }
12a84be5-55c8-4b25-8b52-719b0c84148c
4
public void save() { if(this.chunkFile == null) { log.warning("Chunk file not found. You might want to check that if you want to save anything."); return; } try { this.chunks.save(this.chunkFile); } catch(IOException ex) { ex.printStackTrace(); } if(this.memberFile == null) { log.warning("Member file not found. You might want to check that if you want to save anything."); return; } try { this.members.save(this.memberFile); } catch(IOException ex) { ex.printStackTrace(); } }
780f8949-a978-44da-b418-903744ea8b21
9
public void excute(Minecart minecart, MinecartControl mc, String... job) { if (!(minecart instanceof InventoryHolder) || minecart instanceof PoweredMinecart) { return; } InventoryHolder invMinecart = (InventoryHolder) minecart; HashSet<ItemStack> itemStacks = mc.getUtils().getItemTransferUtil().getItemStacks(job[0]); for (ItemStack itemStack : itemStacks) { if (itemStack.getAmount() == 0) { return; } for (Iterator<Recipe> irt = Bukkit.recipeIterator(); irt.hasNext();) { Recipe r = irt.next(); if (r instanceof ShapedRecipe) { ShapedRecipe recipe = ((ShapedRecipe) r); if (recipe.getResult().getType() == itemStack.getType() && recipe.getResult().getDurability() == itemStack.getDurability()) { System.out.println(recipe.getResult().getType().name()); int y = 0; while (y < itemStack.getAmount()) { crafting(recipe, invMinecart); y += recipe.getResult().getAmount(); } } } } } }
454ca003-6eea-452f-8f43-5449fc1fe875
6
@Override public ReduceOutput call(){ ReduceOutput reduceResult = new ReduceOutput(mapOut.elementAt(0).fileName, in.NC); for (int i = 0; i < mapOut.size(); i++) { reduceResult.wordCount += mapOut.elementAt(i).wordCount; Iterator it = mapOut.elementAt(i).docVector.entrySet().iterator(); while(it.hasNext()){ Map.Entry pair = (Map.Entry)it.next(); for (int j = 0; j < in.keyWords.size(); j++) { if(in.keyWords.elementAt(j).equals(pair.getKey())){ Float f = reduceResult.wordFreqs.elementAt(j); reduceResult.wordFreqs.remove(j); reduceResult.wordFreqs.add(j, f + (Float)pair.getValue()); } } it.remove(); } } for (int i = 0; i < reduceResult.wordFreqs.size(); i++) { Float f = reduceResult.wordFreqs.elementAt(i); reduceResult.wordFreqs.remove(i); reduceResult.wordFreqs.add(i, (f/reduceResult.wordCount) * 100); } if(reduceResult.containsAll()) Main.outputDocs.add(reduceResult); return reduceResult; }
0a21ff3a-cba0-4b70-8f93-6e66b49722ff
9
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Camion other = (Camion) obj; if (this.carga != other.carga) { return false; } if (this.ejes != other.ejes) { return false; } if (!Objects.equals(this.matricula, other.matricula)) { return false; } if (!Objects.equals(this.nroMotor, other.nroMotor)) { return false; } if (!Objects.equals(this.nroChasis, other.nroChasis)) { return false; } if (!Objects.equals(this.marca, other.marca)) { return false; } if (!Objects.equals(this.modelo, other.modelo)) { return false; } return true; }
fbd460a1-5493-4654-ab91-6e985259a88a
1
public FreebaseUrl(String url){ super(url); Properties props = new Properties(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("secrets.properties"); try{ props.load(inputStream); key = props.getProperty("omnom.freebase.apikey"); } catch(IOException ex){ ex.printStackTrace(); } }
5bdfe686-7eae-477d-b571-a460c15217fe
6
private static void testBoundaries() { int[] boundaries = { 1602, 540, 488, 238, 245, 258, 430, 441, 440, 441, 441, 422, 298, 430, 1000}; int[] histogram = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; Hand h; for(int i = 0; i < 1000000; i++) { if(i % 10000 == 0) System.out.print("."); h = randHand(); int rank = evaluator.evaluate(h.toCards()); for(int j = 0; j < 15; j++) { if(rank < boundaries[j]) { histogram[j] += 1; break; } else if(j == 14) { histogram[j] += 1; break; } else { rank -= boundaries[j]; } } } for(int i = 0; i < 15; i++) { System.out.println(i + ": " + histogram[i]); } }
e7b35fb8-8df6-40c3-acc8-51c5c477a8e4
9
public void render(Screen screen) { if (getDir() == 0) sprite = Sprite.zombie_up; if (getDir() == 1) sprite = Sprite.zombie_right; if (getDir() == 2) sprite = Sprite.zombie_down; if (getDir() == 3) sprite = Sprite.zombie_left; if (dead) sprite = Sprite.zombie_dead; screen.renderItem(x - 16, y - 16, sprite); if (hit) { screen.renderBar(xL - Screen.xOffset, yT - 4 - Screen.yOffset, getHealthPercent(32), LargeSprite.floatingHealth); } if (Player.target == this) { screen.renderAbsolute((screen.width / 2) - 62, 5, Sprite.zombie_head); screen.renderBar((screen.width / 2) - 46, 13, 97.0, LargeSprite.back); screen.renderBar((screen.width / 2) - 46, 14, getHealthPercent(100), LargeSprite.health); screen.renderAbsolute((screen.width / 2) - 64, 5, LargeSprite.enemy_health); } if (frozen && !dead) { screen.renderItem(x - 16, y - 16, Sprite.freeze); } }
34ceb5eb-4a46-49fd-b1db-6ef18e99ecc8
3
public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = ObjectMap.nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); }
54690fde-c66d-435a-94e2-210e66c3e005
6
public void initHSLbyRGB( int R, int G, int B ) { // sets Hue, Sat, Lum int cMax; int cMin; int RDelta; int GDelta; int BDelta; int cMinus; int cPlus; pRed = R; pGreen = G; pBlue = B; //Set Max & MinColor Values cMax = iMax( iMax( R, G ), B ); cMin = iMin( iMin( R, G ), B ); cMinus = cMax - cMin; cPlus = cMax + cMin; // Calculate luminescence (lightness) pLum = ((cPlus * HSLMAX) + RGBMAX) / (2 * RGBMAX); if( cMax == cMin ) { // greyscale pSat = 0; pHue = UNDEFINED; } else { // Calculate color saturation if( pLum <= (HSLMAX / 2) ) { pSat = (int) (((cMinus * HSLMAX) + 0.5) / cPlus); } else { pSat = (int) (((cMinus * HSLMAX) + 0.5) / ((2 * RGBMAX) - cPlus)); } //Calculate hue RDelta = (int) ((((cMax - R) * (HSLMAX / 6)) + 0.5) / cMinus); GDelta = (int) ((((cMax - G) * (HSLMAX / 6)) + 0.5) / cMinus); BDelta = (int) ((((cMax - B) * (HSLMAX / 6)) + 0.5) / cMinus); if( cMax == R ) { pHue = BDelta - GDelta; } else if( cMax == G ) { pHue = (HSLMAX / 3) + RDelta - BDelta; } else if( cMax == B ) { pHue = ((2 * HSLMAX) / 3) + GDelta - RDelta; } if( pHue < 0 ) { pHue = pHue + HSLMAX; } } }
c0e82d8a-9f6e-4547-8499-eac6ba129fa4
1
@Override public long spawnBoss(String bossData) { super.spawnBoss(bossData); GameActor a = Application.get().getLogic().createActor(bossData); PhysicsComponent pc = (PhysicsComponent)a.getComponent("PhysicsComponent"); pc.setLocation(x + Display.getWidth() + 100, y + 200); pc.setAngleRad(MathUtil.getOppositeAngleRad(upAngle)); pc.setTargetAngle(pc.getAngleRad()); AIComponent aic = (AIComponent)a.getComponent("AIComponent"); BaseAI ai = aic.getAI(); if(ai instanceof EnemyBossAI) { EnemyBossAI ebai = (EnemyBossAI)ai; ebai.setSector(ID); } return a.getID(); }
e0fece9a-066a-46c6-bf80-ef66d0508770
9
public boolean execute()throws MalformedURLException,IOException,TransactionException{ Transaction tr; int code; do{ tr=new Transaction(host,path,port); if(tr.execute()){ code=tr.getCode(); switch (code){ case 200: //TBD data=tr.getStrData(); bdata=tr.getByteData(); break; case 301: case 302:case 303:case 307: // System.out.println("LOCATION"+tr.getLocation()); url=new Url(tr.getLocation()); if(!url.isValid()){System.err.println(url.toString()+"LOCATIOn="+tr.getLocation());}//ATTENTION Почему валидация не проходт unfoldUrl(); //ADD HISTORY break; default: data=null; System.out.println("DRILLDOWN ERR CODE="+code); } } else { code=999; data=null; //add logging } }while(code>300 && code < 400); return data!=null; }
e5bd8522-8170-46c1-8006-b70311ea67f2
7
@Override public void sawOpcode(int opcodeSeen) { boolean check = true; String sigOperand = ""; try { sigOperand = getSigConstantOperand().toString(); } catch(IllegalStateException e) { check = false; } if (check == true && opcodeSeen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("setSecurityManager") && sigOperand.equals("(Ljava/lang/SecurityManager;)V")) //System.out.println("ConstantOperande: "+getSigConstantOperand().toString()); smSetsSeen = smSetsSeen + 1; if (smSetsSeen > 1) { System.out.println("Creating a bug report"); bugReporter.reportBug(new BugInstance(this, "MULTIPLE_SECURITY_MANAGER_SET_BUG",HIGH_PRIORITY) .addClassAndMethod(this).addString("ConstantOperand: "+sigOperand).addSourceLine(this)); } }
6ca17571-7677-444a-848e-6aa96d747f43
0
@Override public int getType() { return BuildingType.FARM.ordinal(); }
58875367-8312-43d1-b151-bbf99f0a12a8
6
public Animation(BufferedImage step1, BufferedImage step2, BufferedImage step3){ if(step1 == null || step2 == null || step3 == null) { if(step1 == null) System.err.print("Step 1 was NPE. Address: " + this + "\n"); if(step2 == null) System.err.print("Step 2 was NPE. Address: " + this + "\n"); if(step3 == null) System.err.print("Step 3 was NPE. Address: " + this + "\n"); throw new RuntimeException("Animation NEP"); } SPRITES = new BufferedImage[]{step1, step2, step3}; }
b6d554d8-7dc6-4370-bfcd-ea18760676b4
3
private void updateNeededMoney(int amount) { int money = this.money + amount; if(money < 0) { neededMoney -= money; } else if(neededMoney > 0) { neededMoney -= money; if(neededMoney < 0) { neededMoney = 0; } } }
9b92377d-156a-4ec4-8559-f51ee052f69e
0
public void addPredator(Animal animal) { predators.add(animal); }
009e1339-6df0-46e0-843e-c7ffa8872288
4
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
be8d7a04-a996-4807-bad6-cf7f62d4ac79
3
@Override public void doTag() throws JspException { JspWriter out = getJspContext().getOut(); // sorge für Verbindung zur Datenbank FilmothekModel model = new FilmothekModel(); UserBean borrower; try { // gibt das Rückgabedatum aus, falls der Film ausgeliehen ist. if(this.film.getBorrowerID() > 0){ df = DateFormat.getDateInstance(DateFormat.LONG, Locale.GERMANY); out.println("Rückgabe: "+df.format(film.getReturnDate())); // ist der Benutzer der Admin, zeige ihm einen Mail-Link zum Ausleihenden User if(this.user.getRole().equals(UserBean.ROLE_ADMIN)){ out.println("<br />"); borrower = model.getUser(film.getBorrowerID()); out.println("Verliehen an: <a href='mailto:"+borrower.getEmail()+"'>"+borrower.getName()+"</a>"); } } } catch (java.io.IOException ex) { throw new JspException("Error in FilmStatusTagHandler tag", ex); } }
454f0a66-704d-4b8d-a5d8-b5085c99faab
1
private void promptForMatchSave() { int chosenOption = JOptionPane.showConfirmDialog(this, "Save the current game before closing it?", "Quit without saving?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (chosenOption == JOptionPane.YES_OPTION) { showSaveDialog(); } }
5363d8d0-1acf-458b-b983-9bfda23aadf8
3
@Override public void reactPressed(MouseEvent e) { if (isPressed) return; super.reactPressed(e); if (StateMachine.getState() == ProgramState.SONG_PLAYING) { StateMachine.setState(ProgramState.EDITING); theStaff.stopSong(); } else if (StateMachine.getState() == ProgramState.ARR_PLAYING) { StateMachine.setState(ProgramState.ARR_EDITING); theStaff.stopSong(); } }
63257a54-ed1c-4f94-8ae2-0584a5991717
5
public static void listPlayersHomes( BSPlayer player ) throws SQLException { if ( player.getHomes().isEmpty() ) { player.sendMessage( Messages.NO_HOMES ); return; } boolean empty = true; for ( String server : player.getHomes().keySet() ) { String homes; if ( server.equals( player.getServer().getInfo().getName() ) ) { homes = ChatColor.RED + server + ": " + ChatColor.BLUE; } else { homes = ChatColor.GOLD + server + ": " + ChatColor.BLUE; } for ( Home h : player.getHomes().get( server ) ) { homes += h.name + ", "; empty = false; } if ( empty ) { player.sendMessage( Messages.NO_HOMES ); return; } player.sendMessage( homes.substring( 0, homes.length() - 2 ) ); } }
499a1f27-22a0-436a-87f3-e55d7100bed2
3
public void checkConnection() throws Exception { if (!socket.isConnected()) { //fixed if(Server.mapTest.containsKey(socket)) { Server.mapTest.remove(socket); } //fixed for (Map.Entry<Socket,User> entry: Server.mapTest.entrySet()) { Socket temp = entry.getKey(); PrintWriter tempWriter = new PrintWriter(temp.getOutputStream()); tempWriter.println("User from "+ temp.getLocalAddress().getHostName() +" disconnected"); tempWriter.flush(); System.out.println("User from "+ temp.getLocalAddress().getHostName() +" disconnected"); } } }
2944b4fe-7a23-4868-be8b-cae37839ed4d
3
static boolean check(int r, int c) { return r >= 0 && r < 4 && c >= 0 && c < 4; }
d8b072ec-f0d9-454d-a093-aab2b5798a26
2
private void tblEmployeeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblEmployeeMouseClicked int row = tblEmployee.convertRowIndexToModel(tblEmployee.getSelectedRow()); int personeelsnummer = Integer.parseInt(tblEmployee.getModel().getValueAt(row, 0).toString()); selectedEmployee = RoosterProgramma.getInstance().getEmployee(personeelsnummer); if (evt.getClickCount() == 1) { btnDelete.setEnabled(true); btnChange.setEnabled(true); } else { if (isEdit) { RoosterProgramma.getInstance().showPanel(new ChAddEmployee(selectedEmployee), this); } else { Calendar calendar = Calendar.getInstance(); EmployeeTimeSheet timesheet = new EmployeeTimeSheet(selectedEmployee, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1); RoosterProgramma.getInstance().showPanel(timesheet, this); } } }//GEN-LAST:event_tblEmployeeMouseClicked
615b055a-75fc-4a6b-a58d-137fea3ec90c
5
public CycList deleteDuplicates() { if (this.isProperList) { if (this.contains(this.dottedElement)) { this.setDottedElement(null); } } for (int i = 0; i < this.size(); i++) { for (int j = i + 1; j < this.size(); j++) { if (this.get(i).equals(this.get(j))) { this.remove(j); j--; } } } return this; }
408d5aee-8aea-447e-a915-0528c0149ada
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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true); } }); }
a659c03e-c0fd-4825-9250-9f864ad211bc
8
public static boolean wordBreak(String s, HashSet<String> dict) { int len = s.length(); boolean res = false; //String tmpStr = s; Iterator<String> iterator=dict.iterator(); String[] str = new String[len*len]; int[] idx = new int[len*len]; int i=0; int tmpidx; String repStr = ""; int nextStart = 0; //while(iterator.hasNext()){ int tmpLen = s.length()+1; String tmp = null; while( ( tmp = findLongestString(dict , tmpLen ))!=null){ //tmp = (String)iterator.next(); System.out.println("DICT:"+tmp ); tmpLen = tmp.length()+1; boolean gotOne = false; while( ( tmpidx = s.indexOf( tmp,nextStart ) ) >=0 ){//BUG str[i]=tmp; idx[i]=tmpidx; i++; nextStart = tmpidx + tmp.length(); gotOne = true; if(gotOne){ break; } //System.out.println("NextStart:"+nextStart); } nextStart=0; } CollectionTool.printArray(str); // CollectionTool.printArray(idx); int act_len = i; //int nextIdx = 0; //System.out.println("Find next:"+findNext(nextIdx, str[2].length() ,idx)); for(int k=0;k<act_len;k++){ if(idx[k]==0){ System.out.println("STR:"+str[k]); int totalen = str[k].length(); int nowIdx = 0; int nextIdx = -1; int strNowIdx = k; while( ( nextIdx = findNextIdx( nowIdx , str[strNowIdx].length() , idx) )>=0){ System.out.println("BF-totalen:"+totalen+",nowIdx:"+nowIdx+",|strNowIdx:"+strNowIdx+",nextIdx:"+nextIdx); System.out.println("NOW-IDX:"+ nowIdx + ",Next IDX:"+nextIdx ); System.out.println("STR NOW:"+ str[strNowIdx]+",STR NXT:"+ str[nextIdx] ); if( totalen <= s.length()){ //+ str[nextIdx ].length() totalen += str[nextIdx].length(); nowIdx += str[strNowIdx].length(); //nextIdx = nextIdx+str[tmpIdx].length()-1; strNowIdx = nextIdx; } System.out.println("AF-totalen:"+totalen+",nowIdx:"+nowIdx+",strNowIdx:"+strNowIdx+",nextIdx:"+nextIdx); System.out.println("--------"); } //totalIdx += str[nextIdx].length(); if( totalen == s.length()){ return true; } } } return res; }
656af2a3-2ab7-4fc2-8996-c8d1447f981e
4
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) { if (attr.isRegularFile()) { String name = "" + file; if (name.endsWith(".txt")) { for (JSONArray comments : extractor.extractFromCrawler(file, related)) { this.docs.addJSONComments(comments); } } else if (Character.isDigit(name.charAt(name.length() - 1))) { this.docs.addComments(extractor.extractFromDUC(file)); } } return CONTINUE; }
459398b5-cb09-46f1-ac53-9dfea2e07a0e
4
@Override public void initTableModel(JTable table, List<Users> list) { //Формируем массив пользователей для модели таблицы Object[][] usersArr = new Object[list.size()][table.getColumnCount()]; int i = 0; for (Users user : list) { //Создаем массив для пользователя Object[] row = new Object[table.getColumnCount()]; //Заполняем массив данными row[0] = user.getId(); row[1] = user.getUserName(); //Определяем тип пользователя int userTypeId = user.getUserTypeId(); String userType = ""; try { PreparedStatement statement = getConnection().prepareStatement(userTypeIdQuery); statement.setInt(1, userTypeId); ResultSet result = statement.executeQuery(); if (result.next()){ userType = result.getString("USERNAME"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Ошибка при создании запроса"); } row[2] = userType; //Получаем статус пользователя int state = user.getUserState(); String userState; switch (state){ case 1: { userState = activeState; break; } default: { userState = nonActiveState; break; } } row[3] = userState; usersArr[i++] = row; } table.setModel(new DefaultTableModel( usersArr, UsersDAO.getFieldsName()) { public Class getColumnClass(int columnIndex) { return types[columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); table.getColumnModel().getColumn(0).setPreferredWidth(80); table.getColumnModel().getColumn(1).setPreferredWidth(120); table.getColumnModel().getColumn(2).setPreferredWidth(140); table.getColumnModel().getColumn(3).setPreferredWidth(120); }
f5f8f685-5b57-4a87-ae8c-de1ad8d71261
1
public static <R,T> R reduce(Collection<T> c, Function2<R,T> f, R z) { for (T e : c) { z = f.apply(z, e); } return z; }
6f4d8c6c-af7f-4281-9a0a-0b63522459f8
2
public boolean wordExists(final String word, final List<String> words){ for (final String current : words) { if( word.equalsIgnoreCase(current) ) { return true; } } return false; }
a11514ef-61a6-4529-854c-333c428e07fa
5
private ImageProcessor performWatershedding(List<Point> maximList, List<BoundaryBox> bbs, int width, int height, double[] hMin, ImageProcessor origImg){ ImageProcessor tempMask = new ByteProcessor(width, height); for(int i = 0; i < maximList.size(); i++){ BoundaryBox bb = bbs.get(i); BoundaryBox boundBox = BoundaryBox.clip(new BoundaryBox( maximList.get(i).getX() - bb.getWidth() - 80, maximList.get(i).getY() - bb.getHeight() - 80, 2*bb.getWidth()+160, 2*bb.getHeight()+160), 0, 0, width - 1, height - 1); ImageProcessor window = new ByteProcessor(width, height); ImageProcessor im = origImg; im.setRoi(boundBox.getX(), boundBox.getY(), boundBox.getWidth(), boundBox.getHeight()); ImageProcessor interest = im.crop(); window.copyBits(regionTight(interest, .1, hMin[i], boundBox.getWidth(), boundBox.getHeight()), boundBox.getX(), boundBox.getY(), Blitter.COPY); if(window.get(maximList.get(i).getX(), maximList.get(i).getY()) != 0){ float num = window.get(maximList.get(i).getX(), maximList.get(i).getY()); for(int j = boundBox.getX(); j < boundBox.getX() + boundBox.getWidth(); j++){ for(int k = boundBox.getY(); k < boundBox.getY() + boundBox.getHeight(); k++){ if(window.get(j,k) == num){ tempMask.putPixelValue(j,k,255); } } } } // for(int j = boundBox.getX(); j < boundBox.getX() + boundBox.getWidth(); j++){ // for(int k = boundBox.getY(); k < boundBox.getY() + boundBox.getHeight(); k++){ // tempMask.putPixelValue(j,k,window.get(j,k)); // } // } im.resetRoi(); } ImageProcessor mask = findConnectedComponents(tempMask); mask.threshold(0); ImageProcessor temp = origImg.duplicate(); temp.threshold(25); mask.copyBits(temp, 0, 0, Blitter.AND); mask.copyBits(tempMask, 0, 0, Blitter.AND); mask.threshold(0); mask = setLabels(bwAreaOpen(mask, 800)); // mask.threshold(0); return mask; // return tempMask; }
5b0c5bff-eacb-42d4-a93e-654b387066d7
4
@Override public boolean onMouseDown(int mX, int mY, int button) { if(mX > x && mX < x + width && mY > y && mY < y + height) { //GameActor toBuy = Application.get().getLogic().getActor(Application.get().getLogic().createActor("assets/data/actors/cannon.xml")); //Application.get().getLogic().getGame().setCurrentMouseAction(new PlaceWeaponAction(toBuy)); Application.get().getHumanView().popScreen(); return true; } return false; }
c5ff7b0e-aeeb-4f50-aba1-4b75ef65d026
7
public static void main(String args[]){ int i=0; int j=0; addset.add(firstset[0]); for(i =0 ;i< firstset.length;i++){ for(j=0;j<secondset.length;j++){ if (firstset[i] == secondset[j]){ subsset[i] = 0; } if(!addset.contains(secondset[j])){ addset.add(secondset[j]); } if(!addset.contains(firstset[i])){ addset.add(firstset[i]); } } } System.out.println("Substraction is"); for(i=0;i<subsset.length;i++){ if(subsset[i] != 0){ System.out.print(subsset[i]+ " "); } } System.out.println(); System.out.println("Addition is"); System.out.print(addset); }
ea3980f1-7ce5-4a1a-b07b-fb370e0bac57
3
private boolean isObstructed() { IntPoint[] blocks = fallingPiece.getBlocks(); for(int i = 0; i < 4; i++) { IntPoint p = blocks[i]; if(!p.inBounds(length, width, height)) return false; if(cubes[p.getX()][p.getY()][p.getZ()] != Piece.NOTHING) { return false; } } return true; }
6f5b0db1-053c-4ec0-b7ce-ba65a0ec69a0
1
@Override public void deleteUser(Integer id) { User user = userDao.findById(id); if(user==null) return; userDao.delete(user); }
5729e808-c461-47d7-8526-dc55356da9a1
4
public void run(){ requestFocus(); long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns = 1000000000.0 / 60.0; double delta = 0; int frames = 0; int updates = 0; while(running){ long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; while(delta >= 0.0){ update(); updates++; delta--; } render(); frames++; if(System.currentTimeMillis() - timer > 1000){ timer += 1000; if(debug) frame.setTitle(title + " | " + updates + " ups, " + frames + " fps"); frames = 0; updates = 0; } } }