method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
fcba6912-297d-44da-8322-24b07936693d
3
public static Scanner scannerForWebPage(String page) { try { String filename = page.substring(page.lastIndexOf('/')+1); File local = new File(filename); if (local.isFile()) return new Scanner(local); URL u = new URL(page); FileOutputStream save = new FileOutputStream(local); InputStream read = u.openStream(); byte[] got = new byte[1024]; int have = read.read(got); while (have > 0) { save.write(got, 0, have); have = read.read(got); } save.close(); read.close(); return new Scanner(local); } catch (IOException e) { System.err.println("ERROR reading "+page); e.printStackTrace(); return null; } }
7e65fa45-d840-4b7b-ab46-17a9d4f7a8af
5
private T NextLargestRec(T key, BTPosition<T> node) { T found = null; if (node.getLeft() != null) { found = NextLargestRec(key, node.getLeft()); } if (comp.compare(node.element(), key) > 0 && found == null) { found = node.element(); } if (node.getRight() != null && found == null) { found = NextLargestRec(key, node.getRight()); } return found; }
aa6e0e9c-9b6b-4357-90f8-7779e9c94933
8
@Override public List<Map<String, ?>> Fotos_usuario(String idtr,String tipo) { List<Map<String, ?>> lista = new ArrayList<Map<String, ?>>(); String tabla ; if(tipo.equals("todo")){ tabla ="rhth_fotos_trabajador"; }else{ tabla ="rhtr_fotos_trabajador"; } this.cnn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE); String sql = "select * from "+tabla+" where id_trabajador= '"+idtr+"'"; try { ResultSet rs = this.cnn.query(sql); while (rs.next()) { Map<String, Object> cd = new HashMap<String, Object>(); cd.put("ar_foto",rs.getString("ar_foto")); cd.put("EFOTO",rs.getString("EFOTO")); lista.add(cd); } } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } catch (Exception e) { throw new RuntimeException("ERROR : " + e.getMessage()); } finally { try { this.cnn.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } return lista; }
4f6f0a17-1d30-443d-b601-15a3084765a6
5
public boolean processMsg(CConnection cc) { OutStream os = cc.getOutStream(); StringBuffer username = new StringBuffer(); StringBuffer password = new StringBuffer(); // JW: Launcher passes in username and password as properties of Options object, // so there's no need to pop up a dialog asking for a username // and password if they are already recorded within the Options object. // Cast cc object as CConn, so we access to opts CConn cconn = (CConn) cc; if (cconn.opts.username==null || cconn.opts.username.equals("") || cconn.opts.password==null || cconn.opts.password.equals("")) CConn.upg.getUserPasswd(username, password); else { username.append(cconn.opts.username); password.append(cconn.opts.password); } // Return the response to the server os.writeU32(username.length()); os.writeU32(password.length()); byte[] utf8str; try { utf8str = username.toString().getBytes("UTF8"); os.writeBytes(utf8str, 0, username.length()); utf8str = password.toString().getBytes("UTF8"); os.writeBytes(utf8str, 0, password.length()); } catch(java.io.UnsupportedEncodingException e) { e.printStackTrace(); } os.flush(); return true; }
6ec647df-5896-4230-a63b-e6406e423cc0
9
public List<Entry> processData(Document doc) { List<Entry> entryList = new ArrayList<>(); List<String> scriptures = new ArrayList<>(); List<String> topic = new ArrayList<>(); String date; String content = null; String scrip; NodeList entry = doc.getElementsByTagName("entry"); for (int temp = 0; temp < entry.getLength(); ++temp) { Node node = entry.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); ++i) { Node childNode = childNodes.item(i); if (childNode.getNodeName() == "scripture") { Element childElement = (Element) childNode; scrip = childElement.getAttribute("book"); if (childElement.hasAttribute("chapter")) { scrip = scrip + " " + childElement.getAttribute("chapter"); } if (childElement.hasAttribute("startverse")) { scrip = scrip + ":" + childElement.getAttribute("startverse"); } if (childElement.hasAttribute("endverse")) { scrip = scrip + "-" + childElement.getAttribute("endverse"); } scriptures.add(scrip); } if (childNode.getNodeName() == "topic") { topic.add(childNode.getTextContent()); } if (childNode.getNodeName() == "content") { content = element.getTextContent().trim(); content = content.replaceAll("\\n\\s+", "\n"); } } date = element.getAttribute("date"); entryList.add(new Entry(date, content, scriptures, topic)); } } return entryList; }
58e76988-eaa5-451f-acc7-2bcc8cb8cbac
9
public Array<Warp> createWarps(){ Array<Warp> warps = new Array<>(); MapProperties prop = tileMap.getProperties(); //create right warp if(prop.get("next")!=null) { String next = prop.get("next", String.class); String nextWarp = prop.get("nextWarp", String.class); int nextID = 0; if(nextWarp!=null) nextID = Integer.parseInt(nextWarp); Rectangle rect = new Rectangle(width-Vars.TILE_SIZE*2, 0, Vars.TILE_SIZE*2, height); Warp w = new Warp(this, next.replaceAll(" ", ""), 1, nextID, rect.x, rect.y+rect.height/2, rect.width, rect.height); w.setInstant(true); warps.add(w); } //create left warp if(prop.get("previous")!=null) { String next = prop.get("previous", String.class); String nextWarp = prop.get("prevWarp", String.class); int nextID = 1; if(nextWarp!=null) nextID = Integer.parseInt(nextWarp); Rectangle rect = new Rectangle(Vars.TILE_SIZE*2, 0, Vars.TILE_SIZE*2, height); Warp w = new Warp(this, next.replaceAll(" ", ""), 0, nextID, rect.x, rect.y+rect.height/2, rect.width, rect.height); w.setInstant(true); warps.add(w); } //create all other warps if(tileMap.getLayers().get("entities")!=null){ MapObjects objects = tileMap.getLayers().get("entities").getObjects(); for(MapObject object : objects) { if (object instanceof RectangleMapObject) { Rectangle rect = ((RectangleMapObject) object).getRectangle(); if(object.getProperties().get("warp")!=null) { String next = object.getProperties().get("next", String.class); String nextWarp = object.getProperties().get("nextWarp", String.class); String id = object.getProperties().get("ID", String.class); String condition = object.getProperties().get("warp", String.class); boolean instant = false; //instant property must have a constant tile offset to ensure that the player //doesn't constantly bounce between levels if(object.getProperties().get("instant")!=null) instant = true; int warpID = Integer.parseInt(id); int nextID = Integer.parseInt(nextWarp); Warp w = new Warp(this, next.replaceAll(" ", ""), warpID, nextID, rect.x+rect.width/2f, rect.y+rect.height/2-Vars.TILE_SIZE*(9f/80f), rect.width, rect.height); w.setCondition(condition); w.setInstant(instant); warps.add(w); } } } } return warps; }
32b15526-4a32-4b46-974c-6ac2a537c172
5
public Object [][] getDatos(){ Object[][] data = new String[getCantidadElementos()][colum_names.length]; //realizamos la consulta sql y llenamos los datos en "Object" try{ if (colum_names.length>=0){ r_con.Connection(); String campos = colum_names[0]; for (int i = 1; i < colum_names.length; i++) { campos+=","; campos+=colum_names[i]; } String consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))"); PreparedStatement pstm = r_con.getConn().prepareStatement(consulta); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ for (int j = 0; j < colum_names.length; j++) { data[i][j] = res.getString(j+1); } i++; } res.close(); } } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } return data; }
932ab287-a3b9-4870-be65-f1ed39107f2b
9
public static void startupWebtoolsSystem() { synchronized (Stella.$BOOTSTRAP_LOCK$) { if (Stella.currentStartupTimePhaseP(0)) { if (!(Stella.systemStartedUpP("stella", "/STELLA"))) { StartupStellaSystem.startupStellaSystem(); } } if (Stella.currentStartupTimePhaseP(1)) { Module.defineModuleFromStringifiedSource("/STELLA/XML-OBJECTS", "(:LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"xml_objects\" :JAVA-PACKAGE \"edu.isi.webtools.objects.xml_objects\" :CASE-SENSITIVE? TRUE :INCLUDES (\"STELLA\") :CODE-ONLY? TRUE)"); Module.defineModuleFromStringifiedSource("/STELLA/XML-OBJECTS/SOAP-ENV", "(:LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"soap_env\" :JAVA-PACKAGE \"edu.isi.webtools.objects.soap_env\" :CASE-SENSITIVE? TRUE :INCLUDES (\"XML-OBJECTS\") :NAMESPACE? TRUE :CODE-ONLY? TRUE)"); Module.defineModuleFromStringifiedSource("/STELLA/XML-OBJECTS/XSD", "(:LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"xmlschema\" :JAVA-PACKAGE \"edu.isi.webtools.objects.xmlschema\" :CASE-SENSITIVE? TRUE :INCLUDES (\"XML-OBJECTS\") :NAMESPACE? TRUE)"); Module.defineModuleFromStringifiedSource("/STELLA/XML-OBJECTS/XSI", "(:LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"xmlschemainstance\" :JAVA-PACKAGE \"edu.isi.webtools.objects.xmlschemainstance\" :CASE-SENSITIVE? TRUE :INCLUDES (\"XML-OBJECTS\") :NAMESPACE? TRUE)"); Module.defineModuleFromStringifiedSource("/STELLA/XML-OBJECTS/APACHE-SOAP", "(:LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"apachesoap\" :JAVA-PACKAGE \"edu.isi.webtools.objects.apachesoap\" :CASE-SENSITIVE? TRUE :INCLUDES (\"XML-OBJECTS\") :NAMESPACE? TRUE)"); Module.defineModuleFromStringifiedSource("/HTTP", "(:USES (\"STELLA\") :LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"http\" :JAVA-PACKAGE \"edu.isi.webtools.http\" :CODE-ONLY? TRUE)"); Module.defineModuleFromStringifiedSource("/SOAP", "(:USES (\"STELLA\" \"SOAP-ENV\" \"HTTP\") :LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"http\" :JAVA-PACKAGE \"edu.isi.webtools.soap\" :CODE-ONLY? TRUE)"); Module.defineModuleFromStringifiedSource("/HTTP/WEBTOOLS", "(:INCLUDES (\"HTTP\" \"SOAP\") :LISP-PACKAGE \"STELLA\" :CPP-PACKAGE \"webtools\" :JAVA-PACKAGE \"edu.isi.webtools\" :CODE-ONLY? TRUE)"); } { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/HTTP/WEBTOOLS", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { Webtools.SYM_WEBTOOLS_STARTUP_WEBTOOLS_SYSTEM = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-WEBTOOLS-SYSTEM", null, 0))); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("STARTUP-WEBTOOLS-SYSTEM", "(DEFUN STARTUP-WEBTOOLS-SYSTEM () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.StartupWebtoolsSystem", "startupWebtoolsSystem", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Webtools.SYM_WEBTOOLS_STARTUP_WEBTOOLS_SYSTEM); KeyValueList.setDynamicSlotValue(function.dynamicSlots, edu.isi.webtools.http.Http.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("StartupWebtoolsSystem"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/HTTP/WEBTOOLS"))))); { int phase = Stella.NULL_INTEGER; int iter006 = 0; int upperBound007 = 9; for (;iter006 <= upperBound007; iter006 = iter006 + 1) { phase = iter006; Stella.$STARTUP_TIME_PHASE$ = phase; _StartupHttpClient.startupHttpClient(); _StartupHttpServer.startupHttpServer(); _StartupSessions.startupSessions(); edu.isi.webtools.objects.xml_objects._StartupXmlObject.STARTUP_XML_OBJECT(); edu.isi.webtools.objects.xmlschema._StartupXmlSchema.STARTUP_XML_SCHEMA(); edu.isi.webtools.objects.xmlschemainstance._StartupXmlSchemaInstance.STARTUP_XML_SCHEMA_INSTANCE(); edu.isi.webtools.objects.apachesoap._StartupApacheSoap.STARTUP_APACHE_SOAP(); _StartupSoapEnv.STARTUP_SOAP_ENV(); edu.isi.webtools.objects.xml_objects._StartupMarshaller.STARTUP_MARSHALLER(); _StartupSoap.startupSoap(); } } Stella.$STARTUP_TIME_PHASE$ = 999; } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } }
750817e5-f10a-473d-99f2-96f1c2cbd892
2
public static boolean isSection(String line){ if(line.charAt(0) == '[' && line.charAt(line.length() - 1) == ']'){ return true; } return false; }
fb6e3c7b-3cac-4190-af1f-0bf3e16cab80
3
public String next() { if(console) advance(); String ret = token; String temp = line; if(!console) advance(); if(temp.equals(line)) line = line.substring(ret.length()).trim(); return ret; }
751a7982-b5ef-4c6c-9bff-8777708cd7ab
0
@Override public User getUser() { return user; }
2df09fd0-7145-4c9e-9a4f-0c29a94030a4
4
@Override public void run() { try { this.out = new DataOutputStream(socket.getOutputStream()); this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "US-ASCII")); finishFlag = false; while(!finishFlag) { if(in.ready()) { processRequest(readFromClient()); } else { Thread.sleep(100); } while(gameID != null) { Thread.sleep(100); } } } catch(IOException | InterruptedException e) { System.out.println("Lost connection with " + nickname + " (" + socket.getInetAddress() + ")"); } close(); }
1abfcd24-f5a8-4298-8c65-d08f103de13e
7
public void addLocus(Locus newLocus) throws Exception { double tolerance = 1.0e-7; newLocus.setChrom(this); if (newLocus.getPosition()<headPos) { if (newLocus.getPosition()<headPos-tolerance) { throw new Exception("addLocus: position invalid"); } else { newLocus.position = headPos; } } if (newLocus.getPosition()>tailPos) { if (newLocus.getPosition()>tailPos+tolerance) { throw new Exception("addLocus: position invalid"); } else { newLocus.position = tailPos; } } if (locus.isEmpty()) locus.add(newLocus); else { int index = 0; Locus loc = locus.get(index); while (index<locus.size() && locus.get(index).getPosition()<= newLocus.getPosition()) { index++; } locus.add(index, newLocus); } } //addLocus
71596a62-8e6b-4d2c-9c87-5e77a09e9c02
3
private void executeRemoving() { if (action.contains("rooms")) { } else if (action.contains("corridors")) { } else if (action.contains("inner yards")) { } }
358fa483-1417-46a2-a493-40f1476f1870
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(presentar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(presentar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(presentar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(presentar.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 presentar().setVisible(true); } }); }
ed6e9f0e-cfaf-43ed-bbbe-c3c366dbf94d
8
public void optimizeParam(int numItns) { assert wordTopicHist != null; // update histograms int njMax = wordTopicCountsNorm[0]; for (int j=1; j<T; j++) if (wordTopicCountsNorm[j] > njMax) njMax = wordTopicCountsNorm[j]; wordTopicNormHist = new int[njMax + 1]; for (int j=0; j<T; j++) wordTopicNormHist[wordTopicCountsNorm[j]]++; // optimize hyperparameters for (int i=0; i<numItns; i++) { double denominator = 0.0; double currentDigamma = 0.0; for (int n=1; n<wordTopicNormHist.length; n++) { currentDigamma += 1.0 / (paramSum + n - 1); denominator += wordTopicNormHist[n] * currentDigamma; } paramSum = 0.0; for (int w=0; w<W; w++) { double oldParam = param[w]; param[w] = 0.0; currentDigamma = 0; for (int n=1; n<wordTopicHist[w].length; n++) { currentDigamma += 1.0 / (oldParam + n - 1); param[w] += wordTopicHist[w][n] * currentDigamma; } param[w] *= oldParam / denominator; if (param[w] == 0.0) param[w] = 1e-10; paramSum += param[w]; } } }
ca507a64-80b0-436a-9cfe-47b8a25ca1d1
0
public void mouseReleased(MouseEvent e) { }
a9d1456d-4487-4f2b-b269-b91a44f86a0b
2
private void reloadBoardType(BoardTypeEnum myBoardType) { String[] boardTypes = comboBoard.getItems(); String label = myBoardType.getLabel(); for (int index = 0; index < boardTypes.length; index++) { if (label.equals(boardTypes[index])) { comboBoard.select(index); break; } } }
acac9198-c4b4-47d8-a689-859bc17c132c
5
public static List<Integer> makeEratosthenesSieve() { List<Integer> primes = new ArrayList<Integer>(); int upperBound = 10000; int upperBoundSquareRoot = (int) Math.sqrt(upperBound); boolean[] isComposite = new boolean[upperBound + 1]; for (int m = 2; m <= upperBoundSquareRoot; m++) { if (!isComposite[m]) { primes.add(m); for (int k = m * m; k <= upperBound; k += m) isComposite[k] = true; } } for (int m = upperBoundSquareRoot; m <= upperBound; m++) if (!isComposite[m]) primes.add(m); // 25 liczb pierwszych < 100 primes = primes.subList(25, primes.size()); return getTenPrimes(primes); }
f3912f6c-5484-4bac-8bd3-10f916ef1ce4
8
public boolean inDuelArena() { if((absX > 3322 && absX < 3394 && absY > 3195 && absY < 3291) || (absX > 3311 && absX < 3323 && absY > 3223 && absY < 3248)) { return true; } return false; }
1317f88a-dac3-48c8-8355-c17be5604a3e
2
@Override //Disparado quando a tag de inicio eh encontrada public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String tipo = getTipo(); if(tipo.equals("getCPU")){ switch(qName.toLowerCase()){ //tag atual. Ex.: <host...> case "host": doc = new Tag(); //Cria um novo objeto para guardar o valor doc.name = attributes.getValue("name"); //Ex.: <host ... service="..." .../> //lista.add(doc.name); //System.out.println("\tHOST_NAME:\t" + doc.name); //System.out.println("\tSERVICE:\t" + doc.service); break; default: break; }//fim do switch }//fim if }//fim startElement
0c48c93b-70ca-4645-83ec-065be1af21e3
0
public void func() { System.out.println(this + ".func() : " + data); }
ff188d01-f6b0-425b-8fae-d598fea213ec
3
public static Item[] getSortedList() { Item[] inventoryList = Survivalist.getCurrentGame().getInventory().clone(); Item tempItem; for(int i = 0; i < inventoryList.length - 1; i++) { for (int j = i + 1; j < inventoryList.length; j++) { if(inventoryList[i].getDescription().compareToIgnoreCase(inventoryList[j].getDescription()) > 0) { tempItem = inventoryList[i]; inventoryList[i] = inventoryList[j]; inventoryList[j] = tempItem; } } } //sort list //return list return inventoryList; }
5cd263dd-8a06-463b-96c8-b4cee74f8834
0
public void mouseExited(MouseEvent e) { }
009e381a-403e-4d4e-a58c-d5934108b378
3
private static ArrayList<File> files(File dir) { final ArrayList<File> files = new ArrayList<File>(); if (!dir.isDirectory()) throw new IllegalArgumentException("dir Isn't a Directory! " + dir); for (int i = 0; i < dir.listFiles().length; i++) { if (dir.listFiles()[i].isDirectory()) { files.addAll(files(dir.listFiles()[i])); } files.add(dir.listFiles()[i]); } return files; }
a34d0e10-86a4-4afe-984d-a5cd66cc33d2
9
public static void turn (char[][] game, int player){ int x, y; //read in x & y coordinates boolean valid_coord = false; while (!valid_coord){ Scanner in = new Scanner(System.in); System.out.println("Player " + player); System.out.println("Please enter your x coordinate: "); x = in.nextInt(); System.out.println("Please enter your y coordinate: "); y = in.nextInt(); //check for valid coordinates if ((x > 2) || (x < 0)|| (y > 2) || (y < 0)) { valid_coord = false; System.out.println("bad coordinates. try again"); } else { //you have valid coordinates & now check the grid if ((game[x][y] == 'X') || (game[x][y] == 'O')){ valid_coord = false; System.out.println("the square is already filled! try again"); } else{ if (player == 1) { game[x][y] = 'X'; squares++; } else { //it's player 2 duh game[x][y] = 'O'; squares++; } if (squares >= 5) { check_3(player, game); } valid_coord = true; } } } }
a8cf6629-70fd-466c-bdaf-c0c9038f5971
7
protected void validateField() throws Exception { // do some type checking here if (m_fieldDefs != null) { Attribute a = getFieldDef(m_fieldName); if (a == null) { throw new Exception("[FieldRef] Can't find field " + m_fieldName + " in the supplied field definitions"); } if ((m_opType == FieldMetaInfo.Optype.CATEGORICAL || m_opType == FieldMetaInfo.Optype.ORDINAL) && a.isNumeric()) { throw new IllegalArgumentException("[FieldRef] Optype is categorical/ordinal but matching " + "parameter in the field definitions is not!"); } if (m_opType == FieldMetaInfo.Optype.CONTINUOUS && a.isNominal()) { throw new IllegalArgumentException("[FieldRef] Optype is continuous but matching " + "parameter in the field definitions is not!"); } } }
b23ca1b1-64a8-4731-8e9a-383ad79959ae
2
public void addFormVotingUser(int userId, int formId) throws ErrorAddingUserException { try { String q = "insert into ValidVoter values(?, ?);"; PreparedStatement st = conn.prepareStatement(q); st.setInt(1, userId); st.setInt(2, formId); st.executeUpdate(); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch(Exception e2) { e2.printStackTrace(); } throw new ErrorAddingUserException(); } }
e240d2bc-187a-4dc0-bb71-094b6f7d9d0c
9
@EventHandler public void onChat(PlayerChatEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); ChatMode chatMode = ruChat.modes.get(player); boolean isGlobal = event.getMessage().startsWith("!") && event.getMessage().length() > 1; boolean isSale = event.getMessage().startsWith("#") && event.getMessage().length() > 1; if (isSale) { event.setMessage(event.getMessage().substring(1)); Utils.saleMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [S]: %2$s"); return; } if (isGlobal) { event.setMessage(event.getMessage().substring(1)); Utils.globalMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [G]: %2$s"); return; } if (chatMode == ChatMode.GLOBAL) { Utils.globalMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [G]: %2$s"); return; } if (chatMode == ChatMode.PRIVATE) { Utils.privateMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [P]: %2$s"); return; } if (chatMode == ChatMode.SALE) { Utils.saleMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [S]: %2$s"); return; } if (chatMode == ChatMode.HELP) { Utils.helpMessage(player, event.getMessage()); event.getRecipients().clear(); event.setFormat("%1$s [H]: %2$s"); return; } }
a974b708-08b2-4d54-a374-d02ca9062f73
1
@Override public boolean register(Game g, Rack r) { super.register(g, r); no_progress = g.rack_size*2; return random.register(g, r) && learner.register(g, r); }
3c9d259a-521b-412a-ac62-c8158b2be93b
2
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { final XYDataset dataset = studyDatasetBaseLyon(); final JFreeChart chart = createSimpleChart(dataset); final ChartPanel chartPanel = new ChartPanel(chart); jPanel2.removeAll(); jPanel2.add(chartPanel); jPanel2.repaint(); } catch (IOException ex) { Logger.getLogger(NEATFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(NEATFrame.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed
56f28cfb-eade-43a4-b617-8d619aa7d149
3
@Override public boolean createTable(String query) { Statement statement = null; try { if (query.equals("") || query == null) { this.writeError("SQL Create Table query empty.", true); return false; } statement = connection.createStatement(); statement.execute(query); return true; } catch (SQLException ex) { this.writeError(ex.getMessage(), true); return false; } }
6921e62d-4e14-42c6-8fa8-0fc1dda61127
7
public static boolean setNewLeader(String[] args, CommandSender s){ //Various checks if(Util.isBannedFromGuilds(s) == true){ //Checking if they are banned from the guilds system s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error."); return false; } if(!s.hasPermission("zguilds.player.setnewleader")){ //Checking if they have the permission node to proceed s.sendMessage(ChatColor.RED + "You lack sufficient permissions to set a new guild leader. Talk to your server admin if you believe this is in error."); return false; } if(!Util.isInGuild(s) == true){ //Checking if they're already in a guild s.sendMessage(ChatColor.RED + "You need to be in a guild to use this command."); return false; } if(args.length > 2 || args.length == 1){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "Incorrectly formatted guild Set New Leader command! Proper syntax is: \"/guild setnewleader <player name>\""); return false; } if(Util.isGuildLeader(s.getName()) == false){ //Checking if the player is the guild leader s.sendMessage(ChatColor.RED + "You need to be the guild leader to use that command."); return false; } targetPlayersName = args[1].toLowerCase(); targetPlayersGuild = Main.players.getString("Players." + targetPlayersName + ".Current_Guild"); sendersPlayerName = s.getName().toLowerCase(); sendersGuild = Main.players.getString("Players." + sendersPlayerName + ".Current_Guild"); defaultGuildRank = Main.guilds.getInt("Guilds." + sendersGuild + ".New_Member_Starting_Rank"); if(!sendersGuild.matches(targetPlayersGuild)){ //Checking if the player is the guild leader s.sendMessage(ChatColor.RED + "That player isn't in the same guild as you, you can't set them as your guild leader!"); return false; } Main.players.set("Players." + sendersPlayerName + ".Guild_Leader", false); Main.players.set("Players." + targetPlayersName + ".Guild_Leader", true); Main.players.set("Players." + sendersPlayerName + ".Current_Rank", defaultGuildRank); Main.players.set("Players." + targetPlayersName + ".Current_Rank", 10); s.sendMessage(ChatColor.DARK_GREEN + "You declared the user " + targetPlayersName + " as the new guild leader of " + sendersGuild + "."); Main.saveYamls(); return true; }
aa10e6a1-70ed-4455-aab3-97b7128e38e1
2
public CharSequence getNameSignature() { String stereotypes = Stereotypes.toSignature(this.stereotypes); if(stereotypes!=null && !stereotypes.isEmpty()) return stereotypes + " " + className; return className; }
785eb9a6-dd96-4665-8009-4a897264ab21
7
public static Territory[] getTerritories(String mapName) throws IOException{ File file = new File("WarbornData/maps/" + mapName + ".txt"); LineNumberReader lnr = new LineNumberReader(new FileReader(file)); lnr.skip(file.length()-1); int lines = lnr.getLineNumber()+1; BufferedReader in = new BufferedReader(new FileReader(file)); Territory[] territories = new Territory[lines]; String[][] connectionsNameList = new String[lines][lines]; String lineToRead = in.readLine(); for(int i = 0; lineToRead != null; i++){ String[] territoryNames = lineToRead.split(":"); territories[i] = new Territory(territoryNames[FIRSTHALF], i); String[] connectionsName = new String[territoryNames[1].split(";").length+1]; String[] namesToInsert = territoryNames[SECONDHALF].split(";"); connectionsName[TERRITORYNAME] = territoryNames[FIRSTHALF]; for(int j = 1; j < connectionsName.length; j++){ connectionsName[j] = namesToInsert[j-1]; } connectionsNameList[i] = connectionsName; lineToRead = in.readLine(); } for(int x = 0; x < connectionsNameList.length; x++){ for(int y = 1; y < connectionsNameList[x].length; y++){ if(connectionsNameList[x][y] == null){ break; } for(int z = 0; z < territories.length; z++){ if(connectionsNameList[x][y].equalsIgnoreCase(territories[z].getName())){ territories[x].addConnection(territories[z]); } } } } return territories; }
5faf3119-5118-4b40-865c-c1e2c2fd829b
5
@Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(double1); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((doubleObject == null) ? 0 : doubleObject.hashCode()); result = prime * result + Float.floatToIntBits(float1); result = prime * result + ((floatObject == null) ? 0 : floatObject.hashCode()); result = prime * result + int1; result = prime * result + ((integerObject == null) ? 0 : integerObject.hashCode()); result = prime * result + (int) (long1 ^ (long1 >>> 32)); result = prime * result + ((longObject == null) ? 0 : longObject.hashCode()); result = prime * result + ((string1 == null) ? 0 : string1.hashCode()); return result; }
aade8a15-0fd7-4a83-ac2d-d7065fe65a1e
7
private DataTelegram getDataTelegram(final long maximumWaitingTime, byte telegramType) { long waitingTime = 0, startTime = System.currentTimeMillis(); long sleepTime = 10; while(waitingTime < maximumWaitingTime) { try { synchronized(_syncSystemTelegramList) { if(_disconnecting) throw new RuntimeException("Verbindung zum Datenverteiler wurde unterbrochen"); _syncSystemTelegramList.wait(sleepTime); if(sleepTime < 1000) sleepTime *= 2; DataTelegram telegram = null; ListIterator iterator = _syncSystemTelegramList.listIterator(0); while(iterator.hasNext()) { telegram = (DataTelegram)iterator.next(); if(telegram != null) { // in der LinkedList können theoretisch null-Objekte vorkommen if(telegram.getType() == telegramType) { iterator.remove(); return telegram; } else { System.out.println(telegram.parseToString()); } } } // while } waitingTime = System.currentTimeMillis() - startTime; } catch(InterruptedException ex) { _debug.warning("Thread wurde unterbrochen", ex); break; } } // while return null; }
033605bb-8ccc-4c85-b2e8-69c263dff9eb
9
static private final int jjMoveStringLiteralDfa4_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0); return 4; } switch(curChar) { case 71: return jjMoveStringLiteralDfa5_0(active0, 0x20L); case 95: return jjMoveStringLiteralDfa5_0(active0, 0x1000L); case 97: return jjMoveStringLiteralDfa5_0(active0, 0x880L); case 98: return jjMoveStringLiteralDfa5_0(active0, 0x40L); case 101: return jjMoveStringLiteralDfa5_0(active0, 0x100L); case 111: return jjMoveStringLiteralDfa5_0(active0, 0x200L); case 115: return jjMoveStringLiteralDfa5_0(active0, 0x2400L); default : break; } return jjStartNfa_0(3, active0); }
9fb2a09d-101a-4691-adf2-58f1bc7579b0
9
public ArrayList<Ticket> createTicketArrayListByQueue(int queueType) { ArrayList<Ticket> result = new ArrayList<Ticket>(); ResultSet rs = null; PreparedStatement statement = null; try { String sqlString; switch (queueType) { case 0: sqlString = "select * from Tickets where Pending=true"; break; case 1: sqlString = "select * from Tickets where Active=true"; break; case 2: sqlString = "select * from Tickets where Closed=true"; break; default: sqlString = "select * from Tickets where Pending=true"; break; } statement = conn.prepareStatement(sqlString); rs = statement.executeQuery(); while (rs.next()) { int dbid; int workerid; String subject; boolean pending; boolean active; boolean closed; dbid = rs.getInt("TicketID"); workerid = rs.getInt("WorkerID_FK"); subject = rs.getString("Subject"); pending = rs.getBoolean("Pending"); active = rs.getBoolean("Active"); closed = rs.getBoolean("Closed"); Ticket temp = ModelFactory.createTicket(dbid, workerid, subject, pending, active, closed); result.add(temp); } } catch(SQLException e){ e.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (Exception e) {} try { if (statement != null) statement.close(); } catch (Exception e) {} } return result; }
4e5e3eb4-2ff5-4945-9713-369cdaa12a61
0
private String replacePi(String calculation) { return calculation.replaceAll("pi", Double.toString(Math.PI)); }
1ca017b2-635d-4665-857f-705790ebc512
0
public String getId() { return id; }
c00d3dc8-7ea3-4746-8c09-29d8b8563db4
0
@Test public void validationDoubleWithDoublePositiveTest() { view.getTimeStepTextField().setText("11.6"); view.getTimeStepTextField().getInputVerifier().verify(view.getTimeStepTextField()); assertTrue(view.getDrawButton().isEnabled()); }
a45d851a-b8f7-4bd2-a3d8-8569a3d1f58e
7
@Override public boolean perform(final Context context) { // Example: /<command> format[ get][ <Player>] int position = 2; if (context.arguments.size() >= 2 && !context.arguments.get(1).equalsIgnoreCase(this.name)) position = 1; OfflinePlayer target = Parser.parsePlayer(context, position); if (target == null && context.sender instanceof OfflinePlayer) target = (OfflinePlayer) context.sender; if (target == null) { Main.messageManager.send(context.sender, "Unable to determine player", MessageLevel.SEVERE, false); return false; } // Parse target player name String targetName = target.getName(); if (target.getPlayer() != null) targetName = target.getPlayer().getName(); // Verify requester has permission for player if (!Timestamp.isAllowed(context.sender, this.permission, targetName)) { Main.messageManager.send(context.sender, "You are not allowed to use the " + this.getNamePath() + " action of the " + context.label + " command for " + target.getName(), MessageLevel.RIGHTS, false); return true; } final Recipient recipient = Timestamp.getRecipient(target); Main.messageManager.send(context.sender, "Timestamp format for " + targetName + ": " + TimestampFormatGet.message(recipient), MessageLevel.STATUS, false); return true; }
6f28ba44-14c1-4ae9-824d-52a5fd593e78
3
public void visitCheckExpr(final CheckExpr expr) { if (expr instanceof ZeroCheckExpr) { visitZeroCheckExpr((ZeroCheckExpr) expr); } else if (expr instanceof RCExpr) { visitRCExpr((RCExpr) expr); } else if (expr instanceof UCExpr) { visitUCExpr((UCExpr) expr); } }
44c08255-656c-4a85-a2b6-e62142f7ac32
8
public void handleKey(int action){ if(action<0 || current == 0){ if(action==current) current=0; return; } switch(current){ case InteractivePanel.LEFT: properties.setLeftCtrl(action); leftCtrl.setText(KeyEvent.getKeyText(action)); break; case InteractivePanel.RIGHT: properties.setRightCtrl(action); rightCtrl.setText(KeyEvent.getKeyText(action)); break; case InteractivePanel.UP: properties.setUpCtrl(action); upCtrl.setText(KeyEvent.getKeyText(action)); break; case InteractivePanel.SHOOT: properties.setShootCtrl(action); shootCtrl.setText(KeyEvent.getKeyText(action)); break; case InteractivePanel.POWER: properties.setPowerCtrl(action); powerCtrl.setText(KeyEvent.getKeyText(action)); break; } current =0; repaint(); }
bdc06262-4b54-4e73-8bbd-b416f40807eb
9
public static void registerSlot(Slot slot, String targetSignal, Class<?>[] params) throws IllegalArgumentException, InvalidReturnTypeException { SignalStructure struct = linker.get(targetSignal); if (params == null) { if (struct.getInvokerParameters() != null) { throw new IllegalArgumentException("Error: The argument is not expected to be null"); } } else { if (struct.getInvokerParameters().length != params.length) { throw new IllegalArgumentException ("Error: The entered number of arguments: " + params.length + " does not equal the expected number: " + struct.getInvokerParameters().length); } for (int i = 0; i < params.length; i++) { if (struct.getInvokerParameters()[i] != params[i]) { throw new IllegalArgumentException("Error: The entered object of class: " + struct.getInvokerParameters()[i] + " does not match the expected class: " + params[i]); } } } if (slot.getReturnType() == null) { if (struct.getReturnType() != null) { throw new InvalidReturnTypeException("Error: The argument is not expected to be null"); } } else { if (slot.getReturnType() != struct.getReturnType()) { throw new InvalidReturnTypeException("Error: The return type: " + slot.getReturnType() + " does not match the expected return type: " + struct.getReturnType()); } } linker.get(targetSignal).getRegisteredSlots().add(slot); }
f6291e0c-b1e9-4604-ac7a-4e1d232551e4
3
public void processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) { if((inOff + len) > in.length) { throw new RuntimeException("output buffer terlalu sedikit"); } if((outOff + len) > out.length) { throw new RuntimeException("out put buffer terlalu sedikit"); } for(int i = 0; i < len; i++) { x = (x + 1) & 0xff; y = (engineState[x] + y) & 0xff; //swap byte tmp = engineState[x]; engineState[x] = engineState[y]; engineState[y] = tmp; //xor out[i + outOff] = (byte) (in[i + inOff] ^ engineState[(engineState[x] + engineState[y]) & 0xff]); } }
f72c02bc-5e3f-4aee-af5f-5790ac0c084a
2
public void input(char input){ if(!running){ running=true; player.charInput(input); for(Enemy e: enimies){ //e.takeTurn(); } running=false; } }
460b0afa-fc16-4a68-b95f-384607651a75
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; }
1659dd05-1d14-49d0-80b9-ea32c032c5f2
5
public JdbcQueryTaskParameters(String sql, int fetchSize, boolean returnKeys, PreparedStatementCallback<?> action, Object... args) { int hashCode = 0; this.sql = sql; hashCode += sql.hashCode(); this.fetchSize = fetchSize; hashCode += fetchSize; this.returnKeys = returnKeys; hashCode += (returnKeys ? 1231 : 1237); this.action = action; this.args = args; if(args != null) { for(Object arg : args) { hashCode += (arg == null? 0 : arg.hashCode()); } } this.hashCode = 17 + 23 * hashCode; }
0a0c25f6-fd8b-4f45-aad9-cf0bfccec62c
7
public boolean Hand1BeatsHand2(String hand1, String hand2) { Hand firstHand = new Hand(hand1); Hand secondHand = new Hand(hand2); PokerHandValue firstHandRank = GetHandRank(firstHand); PokerHandValue secondHandRank = GetHandRank(secondHand); while (firstHandRank.compareTo(secondHandRank) == 0 && !firstHand.toString().equals("")) { for (int i = 0; i < firstHandRank.Value.length(); i++) { firstHand = firstHand.RemoveAllCardsOfValue(firstHandRank.Value.substring(i, i + 1)); secondHand = secondHand.RemoveAllCardsOfValue(firstHandRank.Value.substring(i, i + 1)); } if(firstHand.toString().equals("") || secondHand.toString().equals("")) return false; firstHandRank = GetHandRank(firstHand); secondHandRank = GetHandRank(secondHand); } return !(firstHand.toString().equals("") && secondHand.toString().equals("")) && firstHandRank.compareTo(secondHandRank) > 0; }
d9dc9e98-72a0-4036-9700-29214b0c5167
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaEstoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaEstoque.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 TelaEstoque().setVisible(true); } }); }
b57caf2c-9c62-42da-bdf0-617051ce721f
3
public ArrayList<HashMap<String, String>> getOxima(int id){ /* * epistefei ta stoixia enos sugkekrimenou oximatos */ ArrayList<HashMap<String, String>> oxima=new ArrayList<HashMap<String, String>>(); HashMap<String, String> map = new HashMap<String, String>(); try { pS = conn.prepareStatement("SELECT * FROM oximata WHERE id=?"); pS.setInt(1, id); rs=pS.executeQuery(); if(rs.next()){ map.put("id", id+""); map.put("diadromi", rs.getString("diadromi")); oxima.add(map); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return oxima; }
dd929af5-a779-497d-8b26-8459a77bf92a
1
public static InputStream loadResourceAsStream(String resourcePath) { if(resourcePath.startsWith("/")){ return ResourceLoader.class.getResourceAsStream(resourcePath); }else{ System.err.println("A resource path must(!) begin with a \"/\""); return null; } }
53da3d16-596f-4e3b-afbc-cde876b42684
4
@Override public Card chooseCard(Player player, Card[] cards, GameState state) { //If there's only one choice, we have no choice but to do it if(cards.length == 1) { return cards[0]; } int alpha = Integer.MIN_VALUE; int beta = Integer.MAX_VALUE; Card choice = null; ArrayList<Color> playerList = new ArrayList<Color>(); for(Player p : state.getPlayerList()) { playerList.add(p.getFaction()); } playerList.remove(player.getFaction()); //We perform alpha beta search on each state to see if //it's the best for(Card card : cards) { ArrayList<Card> cardChoices = new ArrayList<Card>(); cardChoices.add(card); int check = alphabetaCardPicking(new GameState(state), new ArrayList<Color>(playerList), cardChoices, alpha, beta, player.getFaction(), maxDepth); System.out.println("\ncheck: " + check); //Check to see if this state is better if(check > alpha) { alpha = check; choice = card; } } return choice; }
32f4a4d9-293e-496b-ab3c-a9f58e8cd5aa
0
public int getS1() { return this.state1; }
67e59c41-2705-48a2-8e26-9494a03cc6fe
5
final void method1228(int i, int i_63_, int i_64_, int[] is, boolean bool, int[] is_65_) { try { if ((anInt2103 ^ 0xffffffff) != (i_64_ ^ 0xffffffff)) anInt2103 = i_64_; anIntArray2092 = is; if (i_63_ <= 54) anIntArray2092 = null; ((Class154) this).anIntArray2095 = is_65_; anInt2090++; ((Class154) this).anInt2093 = i; ((Class154) this).aBoolean2100 = bool; method1234(-25); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("oo.F(" + i + ',' + i_63_ + ',' + i_64_ + ',' + (is != null ? "{...}" : "null") + ',' + bool + ',' + (is_65_ != null ? "{...}" : "null") + ')')); } }
901ea4f2-459f-4af5-b50b-80529a298e09
8
public Expr array_length(Context ctx, HashMap<String, Expr> symbolTable) throws Z3Exception{ Expr ret = null; if(this.a_inputs.get(0).leaf!=null && this.a_inputs.get(0).leaf.type.equals("string") && symbolTable.containsKey(((a_string)this.a_inputs.get(0).leaf).s)){ ret = ctx.MkConst((((a_string)this.a_inputs.get(0).leaf).s+"_lastIndex"), ctx.IntSort()); } else if (this.a_inputs.get(0).leaf!=null && this.a_inputs.get(0).leaf.type.equals("a_expression") && ((a_expressionT)this.a_inputs.get(0).leaf).e.leaf!=null && ((a_expressionT)this.a_inputs.get(0).leaf).e.leaf.type.equals("string") && symbolTable.containsKey(((a_string)((a_expressionT)this.a_inputs.get(0).leaf).e.leaf).s)){ ret = ctx.MkConst((((a_string)((a_expressionT)this.a_inputs.get(0).leaf).e.leaf).s+"_lastIndex"), ctx.IntSort()); } else System.out.println("array not defined!"); return ret; }
3fec24d6-c762-4b8e-b43e-51abcdf323f0
0
public int GetBusNumber() { return busNumber; }
5205066a-a84e-47be-8416-8bc0e067c4ed
5
private void recv(SyncPDU m) { cancelTimerTask(); try { byte type = m.getType(); boolean sv = false; switch (type) { case SyncPDU.REQALL: respondSendAllItems(m); break; case SyncPDU.REQ: respondSendRequestedItems(m); break; case SyncPDU.SV: sv = true; case SyncPDU.CPI: handle(sv, m); break; default: break; } } catch (Exception e) { e.printStackTrace(); } resetTimer(TIMEOUT); }
34e2189c-4818-4e38-bbb8-53bcba715c7c
7
public static boolean checkSudoku(int[][] matrix) { ArrayList<HashSet<Integer>> rowsSets = new ArrayList<HashSet<Integer>>(9); ArrayList<HashSet<Integer>> columnsSets = new ArrayList<HashSet<Integer>>(9); ArrayList<HashSet<Integer>> subSets = new ArrayList<HashSet<Integer>>(9); for(int i = 0; i < 9; i++) { rowsSets.add(new HashSet<Integer>()); columnsSets.add(new HashSet<Integer>()); subSets.add(new HashSet<Integer>()); } for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { int num = matrix[i][j]; if(num == 0) { continue; } if(rowsSets.get(i).contains(num)) { return false; } else { rowsSets.get(i).add(num); } if(columnsSets.get(j).contains(num)) { return false; } else { columnsSets.get(j).add(num); } int subGridi = (i/3)*3 + j/3; if(subSets.get(subGridi).contains(num)) { return false; } else { subSets.get(subGridi).add(num); } } } return true; }
f29727c7-9ea0-4ee3-8803-2f84a00bf767
2
private static void dfs(int n, ArrayList<ArrayList<Integer>> g, ArrayList<Integer> results, boolean[] visited){ visited[n]=true; for(Integer neighbor:g.get(n)){ if(!visited[neighbor]){ dfs(neighbor, g, results, visited); } } results.add(n); }
6d34e696-0da5-4ca7-a887-9ae3a6821530
3
private void putInCache(String prefix, String uri) { // Not already in cache if (!uri2Prefix.containsKey(uri)) { // Find an available default namespace if (DEFAULT_NS.equals(prefix)) { int index = 0; while(prefix2Uri.containsKey(DEFAULT_NS + index)){ index++; } prefix = DEFAULT_NS + index; } prefix2Uri.put(prefix, uri); uri2Prefix.put(uri, prefix); } }
fa808c75-20d1-4683-8237-52f63a4bcf92
6
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); Class.forName("oracle.jdbc.OracleDriver") ; out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE> </TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>Total Revenue from Hotel Room Bookings\n"); out.write(" </H1>\n"); out.write("\n"); out.write(" "); Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("select Resort_id,Rate_id from Resort_Rating" ) ; out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>Resort</TH>\n"); out.write(" <TH>Rate</TH>\n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); while(resultset.next()){ out.write("\n"); out.write(" <TR>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); } out.write("\n"); out.write(" </TABLE>\n"); out.write(" </BODY>\n"); out.write("</html>\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
9e4300e0-c24a-40d0-830c-91119dcffb12
7
@Override public void paintComponent(Graphics g) { super.paintComponent(g); //------------------------------------------------------------------------------Painting the correct character if (characterChosen == 1) { g.drawImage(hero.image, heroCurrentX, heroCurrentY, 50, 50, null); } if (characterChosen == 2) { g.drawImage(hero.image2, heroCurrentX, heroCurrentY, 50, 50, null); } if (characterChosen == 3) { g.drawImage(hero.image3, heroCurrentX, heroCurrentY, 50, 50, null); } //------------------------------------------------------------------------------Drawing the coins g.drawImage(zombie.image, zombie.x, zombie.y, 50, 50, null); // Draw line to separate game field from bucket panel g.drawLine(0, 400, 500, 400); // Draw images on game field g.setColor(backgroundColor); if (coinPicked1 == true) { button1.setEnabled(false); //Grays out the button item1.x = 5000; // Moves the button offscreen (since we couldn't figure out a way to delete or un-draw the image) } else // coin has not been picked { g.drawImage(item1.image, item1.x, item1.y, 50, 50, null); rc1 = new Rectangle(item1.x, item1.y, 50, 50); } if (coinPicked2 == true) { button2.setEnabled(false); item2.x = 5000; } else { g.drawImage(item2.image, item2.x, item2.y, 50, 50, null); rc2 = new Rectangle(item2.x, item2.y, 50, 50); } if (coinPicked3 == true) { button3.setEnabled(false); item3.x = 5000; } else { g.drawImage(item3.image, item3.x, item3.y, 50, 50, null); rc3 = new Rectangle(item3.x, item3.y, 50, 50); } if (coinPicked4 == true) { button4.setEnabled(false); item4.x = 5000; } else { g.drawImage(item4.image, item4.x, item4.y, 50, 50, null); rc4 = new Rectangle(item4.x, item4.y, 50, 50); } //---------------------------------------------------------------------- }
ed17dec7-15cc-488a-aa80-ef260bd715bb
5
public static Check getInstance(int checkType) throws UnsupportedOptionsException { switch (checkType) { case XZ.CHECK_NONE: return new None(); case XZ.CHECK_CRC32: return new CRC32(); case XZ.CHECK_CRC64: return new CRC64(); case XZ.CHECK_SHA256: try { return new SHA256(); } catch (java.security.NoSuchAlgorithmException e) {} break; } throw new UnsupportedOptionsException( "Unsupported Check ID " + checkType); }
fd774d16-3fe1-473f-bbff-38c91c739ac3
3
private void loadSettings() { if (settings.containsKey(Settings.THEME)) { changeTheme((String)settings.get(Settings.THEME)); } else { changeTheme(Utils.GUITHEME.Snow.name()); } if (settings.containsKey(Settings.SCREEN_LOC_X)) { int x = ((Number)settings.get(Settings.SCREEN_LOC_X)).intValue(); int y = ((Number)settings.get(Settings.SCREEN_LOC_Y)).intValue(); setLocation(x, y); } else { // default to center: Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int sHeight = screenSize.height; int sWidth = screenSize.width; Point loc = new Point(sWidth / 2 - (getWidth() / 2), sHeight / 2 - (getHeight() / 2)); setLocation(loc); } if (settings.containsKey(Settings.SCREEN_SIZE_X)) { int x = ((Number)settings.get(Settings.SCREEN_SIZE_X)).intValue(); int y = ((Number)settings.get(Settings.SCREEN_SIZE_Y)).intValue(); setSize(x, y); } else { setSize(640, 480); } }
e05b2261-a9a3-4450-8340-b2f32560b545
3
public static EnvironmentReasonEnumeration fromString(String v) { if (v != null) { for (EnvironmentReasonEnumeration c : EnvironmentReasonEnumeration.values()) { if (v.equalsIgnoreCase(c.toString())) { return c; } } } throw new IllegalArgumentException(v); }
20191cf9-9b30-4825-a903-88cf363bbf4d
9
public void keyReleased(KeyEvent Par1) { int Key = Par1.getKeyCode(); if(currentState == State.Game) { if(Key == KeyEvent.VK_W) { Character.setVelY(0); Character.canMoveUp = true; } else if(Key == KeyEvent.VK_S) { Character.setVelY(0); Character.canMoveDown = true; } else if(Key == KeyEvent.VK_D) { Character.setVelX(0); Character.canMoveRight = true; } else if(Key == KeyEvent.VK_A) { Character.setVelX(0); Character.canMoveLeft = true; } else if(Key == KeyEvent.VK_SPACE) { canAttack = true; } else if(Key == KeyEvent.VK_F3) { Info = false; } else if(Key == KeyEvent.VK_ESCAPE) { canSwitchState = true; } else if(Key == KeyEvent.VK_K) { Character.setHealth(Character.getHealth() - 1); } } }
d24fa842-85e3-4b45-89bc-37ae1bb7deec
5
private void popAndDownload() { Downloadable downloadable; while ((downloadable = (Downloadable)this.remainingFiles.poll()) != null) { if (downloadable.getNumAttempts() > 5) { if (!this.ignoreFailures) this.failures.add(downloadable); //Launcher.getInstance().println("Gave up trying to download " + downloadable.getUrl() + " for job '" + this.name + "'"); } else { try { String result = downloadable.download(); this.successful.add(downloadable); //Launcher.getInstance().println("Finished downloading " + downloadable.getTarget() + " for job '" + this.name + "'" + ": " + result); } catch (Throwable t) { //Launcher.getInstance().println("Couldn't download " + downloadable.getUrl() + " for job '" + this.name + "'", t); this.remainingFiles.add(downloadable); } } } if (this.remainingThreads.decrementAndGet() <= 0) this.listener.onDownloadJobFinished(this); }
21017e7b-4ac1-47d0-ad26-d3db9ad9b14a
0
public Timestamp getRegtime() { return this.regtime; }
500b01e3-b8fe-4803-bd63-acb4fd9f7222
9
public boolean isDefault(aos.apib.Base o) { TrackerInfo__Tuple v = (TrackerInfo__Tuple)o; if (v.id != __def.id) return false; if (v.warningCount != __def.warningCount) return false; if (v.upload != __def.upload) return false; if (v.download != __def.download) return false; if (v.isOnline != __def.isOnline) return false; if (v.cumulativeOnlineTime != __def.cumulativeOnlineTime) return false; if (v.delay != __def.delay) return false; if (baseclasses != null && baseclasses.length == 1) return baseclasses[0].isDefault(o); return true; }
189d4382-7d0f-4a5e-94f1-ef9ca438fe8e
7
private String affectedFacialTarget(int affected) { switch(affected) { case 0: return "outer-left character"; case 1: return "inner-left character"; case 2: return "inner-right character"; case 3: return "outer-right character"; case 4: return "selected character"; case 5: return "all characters"; case 6: return "random character?"; default: return "UNKNOWN #" + affected; } }
f58d8860-8875-4c6a-b028-206e23898459
1
public void Login() throws IOException { String urlString = ""; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // client.setCookies(connection, cookieJar); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection .setRequestProperty( "Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); connection.setRequestProperty("Accept-Encoding", "gzip,deflate"); connection.setRequestProperty("Referer", "***"); connection .setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3)"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cache-Control", "no-cache"); connection.setRequestProperty("Content-Length", "64"); connection.setRequestProperty("Host", "***"); connection.setRequestProperty("Cookie", ""); String message = "number=***&passwd=***&select=cert_no&returnUrl="; System.out.println(message); OutputStream out = connection.getOutputStream(); out.write(message.getBytes()); out.close(); connection.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } }
3527d9e1-73c2-4c6c-91b8-0554c2c84430
7
public int ladderLength(String start, String end, Set<String> dict) { Queue<String> queue = new LinkedList<String>(); Set<String> visited = new HashSet<String>(); int level = 1; int lastNum = 1; int curNum = 0; queue.offer(start); visited.add(start); while(!queue.isEmpty()){ String cur = queue.poll(); lastNum--; for(int i=0; i<cur.length(); i++){ char[] curChar = cur.toCharArray(); for(char c='a'; c<='z'; c++){ curChar[i] = c; String newTmp = new String(curChar); if(newTmp.equals(end)) return level+1; if(dict.contains(newTmp) && !visited.contains(newTmp)) { curNum++; queue.offer(newTmp); visited.add(newTmp); } } } if(lastNum == 0) { lastNum = curNum; curNum = 0; level++; } } return 0; }
ec1fe9de-fe6a-4a0c-9f35-f9d41137af5b
6
private void complExpAritmetica() {//ok if (tipoDoToken[1].equals(" +")) { if (!acabouListaTokens()) { nextToken(); this.termoAritmetico(); if (!acabouListaTokens()) { nextToken(); this.complExpAritmetica(); } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } } else if (tipoDoToken[1].equals(" -")) { if (!acabouListaTokens()) { nextToken(); this.termoAritmetico(); if (!acabouListaTokens()) { nextToken(); this.complExpAritmetica(); } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } } else { System.out.println("não achei + nem -"); return; } }
bbfbaccd-25e6-4e4b-8985-47d5f884f728
9
public TTTBoard() { grid = new Grid(); ComputerPlayerMinMax computer = new ComputerPlayerMinMax(grid); computer.setType(CellType.CROSS); int firstPlayer = -1; System.out.println("Your symbol is O and computer's symbol is X."); System.out.println("Enter 0 to play first; 1 to let computer play first."); try { firstPlayer = input.nextInt(); } catch (Exception e) { System.out.println("Invalid input. Please enter either 0 or 1."); } while (firstPlayer < 0 || firstPlayer > 1) { System.out.println("Please enter either 1 or 0."); while (!input.hasNextInt()) { System.out.println("That's not a number!"); input.next(); } firstPlayer = input.nextInt(); } gameInit(firstPlayer); System.out.println("Board grid before starting the game."); grid.drawGrid(); do { playerMove(currentPlayer, computer); grid.drawGrid(); updateGameState(currentPlayer); if (currentState == GameState.CROSS_WON) { System.out.println("COMPUTER WON! TRY AGAIN!"); System.out.println("============================================"); } else if (currentState == GameState.CIRCLE_WON) { System.out.println("YOU WON! GOOD JOB!"); System.out.println("============================================"); } else if (currentState == GameState.DRAW) { System.out.println("DRAW! NICE TRY!"); System.out.println("============================================"); } currentPlayer = (currentPlayer == CellType.CROSS) ? CellType.CIRCLE : CellType.CROSS; } // keep on playing until one player wins or the game is drawn while (currentState == GameState.PLAYING); }
f4fddd89-70a3-4764-bb9b-6013d83a4f7e
1
@Override public void clearAttributes() { if (attributes != null) { this.attributes.clear(); this.isReadOnly.clear(); } }
9aed8e8f-489c-4913-ad94-6a1f9cc19120
2
public static void start(Component component, Cursor cursor) { JRootPane rootPane = SwingUtilities.getRootPane(component); if (rootPane != null) { Component glassPane = rootPane.getGlassPane(); MouseCapture capture = new MouseCapture(glassPane, component); glassPane.addMouseListener(capture); glassPane.addMouseMotionListener(capture); glassPane.addHierarchyListener(capture); if (cursor != null) { glassPane.setCursor(cursor); } MAP.put(component, capture); glassPane.setVisible(true); } }
eee958f5-86c4-4dd6-a156-a09e4098c3b3
5
public AST rStatement() throws SyntaxError { AST t; if (isNextTok(Tokens.If)) { scan(); t = new IfTree(); t.addKid(rExpr()); expect(Tokens.Then); t.addKid(rBlock()); expect(Tokens.Else); t.addKid(rBlock()); return t; } if (isNextTok(Tokens.While)) { scan(); t = new WhileTree(); t.addKid(rExpr()); t.addKid(rBlock()); return t; } if (isNextTok(Tokens.Repeat)){ scan(); t = new RepeatTree(); t.addKid(rBlock()); expect(Tokens.While); t.addKid(rExpr()); return t; } if (isNextTok(Tokens.Return)) { scan(); t = new ReturnTree(); t.addKid(rExpr()); return t; } if (isNextTok(Tokens.LeftBrace)) { return rBlock(); } t = rName(); t = (new AssignTree()).addKid(t); expect(Tokens.Assign); t.addKid(rExpr()); return t; }
686346f8-f362-4858-8c96-fd0aef951adc
0
@Test public void test_getSizeY(){ assertNotNull(pawn); assertEquals(posY, pawn.getY()); }
8b2afe38-fc75-43f0-a081-12d18b3bd253
1
public static boolean isVandalism(int s) { if(s==62977) return true; return false; }
8f8ecac8-4e6d-4312-aa87-d98d5b10a518
9
private void Ok() { if(list == null) { setList(); } if(loginTextField.getText().length() == 0) { JOptionPane.showMessageDialog(f, "Enter login"); return; } if(passTextField.getText().length() == 0) { JOptionPane.showMessageDialog(f, "Enter password"); return; } try { ConnectMethods.LogInfo info = list.Authenticate(loginTextField.getText(), passTextField.getText()); if(info == ConnectMethods.LogInfo.INCORRECT_LOGGIN) { JOptionPane.showMessageDialog(f, "Login was not found in database, check your login"); passTextField.setText(""); loginTextField.setText(""); } if(info == ConnectMethods.LogInfo.INCORRECT_PASS) { JOptionPane.showMessageDialog(f, "Incorrecn password, check your password"); passTextField.setText(""); } if(info == ConnectMethods.LogInfo.ALREADY_LOGGED) { JOptionPane.showMessageDialog(f, "User is already logged"); passTextField.setText(""); } if(info == ConnectMethods.LogInfo.CORRECT_DATA) { f.dispose(); OpenProjFrame OPFrame = new OpenProjFrame(list, loginTextField.getText()); OPFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); OPFrame.setVisible(true); } } catch (RemoteException e1) { JOptionPane.showMessageDialog(f, "Disconnect from server"); return; } catch (NullPointerException e1) { this.dispose(); LoginFrame log = new LoginFrame(); log.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); log.setVisible(true); } }
0a9614f4-4d2e-426a-983b-963c53f691b5
6
private boolean isPic(String s) { if(s.startsWith("http") && (s.contains(".jpg")||s.contains(".png")||s.contains(".bmp")||s.contains(".gif")||s.contains("jpeg"))){ return true; } else return false; }
821d3788-5f65-4563-b177-550dc6224b4c
3
public static String escapeChars(final byte... bytes) { final StringBuilder buf = new StringBuilder(); for (byte b : bytes) if (b >= 32 && b < 127) buf.append(Character.toChars(b)); else buf.append('.'); return buf.toString(); }
2af95ddc-0015-447e-bf27-7bfb873ee3e7
9
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true){ int n = sc.nextInt(); if(n==0)break; int[] a = new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); int s = a[0]; int t = a[0]; Queue<String> l = new LinkedList<String>(); for(int i=1;i<n;i++){ if(t+1==a[i])t++; else { if(s<t)l.add(s+"-"+t); else l.add(s+""); s = a[i]; t = a[i]; } } if(s<t)l.add(s+"-"+t); else l.add(s+""); boolean f = true; while(!l.isEmpty()){ if(!f)System.out.print(" "); f = false; System.out.print(l.poll()); } System.out.println(); } }
a80e234f-2449-4134-aaed-7270006d8806
7
public static void createTiles() { try { Tilelist = new ArrayList<Tile>(); SpriteSheet tiles = new SpriteSheet(PATH_TILE, TILEWIDTH, TILEHEIGHT); tiles.setFilter(SpriteSheet.FILTER_NEAREST); SpriteSheet walls = new SpriteSheet(PATH_WALL, WALLWIDTH, WALLHEIGHT); walls.setFilter(SpriteSheet.FILTER_NEAREST); Scanner in = new Scanner(new File(PATH_DATA)); String line; String tag; int x = 0, wx = 0; while (in.hasNext()) { line = in.nextLine(); if (line.contains("(")) { while (!line.contains(")")) { line = in.nextLine(); tag = line.split(":")[0]; if (tag.equals("wx")) wx = Integer.valueOf(line.split(":")[1]); if (tag.equals("x")) x = Integer.valueOf(line.split(":")[1]); } Tile t = new Tile(tiles.getSprite(x, 0)); t.setLrwall(walls.getSprite(wx, 0)); t.setLlwall(walls.getSprite(wx, 1)); Tilelist.add(t); if (LOG) System.out.println("created Tile " + x + " " + wx); } } in.close(); } catch (SlickException | FileNotFoundException e) { e.printStackTrace(); } }
29ca31da-647a-4842-8a11-4a48980460f6
8
public static TreeNode getLastCommonParent(TreeNode root, TreeNode n1, TreeNode n2) { if (root == null || n1 == null || n2 == null) { return null; } ArrayList<TreeNode> p1 = new ArrayList<TreeNode>(); boolean res1 = getNodePath(root, n1, p1); ArrayList<TreeNode> p2 = new ArrayList<TreeNode>(); boolean res2 = getNodePath(root, n2, p2); if (!res1 || !res2) { return null; } TreeNode last = null; Iterator<TreeNode> iter1 = p1.iterator(); Iterator<TreeNode> iter2 = p2.iterator(); while (iter1.hasNext() && iter2.hasNext()) { TreeNode tmp1 = iter1.next(); TreeNode tmp2 = iter2.next(); if (tmp1 == tmp2) { last = tmp1; } else { // 直到遇到非公共节点 break; } } return last; }
249e124c-8d37-41c6-b06e-1f519afccca5
7
public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { int x1 = input.nextInt(); int y1 = input.nextInt(); int x2 = input.nextInt(); int y2 = input.nextInt(); if (x1 + x2 + y1 + y2 == 0) return; int dx = x1 - x2; int dy = y1 - y2; // no moves needed (same spot) if (dx == 0 && dy == 0) { System.out.println(0); } // same column, row, diagonal, 1 move else if (dx == 0 || dy == 0 || Math.abs(dx) == Math.abs(dy)) { System.out.println(1); } // max of two moves ever else { System.out.println(2); } } }
259d444e-630f-42a9-9f44-00fefd88d94f
1
public Set<String> getURLs(String url) throws IOException { Set<String> urls = new HashSet<>(); String content = getURLContent(url); Matcher m = Pattern.compile(urlPattern).matcher(content); while (m.find()) { urls.add(m.group()); } return urls; }
c6047eb2-eab2-4178-8b61-39bf39303f50
2
public void flipHorizontal() { byte image[] = new byte[width * height]; int off = 0; for (int offY = 0; offY < height; offY++) { for (int offX = width - 1; offX >= 0; offX--) { image[off++] = pixels[offX + offY * width]; } } pixels = image; offsetX = trimWidth - width - offsetX; }
54878e9f-6c43-4441-8651-58d9b7777c98
2
public ArrayList<ArrayList<Integer>> permute(int[] num) { LinkedList<int[]> mappers = search(num.length); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for (int[] mapper : mappers) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for (int i : mapper) { tmp.add(num[i]); } result.add(tmp); } return result; }
d6e36893-76b0-4525-9d4a-cbdfee89125e
4
public static VoteCast closePolls(){ open = false; Broadcast.vote("Voting for next map is now closed."); VoteCast win; if(A >= B && A >= R) win = VoteCast.A; else if(B > A && B >= R) win = VoteCast.B; else win = VoteCast.R; HotbarManager.clearAll(); return win; }
8a67558c-e3f5-40f1-9006-9d72fccbaee6
1
@Test public void clone_test() { try{ double []mat1= {1.0,2.0,3.0,1.0}; double result[] = Vector.clone(mat1); double exp[]= {1.0,2.0,3.0,1.0}; Assert.assertArrayEquals(exp, result, 0); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
b83251fb-194b-4b43-9a03-3418bcb482e4
2
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); if (this.troveKey == null){ Properties props = new Properties(); try{ // properties file should be put here (not included in repo) props.load(getServletContext().getResourceAsStream("/WEB-INF/aditl.properties")); this.troveKey = props.getProperty("trovekey"); } catch (Exception e){ out.println(e.getMessage()); } } String year = request.getParameter("year"); // use newspapers api to get key terms around date/location // out.println("{year: '" + year + "'}"); }
dea82c5b-7445-4458-aab8-8c88afb448c6
3
public List<List<Object>> calculateMedianString() { List<List<Object>> bestKMer = new ArrayList<List<Object>>(); List<String> allKMers = calculateAllKMers(); int smallestHammingDistance = allKMers.size(); for (String pattern : allKMers) { List<Object> helpList = new ArrayList<Object>(); int totalHammingDistance = calculateTotalHammingDistance(pattern); if (totalHammingDistance < smallestHammingDistance) { if (bestKMer.size() > 0) { bestKMer.remove(0); helpList.add(totalHammingDistance); helpList.add(pattern); bestKMer.add(helpList); smallestHammingDistance = totalHammingDistance; } else { helpList.add(totalHammingDistance); helpList.add(pattern); bestKMer.add(helpList); smallestHammingDistance = totalHammingDistance; } } } return bestKMer; }
ce4611f3-d0f5-48a4-81cc-0071c7beca9b
9
public boolean checkSetState(UnitState s) { switch (s) { case ACTIVE: case SENTRY: return true; case IN_COLONY: return !isNaval(); case FORTIFIED: return getState() == UnitState.FORTIFYING; case IMPROVING: return location instanceof Tile && getOwner().canAcquireForImprovement(location.getTile()); case SKIPPED: if (getState() == UnitState.ACTIVE) return true; // Fall through case FORTIFYING: return (getMovesLeft() > 0); default: logger.warning("Invalid unit state: " + s); return false; } }
061a98b7-3ef9-4d95-ba28-e5a48d400bd6
8
public boolean pickAndExecuteAnAction() { if(!payments.isEmpty()){ for(Payment p: payments){ makeTransaction(p); return true; } } if(!marketpayments.isEmpty()){ synchronized(marketpayments){ for(MarketPayment m: marketpayments){ PayMarket(m); return true; } } } if(!checks.isEmpty()){ synchronized(checks){ for(Check c: checks){ if(c.paid == false){ if(c.getCheckTotal() == 0.0){ calculateBillTotal(c); return true; } } } // for(Check c: checks){ // if(c.state.equals(CheckState.needsToBeCalculated)){ // calculateBillTotal(c); // return true; // } // } } } return false; }
4fbbc036-2e92-4178-b64a-5f6b33d98e3e
2
@Override public String makeMove(CardGame game, CardPanel panel) { Hand hand = game.getHand(); List<List<Card>> board = game.getBoard(); Card fromDeck = game.getDeck().pop(); //Do this first in case we get the same index twice in a row! if (hand != null && hand.getIndex() != -1) { this.prevHand = hand; board.set(prevHand.getIndex(), hand.getList()); } List<Card> toBeHand = board.get(fromDeck.getRank().ordinal()); toBeHand.add(fromDeck); game.setHand(new Hand(toBeHand, fromDeck.getRank().ordinal())); //Nothing there. board.set(fromDeck.getRank().ordinal(), new CopyOnWriteArrayList<Card>()); return ""; }
8c244798-f344-4d79-b95a-8128bcce479f
1
public void testGet_DateTimeFieldType() { DateMidnight test = new DateMidnight(); assertEquals(1, test.get(DateTimeFieldType.era())); assertEquals(20, test.get(DateTimeFieldType.centuryOfEra())); assertEquals(2, test.get(DateTimeFieldType.yearOfCentury())); assertEquals(2002, test.get(DateTimeFieldType.yearOfEra())); assertEquals(2002, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); assertEquals(2002, test.get(DateTimeFieldType.weekyear())); assertEquals(23, test.get(DateTimeFieldType.weekOfWeekyear())); assertEquals(7, test.get(DateTimeFieldType.dayOfWeek())); assertEquals(160, test.get(DateTimeFieldType.dayOfYear())); assertEquals(0, test.get(DateTimeFieldType.halfdayOfDay())); assertEquals(0, test.get(DateTimeFieldType.hourOfHalfday())); assertEquals(24, test.get(DateTimeFieldType.clockhourOfDay())); assertEquals(12, test.get(DateTimeFieldType.clockhourOfHalfday())); assertEquals(0, test.get(DateTimeFieldType.hourOfDay())); assertEquals(0, test.get(DateTimeFieldType.minuteOfHour())); assertEquals(0, test.get(DateTimeFieldType.minuteOfDay())); assertEquals(0, test.get(DateTimeFieldType.secondOfMinute())); assertEquals(0, test.get(DateTimeFieldType.secondOfDay())); assertEquals(0, test.get(DateTimeFieldType.millisOfSecond())); assertEquals(0, test.get(DateTimeFieldType.millisOfDay())); try { test.get((DateTimeFieldType) null); fail(); } catch (IllegalArgumentException ex) {} }