method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
09282f72-abdd-4494-a237-e0dbe5f01c73
3
@Override public EntidadBancaria insert(EntidadBancaria entidad) { PreparedStatement preparedStatement; Connection connection = connectionFactory.getConnection(); try { preparedStatement = connection.prepareStatement("INSERT INTO entidadbancaria(nombre, fechaCreacion, codigoEntidad) VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, entidad.getNombre()); preparedStatement.setString(3, entidad.getCodigoEntidad()); preparedStatement.setDate(2, new java.sql.Date(new Date().getTime())); int rows = preparedStatement.executeUpdate(); if (rows > 0) { ResultSet resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { entidad.setIdEntidad(resultSet.getInt(1)); } } else { throw new RuntimeException("Fallo insertando datos"); } } catch (SQLException ex) { throw new RuntimeException(ex); } connectionFactory.closeConnection(); return entidad; }
9aee4ed5-f392-4040-8c37-6c33f07ba241
5
public MdpApp getAppPassword(File file) { ObjectInputStream ois = null; MdpApp mdpApp = null; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))); mdpApp = (MdpApp) ois.readObject(); AppUtils.setConsoleMessage("*** FileDAO ***\n mdp crypté : " + mdpApp.getMdpSha256(), FileDAO.class, MessageType.INFORMATION, 67, AppParams.DEBUG_MODE); AppUtils.setConsoleMessage("Succès de la récupération du mot de passe applicatif.", FileDAO.class, MessageType.INFORMATION, 68, AppParams.DEBUG_MODE); } catch (FileNotFoundException e) { AppUtils.setConsoleMessage("Erreur : le chemin d'accès au fichier est incorrect.", FileDAO.class, MessageType.ERROR, 70, AppParams.DEBUG_MODE); e.printStackTrace(); } catch (IOException e) { AppUtils.setConsoleMessage("Erreur : une exception est survenue lors de la tentative d'accès au fichier.", FileDAO.class, MessageType.ERROR, 73, AppParams.DEBUG_MODE); e.printStackTrace(); } catch (ClassNotFoundException e) { AppUtils.setConsoleMessage("Erreur : le type d'objet retourné n'est pas celui attendu.", FileDAO.class, MessageType.ERROR, 76, AppParams.DEBUG_MODE); e.printStackTrace(); } finally { try { if (ois != null) ois.close(); } catch (IOException e) { AppUtils.setConsoleMessage("Erreur : une exception est survenue lors de la tentative de fermeture du flux de lecture.", FileDAO.class, MessageType.ERROR, 83, AppParams.DEBUG_MODE); e.printStackTrace(); } } return mdpApp; }
593e8bfe-aaf5-48cf-9ea9-c7038a64371c
4
@Override public void propertyChanged(String id, String value) { if(id.equals(PRP_MODE)) { if(this.isVisible()) updateControls(); } if (id.equals(PRP_LANGUAGE_CODE)) { createControls(); if (this.isVisible()) { this.setVisible(false); // this.removeAll(); showPropertyPanel(pModel.getSelectedObject()); } } }
d3cfb8a3-198f-4d50-9901-fd69c56244d6
5
public static String getSkin(Block block) { if (!isApplicable(block)) return null; TileEntitySkull skull = (TileEntitySkull) ((CraftWorld) block .getWorld()).getHandle().getTileEntity(block.getX(), block.getY(), block.getZ()); try { Field field = TileEntitySkull.class.getDeclaredField("c"); field.setAccessible(true); return (String) field.get(skull); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
20af5178-f47a-41d6-b1af-7f6a8a7ca389
8
final void method1716(boolean bool) { anInt5897++; int i = ((Class239) this).aClass348_Sub51_3136.method3428 ((byte) -105).method1458(-23688); if ((i ^ 0xffffffff) > -97) ((Class239) this).anInt3138 = 0; if (bool != false) aClass355_5900 = null; if (((Class239) this).anInt3138 > 1 && (i ^ 0xffffffff) > -129) ((Class239) this).anInt3138 = 1; if (((Class239) this).anInt3138 > 2 && i < 192) ((Class239) this).anInt3138 = 2; if (((Class239) this).anInt3138 < 0 || (((Class239) this).anInt3138 ^ 0xffffffff) < -4) ((Class239) this).anInt3138 = method1710(20014); }
0b0de0ed-333f-412c-b294-bddcf23a805e
1
private int[] createBowl(int [] platter) { int[] bowl = new int[NUM_FRUITS]; int sz = 0; while (sz < bowlsize) { // pick a fruit according to current fruit distribution int fruit = pickFruit(platter); int c = 1 + random.nextInt(3); c = Math.min(c, bowlsize - sz); c = Math.min(c, platter[fruit]); bowl[fruit] += c; sz += c; } return bowl; }
54cd6241-d5d6-46c1-b29a-f3faf07451c6
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Bid other = (Bid) obj; if (bid == null) { if (other.bid != null) return false; } else if (!bid.equals(other.bid)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; }
6df05cf8-3cfa-4430-974d-e67e5ce6861a
2
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); String password = request.getParameter("password"); HttpSession session = request.getSession(true); try { if (verify(username, password)) { session.setAttribute("username", username); session.setAttribute("password", password); ResultSet r = DatabaseQuery.getResultSet("select * from users where id = " + username); r.next(); session.setAttribute("name", r.getString("username")); session.setMaxInactiveInterval(30); response.sendRedirect("start.html"); } else { out.println("Username or Password Dismatch!"); out.println("<a href = \"signin.html\">Back</a>"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
28c6e28e-1245-4c42-9332-1a1fdd1dc0c5
0
@Override public String toString() { return String.format("Equivalence { uri: %s, amount: %s, duplicates: %s }", this.uri, this.getAmount(), this.duplicates); }
408a7ee1-d89c-4337-8d58-d4fa54208d86
4
public void moveY(int playerY) { if(!dead){ if(playerY > y){ dy = .3; }else if(playerY < y){ dy = -.3; } if(!knockback){ y += dy; }else{ y += dy * -1; } } }
a266264f-f7b5-4124-a5d5-c5cd217f6a42
7
private void fushImage(String url,String httpQueryString,OutputStream outputStream, MydfsTrackerServer storageTracker){ System.out.println("getQueryString():"+httpQueryString); if(httpQueryString!=null){ url = url+"?"+httpQueryString; } System.out.println(url); InputStream inputStream = storageTracker.receiveData(url); BufferedInputStream bis = new BufferedInputStream(inputStream); BufferedOutputStream out = new BufferedOutputStream(outputStream); byte[] buf = new byte[1024]; int len; try { while((len = bis.read(buf)) > 0){ out.flush(); out.write(buf, 0, len); out.flush(); } } catch (IOException e) { e.printStackTrace(); }finally{ try { if(bis!=null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if(out!=null) out.close(); } catch (IOException e) { e.printStackTrace(); } } }
ecf0cc56-acc5-4bd4-b438-3bd8812a041e
2
public static void main(String[] args) { // ûΨһƾ֤ String appId = "000000000000000000"; // ûΨһƾ֤Կ String appSecret = "00000000000000000000000000000000"; // ýӿڻȡaccess_token AccessToken at = WeixinUtil.getAccessToken(appId, appSecret); if (null != at) { // ýӿڴ˵ int result = WeixinUtil.createMenu(getMenu(), at.getToken()); // жϲ˵ if (0 == result) log.info("˵ɹ"); else log.info("˵ʧܣ룺" + result); } }
07d72683-ef76-4f61-95b2-8077b55e4ab7
1
public long remainingSeconds() { if ( !isActive() ) return 0; return whenStarted + seconds - CurrentTime.inSeconds(); }
72919694-a582-4d6f-abd3-faf62c47f788
5
public boolean pushRequest(Request r){ if(conState != ConnectionState.connected){ throw new RuntimeException("Can only send requests on 'connected' connections"); }else if(peer_choking){ throw new RuntimeException("Can only send requests on unchoked connections"); } if(ourRequests.contains(r.index)){ return false;//already contained. } if(ourRequests.size()+1>max_queued){ throw new RuntimeException("Over enqued max size set to: "+max_queued); } ourRequests.add(r); try { maintenance+=17; mp.request(sockOut, r.index,r.begin,r.len); } catch (IOException e) { conState = ConnectionState.closed; } return true; }
8d803078-0af2-45a7-9981-7267ca399ae9
2
public long getLong(int index) throws JSONException { Object object = get(index); try { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
4f82d6d7-118d-48ce-b8bf-61540df1147b
0
@Test public void testGcdBaseCase() { // the base case means that q == 0, so return p int q = 0; int p = 5; int result = BasicMath.gcd(p, q); assertEquals(result, p); }
4b0ddb90-cbaf-4016-83ec-caf79bf309fc
2
public RushTeam(String name, String displayName) { setName(name); setDisplayName(displayName); switch(displayName) { case "Blue": setColor(ChatColor.BLUE); break; case "Orange": setColor(ChatColor.GOLD); break; default: break; } }
3ed6edcc-ec22-4b92-a2b3-39376d0eff2c
7
private static void testTimeSVM(){ svm_problem prob = new svm_problem(); prob.l = storeFile.length; int noFea = storeFile[0].length-1; prob.x = new svm_node[prob.l][noFea]; prob.y = new double[prob.l]; for (int i = 0; i <prob.l; i++){ svm_node[] nodeList = prob.x[i]; for (int j = 1; j <= noFea; j++){ svm_node aNode = new svm_node(); aNode.index = j-1; aNode.value = storeFile[i][j]?1:0; nodeList[j-1] = aNode; } prob.y[i] = storeFile[i][0]?1:-1; } // set param svm_parameter param = new svm_parameter(); param.svm_type = svm_parameter.C_SVC; param.kernel_type = svm_parameter.LINEAR; param.degree = 3; param.gamma = 0; // 1/num_features param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; param.nr_weight = 0; param.weight_label = new int[0]; param.weight = new double[0]; svm_model model = svm.svm_train(prob, param); //System.println() // svm.svm_save_model("abc.model", model); double[] dim=new double[noFea]; for (int i = 0; i < model.SV.length; i++){ for (int j = 0; j < noFea; j++){ dim[j] += model.SV[i][j].value * model.sv_coef[0][i]; } } for (int j = 0; j < noFea; j++){ System.out.println(dim[j]); } }
5d9b30b0-848e-4850-b609-f1c8b3905a8c
0
public UnrestrictedBruteParser(Grammar grammar, String target) { super(grammar, target); }
17c4263c-5c46-445f-8730-3dbc07994f93
6
public signUpAdmin(){ JPanel dialogPanel2 = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; //adding the the label for the Username setLocation(560,380); fNameAdd = new JLabel("First Name: "); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 2; dialogPanel2.add(fNameAdd, constraints); fNameAddValue = new JTextField(20); constraints.gridx = 1; constraints.gridy = 0; constraints.gridwidth = 2; dialogPanel2.add(fNameAddValue,constraints); lNameAdd = new JLabel("Last Name: "); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 2; dialogPanel2.add(lNameAdd, constraints); lNameAddValue = new JTextField(20); constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 2; dialogPanel2.add(lNameAddValue,constraints); userNameAdd = new JLabel("User Name: "); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 2; dialogPanel2.add(userNameAdd, constraints); //addint the text field for the username userNameAddValue = new JTextField(20); constraints.gridx = 1; constraints.gridy = 2; constraints.gridwidth = 2; dialogPanel2.add(userNameAddValue,constraints); //adding the Jlabel for the password passwordAdd = new JLabel("Password: "); constraints.gridx = 0; constraints.gridy = 3; constraints.gridwidth = 1; dialogPanel2.add(passwordAdd,constraints); //adding the password filed to the message passwordAddValue = new JPasswordField(20); constraints.gridx = 1; constraints.gridy = 3; constraints.gridwidth = 2; dialogPanel2.add(passwordAddValue,constraints); //adding a border around th panel dialogPanel2.setBorder(new LineBorder(Color.BLUE)); okButton = new JButton("SUBMIT"); ActionListener okButtonAction = new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { String fName = getFirstNameValue(); String lName = getLastNameValue(); String uName= getUserNameValue(); String password = getPasswordValue(); if(fName.equals("") || lName.equals("") || uName.equals("") || password.equals("")){ JOptionPane.showMessageDialog(signUpAdmin.this, "YOU MUST ENTER ALL INFORMATION", "CHECK VALUES AGAIN AND TRY AGAIN", JOptionPane.ERROR_MESSAGE); } else{ try { // throw new UnsupportedOperationException("Not supported yet."); logIn.addTo(fName,lName,uName,password); System.out.println("Im in signupadmin"); dispose(); adminLogInDialog dialogBox = new adminLogInDialog(new JPanel()); dialogBox.setVisible(true); } catch (SAXException ex) { Logger.getLogger(signUpAdmin.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(signUpAdmin.class.getName()).log(Level.SEVERE, null, ex); } } } };//end of actionListener //add action listener okButton.addActionListener(okButtonAction); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); getContentPane().add(dialogPanel2, BorderLayout.CENTER); getContentPane().add(buttonPanel, BorderLayout.PAGE_END); pack(); setResizable(false); }//end constructor
6278adb2-c5a0-4461-a610-8c75be32ad24
2
public void setTileCircuit(Vector2f pos, int circuit, int inputID){ Vector2f temp = TileUtil.getCoordinate(pos); for(Tile tile : tileList ) { if (TileUtil.getCoordinate(tile.getPosition()).equals(temp)){ tile.setCircuit(circuit); tile.setInput(inputID); } } }
282c0c2d-88b5-4233-8284-a63c2fc17061
0
public BuscaEmpresa() { System.out.println("Instanciando uma Tarefa do tipo BuscaEmpresa " + this); }
b2379810-f7bb-49f9-be4c-e91097f6e7ec
2
public static BusSubmodesOfTransportEnumeration fromValue(String v) { for (BusSubmodesOfTransportEnumeration c: BusSubmodesOfTransportEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
b2ffa321-b011-45ed-90a7-4a50706e5eca
1
public void setTexture(String texturePath){ try { texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(texturePath)); } catch (IOException e) { e.printStackTrace(); } }
f3ad4cb7-4dd9-4783-b82d-33cc53548b73
0
public PartB getPartB() { return partB; }
65c2334b-4154-4b74-8c11-582efe607af2
5
public String getVersionFromManagementDependency(Dependency dependency) { for (DependencyType depType: Arrays.asList(DEPENDENCY_MANAGEMENT_LIST, PLUGIN_MANAGEMENT, PLUGIN_MANAGEMENT_DEPENDENCIES)) { for (Dependency mgtDep: dependencies.get(depType)) { if (mgtDep.equalsIgnoreVersion(dependency) ) { if (mgtDep.getVersion() != null) { //System.out.println("In " + getThisPom() + " - found version " + mgtDep.getVersion() + " for " + // dependency.getGroupId() + ":" + dependency.getArtifactId() + " according to the list of " + listType); return mgtDep.getVersion(); } } } } if (parentPOM != null) { return parentPOM.getVersionFromManagementDependency(dependency); } return null; }
f54f8567-8ace-4357-ac57-33746094994a
4
protected void updateLandingStrip() { if (landingStrip == null || landingStrip.destroyed()) { final LandingStrip newStrip = new LandingStrip(this) ; final Tile o = origin() ; final int S = this.size ; for (int n : TileConstants.N_ADJACENT) { n = (n + 2) % 8 ; newStrip.setPosition(o.x + (N_X[n] * S), o.y + (N_Y[n] * S), world) ; if (newStrip.canPlace()) { newStrip.doPlace(newStrip.origin(), null) ; landingStrip = newStrip ; break ; } } } }
48d98d53-1892-4663-a109-859906302e27
9
static void processCommandLine(String[] arguments) { if (arguments.length > 0) { ArrayList<String> args = new ArrayList<String>(); for (String arg : arguments) { args.add(arg); } while (args.size() > 0) { if ("-a".equalsIgnoreCase(args.get(0))) { //$NON-NLS-1$ args.remove(0); try { File adbFile = new File(args.get(0)); if (adbFile.exists()) { args.remove(0); RemoteResourcesConfiguration.getInstance().set( RemoteResourcesConfiguration.ADB_PATH, adbFile.getPath()); } else { System.err .println(RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.RemoteResourcesServer_Error_AdbNotFound)); } } catch (IndexOutOfBoundsException e) { System.err .println(RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.RemoteResourcesServer_Error_AdbNoPath)); } } else if ("-p".equalsIgnoreCase(args.get(0))) { args.remove(0); try { String port = args.get(0); args.remove(0); Integer.valueOf(port, 10); RemoteResourcesConfiguration.getInstance().set( RemoteResourcesConfiguration.SERVER_PORT, port); } catch (NumberFormatException e) { System.err .println(RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.RemoteResourcesServer_Error_InvalidPortNumber)); } catch (IndexOutOfBoundsException e) { System.err .println(RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.RemoteResourcesServer_Error_NoPortNumber)); } } else { args.remove(0); System.err .println("Usage: java com.eldorado.remoteresources.RemoteResourcesServer [-a path/to/adb] [-p <PORT_NUMBER>]"); //$NON-NLS-1$ } } } }
d46a3d82-c45a-4409-9062-7154f25f5b61
0
public void setAddress(Address address) { Address = address; }
ca18a6d0-d6ab-47c6-be2d-9cb636c58946
3
public static void bfs(int root) { Queue<Integer> q = new LinkedList<Integer>(); Arrays.fill(v, 0, V, false); q.add(root); v[root] = true; while (!q.isEmpty()) { int node = q.poll(); for (int i = 0; i < G[node].size(); i++) { Edge nodde = G[node].get(i); int neigh = nodde.destino; if (!v[neigh]) { v[neigh] = true; T[neigh] = node; H[neigh] = nodde.peso; L[neigh] = L[node] + 1; q.add(neigh); } } } }
60f2cde6-2310-47eb-8d77-393daa3851eb
4
void add(float v) { switch(dim) { case 0: x = v; dim ++; return; case 1: y = v; dim ++; return; case 2: z = v; dim ++; return; case 3: w = v; dim ++; return; default: throw new IllegalArgumentException(); } }
516c85b2-e1e2-4ffc-a0d3-fe6fa8acfdbc
0
public void setStartDate(XMLGregorianCalendar value) { this.startDate = value; }
7951d8a8-3ab8-4c59-850f-d570f3e80290
1
@Override public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (name.equals("page")) { setTitle(getTitle()); } }
2204dcc9-01ee-4a8b-994d-8f5d09d55869
6
private void makeDropTarget(final java.io.PrintStream out, final java.awt.Component c, final boolean recursive) { // Make drop target final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget(); try { dt.addDropTargetListener(dropListener); } // end try catch (java.util.TooManyListenersException e) { e.printStackTrace(); log(out, "FileDrop: Drop will not work due to previous error. Do you have another listener attached?"); } // end catch // Listen for hierarchy changes and remove the drop target when the // parent gets cleared out. c.addHierarchyListener(new java.awt.event.HierarchyListener() { @Override public void hierarchyChanged(final java.awt.event.HierarchyEvent evt) { log(out, "FileDrop: Hierarchy changed."); java.awt.Component parent = c.getParent(); if (parent == null) { c.setDropTarget(null); log(out, "FileDrop: Drop target cleared from component."); } // end if: null parent else { new java.awt.dnd.DropTarget(c, dropListener); log(out, "FileDrop: Drop target added to component."); } // end else: parent not null } // end hierarchyChanged }); // end hierarchy listener if (c.getParent() != null) new java.awt.dnd.DropTarget(c, dropListener); if (recursive && (c instanceof java.awt.Container)) { // Get the container java.awt.Container cont = (java.awt.Container) c; // Get it's components java.awt.Component[] comps = cont.getComponents(); // Set it's components as listeners also for (int i = 0; i < comps.length; i++) makeDropTarget(out, comps[i], recursive); } // end if: recursively set components as listener } // end dropListener
95d5a51d-3939-4739-b0a2-bc521c58d6a6
1
public String getPartName(String xpathExpression){ if (xpathExpression.contains("/")){ String varPart = xpathExpression.substring(0, xpathExpression.indexOf("/")); return varPart.substring(varPart.indexOf(".")+1); }else{ return xpathExpression.substring(xpathExpression.indexOf(".")+1); } }
61124ea6-fcee-4556-bfca-b348924cab87
8
@Override public Object getValueAt(int row, int column) { Mannschaft m = WettkampfTag.get().getMannschaften().get(row); switch (column) { case -1: return m; case 0: return icon; case 1: return m.getName(); case 2: return m.getVerein(); case 3: return m.getRiege() != null ? m.getRiege().getName() : ""; case 4: return m.getWettkampf() != null ? m.getWettkampf().getName() : ""; } return null; }
2f091a0b-537e-4920-9e2c-1d77822d9303
5
public CSProperties getParameter() throws IOException { CSProperties p = DataIO.properties(); for (Params paras : getParams()) { String f = paras.getFile(); if (f != null) { // original properties. p.putAll(DataIO.properties(new FileReader(new File(f)), "Parameter")); // check for tables in the file. List<String> tables = DataIO.tables(new File(f)); if (!tables.isEmpty()) { for (String name : tables) { CSTable t = DataIO.table(new File(f), name); // convert them to Properties. CSProperties prop = DataIO.fromTable(t); p.putAll(prop); } } } for (Param param : paras.getParam()) { p.put(param.getName(), param.getValue()); } } return p; }
38c48642-4eb4-4cb3-8025-ea040cba6158
3
public static double toDouble(Object object) { if (object instanceof Number) { return ((Number) object).doubleValue(); } try { return Double.valueOf(object.toString()); } catch (NumberFormatException e) { } catch (NullPointerException e) { } return 0; }
addc53c0-0d73-4dc8-8d5e-147c02d7306a
2
public ArrayList<Tayte> haeTaytteet() throws DAOPoikkeus{ System.out.println("haetaan taytteita"); String sql = "select * from Tayte"; Connection yhteys = avaaYhteys(); ArrayList<Tayte> taytteet = new ArrayList<Tayte>(); PreparedStatement lause; try { lause = yhteys.prepareStatement(sql); System.out.println("ps"); ResultSet result = lause.executeQuery(); System.out.println("rs"); while(result.next()) { String nimi = result.getString("nimi"); int id = result.getInt("TayteID"); // lisätään Pizza väliaikaiseen listaan Tayte tayte = new Tayte(nimi,id); taytteet.add(tayte); System.out.println(nimi + " " + id); } } catch (SQLException e) { System.out.println("vituiks meni"); } finally { suljeYhteys(yhteys); } return taytteet; }
3b52fc0d-0753-42c2-aaeb-eba9ac532b58
9
public static By by(String locator) { By by; if(locator.startsWith("//")) by = By.xpath(locator); else if(locator.startsWith("class=")) by =By.className(locator.replace("class=","")); else if(locator.startsWith("css=")) by = By.cssSelector(locator.replace("css=", "").trim()); else if(locator.startsWith("link=")) by = By.linkText(locator.replace("link=", "")); else if(locator.startsWith("name=")) by = By.name(locator.replace("name=", "").trim()); else if(locator.startsWith("tag=")) by = By.tagName(locator.replace("tag=", "").trim()); else if(locator.startsWith("partialText=")) by= By.partialLinkText(locator.replace("partialText=","")); else if(locator.startsWith("text=")) by =By.linkText(locator.replace("text=","")); else if(locator.startsWith("id=")) by= By.id(locator.replace("id=","")); else by = By.id(locator); return by; }
feb5c90b-5658-45d6-adaa-d05a6beeb40f
1
public Piece createPromotionPiece(boolean isWhite) { return new Queen(isWhite, isWhite ? this.board.whiteQueenImage : this.board.blackQueenImage); }
022d1c4f-590d-4020-b1e2-98f82adcd424
4
public boolean onCommand(CommandSender cs, Command cmd, String string, String[] args) { Home Home = new Home(MainClass); SetHome SetHome = new SetHome(MainClass); if(string.equalsIgnoreCase("sethome")){ if(!(cs instanceof Player)){ return false; } else SetHome.setHome(cs, cmd, string, args); } else if(string.equalsIgnoreCase("home")){ if(!(cs instanceof Player)){ return false; } else Home.teleportHome(cs, cmd, string, args); } return false; }
cfd68a93-21e4-48ad-8b22-941c5f139adf
6
@Override public void Play(PlayerResponse response) { try { List<Card> cards = response.getCards(); if(cards.size() < 4) throw new Exception("not enough cards"); if(mP.getCurrentTurn() == bidPartner.getPosition()) { passCards(bidPartner, bidWinner, cards); mP.setCurrentTurn(bidWinner.getPosition()); for (PinochlePlayer player : mP.getPlayers()) { PinochleMessage message = new PinochleMessage(); message.setCards(player.getCurrentCards()); player.setMessage(message); } mP.updateAll(); } else { passCards(bidWinner, bidPartner, cards); for (PinochlePlayer player : mP.getPlayers()) { PinochleMessage message = new PinochleMessage(); message.setCards(player.getCurrentCards()); player.setMessage(message); } mP.updateAll(); mP.setState(mP.getMeld()); mP.setCurrentTurn(bidWinner.getPosition()); mP.Play(null); } } catch(Exception e) { for (PinochlePlayer player : mP.getPlayers()) { PinochleMessage message = new PinochleMessage(); message.setCards(player.getCurrentCards()); player.setMessage(message); } mP.updateAll(); } }
2867d8db-ad9d-4523-ab93-52b6a75187fe
2
public void print_heap(Binarynode root) { System.out.println(root.value); if (root.left != null) { print_heap(root.left); } if (root.right != null) { print_heap(root.right); } }
c921654b-64d4-4a49-b32f-8a82e28aefef
1
public static void writeDataToFile(DataContainer dataContainer) throws IOException { File fileDir = new File(backupFilePath); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF-8")); Set<TableDescription> tableDescriptions = dataContainer.getTableDescriptions(); Iterator<TableDescription> iterator = tableDescriptions.iterator(); while (iterator.hasNext()) { TableDescription tableDescription = iterator.next(); String tableName = tableDescription.getName(); writeTableDescription(out, tableDescription); Map<String, Row> dataInTable = dataContainer.getRowsByDescription(tableDescription); writeTableRows(out, dataInTable); out.write("table end\n"); } out.close(); }
f8819830-55e0-4457-9eff-748de89d6f6c
9
private void initControls() throws RemoteException, NotBoundException, MalformedURLException { this.setLocationRelativeTo(null); //setExtendedState(this.getExtendedState() | MAXIMIZED_BOTH) // ############## INITIATE PERSONS ################ List<IPersonDTO> personsDTO = personController.loadPersons(); List<IDepartmentDTO> depts = departmentController.loadDepartments(); cobDepartment.addItem(""); for (IDepartmentDTO d : depts) { cobDepartment.addItem(d); } cobContribution.addItem(""); cobContribution.addItem("Ja"); cobContribution.addItem("Nein"); this.personTable.setModel(new PersonTableModel(personsDTO)); personSorter = new TableRowSorter<PersonTableModel>(); personTable.setAutoCreateRowSorter(true); btnCreatePerson.addActionListener(new CreateNewPersonListener(personTable, controllerFactory)); btnEditPerson.addActionListener(new EditPersonListener(personTable, controllerFactory)); btRechte.addActionListener(new EditRolesListener(personTable, controllerFactory, roleController, editPersonRoleController)); //btnDeletePerson.addActionListener(new DeletePersonListener(personTable, controllerFactory)); // ################### INITIATE TOURNAMENTS ############################ List<ITournamentDTO> tournamentsDTO = tournamentController.loadTournaments(); tournamentTable.setModel(new TournamentTableModel(tournamentsDTO)); tournamentTable.setAutoCreateRowSorter(true); btnCreateTournament.addActionListener(new CreateNewTournamentListener(tournamentTable, controllerFactory, managerRoles)); btnEditTournament.addActionListener(new EditTournamentListener(tournamentTable, controllerFactory)); jButton1.addActionListener(new ShowTournamentListener(tournamentTable, controllerFactory, teamController)); tournamentTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (managerRoles != null) { TournamentTableModel model = (TournamentTableModel) tournamentTable.getModel(); ITournamentDTO tournament = model.getTournamentDTO(tournamentTable.getSelectedRow()); for (IRoleDTO r : managerRoles) { try { if (departmentController.isSportInDepartment(r.getDepartment(), tournament.getSport())) { btnEditTournament.setEnabled(true); break; } else { btnEditTournament.setEnabled(false); } } catch (RemoteException ex) { Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex); } } } } }); // ################### INITIATE TOURNAMENTTEAMS ############################ List<ITournamentTeamDTO> tournamentTeamsDTO = teamController.loadTounamentTeams(); tournamentTeamTable.setModel(new TournamentTeamTableModel(tournamentTeamsDTO)); tournamentTeamTable.setAutoCreateRowSorter(true); btnEditTeam.addActionListener(new EditTeamListener(tournamentTeamTable, controllerFactory)); tournamentTeamTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (coachRoles != null) { TournamentTeamTableModel model = (TournamentTeamTableModel) tournamentTeamTable.getModel(); ITournamentTeamDTO team = model.getTournamentTeamDTO(tournamentTeamTable.getSelectedRow()); for (ICoachDTO coach : team.getCoaches()) { for (IRoleDTO r : coachRoles) { if (coach.getId() == r.getId()) { btnEditTeam.setEnabled(true); return; } } } btnEditTeam.setEnabled(false); } } }); }
456c5eaf-8fd4-4515-8182-7316dd3ed397
5
public Relation readFile(){ BufferedReader reader; String currentLine; try { reader = new BufferedReader(new FileReader(input)); //Read the first line, that will be the relation name storedRelation.relationName = reader.readLine().split(" ")[1]; //Burn one - blank line reader.readLine(); while((currentLine = reader.readLine()).toLowerCase().contains("@attribute")){ //Put in our attributeTypes Attribute oneAttribute = new Attribute(currentLine.split(" ")[1].trim(),currentLine.split(" ")[2].trim()); storedRelation.attributeData.add(oneAttribute); } if(reader.readLine().toLowerCase().equals("@data")){ //I dont NEED to do this, but im going to, to make sure while((currentLine = reader.readLine()) != null){ //Should be able to read till the end of the file for(int i=0;i<storedRelation.attributeData.size();i++){ //read in the actual data for each of the attributes {a,b,c..} storedRelation.attributeData.get(i).instanceValues.add(currentLine.split(",")[i].trim()); } } } else { //TODO: Freak out, maybe print something later if this matters (No @data where expected) } //Now find the unique values since we have read in all the data } catch (Exception e) { e.printStackTrace(); } return storedRelation; }
3c159fe4-d514-4d3a-a43a-962e69c3b33b
4
void resetEditors (boolean tab) { TableItem oldItem = comboEditor.getItem (); comboEditor.setEditor (null, null, -1); if (oldItem != null) { int row = table.indexOf (oldItem); try { new String (nameText.getText ()); } catch (NumberFormatException e) { nameText.setText (oldItem.getText (NAME_COL)); } String [] insert = new String [] {nameText.getText (), combo.getText ()}; data.setElementAt (insert, row); for (int i = 0 ; i < TOTAL_COLS; i++) { oldItem.setText (i, ((String [])data.elementAt (row)) [i]); } if (!tab) disposeEditors (); } setLayoutState (); refreshLayoutComposite (); setTopControl (currentLayer); layoutGroup.layout (true); }
15f5e02c-ecd3-4f32-9a0d-5590c076380f
0
@Test public void isEmptyReturnsTrueWhenEmpty() { assertTrue(s.isEmpty()); }
e427ae67-6458-45ee-aef4-df37178108ad
9
private Coordinates getNextCoordinates() throws CloneNotSupportedException { try { Coordinates lastHitCopy = lasthit.clone(); switch (direction) { case 0: if (lasthit.getX() == 9) { return null; } lastHitCopy.setX(lasthit.getX() + 1); lastHitCopy.setY(lasthit.getY()); break; // Left case 1: if (lasthit.getX() == 0) { return null; } lastHitCopy.setX(lasthit.getX() - 1); lastHitCopy.setY(lasthit.getY()); break; //Top case 2: if (lasthit.getY() == 0) { return null; } lastHitCopy.setX(lasthit.getX()); lastHitCopy.setY(lasthit.getY() - 1); break; //Down case 3: if (lasthit.getY() == 9) { return null; } lastHitCopy.setX(lasthit.getX()); lastHitCopy.setY(lasthit.getY() + 1); break; default: direction =-1; return null; } lasthit = lastHitCopy; return lastHitCopy; } catch(CloneNotSupportedException asdf) { return null; } }
ca8ac338-d218-45d9-a2a5-9e827d402ef8
8
public void draw() { // Get the loaded materials and initialise necessary variables Material[] materials = couchMesh.materials; Material material; Triangle drawTriangle; int currentMaterial = -1; int triangle = 0; // For each triangle in the object for (triangle = 0; triangle < couchMesh.triangles.length;) { // Get the triangle that needs to be drawn drawTriangle = couchMesh.triangles[triangle]; // Activate a new material and texture currentMaterial = drawTriangle.materialID; material = (materials != null && materials.length > 0 && currentMaterial >= 0) ? materials[currentMaterial] : defaultMtl; material.apply(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.getTextureHandle()); // Draw triangles until material changes GL11.glBegin(GL11.GL_TRIANGLES); while (triangle < couchMesh.triangles.length && drawTriangle != null && currentMaterial == drawTriangle.materialID) { GL11.glTexCoord2f(drawTriangle.texture1.x, drawTriangle.texture1.y); GL11.glNormal3f(drawTriangle.normal1.x, drawTriangle.normal1.y, drawTriangle.normal1.z); GL11.glVertex3f((float) drawTriangle.point1.pos.x, (float) drawTriangle.point1.pos.y, (float) drawTriangle.point1.pos.z); GL11.glTexCoord2f(drawTriangle.texture2.x, drawTriangle.texture2.y); GL11.glNormal3f(drawTriangle.normal2.x, drawTriangle.normal2.y, drawTriangle.normal2.z); GL11.glVertex3f((float) drawTriangle.point2.pos.x, (float) drawTriangle.point2.pos.y, (float) drawTriangle.point2.pos.z); GL11.glTexCoord2f(drawTriangle.texture3.x, drawTriangle.texture3.y); GL11.glNormal3f(drawTriangle.normal3.x, drawTriangle.normal3.y, drawTriangle.normal3.z); GL11.glVertex3f((float) drawTriangle.point3.pos.x, (float) drawTriangle.point3.pos.y, (float) drawTriangle.point3.pos.z); triangle++; if (triangle < couchMesh.triangles.length) drawTriangle = couchMesh.triangles[triangle]; } GL11.glEnd(); } }
f2001760-96c7-4366-bbb2-0a9b14b68cee
3
public void setTrue(TTrue node) { if(this._true_ != null) { this._true_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._true_ = node; }
9db30521-4b9f-4a71-a259-0f5bbeebabfb
4
public void openConnection(String driverClassName, String url, String username, String password) throws IllegalArgumentException, ClassNotFoundException, SQLException { String msg = "Error: url is null or zero length!"; if (url == null || url.length() == 0) { throw new IllegalArgumentException(msg); } username = (username == null) ? "" : username; password = (password == null) ? "" : password; Class.forName(driverClassName); conn = DriverManager.getConnection(url, username, password); }
ef781e5f-ef7f-478d-8038-1612301dd4f0
5
@Override public synchronized List<String> getDocumentList() throws RemoteException { try { unlockDocument(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } List<String> documentList = server.getDocumentList(); dernier = new HashMap<String, String>(); suivant = new HashMap<String, String>(); if(idDernier.equals(this.getUrl())){ for(String name : documentList){ dernier.put(name, null); suivant.put(name, null); } } else { for(String name : documentList){ dernier.put(name, idDernier); suivant.put(name, null); } } return documentList; }
4c12d9c5-ad83-4764-8807-4aca1f16c1f9
1
private boolean WriteConfigFile() { //write status boolean status = false; try { //open the file output stream outStream = new FileOutputStream(System.getProperty("user.dir")+"/Data.csv"); //get the data stream for the file out = new DataOutputStream(outStream); //read data from the file br = new BufferedWriter(new OutputStreamWriter(out)); status = true; } catch(Exception e){} //return status of file read return status; }
be1ccee5-7955-4e32-9440-c80ee5b76023
0
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
1e8aa5a5-f51d-4652-b766-1060d3d6eabc
1
public double getPriority(T item) throws NoSuchElementException { int index; try { index = map.get(item); } catch (NullPointerException npe) { throw new NoSuchElementException(); } PQElement<T> y = heap.get(index); return y.priority; }
5bb798c6-7424-4897-9952-8c3afff14a43
2
public int attackNormal( Character opponent ) { int type = (int)(Math.random()*2); int damage = 0; if (type == 0){ System.out.println(_name+" asks annoying question!"); damage = askQuestion(opponent);} else { System.out.println(_name + " does his homework using code found online!"); damage = doHW(opponent);} if ( damage < 0 ) damage = 0; opponent.lowerHP( damage ); return damage;}
77cdbd98-1074-4003-beee-e5a109a414ea
2
@Override public ISocketServerConnection getConnectionById(long aIdConnection) { for (Iterator<ISocketServerConnection> it = getConnections().iterator(); it.hasNext();) { ISocketServerConnection ssc = it.next(); if (aIdConnection == ssc.getIdConnection()) return ssc; } return null; }
90e9e198-51de-4513-861b-a9fa74e3cbde
9
public void processFileAssoc(Source sourceInput, String localName, File outputFile, ArrayList parameterList, String initialMode, PrintStream traceDestination) throws TransformerException { if (showTime) { System.err.println("Processing " + sourceInput.getSystemId() + " using associated stylesheet"); } long startTime = now(); Source style = PreparedStylesheet.getAssociatedStylesheet(config, sourceInput, null, null, null); Templates sheet = PreparedStylesheet.compile(style, config, compilerInfo); if (showTime) { System.err.println("Prepared associated stylesheet " + style.getSystemId()); } Controller controller = newController(sheet, parameterList, traceDestination, initialMode, null); File outFile = outputFile; if (outFile != null && outFile.isDirectory()) { outFile = makeOutputFile(outFile, localName, sheet); } StreamResult result = (outFile == null ? new StreamResult(System.out) : new StreamResult(outFile.toURI().toString())); try { controller.transform(sourceInput, result); } catch (TerminationException err) { throw err; } catch (XPathException err) { // The error message will already have been displayed; don't do it twice if (!err.hasBeenReported()) { err.printStackTrace(); } throw new XPathException("Run-time errors were reported"); } if (showTime) { long endTime = now(); System.err.println("Execution time: " + (endTime - startTime) + " milliseconds"); } }
37d53368-5793-4e50-b9df-6f9419a2c782
4
public List<String> openFile(File file) { List<String> list = new ArrayList<String>(); if (!file.isDirectory() && file.canWrite()) { path = Paths.get(file.getAbsolutePath()); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { String line = null; while ((line = reader.readLine()) != null) { list.add(line); } } catch (IOException e) { System.err.format("IOException: %s%n", e); } } return list; }
7c1b9318-a661-4d65-9e5b-c0a1b0dfdef2
2
public List<File> getArgumentsAsFiles() { List<File> arguments = new ArrayList<>(); for (CmdLineData one : mData) { if (!one.isOption()) { arguments.add(new File(one.getArgument())); } } return arguments; }
9413cd1c-1b73-44c7-98d0-d2848e1a5d10
2
public void modificarImagen(int id, ArrayList datos) { // Cambiamos todos los datos, que se puedan cambiar, a minúsculas for(int i = 0 ; i < datos.size() ; i++) { try{datos.set(i, datos.get(i).toString().toLowerCase());} catch(Exception e){} } biblioteca.modificarRegistros("imagen", id, datos); }
601d6959-63b4-468f-ba1d-ba8b0e6c0084
1
public VariableDependencyGraph getVariableDependencyGraph(Grammar grammar) { VariableDependencyGraph graph = new VariableDependencyGraph(); initializeDependencyGraph(graph, grammar); Production[] uprods = getUnitProductions(grammar); for (int k = 0; k < uprods.length; k++) { graph .addTransition(getTransitionForUnitProduction(uprods[k], graph)); } return graph; }
1f077585-8bb0-410a-86ba-99d0867b3b6c
3
public int put(int key, int n) { int pos, t = 1; while (t < m) { pos = toHash(key, t); if (table[pos] == null) { table[pos] = new HashEntry(key, t); // ???????????????????????????????????????????????????????????????????????????????????? // // ???????????????????????????????????????????????????????????????????????????????????? // if (n % (Math.ceil(m / 50)) == 0) { Stats stats = new Stats(m, n, t); Main.statsQuadratic.add(stats); } // ???????????????????????????????????????????????????????????????????????????????????? // // ???????????????????????????????????????????????????????????????????????????????????? // return t; } t++; } return -1; }
72b352ac-47b6-4db1-a017-9cd43cf4b896
1
public boolean choisirLigne(int id) throws IOException { connexion.envoyer("CHOIX "+id+" "+Main.controleur.getId()); reponse = connexion.recevoir(); return (reponse.equals("OK") ? true : false); }
30305628-8fdb-4c9e-bd73-6a364b7326a7
6
public static void string_cppOutputLiteral(String string) { { int free = Stella.$CPP_MAX_STRING_LITERAL_LENGTH$; ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\""); { char ch = Stella.NULL_CHARACTER; String vector000 = string; int index000 = 0; int length000 = vector000.length(); for (;index000 < length000; index000 = index000 + 1) { ch = vector000.charAt(index000); if (free <= 1) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\" \""); free = Stella.$CPP_MAX_STRING_LITERAL_LENGTH$; } switch (ch) { case '\\': case '"': ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\\"); free = free - 1; break; case '\n': ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\\"); free = free - 1; ch = 'n'; break; case '\r': ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\\"); free = free - 1; ch = 'r'; break; default: break; } ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(ch); free = free - 1; } } ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("\""); } }
4df6e2af-b51f-400d-98e0-9f0b8bd7827b
4
protected void removeFromTeamAOrB(String teamType) { Object selectedValue = null; String selectedStudent = null; int selectedIndex = 0; if (teamType.equals("A")) { selectedValue = teamACDJlst.getSelectedValue(); if (selectedValue == null ) { //warn no selected student JOptionPane.showMessageDialog(this, "No student selected", "Warning", JOptionPane.WARNING_MESSAGE); } else { selectedStudent = selectedValue.toString(); selectedIndex = teamACDJlst.getSelectedIndex(); teamACDDLM.remove(selectedIndex); studentsCDDLM.addElement(selectedStudent); teamACDJlbl.setText("Team A(" + teamACDDLM.getSize() + "/" + userNumb + ")"); } } else if (teamType.equals("B")) { selectedValue = teamBCDJlst.getSelectedValue(); if (selectedValue == null ) { //warn no selected student JOptionPane.showMessageDialog(this, "No student selected", "Warning", JOptionPane.WARNING_MESSAGE); } else { selectedStudent = selectedValue.toString(); selectedIndex = teamBCDJlst.getSelectedIndex(); teamBCDDLM.remove(selectedIndex); studentsCDDLM.addElement(selectedStudent); teamBCDJlbl.setText("Team B(" + teamBCDDLM.getSize() + "/" + userNumb + ")"); } } }
ec80746e-7a54-4bbb-8911-547f2e4f7d62
0
public List<ParkManager> getManagerList() { return managerList; }
0ce66fa3-e51f-4504-903f-cf745255c17e
5
@Override public void keyPressed (KeyEvent keyEvent) { //System.out.println("key pressed"); switch (keyEvent.getExtendedKeyCode()) { case 32: frame.getHero().attack(); break; case 37: frame.getHero().setHeroOwnHorizontalSpeed(-AppFrame.getHero().getOwnHorizontalSpeed()); break; case 38: //frame.getHero().setHeroOwnVerticalSpeed(-AppFrame.getHero().getOwnVerticalSpeed()); frame.getHero().upKeyPressed(); break; case 39: frame.getHero().setHeroOwnHorizontalSpeed(AppFrame.getHero().getOwnHorizontalSpeed()); break; case 40: frame.getHero().crouch(); break; } }
64e6ac00-8cd6-4a23-981f-93758beee40d
9
public Matrix<T> getVer () throws Exception { if (this.cols != this.rows) { throw new MatrixIsNotInversebleException(); } Matrix<T> ex = this.getEx(); // set the diagonal line elements of the Matrix as "1" for (int r = 0; r < rows; r++) { T c = ex.get(r, r); if (!c.isOne()) { ex.set(r, r, this.one); for (int j = r + 1; j < ex.cols; j++) { ex.set(r, j, ex.get(r, j).div(c)); } } // set the lower triangular matrix elements as "0" for (int r2 = r + 1; r2 < rows; r2++) { T key = ex.get(r2, r); for (int j = r; j < ex.cols; j++) { T a = ex.get(r, j); T b = ex.get(r2, j); T out = b.minus(a.mul(key)); ex.set(r2, j, out); } } } // set the uper triangular matrix elements as "0" for (int r = rows - 1; r >= 0; r--) { for (int r2 = 0; r2 < r; r2 ++) { T key = ex.get(r2, r); for (int c = r; c < ex.cols; c++) { T a = ex.get(r2, c); T b = ex.get(r, c); T x = key.mul(b); ex.set(r2, c, a.minus(x)); } } } return ex.getVMatrix(); }
8f6bccd9-0fab-44a4-a161-9d8dca8caa6a
0
@Basic @Column(name = "log_time") public Timestamp getLogTime() { return logTime; }
43a1aa94-9c80-4239-99fe-8354176cbbca
1
public static void buyItemTester(String name){ if(!ItemStorageInventory.create().addItem(ItemFactory.create().buyItem(name)) ){ System.out.println(name + " cannot be bought\n"); } }
d2b0152d-c00a-4d54-9f06-dd7b9b13a73c
7
private void executeAdding() { if (action.contains("rooms")) { Coordinate coordinate = sphereConverter.giveMouseCoordinates(mouseCoordinateX, mouseCoordinateY); if (coordinate.giveLatitude() >= -90 && coordinate.giveLongitude() <= 90) { Room room = new Room(-1, 50); room.setLocation(coordinate.giveLongitude(), coordinate.giveLatitude()); room.setBiotype(Biotype.SNOW); vortexes.addVortexSpace(room); repaint(); } } //TODO refaktoroi else if (action.contains("corridors")) { Coordinate coordinate = sphereConverter.giveMouseCoordinates(mouseCoordinateX, mouseCoordinateY); int id = vortexes.getSpace(coordinate.giveLongitude(), coordinate.giveLatitude(), sphereConverter); if (firstChosen == -1) { firstChosen = id; } else { secondChosen = id; if (firstChosen != secondChosen) { VortexSpace first = vortexes.getSpace(firstChosen); VortexSpace second = vortexes.getSpace(secondChosen); double distance = sphereConverter.giveDistance(first.getLocation()[0], first.getLocation()[1], second.getLocation()[0], second.getLocation()[1]); Corridor corridor = new Corridor(-1, distance); int newId = corridors.addCorridor(corridor); first.addNeighbor(newId, secondChosen); second.addNeighbor(newId, firstChosen); } firstChosen = -1; secondChosen = -1; } } else if (action.contains("inner yards")) { } }
e6cf5a60-3f1b-4986-8029-6ef35d7d554a
5
public final DBMultipleStatement createMultipleStatement(final String... queries) { if ((queries == null)||(queries.length == 0)) return null; try { final Connection connection = m_Pool.getConnection(); /* Disable auto commit */ connection.setAutoCommit(false); /* Prepare statements */ final PreparedStatement[] statements = new PreparedStatement[queries.length]; for (int i = 0; i < queries.length; i++) statements[i] = connection.prepareStatement(queries[i], Statement.RETURN_GENERATED_KEYS); return new DBConnection.DBMultipleStatement(connection, statements); } catch (final SQLException e) { LoggingUtility.error("Can't create prepared statement using query: " + e.getMessage()); } catch (final Exception e) { LoggingUtility.error("Connection wasn't established: " + e.getMessage()); } return null; } /* End of 'DBConnection::createStatement' method */
ec50aa55-2d4c-4ab2-a1a3-aeb16d8269be
4
public void update() { if (centerX <= 350 || speedX <= 0) { centerX += speedX; bg1.setSpeedX(0); bg2.setSpeedX(0); } else { bg1.setSpeedX(-MOVESPEED); bg2.setSpeedX(-MOVESPEED); } centerY += speedY; // Handles Jumping if (jumping == true) { speedY++; } // Prevents from going out of the screen if (centerX + speedX < 60) { centerX = 60; } r1.setRect(centerX - 34, centerY - 63 , 68, 63); r2.setRect(r1.getX(), r1.getY() + 63, 68, 64); }
5c2c3112-6636-4730-8591-ac8a9b846a7a
4
public final boolean isVisited(){ if (isStranded()) return false; if (tile1 == null){ return tile2.isVisited(); } if (tile2 == null){ return tile1.isVisited(); } return tile1.isVisited() || tile2.isVisited(); }
e376b2f9-531e-4f96-9891-3b58f5432f27
3
@Override protected void read(InputBuffer b) throws IOException, ParsingException { VariableLengthIntegerMessage vLength = getMessageFactory().parseVariableLengthIntegerMessage(b); b = b.getSubBuffer(vLength.length()); long length = vLength.getLong(); if (length > MAX_LENGTH || length < 0) { throw new ParsingException("String is too long. Maximum length is " + MAX_LENGTH); } byte[] bytes = b.get(0, (int) length); try { message = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.log(Level.SEVERE, "UTF-8 not supported!", e); System.exit(1); } }
4b23e1ea-507b-4fab-819b-3106faeaccd3
9
public void deleteRowFromTable(int id) { int currentTable = tabbedPane.getSelectedIndex(); if(currentTable == 0) { for(int row = 0;row < movieModel.getRowCount();row++) { if(movieModel.getValueAt(row, 0).equals(Integer.toString(id))) { movieModel.removeRow(row); } } } if (currentTable == 1) { for(int row = 0;row < musicModel.getRowCount();row++) { if(musicModel.getValueAt(row, 0).equals(Integer.toString(id))) { musicModel.removeRow(row); } } } if (currentTable == 2) { for(int row = 0;row < tvModel.getRowCount();row++) { if(tvModel.getValueAt(row, 0).equals(Integer.toString(id))) { tvModel.removeRow(row); } } } }
0f1a6436-1f0d-472d-a322-bfacfb125129
2
@Override public void render() { for(int x = 0; x < Game.WIDTH; x+= Tile.TILE_SIZE) { for(int y = 0; y < Game.HEIGHT; y+= Tile.TILE_SIZE) { g.drawImage(Images.WALL, x, y, Tile.TILE_SIZE, Tile.TILE_SIZE, null); } } g.drawImage(Images.BLANK_GUI, 62, 8, 900, 740, null); renderText(new Font("Impact", Font.BOLD, 64), Color.BLUE, 322, 108, "GAME OVER!"); renderText(new Font("Impact", Font.BOLD, 64), Color.black, 190, 270, "You Scored: " + Game.instance.theWorld.thePlayer.getFinalScore()); super.render(); }
a6edc983-4c73-4b8c-931a-8bb8734da7b0
3
public void setIdentificador(TIdentificador node) { if(this._identificador_ != null) { this._identificador_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._identificador_ = node; }
a152deb6-b1ef-482a-b83a-e3a7491496af
4
public void SetNodeSubscriptField(Field field, Persistent obj, NodeReference node) { Long Id = obj.Id; String fieldName = field.getName(); try { Object fieldValue = field.get(obj); if (fieldValue instanceof java.lang.String) { node.set(fieldValue.toString(), Id, fieldName); } else if (fieldValue instanceof java.lang.Long) { long longValue = field.getLong(obj); node.set(longValue, Id, fieldName); } else if (fieldValue instanceof java.util.Date) { Date dateValue = (Date) fieldValue; String strValue = dateValue.toGMTString(); node.set(strValue, obj.Id, fieldName); } } catch (IllegalArgumentException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); log.WriteToFile(e.getMessage(), true); } }
b3ff807a-d813-46b9-9877-9eb5091577e8
1
public void RemoveFromMenu() { if (Glob.instance != null) Glob.instance.paginae.remove(res); RemoveListener(); }
d2cdf139-fb4e-4cc7-8af6-10f78f2baeb3
2
private void changeAccount() { setVisible(false); ArrayList<Booking> bookings = table.getSelectedObjects(); for (Booking booking : bookings) { AccountSelector sel = AccountSelector.getAccountSelector(accounts, accountTypes); sel.setVisible(true); Account account = sel.getSelection(); if (account != null) { booking.setAccount(account); } journalInputGUI.fireTransactionDataChanged(); } }
8dfd7118-5e33-4e3b-adbf-57dea0ec155c
3
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AcessoSistema login = new AcessoSistema(); String nome = request.getParameter("nomeUsuario"); String senha = request.getParameter("Senha"); int result; HttpSession session = request.getSession(); RequestDispatcher view; session.setAttribute("usuario", nome); result = login.verificarDados(nome, senha); if(result == AcessoSistema.ALUNO){ view = request.getRequestDispatcher("menuPrincipalAluno.html"); view.forward(request, response); }else if(result == AcessoSistema.PROFESSOR){ view = request.getRequestDispatcher("menuPrincipalProfessor.html"); view.forward(request, response); }else if(result == AcessoSistema.PESSOA_EXTERNA){ view = request.getRequestDispatcher("menuPrincipalProfessor.html"); view.forward(request, response); }else { request.setAttribute("fracasso", "erro"); view = request.getRequestDispatcher("telaLogin.jsp"); view.forward(request, response); } login.completarTransacoes(); }
be20757a-fd40-4c64-97aa-b2532fd4ec56
3
static String format(String msg, Object... args) { try { if (args != null && args.length > 0) { return String.format(msg, args); } return msg; } catch (Exception e) { return msg; } }
65524b2f-ce29-4df4-8ef3-2c3ad9123905
8
public void clientInput(String input, int type) { if (type == 1) // audio { try { sendMessage("/audio " + Compressor.byteArrayToString(Compressor.compress(Compressor.stringToByteArray(input)))); } catch (IOException e) {} } else // text input { if (input.toLowerCase().equals("/exit") || input.toLowerCase().equals("/disconnect")) { endSession(); System.exit(0); } else { boolean shouldSend = true; // filter reserves stuff try { if (input.toLowerCase().substring(0, 6).equals("/audio")) shouldSend = false; } catch (Exception e) {} if (shouldSend) { try { sendMessage("/text " + Compressor.byteArrayToString(Compressor.compress(Compressor.stringToByteArray(input)))); } catch (IOException e) {} } } } }
47283169-0927-4769-abd3-d4eda8bb2f7e
3
public double[][][] getGridD2ydx1dx3(){ double[][][] ret = new double[this.lPoints][this.mPoints][this.nPoints]; for(int i=0; i<this.lPoints; i++){ for(int j=0; j<this.mPoints; j++){ for(int k=0; k<this.nPoints; k++){ ret[this.x1indices[i]][this.x2indices[j]][this.x3indices[k]] = this.d2ydx1dx3[i][j][k]; } } } return ret; }
06e4b2b1-4896-4a2f-b69b-7ce14a597634
7
public Object [] getResultTypes() { int addm = (m_AdditionalMeasures != null) ? m_AdditionalMeasures.length : 0; int overall_length = RESULT_SIZE+addm; overall_length += NUM_IR_STATISTICS; overall_length += NUM_WEIGHTED_IR_STATISTICS; overall_length += NUM_UNWEIGHTED_IR_STATISTICS; if (getAttributeID() >= 0) overall_length += 1; if (getPredTargetColumn()) overall_length += 2; Object [] resultTypes = new Object[overall_length]; Double doub = new Double(0); int current = 0; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // Unweighted IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; // Weighted IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // Timing stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // sizes resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // ID/Targets/Predictions if (getAttributeID() >= 0) resultTypes[current++] = ""; if (getPredTargetColumn()){ resultTypes[current++] = ""; resultTypes[current++] = ""; } // Classifier defined extras resultTypes[current++] = ""; // add any additional measures for (int i=0;i<addm;i++) { resultTypes[current++] = doub; } if (current != overall_length) { throw new Error("ResultTypes didn't fit RESULT_SIZE"); } return resultTypes; }
5fc9a1ae-7837-4dcd-b6f2-908021f38ef4
6
public boolean createUser(DataRow row) { if(!select(row).isEmpty()) { ErrorDialog errorDialog = new ErrorDialog(true, "W bazie danych istnieje wpis o podanych parametrach.", "DatabaseManager", "createUser(DataRow row)", "row"); errorDialog.setVisible(true); return false; } boolean result; DataRow removed = new DataRow(row.getTableName() + row.getName()); removed.setTableName("removedData"); removed.addAttribute("tableName", row.tableName); removed.addAttribute("objectName", row.name); try { result = local.insert(row); if(!local.select(removed).isEmpty()) { local.remove(removed); } if(server.checkConnection()) { result = result && server.insert(row); if(!server.select(removed).isEmpty()) { server.remove(removed); } } } catch(Exception e) { ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w bazie danych: \n" + e.getMessage(), "DatabaseManager", "createUser(DataRow row)", "row"); errorDialog.setVisible(true); result = false; } return result; }
1a7187ef-0f36-4a90-a903-e9ccb118e5e9
5
private Tile getTileFromGid(Document d, Map m, int x, int y, int gid) { if (gid == 0) { return null; } Tileset tileset = null; NodeList tilesets = d.getElementsByTagName("tileset"); ArrayList<Tileset> ts = new ArrayList<>(); for (int i = 0; i < tilesets.getLength(); ++i) { Element e = (Element) tilesets.item(i); String name = ((Element) e.getElementsByTagName("image").item(0)).getAttribute("source"); name = name.substring(name.lastIndexOf("/") + 1).replaceAll(".png", ""); ts.add(((Tileset) rt.get("tilesets").get(name)).setGidRange(Utils.i((e.getAttribute("firstgid"))))); } for (Tileset t : ts) { if (t.inGidRange(gid)) { tileset = t; break; } } if (tileset != null) { return new Tile(m, new Vector2f(x, y), tileset.getTileSize(), tileset.getTilePosFromGid(gid), tileset); } else { return null; } }
bb2801ec-8491-4afa-8ad8-d78bd9c19918
8
public boolean covers (GeneralizedConditionChunk cond) { if(cond == null) return false; if(!equalsKeys(cond)) return false; for(Dimension i : cond.values()) { Dimension d = get(i.getID()); if(!d.checkMatchAll()) { for(Value j : i.values()) { if(!(d.containsKey(j.getID()))) return false; Value v = d.get(j.getID()); if(v.getActivation() < j.getActivation() && !(Math.abs(v.getActivation() - j.getActivation()) <= Value.GLOBAL_ACTIVATION_EPSILON)) return false; } } } return true; }
acd92342-ecb8-4f71-b6aa-245d88c2b7dc
6
public Point awayFromSegmentationPoint(Point point, int... numbersToSkip) { boolean lResult = false; double lAbsoluteDistance = shape.getDelta() / 2; double lDistance; double lDistance2; double minDistance = 10000; Point firstMinPoint = null; Point secondMinPoint = null; mainCycle: for (int i = 0; i < shape.getListOfPoints().size() - 1; i++) { for (int numberToSkip : numbersToSkip) { if (i == numberToSkip) { continue mainCycle; } } Point firstPoint = shape.getListOfPoints().get(i); Point secondPoint = shape.getListOfPoints().get(i + 1); Point.StraightLine line = new Point.StraightLine(firstPoint, secondPoint); double distance = line.distanceToPoint(point); if (distance < minDistance) { minDistance = distance; firstMinPoint = firstPoint; secondMinPoint = secondPoint; } } if (firstMinPoint != null) { if (minDistance < shape.getDelta()) { point = awaySeg(firstMinPoint, secondMinPoint, point, point); } } return point; }
8b185760-d09a-4554-a12e-7b6d63d09191
9
@Override public List<SearchResult<SequenceMatcher>> searchForwards(final WindowReader reader, final long fromPosition, final long toPosition) throws IOException { // Initialise: final int sequenceLength = matcher.length(); final int lastSequencePosition = sequenceLength - 1; long searchPosition = fromPosition > 0? fromPosition : 0; // While there is data to search in: Window window; while (searchPosition <= toPosition && (window = reader.getWindow(searchPosition)) != null) { // Does the sequence fit into the searchable bytes of this window? // It may not if the start position of the window is already close // to the end of the window, or the sequence is long (potentially // could be longer than any single window - but mostly won't be): final long windowStartPosition = window.getWindowPosition(); final int windowLength = window.length(); final int arrayStartPosition = reader.getWindowOffset(searchPosition); final int arrayLastPosition = windowLength - 1; if (arrayStartPosition + lastSequencePosition <= arrayLastPosition) { // Find the last point in the array where the sequence still fits // inside the array, or the toPosition if it is smaller. final int lastMatchingPosition = arrayLastPosition - lastSequencePosition; final long distanceToEnd = toPosition - windowStartPosition; final int arrayMaxPosition = distanceToEnd < lastMatchingPosition? (int) distanceToEnd : lastMatchingPosition; // Search forwards in the byte array of the window: final List<SearchResult<SequenceMatcher>> arrayResult = searchForwards(window.getArray(), arrayStartPosition, arrayMaxPosition); // Did we find a match? if (!arrayResult.isEmpty()) { final long readerPositionOffset = searchPosition - arrayStartPosition; return SearchUtils.addPositionToResults(arrayResult, readerPositionOffset); } // Continue the search one on from where we last looked: searchPosition += (arrayMaxPosition - arrayStartPosition + 1); // Did we pass the final toPosition? In which case, we're finished. if (searchPosition > toPosition) { return SearchUtils.noResults(); } } // From the current search position, the sequence crosses over in to // the next window, so we can't search directly in the window byte array. // We must use the reader interface on the sequence to let it match // over more bytes than this window has available. // Search up to the last position in the window, or the toPosition, // whichever comes first: final long lastWindowPosition = windowStartPosition + arrayLastPosition; final long lastSearchPosition = toPosition < lastWindowPosition? toPosition : lastWindowPosition; final List<SearchResult<SequenceMatcher>> readerResult = doSearchForwards(reader, searchPosition, lastSearchPosition); // Did we find a match? if (!readerResult.isEmpty()) { return readerResult; } // Continue the search one on from where we last looked: searchPosition = lastSearchPosition + 1; } return SearchUtils.noResults(); }
c33659d9-fba1-4a94-a76f-e5121b251da2
3
public List<Image> getImages() { List<Image> images = new ArrayList<Image>(); Document document = Jsoup.parseBodyFragment(getContent()); for(Element img : document.body().select("img")) { try { URL src = new URL(BakaTsuki.getAbsolute(img.attr("src"))); if (isColorful(src)) { String url = src.toString(); url = url.replace("images/thumb", "images"); url = url.substring(0, url.lastIndexOf('/')); images.add(Image.makeUnloadedImage(url)); } } catch (MalformedURLException e) { e.printStackTrace(); } } return images; }
3b2bf04a-e927-41bc-b90a-a290fff26807
2
public void setOutputMode(String outputMode) { if( !outputMode.equals(AlchemyAPI_Params.OUTPUT_XML) && !outputMode.equals(OUTPUT_RDF) ) { throw new RuntimeException("Invalid setting " + outputMode + " for parameter outputMode"); } this.outputMode = outputMode; }
d26a4e47-b987-49ce-ad85-9f26b6a9b3c1
5
@Override public boolean test(String value) { // TODO Auto-generated method stub if (value == null || value.equals("")) return true; try { int i = Integer.parseInt(value); if (i >= 0 && i <= 9999) return true; return false; } catch (Exception e) { // TODO: handle exception return false; } }
c7e2d473-3047-4c78-87bf-1bd9590f8537
0
public static void add(Node node) { getController().rootPane.getChildren().add(node); }
970aeca1-d192-4e86-b496-08fa484b3e19
0
public int getGold() { return gold; }
8f623631-92cb-47b6-849f-4fb9d4be3f23
6
@Override public V put(K key, V value) { if (size > loadFactor * this.array.length) { resizeTable(); } int i = 0; V data = null; int hash = hash(key, i); Entry<K, V> entry = this.array[hash]; while (entry != null) { if (key.equals(entry.key)) { entry.value = value; if (entry.isDeleted) { entry.isDeleted = false; entry.iterNbr = i; size++; } return value; } else if (entry.isDeleted) { break; } hash = hash(key, i); entry = this.array[hash]; i++; } if (entry == null) { entry = new Entry<K, V>(); entry.key = key; entry.value = value; entry.iterNbr = i; array[hash] = entry; data = value; size++; } return data; }