method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0bf035f0-9ee9-4183-b3b6-51bd2a626ab2
9
private static void createConfigs() { for(int z = 0; z < fileList.size(); z++) { String filePath = CONFIG_FOLDER + fileList.get(z); File conf = new File(filePath); if(!conf.exists()) { try { String[] folders = filePath.split("/"); for(int i = 0; i < folders.length - 1; i++) { String folderpath = ""; for(int g = 0; g < i; g++) folderpath += folders[g] + "/"; File folder = new File(folderpath + folders[i]); if(folder.exists()) continue; else if(!folder.mkdir()) MorgulPlugin.log("Folder " + folders[i] + " could not be Created"); } if(conf.createNewFile()) { MorgulPlugin.log("Config " + fileList.get(z) + " Created."); FileWriter fstream = new FileWriter(conf); BufferedWriter bufOut = new BufferedWriter(fstream); Scanner confScan = new Scanner(Config.class.getResourceAsStream("/configs/" + fileList.get(z))); while(confScan.hasNextLine()) bufOut.write(confScan.nextLine() + "\n"); confScan.close(); bufOut.close(); } else MorgulPlugin.log("Config File could not be created."); } catch (IOException e) { MorgulPlugin.log(e.getMessage()); return; } } } }
f667330b-e2e4-41fe-aea4-002a17875550
4
public static void UpperPlaceOfPublication(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Media set place_of_publication = CONCAT( UPPER( LEFT( place_of_publication, 1 ) ) , SUBSTRING( place_of_publication, 2 ))"); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ e.printStackTrace(); } }
9261a462-e66f-438e-8efc-4276e72747b8
7
public String simplifyPath(String path) { String[] paths = path.split("/+"); Deque<String> deque = new LinkedList<String>(); for (String dir : paths) { if (dir.equals(".") || dir.equals("")) { continue; } else if (dir.equals("..")) { if (deque.size() > 0) deque.pop(); } else { deque.push(dir); } } StringBuilder sb = new StringBuilder(); while (!deque.isEmpty()) { sb.append('/'); sb.append(deque.removeLast()); } if (sb.length() == 0) return "/"; return sb.toString(); }
479c9281-2b34-4254-b599-7e71ba61b183
4
public static boolean isPrime_v1 (int num) { if ( num == 1) { return true; } if ( num % 2 == 0 ){ return false; } for ( int i = 3 ; i <= Math.sqrt(num); i += 2 ) { if ( num % i == 0 ) { return false; } } return true; }
94fd8b08-32ad-4838-817e-ea461841f9b6
3
public final char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; }
bad55364-b72c-4989-a6fa-925b47dc7609
2
public void keyPressed(KeyEvent k) { if (k.getKeyCode() == KeyEvent.VK_RIGHT) { myPaddle.moveRight(); padq.offer(new Position(myPaddle.getPosition())); } else if (k.getKeyCode() == KeyEvent.VK_LEFT) { myPaddle.moveLeft(); padq.offer(new Position(myPaddle.getPosition())); } }
95d8edb2-6273-4d0b-865e-afeb3ce9c101
7
public void run() { // get line and buffer from ThreadLocals SourceDataLine line = (SourceDataLine)localLine.get(); byte[] buffer = (byte[])localBuffer.get(); if (line == null || buffer == null) { // the line is unavailable return; } // copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { // if paused, wait until unpaused synchronized (pausedLock) { if (paused) { try { pausedLock.wait(); } catch (InterruptedException ex) { return; } } } // copy data numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { ex.printStackTrace(); } }
3f583413-ef34-4017-9a43-c0738871047c
4
@Override public Object evaluate(Context context) { Iterator<Term> i = terms.iterator(); Object value = i.next().operand.evaluate(context); while (i.hasNext()){ Term next = i.next(); switch (next.operator){ case AND: value = Operations.and(value, next.operand.evaluate(context)); break; case OR: value = Operations.and(value, next.operand.evaluate(context)); break; case XOR: value = Operations.and(value, next.operand.evaluate(context)); break; } } return value; }
112771eb-a3b3-4b1f-9f7a-fa7b6303ec7c
4
public static void main(String[] args) throws UnknownHostException { //Initialize Logger Logger.initialize("thralld_server started at:"+(new Date()).toString(),Level.SEVERE); System.out.println("thralld_server started at:"+(new Date()).toString()); //Setup available commands setupAvailableCommands(); //Set the command prompt commandPrompt += "@" + InetAddress.getLocalHost().getHostName() + ">"; while(true) { //System.out.println("Waiting for commands"); //1. Get the command entered String currCommandLine = getCommandFromConsole(); if(currCommandLine != null) { currCommandLine = currCommandLine.trim(); if(!currCommandLine.isEmpty()) { //Get the name of the command String[] commandLineParts = currCommandLine.split(" "); String mainCommand = commandLineParts[0].toLowerCase(); //If the command is present in available commands if(availableCommands.containsKey(mainCommand)) { //Handle the command. handleCommand(mainCommand, currCommandLine); } else { //Display help message. displayHelpMessage(); } } } } }
c8074437-2eec-44c4-aea8-463b4f53f570
7
@Override public void trainOnInstanceImpl(Instance inst) { this.iterationControl++; double costNow; if (this.iterationControl <= this.numInstancesInitOption.getValue()) { costNow = 0; } else { costNow = (this.costLabeling - this.numInstancesInitOption.getValue()) / ((double) this.iterationControl - this.numInstancesInitOption.getValue()); } if (costNow < this.budgetOption.getValue()) { //allow to label switch (this.activeLearningStrategyOption.getChosenIndex()) { case 0: //Random labelRandom(inst); break; case 1: //fixed maxPosterior = getMaxPosterior(this.classifier.getVotesForInstance(inst)); labelFixed(maxPosterior, inst); break; case 2: //variable maxPosterior = getMaxPosterior(this.classifier.getVotesForInstance(inst)); labelVar(maxPosterior, inst); break; case 3: //randomized maxPosterior = getMaxPosterior(this.classifier.getVotesForInstance(inst)); maxPosterior = maxPosterior / (this.classifierRandom.nextGaussian() + 1.0); labelVar(maxPosterior, inst); break; case 4: //selective-sampling maxPosterior = getMaxPosterior(this.classifier.getVotesForInstance(inst)); labelSelSampling(maxPosterior, inst); break; } } }
febdd57f-45b2-4a69-a9fa-856bb99c232c
1
public void output() { ListElement current = head; while (current != tail.next) { System.out.print(Integer.toString(current.value) + " "); current = current.next; } System.out.println(); }
306dc2a1-3fcb-4971-bc26-6f498b333024
7
@Override public void saveMarks(List<Student> students,int courseId) throws SQLException { Connection connect = null; PreparedStatement statement = null; try { Class.forName(Params.bundle.getString("urlDriver")); connect = DriverManager.getConnection(Params.bundle.getString("urlDB"), Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB")); String selectCourse = "update mark set mark= ? where student_id= ? and course_catalog_id=?"; statement = connect.prepareStatement(selectCourse); for(Student s:students){ for(Mark m:s.getGeneralCourses()){ if(m.getCourse().getId()==courseId){ statement.setInt(1,m.getMark()); statement.setLong(2,s.getId()); statement.setInt(3,courseId); break; } } } statement.execute(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(connect != null) connect.close(); if(statement != null) statement.close(); } }
b474447b-c127-421c-957c-f35c471afd93
5
final int method1859(int i, long l) { if (i != 71) method1859(41, -7L); if (aLong6161 < aLong6160) { aLong6162 += aLong6160 + -aLong6161; aLong6161 += -aLong6161 + aLong6160; aLong6160 += l; return 1; } int i_3_ = 0; do { i_3_++; aLong6160 += l; } while (i_3_ < 10 && aLong6161 > aLong6160); if ((aLong6161 ^ 0xffffffffffffffffL) < (aLong6160 ^ 0xffffffffffffffffL)) aLong6160 = aLong6161; return i_3_; }
fddb44b5-95b1-4e16-b9fc-6f8e363b92c1
5
public void run() { try { String prevChecksum = ""; while(true) { String currentChecksum = getFileChecksum(); if(currentChecksum.equals(prevChecksum)) { Thread.sleep(1000); continue; } BufferedReader fileReader = new BufferedReader(new FileReader(file)); String loop; pw.println(Config.FILE_START); while((loop=fileReader.readLine())!=null) { pw.println(loop); } pw.println(Config.FILE_END); pw.flush(); fileReader.close(); prevChecksum = currentChecksum; } } catch(Exception e) { if(file.exists()) System.out.println("Exception: " + e.toString()); else run(); } }
a0019bd1-b31e-4f87-86d9-1b4000fa00d0
4
public String reactionToString(Reaction R){ String str = ""; for(int i=0; i<R.getReactants().length; i++){ str = str+R.getMolReactants().get(i).toStringf()+" "; if(i!=R.getReactants().length-1){ str = str+"+ "; } } str=str+"---> "; for(int i=0; i<R.getProducts().length; i++){ str = str+R.getMolProducts().get(i).toStringf()+" "; if(i!=R.getProducts().length-1){ str = str+"+ "; } } return str; }
73d7a6a8-89fe-4c33-aeb3-6f8564b6ad9f
7
static void checkDependencyReferencesPresent(List<AccessibleObject> objects, Map<String, AccessibleObject> props) { // iterate overall properties marked by @Property for(int i = 0; i < objects.size(); i++) { // get the Property annotation AccessibleObject ao = objects.get(i) ; Property annotation = ao.getAnnotation(Property.class) ; if (annotation == null) { throw new IllegalArgumentException("@Property annotation is required for checking dependencies;" + " annotation is missing for Field/Method " + ao.toString()) ; } String dependsClause = annotation.dependsUpon() ; if (dependsClause.trim().isEmpty()) continue ; // split dependsUpon specifier into tokens; trim each token; search for token in list StringTokenizer st = new StringTokenizer(dependsClause, ",") ; while (st.hasMoreTokens()) { String token = st.nextToken().trim() ; // check that the string representing a property name is in the list boolean found = false ; Set<String> keyset = props.keySet(); for (Iterator<String> iter = keyset.iterator(); iter.hasNext();) { if (iter.next().equals(token)) { found = true ; break ; } } if (!found) { throw new IllegalArgumentException("@Property annotation " + annotation.name() + " has an unresolved dependsUpon property: " + token) ; } } } }
fcb8dc74-bb7f-40fe-9d41-07dc5bd01438
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String alias = request.getRequestURI().replace(request.getContextPath() + "/", ""); ISimpleDatasetConfiguration dataset = DatasetConfigurationFactory.getDataset(alias); String parRequest = request.getParameter("request"); String parCrs = request.getParameter("crs"); // Operation DescribeSpatialDataset if (parRequest != null && parRequest.toLowerCase().equals("describespatialdataset")) { response.sendRedirect(dataset.getDatasetFeed()); // Operation GetSpatialDataset } else if (parRequest != null && parRequest.toLowerCase().equals("getspatialdataset")) { if (parCrs == null) { throw new OpenSearchException("Missing 'crs' parameter!"); } try { int epsg = Integer.valueOf(parCrs.split(":")[1]); response.sendRedirect(dataset.getDataset(epsg)); } catch (NumberFormatException ex) { throw new OpenSearchException(ex); } // else OpenSearchDescription } else { response.sendRedirect(dataset.getOpenSearchDescriptionDocument()); } } catch (OpenSearchException ex) { PrintWriter writer = response.getWriter(); writer.write("Error: " + ex.getMessage()); writer.close(); } }
8034f509-a0ff-4084-a2f0-825c67478e0e
1
public boolean isRowFiltered(Row row) { if (mRowFilter != null) { return mRowFilter.isRowFiltered(row); } return false; }
1d4010d3-a862-4aba-9766-323b2440eaf1
4
private static void record(Record record, ItemStack stack, int score) { ItemMeta meta = stack.getItemMeta(); List<String> lore = meta.getLore(); boolean set = false; final String loreLine = record.getLoreLine(); for (int i = 0; i < lore.size(); i++) { String string = lore.get(i); if (string.startsWith(loreLine)) { int count = Integer.parseInt(string.substring((loreLine).length())); if (count < score) { lore.set(i, loreLine + score); } set = true; break; } } if (!set) { lore.add(loreLine + score); } meta.setLore(lore); stack.setItemMeta(meta); }
084e60e7-3d53-4d02-b1ca-159db141af22
7
@SuppressWarnings("unchecked") public PairList<Integer, Double> getValueSortedBucket(int material) { material = (material & RawMaterial.MATERIAL_MASK) >> 8; final int numMaterials = Material.values().length; if ((material < 0) || (material >= numMaterials)) return null; if (buckets == null) { final PairList<Integer, Double>[] newBuckets = new PairList[numMaterials]; for (int matIndex = 0; matIndex < numMaterials; matIndex++) { final int matCode = Material.values()[matIndex].mask(); final TreeSet<Pair<Integer, Double>> newBucket = new TreeSet<Pair<Integer, Double>>(new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) { return o1.second.compareTo(o2.second); } }); for (int i = 0; i < total(); i++) { final int resourceCode = get(i); if ((resourceCode & RawMaterial.MATERIAL_MASK) == matCode) { final int resourceValue = value(resourceCode); newBucket.add(new Pair<Integer, Double>(Integer.valueOf(resourceCode), Double.valueOf(resourceValue))); } } final PairSVector<Integer, Double> finalBucket = new PairSVector<Integer, Double>(); final double pieceSize = 1.0 / newBucket.size(); double currValue = 0.0; for (final Pair<Integer, Double> p : newBucket) { finalBucket.add(p.first, Double.valueOf(currValue)); currValue += pieceSize; } newBuckets[matIndex] = finalBucket; } buckets = newBuckets; } return buckets[material]; }
9fb56ed3-acbd-4f99-9bf9-b86f601116be
4
@Override public void stateChanged(ChangeEvent event) { if (event.getSource().equals(startDatePicker.getModel())) { eventStart.set( startDatePicker.getModel().getYear(), startDatePicker.getModel().getMonth(), startDatePicker.getModel().getDay()); if (eventStart.after(eventEnd)) { eventEnd = (Calendar) eventStart.clone (); eventEnd.add(Calendar.DATE, 1); endDatePicker.getModel().setDate( eventEnd.get(Calendar.YEAR), eventEnd.get(Calendar.MONTH), eventEnd.get(Calendar.DATE)); endDatePicker.getModel().setSelected(true); } } if (event.getSource().equals(endDatePicker.getModel())) { eventEnd.set( endDatePicker.getModel().getYear(), endDatePicker.getModel().getMonth(), endDatePicker.getModel().getDay()); if (eventStart.after(eventEnd)) { eventStart = (Calendar) eventEnd.clone (); eventStart.add(Calendar.DATE, -1); startDatePicker.getModel().setDate( eventStart.get(Calendar.YEAR), eventStart.get(Calendar.MONTH), eventStart.get(Calendar.DATE)); startDatePicker.getModel().setSelected(true); } } }
fb6be465-8216-4808-ba4e-fbbd69d309c2
6
private static Method getMethod(Object o, Object[] args, String methodName, Class<?>[] argsArray){ Method method = null; try { method = o.getClass().getMethod(methodName, argsArray); } catch (NoSuchMethodException e) { try{ method = o.getClass().getDeclaredMethod(methodName, argsArray); }catch (NoSuchMethodException e2) { for(int i = 0; i < args.length; i++){ //引数がひとつであれば大丈夫。引数が複数の場合はほぼ無理。一括で引数すべてのスーパークラス取得するので。 if(args[i].getClass().getSuperclass() != null){//primitive, interface, Objectであればスーパークラスはnull argsArray[i] = args[i].getClass().getSuperclass(); } else{//すべてのインターフェースについてためす。j=0...,その後インターフェースのスーパークラス // if(args[i].getClass().getInterfaces() != null){ // Class<?>[] icls = args[i].getClass().getInterfaces(); // for(int j = 0; j < icls.length; j++){ // argsArray[i] = icls[j]; // } // } } counter++; if(counter == 5){ message = "NoSuchMethodException\r\n"; display.append(message); return null; } method = getMethod(o, args, methodName, argsArray); } } } return method; }
bdfb8616-0dd4-4e37-95fc-e35001727b01
6
public void ToolsHouseInputValidated(){ try{ this.SetInput(ReadInput.readLine().trim().toUpperCase()); } catch(IOException e){ SetValidatedInput(false); return; } if(this.Input != EXIT){ try{ int i = Integer.parseInt(Input); if(i == THIRD || i == SECOND || i == FIRST) SetValidatedInput(true); else SetValidatedInput(false); }catch(Exception e){ SetValidatedInput(false); return; } }else{ SetValidatedInput(true); } }
b9709545-44fa-4b8d-9fbf-13918b6540b2
2
public WrapperMoney sellItemBucket(int idx, int count, WrapperMoney in) throws Exception { isValidItem(idx); Bucket b = cache[idx]; int diff = b.value * count - in.sum(); if (diff < 0 ) { return null; } if ( diff ==0 ){ return new WrapperMoney(Arrays.asList(Money.zero)); } return getChange(diff); }
2ee74dc9-925f-49a6-999d-4438630dc2d0
8
public ArrayList<BooksDTO> selectBook(BooksDTO booksDTO, int option, String keyword) { conn = JDBCUtil.getInstance().getConnection(); // 결과 마인드맵 리스트를 담을 객체 ArrayList<BooksDTO> list = new ArrayList<BooksDTO>(); try { System.out.println("나와랏"); if (option == StatusUtil.bookOptionRegistNumber) { pstmt = conn.prepareStatement(GET_BOOKS_REGISTNUMBER); } else if (option == StatusUtil.bookOptionTitle) { pstmt = conn.prepareStatement(GET_BOOKS_TITLE); } else if (option == StatusUtil.bookOptionAuthor) { pstmt = conn.prepareStatement(GET_BOOKS_AUTHOR); } else if (option == StatusUtil.bookOptionPublisher) { pstmt = conn.prepareStatement(GET_BOOKS_PUBLISHER); } else if (option == StatusUtil.bookOptionISBN) { pstmt = conn.prepareStatement(GET_BOOKS_ISBN); } pstmt.setString(1, "%" + keyword + "%"); rs = pstmt.executeQuery(); while (rs.next()) { BooksDTO books = new BooksDTO(); UsersDTO users = new UsersDTO(); books.setBookRegistNumber(rs.getString("bookRegistNumber")); books.setBookTitle(rs.getString("bookTitle")); books.setBookAuthor(rs.getString("bookAuthor")); books.setBookPublisher(rs.getString("bookPublisher")); books.setBookPublicationYear(rs.getInt("bookPublicationYear")); books.setBookISBN(rs.getString("bookISBN")); books.setBookApplicationMark(rs.getInt("bookApplicationMark")); books.setBookCategory(rs.getInt("bookCategory")); books.setBookPrice(rs.getInt("bookPrice")); books.setBookCount(rs.getInt("bookCount")); users.setUserId(rs.getString("bookRentedBy")); books.setBookRentedBy(users); books.setBookStatus(rs.getInt("bookStatus")); books.setBookRentDate(rs.getDate("bookRentDate")); books.setBookReturnDate(rs.getDate("bookReturnDate")); list.add(books); } // test for (int i = 0; i < list.size(); i++) { System.out.println("list얌 " + list.get(i).getBookTitle() + ", " + list.get(i).getBookRentedBy().getUserId()); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }
bb164e85-91b2-4ab2-8c15-b4cf41b8b5ed
7
@Override public void run() { String status = Thread.currentThread().getName(); if(status.equals(Message.send_status)){ this.serialize_send(); } else if(status.equals(Message.receive_status)){ try { this.serialize_receive(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else return; }
da892e83-942d-4992-825c-9f79937778e1
0
public static <T> Query<T> flatternAncestors(T child, Selector<T, T> selector) { return new Query<T>(new AncestorIterable<T>(child, selector )); }
5dbef50d-ddce-42e5-8e0c-7155e813f7cb
2
public void sendCommand(String sql, String date, String task, String subtask){ try{ // Execute SQL query PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1,date); ps.setString(2,task); if (subtask != ""){ ps.setString(3,subtask); } ps.executeUpdate(); ps.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); } }
45acd4ff-4635-4cc4-b85b-8b202c0dec2d
0
public CommingRequesFileTransferHandler(ServerSocket socket, String name) { serverSocket = socket; fileName = name; receiveListInBytes = new ArrayList<byte[]>(); }
1b16be35-ca3e-4485-8c8d-c08f4cf54970
8
public static void main(String[] args) { //process the input first //if the input is from the console Scanner in = null; if (args.length == 0) { in = new Scanner(System.in); } else if (args.length == 1) { File file = new File(args[0]); if (!file.exists() || !file.canRead()) { System.err.println("Problem with input file!"); System.exit(1); } try { in = new Scanner(file); } catch (FileNotFoundException ex) { System.out.println("Error happens when uploading the file!"); } } else { System.out.println("Error with the argument!"); System.exit(1); } ArrayList<Integer> betList = new ArrayList<Integer>(); int num = in.nextInt(); while(num != 0) { int currInput = 0; for (int i = 0; i < num; i++) { currInput = in.nextInt(); betList.add(currInput); } int result = processList(betList); if (result != 0) { System.out.println("The maximum winning streak is " + result + "."); } else { System.out.println("Losing streak."); } betList = new ArrayList<Integer>(); num = in.nextInt(); } }
13ddec03-c373-4aaf-a061-e3ce384a90f5
2
@Override public ParseResult<T, List<A>> parse(LList<T> tokens) { ParseResult<T, List<A>> r = this.parser.parse(tokens); if(!r.isSuccess()) { assert false; // many0 should *always* succeed } // have to match parser at least one time if(r.getValue().size() >= 1) { return r; } return ParseResult.failure("unable to match 'many1'", tokens); }
fdae9ea4-985d-46b1-a076-5dd0a968d581
9
@SuppressWarnings("unchecked") public <P> P as(Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(object).call(name, args).get(); } // [#14] Simulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); }
356a639a-aa0a-4a70-8fbb-b703e8d05fee
9
public static void main(String[] args) throws IOException { while (true) { String[] input = READER.readLine().split(" "); int height = Integer.parseInt(input[0]); int width = Integer.parseInt(input[1]); if (height == 0 && width == 0) { return; } for (int i = 0; i < height; ++i) { char[] line = new char[width]; if (i == 0 || i == height - 1) { Arrays.fill(line, CELL); System.out.println(line); } else { for (int j = 0; j < width; ++j) { if (j == 0 || j == width - 1) { line[j] = CELL; } else { line[j] = POINT; } } System.out.println(line); } } System.out.print("\n"); } }
f914855d-ef38-42aa-9d95-cc59f96ace30
7
public String formatLiteralVariableString(final String str) throws InvalidArgumentException { if (null == str || "".equals(str.trim())) throw new InvalidArgumentException( ErrorMessage.LITERAL_VARIABLE_DEFINITION_NOT_FOUND); if (str.charAt(0) == DomConst.Literal.LITERAL_VARIABLE_PREFIX || str.charAt(0) == DomConst.Literal.LITERAL_BOOLEAN_FUNCTION_PREFIX) return str; AppConstant appConstant = null; try { Integer.parseInt(str); appConstant = getAppConstants().getAppConstant(Val.LABEL); } catch (Exception e) { try { Converter.timeString2long(str); appConstant = getAppConstants().getAppConstant(Duration.LABEL); } catch (Exception e1) { } } if (null == appConstant) return str; String newStr = appConstant.getLabel() + Literal.PREDICATE_START + str + Literal.PREDICATE_END; return newStr; }
b013e08b-b312-41d5-a133-c8d80407b27b
3
private int getNextCellIndex () { int selectedCellIndex = -1; double minF = Double.MAX_VALUE; for (int i = 0; i < openedCells.size(); i++) { Point currentOpenCell = openedCells.get(i); double localF = 0; if (field[currentOpenCell.x][currentOpenCell.y] instanceof EmptyCell) { localF = ((EmptyCell) field[currentOpenCell.x][currentOpenCell.y]).getF(); } if (localF < minF) { minF = localF; selectedCellIndex = i; } } return selectedCellIndex; }
450cde50-7efb-4187-9b9f-5c4e4a6a0671
1
public static void printClockLn(String string, int l) { if (check(l)) { toTerminal(getTime() + " " + string + "\n", l); } }
db5a430a-5f5a-4da9-bf99-8752f3faeab3
4
private int objectState( char next ) { if ( next == ',' ) { buffer.pop(); next = nextValue(); } switch (next) { case END_OBJECT: { popState(); return returnValue( END_OBJECT, state ); } case '"': { parseAndSetString(); buffer.pop(); next = nextValue(); if ( next != ':' ) { throw new IllegalStateException( "Expected ':', found '" + next + "' at pos[" + pos + "]" ); } pushAndSetState( STATE_VALUE ); return returnValue( KEY, state ); } default: { throw new IllegalStateException( "Unexpected '" + next + "' in object at pos[" + pos + "]" ); } } }
604c840e-4a36-42b2-bc59-4415d132966d
9
protected void draw_symbol(Graphics2D g, float xpos, float ypos, Object symbol, int size1) { if (symbol == null) return; int size2 = size1 / 2; g.setStroke(symbolStroke); if (symbol instanceof Ellipse2D.Float) { Ellipse2D.Float circle = (Ellipse2D.Float) symbol; circle.setFrame(xpos - size2, ypos - size2, size1, size1); g.setColor(symbolColor); g.fill(circle); g.setColor(lineColor); g.draw(circle); return; } else if (symbol instanceof Rectangle) { Rectangle rect = (Rectangle) symbol; rect.setRect(xpos - size2, ypos - size2, size1, size1); g.setColor(symbolColor); g.fill(rect); g.setColor(lineColor); g.draw(rect); return; } else if (symbol instanceof NamedGeneralPath) { String name = ((NamedGeneralPath) symbol).getName(); if (name.equals(LineSymbols.UP)) { GeneralPath triangle = ((NamedGeneralPath) symbol).getGeneralPath(); triangle.reset(); triangle.moveTo(xpos, ypos - size2); triangle.lineTo(xpos - size2, ypos + size2); triangle.lineTo(xpos + size2, ypos + size2); triangle.lineTo(xpos, ypos - size2); triangle.closePath(); g.setColor(symbolColor); g.fill(triangle); g.setColor(lineColor); g.draw(triangle); return; } else if (name.equals(LineSymbols.DOWN)) { GeneralPath triangle = ((NamedGeneralPath) symbol).getGeneralPath(); triangle.reset(); triangle.moveTo(xpos - size2, ypos - size2); triangle.lineTo(xpos + size2, ypos - size2); triangle.lineTo(xpos, ypos + size2); triangle.lineTo(xpos - size2, ypos - size2); triangle.closePath(); g.setColor(symbolColor); g.fill(triangle); g.setColor(lineColor); g.draw(triangle); return; } else if (name.equals(LineSymbols.LEFT)) { GeneralPath triangle = ((NamedGeneralPath) symbol).getGeneralPath(); triangle.reset(); triangle.moveTo(xpos - size2, ypos); triangle.lineTo(xpos + size2, ypos - size2); triangle.lineTo(xpos + size2, ypos + size2); triangle.lineTo(xpos - size2, ypos); triangle.closePath(); g.setColor(symbolColor); g.fill(triangle); g.setColor(lineColor); g.draw(triangle); return; } else if (name.equals(LineSymbols.RIGHT)) { GeneralPath triangle = ((NamedGeneralPath) symbol).getGeneralPath(); triangle.reset(); triangle.moveTo(xpos + size2, ypos); triangle.lineTo(xpos - size2, ypos - size2); triangle.lineTo(xpos - size2, ypos + size2); triangle.lineTo(xpos + size2, ypos); triangle.closePath(); g.setColor(symbolColor); g.fill(triangle); g.setColor(lineColor); g.draw(triangle); return; } else if (name.equals(LineSymbols.ERROR)) { GeneralPath path = ((NamedGeneralPath) symbol).getGeneralPath(); path.reset(); path.moveTo(xpos - size2 / 2, ypos - size2 - 2); path.lineTo(xpos + size2 / 2, ypos - size2 - 2); path.lineTo(xpos, ypos - size2 - 2); path.lineTo(xpos, ypos + size2 + 2); path.lineTo(xpos + size2 / 2, ypos + size2 + 2); path.lineTo(xpos - size2 / 2, ypos + size2 + 2); Ellipse2D.Float elli = new Ellipse2D.Float(xpos - size2 / 2 - 0.5f, ypos - size2 / 2 - 0.5f, size2 + 1, size2 + 1); path.append(elli, false); g.setColor(symbolColor); g.fill(elli); g.setColor(lineColor); g.draw(path); return; } } }
b27e43df-524c-4e7d-bcb8-8f48ce8358fc
1
public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; }
73fb12f4-c686-4a97-ba35-ae6563d14840
6
public static void addArticlesIntoDatabase(List<Article> alist) { StringBuffer sb = new StringBuffer("INSERT INTO soc.articles VALUES"); StringBuffer sb2 = new StringBuffer("INSERT INTO soc.coauthors VALUES"); try { if (conn == null || conn.isClosed()) { init(); } if (statement == null || statement.isClosed()) { statement = conn.createStatement(); } for (Article a : alist) { sb.append(a.sql); sb2.append(a.authorsql); } sb.deleteCharAt(sb.length() - 1); sb2.deleteCharAt(sb2.length() - 1); statement.execute(sb.toString()); statement.execute(sb2.toString()); statement.close(); } catch (SQLException e) { e.printStackTrace(); } }
3bf217a0-ce4a-4389-af83-7199071f28d8
8
public boolean stem() { int v_1; int v_2; int v_3; int v_4; // (, line 133 // do, line 134 v_1 = cursor; lab0: do { // call prelude, line 134 if (!r_prelude()) { break lab0; } } while (false); cursor = v_1; // do, line 135 v_2 = cursor; lab1: do { // call mark_regions, line 135 if (!r_mark_regions()) { break lab1; } } while (false); cursor = v_2; // backwards, line 136 limit_backward = cursor; cursor = limit; // do, line 137 v_3 = limit - cursor; lab2: do { // call standard_suffix, line 137 if (!r_standard_suffix()) { break lab2; } } while (false); cursor = limit - v_3; cursor = limit_backward; // do, line 138 v_4 = cursor; lab3: do { // call postlude, line 138 if (!r_postlude()) { break lab3; } } while (false); cursor = v_4; return true; }
b110081a-b30e-4454-86e1-4ea330ae16b6
7
private URL addDownloadKey(URL url, String downloadHost, String downloadKey, String clientId) { if (downloadHost != null && !downloadHost.isEmpty()) { try { url = new URI(url.getProtocol(), url.getUserInfo(), downloadHost, url.getPort(), url.getPath(), url.getQuery(), null).toURL(); } catch (URISyntaxException ex) { //Ignore, just keep old url } catch (MalformedURLException ex) { //Ignore, just keep old url } } String textUrl = url.toString(); if (url.getQuery() == null || url.getQuery().isEmpty()) { textUrl += "?"; } else { textUrl += "&"; } textUrl += "t=" + downloadKey + "&c=" + clientId; try { return new URL(textUrl); } catch (MalformedURLException ex) { throw new Error("Code error: managed to take valid url " + url.toString() + " and turn it into invalid URL " + textUrl); } }
f144d663-da4a-48d4-a3bf-6604936778b7
4
public static void Adjust(int[] a, int i, int n) { int j = 0; int temp = 0; temp = a[i]; j = 2 * i + 1; while(j <= n-1) { if(j < n-1 && a[j] < a[j+1]) j++; if(temp >= a[j]) break; a[(j-1)/2] = a[j]; j = 2 * j + 1; } a[(j-1)/2] = temp; }
2911bea6-70b7-4910-a5fc-799a44565e0f
8
private void repondreRequete (HttpServletRequest requete, HttpServletResponse reponse, Map<String, Action> routes) throws ServletException, IOException { requete.setCharacterEncoding("utf-8"); reponse.setCharacterEncoding("utf-8"); /* for (Object k : requete.getParameterMap().keySet()) System.out.println(k.toString() + " : " + requete.getParameter(k.toString())); */ String action = requete.getServletPath().toLowerCase(); if (action.endsWith("/")) { action = action.substring(0, action.length() - 1); } try { Action route = determinerAction(action, routes); if (route != null) route.repondre(requete, reponse, action); else reponse.sendError(404); } catch (DejaConnecteException e) { requete.getRequestDispatcher(UrlService.page("site/index.jsp")).forward(requete, reponse); requete.setAttribute("erreur", e.getMessage()); } catch (AccesRefuseException e) { requete.getSession().setAttribute(Chaine.PAGE_VOULUE, requete.getServletPath()); reponse.sendError(401); } catch (InterditException e) { reponse.sendError(403); } catch (JeSuisUneLicorneException e) { reponse.sendError(218); } catch (JeSuisUneTheiereException e) { reponse.sendError(418); } catch (Exception e) { e.printStackTrace(); reponse.sendError(500); } }
4ade3a77-d158-40b9-b000-f8f6b126cacd
8
public static final Color checkAlphaColour(int red, int green, int blue, int alpha) { if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; if (alpha < 0) alpha = 0; else if (alpha > 255) alpha = 255; return new Color(red, green, blue, alpha); }
e6125c0f-81bb-4255-a82d-65472af63b1d
3
private static int getValueOf(TokenType type, String s) { switch (type){ case DIGIT: case NTY: case TEEN: int toReturn = type.getValue(s); assert (toReturn >= 0) : "No value found for token type " + type; return toReturn; default: return NO_VAL; } }
1e154c4f-f817-43f5-9ae7-b4cdaa1676b4
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(QuizForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(QuizForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(QuizForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(QuizForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new QuizForm().setVisible(true); } }); }
07c15b72-9b6c-4fbd-845d-ade62fe9a875
1
@Override public Auction bid(String username, int itemId) { // searches.get(itemId)); Auction a = searches.get(itemId); if(a != null){ a.setCurrentBid(a.getCurrentBid()+1); a.setNumerOfBidsRemaining(a.getNumberOfBidsRemaining()-1); a.setOwner(username); // return a; } System.out.println("The price of " + a.getName() + " has increased to " + a.getCurrentBid() + " and the current owner is " + username + ".\n"); return a; }
38f528c7-b6b0-4879-a9fb-ab0af2c6e231
6
public Format setOutputFormat(Format output) { if (output == null || matches(output, outputFormats) == null) return null; RGBFormat incoming = (RGBFormat) output; Dimension size = incoming.getSize(); int maxDataLength = incoming.getMaxDataLength(); int lineStride = incoming.getLineStride(); float frameRate = incoming.getFrameRate(); int flipped = incoming.getFlipped(); int endian = incoming.getEndian(); if (size == null) return null; if (maxDataLength < size.width * size.height * 3) maxDataLength = size.width * size.height * 3; if (lineStride < size.width * 3) lineStride = size.width * 3; if (flipped != Format.FALSE) flipped = Format.FALSE; outputFormat = outputFormats[0].intersects(new RGBFormat(size, maxDataLength, null, frameRate, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, lineStride, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED)); return outputFormat; }
d4781d78-ae3e-4a25-80c6-2353b674d280
6
@Override public void run() { for(int i = 0; i < gots.size(); i++){ if(!gots.get(i).sendInit(seed, nbrOfPlayers, i)){ System.out.println("SENDING INIT FAILED"); } } long desiredSleep = Constants.GAME_SPEED; long diff = 0; while(true) { Byte[] commands = new Byte[nbrOfPlayers]; for(int i = 0; i < nbrOfPlayers; ++i){ commands[i] = gm.getIncomingCommand(i); } //Send movements and frame ID gm.setOutgoingCommands(commands, frameID++); time = System.currentTimeMillis(); try { long sleepingTime = desiredSleep - diff; if(sleepingTime > 0){ Thread.sleep(sleepingTime); } } catch (InterruptedException e) { e.printStackTrace(); } diff = (System.currentTimeMillis() - time) - desiredSleep; } }
d09f6dcf-1830-4d07-bbf1-61e504fb5910
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final DataMessage other = (DataMessage) obj; if (this.sequenceNumber != other.sequenceNumber || this.getSource() != other.getSource()) { return false; } return true; }
d975f641-c5fc-4728-a883-d5bd88457e43
3
@Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("httpcodec", new HttpServerCodec(8192, 8192 * 2, maxChunkSize)); if (blackList != null && blackList.length > 0) { p.addLast("filter", new InboundFilterHandler(blackList)); } if (cachingEnabled) { p.addLast("caching", new InboundCacheHandler(proxyServer)); } p.addLast("proxy", new InboundProxyHandler(proxyServer)); }
6893047f-3250-4bcd-bcef-4cad408034d6
1
@Test public void transferInstructionOpcodeTest() { //To test instruction is not created with illegal opcode for format try { instr = new TransferInstr(Opcode.ADD, 0, 0); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } assertNull(instr);//instr should be null if creation has failed, which it should because of invalid opcode }
c9e54a4e-94f5-40df-92a1-f9f073aed2b0
1
public boolean estEnAttente(){ if(this.etat == EN_ATTENTE){ return true ; } else { return false ; } }
39bec502-1604-4693-8924-8c5c5c2389c7
9
public double distance(double x, double y) { if (x >= left && x <= right) { if (y >= top) { if (y <= bottom) { return 0; } else { return y - bottom; } } else { return top - y; } } else if (y >= top && y <= bottom) { if (x < left) { return left - x; } else { return x - right; } } double dx = x < left ? left - x : x - right; double dy = y < top ? top - y : y - bottom; return Math.sqrt(dx * dx + dy * dy); }
fd8abc6b-0ada-4887-9f38-04e81a04d994
8
public void keyPressed(KeyEvent e){ int keyCode = e.getKeyCode(); //if you press up, move up if(keyCode == KeyEvent.VK_UP){ //if you touch a "w" or wall, the move does not occur if(!m.getMap(p.getTileX(), p.getTileY() - 1).equals("w") ) p.move(0, -1); } //if you press down, move down if(keyCode == KeyEvent.VK_DOWN){ if(!m.getMap(p.getTileX(), p.getTileY() + 1).equals("w")) p.move(0, 1); } //if you press left if(keyCode == KeyEvent.VK_LEFT){ if(!m.getMap(p.getTileX() - 1, p.getTileY() ).equals("w")) p.move(-1, 0); } //if you press right if(keyCode == KeyEvent.VK_RIGHT){ if(!m.getMap(p.getTileX() + 1, p.getTileY() ).equals("w") ) p.move(1, 0); } }//end of keyCode
e889ae2b-2201-4d91-86f8-fa60e9e58974
9
@Override public void mouseDragged(MouseEvent e) { if (e.getSource().equals(this.pnLeftImage) || e.getSource().equals(this.pnRightImage)) { JPanelPicture currentPanel = null; Point currentAnchor = null; JSpinner currentSpinerX = null; JSpinner currentSpinerY = null; if (e.getSource().equals(this.pnLeftImage)) { currentPanel = this.pnLeftImage; currentAnchor = composer.LeftAnchor; currentSpinerX = this.spnrLeftAnchorX; currentSpinerY = this.spnrLeftAnchorY; } if (e.getSource().equals(this.pnRightImage)) { currentPanel = this.pnRightImage; currentAnchor = composer.RightAnchor; currentSpinerX = this.spnrRightAnchorX; currentSpinerY = this.spnrRightAnchorY; } // Двигаем якорь if (this.overPoint == 1) { currentAnchor.setLocation(currentPanel.coorsFromPanelToPic(e.getPoint())); this.stopAutoApply = true; currentSpinerX.setValue(currentAnchor.x); this.stopAutoApply = false; currentSpinerY.setValue(currentAnchor.y); currentPanel.repaint(); } // Двигаем смещением if (this.overPoint == 2) { Point pnt = new Point(currentPanel.coorsFromPanelToPic(e.getPoint())); Point pntPrev = new Point(currentAnchor.x + composer.resultOffsetX, currentAnchor.y + composer.resultOffsetY); this.stopAutoApply = true; this.spnrResultOffsetX.setValue(pnt.x - currentAnchor.x); this.spnrResultOffsetY.setValue(pnt.y - currentAnchor.y); this.spnrWidth.setValue(composer.ResultWidth + (pntPrev.x - pnt.x)); this.stopAutoApply = false; this.spnrHeight.setValue(composer.ResultHeight + (pntPrev.y - pnt.y)); currentPanel.repaint(); } // Двигаем размером изображения if (this.overPoint == 3) { Point pnt = new Point(currentPanel.coorsFromPanelToPic(e.getPoint())); if ((pnt.x - currentAnchor.x - composer.resultOffsetX < 10)|| (pnt.y - currentAnchor.y - composer.resultOffsetY<10) ) return; this.stopAutoApply = true; this.spnrWidth.setValue(pnt.x - currentAnchor.x - composer.resultOffsetX); this.stopAutoApply = false; this.spnrHeight.setValue(pnt.y - currentAnchor.y - composer.resultOffsetY); currentPanel.repaint(); } } }
9785678e-b431-41b2-8948-bc7a8a96cf37
2
@Override public int hashCode() { int result = rWord != null ? rWord.hashCode() : 0; result = 31 * result + (eWord != null ? eWord.hashCode() : 0); return result; }
e78f7f7f-8a9d-4cb9-877d-a1ff0711750d
1
private final String getLabel(final Label label) { String name = (String) labelNames.get(label); if (name == null) { name = Integer.toString(labelNames.size()); labelNames.put(label, name); } return name; }
22ea404a-6d8e-4bd8-9029-c76280f53537
3
private void tblListagemFuncionarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListagemFuncionarioMouseClicked Object valor = tblListagemFuncionario.getValueAt( tblListagemFuncionario.getSelectedRow(), 0); Funcionario funci = null; try { funci = dao.Abrir((int)valor); } catch (ErroValidacaoException ex) { System.out.printf("Erro"); } frmFuncionarioEditar janela = null; try { janela = new frmFuncionarioEditar(funci, dao); } catch (ErroValidacaoException ex) { Logger.getLogger(frmFuncionarioListar.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(frmFuncionarioListar.class.getName()).log(Level.SEVERE, null, ex); } this.getParent().add(janela); janela.setVisible(true); this.setVisible(false); }//GEN-LAST:event_tblListagemFuncionarioMouseClicked
c3bc9909-bbe9-4920-a218-3e895bb7feda
2
private boolean jj_3R_57() { Token xsp; xsp = jj_scanpos; if (jj_3_54()) jj_scanpos = xsp; if (jj_3R_87()) return true; return false; }
8ef61793-265c-4d79-983d-b01517e1be0d
7
public CantroserverView(SingleFrameApplication app) { super(app); initComponents(); owner = (CantroserverApp)app; jList1.addListSelectionListener(this); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.resources.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.resources.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); }
9ad8a8ae-6235-44db-9354-63124793f2a3
5
@Override public void packetIncoming(Packet packet) { if(packet.channel.equals(References.CHANNEL_PLAYER_DC)){ this.playerDC(packet); }else if(packet.channel.equals(References.CHANNEL_JOIN)){ this.join(packet); }else if(packet.channel.equals(References.CHANNEL_STARTGAME)) { this.startGame(packet); }else if(packet.channel.equals(References.CHANNEL_SPAWNPLAYER)) { this.spawnPlayer(packet); }else if(packet.channel.equals(References.CHANNEL_PLAYER_UPDATE)) { this.updatePlayer(packet); }else { Server.sendDataToAll(packet); } }
06c929a0-0bb7-4cec-8d40-79ae8be1f1d3
6
@EventHandler public void WitchResistance(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getWitchConfig().getDouble("Witch.Resistance.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getWitchConfig().getBoolean("Witch.Resistance.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, plugin.getWitchConfig().getInt("Witch.Resistance.Time"), plugin.getWitchConfig().getInt("Witch.Resistance.Power"))); } }
5b15edd9-b5db-41aa-8221-255ef88eec7a
6
public static String unescape(String s) { int len = s.length(); StringBuffer b = new StringBuffer(); for (int i = 0; i < len; ++i) { char c = s.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < len) { int d = JSONTokener.dehexchar(s.charAt(i + 1)); int e = JSONTokener.dehexchar(s.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } b.append(c); } return b.toString(); }
d0026726-6863-4823-955f-a3345385c4f0
9
protected AttributeClassObserver newNumericClassObserver() { switch (this.numericEstimatorOption.getChosenIndex()) { case 0: return new GaussianNumericAttributeClassObserver(10); case 1: return new GaussianNumericAttributeClassObserver(100); case 2: return new GreenwaldKhannaNumericAttributeClassObserver(10); case 3: return new GreenwaldKhannaNumericAttributeClassObserver(100); case 4: return new GreenwaldKhannaNumericAttributeClassObserver(1000); case 5: return new VFMLNumericAttributeClassObserver(10); case 6: return new VFMLNumericAttributeClassObserver(100); case 7: return new VFMLNumericAttributeClassObserver(1000); case 8: return new BinaryTreeNumericAttributeClassObserver(); } return new GaussianNumericAttributeClassObserver(); }
0754c139-d5d5-42a0-8c22-583e4eaa2a74
1
public static void left() { if(GraphicsMain.viewX - 100 > 0) { viewX -= 1; } }
cfe6993f-6de9-458b-89fc-b726f197e0a5
4
@Override public boolean keyDown(int keycode) { switch(keycode) { case Keys.W: direction.y = speed; animationTime = 0; break; case Keys.A: direction.x = -speed; animationTime = 0; break; case Keys.S: direction.y = -speed; animationTime = 0; break; case Keys.D: direction.x = speed; animationTime = 0; break; } return true; }
fe28ac52-21d2-4cfe-bdee-04d5fdd0245c
9
public void canvasMouseReleased(MouseEvent e) { actObjectleft = null; actObjectright = null; if(mytabbedpane.getSelectedIndex()==0) { for(GeometricObject go : geomListleft) { if(go.isInside(e.getX(), e.getY()) != -1) { actObjectleft = go; if(isActive == false) { menuBar.add(go.setOptionsBar(), 1); isActive = true; menuBar.validate(); } selectedGrabber = go.isInside(e.getX(), e.getY()); } else { if(isActive == true) { menuBar.remove(1); isActive = false; menuBar.validate(); } } } } else { for(GeometricObject go : geomListright) { if(go.isInside(e.getX(), e.getY()) != -1) { actObjectright = go; if(isActive == false) { menuBar.add(go.setOptionsBar(), 1); isActive = true; menuBar.validate(); } selectedGrabber = go.isInside(e.getX(), e.getY()); } else { if(isActive == true) { menuBar.remove(1); isActive = false; menuBar.validate(); } } } } repaint(); // update the canvas }
5719a8f4-80f3-4a06-a6e1-5cfcb8c275f9
4
private void listFiles() { FTPClient client = new FTPClient(); try { client.connect("ftp.site.com"); client.login("username", "password"); FTPFile[] files = client.listFiles(); for (FTPFile ftpFile : files) { if (ftpFile.getType() == FTPFile.FILE_TYPE) { System.out.println("File: " + ftpFile.getName() + "size-> " + FileUtils.byteCountToDisplaySize( ftpFile.getSize())); } } client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
768921a2-616c-4f89-89a0-65191bd7dabe
6
public static final boolean contentEquals( Object c1, Object c2 ) { if( c1 == null && c2 == null ) return true; if( c1 == null || c2 == null ) return false; if( c1 instanceof byte[] && c2 instanceof byte[] ) { return equals( (byte[])c1, (byte[])c2 ); } return c1.equals(c2); }
424f6db0-b3d0-4df1-8373-d9185e61493e
7
private void getAllInterface(Class<?> clazz, Set<String> interfacesSet) { Class<?>[] interfaces = clazz.getInterfaces(); Class<?> c = clazz; while (null != c) { interfacesSet.add(c.getName()); c = c.getSuperclass(); } for (Class<?> inte : interfaces) { interfacesSet.add(inte.getName()); } if (!clazz.getSuperclass().getName().equals("java.lang.Object")) { getAllInterface(clazz.getSuperclass(), interfacesSet); } }
a753a376-d4c7-40d5-8de2-e9e6605bd0ce
0
public boolean isBetter(Object other) { double otherValue = ((Quantity) other).convertTo(this.unit); return this.value > otherValue; }
6da462ff-92df-4da0-a61b-862b95ddf5eb
7
public static int fillTableVerbose(int rows, int cols,int colStart,int colEnd){ int cri=1;//current row index. begin calc at table [1][1] int cci=1;//current col. index int up,left,caddy,bestChoice=0,val=0;//the ones to look at and the one to choose. char let1,let2;//left and top seq letters. gene left genome top int endVal=(rows-1)*(cols-1);//table index starts@0.Exit at ending cell. //msg.println("endVal="+endVal); while(cri*cci<=endVal){ bestChoice=0; //msg.println("cri="+cri+" cci="+cci); //start@table[1][1] up=table[cri-1][cci]-2;//does it make sense to sub constants here??? left=table[cri][cci-1]-2; caddy=table[cri-1][cci-1];//up&left //charAt starts index@0 let1=gene.charAt(cri-1);//gene on left let2=gen[0].charAt(cci-1);//genome on top bestChoice=Math.max(up,left); bestChoice=Math.max(bestChoice,caddy);//max of 3 neighbors if(let1==let2&&bestChoice==caddy){//Nucleotides match //msg.println("letters did match and caddy was my choice"); val=1; } else if(let1!=let2&&bestChoice==caddy){//only care about the match/mismatch if bestChoice=caddy, NO GAP //msg.println("letters did NOT match and bestChoice was caddy"); val=-1;//mismatch penalty } else{ val=0;//gap } // msg.println("comparing "+let1+" and "+let2); // msg.println("up="+up); // msg.println("left="+left); // msg.println("caddy="+caddy); // msg.println("bestChoice was"+bestChoice); // msg.println("val is "+val); table[cri][cci]=val+bestChoice;//val of match/mismatch + caddy, up-2 or left-2 if(cri*cci>=endVal){break;} if(cri==rows-1){//last row cri=1;//back to top of table cci++;//move over 1 column } else{ cri++;//increment current row index; } printBoard(table); } msg.println("score="+(val+bestChoice)+"\nFinal board: \n"); printBoard(table); return val+bestChoice;//final allignment score }
cf848bbe-c40e-4f8e-89ff-1014225daf0d
8
public void run() { final double S = 1; // Units to move try { GameObject ball = pongModel.getBall(); GameObject bats[] = pongModel.getBats(); while ( true ) { double x = ball.getX(); double y = ball.getY(); // Deal with possible edge of board hit if ( x >= W-B-BALL_SIZE ) ball.changeDirectionX(); if ( x <= 0+B ) ball.changeDirectionX(); if ( y >= H-B-BALL_SIZE ) ball.changeDirectionY(); if ( y <= 0+M ) ball.changeDirectionY(); ball.moveX( S ); ball.moveY( S ); // As only a hit on the bat is detected it is assumed to be // on the front or back of the bat // A hit on the top or bottom has an interesting affect if ( bats[0].collision( ball ) == GameObject.Collision.HIT || bats[1].collision( ball ) == GameObject.Collision.HIT ) { ball.changeDirectionX(); } pongModel.modelChanged(); // Model changed refresh screen Thread.sleep( 20 ); // About 50 Hz } } catch ( Exception e ) {}; }
880d702d-6608-4e17-aeb8-c63ea94cfa63
2
public void moveJump(Jump jump) { if (this.jump != null) throw new AssertError("overriding with moveJump()"); this.jump = jump; if (jump != null) { jump.prev.jump = null; jump.prev = this; } }
ca91ebc9-b349-4f51-afda-4ca2dfedb961
9
public static void main(String[] args) { class Point { double x; double y; } Scanner s = new Scanner(System.in); String input; Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); double dist1, dist2, dist3; System.out.print("Please enter x coordinate number 1 : "); point1.x = s.nextDouble(); System.out.print("Please enter y coordinate number 1 : "); point1.y = s.nextDouble(); System.out.print("Please enter x coordinate number 2 : "); point2.x = s.nextDouble(); System.out.print("Please enter y coordinate number 2 : "); point2.y = s.nextDouble(); System.out.print("Please enter x coordinate number 3 : "); point3.x = s.nextDouble(); System.out.print("Please enter y coordinate number 3 : "); point3.y = s.nextDouble(); dist1 = Math.sqrt((point1.x * point1.x) + (point1.y * point1.y)); dist2 = Math.sqrt((point2.x * point2.x) + (point2.y * point2.y)); dist3 = Math.sqrt((point3.x * point3.x) + (point3.y * point3.y)); if(dist1 == dist2 && dist1 == dist3){ System.out.println("These are all the same distance."); } else if(dist1 == dist2){ if(dist1 < dist3){ System.out.println("The 1st and 2nd coordinates are the same and closer than the 3rd set."); } else{ System.out.println("The 1st and 2nd coordinates are the same and further than the 3rd set."); } } else if(dist1 == dist3){ if(dist1 < dist2){ System.out.println("The 1st and 3rd coordinates are the same and closer than the 2rd set."); } else{ System.out.println("The 1st and 3rd coordinates are the same and further than the 2rd set."); } } else if(dist1 < dist2){ if(dist1 < dist3){ System.out.println("Point 1 is closest."); } else{ System.out.println("Point 3 is closest."); } } else{ if(dist2 < dist3){ System.out.println("Point 2 is closest."); } else{ System.out.println("Point 3 is closest."); } } }
8325eb55-630f-44ed-82eb-228b673aafac
9
public void reorderList(ListNode head) { if(head == null || head.next ==null) return; ListNode curr1 = head; int count = 0; while(curr1 != null) { curr1=curr1.next; count ++; } //split after count/2 ListNode second = null; curr1 = head; int i = 1; while(i < (count+1)/2) { curr1=curr1.next; i++; } second = curr1.next; curr1.next = null; //revert the second ListNode dummy2 = new ListNode(-1); dummy2.next = second; ListNode curr2 = second.next; while(curr2 != null) { ListNode x = curr2.next; second.next = curr2.next; curr2.next = dummy2.next; dummy2.next = curr2; curr2 = x; } //merge ListNode dummy = new ListNode(-1); ListNode curr = dummy; curr1 = head; curr2 = dummy2.next; while(curr1 != null && curr2 != null) { ListNode x =curr1.next; ListNode y =curr2.next; curr.next = curr1; curr1.next = curr2; curr = curr2; curr1 = x; curr2 = y; } if(curr1 != null) curr.next = curr1; if(curr2 != null) curr.next = curr2; head = dummy.next; }
3acad4d3-c460-4a30-b8ad-b1d0a99da7c3
1
private void connect_db(){ if(!secondary) db = new Database("jdbc:postgresql://localhost/vsy","vsy","vsy"); else db = new Database("jdbc:postgresql://localhost/vsy2","vsy2","vsy2"); }
9103508e-ec82-48aa-b1ed-c012bed27d25
7
public void setFeature (String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { if (name.equals(NAMESPACES)) { checkNotParsing("feature", name); namespaces = value; if (!namespaces && !prefixes) { prefixes = true; } } else if (name.equals(NAMESPACE_PREFIXES)) { checkNotParsing("feature", name); prefixes = value; if (!prefixes && !namespaces) { namespaces = true; } } else if (name.equals(XMLNS_URIs)) { checkNotParsing("feature", name); uris = value; } else { throw new SAXNotRecognizedException("Feature: " + name); } }
1a8260f1-3ef2-4be9-8e3e-9b2707a408a0
3
protected void addImage(String relURL) { this.imageURL = relURL; this.imageConstraints = new GridBagConstraints(); imageConstraints.gridx = 1; imageConstraints.gridy = 0; imageConstraints.gridheight = 4; this.imageIndex = 0; try { imageIcon = new ImageIcon(ImageIO.read(getClass().getResource(imageURL))); } catch (IOException ex) { Logger.getLogger(InteractiveDisplay.class.getName()).log(Level.SEVERE, null, ex); } //imageIcon = new ImageIcon(getClass().getResource(imageURL)); imageLabel = new JLabel(imageIcon); imageLabel.setName(IMAGE_NAME); if (mouseClick != null) { imageLabel.addMouseListener(mouseClick); imageLabel.addMouseMotionListener(mouseClick); } else { imageLabel.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent arg0) { //Nothing } @Override public void mouseMoved(MouseEvent arg0) { Point target = arg0.getPoint(); int pixel = getBufferedImage().getRGB(target.x, target.y); handlePixelValue(pixel); } }); } System.out.println(imageIcon.getIconWidth()+", "+imageIcon.getIconHeight()); imagePane.setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); imageLabel.setMinimumSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight())); imageLabel.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight()); /*imageLabel.setBounds(0,0,512,512); imageLabel.setMinimumSize(new Dimension(512,512)); imagePane.setPreferredSize(new Dimension(512, 512));*/ if (this.imageIndex == this.captions.length-1) { System.out.println("RESIZING"); imageLabel.setBounds(0,0,512,512); } body.add(imageLabel, imageConstraints); imagePane.add(imageLabel, new Integer(1)); imagePane.moveToFront(imageLabel); body.add(imagePane, imageConstraints); }
b0a55366-797c-4f7a-98ac-65dc0f10ad8f
3
public void drawTo(PPMEC PPM) { int c = (int) (xRatio * PPM.getWidth()); int r = (int) (yRatio * PPM.getHeight()); int hLengthB = (int) (baseR * PPM.getWidth() / 2); double angleR = Math.toRadians(ANGLE); double angleHR = Math.toRadians(ANGLEH); double h = (int) (Math.tan(angleR) * hLengthB); PPM.setPixel(r, c, color); for (int i = (r + 1); i < (r + h + 1); i++) { int hp = (int) Math.sqrt((i - r) * (i - r)); for (int k = 0; k < PPM.getWidth(); k++) { int b = (int) Math.sqrt((c - k) * (c - k)); double tan = b / (hp * 1.0); double arctan = Math.atan(tan); if ((arctan <= angleHR) ) { PPM.setPixel(i, k, color); } } } }
e8431dc9-8770-4ebf-a77c-243f6a086ea5
2
@Override public boolean delete(Object item) { conn = new SQLconnect().getConnection(); String sqlcommand = "UPDATE `Timeline_Database`.`Timenodes` SET `display`='false' WHERE `id`='%s';"; if(item instanceof Timenode) { Timenode newitem = new Timenode(); newitem = (Timenode)item; try { String sql = String.format(sqlcommand,newitem.getId()); Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象 System.out.println(sql); int count = st.executeUpdate(sql); // 执行插入操作的sql语句,并返回插入数据的个数 System.out.println("delete " + count + " entries"); //输出插入操作的处理结果 conn.close(); return true; }catch (SQLException e) { System.out.println("删除数据失败 " + e.getMessage()); return false; } } return false; }
e22ea571-a38c-493a-8559-5773fc10a09d
6
public static List<String> GetMissingDependencies(File f, String delimeter) throws IOException{ HashMap<Integer,Set<String>> columnData = new HashMap<Integer,Set<String>>(); List<String> missingValues = new ArrayList<String>(); FileReader file_reader = new FileReader(f); BufferedReader reader = new BufferedReader(file_reader); CSVReader csv_reader = new CSVReader(delimeter); List<String> columns = null; //read csv line by line and convert to sql, and add to a list while((columns = csv_reader.getcolumns(reader)) != null){ for(int i = 0 ; i < columns.size() ;i++){ if(columnData.get(i) == null){ columnData.put(i, new TreeSet<String>()); } columnData.get(i).add(columns.get(i)); } } Set<Integer> keys = columnData.keySet(); for(int i = 1 ; i < keys.size();i++){ Set<String> data = columnData.get(i); for(String str : data){ if(!columnData.get(0).contains(str)){ missingValues.add(str); } } } return missingValues; }
a3df49a7-da63-44cd-90de-f0f1aaca9a14
8
float calcSurfacePoint(float cutoff, float valueA, float valueB, Point3f surfacePoint) { float fraction; if (isJvxl && jvxlEdgeDataCount > 0) { fraction = jvxlGetNextFraction(edgeFractionBase, edgeFractionRange, 0.5f); thisValue = fraction; } else { float diff = valueB - valueA; fraction = (cutoff - valueA) / diff; if (isCutoffAbsolute && (fraction < 0 || fraction > 1)) fraction = (-cutoff - valueA) / diff; if (fraction < 0 || fraction > 1) { Logger.error("problem with unusual fraction=" + fraction + " cutoff=" + cutoff + " A:" + valueA + " B:" + valueB); fraction = Float.NaN; } thisValue = valueA + fraction * diff; if (!isJvxl) fractionData.append(jvxlFractionAsCharacter(fraction, edgeFractionBase, edgeFractionRange)); } edgeVector.sub(pointB, pointA); surfacePoint.scaleAdd(fraction, edgeVector, pointA); return fraction; }
15548575-2eaa-478f-ba60-d553910e2c79
7
private void createNewUser(String username, String newUserName, String newUserPid, String newUserPassword, boolean admin, String configurationArea, Collection<DataAndATGUsageInformation> data) throws ConfigurationTaskException, RequestException { if(isAdmin(username)) { // Es werden 4 Fälle betrachtet // Fall 1: Es gibt weder ein Objekt, das den Benutzer in der Konfiguration darstellt, noch einen Eintrag in der XML-Datei (Objekt erzeugen und XML-Eintrag erzeugen (Normalfall)) // Fall 2: Es gibt einen Eintrag in der XML-Datei aber kein Objekt das den Benutzer in der Konfiguration darstellt (Objekt erzeugen und gegebenfalls XML-Datei anpassen) // Fall 3: Es gibt ein Objekt, aber keinen Eintrag in der XML-Datei (Eintrag in die XML-Datei, Objekt nicht ändern) // Fall 4: Es gibt ein Objekt und einen Eintrag in der XML-Datei (Fehlerfall) // Speichert, ob es zu einem Benutzer ein gültiges Objekt gibt final boolean userHasObject = userHasObject(newUserName, newUserPid); if((!userHasObject) && (!_userAccounts.containsKey(newUserName))) { try { // Fall 1: Eintrag XML und Objekt erzeugen // Es wird erst das Objekt angelegt, da es passieren kann, dass der Benutzer keine Rechte dafür besitzt. // Dann würde eine Exception geworfen und es muss auch kein Eintrag in die XML-Datei gemacht werden. // Darf der Benutzer Objekt anlegen und es kommt beim schreiben der XML-datei zu einem Fehler, so kann // die Methode erneut aufgerufen werden und es wird automatisch Fall 3 abgearbeitet. createUserObject(configurationArea, newUserName, newUserPid, data); createUserXML(newUserName, newUserPassword, admin); } catch(Exception e) { _debug.error("Neuen Benutzer anlegen, XML und Objekt", e); throw new RequestException(e); } } else if(!userHasObject) { // Fall 2, das Objekt fehlt createUserObject(configurationArea, newUserName, newUserPid, data); } else if(!_userAccounts.containsKey(newUserName)) { try { // Fall 3, der Eintrag in der XML-Datei fehlt createUserXML(newUserName, newUserPassword, admin); } catch(Exception e) { _debug.error("Neuen Benutzer anlegen, XML", e); throw new RequestException(e); } } else { // Fall 4, es ist alles vorhanden. Ein bestehender Benutzer soll überschrieben werden. Das ist ein // Fehler. throw new ConfigurationTaskException("Der Benutzername ist bereits vergeben"); } } else { throw new ConfigurationTaskException("Der Benutzer hat nicht die nötigen Rechte"); } }
030dc7bf-2cae-40db-b845-0e095b5007ab
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
83859f74-c0db-45b6-9496-36d2ffe55d2f
3
public void displayLogs(ArrayList<TimeStampedMessage> sortedLogs) { System.out.println("LOG FILE WITH ORDER AND CONCURRENT FLAG"); if (sortedLogs.size() == 0) { System.out.println("LOGFILE IS EMPTY"); return; } System.out.println(sortedLogs.get(0).toString() + " ConCurrent:" + sortedLogs.get(0).getConcurrent()); for (int i = 1; i < sortedLogs.size(); i++) { if ((sortedLogs.get(i).timeStamp).compareClock(sortedLogs .get(i - 1).timeStamp) != 0) { System.out.println(""); } System.out.println(sortedLogs.get(i).toString() + " ConCurrent:" + sortedLogs.get(i).getConcurrent()); } System.out.println("LOG FILE END"); }
d91fc446-5675-49a0-850b-325b64ecde33
0
public Timer(int granularity) { this.granularity=granularity; }
1bbf8aa7-f8d0-4fb9-9b5a-2f19a87cf388
7
@Override public Double draw(String id, Double out) { if(id == null || "".equals(id.trim()) || out < 0) { return -1.0; } for(Account a : accounts) { if(id.equals(a.getId())) { if(a.getBalance() < 0 || a.getBalance() < out) { return -1.0; } a.setBalance(a.getBalance() - out); System.out.println("Drawed " + out + " RMB successfully."); return a.getBalance(); } } return -1.0; }
53f4a2a3-0aae-4457-bef1-ada178631a8d
8
public static ListNode merge(ListNode l1, ListNode l2) { /* If any of the two lists is empty, return the other one */ if (l1 == null) { return l2; } if (l2 == null) { return l1; } /* * Keep two pointers: * (1) results (HEAD) of merged list, * (2) tail (TAIL) of merged list */ ListNode result = null; ListNode tail = null; /* * Initialize RESULTS and TAIL to point to the smaller of * both lists first elements */ if (l1.data <= l2.data) { result = tail = l1; l1 = l1.next; }else { result = tail = l2; l2 = l2.next; } while (l1 != null && l2 != null) { if (l1.data <= l2.data) { tail.next = l1; tail = l1; l1 = l1.next; }else { tail.next = l2; tail = l2; l2 = l2.next; } } /* At this point, at least one of the two lists must have been * completely traversed; if any elements remain in the other one, * add them to the resulting list */ while (l1 != null) { tail.next = l1; tail = l1; l1 = l1.next; } while (l2 != null) { tail.next = l2; tail = l2; l2 = l2.next; } return result; }
c591a642-8cc6-41f7-94ef-6f07d29b4a72
9
public boolean isPalindrome2(String s) { if (s == null || s.length() == 0) { return true; } int front = 0; int end = s.length() - 1; while (front < end) { while (front < s.length() && !isValid(s.charAt(front))) { front++; } // for empty string if (front == s.length()) { return true; } while (end >= 0 && !isValid(s.charAt(end))) { end--; } // compare char if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) { break; } else { front++; end--; } } return end <= front; }
d82e5b0c-a069-4ca4-986b-28f557ce8b6d
6
protected void animateModel() { _rootMatrix.getIdentityMatrix(); if (_xRotationAngle != 0) { tempMtx.getArbitraryAxisRotationMatrix(_xRotationAngle, 1, 0, 0); // tempMtx.getXAxisRotationMatrix(_xRotationAngle); _rootMatrix.multiply(tempMtx); } if (_yRotationAngle != 0) { tempMtx.getArbitraryAxisRotationMatrix(_yRotationAngle, 0, 1, 0); // tempMtx.getYAxisRotationMatrix(_yRotationAngle); _rootMatrix.multiply(tempMtx); } if (_zRotationAngle != 0) { tempMtx.getArbitraryAxisRotationMatrix(_zRotationAngle, 0, 0, 1); _rootMatrix.multiply(tempMtx); } MatrixS4 normalsTrans = new Matrix4(); normalsTrans.getIdentityMatrix(); normalsTrans.multiply(_rootMatrix); tempMtx.getScalingMatrix(_xScale, _yScale, _zScale); _rootMatrix.multiply(tempMtx); tempMtx.getTranslationMatrix(_position.getX(), _position.getY(), _position.getZ()); _rootMatrix.multiply(tempMtx); for (int i = 0; i < _model.getSubsets().length; i++) { for (int j = 0; j < _model.getSubsets()[i].getVertices().length; j++) { _animatedModel.getSubsets()[i].getVertices()[j].setX(_model .getSubsets()[i].getVertices()[j].getX()); _animatedModel.getSubsets()[i].getVertices()[j].setY(_model .getSubsets()[i].getVertices()[j].getY()); _animatedModel.getSubsets()[i].getVertices()[j].setZ(_model .getSubsets()[i].getVertices()[j].getZ()); _animatedModel.getSubsets()[i].getVertices()[j].setW(_model .getSubsets()[i].getVertices()[j].getW()); _animatedModel.getSubsets()[i].getVertices()[j] .multiply(_rootMatrix); } for (int j = 0; j < _model.getSubsets()[i].getNormals().length; j++) { _animatedModel.getSubsets()[i].getNormals()[j].setX(_model .getSubsets()[i].getNormals()[j].getX()); _animatedModel.getSubsets()[i].getNormals()[j].setY(_model .getSubsets()[i].getNormals()[j].getY()); _animatedModel.getSubsets()[i].getNormals()[j].setZ(_model .getSubsets()[i].getNormals()[j].getZ()); _animatedModel.getSubsets()[i].getNormals()[j].setW(_model .getSubsets()[i].getNormals()[j].getW()); _animatedModel.getSubsets()[i].getNormals()[j] .multiply(normalsTrans); } } }
20d30170-38f3-4407-8e8d-07be92045baf
5
public FieldDescriptor findExtensionByName(String name) { if (name.indexOf('.') != -1) { return null; } if (getPackage().length() > 0) { name = getPackage() + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); if (result != null && result instanceof FieldDescriptor && result.getFile() == this) { return (FieldDescriptor)result; } else { return null; } }
1e142c76-0057-49c7-92f6-285661b7dc94
6
public void rebond(Projectiles projectile, char orientation) { if (orientation == 'y') { projectile.getVitesse().setY(-projectile.getVitesse().getY() * projectile.getFacRebond()); projectile.getVitesse().setX(projectile.getVitesse().getX() * projectile.getFacRebond()); if (projectile.getVitesse().getY() < 1.80 && projectile.getVitesse().getY() > -1.80) { projectile.getVitesse().setY(-projectile.getVitesse().getY() * 0.8); } if (projectile.getVitesse().getY() < 0.18 && projectile.getVitesse().getY() > -0.18) { projectile.getVitesse().setY(0); } } if (orientation == 'x') { projectile.getVitesse().setX(-projectile.getVitesse().getX()); projectile.setReverse(!projectile.isReverse()); } }
69cca228-0857-4cb6-8299-689ffb6c0c0d
0
public MemoryLeak() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; }
89b3404b-ca07-49e0-9f30-f1728e77626e
2
public int genererNumeroClient(){ System.out.println("ModeleLocations::genererNumeroClient()") ; int numMax = 0 ; for(Client client : this.clients){ if(client.getNumero() > numMax){ numMax = client.getNumero() ; } } return numMax + 1 ; }
b14c1d11-52df-456d-adcf-69d20a4bda50
2
public void update(long deltaMs) { Iterator<IntBuffer> it = sources.iterator(); while(it.hasNext()) { IntBuffer source = it.next(); if(AL10.alGetSourcei(source.get(0), AL10.AL_SOURCE_STATE) == AL10.AL_STOPPED) { AL10.alDeleteSources(source.get(0)); it.remove(); } } }
39c5521c-9ede-438f-89fc-c7845e915a4f
7
static public void start() { CallableStatement callableStatement = null; Connection con = null; Connection mscon = null; ArrayList<StrongmailMailing> smlist = new ArrayList<StrongmailMailing>(); try { Class.forName("org.postgresql.Driver"); String jdbcFormat = String.format("jdbc:%s://%s:%s/%s", "postgresql", "localhost", 5432, "postgres"); con = DriverManager.getConnection(jdbcFormat, "postgres", "str0ngmail"); String select = "select * from mailing order by modified_time desc"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(select); while (rs.next()) { StrongmailMailing smm = new StrongmailMailing(); smm.mailingId = rs.getInt("mailing_id"); smm.mailingName = rs.getString("name"); smm.mailingDepartment = rs.getString("from_name"); smm.mailingDepartmentId = rs.getInt("department_id"); smlist.add(smm); } MsSqlServerLoader.loadData(smlist); } catch (SQLException sqle) { System.out.println(String.format("SQL EXCEPTION: loadData %s %d %s", sqle.getLocalizedMessage(), sqle.getErrorCode(), sqle.getSQLState())); sqle.printStackTrace(); } catch (Exception e) { System.out.println("EXCEPTION: loadDataMessageStudio " + e.getMessage()); } finally { if (callableStatement != null) { try { callableStatement.close(); } catch (SQLException e) { } } if (con != null) { try { con.close(); } catch (SQLException e) { } } } }
826d41cd-02fa-4393-94ac-dcf989754101
2
public Object clone() { try { SlotSet other = (SlotSet) super.clone(); if (count > 0) { other.locals = new LocalInfo[count]; System.arraycopy(locals, 0, other.locals, 0, count); } return other; } catch (CloneNotSupportedException ex) { throw new alterrs.jode.AssertError("Clone?"); } }