method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
4e01d9d9-0739-47c1-a2d2-4656f2687a30
8
private void checkKeys() { if (Keyboard.typed(KeyEvent.VK_LEFT)) { moveTiles(Direction.LEFT); if (!hasStarted) hasStarted = true; } if (Keyboard.typed(KeyEvent.VK_RIGHT)) { moveTiles(Direction.RIGHT); if (!hasStarted) hasStarted = true; } if (Keyboard.typed(KeyEvent.VK_UP)) { moveTiles(Direction.UP); if (!hasStarted) hasStarted = true; } if (Keyboard.typed(KeyEvent.VK_DOWN)) { moveTiles(Direction.DOWN); if (!hasStarted) hasStarted = true; } }
6ed6a06d-6174-492c-b23c-81a9bb1c9092
5
public void writeControl (byte type, byte request, short value, short index, byte buf []) throws IOException { if (buf == null) { // assume we're doing a No-Data-Control, and somebody // has to make a 0-length buf buf = new byte[0]; } if (buf.length >= MAX_CONTROL_LENGTH || (type & ControlMessage.DIR_TO_HOST) != 0) throw new IllegalArgumentException (); if (Windows.trace) System.out.println ( "Dev.writeControl, rqt 0x" + Integer.toHexString (0xff & type) + ", req 0x" + Integer.toHexString (0xff & request) + ", value 0x" + Integer.toHexString (0xffff & value) + ", index 0x" + Integer.toHexString (0xffff & index) + ", len " + Integer.toString (buf.length) ); int status = controlMsg (fd, type, request, value, index, buf, 0, (short) buf.length); if (status < 0) throw new USBException ("control write error", -status); }
6d778ef3-4659-4ee6-b1cb-b1d3d66d6fc3
5
public void parse() throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(getFichierObject())); String line = null; String[] lineSplit; String[] vertex; List<Vecteur> vts = new ArrayList<>(); List<Vecteur> vns = new ArrayList<>(); List<Vecteur> vs = new ArrayList<>(); while ((line = br.readLine()) != null) { lineSplit = line.split(" "); // System.out.println("line : "+line); switch (lineSplit[0]) { case "v": Vecteur v = new Vecteur(Double.parseDouble(lineSplit[2]), Double.parseDouble(lineSplit[3]), Double.parseDouble(lineSplit[4])); // System.out.println("v : "+v); vs.add(v); break; case "vn": vns.add(new Vecteur(Double.parseDouble(lineSplit[2]), Double.parseDouble(lineSplit[3]), Double.parseDouble(lineSplit[4]))); break; case "vt": vts.add(new Vecteur(Double.parseDouble(lineSplit[2]), Double.parseDouble(lineSplit[3]), Double.parseDouble(lineSplit[4]))); break; case "f": vertex = lineSplit[1].split("/"); Vertex v1 = new Vertex(vs.get(Integer.parseInt(vertex[0])-1), vts.get(Integer.parseInt(vertex[1])-1), vns.get(Integer.parseInt(vertex[2])-1)); vertex = lineSplit[2].split("/"); Vertex v2 = new Vertex(vs.get(Integer.parseInt(vertex[0])-1), vts.get(Integer.parseInt(vertex[1])-1), vns.get(Integer.parseInt(vertex[2])-1)); vertex = lineSplit[3].split("/"); Vertex v3 = new Vertex(vs.get(Integer.parseInt(vertex[0])-1), vts.get(Integer.parseInt(vertex[1])-1), vns.get(Integer.parseInt(vertex[2])-1)); faces.add(new Face(v1, v2, v3)); vertexs.add(v1); vertexs.add(v2); vertexs.add(v3); break; default: break; } } // facesInitiale.add(faces); // vertexsInitiale.add(vertexs); }
1b417617-1a2f-4b64-9be6-ce14b86cb1cb
9
protected void computeRect(Raster[] sources, WritableRaster dest, Rectangle destRect) { int formatTag = MediaLibAccessor.findCompatibleTag(sources, dest); MediaLibAccessor srcMA1 = new MediaLibAccessor(sources[0], destRect, formatTag); MediaLibAccessor srcMA2 = new MediaLibAccessor(sources[1], destRect, formatTag); MediaLibAccessor dstMA = new MediaLibAccessor(dest, destRect, formatTag); mediaLibImage[] srcMLI1 = srcMA1.getMediaLibImages(); mediaLibImage[] srcMLI2 = srcMA2.getMediaLibImages(); mediaLibImage[] dstMLI = dstMA.getMediaLibImages(); switch (dstMA.getDataType()) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_INT: for (int i = 0 ; i < dstMLI.length; i++) { Image.Max(dstMLI[i], srcMLI1[i], srcMLI2[i]); } break; case DataBuffer.TYPE_FLOAT: case DataBuffer.TYPE_DOUBLE: for (int i = 0 ; i < dstMLI.length; i++) { Image.Max_Fp(dstMLI[i], srcMLI1[i], srcMLI2[i]); } break; } if (dstMA.isDataCopy()) { dstMA.clampDataArrays(); dstMA.copyDataToRaster(); } }
17cb8b9b-f6ca-4607-9d7d-aecb663de23f
0
public boolean isLayer() { return isLayer; }
8822952e-78fb-4896-89db-563128376fe2
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DeliveryPacket)) { return false; } DeliveryPacket other = (DeliveryPacket) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
32f74984-76c7-4630-85f1-4cb57d9faf01
3
public int getMax(int[][] matrix, int startRow) { int curMax = 0; for (int i = startRow; i < matrix.length - 1; i++) { for (int j = i + 1; j < matrix.length; j++) { if (matrix[i][j] > curMax) { curMax = matrix[i][j]; } } } return curMax; }
32132eae-c604-47a3-be1b-ff122ddea88d
1
public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }
0697afb3-f807-499a-a96d-758fcf26441d
5
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
01109dbb-ba78-473a-b039-a5b11c39a825
3
private int getMaxChildHeuristic(Map <Integer, Integer> heuristicMap) { int maxWeight = 0; for (TrieNode child : this.children.values()) { Integer weight = heuristicMap.get(Integer.valueOf(child.getId())); if (weight != null && weight > maxWeight) { maxWeight = weight; } } return maxWeight; }
ee1827ff-aabf-4b06-ab72-bcea58184c1c
7
public DirectionalDeltaSource getDirectionalDelta() { if (empty) throw new IllegalStateException("No element(s) have been added to cumulative delta"); return new DirectionalDeltaSource() { private DirectionalFragment fragment = forward; private int number = 0; private int dataAt = 0; public boolean nextFragment() { if (null == fragment) return false; else fragment = fragment.next(); dataAt = 0; if (0L > fragment.offset) { number = 0; fragment = null; return false; } else { number++; return true; } } public Delta.Type getType() { return FORWARD; } public int getFragmentNumber() { return number; } public int read(byte[] buf, int off, int len) { if (fragment.data.length <= dataAt) return -1; else if (fragment.data.length < len + dataAt) len = fragment.data.length - dataAt; System.arraycopy(fragment.data, dataAt, buf, off, len); dataAt += len; return len; } public int skipBytes(int len) { if (0 > len) throw new IllegalArgumentException(Integer.toString(len)); else if (fragment.data.length < len + dataAt) len = fragment.data.length - dataAt; dataAt += len; return len; } public int read(byte[] buf) { return read(buf, 0, buf.length); } public long getOffset() { return fragment.offset; } public int getLength() { return fragment.data.length; } }; }
b07b7328-ced8-4cbe-9877-e5631911137b
3
@Override public Iterator<T> iterator() { return new Iterator<T>(){ // Classe anonyme LLIterator private SLLNode<T> nextNode = head; private int nbLeft = size; @Override public boolean hasNext() { return nbLeft > 0; } @Override public T next() { if(nbLeft > 0){ T elem = nextNode.value; nextNode = nextNode.next; --nbLeft; return elem; } else throw new NoSuchElementException("Fin de Liste"); } public void remove(){ if(nbLeft == size) throw new IllegalStateException("next() n'a pas été appelé!"); else{ nextNode.prev.prev.next = nextNode; nextNode.prev = nextNode.prev.prev; if(nbLeft+1 == size) head = nextNode.prev; size--; } } }; }
be8215a7-22ba-4ece-9fa1-634d2e7fd000
2
public String getPrettyWarnings() { String warnings = null; if (hasWarnings()) { for (String warnMsg : getWarnings()) { warnings = warnings + "|" + warnMsg; } } else { warnings = "Unknown"; } return warnings; }
450982b6-3671-42d0-ab43-c6774f197b33
7
private void demo() { String protocol = "http://"; String port = ":5910"; String hostname=""; try { hostname = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(hostname.equals("127.0.0.1")) hostname = "localhost"; String baseUrl = protocol + hostname + port; String options = "\n-------------------------------------------------------------------\n" + "*. CRUD operations provided by the service ! \n" + "\t1. GET /user/ should return the user with a specific ID \n" + "\t2. POST /User/ should create a new user \n" + "\t3. DELETE /Tasks/{userId}/{taskId} should delet the task with ID {taskId} for user with ID {userId} \n" + "\t4. POST Tasks/ The user with id user_id add task \n" + "\t5. Send Tasks/Reminder/User/{user_id} sending reminder for users about the tasks of the day \n" + "\t6. Send Tasks/Reminder/Caregiver/{cg_id} sending reminder for users about the tasks of the day \n" + "0. exit ^_^"; ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource resource = client.resource(baseUrl); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String url; int selected = 100; try { Scanner scanner = new Scanner(System.in); while (selected !=0){ String firstname,lastname,gender,email, birthdate; int user_id; switch (selected) { case 1: System.out.print("Enter the user id : "); user_id = Integer.parseInt(br.readLine().toString().trim()); url = baseUrl + "/user/"+user_id; resource = client.resource(url); getUserbyId(resource); break; case 2: url = baseUrl + "/user"; System.out.println("Enter the user firstname "); firstname=br.readLine(); System.out.println("Enter the user lastname "); lastname=br.readLine(); System.out.println("Enter the user birthdate"); birthdate=br.readLine(); System.out.println("Enter the user email "); email=br.readLine(); System.out.println("Enter the user gender (Male/Female) "); gender=br.readLine(); resource = client.resource(url); System.out.println(resource); addUser(resource, firstname, lastname, gender, email, birthdate); break; } if(selected!=0) System.out.println(options); System.out.println("Choose the number: "); selected = Integer.parseInt(scanner.next().toString()); } br.close(); } catch (Exception e) { System.err.println("Something went wrong. Check the URI and Parameters !"); e.printStackTrace(); } }
be0f653b-e8b9-4500-9e83-22250eea3111
3
@Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } double x = 0., y = 0.; ThreadLocalRandom rand = ThreadLocalRandom.current(); for (int i = offset; i < iterationsCount; i += threadsCount) { x = rand.nextDouble(); y = rand.nextDouble(); double length = Math.sqrt( x * x + y * y ); if (length <= 1.d) { localCaught++; } } caughtValues.addAndGet(localCaught); }
ef470524-2917-4fe8-9ab7-fadb82a967e6
3
@Test public void lineOneTomorrowAdenExpl() { LinkedList<String> meals = new LinkedList<String>(); LinkedList<String> price = new LinkedList<String>(); Canteen curCanteen = new Canteen(new CanteenData(CanteenNames.ADENAUERRING, 1));// 1 for "tomorrow" for (MealData m : curCanteen.getCanteenData().getLines().get(0).getTodayMeals()) { meals.add(m.getMealName().toLowerCase()); price.add(m.getS_price().toString()); } userInput.add("hello"); userInput.add("i am bettina"); userInput.add("what can i eat at line one in canteen adenauerring tomorrow"); userInput.add("whats the price of " + meals.get(0)); this.runMainActivityWithTestInput(userInput); for (int i = 0; i < meals.size(); i++) { assertTrue(nlgResults.get(2).toLowerCase().contains(meals.get(i))); } if (meals.size() > 0) { assertTrue(nlgResults.get(3).contains(price.get(0))); } }
3b493429-f110-4df3-a765-4e2081c0ff98
7
public static void playSound(String pathToFX) { try { soundFile = new File(pathToFX); } catch (Exception e) { e.printStackTrace(); } try { audioStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e) { e.printStackTrace(); } audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } sourceLine.start(); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { @SuppressWarnings("unused") int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); } } sourceLine.drain(); sourceLine.close(); System.out.println("done playing music"); }
ab7968ed-bc2e-4cfb-ab19-46315d4b79a8
7
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("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE>Agent table </TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>Welcome to Agent Database </H1>\n"); out.write(" \n"); out.write(" "); try{ Class.forName("oracle.jdbc.OracleDriver") ; Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("SELECT * from Agent ") ; out.write("\n"); out.write(" \n"); out.write(" \n"); out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>Agent ID</TH>\n"); out.write(" <TH>Phone Number</TH>\n"); out.write(" <TH>Email Address</TH>\n"); out.write(" <TH>First Name</TH>\n"); out.write(" <TH>Last Name</TH>\n"); out.write(" <TH>Date of Birth</TH>\n"); out.write(" <TH>Zip Code</TH>\n"); out.write(" <TH>Gender</TH>\n"); out.write(" <TH>Type</TH>\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> <label> \n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(3) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(4) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(5) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(6) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(7) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(8) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(9) ); out.write("</TD>\n"); out.write(" </TR>\n"); out.write(" \n"); out.write(" }\n"); out.write(" "); } out.write('\n'); out.write('\n'); } catch(SQLException sqe) { out.println(sqe); } out.write("\n"); out.write(" \n"); out.write(" </TABLE>\n"); out.write(" \n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"SaveNewAgent.jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Insert Agent\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div> \n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"DeleteAgent.jsp\">\n"); out.write(" <label>Delete an Agent with specific ID\n"); out.write(" <input type=\"text\" name=\"v0\" id=\"value2\" />\n"); out.write(" \n"); out.write(" </label>\n"); out.write(" &nbsp;&nbsp;\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Delete\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" \n"); out.write(" \n"); out.write("\n"); out.write(" </BODY>\n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"AgentPage.jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Back\" />\n"); out.write(" </label>\n"); out.write(" </form>\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); } }
5ae1b772-af93-47e7-a97d-702fdaeee353
4
public static double cbrt(double x) { /* Convert input double to bits */ long inbits = Double.doubleToLongBits(x); int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023; boolean subnormal = false; if (exponent == -1023) { if (x == 0) { return x; } /* Subnormal, so normalize */ subnormal = true; x *= 1.8014398509481984E16; // 2^54 inbits = Double.doubleToLongBits(x); exponent = (int) ((inbits >> 52) & 0x7ff) - 1023; } if (exponent == 1024) { // Nan or infinity. Don't care which. return x; } /* Divide the exponent by 3 */ int exp3 = exponent / 3; /* p2 will be the nearest power of 2 to x with its exponent divided by 3 */ double p2 = Double.longBitsToDouble((inbits & 0x8000000000000000L) | (long)(((exp3 + 1023) & 0x7ff)) << 52); /* This will be a number between 1 and 2 */ final double mant = Double.longBitsToDouble((inbits & 0x000fffffffffffffL) | 0x3ff0000000000000L); /* Estimate the cube root of mant by polynomial */ double est = -0.010714690733195933; est = est * mant + 0.0875862700108075; est = est * mant + -0.3058015757857271; est = est * mant + 0.7249995199969751; est = est * mant + 0.5039018405998233; est *= CBRTTWO[exponent % 3 + 2]; // est should now be good to about 15 bits of precision. Do 2 rounds of // Newton's method to get closer, this should get us full double precision // Scale down x for the purpose of doing newtons method. This avoids over/under flows. final double xs = x / (p2*p2*p2); est += (xs - est*est*est) / (3*est*est); est += (xs - est*est*est) / (3*est*est); // Do one round of Newton's method in extended precision to get the last bit right. double temp = est * HEX_40000000; double ya = est + temp - temp; double yb = est - ya; double za = ya * ya; double zb = ya * yb * 2.0 + yb * yb; temp = za * HEX_40000000; double temp2 = za + temp - temp; zb += za - temp2; za = temp2; zb = za * yb + ya * zb + zb * yb; za = za * ya; double na = xs - za; double nb = -(na - xs + za); nb -= zb; est += (na+nb)/(3*est*est); /* Scale by a power of two, so this is exact. */ est *= p2; if (subnormal) { est *= 3.814697265625E-6; // 2^-18 } return est; }
23782220-69b2-46f9-ad1d-463e2cb23701
1
public void makeDeclaration(Set done) { block.propagateUsage(); block.makeDeclaration(done); if (nextByAddr != null) nextByAddr.makeDeclaration(done); }
b5bf32cb-08dc-4c98-adc1-c71c8a9a5c94
9
public static List<Long> triggerAfterSubmissionEvaluation(Submission submission) { Problem problem = submission.getProblem(); if (problem==null){ throw new IllegalArgumentException("Problem cannot be null"); } if (problem.getId()==0){ throw new IllegalArgumentException("A problem with id 0 is not valid. It must be greater than 1"); } if (submission.getId()==0){ throw new IllegalArgumentException("Submission must be persistent, an id=0 is not allowed"); } // Atualiza a tabela de cache da informacao se o usuario ja acertou um // determinado problema updateUserProblem(submission); // atualiza as informacoes do perfil do usuario (num. de problemas // tentados, numero de problemas corretos) updateProfile(submission.getUserId()); // atualiza no perfil a quantidade de submissões do usuario // updateProfileSubmissionCount(submission.getUserId()); //nao precisa // mais, atualizei tbm no updateProfile if (submission.isEvaluationCorrect()) { // Só precisa atualizar se o tempo for realmente menor double currentFastestSubmission = problem.getFastestSubmissionTime(); if (currentFastestSubmission<=0) currentFastestSubmission = Double.MAX_VALUE; if (submission.getTime() < currentFastestSubmission) { updateFastSubmissionProblem(submission); } } QuestionnaireDao questDao = new QuestionnaireDaoMySQL(); // recupera todos os questionários abertos do usuário que fez a // submissão ArrayList<Long> questIdList = questDao .getQuestBySub(submission.getId()); if (questIdList != null) { for (Long questId : questIdList) { // para cada questionário, recupera os problemas que ele acertou ArrayList<Long> problemIdList = questDao.getProblemCorrect( questId, submission.getId()); /* * Caso o aluno não tenha acertado algum problema do * questionário problemIdList será uma lista vazia. Neste caso a * nota do aluno será 0 */ if (problemIdList != null) { String problems = problemIdList.toString(); problems = problems.replace('[', '('); problems = problems.replace(']', ')'); // atualiza a nota do aluno questDao.updateScore(problems, submission.getId(), questId); } else { // atualiza nota questDao.updateScoreWithEmptyProbList(submission.getId(), questId); } } } return questIdList; }
a4792bbb-238e-4414-8a01-8763cd39b93d
3
@Override public void sort(int[] array) { for( int i = 0, s = array.length; i < s; ++i ) { Integer min = array[i]; int minIndex = i; for( int j = i+1; j < s; ++j ) { if( min > array[j] ) { minIndex = j; min = array[j]; } } int swap = min; array[ minIndex ] = array[i]; array[i] = swap; } }
33c95150-c639-4721-8c27-9a02fb9ba464
1
public static void main(String[] args) { for (String arg : args) { params += arg + "\n"; } }
2f6ca0f9-65c4-4155-8389-615d03044f30
5
@Override public void mousePressed(final MouseEvent e) { final Point p = e.getPoint(); final Element element = getGraphicPanel().getElementAt(p); if (element instanceof Vertex) { final Vertex vertex = (Vertex) element; if (this.edge == null) { this.edge = new Edge(getPanel().getProcess().getNameGenerator().nextEdgeName()); if (vertex.canHaveOutput()) { final BPComponent vertexComponent = (BPComponent) vertex.getComponent(); this.edge.getEdgeComponent().setSourceX(p.x); this.edge.getEdgeComponent().setSourceY(p.y); this.edge.getEdgeComponent().setTargetX(p.x); this.edge.getEdgeComponent().setTargetY(p.y); this.edge.getEdgeComponent().updateComponent(vertexComponent, null); getPanel().getProcess().addElement(this.edge); this.edge.updateSource(vertex, null); // TODO: limit repaint region getPanel().repaint(); } } else { if (vertex.canHaveInput() && !vertex.equals(this.edge.getSource())) { this.edge.updateTarget(vertex, null); final BPComponent vertexComponent = (BPComponent) vertex.getComponent(); this.edge.getEdgeComponent().setTargetX(p.x); this.edge.getEdgeComponent().setTargetY(p.y); this.edge.getEdgeComponent().updateComponent(null, vertexComponent); // TODO: limit repaint region getPanel().repaint(); this.edge = null; } } } }
abf9c242-eab4-41eb-a0cb-9739af5053c3
8
public void mouseClicked(MouseEvent mouse){ System.out.println(mouse.getSource()); if(conversationJLabels!=null){ for(JLabel jl:conversationJLabels){ if(mouse.getSource().equals(jl)){ System.out.println("Clicked JLabel"); for(DialoguePart dp:conversationDialogue){ if(jl.getText().equals(dp.getQuestion())){ flushPanel(conversationWindow,"Answer: "); JLabel answer = new JLabel("<html><p style=\"width:600px\">"+dp.getAnswer()+"</p></html>"); answer.setBackground(new Color(50+r.nextInt(50),200+r.nextInt(50),100+r.nextInt(50))); answer.setOpaque(true); answer.setFont(new Font("Serif", Font.PLAIN, fontSize)); conversationWindow.add(answer); conversationWindow.add(back); conversationWindow.revalidate(); conversationWindow.repaint(); return; } } } } } if(mouse.getSource().equals(back)){ this.changeConversation(conversationDialogue); return; } if(mouse.getSource().equals(exit)){ flushPanel(conversationWindow,"Click on a person to ask questions"); conversationWindow.revalidate(); conversationWindow.repaint(); return; } Point mousePos = new Point(mouse.getX(),mouse.getY()); if(!roomIconClicked(mousePos)){ currentRoom.thingClicked(mousePos); } }
13a5c61c-e2a6-4f07-adec-d5ecab91cf02
5
public EmployeeGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(0, 0, 448, 271); contentPane.add(panel); panel.setLayout(null); JLabel lblEmployee = new JLabel("Employee"); lblEmployee.setBounds(186, 12, 70, 15); panel.add(lblEmployee); JLabel lblName = new JLabel("Name:"); lblName.setBounds(12, 52, 70, 15); panel.add(lblName); txt_E_name = new JTextField(); txt_E_name.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update.update(nameTBL, "name", txt_E_name.getText(), nameID, currentID); } }); txt_E_name.setColumns(10); txt_E_name.setBounds(159, 50, 168, 19); panel.add(txt_E_name); JLabel lblSurname = new JLabel("Surname:"); lblSurname.setBounds(12, 88, 70, 15); panel.add(lblSurname); txt_E_surname = new JTextField(); txt_E_surname.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update.update(nameTBL, "surname", txt_E_surname.getText(), nameID, currentID); } }); txt_E_surname.setColumns(10); txt_E_surname.setBounds(159, 86, 168, 19); panel.add(txt_E_surname); JLabel lblSpecializion = new JLabel("Specialization:"); lblSpecializion.setBounds(12, 123, 108, 15); panel.add(lblSpecializion); txt_E_spec = new JTextField(); txt_E_spec.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update.update(nameTBL, "specialization", txt_E_spec.getText(), nameID, currentID); } }); txt_E_spec.setColumns(10); txt_E_spec.setBounds(159, 121, 168, 19); panel.add(txt_E_spec); JButton btn_E_first = new JButton("<<"); btn_E_first.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { result = query.query(nameTBL, 1, nameID); insertValues(result); currentID = 1; } }); btn_E_first.setBounds(12, 185, 54, 25); panel.add(btn_E_first); JButton btn_E_back = new JButton("<"); btn_E_back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentID > 1) { currentID--; result = query.query(nameTBL, currentID, nameID); while (result[1]==null){ currentID--; result = query.query(nameTBL, currentID, nameID); } insertValues(result); } } }); btn_E_back.setBounds(66, 185, 54, 25); panel.add(btn_E_back); JButton btn_E_forward = new JButton(">"); btn_E_forward.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { currentID++; if (currentID > 0 && currentID <= maxID) { result = query.query(nameTBL, currentID, nameID); while (result[1] == null) { currentID++; result = query.query(nameTBL, currentID, nameID); } insertValues(result); } } }); btn_E_forward.setBounds(118, 185, 54, 25); panel.add(btn_E_forward); JButton btn_E_last = new JButton(">>"); btn_E_last.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { maxID = query.maxID(nameTBL, nameID); currentID = maxID; result = query.query(nameTBL, maxID, nameID); insertValues(result); } }); btn_E_last.setBounds(173, 185, 54, 25); panel.add(btn_E_last); JButton btn_E_new = new JButton("New"); btn_E_new.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { currentID = maxID + 1; frameEGui.txt_E_name.setText(""); frameEGui.txt_E_name.requestFocusInWindow(); frameEGui.txt_E_surname.setText(""); frameEGui.txt_E_spec.setText(""); } }); btn_E_new.setBounds(228, 185, 70, 25); panel.add(btn_E_new); JButton btn_E_save = new JButton("Save"); btn_E_save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newValues[0] = "" + txt_E_name.getText(); newValues[1] = "" + txt_E_surname.getText(); newValues[2] = "" + txt_E_spec.getText(); insert.insert(nameTBL, nameTxtF, newValues); maxID = query.maxID(nameTBL, nameID); } }); btn_E_save.setBounds(296, 185, 68, 25); panel.add(btn_E_save); JButton btn_E_del = new JButton("Del"); btn_E_del.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { delete.delete(nameTBL, nameID, currentID); } }); btn_E_del.setBounds(366, 185, 70, 25); panel.add(btn_E_del); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); }
f7a0ff57-8c53-4ed1-9d61-f2fd7634ae3f
5
@Override public void init(){ global.setSystemLaF(true); if(getParameter("url")!=null) if(!(getParameter("url").equals("none"))){ //loaders.WebFile file=null; String in=""; try { URL url = new URL(getParameter("url")); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); in=""; String str; while ((str = reader.readLine()) != null){ in+=str; } reader.close(); global.getManager().loadXml(in.toString()); } catch (IOException ex) { } } if(getParameter("editable")!=null) super.init(); }
57c50748-07a6-4933-a71f-eb2ed941ce56
5
public void advance() { try { switch (parser.ttype) { case StreamTokenizer.TT_NUMBER: tokenType = TYPE_INT_CONST; intValue = (int)parser.nval; break; case StreamTokenizer.TT_WORD: String word = parser.sval; if (keywords.containsKey(word)) { tokenType = TYPE_KEYWORD; keyWordType = ((Integer)keywords.get(word)).intValue(); } else { tokenType = TYPE_IDENTIFIER; identifier = word; } break; case '"': tokenType = TYPE_STRING_CONST; stringValue = parser.sval; break; default: tokenType = TYPE_SYMBOL; symbol = (char)parser.ttype; break; } lineNumber = parser.lineno(); parser.nextToken(); } catch (IOException ioe) { System.out.println ("JackTokenizer failed during advance operation"); System.exit(-1); } }
1647578c-9969-4dd3-98f4-694236e2fa93
7
public static int searchInsert(int[] A, int target) { if (null == A || 0 == A.length) return 0; int low = 0; int high = A.length - 1; while (low < high) { int mid = (low + high)/2; if (A[mid] == target) return mid; else if (A[mid] < target) low = mid + 1; else if (A[mid] > target) high = mid - 1; } return A[low] < target ? low + 1 : low; }
a95c6cca-22ee-4acb-8c98-60676ac942a1
2
public static void main(String[] args) { System.out.println("Opening port..."); try { serverSocket = new ServerSocket(PORT); } catch (IOException iex) { System.out.println("Unable to attach to port!"); System.exit(1); } do { handeClient(); } while (true); }
3217ac42-a42b-4841-9492-23c3216f48ae
1
public void setSubExpressions(int i, Expression expr) { int diff = expr.getFreeOperandCount() - subExpressions[i].getFreeOperandCount(); subExpressions[i] = expr; expr.parent = this; for (Operator ce = this; ce != null; ce = (Operator) ce.parent) ce.operandcount += diff; updateType(); }
28962908-d0d7-4dce-a298-7a24e637adb9
6
public void mouseReleased(MouseEvent e) { if (layerDrag && (e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { Dimension d = getSize(); CPArtwork artwork = controller.getArtwork(); Object[] layers = artwork.getLayers(); layerDrag = true; layerDragY = e.getPoint().y; int layerOver = (d.height - layerDragY) / layerH; if (layerOver >= 0 && layerOver <= layers.length && layerOver != layerDragNb && layerOver != layerDragNb + 1) { artwork.moveLayer(layerDragNb, layerOver); } layerDrag = false; layerDragReally = false; repaint(); } }
5425de17-d7d3-4974-bbd4-47daff8c4a75
9
public final void handleDestroy(BlockBreakEvent event) { destroy(event); if (event.isCancelled()) return; event.setCancelled(true); Block block = event.getBlock(); block.setType(Material.AIR); if (event.getPlayer().getGameMode() != GameMode.CREATIVE) { for (Iterator<ItemStack> dropped = getDrops().iterator(); dropped.hasNext(); ) { ItemStack item = (ItemStack)dropped.next(); ItemStack item2 = item.clone(); int toDrop = 0; if (BlockAPI.getInstance().getCustomBlock(item) != null) { for (int x = 0; x < BlockAPI.getCustomBlockAmount(item); x++) { double gen = Math.random(); if (gen < getLootPercentageOnExplode()) toDrop++; } item2 = BlockAPI.setCustomBlockAmount(item2, toDrop); } else { for (int x = 0; x < item.getAmount(); x++) { double gen = Math.random(); if (gen < getLootPercentageOnExplode()) toDrop++; } item2.setAmount(toDrop); } if (toDrop>0) block.getWorld().dropItemNaturally(block.getLocation(), item2); } } removeLocation(block.getLocation()); }
d809221a-779f-45a1-ab5f-bbf15144f091
8
public ObjectInfoObjectType(SyntaxPart n1, UnitsPart n2, AccessPart n3, StatusPart n4, DescriptionPart n5, ReferencePart n6, IndexPart n7, DefValPart n8) { syntaxPart = n1; if ( syntaxPart != null ) syntaxPart.setParent(this); unitsPart = n2; if ( unitsPart != null ) unitsPart.setParent(this); max_access = n3; if ( max_access != null ) max_access.setParent(this); statusPart = n4; if ( statusPart != null ) statusPart.setParent(this); descriptionPart = n5; if ( descriptionPart != null ) descriptionPart.setParent(this); referencePart = n6; if ( referencePart != null ) referencePart.setParent(this); indexPart = n7; if ( indexPart != null ) indexPart.setParent(this); defValPart = n8; if ( defValPart != null ) defValPart.setParent(this); }
5bfbfe99-27af-4f72-856d-942c8cb30aa9
9
private void pollInput() { while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { if (!toast.visible) { if (Keyboard.getEventKey() == Keyboard.KEY_A) { Main.getGamestate().getPlayer().move(-1, 0); } else if (Keyboard.getEventKey() == Keyboard.KEY_D) { Main.getGamestate().getPlayer().move(1, 0); } else if (Keyboard.getEventKey() == Keyboard.KEY_W) { Main.getGamestate().getPlayer().move(0, -1); } else if (Keyboard.getEventKey() == Keyboard.KEY_S) { Main.getGamestate().getPlayer().move(0, 1); } else if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { new MenuScreen(); return; } checkNewPos(); } else { if (Keyboard.getEventKey() == Keyboard.KEY_RETURN) { Main.setGamestate(null); new MenuScreen(); } } } } }
c911304d-bf2b-41dc-b327-598d8952c09c
1
public byte[] findAttribute(String name) { if (unknownAttributes != null) return (byte[]) unknownAttributes.get(name); return null; }
7495540c-335b-4715-ae85-75393e4f3b65
7
public void reset() { for (int z = 0; z < mapSizeZ; z++) { for (int x = 0; x < mapSizeX; x++) { for (int y = 0; y < mapSizeY; y++) { groundTiles[z][x][y] = null; } } } for (int i = 0; i < SceneGraph.anInt472; i++) { for (int j = 0; j < SceneGraph.cullingClusterPointer[i]; j++) { SceneGraph.cullingClusters[i][j] = null; } SceneGraph.cullingClusterPointer[i] = 0; } for (int i = 0; i < interactiveObjectCachePos; i++) { interactiveObjectCache[i] = null; } interactiveObjectCachePos = 0; for (int i = 0; i < SceneGraph.interactiveObjects.length; i++) { SceneGraph.interactiveObjects[i] = null; } }
55f6f87e-d0ad-4b64-bd3a-1e9cddcc2893
4
public void toggle(){ if (bombsBeingRevealed || isOpen) return; if (markIndex == 0) MainFrame.changeFlagCount(true); else if (markIndex == 1) MainFrame.changeFlagCount(false); ++markIndex; markIndex %= 3; /* if (markIndex != 0) getModel().setEnabled(false); else{ getModel().setEnabled(true); } */ chooseIcon(false); }
8380e44a-5eb7-4bda-a478-20117b81d487
4
public List<AssignmentObj> getAssignmentTable(PreparedStatement pre, boolean inner) { List<AssignmentObj> items = new LinkedList<AssignmentObj>(); try { ResultSet rs = pre.executeQuery(); if (rs != null) { while (rs.next()) { AssignmentObj item = new AssignmentObj(); item.setAsmId(rs.getInt("asm_id")); item.setTopicId(rs.getInt("topic_id")); item.setClassname(rs.getString("classname")); item.setDeadline(new SimpleDateFormat("dd/MM/yyyy").format(rs.getTimestamp("deadline"))); if(inner){ item.setName(rs.getString("name")); } items.add(item); } } } catch (Exception ex) { ex.printStackTrace(); } return items; }
e491f042-ccd3-48ff-b48e-b61788d55fa6
2
private void isEqualToInteger(final Object param, final Object value) { if (value instanceof Integer) { if (!((Integer) value).equals(((Integer) param))) { throw new IllegalStateException("Integers are not equal."); } } else { throw new IllegalArgumentException(); } }
d45fa34a-41fb-4cc8-972b-d8a80e9ecc59
8
public Node getNodeAt(Graphics2D g2, Point point) { Rectangle rect = new Rectangle(point.x - 1, point.y - 1, 3, 3); for (Node node : tree.getExternalNodes()) { Shape taxonLabelBound = tipLabelBounds.get(node); if (taxonLabelBound != null && g2.hit(rect, taxonLabelBound, false)) { return node; } } for (Node node : tree.getNodes()) { Shape branchPath = transform.createTransformedShape(treeLayoutCache.getBranchPath(node)); if (branchPath != null && g2.hit(rect, branchPath, true)) { return node; } Shape collapsedShape = transform.createTransformedShape(treeLayoutCache.getCollapsedShape(node)); if (collapsedShape != null && g2.hit(rect, collapsedShape, false)) { return node; } } return null; }
7f720f05-d571-48b3-ba00-34646cd790c7
1
Item newDouble(final double value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(DOUBLE).putLong(key.longVal); result = new Item(index, key); put(result); index += 2; } return result; }
9574850f-6538-4913-b8ab-ece14f1265f9
0
public void setHora(int hora) { this.hora = hora; }
20a9439a-172f-406d-82ad-f8c91bcce425
3
public void addNewOccurrence(String document) { //Duplicate checking boolean add = true; for(Occurrence occ: docsList.toArray()){ if(occ.getDocName().compareTo(document) == 0){ add = false; occ.incFrequency(); } } if(add){ docsList.insert(document); incFrequency(); } }
d9b11d77-940e-44bf-bcaa-bb95e61c6423
7
@Override public boolean tick(Tickable ticking, int tickID) { final Physical affected = this.affected; if((affected instanceof MOB)&&(this.beingSpoken(ID()))) { final MOB mob=(MOB)affected; final Room R=mob.location(); if((R!=null) &&(R.getArea() instanceof BoardableShip) ||((mob.riding()!=null)&&(mob.riding().rideBasis()==Rideable.RIDEABLE_WATER))) { // fine. } else { Ability A=mob.fetchAbility(ID()); if(A==null) A=this; A.invoke(mob, new Vector<String>(1), null, false, 0); } } return super.tick(ticking, tickID); }
040585ea-fc6d-4ffd-b78f-ef46293bd1b3
3
@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { logger.info("User Login to initialize authorized....."); ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal(); //1)获取用户信息的所有资料,如权限角色等. User user = userService.findUser(shiroUser.loginName); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //2)info.setRoles(角色集合); List<Role> roleLists = roleService.selectList(user.getId()); for(Role role: roleLists){ info.addRole(role.getRoleName()); //3)info.setStringPermissions(权限集合); List<Permission> permissionLists = permissionService.selectList(role.getId()); for(Permission permission: permissionLists){ info.addStringPermission(permission.getPermissionName()); } } logger.info("User [" + user.getUserName()+ "] logged in successfully."); return info; }else{ logger.info("User [" + user.getUserName()+ "] logged in fail.!"); return null; } }
f1cd7dfe-9756-4ca4-b5a4-91712b50e3c4
9
public void buyPotatoes(String hisName) { Scanner scan = new Scanner(System.in); for (int i = 0; i < theGame.listOfFarmers.length; i++) { if (hisName.equalsIgnoreCase(theGame.getFarmersName(i))) { System.out.println("You can buy " + theGame.getFarmersAmountOfPotatoes(i) + " potatoes from " + theGame.getFarmersName(i) + " for " + theGame.getFarmersPrice(i) + " each."); System.out.print("Would you like to buy some potatoes? (y/n)\n > "); String answer = scan.nextLine().trim(); while (! answer.equalsIgnoreCase("y")) { if (answer.equalsIgnoreCase("n")) { break; } System.out.print("Would you like to buy some potatoes? (y/n)\n > "); answer = scan.nextLine().trim(); } if (answer.equalsIgnoreCase("y")) { while (true) { System.out.print("How many would you like to buy?\n > "); try { int amount = Integer.parseInt(scan.nextLine().trim()); if (amount > theGame.getFarmersAmountOfPotatoes(i)) { System.out.println("You can't buy that many potatoes."); } else if (amount <= 0) { System.out.println("You need to buy at least 1 potato."); } else { System.out.println("You succesfully bought " + amount + " potatoes from " + theGame.getFarmersName(i)); theGame.removePotatoesFromFarmer(i, amount); break; } } catch (final NumberFormatException e) {} // if (amount > theGame.getFarmersAmountOfPotatoes(i)) // { // System.out.println("You can't buy that many potatoes."); // } // else if (amount <= 0) // { // System.out.println("You need to buy at least 1 potato."); // } // else // { // System.out.println("You succesfully bought " + amount + " potatoes from " + theGame.getFarmersName(i)); // theGame.removePotatoesFromFarmer(i, amount); // break; // } } } } } }
cc437149-e11b-4e6d-8d1e-31da1025c9e9
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ScyReturPabrikItemPK other = (ScyReturPabrikItemPK) obj; if (!Objects.equals(this.noDokumen, other.noDokumen)) { return false; } if (!Objects.equals(this.pcode, other.pcode)) { return false; } return true; }
794d12fa-e793-412b-9d14-3d6b2286bed9
0
@Override public String toString() { return "rlog:" + name(); }
e19d20ae-e3ce-426c-8b63-cd825d6a02f0
9
private static Player nightPhaseHelper(GameState state, Color faction) { for(Player p : state.getPlayerList()) { if(p.getFaction().equals(faction)) { while(state.getTime() == Time.NIGHT) { Player player = state.getPlayer(faction); if(player != null) { ArrayList<Card> den = new ArrayList<Card>(player.getDen()); Collections.sort(den); int index = den.size()-1; while(index >= 0 && den.get(index).checkPhase(Time.NIGHT)) { index--; } if(index < 0) { state.setTime(Time.PICK_CARDS); } else { state = den.get(index).nightAction(new GameState(state)); //Gotta make sure to check if the card is still in play or not if(state.getPlayer(faction).getDen().contains(den.get(index))) { state.getPlayer(faction).removeFromDen(den.get(index)); Card replacement = den.get(index); replacement.setTrue(Time.NIGHT); state.getPlayer(faction).addToDen(den.get(index)); } } } } for(Card c : state.getPlayer(faction).getDen()) { state.getPlayer(faction).removeFromDen(c); c.resetPhases(); state.getPlayer(faction).addToDen(c); } return state.getPlayer(faction); } } return null; }
b3472cb7-57f8-4571-8404-e70b90ff0e7f
4
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == krakButton) { if(task.isDone()) { view.setVisible(true); } else { krakButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); osmButton.setEnabled(false); bool = 0; task.execute(); } } else if(e.getSource() == osmButton) { if(task.isDone()) { view.setVisible(true); } else { osmButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); krakButton.setEnabled(false); bool = 1; task.execute(); } } }
e9f9b429-b391-45b0-84f5-c9570d3275e7
5
private void load(){ String path=""; defaults = new ArrayList<ArrayList<String>>(); try { path = SBStringUtils.getAppPath("data"); File file = new File(path, fileName); if (file.exists()){ CSVReader reader = new CSVReader(new FileReader(file)); try { while (true){ String[] fields = reader.getAllFieldsInLine(); ArrayList<String> d = new ArrayList<String>(); for (int i=0;i<fields.length;i++){ d.add(fields[i]); } defaults.add(d); } } catch (EOFException e) { } reader.close(); } } catch (Exception e){ e.printStackTrace(); } }
f0dbe0c0-dbdb-4f10-bcd5-58e773109e6c
6
static void lireChoix() { int choix = 0; while (choix < 5) { choix = afficheMenu(); switch (choix) { case 1: // deplacer(porteAvion pa, Avion avion);break; case 2:// decoller(Avion avion);break; case 3:// atterir(Avion avion); break; case 4: // rienFaire(); break; case 5: quitter(); break; default:// On reste dans la boucle. choix = 0; } } }
e298edfe-f231-4e76-8fe3-afc4aac4b776
6
void printBandwidth(PassthroughConnection ptc, long time) { int total = 0; for(int cnt=0;cnt<256;cnt++) { total += ptc.packetCounters[cnt] - ptc.packetLastCounters[cnt]; } ptc.printLogMessage(""); ptc.printLogMessage("Bandwidth Stats - last " + (period/1000) + " seconds" ); for(int cnt=0;cnt<256;cnt++) { int usage = ptc.packetCounters[cnt] - ptc.packetLastCounters[cnt]; if(usage > total/100) { printBandwidthLine("0x" + Integer.toHexString(cnt), usage, total, time); } } ptc.printLogMessage(""); printBandwidthLine("Total", total, total, time); total = 0; for(int cnt=0;cnt<256;cnt++) { total += ptc.packetCounters[cnt]; } ptc.printLogMessage(""); ptc.printLogMessage("Bandwidth Stats - since login" ); ptc.printLogMessage(""); for(int cnt=0;cnt<256;cnt++) { int usage = ptc.packetCounters[cnt]; if(usage > total/100) { printBandwidthLine("0x" + Integer.toHexString(cnt), usage, total, time); } } ptc.printLogMessage(""); printBandwidthLine("Total", total, total, time); ptc.printLogMessage(""); clearCounters(); }
5125eacb-3770-4596-acb2-816a9b2ccbb5
0
public void setSampleOutput(String sampleOutput) { this.sampleOutput = sampleOutput; }
d5a4a871-1343-4010-be6c-b3c0a4752162
8
public void ge_while_jump(TextArea area,String prefix,int cur_while_num){ if(or_last<=0 && and_last<=0){ String instr =prefix+ "br i1 %cmp"+String.valueOf(cmp_num-1)+", label %land.lhs.true"+String.valueOf(true_num)+", label %lor.lhs.false"+String.valueOf(false_num)+"\n\n"; area.append(instr); } else if(or_last>=1 && and_last<=0){ String instr = prefix + "br i1 %cmp" + String.valueOf(cmp_num - 1) + ", label %land.lhs.true" + String.valueOf(true_num) + ", label %while.end" + String.valueOf(cur_while_num) + "\n\n"; area.append(instr); } else if(or_last<=0 && and_last>=1){ String instr = prefix +"br i1 %cmp"+String.valueOf(cmp_num-1)+", label %while.body"+String.valueOf(cur_while_num)+", label %lor.lhs.false"+String.valueOf(false_num)+"\n\n"; area.append(instr); } else if(or_last>=1 && and_last>=1){ String instr = prefix + "br i1 %cmp" + String.valueOf(cmp_num-1) + ", label %while.body" + String.valueOf(cur_while_num) + ", label %while.end" + String.valueOf(cur_while_num) + "\n\n"; area.append(instr); } }
fe6eba68-c1a2-47d1-81bd-ac3ad04d4577
5
private void calculateExtremPoints() { ModelProxy tmp; String[] lowest = new String[]{"bottom", "left", "far"}; String[] highest = new String[]{"top", "right", "near"}; for (Map.Entry i : models.entrySet()) { tmp = (ModelProxy) i.getValue(); for (String k : highest) { if (tmp.getExtremPoint(k) > extremPoints.get(k)) { extremPoints.put(k, tmp.getExtremPoint(k)); } } for (String k : lowest) { if (tmp.getExtremPoint(k) < extremPoints.get(k)) { extremPoints.put(k, tmp.getExtremPoint(k)); } } } }
69f2d136-0334-44bc-9c7a-4c885fa8d8f4
5
public static void arquivoPerceptron(String nome, Perceptron perceptron, Double[][] amostras, Double[] esperado, Double[][] testes, Double taxa, Integer maxEpocas) { try { FileWriter fileWriter = new FileWriter(nome); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); // for (int i = 0; i < 5; i++) { bufferedWriter.write("\n\nTreinamento \n"); // perceptron.gerarPesos(amostras[0].length); bufferedWriter.write("Pesos iniciais\n"); bufferedWriter.write(perceptron.getPesoBias().toString().replace(".", ",") + ";"); for (Double peso : perceptron.getPesos()) { bufferedWriter.write(peso.toString().replace(".", ",") + ";"); } bufferedWriter.write("\n"); perceptron.treinamento(amostras, esperado, taxa, maxEpocas); bufferedWriter.write("Pesos Finais\n"); bufferedWriter.write(perceptron.getPesoBias().toString().replace(".", ",") + ";"); for (Double peso : perceptron.getPesos()) { bufferedWriter.write(peso.toString().replace(".", ",") + ";"); } bufferedWriter.write("\n"+ perceptron.getStrResult()); // bufferedWriter.write("Epocas = ;" + perceptron.getQuantEpocas() // + "\n"); if(testes != null){ bufferedWriter.write("Saida\n"); for (int j = 0; j < testes.length; j++) { perceptron.executar(testes[j]); bufferedWriter.write(perceptron.getSaida().toString().replace(".", ",")+";"); } } // } bufferedWriter.close(); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
898d3513-b1ad-4564-a4d2-7ba17ad0813e
7
public void doGet(HttpServletRequest sreq, HttpServletResponse sres) throws ServletException, IOException { String path = (String) sreq.getAttribute("javax.servlet.include.servlet_path"); if (path==null) path=sreq.getServletPath(); if (path.length()==0) { path=(String)sreq.getAttribute("javax.servlet.include.path_info"); if (path==null) path=sreq.getPathInfo(); } String forward=(String)_forwardMap.get(path); if(log.isDebugEnabled())log.debug("Forward "+path+" to "+forward); if (forward!=null) { ServletContext context = getServletContext().getContext(forward); String contextPath=sreq.getContextPath(); if (contextPath.length()>1) forward=forward.substring(contextPath.length()); RequestDispatcher dispatch = context.getRequestDispatcher(forward); if (dispatch!=null) { dispatch.forward(sreq,sres); return; } } sres.sendError(404); }
040f2090-3075-4a53-887d-39a0cdcd2f85
2
public void setMinus(GoTerm goTerm) { if( symbolIdSet != null ) symbolIdSet.removeAll(goTerm.symbolIdSet); if( interestingSymbolIdSet != null ) interestingSymbolIdSet.removeAll(goTerm.interestingSymbolIdSet); }
38c11ea6-b454-4b30-b87f-be6f845ae4e0
2
public boolean existComplaint(int id) { for (int i=0; i < complaints.size(); i++) { if (complaints.get(i).getId() == id) return true; } return false; }
6fbf928d-5f17-4f17-8284-eee6874b677e
5
public void doGame() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("what will your fingerprint be?"); String in = br.readLine(); this.client.network.setFingerprint(in); System.out.println("commands are 'connect' and 'disconnect'"); while(true){ in = br.readLine(); System.out.println(" >"+in); if( in.equalsIgnoreCase("disconnect") && this.client.network.isConnected() ){ this.client.network.stop(); } else if (in.equalsIgnoreCase("connect") && !this.client.network.isConnected()){ this.client.network.start(); } else{ System.out.println("what?"); } } }
e198d263-b32c-46d2-b3f3-764317845b1d
5
public boolean isDefault(aos.apib.Base o) { HeartBeatTimer v = (HeartBeatTimer)o; if (v.peerID != __def.peerID) return false; if (v.upload != __def.upload) return false; if (v.download != __def.download) return false; if (baseclasses != null && baseclasses.length == 1) return baseclasses[0].isDefault(o); return true; }
e04ed158-e051-49e5-b5f1-2bb5847e934c
4
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._tipo_ == oldChild) { setTipo((PTipo) newChild); return; } for(ListIterator<PVar> i = this._var_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PVar) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
76840dd0-7286-4133-b9b1-3cc3961b1ba1
0
public LSystemInputPane getInputPane() { return (LSystemInputPane) getSource(); }
892d040a-d773-485d-beed-b6ffc646434b
2
@Override public Vehicule putVehicule(Vehicule v) throws BadResponseException, JSONException { Representation r = new JsonRepresentation(v.toJSON()); r = serv.putResource("intervention/" + interId + "/vehicule", null, r); Vehicule vehicule = null; try { vehicule = new Vehicule(new JsonRepresentation(r).getJsonObject()); } catch (IOException e) { e.printStackTrace(); } catch (InvalidJSONException e) { e.printStackTrace(); } return vehicule; }
cbd05224-4235-48d1-baec-5882729a6680
0
public boolean getGodMode(){ return godMode; }
c466ca5f-ccbd-48ca-8066-99d00bef1463
0
public void setPanel(Panel p) { this.panel = p; }
ef500793-58e8-4fac-932c-fa8342b99106
4
public void setSenao(List<?> list) { for(PComando e : this._senao_) { e.parent(null); } this._senao_.clear(); for(Object obj_e : list) { PComando e = (PComando) obj_e; if(e.parent() != null) { e.parent().removeChild(e); } e.parent(this); this._senao_.add(e); } }
ea7ed4ea-2868-4e85-a58f-5939b2554b2a
9
private void updateOffsets() { if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_LEFT)) { xOffset = 0.0; yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM)) { xOffset = -this.blockWidth / 2.0; yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_RIGHT)) { xOffset = -this.blockWidth; yOffset = 0.0; } else if (this.blockAnchor.equals(RectangleAnchor.LEFT)) { xOffset = 0.0; yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.CENTER)) { xOffset = -this.blockWidth / 2.0; yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.RIGHT)) { xOffset = -this.blockWidth; yOffset = -this.blockHeight / 2.0; } else if (this.blockAnchor.equals(RectangleAnchor.TOP_LEFT)) { xOffset = 0.0; yOffset = -this.blockHeight; } else if (this.blockAnchor.equals(RectangleAnchor.TOP)) { xOffset = -this.blockWidth / 2.0; yOffset = -this.blockHeight; } else if (this.blockAnchor.equals(RectangleAnchor.TOP_RIGHT)) { xOffset = -this.blockWidth; yOffset = -this.blockHeight; } }
7e11ee2d-93a4-4de2-a62b-103cb09c45db
9
private DetectorMatch mozillaCheck( String fileName ) { DetectorMatch back = null ; nsDetector det = new nsDetector() ; // Set an observer... // The Notify() will be called when a matching charset is found. MyMozillaObserver observer = new MyMozillaObserver() ; det.Init( observer ) ; try { File file = new File( fileName ) ; BufferedInputStream imp = new BufferedInputStream( new FileInputStream( file ) ) ; byte[] buf = new byte[1024] ; int len ; boolean done = false ; boolean isAscii = true ; while ( (!done) && ((len = imp.read( buf, 0, buf.length)) != -1 )) { // Check if the stream is only ascii. if ( isAscii ) { isAscii = det.isAscii( buf, len ) ; } // DoIt if non-ascii and not done yet. if ( !isAscii && !done ) { done = det.DoIt( buf, len, false ) ; } } det.DataEnd() ; back = observer.getMatch() ; if (back == null) // nothing was found, try to present a probable result { String prob[] = det.getProbableCharsets() ; if (prob != null) { if (prob.length > 0) { back = new DetectorMatch( prob[0], "", 0) ; } } } } catch (Exception e) { System.out.println( "ERROR" ) ; } return back ; }
e7548ad8-ebbf-44c5-9b15-15bef0b9fa61
7
public void setWaypoint(double x, double y) { targetX = x; targetY = y; double myTheta = state.get(7) % (Math.PI * 2); //my theta, between 0 and 6.28 if(myTheta < 0) myTheta+= Math.PI * 2.0; double yDist = (state.get(1)+scrollY) - targetY; //y and x distance to the waypoint double xDist = (state.get(0)+scrollX) - targetX; //System.out.print((Math.sqrt((yDist * yDist) + (xDist * xDist))) + " "); if((Math.sqrt((yDist * yDist) + (xDist * xDist)))<30) close = true; //if it hit, stop moving else close = false; double TTotal = Math.asin(yDist / (Math.sqrt((yDist * yDist) + (xDist * xDist)))); //waypoint's theta relative to origin of ship if(xPos+scrollX>x) { if(TTotal > 0) { TTotal = -TTotal + Math.PI; } else TTotal = -TTotal - Math.PI; } TTotal = -TTotal; if(TTotal < 0) TTotal += Math.PI * 2.0; toTurn = TTotal - myTheta; if(toTurn > Math.PI) { toTurn = -(Math.PI * 2.0 - toTurn); } else if (toTurn < -Math.PI) { toTurn = (Math.PI * 2.0 + toTurn); } //speed = Math.min(maxSpeed, maxSpeed * (1-(Math.abs(toTurn) / Math.PI)) * (1-(Math.abs(toTurn) / Math.PI)) * (1-(Math.abs(toTurn) / Math.PI))); speed = Math.min(Math.min(maxSpeed, Math.sqrt((yDist * yDist) + (xDist * xDist))/40.0 * (1-(Math.abs(toTurn) / Math.PI)) * (1-(Math.abs(toTurn) / Math.PI)) * (1-(Math.abs(toTurn) / Math.PI))), state.get(6)+0.5); //yVel = Math.min(20, Math.sqrt((yDist * yDist) + (xDist * xDist)) * (1-(Math.abs(toTurn) / Math.PI))); //System.out.println(speed); //System.out.println(targetX + " " + targetY); //System.out.println(scrollX + " " + scrollY + " " + xPos + " " + yPos); //(toTurn) / Math.PI + " "+ TTotal / Math.PI + " " + myTheta/Math.PI); }
89b345e4-8d22-4b4f-b727-9ae52d3667b1
8
public Vector<String[]> filterTypes( Vector<String[]> oldStreams) { //contains filtered streams Vector<String[]> newStreams = new Vector<String[]>(0,1); if(oldStreams.capacity()>0) { for(int i=0; i < oldStreams.capacity(); i++) { //add mp3 streams if(showMP3Streams.isSelected() && oldStreams.get(i)[4].toLowerCase().startsWith("mp3")) { newStreams.add(oldStreams.get(i)); //add AAC+ streams } else if(showAACStreams.isSelected() && oldStreams.get(i)[4].startsWith("AAC+")) { newStreams.add(oldStreams.get(i)); //the rest of streams } else if(showUnknownStreams.isSelected() && oldStreams.get(i)[4].trim().equals("")){ newStreams.add(oldStreams.get(i)); } } } return newStreams; }
99da8647-41a2-4a54-a518-88a1c25efbe0
0
public String getName() { return name; }
5552134b-5bbd-4428-bddb-2aa1ac8ec515
4
public boolean hasPrayItemInHand(Player p) { //material equals if(!p.getItemInHand().getType().equals(ConfigHandler.prayItem) || !p.getItemInHand().hasItemMeta()) return false; //another check -.- if(!p.getItemInHand().getItemMeta().hasDisplayName()) return false; //has correct name if(p.getItemInHand().getItemMeta().getDisplayName().equalsIgnoreCase(ConfigHandler.prayItemName)) return true; return false; }
b3eae3b0-da6a-4bc1-a981-6cc6d80c5590
2
private void CalcNormals(Vertex[] vertices, int[] indices) { for(int i = 0; i < indices.length; i += 3) { int i0 = indices[i]; int i1 = indices[i + 1]; int i2 = indices[i + 2]; Vector3f v1 = vertices[i1].GetPos().Sub(vertices[i0].GetPos()); Vector3f v2 = vertices[i2].GetPos().Sub(vertices[i0].GetPos()); Vector3f normal = v1.Cross(v2).Normalized(); vertices[i0].SetNormal(vertices[i0].GetNormal().Add(normal)); vertices[i1].SetNormal(vertices[i1].GetNormal().Add(normal)); vertices[i2].SetNormal(vertices[i2].GetNormal().Add(normal)); } for(int i = 0; i < vertices.length; i++) vertices[i].SetNormal(vertices[i].GetNormal().Normalized()); }
a864626a-7a01-4a74-a75e-e873b95711ad
0
public Integer LookupValue(Variable x) { Integer i = valueMap.get(x); return i; }
0431fea5-f925-4422-8193-f4b23bdcef15
3
public void testFactory_between_RInstant() { // test using Days DateTime start = new DateTime(2006, 6, 9, 12, 0, 0, 0, PARIS); DateTime end1 = new DateTime(2006, 6, 12, 12, 0, 0, 0, PARIS); DateTime end2 = new DateTime(2006, 6, 15, 18, 0, 0, 0, PARIS); assertEquals(3, Single.between(start, end1, DurationFieldType.days())); assertEquals(0, Single.between(start, start, DurationFieldType.days())); assertEquals(0, Single.between(end1, end1, DurationFieldType.days())); assertEquals(-3, Single.between(end1, start, DurationFieldType.days())); assertEquals(6, Single.between(start, end2, DurationFieldType.days())); try { Single.between(start, (ReadableInstant) null, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadableInstant) null, end1, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } try { Single.between((ReadableInstant) null, (ReadableInstant) null, DurationFieldType.days()); fail(); } catch (IllegalArgumentException ex) { // expected } }
f7d36a28-33ce-4fc7-95a3-bc0213049990
7
public void renderTile(int xp, int yp, Tile tile) { xp -= xOffset; yp -= yOffset; for (int y = 0; y < tile.sprite.SIZE; y++) { int ya = y + yp; for (int x = 0; x < tile.sprite.SIZE; x++) { int xa = x + xp; if (xa < -tile.sprite.SIZE || xa >= width || ya < 0 || ya >= height) break; if (xa < 0) xa = 0; pixels[xa + ya * width] = tile.sprite.pixels[x + y * tile.sprite.SIZE]; } } }
46c80b04-ebdd-416f-b934-5e571ee7d904
5
public void move() { int pinkoLHS = area.x; int pinkoRHS = area.x + area.width; if (pinkoLHS <= PINKO_MOVE_AREA_LHS) { currentDirection = RIGHT; } if (pinkoRHS >= PINKO_MOVE_AREA_RHS) { currentDirection = LEFT; } if (currentDirection == LEFT){ area.x -= speed; } else if (currentDirection == RIGHT){ area.x += speed; } bottomSpot = getBottomSpot(); topSpot = getTopSpot(); for (int i = 0; i < numberOfPellets; i++){ pellets[i].move(); } }
99b5dfcd-9caf-468e-84aa-e8cc86afc8c8
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Player other = (Player) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (value != other.value) return false; return true; }
36101725-6ed9-49a1-82f6-b92173ec8ee9
8
public void paint(Graphics g) { super.paintComponent(g); Graphics2D graphics_2d = (Graphics2D) g; //draw the chess board graphics_2d.setColor(new Color(0,0,0)); graphics_2d.drawRect(0,0,600,600); graphics_2d.setColor(new Color(128,121,124)); for(int i = 0; i < 500; i += 150) { for(int k = 75; k <= 525; k += 150) { graphics_2d.fillRect(k, i, 75, 75); } } for(int i = 75; i <= 525; i += 150) { for(int k = 0; k < 500; k += 150) { graphics_2d.fillRect(k, i, 75, 75); } } if(highlighted_piece) { graphics_2d.setColor(new Color(255,0,0)); int rectX = (highlighted_x_square-1)*75; int rectY = (8-highlighted_y_square)*75; graphics_2d.fillRect(rectX, rectY, 75, 75); } //draw white pieces for(int i = 0; i < white_pieces.size(); i++) { BoardPiece board_piece = white_pieces.get(i); //set file name string StringBuffer name_buffer = new StringBuffer(board_piece.piece_type); name_buffer.append("_white.png"); String name = name_buffer.toString(); Image piece_image = new ImageIcon(this.getClass().getResource(name)).getImage(); //set coordinates for the piece on the screen int xCord = (board_piece.xCoord-1)*75+18; int yCord = (8-board_piece.yCoord)*75+18; graphics_2d.drawImage(piece_image, xCord, yCord, null); } //draw black pieces for(int i = 0; i < black_pieces.size(); i++) { BoardPiece board_piece = black_pieces.get(i); //set file name string StringBuffer name_buffer = new StringBuffer(board_piece.piece_type); name_buffer.append("_black.png"); String name = name_buffer.toString(); Image image = new ImageIcon(this.getClass().getResource(name)).getImage(); //set coordinates for the piece on the screen int xCord = (board_piece.xCoord-1)*75+18; int yCord = (8-board_piece.yCoord)*75+18; graphics_2d.drawImage(image, xCord, yCord, null); } graphics_2d.setColor(new Color(0,0,0)); if(move_whites) { graphics_2d.drawString("White's move.", 20, 620); } else { graphics_2d.drawString("Black's move.", 20, 620); } }
2dc5afbc-6988-48c7-8d14-5181dbeb02a8
6
protected boolean setEstatCasella( EstatCasella e, int fila, int columna ) throws IndexOutOfBoundsException { switch ( getEstatCasella( fila, columna ) ) { case JUGADOR_A: num_fitxes_a--; break; case JUGADOR_B: num_fitxes_b--; break; case BUIDA: break; } switch ( e ) { case JUGADOR_A: num_fitxes_a++; break; case JUGADOR_B: num_fitxes_b++; break; case BUIDA: break; } caselles[fila][columna] = e; return true; }
5cad60b3-9927-492a-ba77-f0a5a2d4801e
4
public void atBinExpr(BinExpr expr) throws CompileError { int token = expr.getOperator(); int k = CodeGen.lookupBinOp(token); if (k >= 0) { /* arithmetic operators: +, -, *, /, %, |, ^, &, <<, >>, >>> */ if (token == '+') { Expr e = atPlusExpr(expr); if (e != null) { /* String concatenation has been translated into * an expression using StringBuffer. */ e = CallExpr.makeCall(Expr.make('.', e, new Member("toString")), null); expr.setOprand1(e); expr.setOprand2(null); // <---- look at this! className = jvmJavaLangString; } } else { ASTree left = expr.oprand1(); ASTree right = expr.oprand2(); left.accept(this); int type1 = exprType; right.accept(this); if (!isConstant(expr, token, left, right)) computeBinExprType(expr, token, type1); } } else { /* equation: &&, ||, ==, !=, <=, >=, <, > */ booleanExpr(expr); } }
641ae642-4c95-4fb2-a999-6598d4042116
8
protected int countNeighbours(int col, int row) { int total = 0; total = getCell(col-1, row-1) ? total + 1 : total; total = getCell( col , row-1) ? total + 1 : total; total = getCell(col+1, row-1) ? total + 1 : total; total = getCell(col-1, row ) ? total + 1 : total; total = getCell(col+1, row ) ? total + 1 : total; total = getCell(col-1, row+1) ? total + 1 : total; total = getCell( col , row+1) ? total + 1 : total; total = getCell(col+1, row+1) ? total + 1 : total; return total; }
354b6cee-faea-4d1e-a173-96b2969d9107
4
private void fillHotels(List<Hotel> hotels, AbstractDao dao) throws DaoException { if (hotels != null) { for (Hotel hotel : hotels) { Criteria descCrit = new Criteria(); descCrit.addParam(DAO_ID_DESCRIPTION, hotel.getDescription().getIdDescription()); List<Description> desc = dao.findDescriptions(descCrit); if (!desc.isEmpty()) { hotel.setDescription(desc.get(0)); } Criteria cityCrit = new Criteria(); cityCrit.addParam(DAO_ID_CITY, hotel.getCity().getIdCity()); List<City> cities = dao.findCities(cityCrit); if (! cities.isEmpty()) { hotel.setCity(cities.get(0)); } } } }
01b82d23-3516-446a-a0b2-585b8bec34db
7
private FactoryPoint<?> getFactoryPointByName(final List<FactoryPoint<?>> factoryPoints, final String name) { for (final FactoryPoint<?> factoryPoint : factoryPoints) { final FactoryPointMethod<?> factoryPointMethod = (FactoryPointMethod<?>) factoryPoint; if (factoryPointMethod.getMethod().getName().equals(name)) { return factoryPoint; } } assertNotNull(null); return null; }
e23849d9-6e45-4efd-82a0-0cd2ba67a8c6
2
public void stop() { if (volume != Volume.MUTE) { if (clip.isRunning()) clip.stop(); } }
7e326743-c014-4ed3-b9d1-78de0c457afa
4
public void removePiece(Pawn pawn){ if (this.type.equals("start")){ this.numOccupants--; if (this.numOccupants == 0) this.occupied = false; this.pawnList.remove(pawn); } else if (this.type.equals("home")){ this.numOccupants--; if (this.numOccupants == 0) this.occupied = false; this.pawnList.remove(pawn); } else{ this.numOccupants = 0; this.occupied = false; this.playerPieceID = "none"; this.pawnList.clear(); } }
1a7f0c5a-8266-49ce-91ce-19d5718869cb
1
public TDRodCutting(int n, int price[]) { this.n = n; r = new int[price.length]; p = price; cuts = new String[price.length]; r[0] = 0; p[0] = 0; cuts[0] = ""; for (int i = 1; i < price.length; i++) r[i] = Integer.MIN_VALUE; r[n] = cutRod(n); }
05402987-8e24-4fcd-a64e-12fc07e0837f
6
public static boolean chooseOpen() { JFileChooser cho = new JFileChooser(file); cho.setFileSelectionMode(JFileChooser.FILES_ONLY); FileFilter emu = new FileFilter(){{} @Override public boolean accept(File f) { if (f.isDirectory()) return true; String ext = getExtension(f); if (ext != null) { if (ext.equals("db")) return true; else return false; } return false; } @Override public String getDescription() { // TODO Auto-generated method stub return "*.db Database Files"; }}; cho.addChoosableFileFilter((javax.swing.filechooser.FileFilter) emu); cho.setFileFilter(emu); cho.setSelectedFile(file); int choice = cho.showSaveDialog(Main.mainInstance.frame); System.out.println(choice); if (choice == JFileChooser.APPROVE_OPTION) { File f = cho.getSelectedFile(); String ext = getExtension(f); if (ext==null||!ext.equals("db")) f = new File(f.getAbsolutePath()+".db"); return openFile(f); } return false; }
8364471e-f0c3-45ca-b6b9-b8527da2a14e
5
public String loadAgendamento() throws ParseException { Map parametros = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); String dataStr = parametros.get("dataHora").toString(); DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date data2 = inputFormat.parse(dataStr); String idPac = parametros.get("idPaciente").toString(); Integer idPac2 = Integer.parseInt(idPac); String idMed = parametros.get("idMedico").toString(); Integer idMed2 = Integer.parseInt(idMed); String idExa = parametros.get("idExame").toString(); Integer idExa2 = Integer.parseInt(idExa); int i; for (i = 0; i < agendamentos.size(); i++) { if (agendamentos.get(i).getDataHora().compareTo(data2) == 0 && agendamentos.get(i).getIdExame().equals(idExa2) && agendamentos.get(i).getIdPaciente().equals(idPac2) && agendamentos.get(i).getIdMedico().equals(idMed2)) { break; } } this.dataHora = data2; this.idPaciente = idPac2; this.idMedico = idMed2; this.idExame = idExa2; this.obs = agendamentos.get(i).getObs(); this.resultado = agendamentos.get(i).getResultado(); this.pacienteBean = agendamentos.get(i).getPacienteBean(); this.exameBean = agendamentos.get(i).getExameBean(); this.medicoBean = agendamentos.get(i).getMedicoBean(); return "carrega"; }
f0129e6a-8c42-42cb-837d-d8a42e8eb745
9
void start (){ timer.start(); for (int i = 0; i < form.field.length; i++){ for (int j = 0; j < form.field[i].length; j++){ form.field[i][j] = false; } } for (int i = 0; i < form.field.length; i++){ for (int j = 0; j < form.field[i].length; j++) { form.field[i][j] = true; if (j == 2) j = 22; } } for (int i = 0; i < form.field.length; i++){ for (int j = 0; j < form.field[i].length; j++){ form.field[i][j] = true; if (i == 1 && j ==23) i = 11; } } //for (int i = 0; i < formType.length; i++) {formType[i] = i;} //random(0); }
82b8d95e-bcd0-4b94-ad72-821203d2c075
0
public ClientHandeler(ServerConnectionHandler serverConnectionHandler, IdDto oo) { this.conn = serverConnectionHandler; this.id = oo.id; }
11d23a2d-f774-4cfc-bb86-dece04eef8c5
6
public static void DFS(int r, int used, int mask, double curD) { if (used >= dist.length || curD > min) { min = Math.min(curD, min); return; } else for (int i = r; i < dist.length; i++) if ((mask & (1 << i)) == 0) { mask |= (1 << i); for (int j = i + 1; j < dist.length; j++) if ((mask & (1 << j)) == 0) DFS(i + 1, used + 2, mask | (1 << j), curD + dist[i][j]); mask ^= (1 << i); } }
4e9d21c5-36f4-4cf0-87a6-f435f9da351a
8
private void updateButtonState() { if (Simulation.isPaused() && !Simulation.isStarted()) { //if paused and simulation stopped pauseSim.setText("Pause Simulation"); startSim.setText("Start Simulation"); pauseSim.setEnabled(false); } else if (Simulation.isPaused() && Simulation.isStarted()) { // if paused and simulated is running pauseSim.setText("Resume Simulation"); startSim.setText("Stop Simulation"); pauseSim.setEnabled(true); } else if (!Simulation.isPaused() && Simulation.isStarted()) { // if not paused and simulation is running pauseSim.setText("Pause Simulation"); startSim.setText("Stop Simulation"); pauseSim.setEnabled(true); } else if (!Simulation.isPaused() && !Simulation.isStarted()) { //if not paused and not started pauseSim.setText("Pause Simulation"); startSim.setText("Start Simulation"); pauseSim.setEnabled(false); outputStatistics.setEnabled(true); } }
c6615885-1eee-4bc6-998e-e70abfb1b663
7
public boolean addModule(Module module){ boolean attemptToSchedule=true; boolean coupled = false; int count = 0; if (scheduledModules.size() != 0){ for (Module moduleTwo : scheduledModules) { if (checkCoupledModules(module, moduleTwo) != 0) { //ie cannot be scheduled today, as already scheduled one of its clashed modules //can be changed to allow for coupled modules to be scheduled on same day.. will need re-write of room/times class return false; } } } if (coupled == false) { // try to add module to each room.. without clashes. If cannot then // throw exception. while (attemptToSchedule==true) { if (rooms.get(count).addModule(module)==true){ //successfully scheduled a module scheduledModules.add(module); module.setDayNumber(dayNumber); // set the day in the module that the module has been scheduled too. attemptToSchedule = false;//exit loop return true; } //if count become bigger than no of rooms if (count >= (rooms.size() - 1)) { attemptToSchedule = false;//exit loop return false; } count = count + 1; } } return false; //should never reach here. }
7ac5bb8c-b9f4-42f5-9a2b-c4c9d636661d
8
public static int BruteForce (String str, int start, String pattern) { if (str == null || str.length() == 0 || pattern == null || pattern.length() == 0) { return -1; } int i = start, j =0; int sizeS = str.length(), sizeP = pattern.length(); while (i < sizeS && j < sizeP) { if (str.charAt(i) == pattern.charAt(j)) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j == sizeP) { return (i - j); } else { return -1; } }
123e57af-d3e5-4b1a-ba80-36ab8047d593
7
public List<Controls> getControls(boolean detachPrimaryCheckbox) { List<Controls> controlsList = new ArrayList<Controls>(); if (controls == null) { OptionsPanel optionsPanel = new OptionsPanel(); final JCheckBox showTextCHeckBox = new JCheckBox("Show " + getTitle()); if (! detachPrimaryCheckbox) { optionsPanel.addComponent(showTextCHeckBox); } visible = PREFS.getBoolean(getTitle() + isOPenKey, isVisible()); showTextCHeckBox.setSelected(visible); showTextCHeckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { final boolean selected = showTextCHeckBox.isSelected(); if( isVisible() != selected ) { setVisible(selected); } } }); final String whatPrefKey = getTitle() + "_whatToDisplay"; String[] attributes = getAttributes(); final JComboBox combo1 = new JComboBox(attributes); combo1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { String attribute = (String) combo1.getSelectedItem(); setAttribute(attribute); PREFS.put(whatPrefKey, attribute); } }); final String whatToDisplay = PREFS.get(whatPrefKey, null); if( whatToDisplay != null ) { int i = Arrays.asList(attributes).indexOf(whatToDisplay); if( i >= 0 ) { combo1.setSelectedIndex(i); } } optionsPanel.addComponentWithLabel("Display:", combo1); final JSpinner fontSizeSpinner = new JSpinner(new SpinnerNumberModel(defaultFontSize, 0.01, 48, 1)); optionsPanel.addComponentWithLabel("Font Size:", fontSizeSpinner); //final boolean xselected = showTextCHeckBox.isSelected(); //label1.setEnabled(selected); //fontSizeSpinner.setEnabled(selected); final String fontSizePrefKey = getTitle() + "_fontsize"; final float fontsize = PREFS.getFloat(fontSizePrefKey, taxonLabelFont.getSize()); setFontSize(fontsize, false); fontSizeSpinner.setValue(fontsize); fontSizeSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { final float size = ((Double) fontSizeSpinner.getValue()).floatValue(); setFontSize(size, true); PREFS.putFloat(fontSizePrefKey, size); } }); //----------------------------------------- //final boolean xselected = showTextCHeckBox.isSelected(); //label1.setEnabled(selected); //fontSizeSpinner.setEnabled(selected); final String fontMinSizePrefKey = getTitle() + "_fontminsize"; final float size = PREFS.getFloat(fontMinSizePrefKey, 6); setFontMinSize(size, false); final JSpinner fontMinSizeSpinner = new JSpinner(new SpinnerNumberModel(defaultMinFontSize, 0.01, 48, 1)); optionsPanel.addComponentWithLabel("Minimum Size:", fontMinSizeSpinner); //fontMinSizeSpinner.setValue(size); fontMinSizeSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { final float size = ((Double) fontMinSizeSpinner.getValue()).floatValue(); setFontMinSize(size, true); PREFS.putFloat(fontMinSizePrefKey, size); } }); //------------------------- final JSpinner digitsSpinner = new JSpinner(new SpinnerNumberModel(defaultDigits, 2, 14, 1)); if( hasNumericAttributes ) { final JLabel label2 = optionsPanel.addComponentWithLabel("Significant Digits:", digitsSpinner); // label2.setEnabled(selected); // digitsSpinner.setEnabled(selected); final String digitsPrefKey = getTitle() + "_sigDigits"; final int digits = PREFS.getInt(digitsPrefKey, defaultDigits); setSignificantDigits(digits); digitsSpinner.setValue(digits); digitsSpinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { final int digits = (Integer)digitsSpinner.getValue(); setSignificantDigits(digits); PREFS.putInt(digitsPrefKey, digits); } }); } controls = new Controls(getTitle(), optionsPanel, false, false, detachPrimaryCheckbox ? showTextCHeckBox : null); } controlsList.add(controls); return controlsList; }
378d8639-020c-45a8-8b42-4624dd77b9f8
0
@Before public void setUp() { h = new BinaryHeap(); v = new Vertex(0, 0); }