text
stringlengths
14
410k
label
int32
0
9
public synchronized boolean removeItem(FieldItem item, Position position){ if ((position.getX() <= this.getXLength()) || (position.getY() <= this.getYLength())) return false; if (field[position.getX()][position.getY()] == item) { field[position.getX()][position.getY()] = null; return true; } return false; }
3
private static int[] gcd( int numerator, int denominator ) { int highest; int n = 1; int d = 1; if( denominator > numerator ) { highest = denominator; } else { highest = numerator; } for( int x = highest; x > 0; x-- ) { if( ((denominator % x) == 0) && ((numerator % x) == 0) ) { n = numerator / x; d = denominator / x; break; } } return new int[]{ n, d }; }
4
private static void verifyAntBuildFile(File currentFolder, PackDetails packDetails) throws ParserConfigurationException, SAXException, IOException { File antFile = new File(currentFolder, "build.xml"); System.out.println("Verifying ANT build file for validity..."); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(antFile, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if (qName.equals("project")) { if (attributes.getValue("name").equals("LanguagePack")) { throw new InvalidPackConfiguration("build.xml", "The name of the ant should be changed"); } } } }); }
2
public void compileStmnt(String src) throws CompileError { Parser p = new Parser(new Lex(src)); SymbolTable stb = new SymbolTable(stable); while (p.hasMore()) { Stmnt s = p.parseStatement(stb); if (s != null) s.accept(gen); } }
2
@Override public void run() { Client client = new Client(socket); try { InputStream in = socket.getInputStream(); byte type = (byte) in.read(); if (type == 0x00) { while (true) { byte[] buffer = Protocol.decode(in); System.err.println(new String(buffer)); String decoded; if(Server.get().getHuffman()) { decoded = Huffman.getDecoder().decode(buffer); } else { decoded = new String(buffer); } read(client, decoded); } } else if (type == 0x02) { // registration } } catch (IOException e) { /* Do Nothing */ } finally { client.disconnect(); } }
5
private static boolean isDigit(char arg0) { return arg0 >= '0' && arg0 <= '9'; }
1
public boolean Has3Items(int itemID, int amount, int itemID2, int amount2, int itemID3, int amount3){ if(HasItemAmount(itemID, amount)){ if(HasItemAmount(itemID2, amount2)){ if(HasItemAmount(itemID3, amount3)){ return true; } else{ return false; } } else{ return false; } } else{ return false; } }
3
public boolean checkStates() throws BadLocationException { dialog.addMessageToLogger("Checking states for assignment resources to the states", 1); boolean[] assignedStates = new boolean[pn.getStates().size()]; for (State state : pn.getStates()) { int i = pn.getStates().indexOf(state); assignedStates[i] = false; int sumOfAssigned = 0; state.toString(); for (Resource r : state.getPn().getListOfResources()) { for (int j = 0; j < r.getProcess().length; j++) { sumOfAssigned += r.getProcess()[j]; } } if (sumOfAssigned > 0) { assignedStates[i] = true; } } ArrayList<Integer> listOfUnassigned = new ArrayList<Integer>(); for (int i = 0; i < assignedStates.length; i++) { if (!assignedStates[i]) { listOfUnassigned.add(i); } } //System.out.println("SUM OF ALL STATES:" + assignedStates.length); //System.out.println("SUM OF ASSIGNED STATES:" + (assignedStates.length - listOfUnassigned.size())); State newS = new State(pn.getState(), 0, null, pn); //System.out.println(newS.getKey().equals(pn.getStates().get(1).getKey())); //System.out.println(newS.getKey()==pn.getStates().get(1).getKey()); if (listOfUnassigned.size() == 1 && newS.getKey().equals(pn.getStates().get(listOfUnassigned.get(0)).getKey())) { setAssignedResourcesToStates(true); dialog.addMessageToLogger("Valid assignment of resource to the states", 1); return true; } else { setAssignedResourcesToStates(false); dialog.addMessageToLogger("Invalid assignment of resource to the states", 3); return false; } }
8
static int[] getLocalIP() { try { InetAddress addr = InetAddress.getLocalHost(); byte[] ip = addr.getAddress(); if( ip == null || ip.length != 4 ) { return null; } int[] ret = new int[4]; for( int cnt = 0;cnt<4;cnt++) { ret[cnt] = (int)ip[cnt]; if( ret[cnt] < 0 ) { ret[cnt] += 256; } } return ret; } catch (UnknownHostException uhe ) { return null; } }
5
public String readLine(ByteBuffer buffer) throws LineTooLargeException { byte b; boolean more = true; while (buffer.hasRemaining() && more) { b = buffer.get(); if (b == CR) { if (buffer.hasRemaining() && buffer.get() == LF) { more = false; } } else if (b == LF) { more = false; } else { if (lineBufferIdx == maxLine - 2) { throw new LineTooLargeException("exceed max line " + maxLine); } if (lineBufferIdx == lineBuffer.length) { lineBuffer = Arrays.copyOf(lineBuffer, lineBuffer.length * 2); } lineBuffer[lineBufferIdx] = b; ++lineBufferIdx; } } String line = null; if (!more) { line = new String(lineBuffer, 0, lineBufferIdx); lineBufferIdx = 0; } return line; }
9
public final Iterator<Path> filesIterator() { return new Iterator<Path>() { private DirTree currentTree = walkTo(DirTree.this.base); private Iterator<String> dirIter = this.currentTree.directories .keySet().iterator(); private Iterator<String> fileIter = this.currentTree.files.keySet() .iterator(); private final ArrayDeque<Iterator<String>> dirIterStack = new ArrayDeque<>(); private final ArrayDeque<Iterator<String>> fileIterStack = new ArrayDeque<>(); @Override public boolean hasNext() { while (true) { if (this.fileIter.hasNext()) { return true; } if (this.dirIter.hasNext()) { final String nextDir = this.dirIter.next(); if (this.currentTree.directories.get(nextDir) != null) { this.dirIterStack.add(this.dirIter); this.fileIterStack.add(this.fileIter); this.currentTree = this.currentTree.directories .get(nextDir); this.dirIter = this.currentTree.directories .keySet().iterator(); this.fileIter = this.currentTree.files.keySet() .iterator(); } continue; } if (this.dirIterStack.isEmpty()) { return false; } // pop this.currentTree = this.currentTree.parent; this.fileIter = this.fileIterStack.removeLast(); this.dirIter = this.dirIterStack.removeLast(); } } @Override public Path next() { final String next = this.fileIter.next(); return this.currentTree.buildPath().resolve(next); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
5
public void setB(float b) { this.b = b; }
0
public Collection<DepartamentoDTO> buscarTodos(){ Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; try { con = UConnection.getConnection(); String sql = "SELECT * FROM departamento LIMIT 10"; pstm = con.prepareStatement(sql); rs = pstm.executeQuery(); Vector<DepartamentoDTO> ret = new Vector<DepartamentoDTO>(); DepartamentoDTO dto = null; while( rs.next() ){ dto = new DepartamentoDTO(); dto.setDeptno(rs.getInt("deptno")); dto.setDname(rs.getString("dname")); dto.setLoc(rs.getString("loc")); ret.add(dto); } return ret; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { try { if ( rs != null) rs.close(); if (pstm != null) pstm.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } }
5
public boolean benutzerSchonVorhanden(String neuerBenutzername) { Benutzer benutzer = dbZugriff.getBenutzervonBenutzername(neuerBenutzername); if (benutzer != null){ return true; } return false; }
1
@Override public void execute(String[] input) { if (input.length < 2) { laura.print("You need to give me a word to define."); return; } StringBuilder sb = new StringBuilder(); for (int i=1; i<input.length; i++) { sb.append(input[i]); } String query = sb.toString(); WordApi api = new WordApi(); api.getInvoker().addDefaultHeader("api_key", API_KEY); try { List<Definition> definitions = api.getDefinitions( query, null, //partOfSpeech, null, //sourceDictionaries, 3, //limit, "false", //includeRelated, "false", //useCanonical, "false" //includeTags ); for (Definition def: definitions) { laura.print(query + ": (" + def.getPartOfSpeech() + ")"); laura.print(def.getText()); } } catch (ApiException e) { laura.print("Sorry, but I could not contact the definition server."); e.printStackTrace(); } }
4
public static void main(String[] args) { String fileName = null; ClassReader classReader = null; try { /* Filename should be the first command line argument */ fileName = args[0]; } catch(ArrayIndexOutOfBoundsException ex) { errorMessage("Usage: java Decompile <class file>"); } try { try { /* Create ClassReader instance and fill it */ classReader = new ClassReader(fileName); classReader.readAll(); } catch(ClassFileMagicMismatch ex) { errorMessage("This does not appear to be a class file!"); } catch(FileNotFoundException ex) { errorMessage("File not found!"); } catch(EOFException ex) { errorMessage("Class file format seems to be invalid!"); } catch (UnknownConstantPoolTag ex) { errorMessage("Class file format seems to be invalid" + " (unknown tag in constant pool)!"); } catch(NullPointerException ex) { bug(); } finally { /* we no longer need the file object in classReader */ if(classReader != null) classReader.close(); } } catch(IOException ex) { errorMessage("I/O error!"); } /* Here goes the printing */ System.out.format("\n/* File %s */%n", fileName); try { classReader.printNice(); } catch(NullPointerException ex) { bug(); } }
9
public Ticket_Frame() { /* 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(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CE_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> initComponents(); }
6
protected void addedToWorld(World world) { // bereits existierende Aktoren auf der Kachel werden geloescht List l = getWorld().getObjectsAt(getX(), getY(), null); for (int i = 0; i < l.size(); i++) { Actor actor = (Actor) l.get(i); if (actor != this) { getWorld().removeObject(actor); } } }
2
private int getActiveContestantCount(RobotPeer peer) { int count = 0; for (ContestantPeer c : contestants) { if (c instanceof RobotPeer) { RobotPeer robot = (RobotPeer) c; if (!robot.isSentryRobot() && robot.isAlive()) { count++; } } else if (c instanceof TeamPeer && c != peer.getTeamPeer()) { for (RobotPeer robot: (TeamPeer) c) { if (!robot.isSentryRobot() && robot.isAlive()) { count++; break; } } } } return count; }
9
private void addLabel(BufferedWriter bw, int address) throws IOException { // add label if(rom.label[address] != null || rom.labelType[address] != 0) { String label = rom.getLabel(address); if(rom.labelType[address] > 1) label += ": ; "+prettyPrintAddress(address); if(rom.labelType[address] > 2) { //if(addNewLine) bw.write("\n"); if(rom.accesses[address] == null) bw.write("; no known jump sources\n"); else { Iterator<Integer> ii = rom.accesses[address].iterator(); bw.write("; known jump sources: "+prettyPrintAddress(ii.next())); while(ii.hasNext()) bw.write(", "+prettyPrintAddress(ii.next())); bw.write("\n"); } } bw.write(label + "\n"); } }
6
private static boolean hasSuperclass(Class<?> c, Class<?> superClass) { if (superClass == Object.class) return true; Class<?> s = c.getSuperclass(); while(s != null && s != Object.class){ if (s == superClass) return true; s = s.getSuperclass(); } return false; }
7
private Vector<XMLNoteReplacer> getReplacers() { Vector<XMLNoteReplacer> r=new Vector<XMLNoteReplacer>(); r.add(new XMLNoteReplacer("[<]head[^>]*[>].*?[<][/]head[>]","",true)); r.add(new XMLNoteReplacer("[<]p[>](.*?)[<][/]p[>]","::P:PAR:P::$1::P:EPAR:P::",true)); r.add(new XMLNoteReplacer("[<]p\\s[^>]+[>](.*?)[<][/]p[>]","::P:PAR:P::$1::P:EPAR:P::",true)); r.add(new XMLNoteReplacer("[<]br[^>]*[>]","::E:BR:E::",true)); r.add(new XMLNoteReplacer("[<]li[>]::P:PAR:P::(.*?)::P:EPAR:P::","<li>$1</li>",true)); // Correct OpenOffice behaviour. { Vector<XMLNoteReplacer> ulr=new Vector<XMLNoteReplacer>(); ulr.add(new XMLNoteReplacer("[<]ul(\\s[^>]+){0,1}[>]","[<][/][uo]l[>]","::P:UL:P::","::P:EUL:P::",true)); ulr.add(new XMLNoteReplacer("[<]ol(\\s[^>]+){0,1}[>]","[<][/][uo]l[>]","::P:OL:P::","::P:EOL:P::",true)); ulr.add(new XMLNoteReplacer("[<]li(\\s[^>]+){0,1}[>]","[<][/]li[>]","::P:LI:P::","::P:ELI:P::",true)); r.add(new XMLNoteReplacer("[<](ul|ol|li)(\\s[^>]+){0,1}[>]","[<][/](ul|ol|li)[>]", "::P:(PAR|EPAR):P::","([<][/]?li(\\s[^>]+){0,1}[>])",ulr,true,true ) ); } r.add(new XMLNoteReplacer("[&]nbsp[;]"," ",true)); //r.add(new XMLNoteReplacer("[<]li[>](.*?)[<][/]li[>]","::P:LI:P::$1::P:ELI:P::",true)); //r.add(new XMLNoteReplacer("[<]li\\s[^>]+[>](.*?)[<][/]li[>]","::P:LI:P::$1::P:ELI:P::",true)); r.add(new XMLNoteReplacer("[<]b(\\sclass=[\"]h[0-9][\"])\\s*[>](.*?)[<][/]b[>]","::EL:B:$1:EL::$2::EL:EB:EL::",true)); r.add(new XMLNoteReplacer("[<]b[>](.*?)[<][/]b[>]","::EL:B:EL::$1::EL:EB:EL::",true)); r.add(new XMLNoteReplacer("[<]b\\s[^>]+[>](.*?)[<][/]b[>]","::EL:B:EL::$1::EL:EB:EL::",true)); r.add(new XMLNoteReplacer("[<]i[>](.*?)[<][/]i[>]","::EL:I:EL::$1::EL:EI:EL::",true)); r.add(new XMLNoteReplacer("[<]i\\s[^>]+[>](.*?)[<][/]i[>]","::EL:I:EL::$1::EL:EI:EL::",true)); r.add(new XMLNoteReplacer("[<]u[>](.*?)[<][/]u[>]","::EL:U:EL::$1::EL:EU:EL::",true)); r.add(new XMLNoteReplacer("[<]u\\s[^>]+[>](.*?)[<][/]u[>]","::EL:U:EL::$1::EL:EU:EL::",true)); r.add(new XMLNoteReplacer("[<]h1[>](.*?)[<][/]h1[>]","::EL:H1:EL::$1::EL:EH1:EL::",true)); r.add(new XMLNoteReplacer("[<]h1\\s[^>]+[>](.*?)[<][/]h1[>]","::EL:H1:EL::$1::EL:EH1:EL::",true)); r.add(new XMLNoteReplacer("[<]h2[>](.*?)[<][/]h2[>]","::EL:H2:EL::$1::EL:EH2:EL::",true)); r.add(new XMLNoteReplacer("[<]h2\\s[^>]+[>](.*?)[<][/]h2[>]","::EL:H2:EL::$1::EL:EH2:EL::",true)); r.add(new XMLNoteReplacer("[<]h3[>](.*?)[<][/]h3[>]","::EL:H3:EL::$1::EL:EH3:EL::",true)); r.add(new XMLNoteReplacer("[<]h3\\s[^>]+[>](.*?)[<][/]h3[>]","::EL:H3:EL::$1::EL:EH3:EL::",true)); r.add(new XMLNoteReplacer("[<]h4[>](.*?)[<][/]h4[>]","::EL:H4:EL::$1::EL:EH4:EL::",true)); r.add(new XMLNoteReplacer("[<]h4\\s[^>]+[>](.*?)[<][/]h4[>]","::EL:H4:EL::$1::EL:EH4:EL::",true)); r.add(new XMLNoteReplacer("[<]h5[>](.*?)[<][/]h5[>]","::EL:B:EL::$1::EL:EB:EL::",true)); r.add(new XMLNoteReplacer("[<]h5\\s[^>]+[>](.*?)[<][/]h5[>]","::EL:B:EL::$1::EL:EB:EL::",true)); r.add(new XMLNoteReplacer("[<][^>]+[>]","",true,true)); // General tag cleaner. r.add(new XMLNoteReplacer("::E:BR:E::","<br>",true)); r.add(new XMLNoteReplacer("::P:PAR:P::(.*?)::P:EPAR:P::","<p>$1</p>",true)); // If we still have (we don't want that) nested paragraphs, we correct that r.add(new XMLNoteReplacer("::P:(EPAR|PAR):P::","",true)); // For the nested stuff we already have made sure they match, no problem there. r.add(new XMLNoteReplacer("::P:UL:P::","<ul>",true)); r.add(new XMLNoteReplacer("::P:EUL:P::","</ul>",true)); r.add(new XMLNoteReplacer("::P:OL:P::","<ol>",true)); r.add(new XMLNoteReplacer("::P:EOL:P::","</ol>",true)); r.add(new XMLNoteReplacer("::P:LI:P::(.*?)::P:ELI:P::","<li>$1</li>",true)); r.add(new XMLNoteReplacer("::P:LI:P::","<li>",true)); r.add(new XMLNoteReplacer("::P:ELI:P::","</li>",true)); // Correct <li>...<ul> to <li>...</li><ul> //r.add(new XMLNoteReplacer("[<]")) // Now correct nested <li>'s in the html, we can't have nested <li>'s. The outer nesting needs to go. r.add(new XMLNoteReplacer("[<]li[>]\\s*[<]([ou])l[>]","<$1l>",true)); r.add(new XMLNoteReplacer("[<]li[>]([^<]+)[<]([ou])l[>]","<li>$1</li><$2l>",true)); r.add(new XMLNoteReplacer("[<][/]([ou])l[>]\\s*[<][/]li[>]","</$1l>",true)); r.add(new XMLNoteReplacer("[<][/](ul|ol)[>]([^<]+)[<][/]p[>]","</$1><p>$2</p>",true)); // No start paragraph tag for a given paragraph tag. // (other tags have been cleaned with the general tag cleaner). // ul and ol are the only ones left. r.add(new XMLNoteReplacer("::EL:B:([^:]+):EL::(.*?)::EL:EB:EL::","<b$1>$2</b>",true)); r.add(new XMLNoteReplacer("::EL:B:EL::(.*?)::EL:EB:EL::","<b>$1</b>",true)); r.add(new XMLNoteReplacer("::EL:I:EL::(.*?)::EL:EI:EL::","<i>$1</i>",true)); r.add(new XMLNoteReplacer("::EL:U:EL::(.*?)::EL:EU:EL::","<u>$1</u>",true)); r.add(new XMLNoteReplacer("::EL:H1:EL::(.*?)::EL:EH1:EL::","<p><b class=\"h1\">$1</b></p>",true)); r.add(new XMLNoteReplacer("::EL:H2:EL::(.*?)::EL:EH2:EL::","<p><b class=\"h2\">$1</b></p>",true)); r.add(new XMLNoteReplacer("::EL:H3:EL::(.*?)::EL:EH3:EL::","<p><b class=\"h3\">$1</b></p>",true)); r.add(new XMLNoteReplacer("::EL:H4:EL::(.*?)::EL:EH4:EL::","<p><b class=\"h4\">$1</b></p>",true)); // correction r.add(new XMLNoteReplacer("[>]\\s*[<]","><",true,true)); // cleanup empty space between tags, surrounding text //r.add(new XMLNoteReplacer("[>]\\s*",">",true)); r.add(new XMLNoteReplacer("^\\s+","",true)); r.add(new XMLNoteReplacer("\\s+$","",true)); //r.add(new XMLNoteReplacer("[<]p[>]","<p>$1</p>",true)); // correct html that has no paragraphs at all. r.add(new XMLNoteReplacer(new XMLNoteReplacer.Repl() { public String process(String in) { if (in.substring(0,3).equals("<p>")) { return in; } else { int i1=in.indexOf("<p>"); int i2=in.indexOf("</p>"); if (i1<i2) { return "<p>"+in.substring(0,i1)+"</p>"+in.substring(i1); } else { return "<p>"+in; } } } })); // correct the html from the beginning to the first <p> tag r.add(new XMLNoteReplacer(new XMLNoteReplacer.Repl() { public String process(String in) { if (in.substring(in.length()-4).equals("</p>")) { return in; } else { int i; for(i=in.length()-4;i>=0 && !in.substring(i,i+4).equals("</p>");i--); if (i<0) { for(i=in.length()-3;i>=0 && !in.substring(i,i+3).equals("<p>");i--); if (i<0) { return in; } else { return in+"</p>"; } } else { return in.substring(0,i+4)+"<p>"+in.substring(i+4)+"</p>"; } } } })); // correct html from end paragraph to end of html r.add(new XMLNoteReplacer("[<][/]p[>](.*?)[<]p[>]","</p><p>$1</p><p>",true)); // correct lines in between that have no paragraph boundaries r.add(new XMLNoteReplacer("[<]p[>][<][/]p[>]","",true)); // correct empty paragraphs. //This one doesn't work. with </ul></ul></p> //r.add(new XMLNoteReplacer("[<][/](ul|ol)[>](.+?)[<][/]p[>]","</$1><p>$2</p>",true)); // No start paragraph tag for a given paragraph tag. // (other tags have been cleaned with the general tag cleaner). // ul and ol are the only ones left. // I've moved this cleaner up. r.add(new XMLNoteReplacer("(.*)","<p>$1</p>",true)); // enclose html in paragraph tags, in case there were no paragraph tags r.add(new XMLNoteReplacer("[<]p[>][<]p[>]","<p>",true)); // remove double <p><p> r.add(new XMLNoteReplacer("[<][/]p[>][<][/]p[>]","</p>",true)); // remove double </p></p> r.add(new XMLNoteReplacer("([<]p[>][<][/]p[>])+$","",true)); // remove ending (<p></p>)+ r.add(new XMLNoteReplacer(new XMLNoteReplacer.Repl() { public String process(String in) { return correctNested(in,"[<]li[>]","[<][/]li[>]"); } })); return r; }
9
public long getaField2() { return aField2; }
0
@Override public void update(Observable o, Object arg) { if (arg instanceof SearchModel) { this.model = (SearchModel) arg; } /**-50 to count for the offset of the textbox*/ show(this.textField, -50, this.textField.getHeight()); List<PictureObject> pictures = this.model.getPictures(); this.setListItems(pictures); this.panel.removeAll(); /**Adds the search results to the popup, if result resulted in no matches, add a no result label.*/ if (!pictures.isEmpty()) { if (pictures.size() > 2) { this.messageItem.setMessage(SearchConstants.SEE_MORE); this.panel.add(this.messageItem); this.panel.add(new JSeparator()); } int nbrOfItems = 0; for (JPopupListItem item : listItems) { if (item.hasPicture()) { this.panel.add(item); nbrOfItems++; } } setPopupSize(250, (nbrOfItems * 70)); } else { this.messageItem.setBackground(Color.GRAY); this.messageItem.setMessage(SearchConstants.NO_ITEMS); this.panel.add(this.messageItem); setPopupSize(250, 40); } this.panel.revalidate(); }
5
static void addElement(List<Node> list, Node node) { if ( null == list ) { throw new NullPointerException("The collection is null"); } if ( list.isEmpty() ) { list.add(node); } int size = list.size(); int i = 0; int j = size - 1; while ( j-i > 1 ) { int mid = (j + i)/2; Node midNode = list.get(mid); if ( node.compareTo(midNode) < 0 ) { j = mid; } else { i = mid; } } if ( node.compareTo(list.get(i)) < 0 ) { list.add(i, node); } else if ( node.compareTo(list.get(j)) > 0 ) { list.add(j + 1, node); } else if ( node.compareTo(list.get(i)) > 0 && node.compareTo(list.get(j)) < 0 ) { list.add(j, node); } }
8
public static void DFS(int node, int used, int parent, String path) { if (path.length() / 2 == size) ans.add(path.trim()); else { Stack<Integer> change = new Stack<Integer>(); for (int i = 0; i < ady[node].size(); i++) { int neigh = ady[node].get(i); if (check(used, neigh)) { if (parents[neigh] == 1) parent |= (1 << neigh); else { change.push(neigh); parents[neigh]--; } } } for (int i = 1; i <= size; i++) if (check(used, i) && !check(parent, i)) { parents[i]--; DFS(i, used | (1 << i), parent | (1 << i), map2[i] + " " + path); parents[i]++; } while (!change.isEmpty()) parents[change.pop()]++; } }
8
private static boolean isMethodBetter( JavaAbstractMethod method1, int precision1, JavaAbstractMethod method2, int precision2) { //Methods comparison is done in a simplified way compared to the way how Java compiler //chooses the best method. The main difference is in the comparison of methods with variable //numbers of arguments, but such methods are not used very often, so the solution seems //to be suitable. //If one method has a variable number of arguments, and the other one does not, the //method with the fixed number of arguments is preferred. boolean varArgs1 = method1.isVarArgs(); boolean varArgs2 = method2.isVarArgs(); if (varArgs1 != varArgs2) { return varArgs2; } //Otherwise - check parameter types. Class<?>[] params1 = method1.getParameterTypes(); Class<?>[] params2 = method2.getParameterTypes(); int len = Math.min(params1.length, params2.length); for (int i = 0; i < len; ++i) { Class<?> type1 = params1[i]; Class<?> type2 = params2[i]; if (!type1.equals(type2)) { if (precision1 > precision2) { return true; } return isTypeBetter(type1, type2); } } return false; }
8
private static String canonicalize(final SortedMap<String, String> sortedParamMap) { if (sortedParamMap == null || sortedParamMap.isEmpty()) { return ""; } final StringBuffer sb = new StringBuffer(100); for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) { final String key = pair.getKey().toLowerCase(); if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) { continue; } if (sb.length() > 0) { sb.append('&'); } sb.append(percentEncodeRfc3986(pair.getKey())); if (!pair.getValue().isEmpty()) { sb.append('='); sb.append(percentEncodeRfc3986(pair.getValue())); } } return sb.toString(); }
8
public static List<CustomBlock> load(BlockAPI plugin) { ArrayList<CustomBlock> list = new ArrayList<CustomBlock>(); if (!PATH.exists()) { PATH.mkdirs(); return list; } BlockClassLoader classLoader = new BlockClassLoader(plugin.getClass().getClassLoader()); File[] classes = PATH.listFiles(); for (int x = 0; x < classes.length; x++) { File file = classes[x]; if ((!file.isDirectory()) && (file.getAbsolutePath().endsWith(".class"))) try { Class<?> myClass = classLoader.loadClass("file:" + file.getAbsolutePath(), file.getName().replace(".class", "")); Object object = myClass.newInstance(); if ((object instanceof CustomBlock)) { CustomBlock cblock = (CustomBlock)object; list.add(cblock); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return list; }
9
protected static int indexOf(final char[] chars, final String str, final int fromIndex) { for (char ch : chars) { if (str.indexOf(ch, fromIndex) != -1) { return str.indexOf(ch, fromIndex); } } return -1; }
2
public void getWalkingAnimation(int direction){ removeAnimation(currentAnimation); if(crouch){ addAnimation(crouching[current]); currentAnimation = crouching[current]; if (current != direction){ removeAnimation(crouching[current]); current = direction; addAnimation(crouching[current]); currentAnimation = crouching[current]; } if (crouching[current].isStopped()){ crouching[current].start(); } }else{ addAnimation(walking[current]); currentAnimation = walking[current]; if (current != direction) { removeAnimation(walking[current]); current = direction; addAnimation(walking[current]); currentAnimation = walking[current]; } if(walking[current].isStopped()){ walking[current].start(); } } }
5
public static void main(String[] args) { // calculating the sum and average of integer values int[] nums = { 5, 10, 15, 20, 25 }; int sum = 0; double avg = 0; for (int i = 0; i < nums.length; i++) { sum = sum + nums[i]; } avg = sum / (nums.length); System.out.println("Sum: " + sum); System.out.println("Avg: " + avg); }
1
void dessineLab(Graphics g){ int[][] tab = monLab.defLab; int x = -1; int y = -1; for (int i=0;i<tab.length;i++){ if (tab[i][NORD]==-1){ x = (i%Labyrinthe.DIM)*dimCase; y = (i/Labyrinthe.DIM)*dimCase; g.drawLine(x,y,x+dimCase,y); } if (tab[i][SUD]==-1){ x = (i%Labyrinthe.DIM)*dimCase; y = (i/Labyrinthe.DIM+1)*dimCase; g.drawLine(x,y,x+dimCase,y); } if (tab[i][OUEST]==-1){ x = (i%Labyrinthe.DIM)*dimCase; y = (i/Labyrinthe.DIM)*dimCase; g.drawLine(x,y,x,y+dimCase); } if (tab[i][EST]==-1){ x = (i%Labyrinthe.DIM+1)*dimCase; y = (i/Labyrinthe.DIM)*dimCase; g.drawLine(x,y,x,y+dimCase); } } }
5
public float[] distribution(){ float[] bowl = new float[NUM_FRUIT_TYPES]; for (int i = 0; i < NUM_FRUIT_TYPES; i++){ // each fruit bowl[i] = fruitOccuranceMLE(i); } return Vectors.normalize(bowl); }
1
private void checkHighScore() { leaderboard.add(playerScore); // Find out if the score was a highscore, and where it falls if ( playerScore > leaderboard.get(4) && !enteredName ) { enteredName = true; // pop up to add name String name = JOptionPane.showInputDialog("Congrats! You've Made the Leaderboard! Enter your name: "); if ( name == null ) { name = "iCantType"; } leaderboard.set(4, playerScore ); leaderboardNames.set(4, name ); // I'm a child... if ( playerScore > leaderboard.get(3) ) { leaderboard.set(4, leaderboard.get(3) ); leaderboardNames.set(4, leaderboardNames.get(3) ); leaderboardNames.set(3, name ); leaderboard.set(3, playerScore); if ( playerScore > leaderboard.get(2) ) { leaderboard.set(3, leaderboard.get(2) ); leaderboardNames.set(3, leaderboardNames.get(2) ); leaderboardNames.set(2, name ); leaderboard.set(2, playerScore); if ( playerScore > leaderboard.get(1) ) { leaderboard.set(2, leaderboard.get(1) ); leaderboardNames.set(2, leaderboardNames.get(1) ); leaderboardNames.set(1, name ); leaderboard.set(1, playerScore); if ( playerScore > leaderboard.get(0) ) { leaderboard.set(1, leaderboard.get(0) ); leaderboardNames.set(1, leaderboardNames.get(0) ); leaderboardNames.set(0, name ); leaderboard.set(0, playerScore); } } } } saveLeaderboard(); } }
7
public int getDefaultPoints() { return defaultPoints; }
0
protected byte[] toByteArray(short[] samples, int offs, int len) { byte[] b = getByteArray(len * 2); int idx = 0; short s; while (len-- > 0) { s = samples[offs++]; b[idx++] = (byte) s; b[idx++] = (byte) (s >>> 8); } return b; }
1
@Override public boolean check() { System.out.println(this.getClass().getSimpleName()); if (isUpperExists() == false) { return false; } if (isCurrentEqualsUpper() == false) { return false; } if (isLowerExists(1) == false) { return false; } if (shouldSwitchLower()) { if (isExecuteNotClick()) { return true; } getLower(1).click(); getLower(2).click(); return true; } if (shouldSwitchLowerLeft()) { if (isExecuteNotClick()) { return true; } getLower(1).click(); getLowerLeft().click(); return true; } if (shouldSwitchLowerRight()) { if (isExecuteNotClick()) { return true; } getLower(1).click(); getLowerRight().click(); return true; } return false; }
9
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("Prefix")) { if(sender instanceof Player) { Player p = (Player) sender; PlayerUtil pu = new PlayerUtil(p); if(pu.hasPermission("Nostalgia.Command.prefix", PermissionType.NORMAL)) { if(args.length == 0) { String buildprefix = StringUtil.arrangeString(args, " ", 0); String prefix = StringUtil.colorize(buildprefix); pu.setPrefix(prefix); pu.updateName(); p.sendMessage(LangUtil.prefixChanged(p.getDisplayName())); } else if (args.length >= 1) { if(StringUtil.startsWithIgnoreCase(args[0], "p:")) { if(pu.hasPermission("Nostalgia.Command.prefix.others", PermissionType.NORMAL)) { String playerName = StringUtil.removePrefix(args[0], 2); Player t = Nostalgia.getPlayer(playerName); if(t != null) { PlayerUtil tu = new PlayerUtil(t); String buildprefix = StringUtil.arrangeString(args, " ", 1); String prefix = StringUtil.colorize(buildprefix, p, "prefix", PermissionType.NORMAL); tu.setPrefix(prefix); tu.updateName(); t.sendMessage(LangUtil.prefixChanged(t.getDisplayName())); } else { p.sendMessage(LangUtil.mustBeOnline(playerName)); } } else { MessageUtil.noPermission(p, "Nostalgia.Command.prefix.others"); } } else { String buildprefix = StringUtil.arrangeString(args, " ", 0); String prefix = StringUtil.colorize(buildprefix, p, "prefix", PermissionType.NORMAL); pu.setPrefix(prefix); pu.updateName(); p.sendMessage(LangUtil.prefixChanged(p.getDisplayName())); } } else { p.sendMessage(LangUtil.fourthWall()); } } else { MessageUtil.noPermission(p, "Nostalgia.Command.prefix"); } } else { sender.sendMessage(LangUtil.mustBePlayer()); } } return false; }
8
public void planNextStep(double s_elapsed) { for (Scenery scenery : sceneries) { scenery.planNextAction(s_elapsed); } for (Powerup powerup : powerups) { powerup.planNextAction(s_elapsed); } for (Shot shot : shots) { shot.planNextAction(s_elapsed); } for (ProximityBomb bomb : bombs) { bomb.planNextAction(s_elapsed); } for (Robot robot : robots) { robot.planNextAction(s_elapsed); } for (Pyro pyro : pyros) { pyro.planNextAction(s_elapsed); } for (MapObject object : misc_objects) { object.planNextAction(s_elapsed); } }
7
public void parseCommand(String command) { //Split command based on space String[] words = command.split(" "); //First word is the process/command String com = words[0]; //Remaining words are process arguments String[] args = new String[words.length - 1]; MigratableProcessWrapper mpw = null; for (int i = 1; i < words.length; i++) { args[i-1] = words[i]; } if (com.equals("-c") && args.length == 1) { //Connect as slave command if (isMaster) { connectAssSlave(args[0]); } else { System.out.println("Already connected as slave"); } } else if (com.equals("ps") && words.length == 1) { //Print processes command pr.printProcesses(); } else if (com.equals("quit") && words.length == 1) { //Quits the ProcessManager quitPM(); } else { //Attempts to start a process with the command if((mpw = acceptProcess(com, args)) != null) { mpw.setName(command); addProcess(mpw); } } }
9
public void SimpleRunSameGameInterval(String dataFile, String outputFile, int interval){ globalLinkCounter = 0; L = new LinkSet(); MatchData M = new MatchData(dataFile); Match m; int c = 0; ArrayList<LinkSetNode> links; long longinterval = (long)interval*1000l*60l*60l*24l; while((m = M.getNext()) != null) { if(m.getDuration() > 0 && m.winner != -2) { links = getLinksMatch(m); for(LinkSetNode ls : links) { L.addLink(new TimedLinkSetNode(ls.s,ls.d,longinterval,m.gameStartMs)); } c++; if(c%25000 ==0) { System.out.println(c + " done. Size of tree: " + L.size()); } } } System.out.println(c + " done. Size of tree: " + L.size()); System.out.println("links added (including weight increments) " + globalLinkCounter); L.writePartFile(outputFile); L.clear(); }
5
public EasyDate set(int year, int month, int day, int... args) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); if (args.length > 0) { int[] fields = new int[] { Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND }; int i = 0; do { calendar.set(fields[i], args[i]); } while (++i < args.length); } return this; }
2
public double[] rawPersonMeans(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawPersonMeans; }
2
public DNSRR readRR() throws IOException { String rrName = readDomainName(); int rrType = readShort(); int rrClass = readShort(); long rrTTL = readInt(); int rrDataLen = readShort(); DNSInputStream rrDNSIn = new DNSInputStream(buf, pos, rrDataLen); pos += rrDataLen; try { String myName = getClass().getName(); int periodIndex = myName.lastIndexOf('.'); String myPackage = myName.substring(0, 1 + periodIndex); Class<?> theClass = Class.forName(myPackage + "record." + DNS.typeName(rrType)); DNSRR rr = (DNSRR) theClass.newInstance(); if (rrType != DNS.TYPE_TXT) { rr.init(rrName, rrType, rrClass, rrTTL, rrDNSIn); } return rr; } catch (ClassNotFoundException ex) { throw new IOException("Unknown DNSRR (type " + DNS.typeName(rrType) + " (" + rrType + "))"); } catch (IllegalAccessException ex) { throw new IOException("Access error creating DNSRR (type " + DNS.typeName(rrType) + ')'); } catch (InstantiationException ex) { throw new IOException("Instantiation error creating DNSRR (type " + DNS.typeName(rrType) + ')'); } }
5
public Long getUpdatedAt() { return updatedAt; }
0
public void setManufacturerId(String manufacturerId) { this.manufacturerId = manufacturerId; setDirty(); }
0
public static void main(String[] args) { makeAllPieces(); makeSideIcons(); }
0
public String nextValue() throws IOException { Token tkn = nextToken(); String ret = null; switch (tkn.type) { case TT_TOKEN: case TT_EORECORD: ret = tkn.content.toString(); break; case TT_EOF: ret = null; break; case TT_INVALID: default: // error no token available (or error) throw new IOException( "(line " + getLineNumber() + ") invalid parse sequence"); /// unreachable: break; } return ret; }
4
private boolean createDatabase() { Utilities.outputDebug("Loading " + m_plugin.getDataFolder() + File.separator + m_databaseName + ".sqlite"); m_databaseFile = new File(m_plugin.getDataFolder() + File.separator + m_databaseName + ".sqlite"); if (m_databaseFile.exists()) { return true; } if (!m_plugin.getDataFolder().exists()) { m_plugin.getDataFolder().mkdir(); } try { if (!m_databaseFile.createNewFile()) { return false; } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
4
private boolean setID(String fileName, int id) { boolean result = false; int i = 0; File tempFile = null; Storage tempStorage = null; while ((i < storageList_.size()) && (tempFile == null)) { tempStorage = (Storage) storageList_.get(i); tempFile = tempStorage.getFile(fileName); if (tempFile != null) { tempFile.setRegistrationID(id); // set registration ID String newName = tempFile.getName() + id; tempStorage.renameFile(tempFile, newName); // rename filename tempFile.setName(newName); // set the new lfn result = true; } i++; } return result; }
3
private double[] calculateHDDConsumption(Component component, HardwareAlternative hardwareAlternative) { double consumption[] = { -1, -1 }; consumption[0] = component.getUsageHDD().getEnergyPoints(); for (HardwareComponent hdd : hardwareAlternative.getHardwareComponents()) { double temp = Utils.consumptionHDD((Hdd) hdd, component.getUsageHDD())[1]; if (temp != -1 && (temp < consumption[1] || consumption[1] == -1)) consumption[1] = temp; } return consumption; }
4
public Set<Map.Entry<Integer,V>> entrySet() { return new AbstractSet<Map.Entry<Integer,V>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TIntObjectMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if ( o instanceof Map.Entry ) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TIntObjectMapDecorator.this.containsKey( k ) && TIntObjectMapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator<Map.Entry<Integer,V>> iterator() { return new Iterator<Map.Entry<Integer,V>>() { private final TIntObjectIterator<V> it = _map.iterator(); public Map.Entry<Integer,V> next() { it.advance(); int k = it.key(); final Integer key = (k == _map.getNoEntryKey()) ? null : wrapKey( k ); final V v = it.value(); return new Map.Entry<Integer,V>() { private V val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals( key ) && ( ( Map.Entry ) o ).getValue().equals( val ); } public Integer getKey() { return key; } public V getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public V setValue( V value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Integer,V> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Integer key = ( ( Map.Entry<Integer,V> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Integer,V>> c ) { throw new UnsupportedOperationException(); } public void clear() { TIntObjectMapDecorator.this.clear(); } }; }
7
private void handleReadyKey(SelectionKey key) throws IOException { if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { // accept the new connection ServerSocketChannel newChannel = (ServerSocketChannel)key.channel(); SocketChannel sc = newChannel.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); pendingConnections.put(sc, new PlayerConnection(sc, sc.getRemoteAddress())); System.out.println("[Server] Accepted connection from " + sc.getRemoteAddress()); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { SocketChannel sc = (SocketChannel) key.channel(); PlayerConnection conn = pendingConnections.get(sc); ServerPlayer player = null; if (conn == null) { player = clients.get(sc); conn = player.getConnection(); } Packet packet = conn.read(); if (packet == null) { if (!conn.isConnected()) { pendingConnections.remove(sc); // TODO: possibly notify of unexpected disconnect ServerPlayer removed = clients.remove(sc); if (removed != null) game.removePlayer(removed); System.out.println("[Server] Connection from " + conn.getRemoteAddress() + " disconnected"); } else { System.out.println("[Server] Malformed data received from " + conn.getRemoteAddress()); } return; } System.out.println("[Server] Received data from " + conn.getRemoteAddress() + ": " + packet.toString()); if (player == null) { if (packet instanceof ConnectPacket) { ConnectPacket connect = (ConnectPacket)packet; pendingConnections.remove(sc); player = new ServerPlayer(game, conn, connect.name); clients.put(sc, player); game.addPlayer(player); System.out.println("[Server] " + connect.name + " connected from " + conn.getRemoteAddress()); } else { System.err.println("[Server] Pending connection from " + conn.getRemoteAddress() + " sent something other than ConnectPacket: " + packet.getClass().getSimpleName()); return; } } player.handle(packet); } else { System.out.println("[Server] Unknown readyops: " + key.readyOps()); } }
8
public static void allocate(int size, FileRequester fileRequester) { try { Model.modelHeaderCache = new ModelHeader[size]; Model.fileRequester = fileRequester; } catch (ArrayIndexOutOfBoundsException arrayoutofbounds) { Model.modelHeaderCache = new ModelHeader[size + Short.MAX_VALUE]; Model.fileRequester = fileRequester; } }
1
@Get("json") public Representation _get() { String keyword = getAttribute("keyword"); String input = format("^%s", escapeRE(keyword)); Pattern ptrn = compile(input.toLowerCase()); Find find = $namespaces.find(FIND, ptrn).limit(20); List<String> rslts = new ArrayList<>(); for (Map<?, ?> map : find.as(Map.class)) { rslts.add((String) map.get("keyword")); } if (rslts.size() == 1) { NSKeywordCompletion ret = new NSKeywordCompletion(); ret.addValue(rslts.get(0)); ret.addLink("self", ALT_URL + keyword); return ret.json(); } NSKeywordCompletion ret = new NSKeywordCompletion(); for (String rslt : rslts) { ret.addLink("result", ALT_URL + rslt); ret.addValue(rslt); } ret.addLink("self", ALT_URL + keyword); return ret.json(); }
5
@Override public void actionPerformed(ActionEvent e) { Object s = e.getSource(); if(s instanceof JButton) { if(s instanceof ThemeItem) { Option.setTheme(((ThemeItem) s).getTheme()); themeName.setText(Option.getThemeName().replace("/", "")); frame.dispose(); changeTheme.setEnabled(true); } else if(((JButton)s).getText().equals(ViewConstante.BUTTON_CHANGE)){ changeTheme.setEnabled(false); frame = new JFrame(); frame.add(new ThemesView(this)); frame.setVisible(true); frame.setResizable(false); frame.setLocation((int)(gui.getFrame().getLocation().getX()+100), (int)(gui.getFrame().getLocation().getY()+100)); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.pack(); } else if(((JButton)s).getText().equals(ViewConstante.BUTTON_RETOUR_OPTION)){ frame.dispose(); changeTheme.setEnabled(true); } } else if (s instanceof JCheckBox) { methLevel(((JCheckBox)s)); } }
5
private static String getTime(String time) { time = time.split(" ")[3]; time = (Integer.parseInt(time.split(":")[0]) > 12 ? Integer.parseInt(time.split(":")[0])-12 : time.split(":")[0]) + ":" +time.split(":")[1] +(Integer.parseInt(time.split(":")[0]) > 12 ? " PM" : " AM"); return time; }
2
public boolean colorMatch(P p) { if (this.R==250 && this.G==250 && this.B==250) return false; if (this.R == p.R && this.G == p.G && this.B == p.B) return true; return false; }
6
public void setMoney(double money){ this.money = money; }
0
private void drawGrid(Graphics2D g) { for (int i = 0; i < 9; i++) { for (FieldSlot s : field.areas.get(i)) { int x = s.getX(); int y = s.getY(); g.setColor(new Color((200 + 25 * i) % 255, (120 * i) % 255, 90 * i % 255)); g.fillRect(x * width / 9, y * height / 9, width / 9 + 1, height / 9 + 1); g.setColor(Color.BLACK); } } for (int x = 0; x < 9; x++) { for (int y = 0; y < 9; y++) { int xPos = (int) ((float) width / 9 * (x) + (float) width / 32); int yPos = (int) ((float) height / 9 * (y + 1) - (float) height / 64); g.drawChars(field.getSlotChar(x, y), 0, 1, xPos, yPos); } } for (int i = 0; i < 8; i++) { int lineHeight = (int) ((float) height / 9 * (i + 1)); int linePos = (int) ((float) width / 9 * (i + 1)); g.drawLine(0, lineHeight, width, lineHeight); g.drawLine(linePos, 0, linePos, height); } }
5
public void delStudent(String no) { String delete = "DELETE FROM STUDENT WHERE NO=?"; try { PreparedStatement ps = conn.prepareStatement(delete); ps.setString(1, no); ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } }
1
public void clear() { configurationToButtonMap.clear(); selected.clear(); super.removeAll(); }
0
public void repaintSelection() { repaintSelectionInternal(); for (OutlineProxy proxy : mProxies) { proxy.repaintSelectionInternal(); } }
1
public void moveAnchor(int x, int y, int width, int height) { ((Rectangle) shape).x = x; ((Rectangle) shape).y = y; ((Rectangle) shape).height += height; ((Rectangle) shape).width += width; updateCornerRects(); canvas.repaint(); }
0
public final void setSliderButtonImage(BufferedImage image) { double sliderWidth = isVertical ? scrollBarThickness : getSliderSize(); double sliderHeight = isVertical ? getSliderSize() : scrollBarThickness; if (slider == null) slider = new TButton(x + (isVertical ? 0 : scrollBarThickness), y + (isVertical ? scrollBarThickness : 0), sliderWidth, sliderHeight, ""); if (image != null) slider.setImage(image, sliderWidth, sliderHeight); else { if (parentComponent != null) { setColour(scrollBarColour); if (isVertical) // Make slider gradient vertical // too { GradientPaint g1 = slider.gradientUp; GradientPaint g2 = slider.gradientDown; slider.gradientUp = new GradientPaint(slider.getXI() + (slider.getWidthI() / 3), getYI(), g1.getColor1(), slider.getXI() + slider.getWidthI() + (slider.getWidthI() / 3), slider.getYI(), g1.getColor2(), g1.isCyclic()); slider.gradientDown = new GradientPaint(slider.getXI() + (slider.getWidthI() / 3), getYI(), g2.getColor1(), slider.getXI() + slider.getWidthI() + (slider.getWidthI() / 3), slider.getYI(), g2.getColor2(), g2.isCyclic()); } } } }
8
public int getBit(int n) { if (n < 0 || n > length - 1) { throw new IllegalArgumentException( "n must be between 0 and " + (length - 1)); } return ((bits & (1 << n)) >> n); }
2
*/ private void jComboB_ItemsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboB_ItemsActionPerformed /* * lokale Variablen für diese Methode, momentan zu Testzwecken */ int currentSemester = Sims_1._maingame.getSemester(); // current Semester boolean usedCheat = Sims_1._maingame.getCheated(currentSemester); //checks if Cheat was already used in this semester javax.swing.JComboBox box = (javax.swing.JComboBox) evt.getSource(); String selected = (String) box.getSelectedItem(); System.out.println("Right now selected " + selected); if (selected.equals("Spicker")) { if (Sims_1._maingame.cheatSheet.amount == 0) { System.out.println("Kein Spicker verfügbar"); noCheatsAvailableDialog.setVisible(true); } else if ((currentSemester >= 2) && (currentSemester <= 6) && !usedCheat) { warningDialog.setVisible(true); System.out.println("show warning"); } else { System.out.println("Du kannst in dem " + currentSemester + " Semester den Spicker nicht mehr einsetzen"); notAllowedUseCheatDialog.setVisible(true); } } }
5
public String run(PrintWriter out) throws InstantiationException, IllegalAccessException { classInstance = (Program)className.newInstance(); startTime = System.currentTimeMillis(); status = 0; classInstance.run(out, args); status = 3; endTime = System.currentTimeMillis(); return getName() +" ran successfully time = "+ (endTime - startTime) + " milliseconds\n"; }
0
public BuilderPattern build() { return new BuilderPattern(this); }
0
@Override public void handle(HttpExchange he) throws IOException { String response = ""; int statusCode = 200; String method = he.getRequestMethod().toUpperCase(); switch (method) { case "GET": break; case "POST": isr = new InputStreamReader(he.getRequestBody(), "utf-8"); br = new BufferedReader(isr); jsonQuery = br.readLine(); jp = new JsonParser(); jo = (JsonObject) jp.parse(jsonQuery); userName = jo.get("userName").getAsString(); password = jo.get("password").getAsString(); role = jo.get("role").getAsString(); try { response = "" + facade.addUser(userName, password, role); } catch (AlreadyExcistException ex) { response = ex.getMessage(); statusCode = 404; } break; case "PUT": try { isr = new InputStreamReader(he.getRequestBody(), "utf-8"); br = new BufferedReader(isr); jsonQuery = br.readLine(); jp = new JsonParser(); jo = (JsonObject) jp.parse(jsonQuery); userName = jo.get("userName").getAsString(); currentPassword = jo.get("currentPassword").getAsString(); newPassword = jo.get("newPassword").getAsString(); if (!currentPassword.equals(newPassword)){ response = "" + facade.changePassword(userName, newPassword); } } catch (UserNotFoundException ex) { response = ex.getMessage(); statusCode = 404; } break; case "DELETE": isr = new InputStreamReader(he.getRequestBody(), "utf-8"); br = new BufferedReader(isr); jsonQuery = br.readLine(); jp = new JsonParser(); jo = (JsonObject) jp.parse(jsonQuery); userName = jo.get("userName").getAsString(); try { response = "" + facade.deleteUser(userName); } catch (UserNotFoundException ex) { response = ex.getMessage(); statusCode = 404; } break; } he.getResponseHeaders().add("Content-Type", "application/json"); he.sendResponseHeaders(statusCode, 0); try (OutputStream os = he.getResponseBody()) { os.write(response.getBytes()); } }
8
private int dantzig() { int q = 0; for (int j = 1; j < M + N; j++) if (a[M][j] > a[M][q]) q = j; if (a[M][q] <= 0) return -1; // optimal else return q; }
3
public String readStr() { if(inf) { if(sc.hasNext()) return sc.next(); else return null; } else { ExceptionLog.println("Попытка записи в неоткрытый файл"); return null; } }
2
public void setNode(boolean isNode) {this.isNode = isNode;}
0
private static boolean trackCut(double[] upper, double[] under, int position, int deep) { if (upper[position] <= under[position]) { return false; } for (int i = (position - 1); i > (position - deep); i--) { if (upper[i] < under[i]) { return true; } } return false; }
3
private LinkDecor getDecors1(String s) { // System.err.println("s1=" + s); if (s == null) { return LinkDecor.NONE; } s = s.trim(); if ("<|".equals(s)) { return LinkDecor.EXTENDS; } if ("<".equals(s)) { return LinkDecor.ARROW; } if ("^".equals(s)) { return LinkDecor.EXTENDS; } if ("+".equals(s)) { return LinkDecor.PLUS; } if ("o".equals(s)) { return LinkDecor.AGREGATION; } if ("*".equals(s)) { return LinkDecor.COMPOSITION; } return LinkDecor.NONE; }
7
public Couleur obtenirCouleurInverse() { if (this == BLANC) return NOIR; return BLANC; }
1
public void newFruit() { int r = rand.nextInt(5); Fruit fruit; if (r == 0) { fruit = new Orange(); } else { fruit = new Apple(); } // Makes sure fruit doesn't spawn on obstacles or snakes if (fruit.spawned == false) { for (Obstacle o : obstacles) { if (fruit.x == o.getX() && fruit.y == o.getY()) { fruit.newPosition(); newFruit(); } } for (Snake s : snakes) { if (fruit.x == s.getX() && fruit.y == s.getY()) { fruit.newPosition(); newFruit(); } else { fruit.spawned = true; fruits.add(fruit); } } } }
8
public List<EntidadBancaria> findAll(){ try{ List<EntidadBancaria> ListaEntidades; Connection connection = connectionFactory.getConnection(); ListaEntidades = new ArrayList(); String selectTodasEntidades = "SELECT * from EntidadBancaria"; PreparedStatement prepared = null; prepared = connection.prepareStatement(selectTodasEntidades); ResultSet result = prepared.executeQuery(); while (result.next()) { EntidadBancaria entidadBancaria = new EntidadBancaria(); entidadBancaria.setIdEntidad(result.getInt("idEntidad")); entidadBancaria.setCodigoEntidadBancaria(result.getString("codigoEntidad")); entidadBancaria.setNombre(result.getString("nombre")); entidadBancaria.setCif(result.getString("cif")); entidadBancaria.setTipo(TipoEntidadBancaria.valueOf(result.getString("tipoEntidadBancaria"))); ListaEntidades.add(entidadBancaria); } return ListaEntidades; }catch(Exception ex){ throw new RuntimeException(ex); } }
2
public static void chooseHeuristicDynamicCell(List<Measurement> measurements, Computation comp, int threshold, boolean useRSS) { if(useRSS) { HashSet<Integer> indices = Generate.randomInts(threshold, measurements.size(), null); int sum1 = 0; int sum2 = 0; int count1 = 0; int count2 = 0; for(int i : indices) { Measurement curr = measurements.get(i); double dist1 = comp.getLongestVector().getP1().distance(curr.getCoordinates()); double dist2 = comp.getLongestVector().getP2().distance(curr.getCoordinates()); if(dist1 <= dist2) { sum1 += curr.getSignalStrength(); count1++; } else { sum2 += curr.getSignalStrength(); count2++; } } double average1 = sum1/(double)count1; double average2 = sum2/(double)count2; if(average1 >= average2) { double dist1 = comp.getLongestVector().getP1().distance(comp.getHeuristicCell1().getCellTowerCoordinates()); double dist2 = comp.getLongestVector().getP1().distance(comp.getHeuristicCell2().getCellTowerCoordinates()); if(dist2 < dist1) { DefaultCell temp = comp.getHeuristicCell1(); comp.setHeuristicCell1(comp.getHeuristicCell2()); comp.setHeuristicCell2(temp); } } else { double dist1 = comp.getLongestVector().getP2().distance(comp.getHeuristicCell1().getCellTowerCoordinates()); double dist2 = comp.getLongestVector().getP2().distance(comp.getHeuristicCell2().getCellTowerCoordinates()); if(dist2 < dist1) { DefaultCell temp = comp.getHeuristicCell1(); comp.setHeuristicCell1(comp.getHeuristicCell2()); comp.setHeuristicCell2(temp); } } } else { distanceFromSurroundingPointsToVector(comp, measurements, threshold); } }
6
public static void count_vowels(String s) { s = s.toLowerCase(); int count = 0; List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u'); for (int i = 0; i < s.length(); i++) { if (vowels.contains(s.charAt(i))) count++; } System.out.println(count); }
2
public static void main(String args[]){ Scanner sc = new Scanner(System.in); int A,C; while(true) { A= sc.nextInt(); if(A==0) break; C = sc.nextInt(); int recentElement = 0; int cutCount = 0; for(int i=0;i<C;i++) { int n = sc.nextInt(); if(i==0) { cutCount = (A-n); } else { if(recentElement>n) cutCount+=(recentElement-n); } recentElement = n; } System.out.println(cutCount); } }
5
public static void main(String[] args) { ExGui exGui = new ExGui(); exGui.go(); }
0
public void faireActivite() { this.choixActivite = "0"; boolean test = false; boolean recommencer = true; while (!test) { System.out.println("\n\nQuelle activite souhaitez-vous faire ?" + "\n Tapez 1 pour entrer dans le casino (jeux)" + "\n Tapez 2 pour aller au bar" + "\n Tapez 3 pour aller dans une chambre de l'hotel"); // lire le choix avec gestion des exceptions do{ try{ this.choixActivite = keyboard.nextLine(); switch (this.choixActivite) { case "1" : recommencer = false; break; case "2" : recommencer = false; break; case "3" : recommencer = false; break; default : throw new Exception("Ni 1 ni 2 ni 3"); } } catch(Exception e){ System.out.println("Veuillez entrer 1, 2 ou 3"); keyboard.next(); } }while(recommencer); switch (this.choixActivite) { case "1" : jeu.demarrer(); test = true; break; case "2" : bar.demarrer(joueur); test=true; break; case "3" : chambre.demarrer(joueur); test= true; break; default : System.out.println("\n\nLa saisie n'est pas valide, veuillez reessayer..."); } } }
9
public void cargarTabla(NodoBase raiz){ while (raiz != null) { if (raiz instanceof NodoIdentificador){ InsertarSimbolo(((NodoIdentificador)raiz).getNombre(),-1,((NodoIdentificador)raiz).getTipo()); //TODO: A�adir el numero de linea y localidad de memoria correcta } /* Hago el recorrido recursivo */ if (raiz instanceof NodoIf){ cargarTabla(((NodoIf)raiz).getPrueba()); cargarTabla(((NodoIf)raiz).getParteThen()); if(((NodoIf)raiz).getParteElse()!=null){ cargarTabla(((NodoIf)raiz).getParteElse()); } } else if (raiz instanceof NodoAsignacion){ cargarTabla(((NodoAsignacion)raiz).getIdentificador()); cargarTabla(((NodoAsignacion)raiz).getExpresion()); }else if (raiz instanceof NodoOperacion){ cargarTabla(((NodoOperacion)raiz).getOpIzquierdo()); cargarTabla(((NodoOperacion)raiz).getOpDerecho()); }else if (raiz instanceof NodoFor){ cargarTabla(((NodoFor)raiz).getInicia()); cargarTabla(((NodoFor)raiz).getComp()); cargarTabla(((NodoFor)raiz).getHast()); //increDecre cargarTabla(((NodoFor)raiz).getSente()); }else if (raiz instanceof NodoVector){ cargarTabla(((NodoVector)raiz).getVariable()); }else if (raiz instanceof NodoWhile){ cargarTabla(((NodoWhile)raiz).getPrueba()); cargarTabla(((NodoWhile)raiz).getCuerpo()); } raiz = raiz.getHermanoDerecha(); } }
9
@Override public double getClippedValue(double input, double clip) { double result = 0; if (input >= a && input <= c) { result = (input - a) / (c - a); if (result < clip) { return result; } else { return clip; } } else if (input >= c && input <= b) { result = (input - b) / (c - b); if (result < clip) { return result; } else { return clip; } } return result; }
6
public boolean isInAcceptState() { return getState() >= 0 && getCurrState().isAcceptState() && !isInSpaceState() && !isInErrorState(); }
3
@RequestMapping(method = RequestMethod.POST, produces = "application/json") public ResponseEntity<?> create(@ModelAttribute("contact") Contact contact, @RequestParam(required = false) String searchFor, @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page, Locale locale) { contactService.save(contact); if (isSearchActivated(searchFor)) { return search(searchFor, page, locale, "message.create.success"); } return createListAllResponse(page, locale, "message.create.success"); }
2
private boolean isValid() { if (firstName.length() > 50 || lastName.length() > 75 || (!gender.equals("M") && !gender.equals("F"))) { System.err.println("Invalid argument(s) when inserting a user!"); return false; } return true; }
4
public void action(Sac[] tabSacs, DomaineDesMorts ddm, JFrame page, Dieu deus) { this.avancer(1); int k = 0; int nb = 0; int val; if ("Tyr".equals(deus.getNom())) { int det1 = de.getCouleur(); int det2 = de.getCouleur(); String[] choix1 = {tabSacs[det1].getCouleur(), tabSacs[det2].getCouleur()}; JOptionPane jop1 = new JOptionPane(); int rang1 = JOptionPane.showOptionDialog(page, "Quelle couleur du dé choisissez vous?", "Avantage Tyr", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, choix1, choix1[0]); if (rang1 == 0) { val = det1; } else { val = det2; } } else { val = de.getValeur(); } Sac s = tabSacs[val]; int nbViking = s.getNbVikings(); while (k < this.getPuissance() && k < nbViking) { Iterator it = s.getlPion().iterator(); Pion p; p = (Pion) it.next(); if (p.toString().compareTo("Vikings") == 0) { ddm.getlViking().add((Vikings) p); s.getlPion().remove(p); nb++; } k++; } JOptionPane.showMessageDialog(page, "Hel a retiré " + nb + " Vikings du sac " + s.getCouleur().toLowerCase() + ", il les a envoyés dans le domaine des morts.", "Effet de Hel", JOptionPane.INFORMATION_MESSAGE); }
5
public void mouseMoved(MouseEvent e) { String str = "x: " + e.getX() + ",y: " + e.getY(); System.out.println(str); }
0
private static final long getTimeOfDate(Object date) { long theTime; if (date == null) { theTime = System.currentTimeMillis(); } else if (date instanceof Date) { theTime = ((Date) date).getTime(); } else if (date instanceof EasyDate) { theTime = ((EasyDate) date).getTime(); } else if (date instanceof Calendar) { theTime = ((Calendar) date).getTimeInMillis(); } else { throw new ClassCastException("指定的对象不是日期类型:" + date); } return theTime; }
4
public void initiate() { new MainFrame(); serverConnection = new DummyConnection(); int id = serverConnection.assignPlayer("Anders"); if(id != 0)thePlayer = new ThisPlayer("Anders", id, 0); startGame(); }
1
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(CustomizeDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomizeDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomizeDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomizeDisplay.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 CustomizeDisplay().setVisible(true); } }); }
6
private void addProgrammaticLogging(Level level, File dir) { try { dir.mkdirs(); File file = new File(dir, "jscover.log"); if (file.exists()) file.delete(); FileHandler fileTxt = new FileHandler(file.getAbsolutePath(), true); Enumeration<String> names = LogManager.getLogManager().getLoggerNames(); while (names.hasMoreElements()) { String loggerName = names.nextElement(); Logger logger = LogManager.getLogManager().getLogger(loggerName); logger.setLevel(level); logger.addHandler(fileTxt); Handler[] handlers = logger.getHandlers(); for (int index = 0; index < handlers.length; index++) { handlers[index].setLevel(level); handlers[index].setFormatter(logFormatter); } } } catch (IOException e) { throw new RuntimeException(e); } }
4
public ArmorItem(){ super(); this.defenseScore = 1; this.name = "Unknown ARMOR name"; }
0
public static void main(String[] args) { final double PBAIN = 20; final double PTONTE = 25; final double PCOUPE = 30; String strNom; String strService; strNom = JOptionPane.showInputDialog("Nom de l'animal:"); strService = JOptionPane.showInputDialog("Services [B] [T] [G]:"); NumberFormat argent = NumberFormat.getCurrencyInstance(); switch(strService.charAt(0)) { case 'b': case 'B': JOptionPane.showMessageDialog(null, strNom+" a reçu un bain au montant de "+argent.format(PBAIN)); break; case 't': case 'T': JOptionPane.showMessageDialog(null, strNom+" a eu une tonte au montant de "+argent.format(PTONTE)); break; case 'g': case 'G': JOptionPane.showMessageDialog(null, strNom+" a eu une coupe au montant de "+argent.format(PCOUPE)); break; default: JOptionPane.showMessageDialog(null, "Mauvais choix"); } }
6
public boolean checkPositionUsed(Map<String, EnumElement> board, EnumLine line, EnumColumn column) throws PositionAlreadyUsedException { if (board.get(this.createPosition(line, column)) == EnumElement.HIT) { throw new PositionAlreadyUsedException(); } else { return true; } }
1
@Override public void execute(CommandSender arg0, String[] args) { //plugin.dbConfig.players.add(arg1[0]); if(args.length != 1) { arg0.sendMessage(TextComponent.fromLegacyText(ChatColor.DARK_AQUA+"["+ChatColor.RED+"#"+ChatColor.DARK_AQUA+"] "+ChatColor.GOLD+"Utilizzo: /watch [nome]!")); }else{ if(plugin.dbConfig.players.contains(arg0.getName())) { if(ProxyServer.getInstance().getPlayer(args[0]) != null) { plugin.watched.add(ProxyServer.getInstance().getPlayer(args[0]).getName()); arg0.sendMessage(TextComponent.fromLegacyText(ChatColor.DARK_AQUA+"["+ChatColor.YELLOW+"!"+ChatColor.DARK_AQUA+"] "+ChatColor.GOLD+ProxyServer.getInstance().getPlayer(args[0])+" aggiunto nella lista osservati!")); }else{ arg0.sendMessage(TextComponent.fromLegacyText(ChatColor.DARK_AQUA+"["+ChatColor.RED+"#"+ChatColor.DARK_AQUA+"] "+ChatColor.GOLD+"Player non trovato!")); } } } }
3
public static void main(String[] args) { FancyHouse fancyHouse = constructFancyHouse(args); if (fancyHouse == null) { System.out.println ("Illegal arguments"); return; } //testing house with fancy collection of balloons //FancyHouse fancyHouse = FancyHouse.getRandomFancyHouse(5, 7, 7, 10, 1, 3); printHouseInfo(fancyHouse); double execTime = processFancyHouse(fancyHouse); printResult(fancyHouse, execTime); System.out.println(); //testing house with light collections of balloons LightHouse lightHouse = new LightHouse(fancyHouse.getWidth(), fancyHouse.getLength(), fancyHouse.getFloors()); printHouseInfo(lightHouse); execTime = processLightHouse(lightHouse); printResult(lightHouse, execTime); System.out.println(); //testing house with value collection of balloons ValueHouse valueHouse = new ValueHouse(fancyHouse.getWidth(), fancyHouse.getLength(), fancyHouse.getFloors()); printHouseInfo(valueHouse); execTime = processValueHouse(valueHouse); printResult(valueHouse, execTime); System.out.println(); }
1