text
stringlengths
14
410k
label
int32
0
9
private Map<String, SMSThread> buildSMSThreadMap(String response) { Map<String, SMSThread> result = new HashMap<String, SMSThread>(); String jsonResponse = ParsingUtil.removeUninterestingParts(response, FilterResponse.JSON_BEGIN, FilterResponse.JSON_END, false); try { JSONObject json = new JSONObject(jsonResponse); JSONObject messages = json.getJSONObject(JSONContants.MESSAGES); JSONArray names = messages.names(); if (names == null) return result; for (int i = 0; i < names.length(); i++) { JSONObject jsonSmsThread = messages.getJSONObject(names .getString(i)); String id = jsonSmsThread.has(JSONContants.ID) ? jsonSmsThread .getString(JSONContants.ID) : ""; long startTime = jsonSmsThread.has(JSONContants.START_TIME) ? jsonSmsThread .getLong(JSONContants.START_TIME) : 0; String note = jsonSmsThread.has(JSONContants.NOTE) ? jsonSmsThread .getString(JSONContants.NOTE) : ""; boolean isRead = jsonSmsThread.has(JSONContants.IS_READ) ? jsonSmsThread .getBoolean(JSONContants.IS_READ) : false; boolean isStarred = jsonSmsThread.has(JSONContants.STARRED) ? jsonSmsThread .getBoolean(JSONContants.STARRED) : false; SMSThread smsThread = new SMSThread(id, note, new Date( startTime), null, isRead, isStarred); result.put(id, smsThread); } } catch (JSONException e) { e.printStackTrace(); } return result; }
8
@Override public void actionPerformed(ActionEvent ae) { try { String op = ae.getActionCommand(); switch(op){ case "Editar CRLV": editarCrlv(); break; case "Adicionar CRLV": adicionarCrlv(); break; case "Excluir CRLV": deletarCrlv(); break; case "Gerar XML": gerarXml(); break; case "Assinar & Gravar": assinarGravar(); break; } } catch (IOException ex) { Logger.getLogger(ControllerGerenciaCrlvs.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(ControllerGerenciaCrlvs.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ControllerGerenciaCrlvs.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(ControllerGerenciaCrlvs.class.getName()).log(Level.SEVERE, null, ex); } }
9
private boolean evaluateBackgroundClause(String str) { if (str.toLowerCase().startsWith("color")) { Color c = parseRGBColor(str.substring(5).trim()); if (c == null) return false; view.setBackground(c); view.setFillMode(new FillMode.ColorFill(c)); } else if (str.toLowerCase().startsWith("image")) { String s = str.substring(5).trim(); Matcher matcher = IMAGE_EXTENSION.matcher(s); if (matcher.find()) { String address = s.substring(0, matcher.end()).trim(); if (FileUtilities.isRelative(address)) { String base = view.getResourceAddress(); if (base == null) { out(ScriptEvent.FAILED, "No directory has been specified. Save the page first."); return false; } address = FileUtilities.getCodeBase(base) + address; if (System.getProperty("os.name").startsWith("Windows")) address = address.replace('\\', '/'); } view.setFillMode(new FillMode.ImageFill(address)); } } model.notifyChange(); return true; }
7
public Section map() { if (original.getRepository() == null || original.getRepository().toString().isEmpty()) { logger.error("Cannot perform mapping procedure on section " + original.toString() + "! No repository for terminologies specified!"); } try { original.resolveAllLinks();// before start of mapping resolve all // links and original.loadAllIncludes();// load all external information. checkMapping(); if (mapped == null && original.isRoot()) {// the original Section is // a root section... mapped = new Section(); mapped.setDocumentAuthor(original.getDocumentAuthor()); mapped.setDocumentDate(original.getDocumentDate()); mapped.setDocumentVersion(original.getDocumentVersion()); } for (int i = 0; i < original.sectionCount(); i++) { // map all // subsections mapSection(original.getSection(i), mapped); } mapProperties(original.getRootSection());// map the properties mapped.optimizeTree(); // optimize the tree, i.e. remove empty // properties and section that may result // from loading terminologies etc. } catch (Exception e) { e.printStackTrace(); } // mapped.optimizeTree(); return mapped; }
6
public static void main(String[] args) { // Example of creating a set and partitioning it: System.out.println("Starting by creating a partitioned set of 4 elements:"); PartitionListElement<String> list = new PartitionListElement<String>(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); // Call the make partition function to put into all possible partitions PartitionList<String> results = OrderConstrainedPartitionList.makePartitions( list); // Display results for(PartitionListItem<String> newPartition : results){ System.out.println("Partition: " + newPartition.toString()); } System.out.println("Now creating a second partitioned set of 3 elements."); // Next we create a second partitioned set PartitionListElement<String> list2 = new PartitionListElement<String>(); list2.add("A"); list2.add("B"); list2.add("C"); PartitionList<String> results2 = OrderConstrainedPartitionList.makePartitions( list2); // Display results for(PartitionListItem<String> newPartition : results2){ System.out.println("Partition: " + newPartition); } // Join both sets PartitionList<String> results3 = OrderConstrainedPartitionList.joinSets(results, results2); System.out.println("Showing all merged sets:"); for(PartitionListItem<String> newPartition: results3){ System.out.println("Partition: " + newPartition); } System.out.println("Now creating a Third partitioned set of 3 elements."); // Next we create a second partitioned set PartitionListElement<String> list3 = new PartitionListElement<String>(); list3.add("z"); list3.add("y"); list3.add("x"); PartitionList<String> results4 = OrderConstrainedPartitionList.makePartitions( list3); // Display results for(PartitionListItem<String> newPartition : results4){ System.out.println("Partition: " + newPartition); } try{ // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); // Join all sets PartitionList<String> results6 = OrderConstrainedPartitionList.joinPartitionedSets(results3, results4); System.out.println("Saving all merged sets to out.txt"); for(PartitionListItem<String> newPartition: results6){ //System.out.println("Partition: " + newPartition); out.write("Partition: " + newPartition + "\n"); } out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } System.out.println("Save is complete. "); }
6
@Override public void draw(Graphics g) { super.draw(g); Rectangle masse = getAbsoluteRect(); //draw eyes g.setColor(Color.WHITE); g.fillOval((int)(masse.getX() + masse.getWidth() * 0.2), (int)(masse.getY() + masse.getHeight() * 0.4), (int)(masse.getWidth() / 6), (int)(masse.getHeight() / 6)); g.fillOval((int)(masse.getX() + masse.getWidth() * 0.7), (int)(masse.getY() + masse.getHeight() * 0.4), (int)(masse.getWidth() / 6), (int)(masse.getHeight() / 6)); }
0
public boolean unfollowUser(String followingUser, String id){ String userToUnfollow= _users.get(followingUser).getUserById(id); User userFound= _users.get(userToUnfollow); if ((userFound != null) && (userFound.checkIfCanRemoveFollowingUser(followingUser, id))){ return ((_users.get(followingUser).unfollowUser(userToUnfollow, id)) && (userFound.removeFollowingUser(followingUser, id))); } return false; }
3
public boolean isAlive() { return this.getHealth() <= 0; }
0
public int maximalRectangle(char[][] matrix) { int row = matrix.length; if(row == 0) return 0; int col = matrix[0].length; int[][] m = new int[row][col]; for(int i = 0; i < row; ++i){ for(int j = 0; j < col; ++j){ if(matrix[i][j] == '1'){ if(j == 0) m[i][j] = 1; else m[i][j] = m[i][j-1] + 1; } } } int maxArea = 0; for(int i = 0; i < row; ++i){ for(int j = 0; j < col; ++j){ if(m[i][j] != 0){ int height = i; int width = m[i][j]; for(; height >= 0; height--){ width = Math.min(m[height][j], width); int area = width * (i - height + 1); maxArea = Math.max(maxArea, area); } } } } //PublicMethods.print2DArray(m); return maxArea; }
9
public final NiklausParser.parameters_return parameters() throws RecognitionException { NiklausParser.parameters_return retval = new NiklausParser.parameters_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token IDENTIFIER61=null; Token COMMA62=null; Token IDENTIFIER63=null; Token COLON64=null; Token TYPE65=null; CommonTree IDENTIFIER61_tree=null; CommonTree COMMA62_tree=null; CommonTree IDENTIFIER63_tree=null; CommonTree COLON64_tree=null; CommonTree TYPE65_tree=null; RewriteRuleTokenStream stream_COLON=new RewriteRuleTokenStream(adaptor,"token COLON"); RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); RewriteRuleTokenStream stream_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token IDENTIFIER"); RewriteRuleTokenStream stream_TYPE=new RewriteRuleTokenStream(adaptor,"token TYPE"); try { // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:94:11: ( IDENTIFIER ( COMMA IDENTIFIER )* COLON TYPE -> ( ^( TYPE IDENTIFIER ) )+ ) // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:95:3: IDENTIFIER ( COMMA IDENTIFIER )* COLON TYPE { IDENTIFIER61=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_parameters482); stream_IDENTIFIER.add(IDENTIFIER61); // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:95:14: ( COMMA IDENTIFIER )* loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( (LA17_0==COMMA) ) { alt17=1; } switch (alt17) { case 1 : // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:95:15: COMMA IDENTIFIER { COMMA62=(Token)match(input,COMMA,FOLLOW_COMMA_in_parameters485); stream_COMMA.add(COMMA62); IDENTIFIER63=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_parameters487); stream_IDENTIFIER.add(IDENTIFIER63); } break; default : break loop17; } } while (true); COLON64=(Token)match(input,COLON,FOLLOW_COLON_in_parameters491); stream_COLON.add(COLON64); TYPE65=(Token)match(input,TYPE,FOLLOW_TYPE_in_parameters493); stream_TYPE.add(TYPE65); // AST REWRITE // elements: TYPE, IDENTIFIER // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (CommonTree)adaptor.nil(); // 96:3: -> ( ^( TYPE IDENTIFIER ) )+ { if ( !(stream_TYPE.hasNext()||stream_IDENTIFIER.hasNext()) ) { throw new RewriteEarlyExitException(); } while ( stream_TYPE.hasNext()||stream_IDENTIFIER.hasNext() ) { // C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:96:6: ^( TYPE IDENTIFIER ) { CommonTree root_1 = (CommonTree)adaptor.nil(); root_1 = (CommonTree)adaptor.becomeRoot( stream_TYPE.nextNode() , root_1); adaptor.addChild(root_1, stream_IDENTIFIER.nextNode() ); adaptor.addChild(root_0, root_1); } } stream_TYPE.reset(); stream_IDENTIFIER.reset(); } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
9
public void getMenu(int menuIndex){ if (this.isAlive()){ switch (menuIndex){ case WELCOME_MENU: getMenu(welcome()); break; case BANKING_MENU: getMenu(banking()); break; case DEPOSIT_MENU: getMenu(deposit()); break; case WITHDRAW_MENU: getMenu(withdraw()); break; case TRANSFER_MENU: getMenu(transfer()); break; case ACCOUNT_MENU: getMenu(account()); break; case CREATEACCOUNT_MENU: getMenu(createAccount()); break; default: getMenu(this.currentId); break; } this.currentId = menuIndex; } }
8
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
public static boolean doBootstrapperUpdate(Stack<String> updateQueue, JSONObject versionsConfig) { Logger.info("Updater.doBootstrapperUpdate", "Starting update..."); //Show progress GlobalDialogs.showProgressDialog(); GlobalDialogs.setProgressCaption("Cleaning..."); GlobalDialogs.setProgressIndeterminate(true); //Clean patch directory Logger.info("Updater.doBootstrapperUpdate", "Cleaning patch directory..."); try { if (new File("./update/mupdatepatch").isDirectory()) { FileUtils.deleteDirectory(new File("./update/mupdatepatch")); } } catch (IOException ex) { Logger.error("Updater.doBootstrapperUpdate", "Failed to clean the patch directory!", false, ex); GlobalDialogs.hideProgressDialog(); GlobalDialogs.showNotification("Failed to clean the patch directory!"); return false; } //Download and extract patches while (!updateQueue.empty()) { //Load update from JSON String updateName = updateQueue.pop(); JSONObject update = getVersionByName(updateName, "mupdate", versionsConfig); //Update status GlobalDialogs.setProgressCaption("Getting patch '" + updateName + "'..."); //Download version patch Logger.info("Updater.doBootstrapperUpdate", "Downloading patch '" + updateName + "'..."); try { FileUtils.copyURLToFile(new URL(update.get("patch").toString()), new File("./update/mupdate-" + updateName + "-patch.zip")); } catch (IOException ex) { Logger.error("Updater.doBootstrapperUpdate", "Failed to download patch!", false, ex); GlobalDialogs.hideProgressDialog(); GlobalDialogs.showNotification("Failed to download patch '" + updateName + "'!"); return false; } //Extract version patch Logger.info("Updater.doUpdate", "Extracting patch '" + updateName + "'..."); try { Util.decompressZipfile("./update/mupdate-" + updateName + "-patch.zip", "./update/mupdatepatch"); } catch (ZipException ex) { Logger.error("Updater.doBootstrapperUpdate", "Failed to extract patch!", false, ex); GlobalDialogs.hideProgressDialog(); GlobalDialogs.showNotification("Failed to extract patch '" + updateName + "'!"); return false; } } //Update status GlobalDialogs.setProgressCaption("Applying patches..."); //Apply patch Logger.info("Updater.doBootstrapperUpdate", "Applying patch directory..."); try { FileUtils.copyDirectory(new File("./update/mupdatepatch"), new File("./update")); } catch (IOException ex) { Logger.error("Updater.doBootstrapperUpdate", "Failed to apply patch!", false, ex); GlobalDialogs.hideProgressDialog(); GlobalDialogs.showNotification("Failed to apply MUpdate patch!"); return false; } //Hide progress window GlobalDialogs.hideProgressDialog(); return true; }
6
public static Reminder create(long apptId, long userId, long reminderAhead) throws SQLException { Map<String, String> values = new HashMap<String, String>(); values.put("appointmentId", String.valueOf(apptId)); values.put("userId", String.valueOf(userId)); values.put("reminderAhead", String.valueOf(reminderAhead)); Reminder rtn = new Reminder(); Data.create(rtn, values); rtn.reminderAhead = reminderAhead; return rtn; }
0
private void drawCoordinateStroke(int x0, int y0, int x1, int y1) { for(int x = x0; x <= x1; x++) { for(int y = y0; y <= y1; y++) { if(x < width && x > 0 && y < height && y > 0) { image.setRGB(x, y, Color.black.getRGB()); } } } }
6
public int checkSidwaysUp(int originLetter, int originNum, int newLetter, int newNum, Board b) { valid = 0; int diagnalUpLetter = originLetter; int diagnalUpNumber = originNum; if(originLetter > newLetter) //diagnal up left { int diagnalLeftValid = 0; for(int counter = 0; counter < ((originLetter-newLetter)-1); counter++) { diagnalUpLetter = diagnalUpLetter - 1; diagnalUpNumber = diagnalUpNumber - 1; if(b.checkBoard(diagnalUpLetter,diagnalUpNumber).matches(chessPieces)) { System.out.println(error); } else { diagnalLeftValid = 1; } } valid = diagnalLeftValid; } else if(newLetter > originLetter) //diagnal up right { int diagnalRightValid = 0; for(int counter = 0; counter < ((newLetter-originLetter)-1);counter++) { diagnalUpLetter = diagnalUpLetter + 1; diagnalUpNumber = diagnalUpNumber - 1; if(b.checkBoard(diagnalUpLetter,diagnalUpNumber).matches(chessPieces)) { System.out.println(error); } else { diagnalRightValid = 1; } } valid = diagnalRightValid; } return valid; }
6
public Node insertItem(int key) { Node node = new Node(key); if (isEmpty()) root = node; else { Node current = this.root; while (true) if (current.getKey() > key && current.getLeft() != null) current = current.getLeft(); else if (current.getKey() <= key && current.getRight() != null) current = current.getRight(); else break; if (current.getKey() > key) current.setLeft(node); else current.setRight(node); node.setParent(current); } size++; return node; }
7
public void update1(float time){//@override Entity Vector2 tempForce; LinkedList<MyPoint> temp = new LinkedList<MyPoint>(); for (Link l : neighbors){ tempForce = Vector2.vecSubt(l.other.getPos(), this.pos); if (tempForce.length() > l.len * breakLength){ temp.add(l.other); } } for (MyPoint p : temp){ p.removeNeighbor(this); this.removeNeighbor(p); } boolean existing = false; for (MyPoint p : MyPoint.getNodesWithin(connectRange * 0.75,this.getPos())){ if(p.equals(this))break; existing = false; for (Link l : neighbors){ if(l.other.equals(p)){ existing = true; break; } } if (!existing){ addLink(p); p.addLink(this); } } super.update1(time); }
8
public static int[] maxProduct(int[] A) { int[] output = new int[2]; int[] min = new int[2]; Arrays.fill(output, Integer.MIN_VALUE); Arrays.fill(min, 0); for (int i = 0; i < A.length; i++) { if (A[i] <= 0) { if (A[i] < min[1]) { min[0] = min[1]; min[1] = A[i]; } else if (A[i] < min[0]) { min[0] = A[i]; } } if (A[i] > output[1]) { output[0] = output[1]; output[1] = A[i]; } else if (A[i] > output[0]) { output[0] = A[i]; } if (min[0] * min[1] > output[0] * output[1]) { output[0] = min[0]; output[1] = min[1]; } }//end of for return output; }
7
public Card returnAndRemove(Card data) throws Exception { Node<Card> currNode; Node<Card> prevNode; Card returnCard = null; if (head == null) { throw new ListEmptyException(); } else { // find the node with the data in it // adjust the links so the Node is removed from the chain of Nodes currNode = head; prevNode = head; while (currNode != null && data.compareTo(currNode.getData()) >= 0) { if (currNode.getData().equals(data)) { // found the data we are looking for returnCard = currNode.getData(); if (currNode == head) { // reset head and you're done! head = head.getNext(); return returnCard; // leave the method } else { // node was found in the middle of the list prevNode.setNext(currNode.getNext()); return returnCard; // leave the method } } // didn't find it yet, continue on to next node prevNode = currNode; currNode = currNode.getNext(); } // exhausted list, didn't find a match throw new NotFoundException(); } }
5
public static int[] toIntA(byte[] data) { if (data == null || data.length % 4 != 0) return null; // ---------- int[] ints = new int[data.length / 4]; for (int i = 0; i < ints.length; i++) ints[i] = toInt( new byte[] { data[(i*4)], data[(i*4)+1], data[(i*4)+2], data[(i*4)+3], } ); return ints; }
3
@Override public void run() { try { // Eclipse doesn't support System.console() BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); ConfigManager config = NetBase.theNetBase().config(); String server = config.getProperty("net.server.ip"); if ( server == null ) { System.out.print("Enter a host ip, or exit to exit: "); server = console.readLine(); if ( server == null ) return; if ( server.equals("exit")) return; } int basePort = config.getAsInt("dataxferraw.server.baseport", -1); if ( basePort == -1 ) { System.out.print("Enter port number, or empty line to exit: "); String portStr = console.readLine(); if ( portStr == null || portStr.trim().isEmpty() ) return; basePort = Integer.parseInt(portStr); } else { System.out.println("Using base port = " + basePort); } int socketTimeout = config.getAsInt("net.timeout.socket", -1); if ( socketTimeout < 0 ) { System.out.print("Enter socket timeout (in msec.): "); String timeoutStr = console.readLine(); socketTimeout = Integer.parseInt(timeoutStr); } System.out.print("Enter number of trials: "); String trialStr = console.readLine(); int nTrials = Integer.parseInt(trialStr); for ( int index=0; index<DataXferRawService.NPORTS; index++ ) { TransferRate.clear(); int port = basePort + index; int xferLength = DataXferRawService.XFERSIZE[index]; System.out.println("\n" + xferLength + " bytes"); //----------------------------------------------------- // UDP transfer //----------------------------------------------------- TransferRateInterval udpStats = udpDataXferRate(DataXferServiceBase.HEADER_BYTES, server, port, socketTimeout, xferLength, nTrials); System.out.println("UDP: xfer rate = " + String.format("%9.0f", udpStats.mean() * 1000.0) + " bytes/sec."); System.out.println("UDP: failure rate = " + String.format("%5.1f", udpStats.failureRate()) + " [" + udpStats.nAborted() + "/" + udpStats.nTrials() + "]"); //----------------------------------------------------- // TCP transfer //----------------------------------------------------- TransferRateInterval tcpStats = tcpDataXferRate(DataXferServiceBase.HEADER_BYTES, server, port, socketTimeout, xferLength, nTrials); System.out.println("\nTCP: xfer rate = " + String.format("%9.0f", tcpStats.mean() * 1000.0) + " bytes/sec."); System.out.println("TCP: failure rate = " + String.format("%5.1f", tcpStats.failureRate()) + " [" + tcpStats.nAborted()+ "/" + tcpStats.nTrials() + "]"); } } catch (Exception e) { System.out.println("Unanticipated exception: " + e.getMessage()); } }
9
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){ try { Object o1 = session.getAttribute("UserID"); Object o2 = session.getAttribute("UserRights"); boolean bRedirect = false; if ( o1 == null || o2 == null ) { bRedirect = true; } if ( ! bRedirect ) { if ( (o1.toString()).equals("")) { bRedirect = true; } else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; } } if ( bRedirect ) { response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI())); return "sendRedirect"; } } catch(Exception e){}; return ""; }
7
private static <E extends Comparable<E>> void heapifyDown(E[] heap, int index, int startIndex, int endIndex) { int leftChildIndex = index * 2 + 1 - startIndex; int rightChildIndex = index * 2 + 2 - startIndex; int swapIndex = index; // if left child exists and greater than current node if (leftChildIndex <= endIndex) { if (heap[leftChildIndex].compareTo(heap[swapIndex]) > 0) swapIndex = leftChildIndex; // if right child exists and greater than current node and left child if (rightChildIndex <= endIndex) { if (heap[rightChildIndex].compareTo(heap[swapIndex]) > 0) swapIndex = rightChildIndex; } } if (swapIndex != index) { // swap if necessary E temp = heap[index]; heap[index] = heap[swapIndex]; heap[swapIndex] = temp; heapifyDown(heap, swapIndex, startIndex, endIndex); // check next level down } }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Level)) return false; Level other = (Level) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
6
private ReturnValue Helper(TreeNode p) { if (p == null) return new ReturnValue(Integer.MIN_VALUE,Integer.MIN_VALUE); if (p.left == null && p.right == null) return new ReturnValue(p.val,p.val); ReturnValue l = Helper(p.left); ReturnValue r = Helper(p.right); int within = Math.max(Math.max(l.within,r.within) + p.val,p.val); int temp0 = Math.max(l.all,r.all); int temp1 = p.val; if (l.within > 0 && r.within > 0) temp1 = p.val + l.within + r.within; else if (l.within <= 0 && r.within > 0) temp1 = p.val + r.within; else if (r.within <= 0 && l.within > 0) temp1 = p.val + l.within; int all = Math.max(temp0,temp1); return new ReturnValue(within,all); }
9
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { renderButton.setForeground(table.getSelectionForeground()); renderButton.setBackground(table.getSelectionBackground()); } else { renderButton.setForeground(table.getForeground()); renderButton.setBackground(UIManager.getColor("Button.background")); } if (hasFocus) { renderButton.setBorder( focusBorder ); } else { renderButton.setBorder( originalBorder ); } // renderButton.setText( (value == null) ? "" : value.toString() ); if (value == null) { renderButton.setText( "" ); renderButton.setIcon( null ); } else if (value instanceof Icon) { renderButton.setText( "" ); renderButton.setIcon( (Icon)value ); } else { renderButton.setText( value.toString() ); renderButton.setIcon( null ); } return renderButton; }
4
public void doWork(long time, TimeUnit unit) throws Exception { if (!lock.acquire(time, unit)) { throw new IllegalStateException(clientName + " could not acquire the lock"); } try { System.out.println(clientName + " has the lock"); resource.use(); } finally { System.out.println(clientName + " releasing the lock"); lock.release(); // always release the lock in a finally block } }
1
* @throws IOException if a data communication error occurs * @throws UnknownHostException if cyc server host not found on the network */ public boolean isOpenCyc() throws UnknownHostException, IOException { boolean answer; try { answer = converseBoolean("(cyc-opencyc-feature)"); } catch (CycApiException e) { answer = false; } return answer; }
1
public void deleteElement(ValueType value) throws NotExistException { ListElement<ValueType> previous = head; ListElement<ValueType> current = head.getNext(); if (exist(value)) { while (current != tail.getNext()) { if (current.getValue() == value) { previous.setNext(current.getNext()); count--; return; } else { previous = current; current = current.getNext(); } } } else { throw new NotExistException("Element with current value doesn't exist!"); } }
3
@Override public void run() { try { final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); final PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // display welcome screen out.println(Util.buildWelcomeScreen()); boolean cancel = false; CommandHandlerFactory fac = CommandHandlerFactory.getInstance(); while (!cancel) { final String command = reader.readLine(); if (command == null) { continue; } //handle the command final CommandHandler handler = fac.getHandler(command, workingDir); String response = handler.handle(); // setting the working directory if (handler instanceof CDHandler) { workingDir = (response.contains("No such file or directory") || response .contains("You must supply directory name")) ? workingDir : response; logger.info("Working directory set to: " + workingDir); } out.println(response); // command issuing an exit. if (handler instanceof ExitHandler) { cancel = true; } } } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); } finally { try { socket.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to close the socket", e); } } }
8
@Override public FileContent read(String fileName) throws FileNotFoundException, IOException, RemoteException { FileContent data = new FileContent(fileName); ReadWriteLock lock = null; if (!fileReadWriteLock.containsKey(fileName)) { lock = new ReentrantReadWriteLock(); fileReadWriteLock.put(fileName, lock); } else { lock = fileReadWriteLock.get(fileName); } lock.readLock().lock(); Scanner myScanner = new Scanner(new File(dir + "/" + fileName)); while (myScanner.hasNext()) { data.appendData(myScanner.nextLine()); if (myScanner.hasNext()) data.appendData("\n"); } myScanner.close(); lock.readLock().unlock(); return data; }
3
public static void main(String[] args) throws IOException { long inicio = System.currentTimeMillis(); StringBuilder out = new StringBuilder(); BufferedReader in; File archivo = new File("entrada"); if (archivo.exists()) in = new BufferedReader(new FileReader(archivo)); else in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; char cad[]; int n = Integer.parseInt(in.readLine()); map = new char[5][5]; int x = 0; int y = 0; for (int i = 0; i < n; i++) { max = Integer.MAX_VALUE; for (int j = 0; j < 5; j++) { cad = in.readLine().toCharArray(); for (int k = 0; k < cad.length; k++) { if (cad[k] == '0') map[j][k] = '0'; else map[j][k] = '1'; if (cad[k] == ' ') { x = j; y = k; map[j][k] = ' '; } } } dfs(map, x, y, 0, -1, -1); if (max != Integer.MAX_VALUE) { out.append("Solvable in " + max + " move(s).\n"); } else { out.append("Unsolvable in less than 11 move(s).\n"); } } System.out.print(out); if (archivo.exists()) System.out.println("Tiempo transcurrido : " + (System.currentTimeMillis() - inicio) + " milisegundos."); }
8
int[] generateNormalDistSlots(int size, int avg, int stdDev){ int[] slot = new int[size]; for(int i=0; i<slot.length; i++){ slot[i] = (int) n.Normal(avg, stdDev); } return slot; }
1
private void getData(Graphics2D graphics) { int i = 1, slen; data = new ArrayList<String>(); if (scores.count() == 0) slen = 5; else slen = Math.max(5, scores.getHighest().getFormattedScore().length()); header = String.format("Place%" + (slen - 4) + "sScore Level Name", " "); String longest = header; String tmpl = "#%2d %" + slen + "s %s %s"; for (Score score : scores) { String level = String.format("%2d.%-2d", score.getLevel(), score.getWave()); String formatted = String.format(tmpl, i, score.getFormattedScore(), level, score.getName()); if (formatted.length() > longest.length()) longest = formatted; data.add(formatted); if (score == highlight) highlightIndex = i; i++; } dataOffset = screen.getXOffset(graphics, smallFont, longest); }
4
public boolean canHaveAsBalance(BigInteger balance) { return (balance != null) && (balance.compareTo(this.getCreditLimit()) >= 0); }
1
public PostProcessingFileWriter(File file) throws IOException { super(file); }
0
public void automataStateChange(AutomataStateEvent e) { transformNeedsReform = true; repaint(); }
0
@Override public void showHelp(CommandSender sender) { sender.sendMessage(colour1 + "=== " + colour2 + getCommandName() + colour1 + " ==="); sender.sendMessage(colour1 + "Usage: " + colour2 + getCommandUsage()); sender.sendMessage(colour1 + "Desc: " + colour2 + getCommandDesc()); sender.sendMessage((colour1 + "Permission: " + colour2 + this.getPermissionString())); String keys = ""; String prefix = ""; if (sender instanceof Player) prefix = "/"; for (String key : this.getKeyStrings()) keys += prefix + key + ", "; keys = keys.substring(0, keys.length() - 2); sender.sendMessage(colour1 + "Aliases: " + colour2 + keys); if (this.getCommandExamples().size() > 0) { sender.sendMessage(colour1 + "Examples: "); if (sender instanceof Player) for (int i = 0; i < 4 && i < this.getCommandExamples().size(); i++) sender.sendMessage(this.getCommandExamples().get(i)); else for (String c : this.getCommandExamples()) sender.sendMessage(c); } }
7
private void deleteFileServerSide() { try { client.connect("ftp.asite.com"); client.login("username", "password"); // Set a string with the file you want to delete String filename = "/coomons/footer.jsp"; // Delete file boolean exist = client.deleteFile(filename); // Notify user for deletion if (exist) { System.out.println("File '" + filename + "' deleted..."); } // Notify user that file doesn't exist else { System.out.println("File '" + filename + "' doesn't exist..."); } client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
3
public int loopLevel(final Block block) { if (loopEdgeModCount != edgeModCount) { buildLoopTree(); } if ((block == srcBlock) || (block.blockType() != Block.NON_HEADER)) { final LoopNode loop = (LoopNode) loopTree.getNode(block); Assert.isTrue(loop != null, "no loop for " + block); return loop.level; } if (block.header() != null) { final LoopNode loop = (LoopNode) loopTree.getNode(block.header()); Assert.isTrue(loop != null, "no loop for " + block.header()); return loop.level; } throw new RuntimeException(); }
4
/* */ public String getParameter(String name) { /* 206 */ String custom = (String)this.customParameters.get(name); /* 207 */ if (custom != null) return custom; try /* */ { /* 209 */ return super.getParameter(name); /* */ } catch (Exception e) { /* 211 */ this.customParameters.put(name, null); /* 212 */ }return null; /* */ }
2
public static String formatIntoMessage(String topic, String subscription, String message){ StringBuilder sb= new StringBuilder("MESSAGE"); sb.append(StompFrame.endlineChar); if (!topic.equals("")) sb.append("destination:/topic/").append(topic).append(StompFrame.endlineChar); if (!subscription.equals("")) sb.append("subscription:").append(subscription).append(StompFrame.endlineChar); sb.append("message-id:").append(MessageFrame.getCount()).append(StompFrame.endlineChar).append(StompFrame.endlineChar); if (!message.equals("")) sb.append(message).append(StompFrame.endlineChar).append(StompFrame.nullChar); else sb.append(StompFrame.nullChar); return sb.toString(); }
3
public static void ImportDataBookCopies(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement pstm = null ; String sql = "INSERT INTO BookCopies(book_id) SELECT book_id FROM Books WHERE book_id NOT IN (SELECT bc.book_id FROM BookCopies bc, Books b WHERE bc.book_id = b.book_id)"; pstm = (PreparedStatement) conn.prepareStatement(sql); pstm.executeUpdate(); conn.commit(); pstm.close(); conn.close(); System.out.println("Success import excel to mysql table"); }catch(SQLException ex){ System.out.println(ex); } }
4
private static String getContentAsString(ContentStream stream) throws IOException { // from Jeff Potts guide InputStream in2 = stream.getStream(); StringBuffer sbuf = null; sbuf = new StringBuffer(in2.available()); int count; byte[] buf2 = new byte[100]; while ((count = in2.read(buf2)) != -1) { for (int i = 0; i < count; i++) { sbuf.append((char) buf2[i]); } } in2.close(); return sbuf.toString(); }
2
private void senaoEspecial() { String senaoEsp = ""; if (comparaLexema(Tag.SENAO)) { senaoEsp = "_L" + label + ":"; ex.codigoInt(senaoEsp); consomeToken(); if (comparaLexema('{')) { consomeToken(); boolean c = true; while (c) { c = comeco(); } if (numeroErro == 0) { if (comparaLexema(Tag.PARE) || comparaLexema(Tag.CONTINUE)) { consomeToken(); if (comparaLexema(';')) { consomeToken(); } else { numeroErro++; ex.excecao("Erro sintático: ", "Era esperado o simbolo ; depois do token " + listaTokens.get(indiceLista - 1) .getNomeDoToken(), (listaTokens.get(indiceLista - 1) .getLinhaLocalizada())); return; } } } else { return; } if (comparaLexema('}')) { consomeToken(); } else { numeroErro++; ex.excecao("Erro sintático: ", "Era esperado o simbolo } depois do token " + listaTokens.get(indiceLista - 1) .getNomeDoToken(), (listaTokens .get(indiceLista - 1).getLinhaLocalizada())); return; } } else if (comparaLexema(Tag.SE)) { condicionalEspecial(""); } else { numeroErro++; ex.excecao("Erro sintático: ", "Era esperado o simbolo { depois do token " + listaTokens.get(indiceLista - 1) .getNomeDoToken(), (listaTokens.get(indiceLista - 1).getLinhaLocalizada())); return; } } else { return; } }
9
private void lock( ) { try { SwingUtilities.invokeAndWait( new Runnable() { public void run( ) { mainFrame.setLock(true); } }); } catch( Exception exc ) { FastICAApp.exceptionDialog(exc); } }
1
private Double[] doFragmentation(double aMin, double aMax, int points){ Double[] array = new Double[points]; double eps = 0; for (int i = 0; i < points; i++) { eps = aMin + 1.0 * i * (aMax - aMin) / (points - 1); array[i] = eps; } return array; }
1
public Connection abrirConexao() { try { // Carregando o JDBC Driver padrão String driver = "com.mysql.jdbc.Driver"; //classe driver JDBC // String banco = "db_sistema"; //nome do banco // String host = "127.0.0.1"; //maquina onde está o banco // String str_conn = "jdbc:mysql://" + host + ":3307/" + banco; //URL de conexao // //Servidor remoto String host = "192.186.200.73"; //maquina onde está o banco String banco = "db_sistema"; //nome do banco String str_conn = "jdbc:mysql://" + host + ":3306/" + banco; //URL de conexao String usuario = "usersistema"; String senha = "db@!2014L"; Class.forName(driver); //carrega driver conbco = DriverManager.getConnection(str_conn, usuario, senha); Statement stmt = conbco.createStatement();//cria stament para mandar um sql pra o banco System.out.println("conectou!"); } catch (ClassNotFoundException e) { //Driver não encontrado System.out.println("O driver especificado nao foi encontrado. " + e.getMessage()); return null; } catch (SQLException e) { //Não conseguindo se conectar ao banco System.out.println("Nao foi possivel conectar ao Banco de Dados. " + e.getMessage()); return null; } return null; }
2
public Record getRecord(Integer id) { Record record = null; PreparedStatement pStmt = null; ResultSet rs = null; try { pStmt = conn.prepareStatement("SELECT * FROM RECORD WHERE id = ?;"); pStmt.setInt(1, id); rs = pStmt.executeQuery(); while (rs.next()) { record = new Record(); record.setId(rs.getInt("id")); record.setFunds(rs.getDouble("funds")); record.setDate(rs.getString("date")); record.setAccount(getAccount(rs.getInt("id_account"))); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResource(pStmt); closeResource(rs); } return record; }
2
@Override public List<Match> findAll() { List<Match> listM = new ArrayList<Match>(); Statement st = null; ResultSet rs = null; try { st = this.connect().createStatement(); rs = st.executeQuery("select * from Matches"); System.out.println("recherche général effectuée"); while (rs.next()) { Match mt = new Match(rs.getInt("id"), rs.getString("equipeA"), rs.getString("equipeB"),rs.getInt("scoreA"), rs.getInt("scoreB"), rs.getDate("datematch")); listM.add(mt); } } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "recherche general echoué", ex); }finally{ try { if(rs != null) rs.close(); if(st != null) st.close(); } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation statement || resultset echoué", ex); } } return listM; }
5
public static CollectionPerson getInstanceCollectionPerson() { if (collectionPerson == null) { collectionPerson = new CollectionPerson(); } return collectionPerson; }
1
public String toString() { String ret = ""; if(passes) { ret = "passes"; } else { if(callOnFirstRound) { if(callIndex != dealerIndex) { ret = "orders up the dealer"; } else { ret = "picks up"; } } else { ret += "declares "; if(this.trump.startsWith("S")) { ret += "spades"; } else if(this.trump.startsWith("C")) { ret += "clubs"; } else if(this.trump.startsWith("H")) { ret += "hearts"; } else if(this.trump.startsWith("D")) { ret += "diamonds"; } else { System.out.println("ERROR: unknown trump declared. Trump string: " + this.trump); System.exit(1); } } if(isAlone) { ret += " and is going alone"; } } //Check if the ret += "."; return ret; }
8
private void startMetrics() { try { Metrics metrics = new Metrics(this); Metrics.Graph componentLineGraph = metrics.createGraph("Components Used"); for (final Component c : Component.values()) { String name = c.getFancyName(); // Line graph comparing component usage together componentLineGraph.addPlotter(new Metrics.Plotter(name) { @Override public int getValue() { return c.i().isEnabled() ? 1 : 0; } }); // Pie graph of the component Enabled/Disabled Metrics.Graph componentStatsGraph = metrics.createGraph(name + " Stats"); componentStatsGraph.addPlotter(new Metrics.Plotter("Enabled") { @Override public int getValue() { return c.i().isEnabled() ? 1 : 0; } }); componentStatsGraph.addPlotter(new Metrics.Plotter("Disabled") { @Override public int getValue() { return c.i().isEnabled() ? 0 : 1; } }); } // Done :) metrics.start(); } catch (IOException e) { getLogger().info("Failed to start metrics gathering.. :("); } }
5
protected SchlangenKopf(Rectangle masse, IntHolder unit, Color color) { super(masse, unit, color); direction = DIRECTION_START; }
0
public void visit_if_icmple(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
public Object getDataForDataSection(DataSection dataSection) { if (DATA_SECTION_GENERAL == dataSection.getDataSectionName()) { return characterData.getCharacterDataData(); } else if (DATA_SECTION_SKILLS == dataSection.getDataSectionName()) { return characterData.getCharacterDataData(); } else if (DATA_SECTION_KNOWN_SPELLS == dataSection.getDataSectionName()) { return characterData.getCharacterDataData(); } else if (DATA_SECTION_AWARDS == dataSection.getDataSectionName()) { return characterData.getCharacterDataData(); } else if (DATA_SECTION_CONDITIONS == dataSection.getDataSectionName()) { return characterData.getCharacterDataData(); } else if (DATA_SECTION_ACTIVE_SPELLS == dataSection.getDataSectionName()) { return characterData.getActiveSpellList(); } else if (DATA_SECTION_ITEMS == dataSection.getDataSectionName()) { return characterData.getItemContainer(); } else if (DATA_SECTION_LLOYDS_BEACON == dataSection.getDataSectionName()) { return characterData.getLloydsBeaconList(); } else if (DATA_SECTION_UNKNOWNS == dataSection.getDataSectionName()) { return characterData.getUnknownByteDataList(); } else throw new IllegalStateException("DataSection " + dataSection.getDataSectionName()); }
9
@Override public ElementType next() { // if not initialized, initialize it first if (this.currentElementItr == null) { if (this.currentListItr.hasNext()) { // have lists this.currentElementItr = this.currentListItr.next() .iterator(); } else { throw new NoSuchElementException(); } } // initialized, and has next element if (this.currentElementItr.hasNext()) { return this.currentElementItr.next(); } // initialized, but doesn't has next element if (this.currentListItr.hasNext()) { // get next list to iterate this.currentElementItr = this.currentListItr.next().iterator(); return this.currentElementItr.next(); } else { throw new NoSuchElementException( "Iteration has no more elements, You should check hasNext() before iterator it"); } }
4
public static void main(String args[]) throws UnknownHostException, IOException { /* 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(GUI_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI_UI.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 GUI_UI().setVisible(true); } }); System.out.println("benjooo"); Com.Conncect(); //System.out.println("AFTER CONNECT"); String outcome=Com.recieveMessage(); if(forumBody!=null) forumBody.setText(""+outcome); }
7
@Override public int matches( ByteBuffer sequenceA, int indexA, ByteBuffer sequenceB, int indexB, int count ) { for (int i = 0; i < count; i++) { if (sequenceA.get(indexA + i) != sequenceB.get(indexB + i)) { return i; } } return count; }
2
@Override public void run() { super.run(); mUi.updateProgressState("Parser started", 0); try { if (mInputDictionary != null) addWordsFromInputStream(mInputDictionary, true, mTotalDictionaryChars, LOOKING_FOR_WORD_START); addWordsFromInputStream(mInput, (mInputDictionary == null), mTotalChars, LOOKING_FOR_SPACE); } catch (IOException e) { e.printStackTrace(); mUi.showErrorMessage(e.getMessage()); } finally { mUi.updateProgressState("Parser ending...", 0); try { mInput.close(); mUi.updateProgressState("Sorting words (have "+mWords.size()+" words)...", 0); List<WordWithCount> sortedList = removeNonFrequentWords(); mUi.updateProgressState("Creating XML (will use "+mMaxWords+" words)...", 0); createXml(sortedList); mOutput.flush(); mOutput.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); mUi.showErrorMessage(e.getMessage()); } mUi.updateProgressState("Parser ended. Found "+mWords.size()+" words.", 100); mUi.onEnded(); } }
3
private void printCommands(Player playerSender){ if(playerSender.hasPermission("sd")){ String pluginVersion = plugin.getDescription().getVersion(); String pluginName = plugin.getDescription().getName(); playerSender.sendMessage(ChatColor.YELLOW + "|---------- " + pluginName + " v" + pluginVersion + " ----------|"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd tool"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd save"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd reload"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd remove [doorID]"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd close [doorID]"); playerSender.sendMessage(ChatColor.YELLOW + "|" + ChatColor.DARK_GRAY + " sd open [doorID]"); }else{ playerSender.sendMessage(ChatColor.DARK_RED + "You don't have permissions for that command!"); return; } }
1
private void flaggedMinesCheck() throws IllegalStateException { if (flaggedMines < 0) throw new IllegalStateException("The number of flagged mines is below 0."); if (flaggedMines > mineCount) throw new IllegalStateException("The number of flagged mines is above the maximum, "+mineCount+"."); // If the player has flagged all of the mines, check to see if they have over-flagged. if (flaggedMines == mineCount) { int flaggedSquares = 0; for (int y = 0; y < gridSize; y++) { for (int x = 0; x < gridSize; x++) { if (squares[x][y].isFlagged()) { flaggedSquares++; } } } // The player has found all of the mines and won the game. if (flaggedSquares == mineCount) { hasEnded = true; hasSucceeded = true; // Reveal any remaining squares. for (int y = 0; y < gridSize; y++) { for (int x = 0; x < gridSize; x++) { squares[x][y].revealNotMine(); } } } } }
9
public JMenuItem getExportDataMenuItem() { return exportDataMenuItem; }
0
public String toString() { if (top == 0) { return ""; } else { return new String(data, 0, top); } }
1
public void doGuess( String letter ) { if ( ! isReady() || ! letter.matches( "[A-Z]|[a-z]" )) return; if (usedLetters.contains( letter )) { onRedundantLetter.execute( letter ); return; } boolean isGoodGuess = guessLetterAndReveal( letter ); boolean isComplete = ! getWordFormatted().contains( "_" ); if (isGoodGuess) { onGoodGuess.execute(); if (isComplete) endGame( true ); } else { onBadGuess.execute(); if ( ! hasGuessesLeft.evaluate()) endGame( false ); } }
6
public void checkButtonsEnabled(){ topDecreaseButton.setEnabled(topSpinner.nextButton.isEnabled()); topIncreaseButton.setEnabled(topSpinner.prevButton.isEnabled()); bottomDecreaseButton.setEnabled(bottomSpinner.prevButton.isEnabled()); bottomIncreaseButton.setEnabled(bottomSpinner.nextButton.isEnabled()); leftDecreaseButton.setEnabled(leftSpinner.nextButton.isEnabled()); leftIncreaseButton.setEnabled(leftSpinner.prevButton.isEnabled()); rightDecreaseButton.setEnabled(rightSpinner.prevButton.isEnabled()); rightIncreaseButton.setEnabled(rightSpinner.nextButton.isEnabled()); boolean applyEnbaled = (Integer)topSpinner.getValue() != 0 || (Integer)bottomSpinner.getValue() != 0 || (Integer)leftSpinner.getValue() != 0 || (Integer)rightSpinner.getValue() != 0; applyButton.setEnabled(applyEnbaled); }
3
private boolean validateCutTimes() { for(VideoSectionPanel panel : results) { if (!panel.validateTimes()) { //warning window JOptionPane.showMessageDialog(frame, panel.errorMessage(), "Warning - wrong time format", JOptionPane.WARNING_MESSAGE); return false; } } return true; }
2
@Override public String getColumnName(int columnIndex) { switch (columnIndex) { case 0: return "Name"; case 1: return "Size"; case 2: return "Modified"; default: return ""; } }
3
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(VistaLoading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VistaLoading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VistaLoading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VistaLoading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { VistaLoading dialog = new VistaLoading(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public static MaxSegments valueOf(byte id) { if (id == UNSPECIFIED.id) return UNSPECIFIED; if (id == UP_TO_2.id) return UP_TO_2; if (id == UP_TO_4.id) return UP_TO_4; if (id == UP_TO_8.id) return UP_TO_8; if (id == UP_TO_16.id) return UP_TO_16; if (id == UP_TO_32.id) return UP_TO_32; if (id == UP_TO_64.id) return UP_TO_64; if (id == MORE_THAN_64.id) return MORE_THAN_64; throw new IllegalArgumentException("Unknown id: " + id); }
8
@Override public List<PastMeeting> getPastMeetingList(Contact contact) { if(contactExists(contact)) { Iterator meetingIterator = allMeetings.iterator(); Meeting nextMeeting; //Calendar nextCal; List<PastMeeting> returnList = new ArrayList<>(); while(meetingIterator.hasNext()) { nextMeeting = (Meeting) meetingIterator.next(); //nextCal = nextMeeting.getDate(); if(nextMeeting instanceof PastMeeting && nextMeeting.getContacts().contains(contact)) { returnList.add((PastMeeting) nextMeeting); } } // Sorts list using the Comparator from Java Collections. Collections.sort(returnList, dateSorter); return returnList; } else { throw new IllegalArgumentException(); } }
4
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if(commandLabel.compareToIgnoreCase("portalboots") == 0){ if(sender.hasPermission("portalgel.portalboots")){ if(args.length == 1){ if(args[0].compareToIgnoreCase("on") == 0){ plugin.setBoots(true); sender.sendMessage("Portal boots turned on"); } else if(args[0].compareToIgnoreCase("off") == 0){ plugin.setBoots(false); sender.sendMessage("Portal boots turned off"); } } else sender.sendMessage("Correct format for command is: /portalboots <on|off>"); }else sender.sendMessage("You don't have sufficient permissions"); } else return false; return true; }
5
public void close(){ try { file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
1
public Question randomQuestion() { int rndQuestion = random.nextInt(QUESTION_COUNT); int rndExc = random.nextInt(excDatas.length); ExcData excData = excDatas[rndExc]; switch (rndQuestion) { case 0: return new ByDescription(excData); case 1: return new IsChecked(excData); case 2: return new ParentClass(excData); case 3: return new WhichPackage(excData); default: throw new IllegalStateException("Question class not exists with index " + rndQuestion); } }
4
public void visitMultiANewArrayInsn(final String desc, final int dims) { buf.setLength(0); buf.append(tab2).append("MULTIANEWARRAY "); appendDescriptor(FIELD_DESCRIPTOR, desc); buf.append(' ').append(dims).append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitMultiANewArrayInsn(desc, dims); } }
1
public void printPicture() { PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new Printable() { public int print(Graphics graphics, PageFormat pf, int pageIndex) throws PrinterException { if (pageIndex > 0) { return 1; } Graphics2D g2d = (Graphics2D)graphics; g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.drawImage(InteractiveDisplay.this.getBufferedImage(), 0, 0, null); return 0; } }); if (pj.printDialog()) try { pj.print(); } catch (PrinterException e1) { e1.printStackTrace(); } /*if (pj.printDialog()) { try { PageFormat pf = new PageFormat(); Paper p = new Paper(); p.setImageableArea(this.imagePane.getX(), this.imagePane.getY(), this.imagePane.getWidth(), imagePane.getHeight()); pf.setPaper(p); pj.pageDialog(pf); pj.print(); System.out.println("Printed"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Printed"); }*/ }
3
public void playersInWorldMessage(World world, Player player){ if (plugin.getPlayersInWorld(world, player) != "" && world != null){ List<Player> players = world.getPlayers(); if (players.size() == 1){ player.sendMessage(ChatColor.GOLD + "You're the only user in this world!"); }else{ player.sendMessage(ChatColor.GOLD + "Players in this world: " + plugin.getPlayersInWorld(world, player)); } } }
3
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(MenuEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuEmpleado.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 MenuEmpleado().setVisible(true); } }); }
6
public void closePopUp() { Parent parentRoot = ((Stage) stage.getOwner()).getScene().getRoot(); if (parentRoot instanceof StackPane) { ((StackPane) parentRoot).getChildren().remove(mask); } stage.close(); }
1
public Object eval(CallStack callstack, Interpreter interpreter) throws EvalError { publishLineNumber(); int numChild = jjtGetNumChildren(); // Order of body and condition is swapped for do / while final SimpleNode condExp; final SimpleNode body; if (isDoStatement) { condExp = (SimpleNode) jjtGetChild(1); body = (SimpleNode) jjtGetChild(0); } else { condExp = (SimpleNode) jjtGetChild(0); if (numChild > 1) { body = (SimpleNode) jjtGetChild(1); } else { body = null; } } boolean doOnceFlag = isDoStatement; while (doOnceFlag || BSHIfStatement.evaluateCondition(condExp, callstack, interpreter)) { doOnceFlag = false; // no body? if (body == null) { continue; } Object ret = body.eval(callstack, interpreter); if (ret instanceof ReturnControl) { switch (((ReturnControl) ret).kind) { case RETURN: return ret; case CONTINUE: break; case BREAK: return Primitive.VOID; } } } return Primitive.VOID; }
9
private boolean isLegalPosition(Position p) { if ((p != null) && (p.row >= 0) && (p.row < TicTacToeBoard.SIZE) && (p.col >= 0) && (p.col < TicTacToeBoard.SIZE)) { return true; } else { return false; } }
5
PERangeList difference(PERange rangeb) { PERangeList difference = new PERangeList(); int s = (this.begin < rangeb.begin) ? this.begin : rangeb.begin; int e = (this.end < rangeb.begin) ? this.end : rangeb.begin - 1; if (s <= e) { difference.add(new PERange(s, e)); } s = (this.begin <= rangeb.end) ? rangeb.end + 1 : this.begin; e = (this.end > rangeb.end) ? this.end : rangeb.end; if (s <= e) { difference.add(new PERange(s, e)); } return difference.size() == 0 ? null : difference; }
7
public int[][] getVisual(){ int[][] visual = new int[shape.length][shape[0].length]; for (int i = 0; i<shape.length; i++){ for (int j = 0; j<shape[0].length; j++){ if (shape[i][j] != 0){ visual [i][j] = shape[i][j] != STRENGTH_MANA ? visualCode : -1; } } } return visual; }
4
public int moveRight(boolean findChange) { int total = 0; for (int y = 0; y < 4; y++) { for (int x = 0; x < 3; x++) { if (next.grid[x][y] != 0 && next.grid[x][y] == next.grid[x+1][y]) { next.grid[x+1][y] *= 2; next.grid[x][y] = 0; total += weightingMerge(next.grid[x][y]); } else if (next.grid[x+1][y] == 0 && next.grid[x][y] > 0) { next.grid[x+1][y] = next.grid[x][y]; next.grid[x][y] = 0; } } } if (findChange) return total + findChange(); return total; }
7
static int hanoiMoves(int discs){ if(discs == 1){ return 1; } return hanoiMoves(discs-1) + 1 + hanoiMoves(discs-1); }
1
protected void togglePassword(boolean enabled){ if(enabled){ passwordChkbox.setSelected(true); serv_pswd.setEnabled(true); } else { passwordChkbox.setSelected(false); serv_pswd.setEnabled(false); } }
1
@Override public synchronized Fingerprint add(Fingerprint fprint) { Connection conn = db.getConnection(); Vector<PreparedStatement> vps = new Vector<PreparedStatement>(); ResultSet rs = null; try { conn.setAutoCommit(false); Measurement m = (Measurement)fprint.getMeasurement(); int measurementId = HomeFactory.getMeasurementHome().executeInsertUpdate(vps, m); m.setId(measurementId); // wifi HomeFactory.getWiFiReadingVectorHome().executeUpdate(vps, m.getWiFiReadings(), measurementId); // gsm HomeFactory.getGSMReadingVectorHome().executeUpdate(vps, m.getGsmReadings(), measurementId); // bluetooth HomeFactory.getBluetoothReadingVectorHome().executeUpdate(vps, m.getBluetoothReadings(), measurementId); Location l = (Location)fprint.getLocation(); int locationId = l.getId() == null ? -1 : l.getId().intValue(); if (locationId == -1) { locationId = HomeFactory.getLocationHome().executeInsertUpdate(vps, l); //.getPrimaryKeyId(); l.setId(locationId); } int fingerprintId = executeInsertUpdate(vps, fprint); conn.commit(); return getById(fingerprintId); } catch (SQLException e) { log.log(Level.SEVERE, "add fingerprint failed: " + e.getMessage(), e); } finally { try { conn.setAutoCommit(true); if (rs != null) rs.close(); for(PreparedStatement p : vps) { if (p != null) p.close(); } } catch (SQLException es) { log.log(Level.WARNING, "failed to close statement: " + es.getMessage(), es); } } return null; }
7
private void hbCreateDecodeTables(int[] limit, int[] base, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) { for (j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp] = j; pp++; } } }; for (i = 0; i < MAX_CODE_LEN; i++) { base[i] = 0; } for (i = 0; i < alphaSize; i++) { base[length[i] + 1]++; } for (i = 1; i < MAX_CODE_LEN; i++) { base[i] += base[i - 1]; } for (i = 0; i < MAX_CODE_LEN; i++) { limit[i] = 0; } vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (base[i + 1] - base[i]); limit[i] = vec - 1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) { base[i] = ((limit[i - 1] + 1) << 1) - base[i]; } }
9
@Override public int decode( byte[] data, int offset, DecodeState ds, CerealDecoder context ) throws InvalidEncoding, ResourceNotFound { long propDecodeResult = NumberEncoding.readUnsignedBase128(data, offset); long props = NumberEncoding.base128Value(propDecodeResult); offset += NumberEncoding.base128Skip(propDecodeResult); if( (props | KNOWN_PROP_MASK) != KNOWN_PROP_MASK ) { throw new InvalidEncoding(String.format("Unknown block properties encoded: %x", props)); } long bitAddress = 0; long flags = 0; Icon icon = null; BlockInternals internals = BoringBlockInternals.INSTANCE; if( (props & PROP_INTERNALS) != 0 ) { internals = context.removeStackItem(ds, -1, BlockInternals.class); } if( (props & PROP_ICON) != 0 ) { icon = context.removeStackItem(ds, -1, Icon.class); } if( (props & PROP_FLAGS) != 0 ) { flags = context.removeStackItem(ds, -1, Number.class).longValue(); } if( (props & PROP_BIT_ADDRESS) != 0 ) { bitAddress = context.removeStackItem(ds, -1, Number.class).longValue(); } // TODO: We should probably have the no-icon-specified case be Icon.INVISIBLE or something if( icon == null ) throw new InvalidEncoding("Block encoded with no icon"); ds.pushStackItem(new Block(bitAddress, flags, icon, internals)); return offset; }
6
public JGImage toDisplayCompatible(int thresh,JGColor bg_col, boolean fast, boolean bitmask) { Color bgcol = new Color(bg_col.r,bg_col.g,bg_col.b); int bgcol_rgb = (bgcol.getRed()<<16) | (bgcol.getGreen()<<8) | bgcol.getBlue(); JGPoint size = getSize(); int [] buffer = getPixels(); // render image to bg depending on bgcol BufferedImage img_bg; if (bitmask) { img_bg=createCompatibleImage(size.x,size.y,Transparency.BITMASK); } else { img_bg=createCompatibleImage(size.x,size.y,Transparency.TRANSLUCENT); } int [] bg_buf; if (!fast) { Graphics g=img_bg.getGraphics(); g.setColor(bgcol); // the docs say I could use bgcol in the drawImage as an // equivalent to the following two lines, but this // doesn't handle translucency properly and is _slower_ g.fillRect(0,0,size.x,size.y); g.drawImage(img,0,0,null); bg_buf = new JREImage(img_bg).getPixels(); } else { bg_buf=buffer; } //g.dispose(); //ColorModel rgb_bitmask = ColorModel.getRGBdefault(); //rgb_bitmask = new PackedColorModel( // rgb_bitmask.getColorSpace(),25,0xff0000,0x00ff00,0x0000ff, // 0x1000000, false, Transparency.BITMASK, DataBuffer.TYPE_INT); // ColorSpace space, int bits, int rmask, int gmask, int bmask, int amask, boolean isAlphaPremultiplied, int trans, int transferType) int [] thrsbuf = new int [size.x * size.y]; for(int y = 0; y < size.y; y++) { for(int x = 0; x < size.x; x++) { if ( ( (buffer[y*size.x+x] >> 24) & 0xff ) >= thresh) { thrsbuf[y*size.x+x]=bg_buf[y*size.x+x]|(0xff<<24); } else { // explicitly set the colour of the transparent pixel. // This makes a difference when scaling! //thrsbuf[y*size.x+x]=bg_buf[y*size.x+x]&~(0xff<<24); thrsbuf[y*size.x+x]=bgcol_rgb; } } } return new JREImage( output_comp.createImage( new MemoryImageSource(size.x,size.y, //rgb_bitmask, img_bg.getColorModel(), // display compatible bitmask bitmask ? thrsbuf : bg_buf, 0, size.x) ) ); }
6
public void markInputOutput(){ int markIn; int stu = 0; int dist = 0; int pass = 0; int fail = 0; int inval = 0; do { System.out.print("Input a mark: "); String str = System.console().readLine(); markIn = Integer.parseInt(str); stu++; if (markIn >= 70 && markIn <= 100){ dist++; } else if (markIn >= 50 && markIn <= 69){ pass++; } else if (markIn >= 0 && markIn <= 49){ fail++; } else { inval++; } } while(markIn != -1); System.out.println("There are " + stu + " students: " + dist + " distinctions, " + 1 + " pass, " + fail + " fails (plus " + inval + " invalid)."); }
7
public static ImageContentEnumeration fromValue(String v) { for (ImageContentEnumeration c: ImageContentEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
public Object readValue() throws IOException, JSONException { int c = this.skipWSRead(); switch(c) { case -1: return JSONReader.EOF; case JSON.BEGIN_ARRAY: return this.readArray(); case JSON.BEGIN_OBJECT: return this.readObject(); case JSON.QUOTE_CHAR: return this.readString(); default: this.unread(c); return this.readLiteralOrNumber(); } }
4
public static String escape(String string) { char c; String s = string.trim(); StringBuffer sb = new StringBuffer(); int length = s.length(); for (int i = 0; i < length; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char)(c & 0x0f), 16)); } else { sb.append(c); } } return sb.toString(); }
6
public static int dajUkupanBrojRazlicitihGostiju() { Session session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createQuery("from " + Boravak.class.getName()); List<Boravak> sviBoravci = (List<Boravak>)q.list(); session.close(); List<Long> gostIds = new ArrayList(); for(Boravak boravak : sviBoravci) { if(boravak.getGost() != null) { if(!gostIds.contains(boravak.getGost().getId())) { gostIds.add(boravak.getGost().getId()); } } } return gostIds.size(); }
3
public void swapPaint(int var1) { if(var1 > 0) { var1 = 1; } if(var1 < 0) { var1 = -1; } for(this.selected -= var1; this.selected < 0; this.selected += this.slots.length) { ; } while(this.selected >= this.slots.length) { this.selected -= this.slots.length; } }
4
public static int firstMissingPositive(int[] A) { if (null == A || 0 == A.length) return 1; int n = A.length; for (int i = 0; i < n; i++) { int elem = A[i]; while (elem > 0 && elem < n + 1 && elem != A[elem - 1]) { A[i] = A[elem - 1]; A[elem - 1] = elem; elem = A[i]; } } for (int i = 0; i < n; i++) { if (i + 1 != A[i]) return i + 1; } return n + 1; }
8
public void loadCenter(FileSystem fs, Path path, Configuration conf){ SequenceFile.Reader reader ; try { //initializae centers with number of empty vector for(int i =0 ;i<Constant.K;i++) { Map<Integer, Float> centerVect = new HashMap<Integer, Float>(); centers.add(centerVect); } reader = new SequenceFile.Reader(fs, path, conf); IntWritable key = (IntWritable) reader.getKeyClass().newInstance(); IntFloatPairArray value = (IntFloatPairArray) reader.getValueClass().newInstance(); while(reader.next(key, value)) { int centerId = key.get(); chkCenter[centerId] = true; Map<Integer, Float> centerVect = centers.get(centerId); IntFloatPair[] ifp = (IntFloatPair[]) value.toArray(); for(int i=0; i<ifp.length; i++) { centerVect.put(ifp[i].getFirst(), ifp[i].getSecond()); } //centers.set(centerId, centerVect); } //generate new center for empty ones for(int i =0 ;i<Constant.K;i++) { if(!chkCenter[i]) { Map<Integer, Float> centerVect = centers.get(i); for(int j=0; j<10;j++) { int fet = Kmath.getRandom(Constant.FEATURES); centerVect.put(fet, (float)1); } } } reader.close(); } catch(Exception e) { System.out.println("WARNING: No "+path.toString()+":Couldn't read cache file:"+e.toString()); } }
7
public boolean equals( Object obj) { if ((obj == null) || !(obj instanceof SecretKeySpec)) { return false; } SecretKeySpec spec = (SecretKeySpec)obj; if (!this.algorithm.equalsIgnoreCase(spec.algorithm)) { return false; } if (this.key.length != spec.key.length) { return false; } for (int i = 0; i != this.key.length; i++) { if (this.key[i] != spec.key[i]) { return false; } } return true; }
6