text
stringlengths
14
410k
label
int32
0
9
public boolean equals(Object o) { if (!(o instanceof Quaternion) ) { return false; } if (this == o) { return true; } Quaternion comp = (Quaternion) o; if (Float.compare(x,comp.x) != 0) return false; if (Float.compare(y,comp.y) != 0) return false; if (Float.compare(z,comp.z) != 0) return false; if (Float.compare(w,comp.w) != 0) return false; return true; }
6
@Override public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { String url = event.getDescription(); if (url != null) { client.openInBrowser(url); } } catch(Exception e) { e.printStackTrace(); } } }
3
public static void main(String[] args) throws FileNotFoundException, IOException{ Set<String> sw = StopWord.getStopWords(); List<String> dataFiles = new ArrayList<String>(); File[] files = new File("lyricsdata").listFiles(); // Detect what files to clean. for (File file : files) { if (file.isFile()) { String fileName = file.getName(); String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); if(fileEnd.equals("lyric")) { dataFiles.add(fileName); } } } // Clean all files and save them to new file 'fileName.artistcleaned'. for(String fileName : dataFiles) { List<String> cleanedBio = new LinkedList<String>(); try(BufferedReader br = new BufferedReader(new FileReader("lyricsdata/" + fileName))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String bio = sb.toString(); //Separate all words String[] words = bio.split(" |\t|\n"); for(String s : words) { cleanedBio.add(s); } } //Clean the bio and remove stop words. cleanedBio = DataCleaner.firstCleanOfText(cleanedBio); DataCleaner.removeStopWords(sw, cleanedBio); cleanedBio = DataCleaner.secondCleanOfText(cleanedBio); //Print to new file PrintWriter pw = new PrintWriter("lyricsdata/" + fileName + "cleaned"); for(String s : cleanedBio) { pw.println(s.toLowerCase()); } pw.close(); } System.out.println("Data is now cleaned!"); }
7
public void setNumberOfTransactions(BigInteger value) { this.numberOfTransactions = value; }
0
public void setSelectedColor(int button, Color c) { switch (button) { case MouseEvent.BUTTON1: setLeft(c); return; case MouseEvent.BUTTON3: setRight(c); return; default: if ((button & (MouseEvent.BUTTON1_MASK | MouseEvent.BUTTON1_DOWN_MASK)) != 0) setLeft(c); if ((button & (MouseEvent.BUTTON3_MASK | MouseEvent.BUTTON3_DOWN_MASK)) != 0) setRight(c); } }
4
public static void botMove(Field field){ boolean setRandomCell = false; while (!setRandomCell) { int randomXCoordinate = (int)(Math.random()*field.getFieldSize()); int randomYCoordinate = (int)(Math.random()*field.getFieldSize()); if(randomXCoordinate < field.getFieldSize() && randomYCoordinate < field.getFieldSize()){ setRandomCell = field.setCellSecondPlayer(randomXCoordinate,randomYCoordinate); } } }
3
public void reorderList(ListNode head) { //find mid if (head == null || head.next == null) { return; } ListNode p1 = head; ListNode p2 = head; ListNode midPre = head; while (p1.next != null && (p2.next != null && p2.next.next != null)) { p1 = p1.next; midPre = p1; p2 = p2.next.next; } //reverse mid -> end p1 = p1.next; ListNode cur = p1.next; midPre.next = null; p1.next = null; while (cur != null) { ListNode t = cur.next; cur.next = p1; p1 = cur; cur = t; } //now p1 is the head, do merge ListNode p = head; while (p != null && p1 != null) { ListNode A = p.next; ListNode B = p1.next; p.next = p1; p1.next = A; p = A; p1 = B; } }
8
public void updateNPC(Player plr, stream str) { updateBlock.currentOffset = 0; str.createFrameVarSizeWord(65); str.initBitAccess(); str.writeBits(8, plr.npcListSize); int size = plr.npcListSize; plr.npcListSize = 0; for(int i = 0; i < size; i++) { if(plr.RebuildNPCList == false && plr.withinDistance(plr.npcList[i]) == true) { plr.npcList[i].updateNPCMovement(str); plr.npcList[i].appendNPCUpdateBlock(updateBlock); plr.npcList[plr.npcListSize++] = plr.npcList[i]; } else { int id = plr.npcList[i].npcId; plr.npcInListBitmap[id>>3] &= ~(1 << (id&7)); // clear the flag str.writeBits(1, 1); str.writeBits(2, 3); // tells client to remove this npc from list } } // iterate through all npcs to check whether there's new npcs to add for(int i = 0; i < NPCHandler.maxNPCs; i++) { if(server.npcHandler.npcs[i] != null) { int id = server.npcHandler.npcs[i].npcId; if (plr.RebuildNPCList == false && (plr.npcInListBitmap[id>>3]&(1 << (id&7))) != 0) { // npc already in npcList } else if (plr.withinDistance(server.npcHandler.npcs[i]) == false) { // out of sight } else { plr.addNewNPC(server.npcHandler.npcs[i], str, updateBlock); } } } plr.RebuildNPCList = false; if(updateBlock.currentOffset > 0) { str.writeBits(14, 16383); // magic EOF - needed only when npc updateblock follows str.finishBitAccess(); // append update block str.writeBytes(updateBlock.buffer, updateBlock.currentOffset, 0); } else { str.finishBitAccess(); } str.endFrameVarSizeWord(); }
9
void setItemFont () { if (!instance.startup) { tabFolder1.getItem (0).setFont (itemFont); setExampleWidgetSize(); } /* Set the font item's image to match the font of the item. */ Font ft = itemFont; if (ft == null) ft = tabFolder1.getItem (0).getFont (); TableItem item = colorAndFontTable.getItem(ITEM_FONT); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (fontImage(ft)); item.setFont(ft); colorAndFontTable.layout (); }
3
* @return Returns true if the cell is a swimlane. */ public boolean isSwimlane(Object cell) { if (cell != null) { if (model.getParent(cell) != model.getRoot()) { mxCellState state = view.getState(cell); Map<String, Object> style = (state != null) ? state.getStyle() : getCellStyle(cell); if (style != null && !model.isEdge(cell)) { return mxUtils .getString(style, mxConstants.STYLE_SHAPE, "") .equals(mxConstants.SHAPE_SWIMLANE); } } } return false; }
5
public static void main(String[] args) throws SQLException{ int choice = -1; DBtask db = new DBtask();//create new database access object db.getConnection();//establish a connection BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); //while(choice < 0){ System.out.print("Please enter 1 to search, or 2 to add a new item: "); try { choice = Integer.parseInt(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("ERROR: Please enter 1 or 2"); e.printStackTrace(); } //} if (choice == 1){ System.out.println("Would you like to search by: \n1.Category\n2.Size\n3.Gender\n4.Style?"); try { int searchChoice = Integer.parseInt(br.readLine()); if (searchChoice == 1){ System.out.print("Please enter the category you'd like to search for: "); String cat = br.readLine(); Search.searchByCategory(cat); }else if (searchChoice == 2){ System.out.print("Please enter the size you'd like to search for: "); String siz = br.readLine(); Search.searchBySize(siz); }else if (searchChoice == 3){ System.out.print("Please enter the Gender you'd like to search for: "); String gen = br.readLine(); Search.searchByGender(gen); }else if (searchChoice == 4){ System.out.print("Please enter the Style you'd like to search for: "); String sty = br.readLine(); Search.searchByStyle(sty); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if (choice == 2){ try{ System.out.println("Please enter the information for the new item."); System.out.println("Category: "); String cat = br.readLine(); System.out.println("\nStyle: "); String sty = br.readLine(); System.out.print("\nSize: "); String siz = br.readLine(); System.out.println("\nGender: "); String gen = br.readLine(); System.out.println("\nNumber of items: "); int num = Integer.parseInt(br.readLine()); Insert.newEntry(cat, sty, siz, gen, num); } catch (IOException e){ e.printStackTrace(); } } }
9
public boolean marked(int v) { return marked[v]; }
0
point call(side s, int dir, edge base, point o) throws Coordinator.KilledException { // o is at far end of base if (s.a == bottom) { // region is a singleton return null; } point c = s.a.points[1-s.ai]; if (externAngle(o, s.p, c, dir)) { // no more candidates return null; } while (true) { edge na = s.a.neighbors[s.ai][dir]; // next edge into region if (na == base) { // wrapped all the way around return c; } int nai = na.indexOf(s.p); point nc = na.points[1-nai]; // next potential candidate if (encircled(o, c, s.p, nc, dir)) { // have to break an edge s.a.destroy(); s.a = na; s.ai = nai; c = nc; } else return c; } }
5
public static Double getDouble(final Context context, final int position) { if (position < 0 || context.arguments.size() <= position) return null; if (!Parser.isDouble(context.arguments.get(position))) return null; return Double.parseDouble(context.arguments.get(position)); }
3
protected static Ptg calcOct2Hex( Ptg[] operands ) { if( operands.length < 1 ) { return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "OCT2HEX" ); long l = (long) operands[0].getDoubleVal(); // avoid sci notation String oString = String.valueOf( l ).trim(); // 10 digits at most (=30 bits) if( oString.length() > 10 ) { return new PtgErr( PtgErr.ERROR_NUM ); } int places = 0; if( operands.length > 1 ) { places = operands[1].getIntVal(); } long dec; String hString; try { dec = Long.parseLong( oString, 8 ); // must det. manually if binary string is negative because parseInt/parseLong does not // handle two's complement input!!! if( dec >= 536870912L ) // 2^29 (= 30 bits, signed) { dec -= 1073741824L; // 2^30 (= 31 bits, signed) } hString = Long.toHexString( dec ).toUpperCase(); } catch( Exception e ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( dec < 0 ) { // truncate to 10 digits automatically (should already be two's complement) hString = hString.substring( Math.max( hString.length() - 10, 0 ) ); } else if( places > 0 ) { if( hString.length() > places ) { return new PtgErr( PtgErr.ERROR_NUM ); } hString = ("0000000000" + hString); // maximum= 10 bits hString = hString.substring( hString.length() - places ); } PtgStr pstr = new PtgStr( hString ); log.debug( "Result from OCT2HEX= " + pstr.getString() ); return pstr; }
8
private void calculateGridOffset(Grid grid, GridPoint centerOn) { int gridWidthPx = grid.width * this.tileSize; int gridHeightPx = grid.height * this.tileSize; if (gridWidthPx <= this.gridSpace.width && gridHeightPx <= this.gridSpace.height) { // The grid fits in the space we have with room to spare. The // offsets will be used to center the grid in the space. this.gridXOffset = (this.gridSpace.width - gridWidthPx) / 2; this.gridYOffset = (this.gridSpace.height - gridHeightPx) / 2; } else { // The grid does not fit in the space we have. The offsets will be // used to keep the selected square centered in the view. this.gridXOffset = (this.gridSpace.width / 2) - (centerOn.getColumn() * this.tileSize) - (this.tileSize / 2); this.gridYOffset = (this.gridSpace.height / 2) - (centerOn.getRow() * this.tileSize) - (this.tileSize / 2); // Lock the edges of the grid to the edges of the screen when // selecting a square near the edge of the grid. if (this.gridXOffset > 0) { this.gridXOffset = 0; } if (this.gridYOffset > 0) { this.gridYOffset = 0; } if (this.gridXOffset + gridWidthPx < this.gridSpace.width) { this.gridXOffset = this.gridSpace.width - gridWidthPx; } if (this.gridYOffset + gridHeightPx < this.gridSpace.height) { this.gridYOffset = this.gridSpace.height - gridHeightPx; } // If the grid is bigger on one side but smaller in the other, // center on the smaller side. if (gridWidthPx <= this.gridSpace.width) { this.gridXOffset = (this.gridSpace.width - gridWidthPx) / 2; } else if (gridHeightPx <= this.gridSpace.height) { this.gridYOffset = (this.gridSpace.height - gridHeightPx) / 2; } } }
8
private int GetBlockLenth(String BlockText) { int nBlockLineCount = 0; try { if(("" == BlockText)||(null == BlockText)){ return 0; } BufferedReader br = new BufferedReader(new StringReader(BlockText)); while( br.readLine() != null) { nBlockLineCount++; } return nBlockLineCount; } catch (IOException e) { e.printStackTrace(); return 0; } }
4
public FileProtocol getProtocol() { return this.protocol; }
0
@Test public void test_solvable_matrix_size_3_solve() throws ImpossibleSolutionException,UnsquaredMatrixException, ElementOutOfRangeException{ int height=3; int width=3; float[] result; try{ test_matrix = new Determinant(height,width); }catch(UnsquaredMatrixException e){ throw e; } try{ test_matrix.setValueAt(0,0, 5.0f); test_matrix.setValueAt(0,1, 1.0f); test_matrix.setValueAt(0,2, 0.0f); test_matrix.setValueAt(1,0, 5.0f); test_matrix.setValueAt(1,1, 3.0f); test_matrix.setValueAt(1,2, 1.0f); test_matrix.setValueAt(2,0, 3.0f); test_matrix.setValueAt(2,1, 2.0f); test_matrix.setValueAt(2,2, 5.0f); }catch(ElementOutOfRangeException e){ throw e; } try{ result = test_matrix.solve(); }catch(ImpossibleSolutionException e){ throw e; } Assert.assertEquals(43.0f,result[0],.00001f); }
3
static private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; }
7
public void testProperty() { DateMidnight test = new DateMidnight(); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear())); assertEquals(test.property(DateTimeFieldType.millisOfSecond()), test.property(DateTimeFieldType.millisOfSecond())); DateTimeFieldType bad = new DateTimeFieldType("bad") { private static final long serialVersionUID = 1L; public DurationFieldType getDurationType() { return DurationFieldType.weeks(); } public DurationFieldType getRangeDurationType() { return null; } public DateTimeField getField(Chronology chronology) { return UnsupportedDateTimeField.getInstance(this, UnsupportedDurationField.getInstance(getDurationType())); } }; try { test.property(bad); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} }
2
static int count(String s) { int t=0; for(int i=0;i<s.length();i++) { switch(s.charAt(i)) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: t++; } } return t; }
6
public CropDialog(final Panel panel) { setBounds(1, 1, 270, 190); Toolkit toolkit = getToolkit(); Dimension size = toolkit.getScreenSize(); setLocation(size.width / 3 - getWidth() / 3, size.height / 3 - getHeight() / 3); this.setResizable(false); setLayout(null); JPanel pan1 = new JPanel(); pan1.setBorder(BorderFactory.createTitledBorder("Size")); pan1.setBounds(0, 0, 270, 60); JPanel pan2 = new JPanel(); pan2.setBorder(BorderFactory.createTitledBorder("Start Point")); pan2.setBounds(0, 60, 270, 60); JLabel startPointLabelX = new JLabel("X = "); final JTextField startPointFieldX = new JTextField("0"); startPointFieldX.setColumns(3); JLabel startPointLabelY = new JLabel("Y = "); final JTextField startPointFieldY = new JTextField("0"); startPointFieldY.setColumns(3); JLabel heightLabel = new JLabel("Height = "); final JTextField heightField = new JTextField("100"); heightField.setColumns(3); JLabel widthLabel = new JLabel("Width = "); final JTextField widthField = new JTextField("100"); widthField.setColumns(3); JButton okButton = new JButton("OK"); okButton.setSize(270, 40); okButton.setBounds(0, 120, 270, 40); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int height; int width; int x; int y; try { height = Integer.valueOf(heightField.getText().trim()); width = Integer.valueOf(widthField.getText().trim()); y = Integer.valueOf(startPointFieldX.getText().trim()); x = Integer.valueOf(startPointFieldY.getText().trim()); } catch (NumberFormatException ex) { new MessageFrame("Invalid data"); return; } Image original = panel.getImage(); if (height <= 0 || width <= 0 || x < 0 || y < 0 || x >= original.getHeight() || y >= original.getWidth() || x + height >= original.getHeight() || y + width > original.getWidth()) { new MessageFrame("Invalid Parameters"); return; } Image img = BasicImageUtils.crop(height,width, x, y, original); panel.setImage(img); panel.repaint(); dispose(); } }); pan1.add(heightLabel); pan1.add(heightField); pan1.add(widthLabel); pan1.add(widthField); pan2.add(startPointLabelX); pan2.add(startPointFieldX); pan2.add(startPointLabelY); pan2.add(startPointFieldY); add(pan1); add(pan2); add(okButton); }
9
public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c <= '/' || c >= ':') { return false; } } return true; }
7
public ResultSet pesquisa(String NomeProjeto, String Departamento) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; Projeto projet = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_TODOS_PROJETOS_PESQUISA); comando.setString(1, NomeProjeto + "%"); comando.setString(2, Departamento); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
6
private void install() throws ExInstaller { //Establish a SYS connection DatabaseConnection lDatabaseConnection; try { if(!mCommandLineWrapper.hasOption(CommandLineOption.PROMOTE_USER)){ mCommandLineWrapper.overrideOption(CommandLineOption.PROMOTE_USER, "SYS"); } lDatabaseConnection = DatabaseConnection.createConnection(mCommandLineWrapper, true, false, false); } catch (ExPromote e) { throw new ExInstaller("Failed to connect to database: " + e.getMessage(), e); } //Prompt user for promote user name String lPromoteUserName = mCommandLineWrapper.getOption(CommandLineOption.INSTALL_PROMOTE_USER); lPromoteUserName = XFUtil.nvl(lPromoteUserName, DatabaseConnection.DEFAULT_PROMOTE_USER).toUpperCase(); String lArgPassword = null; if (mCommandLineWrapper.hasOption(CommandLineOption.INSTALL_PROMOTE_PASSWORD)){ lArgPassword = mCommandLineWrapper.getOption(CommandLineOption.INSTALL_PROMOTE_PASSWORD); } //Create the new promote user String lNewPassword = createUser(lDatabaseConnection, lPromoteUserName, lArgPassword); Logger.logAndEcho("Setting user privileges..."); //Run the initial install patch for issuing grants to the user runInstallPatch(lDatabaseConnection, lPromoteUserName, SET_PERMISSIONS_FILE_NAME); //Close existing connections lDatabaseConnection.closePromoteConnection(); lDatabaseConnection.closeLoggingConnection(); //RECONNECT as the new promote user mCommandLineWrapper.overrideOption(CommandLineOption.PROMOTE_USER, lPromoteUserName); mCommandLineWrapper.overrideOption(CommandLineOption.PROMOTE_PASSWORD, lNewPassword); //Always use the JDBC string from the previous connection to avoid re-prompting the user for details mCommandLineWrapper.overrideOption(CommandLineOption.JDBC_CONNECT_STRING, lDatabaseConnection.getJDBCConnectString()); try { lDatabaseConnection = DatabaseConnection.createConnection(mCommandLineWrapper, false, true, false); } catch (ExPromote e) { throw new ExInstaller("Failed to connect to database: " + e.getMessage(), e); } Logger.logAndEcho("Creating database objects..."); //Run part 2 PatchScript lInstallPatch = runInstallPatch(lDatabaseConnection, lPromoteUserName, CREATE_OBJECTS_FILE_NAME); //Log the success in the patch tables we just created PromotionController lPromotionController = new PromotionController(lDatabaseConnection, INSTALL_PROMOTION_LABEL); PatchRunController lPatchRunController = new PatchRunController(lDatabaseConnection, lPromotionController, lInstallPatch); try { lPromotionController.startPromote(); lPatchRunController.validateAndStartPatchRun(); lPatchRunController.endPatchRun(true); lPromotionController.endPromote(true); } catch (ExPromote e) { throw new ExInstaller("Failed to log installation", e); } catch (SQLException e) { throw new ExInstaller("Failed to log installation", e); } Logger.logAndEcho("Migrating legacy patches..."); //Migrate patches but do not allow failure to propogate try { runInstallPatch(lDatabaseConnection, lPromoteUserName, MIGRATE_PATCHES_FILE_NAME); } catch (Throwable th){ Logger.logAndEcho("Migration of legacy patches failed; see log for details"); Logger.logError(th); } lDatabaseConnection.closePromoteConnection(); lDatabaseConnection.closeLoggingConnection(); }
7
@Override public void doAction(String value) { switch (value) { case "DAS": this.displayAverageScore(); break; case "DAA": this.displayAverageScore(); break; case "DLL": this.displayAverageScore(); break; default: System.out.println("Invalid action."); } }
3
public static Cons generateDescriptionsAsRule(Description head, Description tail, Proposition rule, boolean reversepolarityP) { { boolean forwardarrowP = ((BooleanWrapper)(KeyValueList.dynamicSlotValue(rule.dynamicSlots, Logic.SYM_LOGIC_FORWARD_ONLYp, Stella.FALSE_WRAPPER))).wrapperValue && (!reversepolarityP); boolean reverseargumentsP = forwardarrowP || reversepolarityP; Symbol arrow = Surrogate.symbolize(Proposition.chooseImplicationOperator(rule, forwardarrowP)); boolean mapheadvariablesP = Description.namedDescriptionP(head); Stella_Object headprop = null; Stella_Object tailprop = null; Cons universals = Stella.NIL; if (reverseargumentsP) { { Description temp = head; head = tail; tail = temp; } mapheadvariablesP = !mapheadvariablesP; } { PatternVariable var = null; Vector vector000 = (mapheadvariablesP ? tail.ioVariables : head.ioVariables); int index000 = 0; int length000 = vector000.length(); Cons collect000 = null; for (;index000 < length000; index000 = index000 + 1) { var = ((PatternVariable)((vector000.theArray)[index000])); if (collect000 == null) { { collect000 = Cons.cons(PatternVariable.generateOneVariable(var, true), Stella.NIL); if (universals == Stella.NIL) { universals = collect000; } else { Cons.addConsToEndOfConsList(universals, collect000); } } } else { { collect000.rest = Cons.cons(PatternVariable.generateOneVariable(var, true), Stella.NIL); collect000 = collect000.rest; } } } } { Object old$Skolemnamemappingtable$000 = Logic.$SKOLEMNAMEMAPPINGTABLE$.get(); try { Native.setSpecial(Logic.$SKOLEMNAMEMAPPINGTABLE$, (mapheadvariablesP ? ((KeyValueMap)(Logic.createSkolemMappingTable(head.ioVariables, tail.ioVariables))) : null)); headprop = Description.generateDescriptionProposition(head, reversepolarityP); } finally { Logic.$SKOLEMNAMEMAPPINGTABLE$.set(old$Skolemnamemappingtable$000); } } { Object old$Skolemnamemappingtable$001 = Logic.$SKOLEMNAMEMAPPINGTABLE$.get(); try { Native.setSpecial(Logic.$SKOLEMNAMEMAPPINGTABLE$, ((!mapheadvariablesP) ? ((KeyValueMap)(Logic.createSkolemMappingTable(tail.ioVariables, head.ioVariables))) : null)); tailprop = Description.generateDescriptionProposition(tail, reversepolarityP); } finally { Logic.$SKOLEMNAMEMAPPINGTABLE$.set(old$Skolemnamemappingtable$001); } } return (Cons.list$(Cons.cons(Logic.SYM_STELLA_FORALL, Cons.cons(universals, Cons.cons(Cons.cons(Cons.cons(arrow, Cons.cons(headprop, Cons.cons(tailprop, Stella.NIL))), Stella.NIL), Stella.NIL))))); } }
9
static ArrayList<NoSchemaDocument> generateCustomers(int count, ArrayList<NoSchemaDocument> accounts) { ArrayList<NoSchemaDocument> customers = new ArrayList<NoSchemaDocument>(); ArrayList<NoSchemaDocument> addressesData = generateAddresses(count); for (int i=0;i<count;i++) { NoSchemaDocument customer = new NoSchemaDocument(); customer.put("name",randomName()); customer.put("ssn",randomSSN()); customer.put("dob",randomDate()); customer.put("age",randomInt(18,99)); if ((i == 0) || (i % 2 == 0)) { customer.put("home phone",randomPhone()); } if ((i == 0) || (i % 3 == 0)) { customer.put("cell phone",randomPhone()); } customer.put("address",addressesData.get(i)); customer.put("account",accounts.get(i)); customers.add(customer); } return customers; }
5
public String getMessage() { if (!specialConstructor) { return super.getMessage(); } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; }
9
@Before public void setUp() { l = new DoublyLinkedList(); }
0
public void loadScheme() { final String discreteModelFilePath = dlgDiscreteModel.open(); if (discreteModelFilePath != null) { Yaml yaml = new Yaml(); InputStream stream = null; try { stream = new FileInputStream(discreteModelFilePath); } catch (FileNotFoundException ex) { showMessage(Messages.ERROR_FILE_NOT_FOUND + discreteModelFilePath, "Error"); } try { scheme = (Scheme) yaml.load(stream); } catch(Exception ex) { showMessage(Messages.ERROR_WRONG_SCHEME_DOCUMENT + discreteModelFilePath, "Error"); } MainWindow.updateExpandBarElements(library.getLibrary().values(), scheme); schemeEditorPrepare(); signalEditorPrepare(); final String message = Messages.DISCRETE_MODEL_FILE_SELECTED + discreteModelFilePath; status(message); } else { status(Messages.DISCRETE_MODEL_FILE_NOT_SELECTED); } }
3
public Sequence(int size) { items = new Object[size]; }
0
protected static List<Field> getDBFields(Class<?> cls) { ArrayList<Field> r = new ArrayList<Field>(); for (Field f : cls.getFields()) { if (f.isAnnotationPresent(Column.class)) r.add(f); } return r; }
3
static final void method1367(int i, int i_0_, float f, int i_1_, float[] fs, int i_2_, int i_3_, int i_4_, int i_5_, int i_6_, float[] fs_7_) { try { i_2_ -= i; anInt2409++; i_1_ -= i_3_; i_4_ -= i_5_; float f_8_ = (float) i_2_ * fs_7_[2] + (fs_7_[1] * (float) i_4_ + fs_7_[0] * (float) i_1_); float f_9_ = (float) i_2_ * fs_7_[5] + ((float) i_1_ * fs_7_[3] + (float) i_4_ * fs_7_[4]); float f_10_ = (fs_7_[6] * (float) i_1_ + (float) i_4_ * fs_7_[7] + (float) i_2_ * fs_7_[8]); float f_11_ = (float) Math.sqrt((double) (f_8_ * f_8_ + f_9_ * f_9_ + f_10_ * f_10_)); float f_12_ = 0.5F + ((float) Math.atan2((double) f_8_, (double) f_10_) / 6.2831855F); if (i_6_ != -4) method1369((byte) 98); float f_13_ = f + (0.5F + ((float) Math.asin((double) (f_9_ / f_11_)) / 3.1415927F)); if (i_0_ != 1) { if ((i_0_ ^ 0xffffffff) != -3) { if ((i_0_ ^ 0xffffffff) == -4) { float f_14_ = f_12_; f_12_ = f_13_; f_13_ = -f_14_; } } else { f_13_ = -f_13_; f_12_ = -f_12_; } } else { float f_15_ = f_12_; f_12_ = -f_13_; f_13_ = f_15_; } fs[0] = f_12_; fs[1] = f_13_; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("qb.E(" + i + ',' + i_0_ + ',' + f + ',' + i_1_ + ',' + (fs != null ? "{...}" : "null") + ',' + i_2_ + ',' + i_3_ + ',' + i_4_ + ',' + i_5_ + ',' + i_6_ + ',' + (fs_7_ != null ? "{...}" : "null") + ')')); } }
7
public Header readFrame() throws BitstreamException { Header result = null; try { result = readNextFrame(); // E.B, Parse VBR (if any) first frame. if (firstframe == true) { result.parseVBR(frame_bytes); firstframe = false; } } catch (BitstreamException ex) { if ((ex.getErrorCode()==INVALIDFRAME)) { // Try to skip this frame. //System.out.println("INVALIDFRAME"); try { closeFrame(); result = readNextFrame(); } catch (BitstreamException e) { if ((e.getErrorCode()!=STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(e.getErrorCode(), e); } } } else if ((ex.getErrorCode()!=STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(ex.getErrorCode(), ex); } } return result; }
6
@Override public void createPlayer(Player player) { checkDataSource(); validate(player); if (player.getId() != null) { throw new IllegalArgumentException("Player already exists " + player); } try (Connection conn = dataSource.getConnection(); PreparedStatement st = conn.prepareStatement("INSERT INTO PLAYERS (name, surname, number, teamid, home, away, position) VALUES (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) { st.setString(1, player.getName()); st.setString(2, player.getSurname()); st.setInt(3, player.getPlayerNumber()); st.setLong(4, player.getTeamID()); st.setInt(5, player.isHome()?1:0); st.setInt(6, player.isAway()?1:0); st.setString(7, player.getPlayerPosition().toString()); int addedRows = st.executeUpdate(); if (addedRows != 1) { throw new ServiceFailureException("Internal Error: More rows inserted when trying to insert player " + player); } ResultSet key = st.getGeneratedKeys(); Long id = key.getLong(1); if (key.next()) { throw new IllegalArgumentException("Given ResultSet contains more rows"); } player.setId(id); } catch (SQLException ex) { String msg = "error when inserting team" + player; Logger.getLogger(TeamMngrImpl.class.getName()).log(Level.SEVERE, msg, ex); throw new ServiceFailureException(msg); } }
6
private Map<Integer, Double> getNeighbors(int userID, int resID) { Map<Integer, Double> neighbors = new LinkedHashMap<Integer, Double>(); //List<Map<Integer, Integer>> neighborMaps = new ArrayList<Map<Integer, Integer>>(); // get all users that have tagged the resource for (UserData data : this.trainList) { if (data.getUserID() != userID) { if (resID == -1) { neighbors.put(data.getUserID(), 0.0); } else if (data.getWikiID() == resID) { neighbors.put(data.getUserID(), 0.0); } } } //boolean allUsers = false; // if list is empty, use all users if (neighbors.size() == 0) { //allUsers = true; for (UserData data : this.trainList) { neighbors.put(data.getUserID(), 0.0); } } //for (int id : neighbors.keySet()) { // neighborMaps.add(this.userMaps.get(id)); //} if (userID < this.userMaps.size()) { Map<Integer, Integer> targetMap = this.userMaps.get(userID); //double lAverage = getLAverage(neighborMaps); for (Map.Entry<Integer, Double> entry : neighbors.entrySet()) { double bm25Value = /*allUsers ? */Utilities.getJaccardSim(targetMap, this.userMaps.get(entry.getKey()));// : // getBM25Value(neighborMaps, lAverage, targetMap, this.userMaps.get(entry.getKey())); entry.setValue(bm25Value); } // return the sorted neighbors Map<Integer, Double> sortedNeighbors = new TreeMap<Integer, Double>(new DoubleMapComparator(neighbors)); sortedNeighbors.putAll(neighbors); return sortedNeighbors; } return neighbors; }
8
public static void main(String[] args){ if (args.length != 2){ throw new RuntimeException("invalid number of arguments. Must receive two argument specifying working directory and server hostname!!!"); } workingDir = args[0].replace("\\", "/"); if (workingDir.charAt(workingDir.length() - 1) != '/') workingDir += '/'; new File(workingDir).mkdirs(); btHost = args[1]; System.out.println(btHost); siteUID = loadSiteUID(); AirNowParser parser = new AirNowParser(workingDir); System.out.println("getting file list!"); String[] fileList = new File(workingDir + "data/").list(new datFilter()); int count = 0; AirNowData data = new AirNowData(); System.out.println(fileList.length + " files to parse!"); LinkedList<String> filesBeingUploaded = new LinkedList<String>(); new File(workingDir + "data/imported/").mkdirs(); for (String fileName : fileList){ System.out.println("parsing " + fileName); try { FileInputStream fis = new FileInputStream(workingDir + "data/" + fileName); AirNowData newData = parser.parseData(fis); fis.close(); if (newData != null){ filesBeingUploaded.add(fileName); System.out.println("Parse success"); count++; if (count == MAX_FILES_PER_UPLOAD){ count = 0; if (uploadData(data)){ moveFiles(filesBeingUploaded); filesBeingUploaded.clear(); data = newData; } else{ data.merge(newData); } } else{ data.merge(newData); } } else{ System.out.println("Parse failed!"); } } catch (IOException e) { System.out.println("Parse failed"); } } if (uploadData(data)){ moveFiles(filesBeingUploaded); } System.out.println("Finished! Exiting!"); System.exit(0); //sometimes doesn't like to end the process on return? }
8
public CryptoModuleInfoType createCryptoModuleInfoType() { return new CryptoModuleInfoType(); }
0
public static String SPARQLQuery(Model model, String queryType) { // get get all statements for a certain element if (queryType.equalsIgnoreCase("pathway")) { query = "CONSTRUCT { ?s ?p ?o } " + "WHERE { ?s a <http://vocabularies.wikipathways.org/wp#Pathway> . " + "?s ?p ?o }"; } else if (queryType.equalsIgnoreCase("datanode")) { query = "CONSTRUCT { ?s ?p ?o } " + "WHERE { ?s a <http://vocabularies.wikipathways.org/gpml#DataNode> . " + "?s ?p ?o}"; } else if (queryType.equalsIgnoreCase("label")) { query = "CONSTRUCT { ?s ?p ?o } " + "WHERE { ?s a <http://vocabularies.wikipathways.org/gpml#Label> . " + "?s ?p ?o}"; } else if (queryType.equalsIgnoreCase("line")) { query = "CONSTRUCT { ?s ?p ?o } " + "WHERE { ?s a <http://vocabularies.wikipathways.org/gpml#Line> . " + "?s ?p ?o}"; } else if (queryType.equalsIgnoreCase("biopax")) { query = "CONSTRUCT { ?s ?p ?o } " + "where {?s a <http://vocabularies.wikipathways.org/wp#PublicationReference> . " + "?s ?p ?o }"; } else {System.out.println("queryType unkown"); throw new EmptyStackException();} System.out.println(query); // run query parseStatements(model, query, queryType); return null; }
5
String extract(String line, String key) { // System.err.println("line in extract |" + line + "|"); line = line.replace('\'', '\"'); // some sites use ' instead of " // System.err.println("line in extract after replace |" + line + "|"); try { key = key.toLowerCase(); String lower_case = line.toLowerCase(); int i = lower_case.indexOf(key); if (i < 0) return null; i += key.length(); if (line.charAt(i) != '=') return null; i++; int i2; if (line.charAt(i) == '"') { i++; i2 = line.indexOf('"', i); if (i2 < 0) { return line.substring(i); } else { return line.substring(i, i2); } } else { int targ = line.length(); for (i2 = i; i < targ; i++) { if (Character.isWhitespace(line.charAt(i))) break; } return line.substring(i, i2); } } catch (StringIndexOutOfBoundsException e) {} return null; }
7
public boolean testDeplacement(Point p) { boolean estDeplacable = true; if (Math.abs(this.point.x - p.x) == 1) { if (Math.abs(this.point.y - p.y) != 2) { estDeplacable = false; } } else if (Math.abs(this.point.x - p.x) == 2) { if (Math.abs(this.point.y - p.y) != 1) { estDeplacable = false; } } else { estDeplacable = false; } return estDeplacable; }
4
@SuppressWarnings("resource") public PatientInformation(DataSource ds) { while (true) { // Ask for health care number from user. System.out.println("Patient Information Update"); System.out.println("Enter 0 to go back."); System.out.println("Please enter the patient's Health Care No.:"); Scanner input = new Scanner(System.in); int health_care_no = 0; try { health_care_no = input.nextInt(); } catch (Exception e) { System.out.println("Please enter a valid Health Care No."); continue; } // Exit program if user chooses to do so. if (health_care_no == 0) return; promptPatientFieldSelection(ds, health_care_no); continue; } }
3
protected static Ptg calcTBillYield( Ptg[] operands ) { if( operands.length < 3 ) { PtgErr perr = new PtgErr( PtgErr.ERROR_NULL ); return perr; } debugOperands( operands, "calcTBILLYIELD" ); try { GregorianCalendar sDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[0].getValue() ); GregorianCalendar mDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[1].getValue() ); double price = operands[2].getDoubleVal(); long settlementDate = (new Double( DateConverter.getXLSDateVal( sDate ) )).longValue(); long maturityDate = (new Double( DateConverter.getXLSDateVal( mDate ) )).longValue(); if( settlementDate >= maturityDate ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( (maturityDate - settlementDate) > 365 ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( price <= 0 ) { return new PtgErr( PtgErr.ERROR_NUM ); } double DSM = maturityDate - settlementDate; double result = ((100 - price) / price) * (360 / DSM); log.debug( "Result from calcTBILLYIELD= " + result ); PtgNumber pnum = new PtgNumber( result ); return pnum; } catch( Exception e ) { } return new PtgErr( PtgErr.ERROR_VALUE ); }
5
public static void printMonsters(ArrayList<Monster> monsters){ ArrayList<String[]> monsterNames = new ArrayList<String[]>(); for (int i = 0; i < monsters.size(); i++){ monsterNames.add(new String[]{monsters.get(i).toString(), monsters.get(i).toPluralString()}); } ArrayList<String[]> names = new ArrayList<String[]>(); ArrayList<Integer> number = new ArrayList<Integer>(); while(monsterNames.size() > 0) { String[] current = monsterNames.remove(0); boolean exists = false; for(int i = 0; i < names.size(); i++) { if(names.get(i)[0].equals(current[0])) { number.set(i, number.get(i) + 1); exists = true; } } if(!exists) { names.add(current); number.add(1); } } for(int j = 0; j < names.size(); j++) { if(number.get(j) == 1) { out.println("1 " + names.get(j)[0]); } else { out.println(Integer.toString(number.get(j)) + " " + names.get(j)[1]); } } }
7
public void direction() { if (untouchable > 0) { Dolphin dolphin = (Dolphin) getWorld().getObjects(Dolphin.class).get(0); if (dolphin.direction == 0) { setRotation(0); } else if (dolphin.direction == 1) { setRotation(-45); } else if (dolphin.direction == 2) { setRotation(-90); } else if (dolphin.direction == 3) { setRotation(-135); } else if (dolphin.direction == 4) { setRotation(-180); } else if (dolphin.direction == 5) { setRotation(-225); } else if (dolphin.direction == 6) { setRotation(-270); } else if (dolphin.direction == 7) { setRotation(-315); } } }
9
@Override public void salvar(Categoria categoria) throws LojaDLOException { if (categoria.getId() != null){ Categoria categoriaFinal = dao.obter(categoria.getId()); categoriaFinal.setNome(categoria.getNome()); categoriaFinal.setDescricao(categoria.getDescricao()); categoriaFinal.setSecao(categoria.getSecao()); } else { if (dao.obter(categoria.getNome()) == null){ dao.incluir(categoria); } else { throw new LojaDLOException("Este nome já existe"); } } }
2
private void transfer() { String amountStr = JOptionPane.showInputDialog(this, "Input an amount to transfer:", "Transfer", JOptionPane.QUESTION_MESSAGE); if (amountStr == null) { return; } try { BigDecimal amount = FORMATTER.stringToValue(amountStr); Set<Account> accounts = new HashSet<Account>(controller.getCurrentUser().getAccounts()); Iterator<Account> iterator = accounts.iterator(); while (iterator.hasNext()) { Account account = iterator.next(); if (account.getType().isLoan() && account.getBalance().negate().compareTo(amount) < 0) { iterator.remove(); } } if (!accounts.isEmpty()) { Account account = (Account) JOptionPane.showInputDialog(this, "Choose an account:", "Transfer", JOptionPane.QUESTION_MESSAGE, null, accounts.toArray(), accounts.iterator().next()); if (account != null) { this.account.withdraw(amount); account.deposit(amount); controller.updateBankDisplay(); } } else { JOptionPane.showMessageDialog(this, "No accounts can accept that balance.", "Transfer failed", JOptionPane.ERROR_MESSAGE); return; } } catch (ParseException px) { controller.handleException(this, px); } catch (InvalidInputException iix) { controller.handleException(this, iix); } catch (InsufficientFundsException ifx) { controller.handleException(this, ifx); } }
9
public static void updateBoundingBox(final WorldAxisAlignedBoundingBox theWorldAxisAlignedBoundingBox, final Vector3f[] myVectors) { if (myVectors == null || myVectors.length == 0) { return; } /* get minimum and maximum */ _myTempMin.set(myVectors[0]); _myTempMax.set(myVectors[0]); for (int i = 1; i < myVectors.length; i++) { /* minimum */ if (_myTempMin.x > myVectors[i].x) { _myTempMin.x = myVectors[i].x; } if (_myTempMin.y > myVectors[i].y) { _myTempMin.y = myVectors[i].y; } if (_myTempMin.z > myVectors[i].z) { _myTempMin.z = myVectors[i].z; } /* maximum */ if (_myTempMax.x < myVectors[i].x) { _myTempMax.x = myVectors[i].x; } if (_myTempMax.y < myVectors[i].y) { _myTempMax.y = myVectors[i].y; } if (_myTempMax.z < myVectors[i].z) { _myTempMax.z = myVectors[i].z; } } /* create world aligned boundingbox */ /* bb position */ theWorldAxisAlignedBoundingBox.position.sub(_myTempMax, _myTempMin); theWorldAxisAlignedBoundingBox.position.scale(0.5f); theWorldAxisAlignedBoundingBox.position.add(_myTempMin); /* bb scale */ theWorldAxisAlignedBoundingBox.scale.sub(_myTempMax, _myTempMin); theWorldAxisAlignedBoundingBox.scale.x = Math.abs(theWorldAxisAlignedBoundingBox.scale.x); theWorldAxisAlignedBoundingBox.scale.y = Math.abs(theWorldAxisAlignedBoundingBox.scale.y); theWorldAxisAlignedBoundingBox.scale.z = Math.abs(theWorldAxisAlignedBoundingBox.scale.z); }
9
private String getExtension(String f) { // get extension of a file String ext = ""; int i = f.lastIndexOf('.'); if (i > 0 && i < f.length() - 1) { ext = f.substring(i + 1); } return ext; }
2
private void reallyPlotPixel(int x, int y, boolean isBG, boolean isSpr) { int val = 0; // background color if (isBG) { val = getBGPixelIndex(x, y); } else { // When BG rendering is off, we display color index 0 // unless the PPU is currently pointing at $3Fxx in which case that value is // NOT WORKING!!! if ((_loopyV & 0x3F00) == 0x3F00) { val = _loopyV & 0x1F; if ((val & 0x13) == 0x10) { val ^= 0x10; // mirrored entries } } } int palIndex = val; if (val % 4 == 0) { palIndex = 0; } if (isSpr) { int val2 = calcSprite(x, y, (val % 4)); if (val2 % 4 == 0) { val2 = 0; } if ((val % 4 == 0) || val2 != 0) { palIndex = val2; } } byte palColor = _mem.getCHRMemory(0x3F00 + palIndex); _display.plot(x, y, (palColor & 0xFF), isMonochrome, isRedIntensified, isGreenIntensified, isBlueIntensified); }
8
public void write_activated (Pipe pipe_) { // Skip activating if we're detaching this pipe if (pipe != pipe_) { assert (terminating_pipes.contains (pipe_)); return; } if (engine != null) engine.activate_in (); }
2
public static void main(String[] args) { if (args.length == 0) { error("Not enough arguments: 0"); } Set<String> commandList = new HashSet<>(); commandList.add("shutdown"); if (commandList.contains(args[0])) { if (send(args[0])) { System.out.println("SUCCESS!"); } else { System.out.println("ERROR!"); } } else { printHelp(); } }
3
final public void run() { // call the hook method to notify that the server is starting serverStarted(); try { // Repeatedly waits for a new client connection, accepts it, and // starts a new thread to handle data exchange. while(!readyToStop) { try { // Wait here for new connection attempts, or a timeout Socket clientSocket = serverSocket.accept(); // When a client is accepted, create a thread to handle // the data exchange, then add it to thread group synchronized(this) { ConnectionToClient c = new ConnectionToClient( this.clientThreadGroup, clientSocket, this); } } catch (InterruptedIOException exception) { // This will be thrown when a timeout occurs. // The server will continue to listen if not ready to stop. } } // call the hook method to notify that the server has stopped serverStopped(); } catch (IOException exception) { if (!readyToStop) { // Closing the socket must have thrown a SocketException listeningException(exception); } else { serverStopped(); } } finally { readyToStop = true; connectionListener = null; } }
4
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { try { UIManager .setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } UIManager.put("swing.boldMetal", Boolean.FALSE); ApplicationContext context = new AnnotationConfigApplicationContext( SpringBootLoader.class); ProjectMainView projectMainView = (ProjectMainView) context .getBean(ProjectMainView.class); projectMainView.createRightSidePanel(); projectMainView.createLeftSidePanelForProject(); projectMainView.createMenu(); projectMainView.setVisible(true); projectMainView.addListenerForTabbedPane(); }
4
private Object[] grabExternalVoxelData( int x, int y, int z ) { Object[] data = new Object[ 5 ]; if ( region == null ) { data[ 0 ] = null; data[ 1 ] = Math.abs( x ) % LENGTH; data[ 2 ] = Math.abs( y ) % LENGTH; data[ 3 ] = Math.abs( z ) % LENGTH; data[ 4 ] = Material.AIR; return data; } int xOff = ( int ) Math.floor( x / ( double ) LENGTH ); int yOff = ( int ) Math.floor( y / ( double ) LENGTH ); int zOff = ( int ) Math.floor( z / ( double ) LENGTH ); x %= LENGTH; y %= LENGTH; z %= LENGTH; if ( x < 0 ) { x += LENGTH; } if ( y < 0 ) { y += LENGTH; } if ( z < 0 ) { z += LENGTH; } Chunk c = region.getChunkAt( this.x + xOff, this.y + yOff, this.z + zOff ); data[ 0 ] = c; data[ 1 ] = x; data[ 2 ] = y; data[ 3 ] = z; if ( c != null ) { data[ 4 ] = c.getMaterialAt( x, y, z ); } else { data[ 4 ] = Material.AIR; } return data; }
5
public List<Movie> meetCriteria(List<RelatedVote> relatedVotes, List<Integer> voted, List<Integer> notVoted){ RelatedVote rv1 = new RelatedVote(); RelatedVote rv2 = new RelatedVote(); List<Movie> l = new ArrayList<Movie>(); if(voted.size() < 2){ //se votou apenas em um pega os dois que tiveram mais votos quando o votado do momento também foi votado no momento dos outros votos for(Integer m : voted){ for(RelatedVote rv : relatedVotes){ if(!isNotVoted(rv, notVoted) && isVoted(rv, m)){ getMost(rv, rv1, rv2); } } } if(rv1 != null) l.add(getMovie(voted, rv1)); if(rv2 != null) l.add(getMovie(voted, rv2)); }else{ //se for o ultimo voto, deve apresentar aquele q ainda nao foi votado e o com mais votos somando os outros dois votados DAO<RelatedVote> dao = new DAO<RelatedVote>(RelatedVote.class); List<RelatedVote> list1 = dao.list(query, notVoted.get(0), voted.get(0), voted.get(1)); List<RelatedVote> list2 = dao.list(query, notVoted.get(1), voted.get(0), voted.get(1)); int count1 = list1.get(0).getAmount() + list1.get(1).getAmount(); int count2 = list1.get(0).getAmount() + list2.get(1).getAmount(); rv1.setMainOptions(count1 > count2 ? list1.get(0) : list2.get(0)); l.add(getMovie(voted, rv1)); String q = "id NOT IN (" + voted.get(0) + ", " + + voted.get(1) + ", " + + notVoted.get(0) + ", " + + notVoted.get(1) + ")"; DAO<Movie> daoM = new DAO<Movie>(Movie.class); l.add(daoM.find(q)); } return l; }
8
private void createTetrominos(char name) { switch(name){ case 'A': nbVariante=2; polyominos=new int[4][1]; polyominos[0][0]=1; polyominos[1][0]=1; polyominos[2][0]=1; polyominos[3][0]=1; couleur="-8355712"; break; case 'B': nbVariante=1; polyominos=new int[2][2]; polyominos[0][0]=1; polyominos[1][0]=1; polyominos[0][1]=1; polyominos[1][1]=1; couleur="-16711936"; break; case 'C': nbVariante=9; polyominos=new int[2][3]; polyominos[0][0]=1; polyominos[1][0]=1; polyominos[1][1]=1; polyominos[1][2]=1; couleur="-4144960"; break; case 'D': nbVariante=9; polyominos=new int[2][3]; polyominos[0][0]=1; polyominos[1][1]=1; polyominos[0][1]=1; polyominos[0][2]=1; couleur="-65281"; break; case 'E': nbVariante=9; polyominos=new int[2][3]; polyominos[0][0]=1; polyominos[0][1]=1; polyominos[1][1]=1; polyominos[1][2]=1; couleur="-14336"; break; } }
5
private void calcGNI() { double GNI = 0; for (int i = 0; i < _econ.size(); i++) { GNI += _econ.get(i).get_GNI(); } for (int i = 0; i < _cities.size(); i++) { GNI += _cities.get(i).get_econ().get_GNI(); } _GNI = GNI; }
2
private List<String> getInitUrls() { String[] s = { "http://shop67109681.taobao.com", "http://shop36505973.taobao.com", "http://shop33082137.taobao.com", "http://shop71710235.taobao.com" }; return Arrays.asList(s); }
0
public static int LevenshteinDistance(String s, String t) { // degenerate cases if (s == t) return 0; if (s.length() == 0) return t.length(); if (t.length() == 0) return s.length(); // create two work vectors of integer distances int[] v0 = new int[t.length() + 1]; int[] v1 = new int[t.length() + 1]; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (int i = 0; i < v0.length; i++) v0[i] = i; for (int i = 0; i < s.length(); i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for (int j = 0; j < t.length(); j++) { int cost = (s.charAt(i) == t.charAt(j)) ? 0 : 1; // v1[j + 1] = Minimum(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost)); } // copy v1 (current row) to v0 (previous row) for next iteration for (int j = 0; j < v0.length; j++) v0[j] = v1[j]; } return v1[t.length()]; }
8
@Override public void validate() { if (platform == null) { addActionError("Please Select Platorm"); } if (location == null) { addActionError("Please Select Location"); } if (android.equals("Please select")) { addActionError("Please Select Os"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
5
public static void main(String[] args) throws FileNotFoundException, IOException, Exception { Conectar("preguntas_v2.db4o"); Preguntas.BorrarTodo(bd); Preguntas.IntroducirDatos(bd); System.out.println("*********************************************************"); System.out.println(" BIENVENIDO AL TEST DEFINITIVO"); System.out.println("*********************************************************"); System.out.println(""); String[] lista = Preguntas.NombreFicherosDirectorio("Preguntas"); int totalpreguntas = Preguntas.numpreg; int num_preg = ValidarOpcion.ValidarEleccionEntero("Elija de cuantas preguntas quiere el examen: (1-" + totalpreguntas + "): ", 1, totalpreguntas); System.out.println("El examen constará de " + num_preg + " preguntas."); System.out.println(""); double resta_fallo = (10 / (double) num_preg) * 0.3333333334; double suma_acierto = 10 / (double) num_preg; System.out.println("Cada acierto valdrá " + Metodos.Redondear(suma_acierto, 3) + " puntos."); System.out.println("Cada fallo restará " + Metodos.Redondear(resta_fallo, 3) + " sobre la puntuación obtenida de los aciertos."); System.out.println("Lee con atención y suerte."); System.out.println(""); int[] numeros = new int[num_preg]; int[] elecciones = new int[5]; String[] letras = Metodos.EleccionPregunta(); int j; boolean salir; int k; Preguntas v; double tempinicio; double tempfinal; double[] tiempos = new double[num_preg]; IniciarTemporizador(); for (i = 0; i < num_preg; i++) { tempinicio = cont; System.out.println("Pregunta " + (i + 1)); j = Metodos.Random(totalpreguntas); do { k = 0; salir = true; while (k < numeros.length) { if (numeros[k] == j) { if (j < totalpreguntas) { j++; } else { j = 1; } salir = false; } k++; } } while (!salir); numeros[i] = j; v = Preguntas.consultaPreguntas(bd, j); System.out.println("n) NS/NC"); eleccioncadena = ValidarOpcion.ValidarEleccionCadenas("Elija una opción: ", letras); eleccion = Metodos.ConvertirLetraNumero(eleccioncadena); elecciones[eleccion - 1]++; tempfinal = cont; tiempos[i] = tempfinal - tempinicio; if (eleccion != 5) { if (v.getsolucion() == eleccion) { aciertos++; } } else { nsnc++; } System.out.println("SOLUCION--> " + Metodos.DevolverLetra(v.getsolucion())); System.out.println(""); } bd.close(); System.out.println("********************"); System.out.println("RESULTADO DEL EXAMEN"); System.out.println("********************"); System.out.println("Cada acierto vale " + Metodos.Redondear(suma_acierto, 3) + " puntos."); System.out.println("Cada fallo resta " + Metodos.Redondear(resta_fallo, 3) + " sobre la puntuación obtenida de los aciertos."); System.out.println("Aciertos: " + aciertos); int fallos = num_preg - aciertos - nsnc; System.out.println("Fallos: " + (fallos)); double fallos2 = ((10 / (double) num_preg) * 0.3333333334) * (double) fallos; double puntosacierto = ((double) aciertos / num_preg) * 10; double calif = puntosacierto - (fallos2); System.out.println("NS/NC: " + nsnc); if (calif >= 5) { System.out.println("Has aprobado el examen."); } else { System.out.println("Has suspendido el examen."); } System.out.println("Calificación: " + Metodos.ComprobarNota(calif) + ", " + Metodos.Redondear(calif, 2)); System.out.println("******************"); System.out.println("Datos de interés: "); System.out.println("******************"); System.out.println("Has tardado " + Metodos.Redondear(cont, 2) + " segundos en completar el test."); double tiempomedio = cont / (double) num_preg; System.out.println("El tiempo medio de respuesta ha sido de: " + Metodos.Redondear(tiempomedio, 2) + " segundos."); System.out.println("La respuesta más rápida ha sido de: " + Metodos.Redondear(Metodos.Minimo(tiempos), 2) + " segundos."); System.out.println("La respuesta más lenta ha sido de: " + Metodos.Redondear(Metodos.Maximo(tiempos), 2) + " segundos."); System.out.println("Porcentaje de opciones elegidas:"); double porcentaje = ((double) elecciones[0] / (double) num_preg) * 100; System.out.println("a): " + Metodos.Redondear(porcentaje, 2) + "%"); porcentaje = ((double) elecciones[1] / (double) num_preg) * 100; System.out.println("b): " + Metodos.Redondear(porcentaje, 2) + "%"); porcentaje = ((double) elecciones[2] / (double) num_preg) * 100; System.out.println("c): " + Metodos.Redondear(porcentaje, 2) + "%"); porcentaje = ((double) elecciones[3] / (double) num_preg) * 100; System.out.println("d): " + Metodos.Redondear(porcentaje, 2) + "%"); porcentaje = ((double) elecciones[4] / (double) num_preg) * 100; System.out.println("NS/NC: " + Metodos.Redondear(porcentaje, 2) + "%"); System.exit(0); }
8
protected void sendMessages() throws Exception { Message[] msgs=generateMessages(num_msgs); CountDownLatch latch=new CountDownLatch(1); AtomicInteger index=new AtomicInteger(0); Sender[] senders=new Sender[num_senders]; for(int i=0; i < senders.length; i++) { senders[i]=new Sender(latch, msgs, index); senders[i].start(); } long start=Util.micros(); latch.countDown(); // starts all sender threads for(Sender sender: senders) sender.join(); // wait until the bundler has no pending msgs left long park_time=1; for(int i=0; i < 1_000_000; i++) { int pending_msgs=bundler.size(); if(pending_msgs == 0) break; LockSupport.parkNanos(park_time); if(i % 10000 == 0) { park_time=Math.min(park_time*2, 1_000_000); // 1 ms max park time } } if(bundler.size() > 0) throw new Exception(String.format("bundler still has %d pending messages", bundler.size())); long time_us=Util.micros()-start; AverageMinMax send_avg=null; for(Sender sender: senders) { if(details) System.out.printf("[%d] count=%d, send-time = %s\n", sender.getId(), sender.send.count(), sender.send); if(send_avg == null) send_avg=sender.send; else send_avg.merge(sender.send); } double msgs_sec=num_msgs / (time_us / 1_000.0); System.out.printf(Util.bold("\n\nreqs/ms = %.2f (time: %d us)" + "\nsend-time = min/avg/max: %d / %.2f / %d ns\n"), msgs_sec, time_us, send_avg.min(), send_avg.average(), send_avg.max()); }
9
private void updateDisplay() { int recursionDepth = spinnerModel.getNumber().intValue(); final List expansion = expander.expansionForLevel(recursionDepth); progressBar.setMaximum(expansion.size() * 2); imageDisplay.setImage(null); Image renderImage = null; final javax.swing.Timer t = new javax.swing.Timer(30, new ActionListener() { public void actionPerformed(ActionEvent e) { int i = renderer.getDoneSymbols() - 1; progressBar.setValue(i); progressBar.repaint(); } }); final Thread drawThread = new Thread() { public void run() { if (expansion.size() < 70) { String expansionString = LSystemInputPane .listAsString(expansion); expansionDisplay.setText(expansionString); } else expansionDisplay.setText("Suffice to say, quite long."); // Now, set the display. Map parameters = lsystem.getValues(); t.start(); Matrix m = new Matrix(); double pitch = pitchModel.getNumber().doubleValue(), roll = rollModel .getNumber().doubleValue(), yaw = yawModel.getNumber() .doubleValue(); m.pitch(pitch); m.roll(roll); m.yaw(yaw); Point origin = new Point(); // Ignored, for now. Image image = renderer.render(expansion, parameters, m, null, origin); imageDisplay.setImage(image); t.stop(); imageDisplay.repaint(); imageDisplay.revalidate(); progressBar.setValue(progressBar.getMaximum()); } }; drawThread.start(); }
1
public String getUsername() { return username; }
0
public RreclassificationParametre(){ this.setNomBase(ConnexionBaseDonnees.getNomBase()); this.setPort(ConnexionBaseDonnees.getPort()); this.setNomUtilisateur(ConnexionBaseDonnees.getUser()); this.setMotDePasse(ConnexionBaseDonnees.getPswd()); this.setHote(ConnexionBaseDonnees.getHote()); tableaux.clear(); tableaux2.clear(); tableaux=FenetreReclassificationParametresClasses.getTableauTailles(); tableaux2=FenetreReclassificationParametresClasses.getTableaux(); for(int fg=0;fg<tableaux.size();fg++){ String test34[][]=tableaux.get(fg); String taillePixels=test34[fg][1]; minim.add(taillePixels); String nomCouche=test34[fg][0].toString(); nomCouches.add(nomCouche); String maxi=test34[fg][2].toString(); maxim.add(maxi); } for(int fg=0;fg<tableaux2.size();fg++){ String test34[][]=tableaux2.get(fg); String nombreClassess=test34[fg][1]; nombreClasses.add(nombreClassess); } System.out.println("reclassification333"); String max=""; for(int i=0;i<FenetreReclassificationParametresClasses.getNomCouches().size();i++){ int ii=0; int jj=0; double iiii=Double.parseDouble(nombreClasses.get(i)); int iii=(int)iiii; double[] numberss = new double[iii*3]; for(ii=ii,jj=0;ii<(numberss.length)&&jj<maxim.size();ii=ii+3,jj++){ System.out.println("ii"+ii); System.out.println("jj"+jj); numberss[ii]=Double.parseDouble(minim.get(jj)); numberss[ii+1]=Double.parseDouble(maxim.get(jj)); numberss[ii+2]=jj; } for(ii=0;ii<numberss.length;ii++){ System.out.println("numberss "+numberss[ii]); } RCaller caller = new RCaller(); caller.setRscriptExecutable("/usr/bin/Rscript"); RCode code = new RCode(); code.addRCode("library(RPostgreSQL)"); code.addRCode("library(rgdal)"); code.addRCode("library(raster)"); code.addRCode("library(maptools)"); code.addRCode("library(sp)"); code.addRCode("library(spatstat)"); code.addRCode("layers <- readGDAL(\"PG:host="+this.hote+" user="+this.nomUtilisateur+" dbname="+this.nomBase+" password="+this.motDePasse+" port="+this.port+" table="+FenetreReclassificationParametresClasses.getNomCouches().get(i)+"\")"); System.out.println("layers <- readGDAL(\"PG:host="+this.hote+" user="+this.nomUtilisateur+" dbname="+this.nomBase+" password="+this.motDePasse+" port="+this.port+" table="+FenetreReclassificationParametresClasses.getNomCouches().get(i)+"\")"); code.addRCode("ras <-raster(layers)"); // code.addRCode("m <- c(minim-1,-0.0000001,0,0.0001, sixieme,1, sixieme,tiers,2, tiers,maxim,3)"); code.addDoubleArray("m", numberss); code.addRCode("rclmat <- matrix(m, ncol=3, byrow=TRUE)"); code.addRCode("rc <- reclass(ras,rclmat)"); code.addRCode("rc.sp <- as(rc, \"SpatialPixelsDataFrame\")"); code.addRCode("writeGDAL(rc.sp,"+"\""+FenetreReclassificationParametresClasses.getNomCouches().get(i)+".tif\", drivername=\"GTiff\")"); caller.setRCode(code); caller.runOnly(); //caller.runAndReturnResult("minim"); // caller.runAndReturnResult("my.mean"); //System.out.println("resultat is "+resulat[0]); //code.addRCode(""); // // File file2 = null; // try { // file2 = code.startPlot(); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } //code.addRCode("plot(points_arbres)"); //System.out.println("Plot will be saved to : " + file2); //code.endPlot(); // code.addRCode("drv <- dbDriver(\"PostgreSQL\")"); //code.addRCode("con <- dbConnect(drv, port=5432, dbname= \"testohmam\", user=\"Gilles\", password=\"959426G/e\")"); //code.addRCode("rs <- dbSendQuery(con, \"select surf from batiments\")"); //code.addRCode("data <- fetch(rs,n=-1)"); //code.addRCode("plot(id,data$surf"); ////code.addRCode("plot(pts)"); //code.addRCode("set.seed(123)"); //code.addRCode("x<-rnorm(10)"); //code.addRCode("y<-rnorm(10)"); //code.addRCode("ols<-lm(y~x)"); //rcaller.setRCode(code); // caller.getParser().getAsStringArray("result"); // code.showPlot(file2); // // code.endPlot(); // } // try { // new RasterShapeDensiteBatiments(connexion,choix);ee // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // code.showPlot(file2); // //caller.runAndReturnResult("fetch(rs,n=10)"); //System.out.println("Available results from lm() object:"); //String [] test2; //String test3=""; // code.endPlot(); //test3=caller.getParser().getXMLFileAsString(); //test3=caller.getParser().getXMLFileAsString(); //caller.getParser().getAsStringArray(test3); //ArrayList<String> test = new ArrayList<String>(); //test=caller.getParser().getNames(); //double [] bla={}; //System.out.println(test3); try { new Raster2pgsqlReclassification(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
@Test public void printWelcomeTest() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")); }
0
void dfs(int v, int[] was1, int[] was2) { ++counter$0; long counterBefore = tempCounter1; if (true) { if (was2[v] == 2 || was1[v] == 1) { memCounter$1 = Math.max(tempCounter1, counterBefore); { tempCounter1 = counterBefore; return; } } was1[v] = 1; tempCounter1 = tempCounter1 + 4; for (int i = 0; i < n; i++) { ++counter$1; if (a[v][i] == 1) { dfs(i, was1, was2); } } } memCounter$1 = Math.max(tempCounter1, counterBefore); }
5
public SubjectType getSubjectType() { if(subjectIndex==1) return FOREIGN_LANG; if(subjectIndex<9) return STANDARD; if(wahlfachType<3) { return FOREIGN_LANG; } else { return NATURAL_SCIENCE; } }
3
public void onStatStateChanged(Stat stat) { if (stat.isNormalState()) logger.info(stat.getName() + " now is in normal state: " + stat.getStoredValueAsString()); else logger.error(stat.getName() + ": " + stat.getStateDescription() + ": " + stat.getStoredValueAsString()); }
1
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); int t = Integer.parseInt(in.readLine().trim()); for (int tt = 0; tt < t; tt++) { int n = Integer.parseInt(in.readLine().trim()); if (n <= 1) out.append(n+"\n"); else { int div = 0; boolean pos = true; String num = ""; while (pos && n > 1) { div = 0; for (int i = 9; i >= 2; i--) { while (n % i == 0) { n /= i; num = i + num; div = i; } } pos = div != 0; } if (pos) out.append(num + "\n"); else out.append("-1\n"); } } System.out.print(out); }
7
public int getMultipleState (String name) { int k; for (k = 0; k < Left.size(); k++) { IconBarElement i = (IconBarElement)Left.elementAt(k); if (i.getName().equals(name) && i instanceof MultipleIcon) { return ((MultipleIcon)i) .getSelected(); } } for (k = 0; k < Right.size(); k++) { IconBarElement i = (IconBarElement)Right.elementAt(k); if (i.getName().equals(name) && i instanceof MultipleIcon) { return ((MultipleIcon)i) .getSelected(); } } return -1; }
6
public static void LoadPluginAtBase(){ File base=new File("."); File[] files=base.listFiles(); String[] regex={".+\\.yml",".+\\.smp"}; for(File f:files){ for(String regexs:regex){ if(f.getName().matches(regexs)){ try { List<String> l=FileUtils.readLines(f,"UTF-8"); JMenuItem Plugin=new JMenuItem(l.get(0).substring(6)); Plugin.addActionListener((ActionEvent e) -> { try { ((PluginAPI)Class.forName(l.get(1).substring(7)).newInstance()).LoadPlugin(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(LoadPlugin.class.getName()).log(Level.SEVERE, null, ex); } }); App.jMenu5.add(Plugin); } catch (IOException ex) { Logger.getLogger(LoadPlugin.class.getName()).log(Level.SEVERE, null, ex); } } } } }
5
@Override public void init() { control = LcdBuilder.create() .prefWidth(1280) .prefHeight(400) //.styleClass(Lcd.STYLE_CLASS_GREEN_DARKGREEN) .foregroundShadowVisible(true) .crystalOverlayVisible(true) .title("Room Temp") .batteryVisible(true) .signalVisible(true) .alarmVisible(true) .unit("°C") .unitVisible(true) .decimals(3) .animationDurationInMs(1500) .minMeasuredValueDecimals(2) .minMeasuredValueVisible(true) .maxMeasuredValueDecimals(2) .maxMeasuredValueVisible(true) .formerValueVisible(true) .threshold(26) .thresholdVisible(true) .trendVisible(true) .numberSystemVisible(false) .lowerRightTextVisible(true) .lowerRightText("Info") //.valueFont(Lcd.LcdFont.ELEKTRA) .valueFont(Lcd.LcdFont.LCD) .animated(true) .build(); control.addEventHandler(ValueEvent.VALUE_EXCEEDED, new EventHandler<ValueEvent>() { @Override public void handle(ValueEvent valueEvent) { System.out.println("exceeded"); } }); charge = 0.0; styleClassCounter = 0; lastTimerCall = System.nanoTime(); timer = new AnimationTimer() { @Override public void handle(long now) { if (now > lastTimerCall + 5_000_000_000l) { styleClassCounter ++; if (styleClassCounter >= STYLE_CLASSES.length) { styleClassCounter = 0; control.setMainInnerShadowVisible(true); control.setForegroundShadowVisible(true); control.setCrystalOverlayVisible(true); } control.getStyleClass().setAll("lcd", STYLE_CLASSES[styleClassCounter]); System.out.println(control.getStyleClass()); control.setValue(RND.nextDouble() * 100); control.setTrend(Lcd.Trend.values()[RND.nextInt(5)]); charge += 0.02; if (charge > 1.0) charge = 0.0; control.setBatteryCharge(charge); control.setSignalStrength(charge); if (styleClassCounter > 34) { control.setMainInnerShadowVisible(false); control.setForegroundShadowVisible(false); control.setCrystalOverlayVisible(false); } lastTimerCall = now; } } }; }
4
public Guid readGuid() throws IOException { final byte[] data = new byte[16]; // @todo resource this for (int i = 0; i < 16; i++) { final int currByte = read(); if (currByte == -1) { throw new RuntimeException("Illegal end of stream"); } data[i] = (byte) currByte; } final Guid guid = CycObjectFactory.makeGuid(data); if (trace == API_TRACE_DETAILED) { debugNote("readGuid: " + guid); } return guid; }
3
public void activateEntry(String text, int pos) { int current = 0; for (Widget i = wdg().child; i != null; i = i.next) { if (i instanceof TextEntry) { current++; if (current == pos) { TextEntry te = (TextEntry) i; if (text.equals("")) te.activate(te.text); else te.activate(text); return; } } } }
4
void saveAll() { YamlConfiguration dc = new YamlConfiguration(); File sv = new File(getDataFolder(), "dragons.sav"); if (!sv.exists()) { getDataFolder().mkdirs(); try { sv.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } for (Entry<String, LivingEntity> e : dragons.entrySet()) { String p = e.getKey(); V10Dragon d = (V10Dragon) ((CraftLivingEntity) e.getValue()).getHandle(); dc.set(p + ".world", d.world.getWorld().getName()); dc.set(p + ".x", d.locX); dc.set(p + ".y", d.locY); dc.set(p + ".z", d.locZ); dc.set(p + ".yaw", d.yaw); dc.set(p + ".lived", d.ticksLived); dc.set(p + ".food", d.fl); } try { dc.save(sv); } catch (IOException e) { getLogger().info("WARNING: Couldn't save!"); e.printStackTrace(); } if (!saveChanged) { return; } for (Entry<String, Integer> e : mh.entrySet()) { config.set("heights." + e.getKey(), e.getValue()); } ArrayList<String> sg = new ArrayList<>(stopGrief); config.set("FullProtect", sg); config.set("Factions", factions); config.set("RideSpeed", rideSpeed); config.set("Lifetime", lifetime); if (economy != null) { config.set("DragonCost", price); } config.set("Silence", silence); saveConfig(); config.set("heights", null); saveChanged = false; }
7
@Override public void run() { for (Planet p : currentPlanets) { if (p.getTag().equals("[=H=]")) { restored.add(p); } } for (Planet p : oldPlanets) { if (p.getTag().equals("[=H=]")) { restored.remove(p); } } }
4
public long getCompanyId() { return companyId; }
0
public boolean savePhpbbUser(String user) throws SQLException, ClassNotFoundException { sqlClass(); sqlCon(); if (!customField.isEmpty()) { query = "SELECT user_id FROM " + tablePref + "profile_fields_data WHERE pf_" + customField + "='" + user + "'"; ResultSet rs = SELECT(query); if (rs.next()) { query = "UPDATE " + tablePref + "users SET user_type='0', user_actkey='', user_inactive_time='0' WHERE user_id=" + rs.getInt("user_id"); UPDATE(query); query = "SELECT * FROM " + tablePref + "users WHERE user_id='" + rs.getInt("user_id") + "'"; rs = SELECT(query); if (rs.next()) { plugin.sendInfo(ForumAA.server.getPlayer(user), "Activated account for " + rs.getString("username")); updateStats(rs.getInt("user_id"), rs.getString("username"), rs.getString("user_colour"), rs.getInt("group_id")); closeCon(); return true; } else { plugin.sendInfo(ForumAA.server.getPlayer(user), "Account activated but could not update Stats"); return true; } } else { plugin.sendError(ForumAA.server.getPlayer(user), "Username could not be found"); return false; } } else { // Update main users table query = "UPDATE " + tablePref + "users SET user_type='0', user_actkey='', user_inactive_time='0' WHERE username_clean='" + user.toLowerCase() + "'"; UPDATE(query); query = "SELECT * FROM " + tablePref + "users WHERE user_type='0' ORDER BY user_regdate DESC LIMIT 1"; ResultSet rs = SELECT(query); if (rs.next()) { plugin.sendInfo(ForumAA.server.getPlayer(user), "Activated account for " + rs.getString("username")); updateStats(rs.getInt("user_id"), rs.getString("username"), rs.getString("user_colour"), rs.getInt("group_id")); closeCon(); return true; } else { plugin.sendInfo(ForumAA.server.getPlayer(user), "Account activated but could not update Stats"); closeCon(); return true; } } }
4
@Override public void deserialize(Buffer buf) { super.deserialize(buf); position = buf.readUByte(); if (position < 63 || position > 255) throw new RuntimeException("Forbidden value on position = " + position + ", it doesn't respect the following condition : position < 63 || position > 255"); spellId = buf.readInt(); spellLevel = buf.readByte(); if (spellLevel < 1 || spellLevel > 6) throw new RuntimeException("Forbidden value on spellLevel = " + spellLevel + ", it doesn't respect the following condition : spellLevel < 1 || spellLevel > 6"); }
4
@Test public void testServerClientConnectWithMessageQueue() { LOGGER.log(Level.INFO, "----- STARTING TEST testServerClientConnectWithMessageQueue -----"); String server_hash = ""; String client_hash = ""; try { server1.setUseMessageQueues(true); } catch (TimeoutException e) { exception = true; } try { server2.setUseMessageQueues(true); } catch (TimeoutException e) { exception = true; } try { server1.startThread(); } catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) { exception = true; } waitListenThreadStart(server1); try { client_hash = server2.addSocket("127.0.0.1", port); } catch (IOException | TimeoutException e) { exception = true; } waitSocketThreadAddNotEmpty(server2); waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED); waitSocketThreadAddNotEmpty(server1); server_hash = getServerLastSocketHash(server1); waitSocketThreadState(server1, server_hash, SocketThread.CONFIRMED); waitMessageQueueAddNotEmpty(server2); waitMessageQueueState(server2, client_hash, MessageQueue.RUNNING); waitMessageQueueAddNotEmpty(server1); waitMessageQueueState(server1, server_hash, MessageQueue.RUNNING); Assert.assertFalse(exception, "Exception found"); LOGGER.log(Level.INFO, "----- TEST testServerClientConnectWithMessageQueue COMPLETED -----"); }
4
public float getY(float x) { return a * x * x + b * x + c; }
0
public void rotate() { switch(getDirection()) { case "up": setDirection("right"); break; case "right": setDirection("down"); break; case "down": setDirection("left"); break; case "left": setDirection("up"); break; default: System.out.println("rotate() is bugged"); } }
4
public boolean equalsExpr(final Expr other) { return (other != null) && (other instanceof ArrayLengthExpr) && ((ArrayLengthExpr) other).array.equalsExpr(array); }
2
public static BufferedImage getImage(final String name, final String URL, final String format) { final File file = new File(Environment.getStorageDirectory(), name); try { if (!file.exists()) { final BufferedImage image = ImageIO.read(new java.net.URL(URL)); ImageIO.write(image, format, file); return image; } else return ImageIO.read(file); } catch (IOException e) { e.printStackTrace(); } return null; }
2
public static double[] lsolve(double[][] A, double[] b) { int N = b.length; for (int p = 0; p < N; p++) { // find pivot row and swap int max = p; for (int i = p + 1; i < N; i++) { if (Math.abs(A[i][p]) > Math.abs(A[max][p])) { max = i; } } double[] temp = A[p]; A[p] = A[max]; A[max] = temp; double t = b[p]; b[p] = b[max]; b[max] = t; // singular or nearly singular if (Math.abs(A[p][p]) <= EPSILON) { throw new RuntimeException("Matrix is singular or nearly singular"); } // pivot within A and b for (int i = p + 1; i < N; i++) { double alpha = A[i][p] / A[p][p]; b[i] -= alpha * b[p]; for (int j = p; j < N; j++) { A[i][j] -= alpha * A[p][j]; } } } // back substitution double[] x = new double[N]; for (int i = N - 1; i >= 0; i--) { double sum = 0.0; for (int j = i + 1; j < N; j++) { sum += A[i][j] * x[j]; } x[i] = (b[i] - sum) / A[i][i]; } return x; }
8
private boolean isUrl(String url) { String regex = "((([A-Za-z]{3,9}:(?://)?)(?:[\\-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9\\.\\-]+|(?:www\\.|[\\-;:&=\\+\\$,\\w]+@)[A-Za-z0-9\\.\\-]+)((?:/[\\+~%/\\.\\w\\-_]*)?\\??(?:[\\-\\+=&;%@\\.\\w_]*)#?(?:[\\.\\!/\\\\\\w]*))?)"; if (Pattern.compile(regex).matcher(url).find()) return true; for (String s : endings) { if (url.contains(s)) return true; } return false; }
3
public static void taytaLomakkeenTiedot(JPanel lomake, EnumMap<Kentta, String> kentat) { EnumMap<Kentta, String> lomakkeenSisalto = new EnumMap(Kentta.class); Component[] komponentit = lomake.getComponents(); //näihin tallenetaan kirjalomakkeen comoboxissa valittu kenttä ja comboboxin nimi, jotta //voidaan yhdistää ne oikeaan tekstikenttään Kentta valittuKentta = null; String kirjaCombonNimi = ""; for (Component komponentti : komponentit) { if (komponentti instanceof JComboBox) { //kirjan lomakkeessa on combobox, jossa valittuna editor tai author JComboBox authorEditor = (JComboBox) komponentti; if (kentat.containsKey(Kentta.editor)) { authorEditor.setSelectedItem(Kentta.editor); } else { authorEditor.setSelectedItem(Kentta.author); } } if (komponentti instanceof JTextArea) { String nimi = komponentti.getName(); JTextArea tekstikentta = (JTextArea) komponentti; //Kirjan erikoistapaus authorille ja editorille if (nimi.equals("kirja")) { String authorOrEditor = kentat.get(Kentta.author); if (authorOrEditor == null) authorOrEditor = kentat.get(Kentta.editor); tekstikentta.setText(authorOrEditor); } else { //Etsitään tekstikenttää vastaava kenttä for (Kentta kentta : Kentta.values()) { if (kentta.toString().equals(nimi) && kentat.containsKey(kentta)) tekstikentta.setText(kentat.get(kentta)); } } } } }
9
@Override public void run() { while(true){ synchronized(thread){ try { JixelGame.setPaused(false); thread.wait(); } catch (InterruptedException e) { printErr("Console thread interrupted", e); } } while (isRunning) { JixelGame.setPaused(true); if (!JixelGame.getKeyInput().isReading()) { String msg = getConsoleMsg(); if (!msg.isEmpty()) { String[] commands = msg.split(" "); cInput(commands); } startConsoleMsg((MAX_WIDTH>>3)-1); } } } }
5
private void update(){ if(isFullScreen != SettingsModel.getFullscreen()) { if (SettingsModel.getFullscreen()){ this.fullScreen(); } else { this.windowed(); } this.setLocationRelativeTo(null); this.setVisible(true); this.isFullScreen = SettingsModel.getFullscreen(); } }
2
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("rowset")) { if (currentAsset != null) { stack.add(currentAsset); currentAsset = null; } } if (qName.equals("row")) { currentAsset = new EveAsset<EveAsset<?>>(); currentAsset.setItemID(getLong(attrs, "itemID")); currentAsset.setLocationID(getLong(attrs, "locationID")); currentAsset.setTypeID(getInt(attrs, "typeID")); currentAsset.setQuantity(getInt(attrs, "quantity")); currentAsset.setFlag(getInt(attrs, "flag")); currentAsset.setSingleton(getBoolean(attrs, "singleton")); currentAsset.setRawQuantity(getInt(attrs, "rawQuantity")); if (!stack.isEmpty()) { EveAsset<EveAsset<?>> peek = stack.peek(); peek.addAsset(currentAsset); } } super.startElement(uri, localName, qName, attrs); accumulator.setLength(0); }
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(LanzamientoDado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LanzamientoDado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LanzamientoDado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LanzamientoDado.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 LanzamientoDado().setVisible(true); } }); }
6
public SchlangenGlied getFirstGlied() { if (previousGlied != null) { return previousGlied.getFirstGlied(); } else { return this; } }
1
public void execute(){ Command commande = commandeCourante.commande; commande.execute(); //Actualisation du modèle puis de la vue. if(commande instanceof LirePlanCommand ){ zone = ((LirePlanCommand)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof LireLivraisonsCommand){ zone = ((LireLivraisonsCommand)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if (commande instanceof AjoutLivraisonCommande){ zone = ((AjoutLivraisonCommande)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof SuppressionLivraisonCommande){ zone = ((SuppressionLivraisonCommande)commande).getZone(); Fenetre.getInstance().actualiserPlan(); } else if(commande instanceof CalculerTourneeCommand){ zone.getTournee().setCheminsResultats(((CalculerTourneeCommand)commande).getChemins()); Fenetre.getInstance().actualiserPlan(); } }
5
public static void main(String [] args) { // Skapar ett TrafficSystem // Utfor stegningen, anropar utskriftsmetoder Random randomized = new Random(); Scanner sc = new Scanner(System.in); System.out.println("The length of the car lanes will be randomized, but the user will set the range."); System.out.println("Choose the maximum length of the lanes: "); int l1 = sc.nextInt(); if (l1 < 2) {throw new RuntimeException("Length must be bigger than 1.");} int lengthmax = l1; System.out.println("Choose the minimum length of the lanes: (If higher than max it will be set to equal)"); int l2 = sc.nextInt(); if(l2 < 2) {throw new RuntimeException("Length must be bigger than 1.");} int lengthmin = l2; if(lengthmin > lengthmax) { lengthmin = lengthmax; } System.out.println("Choose the period of the lights: "); int p1 = sc.nextInt(); if (p1 < 1) {throw new RuntimeException("Period must be higher than 0");} int period = p1; System.out.println("Choose the arrival intensity of the cars (3 means 1/3 chance for a car to enter) :"); int aI = sc.nextInt(); if (aI < 1) {throw new RuntimeException("Intensity can be max 1, come on. One each second.");} int arrivalIntensity = aI; System.out.println("The destination, and arrival intensity, of the cars will be randomized."); System.out.println("How long do you wish to watch the simulation?: "); int d1 = sc.nextInt(); if (d1 < 5) {throw new RuntimeException("Come on, watch atleast 5 seconds.");} int duration = d1; int length1 = (randomized.nextInt(lengthmax) + lengthmin); int length2 = (randomized.nextInt(lengthmax) + lengthmin); TrafficSystem traffSys = new TrafficSystem(length1, length2, period, period/2, arrivalIntensity); for (int i = 0; i < duration; ++i) { traffSys.readParameters(); try { Thread.sleep(450); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } traffSys.print(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n"); traffSys.step(); } traffSys.print(); traffSys.printStatistics(); }
8
public static void trimBranch(Branch branch) { // This does not normalize whitespace! // The document tree is modified in place, but no nodes are removed. if (trimmed.get(branch) != null) return; trimmed.put(branch, branch); List content = branch.content(); // trim leading whitespace // NB: dom4j can have multiple consecutive Text nodes boolean first = true; for (int i = 0, n = content.size(); i < n; i++) { Object obj = content.get(i); if (obj instanceof Text) { Text text = (Text) obj; if (first) { String s = trimLeading(text.getText()); text.setText(s); if (s.length() > 0) first = false; } } else { first = false; if (obj instanceof Branch) trimBranch((Branch) obj); } } // trim trailing whitespace for (int i = content.size()-1; i >= 0; i--) { Object obj = content.get(i); if (obj instanceof Text) { Text text = (Text) obj; String s = trimTrailing(text.getText()); text.setText(s); if (s.length() > 0) break; } else break; } }
9
public String toString(){ String str = "if(" + condition.toString() + "){" + truePart.toString() + "}"; if(falsePart != null) str+="else{" + falsePart.toString() + "}"; return str; }
1