text
stringlengths
14
410k
label
int32
0
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") ArrayHashMapMergingQueue other = (ArrayHashMapMergingQueue) obj; if (mergedMap == null) { if (other.mergedMap != null) { return false; } } else if (!mergedMap.equals(other.mergedMap)) { return false; } if (mergedQueue == null) { if (other.mergedQueue != null) { return false; } } else if (!mergedQueue.equals(other.mergedQueue)) { return false; } return true; }
9
@Override //оповещение наблюдателей public void notifyObservers() { //идем по листу наблюдателей и оповещаем их for (final Observer anObserverList : observerList) { //из состояния моделт берем все, что надо знать наблюдателю и передаем ему anObserverList.update(state.getBricks(), state.getScore(), state.getDifficulty(), state.getTheme(), state.getPicture(), getBrick(state.getDifficulty()), state.getPictureChanged(), state.getResultFromButton(), state.getEndOfTheGame()); } }
1
private static void test_zerosCount(TestCase t) { // Print the name of the function to the log pw.printf("\nTesting %s:\n", t.name); // Run each test for this test case int score = 0; for (int i = 0; i < t.tests.length; i += 2) { int bits = (Integer) t.tests[i]; int exp = (Integer) t.tests[i + 1]; try { field.setInt(vec, bits); } catch (IllegalAccessException e) { e.printStackTrace(); } int res = vec.zerosCount(); boolean cor = exp == res; if (cor) { ++score; } pw.printf( "%s(): Bits: %8X Expected: %2d Result: %2d Correct: %5b\n", t.name, bits, exp, res, cor); pw.flush(); } // Set the score for this test case t.score = (double) score / (t.tests.length / 2); }
3
public LocalInfo getLocalInfo(int addr, int slot) { LocalInfo li = new LocalInfo(this, slot); if (lvt != null) { LocalVarEntry entry = lvt.getLocal(slot, addr); if (entry != null) li.addHint(entry.getName(), entry.getType()); } allLocals.addElement(li); return li; }
2
public String reverseWords(String s) { String result = ""; if (s.length() == 0) return result; Stack<String> stack = new Stack<String>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != ' ') { String word = ""; while (i < s.length() && s.charAt(i) != ' ') { word += s.charAt(i); i++; } stack.push(word); } } while (!stack.isEmpty()) { result += stack.pop(); if (!stack.isEmpty()) result += " "; } return result; }
7
public Coord getc() { Gob tgt = gob.glob.oc.getgob(this.tgt); if(tgt == null) return(gob.rc); Coord c = tgt.position(); return(c); }
1
public DisplayMode getHighestResolutionDisplayMode(){ DisplayMode[] videoCardModes = videoCard.getDisplayModes(); int highest = 0; for(int k = 1; k < videoCardModes.length; k++){ if(videoCardModes[highest].getWidth() < videoCardModes[k].getWidth()){ highest = k; }else if(videoCardModes[highest].getWidth() == videoCardModes[k].getWidth() && videoCardModes[highest].getHeight() < videoCardModes[k].getHeight()){ highest = k; }else if(videoCardModes[highest].getWidth() == videoCardModes[k].getWidth() && videoCardModes[highest].getHeight() == videoCardModes[k].getHeight() && videoCardModes[highest].getBitDepth() < videoCardModes[k].getBitDepth()){ highest = k; } } return videoCardModes[highest]; }
7
private static Method findMethod2(Class clazz, String name, String desc) { Method[] methods = SecurityActions.getDeclaredMethods(clazz); int n = methods.length; for (int i = 0; i < n; i++) if (methods[i].getName().equals(name) && makeDescriptor(methods[i]).equals(desc)) return methods[i]; return null; }
3
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true){ int n = sc.nextInt(); int m = sc.nextInt(); if((n|m)==0)break; double[][] t = new double[n][n]; for(int i=0;i<n;i++)for(int j=0;j<n;j++)t[i][j]=sc.nextDouble(); double[][] dp = new double[m][n]; for(int i=0;i<n;i++)dp[0][i]=1; for(int i=1;i<m;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ dp[i][j] = Math.max(dp[i][j], dp[i-1][k]*t[k][j]); } } } double a = 0; for(int i=0;i<n;i++)a=Math.max(a, dp[m-1][i]); System.out.printf("%.2f\n", a); } }
9
public void in_event () { // If still handshaking, receive and process the greeting message. if (handshaking) if (!handshake ()) return; assert (decoder != null); boolean disconnection = false; // If there's no data to process in the buffer... if (insize == 0) { // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inbuf = decoder.get_buffer (); insize = read (inbuf); inbuf.flip(); // Check whether the peer has closed the connection. if (insize == -1) { insize = 0; disconnection = true; } } // Push the data to the decoder. int processed = decoder.process_buffer (inbuf, insize); if (processed == -1) { disconnection = true; } else { // Stop polling for input if we got stuck. if (processed < insize) io_object.reset_pollin (handle); // Adjust the buffer. insize -= processed; } // Flush all messages the decoder may have produced. session.flush (); // An input error has occurred. If the last decoded message // has already been accepted, we terminate the engine immediately. // Otherwise, we stop waiting for socket events and postpone // the termination until after the message is accepted. if (disconnection) { if (decoder.stalled ()) { io_object.rm_fd (handle); io_enabled = false; } else error (); } }
8
public boolean isEatable() { return false; }
0
private void checkInterval(int value) throws PropertyException { if(value != UNDEFINED) { if((value < 0) || (value > 100)) throw new PropertyException(this, "Value " +value +" is not in range [0, 100]."); } }
3
public void keyReleased(KeyEvent e){ switch(e.getKeyCode()){ case 37: case 65: left = false; ((Player)engine.getWorld().getPlayer()).setNext(left, right,-1); break; case 38: up = false; break; case 39: case 68: right = false; ((Player)engine.getWorld().getPlayer()).setNext(left, right,-2); break; case KeyEvent.VK_SPACE: up = false; break; } }
6
private ActualParameters parseActualParameters() { //System.out.println("parseActualParameters"); ActualParameters node = new ActualParameters(); expect("lp"); String[] operators = {"plus","minus","ident","integer","lp","tilde"}; for(String l : operators) { //int i=0; i< operators.length; i++) { if (nextIs(l)){ node.getExpression().add(parseExpression()); while(nextIs("comma")) { acceptIt(); node.getExpression().add(parseExpression()); } break; } } expect("rp"); return node; }
3
public OdigosCard(int id) { /* * kartela odigou gia anafora provlimatos */ con = new Mysql(); odigosId=id; this.setTitle("Anafora Provlimatos"); /* vgazei to para8uro sto kedro tis othonis me diastaseis 350x250 */ Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setBounds(dim.width/2-150, dim.height/2-125, 350, 250); /*--------------*/ this.setResizable(false); getContentPane().setLayout(null); JLabel provlimaLabel = new JLabel("Provlima:"); provlimaLabel.setBounds(19, 11, 67, 14); getContentPane().add(provlimaLabel); JLabel sxoliaLabel = new JLabel("Sxolia:"); sxoliaLabel.setBounds(19, 36, 67, 14); getContentPane().add(sxoliaLabel); sxolia = new JTextPane(); sxolia.setBounds(107, 36, 189, 131); getContentPane().add(sxolia); provlima = new JComboBox<String>(); provlima.setBounds(107, 8, 189, 20); getContentPane().add(provlima); for(int i=0;i<provlimata.length;i++) provlima.addItem(provlimata[i]); JButton sendButton = new JButton("Send"); sendButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { /* * elegxei ta stoixia kai epeita stelnei tin anafora apothikeuontas thn sthn vash */ if(checkData(sxolia.getText())) send(provlima.getSelectedItem().toString(),sxolia.getText()); } }); sendButton.setBounds(107, 188, 100, 23); getContentPane().add(sendButton); }
2
public void ClearCircleStrong(int X, int Y, int R) { // long time = System.nanoTime(); for (int i1 = Math.max(X-(R+1),0); i1 < Math.min(X+(R+1),w); i1 ++) { for (int i2 = Math.max(Y-(R+1),0); i2 < Math.min(Y+(R+1),h); i2 ++) { if (Math.round(Math.sqrt(Math.pow(i1-X,2)+Math.pow(i2-Y,2))) < (R/2)) { if (cellData[i1][i2]==OIL) { if (random.nextInt(10)==2) { cellData[i1][i2]=AIR; //oilExplode(i1, i2); entityList.add(new ExplosionEntity(i1,i2,8,1)); ClearCircle(i1,i2,10); } } cellData[i1][i2]=AIR; } } } // G2D.setColor(Color.white); // G2D.setPaint(skyPaint); // G2D.fillArc(X-(R/2), Y-(R/2), R, R, 0, 360); // G2D.setPaint(null); // System.out.println(System.nanoTime()-time); }
5
public void registerTick() { // count Frames per second... lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; if( totalTime > 1000 ) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; }
1
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); String webRoot = Utils.getWebRoot();//this.getServletConfig().getServletContext().getRealPath("/"); System.getProperty("user.dir"); File file = new File(webRoot + "account.txt"); System.out.println(file.getAbsolutePath()); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line = null; String[] data = null; String username = null; String password = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) continue; data = line.split("="); username = data[0]; password = data[1]; System.out.println(username + ";" + password); } try { connect(); } catch (Exception e) { e.printStackTrace(); } String sendto = request.getParameter("sendto"); String content = request.getParameter("content"); String title = request.getParameter("title"); // MailUtil.sendMail("买到票拉", "this is test", "289048093@qq.com", true); }
3
public String toString() { String s = ""; for (int r = 0; r < 4; r++) { s += "[ "; for (int c = 0; c < 4; c++) { s += get(c, r) + " "; } s += "]\n"; } return s; }
2
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(PrincipalUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PrincipalUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PrincipalUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PrincipalUI.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() { obterInstancia().setVisible(true); } }); }
6
private String buildJsonUsername() { Iterator<String> iterator = getUserName().iterator(); JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); while (iterator.hasNext()) { jsonArrayBuilder.add((String) iterator.next()); } System.out.println("User Array " + Json.createObjectBuilder().add("users", jsonArrayBuilder).build().toString()); return Json.createObjectBuilder().add("users", jsonArrayBuilder).build().toString(); }
1
public void drawGameObjects(final Graphics g) { for (GameObject gameObject : gameObjects) { gameObject.draw(g); } for (Projectile p : projectiles) { p.draw(g); } for (int i = 0; i < monsters.size(); i++) { monsters.get(i).draw(g); } }
3
public Deck() { for (Card.SIGN sign : Card.SIGN.values()) { for (Card.VALUE value : Card.VALUE.values()) { cards.add(new Card(sign, value)); } } }
2
public static String code(String pngfile) throws IOException { BufferedImage image = null; try{ File file=new File(pngfile); image=ImageIO.read(file); }catch(IIOException e){ //System.out.println("Image not found"); } BufferedImage img=null; int w=image.getWidth(); int h=image.getHeight(); int pixels[]=new int[w*h]; try{ PixelGrabber pg=new PixelGrabber(image,0,0,w,h,pixels,0,w); pg.grabPixels(); }catch(Exception es){ //System.out.println(es+"alok"); } int p=pixels[0]; int b=0xffffff & (p); String bin=""; // System.out.println("b="+b); //int i=1; int nh=h; if(h%2==0) nh=h-1; int incre_w=coprime(w); int incre_h=coprime(nh); int k=incre_w; int l=incre_h; p=pixels[l*w+k]; int b1=0xff&(p); k=k+incre_w; l=l+incre_h; for(int j=0;j<b;j++) { p=pixels[l*w+k]; int m=0xff &(p); if(m%2==0) bin=bin+'0'; else bin=bin+'1'; //i=i+2499; k=k+incre_w; l=l+incre_h; if(k>=w) k-=w; if(l>=nh) l-=nh; } //System.out.println("bin="+bin); String coded=""; pass=""; String bin1=bin.substring(b-b1, b); bin=bin.substring(0, b-b1); k=bin.length(); for(int j=0;j<k;j+=8) coded=coded+(char)Integer.parseInt(bin.substring(j,j+8),2); k=bin1.length(); for(int j=0;j<k;j+=8) pass=pass+(char)Integer.parseInt(bin1.substring(j,j+8),2); pass = decrypt(pass,new BigInteger("3078434453"),new BigInteger("1846993025")); //System.out.println("pass="+pass); //System.out.println("coded="+coded); return(coded); }
9
private void trSort(int n, int depth) { final int[] arr = this.sa; TRBudget budget = new TRBudget(trIlg(n)*2/3, n); for (int isad=n+depth; arr[0]>-n; isad+=(isad-n)) { int first = 0; int skip = 0; int unsorted = 0; do { final int t = arr[first]; if (t < 0) { first -= t; skip += t; } else { if (skip != 0) { arr[first+skip] = skip; skip = 0; } final int last = arr[n+t] + 1; if (last - first > 1) { budget.count = 0; this.trIntroSort(n, isad, first, last, budget); if (budget.count != 0) unsorted += budget.count; else skip = first - last; } else if (last - first == 1) skip = -1; first = last; } } while (first < n); if (skip != 0) arr[first+skip] = skip; if (unsorted == 0) break; } }
9
public synchronized int[] makeMove(Scanner stdin, String play) { int r; int c; int[] a = null; Boolean goodInput = false; while(!goodInput) { r = -1; c = -1; System.out.println ("Enter coordinates to play your " + play); if (stdin.hasNextInt()) { // must be integers r = stdin.nextInt(); } if (stdin.hasNextInt()) { c = stdin.nextInt(); } else { stdin.nextLine(); // consume a line without an integer System.out.println("Both inputs must be integers between 0 and 2."); continue; } // must be in the right coordinate range if ((r < 0) || (r > 2) || (c < 0) || (c > 2)) { System.out.println("Both inputs must be integers between 0 and 2."); continue; } // make sure the space is not occupied else if (board[r][c] != null ){ System.out.println("That location is occupied"); continue; } else { board[r][c] = play; a = new int[2]; a[0]=r; a[1]=c; return a; } } return a; }
8
public IsChecked(ExcData excData) { super(excData.getExceptionClass()); isChecked = isCheckedException(exceptionClass); if (isChecked) { rightAnswer = YesAnswer.getInstance(); } else { rightAnswer = NoAnswer.getInstance(); } }
1
@BeforeClass public static void setUpClass() { }
0
@Override public String valueToString(Object value) throws ParseException { double val = ((Double) value).doubleValue(); return mForceSign ? Numbers.formatWithForcedSign(val) : Numbers.format(val); }
1
public <T> T getItem(Class<T> type, ReadCallback<T> callback) { if (getBoolean()) { T item = callback.read(this); if (valid) { return item; } } return null; }
2
@Test public void square_test() { try{ double [][]mat= {{3.0,2.0}, {1.0,3.0}}; double[][]result = Matrix.square(mat); double [][]exp= {{13.0,9.0}, {9.0,10.0}}; Assert.assertArrayEquals(exp, result); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
1
public static Point[] closestk( Point myList[], int k ) { Comparator<Point> cmptor = new Comparator<Point>() { public int compare(Point p1, Point p2) { double x = Math.sqrt(p1.x*p1.x +p1.y*p1.y) - Math.sqrt(p2.x*p2.x +p2.y*p2.y); if (x>0) return -1; else if (x<0) return 1; else return 0; } }; Queue<Point> priorityQueue = new PriorityQueue<Point>(k, cmptor); for (int i = 0; i < myList.length; i++) { if (priorityQueue.size() < k) priorityQueue.add(myList[i]); else { Point peek = priorityQueue.peek(); if ( cmp(myList[i],peek) < 0 ) { priorityQueue.poll(); priorityQueue.add(myList[i]); } } } Point[] result = new Point[k]; while (!priorityQueue.isEmpty()) for (int i = 0; i < k; i++) result[i] = priorityQueue.poll(); return result; };
7
private static Employee getEmployee(Employee bean, PreparedStatement stmt, ResultSet rs) throws SQLException{ stmt.setString(1, bean.getUsername()); rs = stmt.executeQuery(); if (rs.next()) { Employee newBean = new Employee(); newBean.setName(rs.getString("name")); newBean.setUsername(rs.getString("username")); newBean.setPass(rs.getString("pass")); newBean.setDob(rs.getDate("dob")); newBean.setPhone(rs.getString("phone")); newBean.setAddress(rs.getString("address")); newBean.setEmail(rs.getString("email")); newBean.setPosition(rs.getString("position")); return newBean; } else { System.out.println("unable to retrieve Employee info"); return null; } }
1
private void processMoveToAcePile(MouseEvent e) { int index = (int) (e.getY() / (CARD_Y_GAP + CARD_HEIGHT)); if (index < 4) { activeMove.cardReleased(index, CardMoveImpl.MOVE_TYPE_TO.TO_ACE_PILES); String result = activeMove.makeMove(game, this); processMoveResult(result, activeMove); } }
1
public ArrayList<Statement> getStatements(SearchOptions searchOptions) { ArrayList<Statement> result = new ArrayList<Statement>(); CounterParty counterParty = searchOptions.getCounterParty(); String transactionCode = searchOptions.getTransactionCode(); String communication = searchOptions.getCommunication(); boolean searchOnCounterParty = searchOptions.isSearchOnCounterParty(); boolean searchOnTransactionCode = searchOptions.isSearchOnTransactionCode(); boolean searchOnCommunication = searchOptions.isSearchOnCommunication(); for(BusinessObject businessObject : getBusinessObjects()) { Statement statement = (Statement)businessObject; if ((!searchOnTransactionCode || transactionCode.equals(statement.getTransactionCode())) && (!searchOnCommunication || communication.equals(statement.getCommunication())) && (!searchOnCounterParty || counterParty == statement.getCounterParty())) { result.add(statement); } } return result; }
7
@Override public void run() { // loads the file "kdv_node_unload" InputStream pointFile = getClass().getResourceAsStream( "kdv_node_unload.txt"); BufferedReader pointInput = new BufferedReader(new InputStreamReader( pointFile)); String line = null; double x, y; int index = -1; try { if (pointInput.ready()) { // if file is loaded while ((line = pointInput.readLine()) != null) { if (index >= 0) { // does nothing at the first line // creates the point String[] info = line.split(","); x = (Double.parseDouble(info[3]) / Scale); y = (Double.parseDouble(info[4]) / Scale); points[index] = new Point(index + 1, x, y); // sets max and min coordinates if (x < xMin) xMin = x; if (x > xMax) xMax = x; if (y < yMin) yMin = y; if (y > yMax) yMax = y; } index++; } } } catch (IOException e) { Controller.catchException(e); } controller.setxMax(xMax); controller.setxMin(xMin); controller.setyMax(yMax); controller.setyMin(yMin); }
8
public int search(String txt) { int N = txt.length(); if (N < M) return N; long txtHash = hash(txt, M); // check for match at offset 0 if ((patHash == txtHash) && check(txt, 0)) return 0; // check for hash match; if hash match, check for exact match for (int i = M; i < N; i++) { // Remove leading digit, add trailing digit, check for match. txtHash = (txtHash + Q - RM*txt.charAt(i-M) % Q) % Q; txtHash = (txtHash*R + txt.charAt(i)) % Q; // match int offset = i - M + 1; if ((patHash == txtHash) && check(txt, offset)) return offset; } // no match return N; }
6
public int hashCode() { int result; result = (address != null ? address.hashCode() : 0); result = 29 * result + (city != null ? city.hashCode() : 0); result = 29 * result + (country != null ? country.hashCode() : 0); return result; }
3
static int KMP(char[] p, char[] t) { int i = 0, j = 0, m = p.length, n = t.length, len = 0; while (i < n) { while (j >= 0 && t[i] != p[j]) j = b[j]; i++; j++; len = Math.max(len, j); if (j == m) j = b[j]; } return len; }
4
public static void main(String[] args) { HashSet<Integer> hashSet = new HashSet<Integer>(); if (hashSet.add(10)) System.out.println("element 10 added"); if (hashSet.add(20)) System.out.println("element 20 added"); if (hashSet.add(30)) System.out.println("element 30 added"); System.out.println(); System.out.println("the size of set is " + hashSet.size()); System.out.println(); if (hashSet.contains(40)) System.out.println("set contains 40"); else System.out.println("set does not contain 40"); System.out.println(); if (hashSet.remove(20)) System.out.println("element 20 removed"); else System.out.println("element 20 not removed"); System.out.println(); System.out.println("the element of set are"); Iterator<Integer> iterator = hashSet.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + "\t"); } System.out.println(); System.out.println(); Set<Integer> removedSet = new HashSet<Integer>(); removedSet.add(10); removedSet.add(20); System.out.println("the elements after removing"); hashSet.removeAll(removedSet); Iterator<Integer> riterator = hashSet.iterator(); while (riterator.hasNext()) { System.out.print(riterator.next() + "\t"); } System.out.println(); hashSet.clear(); System.out.println("hashSet cleared"); if (hashSet.isEmpty()) System.out.println("hashSet is empty"); else System.out.println("hashSet is not empty"); }
8
public static String getPackageName(Class<?> clazz) { Assert.notNull(clazz, "Class must not be null"); String className = clazz.getName(); int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR); return (lastDotIndex != -1 ? className.substring(0, lastDotIndex) : ""); }
2
@Override public boolean done(ArrayList<Node> nw, int fab){ int a = ((BeaconFAB)nw.get(0).getFAB(fab)).A; Set<Integer> armies = new HashSet<Integer>(); int min = Integer.MAX_VALUE; int d0 = 0; int d1 = 0; int d2 = 0; int d3 = 0; boolean res = true; int sw = 0; for(Node N:nw) { armies.add(((BeaconFAB)N.getFAB(fab)).A); sw = ((BeaconFAB)N.getFAB(fab)).D; min = min < sw ? min : sw; switch(sw) { case 0: d0++; break; case 1: d1++; break; case 2: d2++; break; case 3: d3++; break; default: break; } if(((BeaconFAB)N.getFAB(fab)).A != a) { res = false; } } return res; }
7
private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i - 1) || !cons(i - 2)) { return false; } { final int ch = this.b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') { return false; } } return true; }
7
public void testWithFieldAddWrapped3() { Partial test = createHourMinPartial(); try { test.withFieldAddWrapped(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); }
1
public void run() { Thread.currentThread().setName("ChatSocketServer"); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("ChatServer listening on " + port + "..."); while (listening) { try { Socket socket = serverSocket.accept(); System.out.println("Socket created at " + socket.getPort()); VanillaSocketThread myThread = new ChatSocketThread(socket); (new Thread(myThread)).start(); } catch (Exception e) { System.out .println("Gracefully dealt with error in " /* + getClass().getTypeName() */+ ",Exception" + e.getMessage()); } } }
3
public void recevoir(Information<Boolean> information) { informationRecue = information; if (information.iemeElement(0) instanceof Boolean) { int nbElements = information.nbElements(); boolean[] table = new boolean[nbElements]; for (int i = 0; i < nbElements; i++) { table[i] = information.iemeElement(i); } for (int i = 0; i < fenetre.length - nbElements; i++) { fenetre[i] = fenetre[i + nbElements]; } for (int i = 0; i < nbElements; i++) { fenetre[i + fenetre.length - nbElements] = table[i]; } if (vue == null) vue = new VueCourbe(fenetre, nom); else vue.changer(fenetre); } else System.out.println(nom + " : " + information); }
5
protected void processLineBreakBlocks(List<String> lineBreakBlocks) { if(generateStatistics) { for(String block : lineBreakBlocks) { statistics.setPreservedSize(statistics.getPreservedSize() + block.length()); } } }
2
public void fadeOut() { double volume = 0.6; for (;;) { if (((volume - 0.05) < 0) || !setVolume(volume)) { break; } try { Thread.sleep(150); } catch (Exception exception) { } volume -= 0.025; } if (synthesizer != null) { synthesizer.close(); synthesizer = null; } if (sequencer != null) { if (sequencer.isOpen()) { sequencer.stop(); } sequencer.close(); } }
7
public JLabel getjLabelDateRapport() { return jLabelDateRapport; }
0
@Override public ArrayList getRecordArray() { ArrayList outputArr = new ArrayList(); outputArr.add( this ); int nChart = -1; for( int i = 0; i < chartArr.size(); i++ ) { if( i == 0 ) { Begin b = (Begin) Begin.getPrototype(); outputArr.add( b ); } Object o = chartArr.get( i ); if( o instanceof ChartObject ) { ChartObject co = (ChartObject) o; outputArr.addAll( co.getRecordArray() ); } else { BiffRec b = (BiffRec) o; outputArr.add( b ); // 20070712 KSC: missed some recs! } if( i == (chartArr.size() - 1) ) { End e = (End) End.getPrototype(); outputArr.add( e ); } } return outputArr; }
4
public void compileInsert() { createSelectorLists(); String insert = "INSERT INTO "; if(!compFromList.isEmpty()) { Selector selector = compFromList.get(0); insert += selector.tableField() + " "; } String fields = "("; for(Selector selector : compSelectList) { if(selector.selectField().equals("id")) continue; fields += selector.selectField() + ","; } fields = fields.substring(0, fields.length() - 1); fields += ")"; String values = " VALUES "; for(T object : resultList) { values += "("; for (Selector selector : compSelectList) { if(selector.selectField().equals("id")) continue; try { Method method = klass.getMethod("get"+selector.getFieldName()); method.setAccessible(true); values += selector.getDataConverter().write(method.invoke(object)) + ","; System.out.println(method.invoke(object)); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } values = values.substring(0, values.length() - 1); values += "),"; } values = values.substring(0, values.length() -1); compiledInsertQuery += insert; compiledInsertQuery += fields; compiledInsertQuery += values; isUpdateCompiled = true; }
9
public String toString() { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); StringBuffer buff = new StringBuffer(); buff.append(this.n + " sequences with distance " + this.getAverageDistance()); //buff.append( getConsensus()); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getFractionA()) + " " ); buff.append("\n"); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getFractionC()) + " " ); buff.append("\n"); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getFractionG()) + " " ); buff.append("\n"); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getFractionT()) + " " ); buff.append("\n"); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getFractionGap()) + " " ); buff.append("\n"); for( int x=0; x < columns.size(); x++) buff.append( nf.format(columns.get(x).getDistance()) + " " ); return buff.toString(); }
6
public ClientPlayGameMessage(int version, int typecode, int gameindicator, int gametypecode, int gameplayrequest, long betamount) { /* make sure parameters are valid */ this.iVersion = 0; if (version >= 0) { this.iVersion = version; } this.iTypeCode = 0; if (typecode > 0 && typecode < 4) { this.iTypeCode = typecode; } this.iGameIndicator = 0; if (gameindicator > 0 && gameindicator < 4) { this.iGameIndicator = gameindicator; } this.iGameTypeCode = 0; if (gametypecode == 1) { this.iGameTypeCode = gametypecode; } this.iGamePlayRequest = 0; if (gameplayrequest > 0 && gameplayrequest < 7) { this.iGamePlayRequest = gameplayrequest; } this.lBetAmount = 0; if (betamount >= 0) { this.lBetAmount = betamount; } }
9
public void addPerson(int x, int y) { Piece person = new Person(x, y); if (this.numberOne==null && this.numberTwo==null) { this.numberOne=person; } else if (numberOne!=null && numberTwo==null){ this.numberTwo=person; } }
4
@Id @Column(name = "item_id") public int getItemId() { return itemId; }
0
public int availableCars(String typeOfCar){ int counter = 0; for(int i = 0; i < CARS.size(); i++){ if (typeOfCar.equals(typeOfCar) && carRented == false){ counter++; } else { return 0; } } return counter; }
3
private boolean testPortConditions(Player p){ int gold = 0; for(ItemStack i : p.getInventory()){ if(i != null){ if(i.getType() == Material.GOLD_BLOCK){ gold += i.getAmount(); }else{ if(!AllowedItems.contains(i.getTypeId())){ p.sendMessage(DeityNether.lang.formatInvalidItems()); return false; } } } } if(gold == GOLD_NEEDED) return true; else if(gold > GOLD_NEEDED){ p.sendMessage(DeityNether.lang.formatTooMuchGold()); return false; }else{ p.sendMessage(DeityNether.lang.formatTooLittleGold()); return false; } }
6
@Override public int doStartTag() throws JspException { try { if (price != 0) { JspWriter out = pageContext.getOut(); out.write(PriceDiscountManager.getFinalPrice(price, discount, userDiscount).toString()); return EVAL_BODY_INCLUDE; } } catch (IOException e) { throw new JspException(e.getMessage()); } return SKIP_BODY; }
2
public void setTime(double time, int index){ this.time[index] = time; }
0
private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. int targetWidth = target.getSize().width; if (targetWidth == 0) targetWidth = Integer.MAX_VALUE; int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) rowWidth += hgap; rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); if (scrollPane != null && target.isValid()) dim.width -= (hgap + 1); return dim; } }
8
@Override public void onEnable() { log.info(String.format("[%s] - Initializing...", getDescription().getName())); log.info(String.format("[%s] - Checking for Vault...", getDescription().getName())); // Set up Vault if(!setupPermissions()) { log.info(String.format("[%s] - Could not find Vault dependency, disabling.", getDescription().getName())); this.getPluginLoader().disablePlugin(this); return; } //Check for CommandBook... Our Mutes clash big time. Plugin plugCB = getServer().getPluginManager().getPlugin("CommandBook"); if(plugCB!=null) { log.info(String.format("[%s] - WARNING!!!! You need to disable CommandBook messaging or Mutes will error everytime.", getDescription().getName())); } log.info(String.format("[%s] - Checking for SimpleClans...", getDescription().getName())); Plugin plug = getServer().getPluginManager().getPlugin("SimpleClans2"); // Set up simpleclans if(plug==null) { log.info(String.format("[%s] - Could not find Simpleclans dependency, disabling.", getDescription().getName())); } else { simplelclans=true; sc = ((SimpleClans) plug); } setupChat(); // Log completion of initialization getLogger().info(String.format("[%s] - Enabled with version %s", getDescription().getName(), getDescription().getVersion())); // Get config and handle // Configuration try { fc= getConfig(); //saveConfig(); if(fc.getList("channels") == null) { getConfig().options().copyDefaults(true); saveDefaultConfig(); reloadConfig(); } } catch (Exception ex) { getLogger().log(Level.SEVERE, "[MumbleChat] Could not load configuration!", ex); } log.info(String.format("[%s] - Registering Listeners", getDescription().getName())); // Channel information reference ccInfo = new ChatChannelInfo(this); if(ccInfo == null) log.info(String.format("[%s] - Configuration is BAD!", getDescription().getName())); if(simplelclans) { // super.getServer().getPluginManager().registerEvents(new SimpleClansListener(this, ccInfo), this); //super.getServer().getPluginManager().registerEvents(new SimpleClansListener(this, ccInfo), this); } chatListener = new ChatListener(this, ccInfo); PluginManager pluginManager = getServer().getPluginManager(); pluginManager.registerEvents(chatListener, this); loginListener = new LoginListener(this, ccInfo); pluginManager.registerEvents(loginListener, this); //Future enhancement testing... //mp = new MumblePermissions(this,cci); //mp.PermissionsExAvailable(); chatExecutor = new ChatCommand(this, ccInfo); pluginManager.registerEvents(chatExecutor, this); log.info(String.format("[%s] - Attaching to Executors", getDescription().getName())); muteExecutor = new MuteCommandExecutor(this, ccInfo); tellExecutor = new TellCommandExecutor(this, ccInfo); getCommand("tell").setExecutor(tellExecutor); getCommand("ignore").setExecutor(tellExecutor); getCommand("whisper").setExecutor(tellExecutor); getCommand("channel").setExecutor(chatExecutor); getCommand("leave").setExecutor(chatExecutor); getCommand("join").setExecutor(chatExecutor); getCommand("chlist").setExecutor(chatExecutor); getCommand("chwho").setExecutor(chatExecutor); getCommand("mute").setExecutor(muteExecutor); getCommand("unmute").setExecutor(muteExecutor); }
7
@Override public void display(UserInterface ui) { if (breakpoints.isEmpty()) { UserInterface.println("There are no breakpoints currently set.\n"); } else { UserInterface.print("Breakpoints are currently set on lines: "); for (String breakpoint : breakpoints) { UserInterface.print(breakpoint + " "); } UserInterface.println("\n"); } }
2
public static void main (String args[]) { java.awt.EventQueue.invokeLater (new Runnable () { public void run () { new LoginWindow (1500).setVisible (true); } } ); }
0
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { Vector<String> origCmds=new XVector<String>(commands); if(commands.size()<2) { CMLib.commands().doCommandFail(mob,origCmds,L("Hold what?")); return false; } commands.remove(0); final List<Item> items=CMLib.english().fetchItemList(mob,mob,null,commands,Wearable.FILTER_UNWORNONLY,false); if(items.size()==0) CMLib.commands().doCommandFail(mob,origCmds,L("You don't seem to be carrying that.")); else for(int i=0;i<items.size();i++) if((items.size()==1)||(items.get(i).canWear(mob,Wearable.WORN_HELD))) { final Item item=items.get(i); int msgType=CMMsg.MSG_HOLD; String str=L("<S-NAME> hold(s) <T-NAME>."); if((mob.freeWearPositions(Wearable.WORN_WIELD,(short)0,(short)0)>0) &&((item.rawProperLocationBitmap()==Wearable.WORN_WIELD) ||(item.rawProperLocationBitmap()==(Wearable.WORN_HELD|Wearable.WORN_WIELD)))) { str=L("<S-NAME> wield(s) <T-NAME>."); msgType=CMMsg.MSG_WIELD; } final CMMsg newMsg=CMClass.getMsg(mob,item,null,msgType,str); if(mob.location().okMessage(mob,newMsg)) mob.location().send(mob,newMsg); } return false; }
9
public void generateString(ArrayList<String> result, String pic, int left, int right){ if (right <left){ return; } if (left==0&&right == 0){ result.add(pic); return; } if(left <0){ return; } if(left ==0){ generateString(result,pic+")",left,right-1); return; } generateString(result,pic+"(",left-1,right); generateString(result,pic+")",left,right-1); }
5
public String getDescription(int skill) { return skillDescriptions[skill]; }
0
private void saveProgress() { if(modified && fileName != null) { if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(frame ,new JLabel("Save progress with " + fileName + " ?") ,"Unsaved Progress" ,JOptionPane.YES_NO_OPTION )) { saveToFile(fileName); } } }
3
public boolean _setSpriteImage(URL spriteURL) { if(image != null) { this.setIcon(new ImageIcon(spriteURL)); return true; } else { return false; } }
1
@Override public boolean consider(Comparable object, int index) { if (index==0) { maximum = object; } if (index<cutOff) { if (maximum.compareTo(object)<0) { maximum = object; } } if (index>=cutOff) { if (maximum.compareTo(object)<=0) return true; } return false; }
5
@Override public boolean ausfuehren(ServerKontext kontext, Spieler spieler, Befehlszeile befehlszeile) { //TODO auslagern in Methoden String richtung = extrahiereRichtung(befehlszeile); Raum nebenRaum = getRaumFuerRichtung(kontext, spieler, richtung); kontext.schreibeAnSpieler(spieler, "Dr.Little schaut nach " + richtung + "en."); kontext.schreibeAnSpieler(spieler, "Er sieht: " + nebenRaum.getName()); Stack<Item> raumItems = nebenRaum.getItems(); kontext.schreibeAnSpieler(spieler, "Zu sehen " + (raumItems.size() == 1 ? "ist" : "sind") + ":"); int anzahlKruemel = 0; boolean gegengift = false; boolean hatDinge = false; for(Item item : raumItems) { if(item.isAnyKuchen()) { anzahlKruemel++; } else if(item == Item.Gegengift) { gegengift = true; } } if(gegengift) { kontext.schreibeAnSpieler(spieler, "Das Gegengift!"); hatDinge = true; } if(anzahlKruemel != 0) { kontext.schreibeAnSpieler(spieler, anzahlKruemel + " Krümel"); hatDinge = true; } if(nebenRaum.hasMaus()) { kontext.schreibeAnSpieler(spieler, "Eine Maus"); hatDinge = true; } if(nebenRaum.hasKatze()) { kontext.schreibeAnSpieler(spieler, "Eine Katze"); hatDinge = true; } if(!hatDinge) { kontext.schreibeAnSpieler(spieler, "nur uninteressante Sachen"); } return true; }
9
protected final MapleData getItemData(final int itemId) { MapleData ret = null; final String idStr = "0" + String.valueOf(itemId); MapleDataDirectoryEntry root = itemData.getRoot(); for (final MapleDataDirectoryEntry topDir : root.getSubdirectories()) { // we should have .img files here beginning with the first 4 IID for (final MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr.substring(0, 4) + ".img")) { ret = itemData.getData(topDir.getName() + "/" + iFile.getName()); if (ret == null) { return null; } ret = ret.getChildByPath(idStr); return ret; } else if (iFile.getName().equals(idStr.substring(1) + ".img")) { return itemData.getData(topDir.getName() + "/" + iFile.getName()); } } } root = equipData.getRoot(); for (final MapleDataDirectoryEntry topDir : root.getSubdirectories()) { for (final MapleDataFileEntry iFile : topDir.getFiles()) { if (iFile.getName().equals(idStr + ".img")) { return equipData.getData(topDir.getName() + "/" + iFile.getName()); } } } return ret; }
8
private boolean createFileChannel(){ File requestedFile = new File(this.filePath); if(requestedFile != null && requestedFile.exists()){ try { // 直接通过文件管道将文件内容输出到客户端 this.fileInput = new FileInputStream(requestedFile); this.fileChannel = fileInput.getChannel(); } catch (IOException e) { e.printStackTrace(); this.closeChannel(); } return true; } return false; }
3
public double [][] envCumProb() throws FileNotFoundException{ envCumProb = new double [envName.size()] [envName.size()]; try { FileReader file = new FileReader("EnvCumProb.txt"); BufferedReader br = new BufferedReader (file); StreamTokenizer tokens = new StreamTokenizer (br); for (int row=0; row<envCumProb.length; row++) { for(int column=0; column<envCumProb[row].length; column++){ if (tokens.nextToken()!= StreamTokenizer.TT_EOF){ switch(tokens.ttype) { case StreamTokenizer.TT_NUMBER: envCumProb[row][column]=tokens.nval; break; default: break; } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // recalculate cum prob values according to timeStep value double timeStep = SimTimer.getCurrentTimeStep(); if(timeStep<1){ for (int r=0; r<envCumProb.length; r++){ for (int c=0; c<envCumProb.length; c++){ envCumProb[r][c]=envCumProb[r][c]*(1/timeStep); } } } //else... think how to use a timestep above 1h...and having probabilities hogher than 1... return envCumProb; }
9
private void validateConfiguration() throws MojoExecutionException { // Validate aliases. for (final Map.Entry<String, String> alias : aliases.entrySet()) { if (StringUtils.isBlank(alias.getValue())) { throw new MojoExecutionException("Illegal alias found. Alias is not allowed to by empty"); } } // Validate sources. if (sourceDirectories.isEmpty()) { if (!defaultSourceDirectory.isDirectory()) { throw new MojoExecutionException(MessageFormat.format( "Illegal default source directory found. Source '{0}' is not a valid directory", defaultSourceDirectory)); } } else { for (final File sourceDirectory : sourceDirectories) { if (!sourceDirectory.isDirectory()) { throw new MojoExecutionException(MessageFormat.format( "Illegal source found. Source {0} is not a valid directory", sourceDirectory)); } } } // Validate includes. for (final String include : includes) { if (StringUtils.isBlank(include)) { throw new MojoExecutionException("Illegal include found. Include is not allowed to be empty"); } } // Validate rootClassName. if (StringUtils.isBlank(fullyQualifiedGeneratedRootClassName)) { throw new MojoExecutionException("Illegal rootClassName found. Root class name is not allowed to be empty"); } }
9
public static boolean transferFont( File inDir, File inFile, File outDir, FontTester tester ) { if( inDir == null ) { inDir = inFile.getParentFile(); } String relPath = getRelativePath( inDir, inFile.getParentFile(), true ); outDir = new File( outDir, relPath ); FileGarbage kill = new FileGarbage(); kill.addFile( outDir, false ); try { for( File file : FontUnpacker.unpack( inFile, kill ) ) { FontFormat format = FontFormat.forFile( file ); if( format == FontFormat.NONE ) { continue; } File newFile = new File( outDir, file.getName() ); if( newFile.exists() ) { continue; } try { System.out.println( file.getPath() ); Font font = Font.createFont( format.awtType(), file ); if( tester != null ) { tester.testFont( font ); } if( !outDir.exists() ) { outDir.mkdirs(); } NativeFiles.copy( file, newFile ); kill.remove( outDir ); } catch( Exception ex ) { } } } catch( Exception exc ) { kill.empty(); } return true; }
8
@Override public void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HandlerUtil.HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = start / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { HandlerUtil.sendNotModified(ctx); return; } } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseStr.getBytes())); HandlerUtil.setDateAndCacheHeaders(response, start); response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
3
@Override public void focusGained(FocusEvent e) { textArea = (OutlinerCellRendererImpl) e.getComponent(); textArea.hasFocus = true; }
0
public Object get(int index) { return index < 0 || index >= size() ? null : mList.get(index); }
2
public void testBinaryCycAccess6() { System.out.println("\n**** testBinaryCycAccess 6 ****"); CycAccess cycAccess = null; try { try { if (connectionMode == LOCAL_CYC_CONNECTION) { cycAccess = new CycAccess(testHostName, testBasePort); } else if (connectionMode == SOAP_CYC_CONNECTION) { cycAccess = new CycAccess(endpointURL, testHostName, testBasePort); } else { fail("Invalid connection mode " + connectionMode); } } catch (Throwable e) { fail(e.toString()); } //cycAccess.traceOnDetailed(); doTestCycAccess6(cycAccess); } finally { if (cycAccess != null) { cycAccess.close(); cycAccess = null; } } System.out.println("**** testBinaryCycAccess 6 OK ****"); }
4
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int opcao; Menu m = new Menu(); try{ m.Menu(); InfoFuncionario info = new InfoFuncionario(); System.out.println("Digite Sua Opcao :"); opcao = sc.nextInt(); do { if(opcao == 1){ info.CadastrarFuncionario(); }if(opcao == 2){ info.ListarFuncionario(); }if (opcao == 3){ System.out.println("Digite o nome a ser removido :"); String nome = sc.next(); info.ExcluirFuncionario(nome); }if (opcao == 4){ info.AlterarFuncionario(); } if(opcao == 0){ break; } m.Menu(); System.out.println("Digite outra opcao"); sc.nextInt(); } while (opcao != 0); } catch (InputMismatchException e) { System.out.println("Opcao Invalida, Digite outra"); sc.nextInt(); } catch (NumberFormatException e1){ System.out.println("CPF Invalido"); sc.next(); } }
8
public void insert(Halfedge halfEdge) { Halfedge previous, next; int insertionBucket = bucket(halfEdge); if (insertionBucket < _minBucket) { _minBucket = insertionBucket; } previous = _hash.get(insertionBucket); while ((next = previous.nextInPriorityQueue) != null && (halfEdge.ystar > next.ystar || (halfEdge.ystar == next.ystar && halfEdge.vertex.get_x() > next.vertex.get_x()))) { previous = next; } halfEdge.nextInPriorityQueue = previous.nextInPriorityQueue; previous.nextInPriorityQueue = halfEdge; ++_count; }
5
@Override public boolean execute(SimpleTowns plugin, CommandSender sender, String commandLabel, String[] args) { final Localisation localisation = plugin.getLocalisation(); if (args.length == 0) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_SPECIFY_STATUS)); return false; } final boolean current = LogUtils.isEnabled(plugin); final Boolean status = new BooleanParser(args[0]).parse(current); if (status == null) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_SPECIFY_STATUS)); return false; } final Logger logger = new Logger(plugin); if (current && !status) { // If logging was enabled, and it's being disabled logger.log(localisation.get(LocalisationEntry.LOG_LOGGING_DISABLED, sender.getName())); } LogUtils.setEnabled(sender, status, plugin); if (!current && status) { // If logging was disabled, and it's been enabled logger.log(localisation.get(LocalisationEntry.LOG_LOGGING_ENABLED, sender.getName())); } sender.sendMessage(localisation.get(LocalisationEntry.MSG_LOG_STATUS_SET, LogUtils.isEnabled(plugin))); return true; }
6
public String getType() { return type; }
0
void sort_duan(double[][] x, double[] y) { Vector<Integer> indices = new Vector<Integer>(); for (int i = 0; i < x.length; i++) { indices.add(new Integer(i)); } if (!stepData.maximizeObjectiveFunctionValue()) { Sorter sorter = new Sorter(y, Sorter.ASCENDING); Collections.sort(indices, sorter); Arrays.sort(y); } else { Sorter sorter = new Sorter(y, Sorter.DESCENDING); Collections.sort(indices, sorter); // sort y[] in ascending order Arrays.sort(y); // reverse the order of y to be in descending order double[] new_y = new double[y.length]; for (int i = 0; i < y.length; i++) { new_y[i] = y[y.length - 1 - i]; } for (int i = 0; i < y.length; i++) { y[i] = new_y[i]; } } double[][] new_x = new double[x.length][x[0].length]; for (int i = 0; i < new_x.length; i++) { new_x[i] = x[indices.get(i).intValue()]; } for (int i = 0; i < x.length; i++) { x[i] = new_x[i]; } }
6
public void checaProyectilChocaConMuros(){ // checa si proyectil colisiona con las paredes // de la derecha y la izquierda... if (proBola.getX() < 0){ proyectilChocaIzquierda(); } else if(proBola.getX() + proBola.getAncho() > getWidth()){ proyectilChocaDerecha(); } // checa si el proyectil choca con el techo... if (proBola.getY() < 0){ proyectilChocaArriba(); } // si choca por debajo, que se disminuyan vidas y se reposiciona // se baja tambien el intervalo de tiempo para ue ladrillos bajen else if (proBola.getY() + proBola.getAlto() > getHeight()){ reposicionaProyectil(); iVidas--; iIntervalo -= 40; } }
4
@Override public void reactPressed(MouseEvent event) { if (isPressed) { isPressed = false; releaseImage(); StateMachine.resetMutePressed(); } else { if (mt.isPressed()) mt.reactPressed(null); isPressed = true; pressImage(); StateMachine.setMutePressed(); } }
2
public void addVoiture(Vehicule voiture) { this.voitures.add(voiture); try { oos = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream( new File("voitures.txt")))); for(int i = 0; i < this.voitures.size(); i++) { oos.writeObject(this.voitures.get(i)); } oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
3
private void processCommands() { // tratador das opções da linha de comando getOpt = new Getopt("prover", argv, ":nsltho:"); getOpt.setOpterr(false); int c; // verifica as opções while ((c = getOpt.getopt()) != -1) { switch(c) { case 's': compiler.setDebugSyn(true); break; case 'l': compiler.setDebugLex(true); break; case 't': showSymTable = true; break; case 'n': compiler.setDoSyntactic(false); break; case 'o': dotFile = getOpt.getOptarg(); break; case 'h': System.out.println("ProofApp"); System.out.println(""); System.out.println("USO: ProofApp [opcoes] [arquivos com a formula]"); System.out.println(""); System.out.println("Opções da linha de comando:"); System.out.println(" -s = Debug da analise sintática"); System.out.println(" -l = Debug da analise léxica"); System.out.println(" -t = Mostra a tabela de símbolos"); System.out.println(" -n = Nao realiza a analise sintática, apenas a léxica"); System.out.println(" -o = Arquivo de saída do grafo da solução"); System.out.println(" -h = Help"); System.exit(0); break; case ':': System.err.println("Argumento ausente na opcao '" + (char)getOpt.getOptopt()+"'."); break; case '?': System.err.println("Opcao '" + (char)getOpt.getOptopt() + "' invalida ignorada."); break; default: System.err.println("Erro na opcao = '" + c + "'."); break; } } // opções default (listagem de nomes de arquivos) defaultOptionsIndex = getOpt.getOptind(); }
9
public static double[] doLinearRegressionFromTo(int start,int end,double[][] args) //input int start, int end { //input double[1]=array of prices double[] answer = new double[3]; int n = 0; int numDays=end-start; double[] x = new double[numDays]; double[] y = new double[numDays]; for(int i=0;i<numDays;i++){x[i]=args[0][i+start];} for(int i=0;i<numDays;i++){y[i]=args[1][i+start];} double sumx = 0.0, sumy = 0.0; for(int i=0;i<x.length;i++) { sumx += x[i]; sumy += y[i]; n++; } double xbar = sumx / n; double ybar = sumy / n; double xxbar = 0.0, yybar = 0.0, xybar = 0.0; for (int i = 0; i < n; i++) { xxbar += (x[i] - xbar) * (x[i] - xbar); yybar += (y[i] - ybar) * (y[i] - ybar); xybar += (x[i] - xbar) * (y[i] - ybar); } double beta1 = xybar / xxbar; double beta0 = ybar - beta1 * xbar; double ssr = 0.0; for (int i = 0; i < n; i++) { double fit = beta1*x[i] + beta0; ssr += (fit - ybar) * (fit - ybar); } double R2 = ssr / yybar; answer[0]=beta1; //returns m(gradient) answer[1]=beta0; //returns c(y-intercept) answer[2]=R2; //returns R-squared return answer; }
5
public Pedestrian(int x, int y, int walktype) { this.walktype = walktype; i = 0; minus = 1; switch (walktype) { case GO_LEFT: speedX = DEFAULT_SPEED_LEFT; speedY = 0; break; case GO_RIGHT: speedX = DEFAULT_SPEED_RIGHT; speedY = 0; break; case GO_UP: speedX = 0; speedY = DEFAULT_SPEED_UP; break; case GO_DOWN: speedX = 0; speedY = DEFAULT_SPEED_DOWN; break; } rect = new Rectangle(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT); time = 0; waitToCross = false; crossed = false; crossing = false; finish = false; }
4
public static void setDistance(Red r1, Red r2, int d) { int N = r1.getSize(); int M = N; int s1, s2, i, n; int[] st = new int[N]; int[] rst = new int[d]; for (n = 0; n < N; ++n) { st[n] = n; s1 = r1.getNodo(n).getS(); r2.getNodo(n).setS(s1); } --M; for (n = 0; n < d; ++n) { i = (int) (M * Math.random()); rst[n] = st[i]; st[i] = st[M - 1]; --M; } for (n = 0; n < d; ++n) { i = rst[n]; s1 = r1.getNodo(i).getS(); if (r1.getNodo(i).isBinary()) { s2 = 1 - s1; } else { if (s1 == 0) { s2 = (Math.random() < 0.5) ? 1 : 2; } else { if (s1 == 1) { s2 = (Math.random() < 0.5) ? 0 : 2; } else { s2 = (Math.random() < 0.5) ? 0 : 1; } } } r2.getNodo(i).setS(s2); } }
9
public static void printRuleInGoalTree(ControlFrame frame, Proposition impliesprop, int depth) { { PatternRecord patternrecord = frame.patternRecord; boolean reversepolarityP = frame.reversePolarityP; System.out.print("RULE: "); { Surrogate rulename = ((Surrogate)(KeyValueList.dynamicSlotValue(impliesprop.dynamicSlots, Logic.SYM_STELLA_SURROGATE_VALUE_INVERSE, null))); if ((rulename == null) && (((Proposition)(KeyValueList.dynamicSlotValue(impliesprop.dynamicSlots, Logic.SYM_LOGIC_MASTER_PROPOSITION, null))) != null)) { rulename = ((Surrogate)(KeyValueList.dynamicSlotValue(((Proposition)(KeyValueList.dynamicSlotValue(impliesprop.dynamicSlots, Logic.SYM_LOGIC_MASTER_PROPOSITION, null))).dynamicSlots, Logic.SYM_STELLA_SURROGATE_VALUE_INVERSE, null))); } if (rulename != null) { System.out.println(rulename.symbolName); Logic.printIndent(Stella.STANDARD_OUTPUT, (2 * depth) + 6); } } { Object old$Printmode$000 = Logic.$PRINTMODE$.get(); Object old$Printlogicalformstream$000 = Logic.$PRINTLOGICALFORMSTREAM$.get(); Object old$Indentcounter$000 = Logic.$INDENTCOUNTER$.get(); Object old$Queryiterator$000 = Logic.$QUERYITERATOR$.get(); try { Native.setSpecial(Logic.$PRINTMODE$, Logic.KWD_FLAT); Native.setSpecial(Logic.$PRINTLOGICALFORMSTREAM$, Stella.STANDARD_OUTPUT); Native.setIntSpecial(Logic.$INDENTCOUNTER$, (2 * depth) + 7); Native.setSpecial(Logic.$QUERYITERATOR$, null); { Description chooseValue000 = null; if (reversepolarityP) { { Description temp000 = patternrecord.optimalPattern; chooseValue000 = ((temp000 != null) ? temp000 : patternrecord.description); } } else { chooseValue000 = ((Description)((impliesprop.arguments.theArray)[1])); } { Description chooseValue001 = null; if (reversepolarityP) { chooseValue001 = ((Description)((impliesprop.arguments.theArray)[0])); } else { { Description temp001 = patternrecord.optimalPattern; chooseValue001 = ((temp001 != null) ? temp001 : patternrecord.description); } } Description.printDescriptionsAsKifRule(chooseValue000, chooseValue001, impliesprop, reversepolarityP); } } } finally { Logic.$QUERYITERATOR$.set(old$Queryiterator$000); Logic.$INDENTCOUNTER$.set(old$Indentcounter$000); Logic.$PRINTLOGICALFORMSTREAM$.set(old$Printlogicalformstream$000); Logic.$PRINTMODE$.set(old$Printmode$000); } } } }
7
public void visit_monitorenter(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
public void setEnd(Date end) { this.end = end; }
0
public boolean renderBlockTorch(Block block, int i, int j, int k) { int l = this.blockAccess.getBlockMetadata(i, j, k); Tessellator tessellator = Tessellator.instance; float f = block.getBlockBrightness(this.blockAccess, i, j, k); if (Block.lightValue[block.blockID] > 0) { f = 1.0F; } tessellator.setColorOpaque_F(f, f, f); double d = 0.4000000059604645D; double d1 = 0.5D - d; double d2 = 0.20000000298023224D; if (l == 1) { this.renderTorchAtAngle(block, (double) i - d1, (double) j + d2, (double) k, -d, 0.0D); } else if (l == 2) { this.renderTorchAtAngle(block, (double) i + d1, (double) j + d2, (double) k, d, 0.0D); } else if (l == 3) { this.renderTorchAtAngle(block, (double) i, (double) j + d2, (double) k - d1, 0.0D, -d); } else if (l == 4) { this.renderTorchAtAngle(block, (double) i, (double) j + d2, (double) k + d1, 0.0D, d); } else { this.renderTorchAtAngle(block, (double) i, (double) j, (double) k, 0.0D, 0.0D); } return true; }
5
protected final void useItemOnPlayersPosition(Player player) throws InvalidActionException { if (player == null) throw new IllegalArgumentException("The given player is invalid!"); if (!(this instanceof Useable)) throw new InvalidActionException("The selected item can't be used!"); if (player.getRemainingActions() <= 0) throw new InvalidActionException("The player has no turns left!"); if (!player.getInventory().getItems().contains(this)) throw new InvalidActionException("The player doesn't have the item in his inventory!"); getGrid().addElementToPosition(this, getGrid().getElementPosition(player)); player.getInventory().remove(this); player.decrementAction(); }
4
public static void update(){ for(int i=0;i<4;i++){ if(i==0) prev[KeyEvent.VK_LEFT]=pressed[KeyEvent.VK_LEFT]; if(i==1) prev[KeyEvent.VK_RIGHT]=pressed[KeyEvent.VK_RIGHT]; if(i==2) prev[KeyEvent.VK_DOWN]=pressed[KeyEvent.VK_DOWN]; if(i==3) prev[KeyEvent.VK_UP]=pressed[KeyEvent.VK_UP]; } }
5
public static void main(String[] args) { try { logger.info("Starting the data provider."); String path = "C:\\DataCommons\\Data"; String domain = "idd:boom.org:boomid"; String contributorName = "BOOM"; int port = 9091; logger.info("Provider data path: " + path); logger.info("Provider domain: " + domain); logger.info("Provider contributor name: " + contributorName); Contributor cont = new Contributor(contributorName, domain); SubjectCollection coll = new SubjectCollection(cont, path, port); coll.start(); int val = 0; do { System.out.print("To quit type (q): "); val = System.in.read(); } while(val != 'q'); coll.stop(); } catch(Exception e) { logger.error("Top level error occured.", e); System.err.println("Error: " + e.getMessage()); } finally { logger.info("Exiting the data provider."); } }
2
public int findNumberByInnovNumber(int linkInnovNum) { int number = -1; for (int i = 0; i < this.getNumberGenes(); i++) { if (genes.get(i).getInnovation_num() == linkInnovNum) { number = i; } } return number; }
2
public static void main(String[] args) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); UIManager.put("Table.background", Color.WHITE); UIManager.put("Table.alternateRowColor", Color.WHITE); break; } } } catch (Exception e) { // if Nimbus is not available try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } } Locale.setDefault(Locale.ENGLISH); //waiting time for splash try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } ToDoList app = new ToDoList(); app.start(); }
8