text
stringlengths
14
410k
label
int32
0
9
protected boolean computeCell(int col, int row) { boolean liveCell = getCell(col, row); int neighbours = countNeighbours(col, row); boolean nextCell = false; if (neighbours < 2) nextCell = false; if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true; if (liveCell && neighbours > 3) nextCell = false; if (!liveCell && neighbours == 3) nextCell = true; return nextCell; }
8
public static ArrayList<bConsultaCompo> getPesquisaCompo(String prod, String data_in) throws SQLException, ClassNotFoundException { ArrayList<bConsultaCompo> sts = new ArrayList<bConsultaCompo>(); Connection conPol = conMgr.getConnection("PD"); ResultSet rs; if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("{call sp_consulta_componemte(?,?)}"); call.setString(1, prod); call.setString(2, data_in); rs = call.executeQuery(); while (rs.next()) { bConsultaCompo reg = new bConsultaCompo(); reg.setCont(rs.getInt("f1")); reg.setCod_prod(rs.getString("f2")); reg.setStr_compo(rs.getString("f3")); reg.setDescricao1(rs.getString("f4")); sts.add(reg); } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
3
public String getEndConditionSummary() { StringBuilder sb = new StringBuilder("This game ends when; "); int i = 0; if(nrOfFlips > 0) { if(i++ > 0) sb.append(" or "); sb.append("the mode has flipped from building to battle: ").append(nrOfFlips).append(" times"); } if(winningScore > 0) { if(i++ > 0) sb.append(" or "); sb.append("a team reaches a score of: ").append(winningScore); } if(maxScore > 0) { if(i > 0) sb.append(" or "); sb.append("the maximum score among the teams are: ").append(maxScore); } if(maxSeconds > 0) { if(i > 0) sb.append(" or "); sb.append("the play time reaches: ").append(maxSeconds).append(" seconds"); } return sb.toString(); }
8
public State hasChosenCharactersState() { return hasChosenCharactersState; }
0
public static String saveDirectory() { try(BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { prop.load(reader); return prop.getProperty("saveDirectory"); } catch (IOException ex) { try { PropHandle.reset(); BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); prop.load(reader); return prop.getProperty("saveDirectory"); } catch (FileNotFoundException ex1) { Logger.getLogger(ConfSetter.class.getName()).log(Level.SEVERE, null, ex1); throw new RuntimeException(); } catch (IOException ex1) { Logger.getLogger(ConfSetter.class.getName()).log(Level.SEVERE, null, ex1); throw new RuntimeException(); } } }
3
public void draw(Bitmap render, int xOffset, int yOffset) { for(int y = 0; y < render.height; y++) { int yPix = y + yOffset; if (yPix < 0 || yPix >= height) continue; for(int x = 0; x < render.width; x++) { int xPix = x + xOffset; if (xPix < 0 || xPix >= width) continue; int alpha = render.pixels[x + y * render.width]; pixels[xPix + yPix * width] = alpha; } } }
6
public static void main(String[] args){ DecimalFormat df = new DecimalFormat("0.0#Hz"); String str; Note myNote = new Note(); System.out.println("Note Length :"+myNote.getLength()); System.out.println("Note Value :" + myNote.getValue()); if(myNote.isNatural()) str = myNote.noteLetter() + " note is Natural"; else str = myNote.noteLetter() + " note is Sharp"; System.out.println(str); System.out.println(myNote.noteLetter() + " note frequency :" + df.format(myNote.noteFrequency())); System.out.println(myNote.toString()); System.out.println("\n--Setting new note length and value--\n"); myNote.setLength(1.0/16.0); myNote.setValue(-6); System.out.println("Note Length :"+myNote.getLength()); System.out.println("Note Value :" + myNote.getValue()); if(myNote.isNatural()) str = myNote.noteLetter() + " note is Natural"; else str = myNote.noteLetter() + " note is Sharp"; System.out.println(str); System.out.println(myNote.noteLetter() + " note frequency :" + df.format(myNote.noteFrequency())); System.out.println(myNote.toString()); System.out.println("\n--Creating new note!--\n"); Note myNote2 = new Note(-7,1); System.out.println("Note Length :"+myNote2.getLength()); System.out.println("Note Value :" + myNote2.getValue()); if(myNote2.isNatural()) str = myNote2.noteLetter() + " note is Natural"; else str = myNote2.noteLetter() + " note is Sharp"; System.out.println(str); System.out.println(myNote2.noteLetter() + " note frequency :" + df.format(myNote2.noteFrequency())); System.out.println(myNote2.toString()); }
3
public void setAvalie(PExpLogica node) { if(this._avalie_ != null) { this._avalie_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._avalie_ = node; }
3
public void poistaPalaute(Palaute p) throws DAOPoikkeus { try { PalauteDAO pDao = new PalauteDAO(); pDao.poistaPalaute(p.getPalauteID()); } catch (DAOPoikkeus po) { throw new DAOPoikkeus("Tietokannasta poistaminen ei onnistunut", po); } }
1
public void joinUserInChannel(ChatChannel chatChannel, User user){ try{ Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:" + DBName; Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement(); String selectUserFromChannel = "SELECT * FROM USERCHATRELATIONS WHERE userID =" + user.getID() + " " + "AND channelID = " + chatChannel.getChannelID(); ResultSet rs = statement.executeQuery(selectUserFromChannel); if(!rs.next()){ String joinUserInChannelUpdate = "INSERT INTO USERCHATRELATIONS (userID, channelID, relationshiptype) " + "VALUES (" + user.getID() + ", " + chatChannel.getChannelID() +", (SELECT ucrtID FROM UserChannelRelationshipTypes WHERE rtype = 'online' ))"; statement.executeUpdate(joinUserInChannelUpdate); } statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } }
2
public void setUp() { // Get questions List<Question> allQuestions = DbAccess.getAllQuestions(false); // creates values for size of list QuestionCount = allQuestions.size(); if(QuestionCount == 0) { // Set Values QuestionText_txtbx.setText("No questions to validate"); Answer1_txtbx.setText("N/A"); Answer2_txtbx.setText("N/A"); Answer3_txtbx.setText("N/A"); Answer4_txtbx.setText("N/A"); // set buttons and text boxes disabled Next_btn.setEnabled(false); Previous_btn.setEnabled(false); Submit_btn.setEnabled(false); Approve_btn.setEnabled(false); Reject_btn.setEnabled(false); Edit_btn.setEnabled(false); QuestionText_txtbx.setEnabled(false); Answer1_txtbx.setEnabled(false); Answer2_txtbx.setEnabled(false); Answer3_txtbx.setEnabled(false); Answer4_txtbx.setEnabled(false); Answer1_rdbtn.setEnabled(false); Answer2_rdbtn.setEnabled(false); Answer3_rdbtn.setEnabled(false); Answer4_rdbtn.setEnabled(false); // Message box pop up to say please select correct answer JOptionPane.showMessageDialog(null,"There are no more questions to validate.", "No Questions to Validate",JOptionPane.WARNING_MESSAGE); } else { Question s = new Question(); s = allQuestions.get(i); List<Answer> sanswers = s.answers; // Assign values from the question to the variables questionText = s.questionText; QuestionDbId = s.dbId; Answer1Text = sanswers.get(0).answerText; Answer1Correct = sanswers.get(0).isCorrect; Answer1DbId = sanswers.get(0).dbId; Answer2Text = sanswers.get(1).answerText; Answer2Correct = sanswers.get(1).isCorrect; Answer2DbId = sanswers.get(1).dbId; Answer3Text = sanswers.get(2).answerText; Answer3Correct = sanswers.get(2).isCorrect; Answer3DbId = sanswers.get(2).dbId; Answer4Text = sanswers.get(3).answerText; Answer4Correct = sanswers.get(3).isCorrect; Answer4DbId = sanswers.get(3).dbId; // Display question and answer text QuestionText_txtbx.setText(questionText); Answer1_txtbx.setText(Answer1Text); Answer2_txtbx.setText(Answer2Text); Answer3_txtbx.setText(Answer3Text); Answer4_txtbx.setText(Answer4Text); // Set Correct Answer Radio buttons Answer1_rdbtn.setSelected(Answer1Correct); Answer2_rdbtn.setSelected(Answer2Correct); Answer3_rdbtn.setSelected(Answer3Correct); Answer4_rdbtn.setSelected(Answer4Correct); // Set Text Boxes to stop editing unless edit button is clicked QuestionText_txtbx.setEnabled(false); Answer1_txtbx.setEnabled(false); Answer2_txtbx.setEnabled(false); Answer3_txtbx.setEnabled(false); Answer4_txtbx.setEnabled(false); // Set radio buttons to stop editing unless edit button is clicked Answer1_rdbtn.setEnabled(false); Answer2_rdbtn.setEnabled(false); Answer3_rdbtn.setEnabled(false); Answer4_rdbtn.setEnabled(false); // Set Submit button as disabled to be changed when Edit_btn is clicked Submit_btn.setEnabled(false); if(QuestionCount == 1) { // set Next and Previous button disabled Next_btn.setEnabled(false); Previous_btn.setEnabled(false); } } }
2
public static Jeu creerJeu(Utilisateur utilisateur, String nom, String description, byte[] icone, String iconeType) throws ChampInvalideException, ChampVideException{ if (utilisateur.getRole().getValeur() < Role.Utilisateur.getValeur()) throw new InterditException("Vous devez être connecté pour créer un jeu"); EntityTransaction transaction = JeuRepo.get().transaction(); Jeu j; try { transaction.begin(); Fichier f = null; if (icone != null && iconeType != null) f = FichierService.genererIcone(icone, iconeType); j = genererJeu(utilisateur, nom, description, f); JeuRepo.get().creer(j); transaction.commit(); } catch(Exception e) { if (transaction.isActive()) transaction.rollback(); if (e instanceof ChampVideException) throw (ChampVideException)e; else if (e instanceof ChampInvalideException) throw (ChampInvalideException)e; else throw (RuntimeException)e; } return j; }
7
public void setCallgraphAlgorithm(CallgraphAlgorithm algorithm) { this.callgraphAlgorithm = algorithm; }
0
void menuLoad() { animate = false; // stop any animation in progress // Get the user to choose an image file. FileDialog fileChooser = new FileDialog(shell, SWT.OPEN); if (lastPath != null) fileChooser.setFilterPath(lastPath); fileChooser.setFilterExtensions(OPEN_FILTER_EXTENSIONS); fileChooser.setFilterNames(OPEN_FILTER_NAMES); String filename = fileChooser.open(); lastPath = fileChooser.getFilterPath(); if (filename == null) return; Cursor waitCursor = display.getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); imageCanvas.setCursor(waitCursor); try { // Read the new image from the chosen file. long startTime = System.currentTimeMillis(); Image newImage = new Image(display, filename); loadTime = System.currentTimeMillis() - startTime; // don't include getImageData in load time imageData = newImage.getImageData(); // Cache the filename. currentName = filename; fileName = filename; // Fill in array and loader data. loader = new ImageLoader(); imageDataArray = new ImageData[] {imageData}; loader.data = imageDataArray; // Display the image. imageDataIndex = 0; displayImage(imageData); } catch (SWTException e) { showErrorDialog(bundle.getString("Loading_lc"), filename, e); } catch (SWTError e) { showErrorDialog(bundle.getString("Loading_lc"), filename, e); } catch (OutOfMemoryError e) { showErrorDialog(bundle.getString("Loading_lc"), filename, e); } finally { shell.setCursor(null); imageCanvas.setCursor(crossCursor); } }
5
@Override public String lookup(String question) { // Tjek om der er valgt et spil if (currentgame == null) { return null; } // Find spørgsmål for (int i = 0; i < currentgame.getQuestions().size(); i++) { if (currentgame.getQuestions().get(i).getQuestion().equals(question)) { String english = currentgame.getQuestions().get(i).getAnswer(); return english; } } return null; }
3
public void pickUpItem() { float eps = (float) 1e-01; float n = player.getTaille(); if((Math.abs(player.getY() - getY()) - (getHeight()/2 + player.getTaille()/2)) <eps){ float x_gauche = player.getX() - n / 2; float x_droite = player.getX() + n / 2; float p_gauche = getX() - getWidth() / 2; float p_droite = getX() + getWidth() / 2; if ((x_droite <= p_droite && x_droite >= p_gauche) || (x_gauche <= p_droite && x_gauche >= p_gauche)) { used = effect(player); if (used) world.remove(getBody()); } } }
6
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Prioridade)) { return false; } Prioridade other = (Prioridade) object; if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.id.equals(other.id))) { return false; } return true; }
5
static final boolean method2935(byte b, int i, int i_0_) { anInt7520++; if (i_0_ >= 1000 && (i ^ 0xffffffff) > -1001) { return true; } if (i_0_ < 1000 && (i ^ 0xffffffff) > -1001) { if (Node_Sub27.method2699(18, i)) { return true; } if (Node_Sub27.method2699(18, i_0_)) { return false; } return true; } if (i_0_ >= 1000 && (i ^ 0xffffffff) <= -1001) { return true; } if (b != 69) { method2934(85); } return false; }
9
public boolean isSamePath(Room r1, Room r2) { if (r1.getCenterX() == start.x && r1.getCenterY() == start.y) { if (r2.getCenterX() == end.x && r2.getCenterY() == end.y) return true; } else if (r2.getCenterX() == start.x && r2.getCenterY() == start.y) { if (r1.getCenterX() == end.x && r1.getCenterY() == end.y) return true; } return false; }
8
public static Date strtotime(String input) { if (input.startsWith("[") || input.startsWith("\"")) { input = Functions.substr(input,1); } if (input.endsWith("[") || input.startsWith("\"")) { input = Functions.substr(input,0,-1); } for (Matcher matcher : matchers) { Date date = matcher.tryConvert(input); if (date != null) { return date; } } return null; }
6
public static void main(String[] args) { ArgParserTest test = new ArgParserTest(); ArgHolder<Boolean> bh = new ArgHolder<Boolean>(Boolean.class); boolean[] b3 = new boolean[3]; ArgHolder<Character> ch = new ArgHolder<Character>(Character.class); char[] c3 = new char[3]; ArgHolder<Integer> ih = new ArgHolder<Integer>(Integer.class); int[] i3 = new int[3]; ArgHolder<Long> lh = new ArgHolder<Long>(Long.class); long[] l3 = new long[3]; ArgHolder<Float> fh = new ArgHolder<Float>(Float.class); float[] f3 = new float[3]; ArgHolder<Double> dh = new ArgHolder<Double>(Double.class); double[] d3 = new double[3]; ArgHolder<String> sh = new ArgHolder<String>(String.class); String[] s3 = new String[3]; test.checkAdd("-foo %i{[0,10)}X3 #sets the value of foo", // 0123456789012345 i3, 'i', 3, new String[] { "-foo " }, new RngCheck[] { new RngCheck(0, CLOSED, 10, OPEN) }, "sets the value of foo", null); test.checkAdd("-arg1,,", null, "Null option name given"); test.checkAdd("-arg1,,goo %f ", null, "Null option name given"); test.checkAdd(" ", null, "Null option name given"); test.checkAdd("", null, "Null option name given"); test.checkAdd(" %v", null, "Null option name given"); test.checkAdd("-foo ", null, "No conversion character given"); test.checkAdd("-foo %", null, "No conversion character given"); test.checkAdd("foo, aaa bbb ", null, "Names not separated by ','"); test.checkAdd(" foo aaa %d", null, "Names not separated by ','"); test.checkAdd("-arg1,-b,", null, "Null option name given"); test.checkAdd("-arg1,-b", null, "No conversion character given"); test.checkAdd("-arg1 ", null, "No conversion character given"); test.checkAdd("-arg1, %v", null, "Null option name given"); test.checkAdd("-arg1,%v", null, "Null option name given"); test.checkAdd("-foo %V", null, "Conversion code 'V' not one of 'iodxcbfsvh'"); test.checkAdd("-h %hX5", null, "Multipliers not supported for %h"); test.checkAdd("-h %h{}", null, "Ranges not supported for %h"); test.checkAdd("-help, -h %h #here is how we help you", null, 'h', 1, new String[] { "-help ", "-h " }, null, "here is how we help you", null); test.checkAdd("-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test", l3, 'd', 1, new String[] { "-arg1 ", "-arg2=" }, new RngCheck[] { new RngCheck(0), new RngCheck(3), new RngCheck(7, OPEN, 16, CLOSED), }, "x3 test", null); test.checkAdd("bbb,ccc%x{[1,2]} #X3 x3 test", l3, 'x', 1, new String[] { "bbb", "ccc" }, new RngCheck[] { new RngCheck(1, CLOSED, 2, CLOSED), }, "X3 x3 test", null); test.checkAdd(" bbb ,ccc, ddd ,e , f=%bX1 #x3 test", b3, 'b', 1, new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" }, null, "x3 test", null); test.checkAdd(" bbb ,ccc, ddd ,e , f= %bX3 #x3 test", b3, 'b', 3, new String[] { "bbb ", "ccc ", "ddd ", "e ", "f= " }, null, "x3 test", null); test.checkAdd("-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar", sh, 's', 1, new String[] { "-b ", "--bar " }, new RngCheck[] { new RngCheck("jerry", OPEN, "john", CLOSED), new RngCheck("fred"), new RngCheck("harry") }, "sets bar", null); test.checkAdd("-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ", dh, 'f', 1, new String[] { "-c ", "coven" }, new RngCheck[] { new RngCheck(0.0), new RngCheck(9.0), new RngCheck(5.0, CLOSED, 6.0, OPEN), new RngCheck(-9.1, CLOSED, 10.2, CLOSED) }, "", null); test.checkAdd("-b %b #a boolean value ", bh, 'b', 1, new String[] { "-b " }, new RngCheck[] {}, "a boolean value ", null); test.checkAdd("-a %i", ih, 'i', 1, "-a ", null, "", null); test.checkAdd("-a %o", lh, 'o', 1, "-a ", null, "", null); test.checkAdd("-a %d", i3, 'd', 1, "-a ", null, "", null); test.checkAdd("-a %x", l3, 'x', 1, "-a ", null, "", null); test.checkAdd("-a %c", ch, 'c', 1, "-a ", null, "", null); test.checkAdd("-a %c", c3, 'c', 1, "-a ", null, "", null); test.checkAdd("-a %v", bh, 'v', 1, "-a ", null, "", null); test.checkAdd("-a %b", b3, 'b', 1, "-a ", null, "", null); test.checkAdd("-a %f", fh, 'f', 1, "-a ", null, "", null); test.checkAdd("-a %f", f3, 'f', 1, "-a ", null, "", null); test.checkAdd("-a %f", dh, 'f', 1, "-a ", null, "", null); test.checkAdd("-a %f", d3, 'f', 1, "-a ", null, "", null); test.checkAdd("-a %i", fh, 'i', 1, "-a ", null, "", "Invalid result holder for %i"); test.checkAdd("-a %c", i3, 'c', 1, "-a ", null, "", "Invalid result holder for %c"); test.checkAdd("-a %v", d3, 'v', 1, "-a ", null, "", "Invalid result holder for %v"); test.checkAdd("-a %f", sh, 'f', 1, "-a ", null, "", "Invalid result holder for %f"); test.checkAdd("-a %s", l3, 's', 1, "-a ", null, "", "Invalid result holder for %s"); test.checkAdd("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null); test.checkAdd("-foo%i{}", ih, 'i', 1, "-foo", null, "", null); test.checkAdd("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null); test.checkAdd("-foo%i{ }}", ih, "Illegal character(s), expecting '#'"); test.checkAdd("-foo%i{ ", ih, "Unterminated range specification"); test.checkAdd("-foo%i{", ih, "Unterminated range specification"); test.checkAdd("-foo%i{0,9", ih, "Unterminated range specification"); test.checkAdd("-foo%i{1,2,3)", ih, "Unterminated range specification"); test.checkAdd("-b %f{0.9}", fh, 'f', 1, "-b ", new RngCheck[] { new RngCheck(0.9) }, "", null); test.checkAdd("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ", new RngCheck[] { new RngCheck(0.9), new RngCheck(7.0), new RngCheck(-0.5), new RngCheck(-4.0), new RngCheck(6.0) }, "", null); test.checkAdd("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }", fh, 'f', 1, "-b ", new RngCheck[] { new RngCheck(0.9, CLOSED, 7.0, OPEN), new RngCheck(-4.0, OPEN, -.5, OPEN), new RngCheck(6.0, CLOSED, 9.0, CLOSED), new RngCheck(10.0, OPEN, 13.4, CLOSED), }, "", null); test.checkAdd("-b %f{(8 9]}", fh, "Missing ',' in subrange specification"); test.checkAdd("-b %f{(8,9,]}", fh, "Unterminated subrange"); test.checkAdd("-b %f{(8,9 ,]}", fh, "Unterminated subrange"); test.checkAdd("-b %f{(8,9 8]}", fh, "Unterminated subrange"); test.checkAdd("-b %f{8 9}", fh, "Range spec: ',' or '}' expected"); test.checkAdd("-b %f{8 *}", fh, "Range spec: ',' or '}' expected"); test.checkAdd("-b %f{8y}", fh, "Range spec: ',' or '}' expected"); test.checkAdd("-b %f{.}", fh, "Malformed float '.}' in range spec"); test.checkAdd("-b %f{1.0e}", fh, "Malformed float '1.0e}' in range spec"); test.checkAdd("-b %f{[*]}", fh, "Malformed float '*' in range spec"); test.checkAdd("-b %f{1.2e5t}", fh, "Range spec: ',' or '}' expected"); test.checkAdd("-b %i{8}", ih, 'i', 1, "-b ", new RngCheck[] { new RngCheck( 8) }, "", null); test.checkAdd("-b %i{8, 9,10 }", ih, 'i', 1, "-b ", new RngCheck[] { new RngCheck(8), new RngCheck(9), new RngCheck(10) }, "", null); test.checkAdd( "-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }", ih, 'i', 1, "-b ", new RngCheck[] { new RngCheck(8), new RngCheck(-9, CLOSED, 10, OPEN), new RngCheck(-17, CLOSED, 15, CLOSED), new RngCheck(-33, OPEN, 2, OPEN), new RngCheck(8, OPEN, 9, CLOSED), }, "", null); test.checkAdd("-b %i{8.7}", ih, "Range spec: ',' or '}' expected"); test.checkAdd("-b %i{6,[*]}", ih, "Malformed integer '*' in range spec"); test.checkAdd("-b %i{g76}", ih, "Malformed integer 'g' in range spec"); test.checkAdd("-b %s{foobar}", sh, 's', 1, "-b ", new RngCheck[] { new RngCheck("foobar") }, "", null); test.checkAdd("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ", new RngCheck[] { new RngCheck("foobar"), new RngCheck("0x233"), new RngCheck(" ") }, "", null); test.checkAdd("-b %s{foobar,(bb,aa], [\"01\",02]}", sh, 's', 1, "-b ", new RngCheck[] { new RngCheck("foobar"), new RngCheck("aa", CLOSED, "bb", OPEN), new RngCheck("01", CLOSED, "02", CLOSED), }, "", null); test.checkAdd("-b %c{'a'}", ch, 'c', 1, "-b ", new RngCheck[] { new RngCheck('a') }, "", null); test.checkAdd("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ", new RngCheck[] { new RngCheck('\n'), new RngCheck('\002'), new RngCheck('B') }, "", null); test.checkAdd("-b %c{'q',('g','a'], ['\t','\\003']}", ch, 'c', 1, "-b ", new RngCheck[] { new RngCheck('q'), new RngCheck('a', CLOSED, 'g', OPEN), new RngCheck('\003', CLOSED, '\t', CLOSED), }, "", null); test.checkAdd("-b %b{true}X2", b3, 'b', 2, "-b ", new RngCheck[] { new RngCheck(true) }, "", null); test.checkAdd("-b %b{ true , false, true }", bh, 'b', 1, "-b ", new RngCheck[] { new RngCheck(true), new RngCheck(false), new RngCheck(true) }, "", null); test.checkAdd("-b %v{true,[true,false)}", bh, "Sub ranges not supported for %b or %v"); test.checkAdd("-b %v{true,[]}", bh, "Sub ranges not supported for %b or %v"); test.checkAdd("-b %b{tru}", bh, "Malformed boolean 'tru}' in range spec"); test.checkAdd("-b %iX2", i3, 'i', 2, "-b ", null, "", null); test.checkAdd("-b %vX3", b3, 'v', 3, "-b ", null, "", null); test.checkAdd("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null); test.checkAdd("-b=%iX2", i3, 'i', 2, "-b", null, "", "Multiplier value incompatible with one word option -b="); test.checkAdd("-b %iX0", i3, 'i', 0, "-b ", null, "", "Value multiplier number must be > 0"); test.checkAdd("-b %iX-6", i3, 'i', 0, "-b ", null, "", "Value multiplier number must be > 0"); test.checkAdd("-b %iXy", i3, 'i', 0, "-b ", null, "", "Malformed value multiplier"); test.checkAdd("-b %iX4", i3, 'i', 4, "-b ", null, "", "Result holder array must have a length >= 4"); test.checkAdd("-b %iX4", ih, 'i', 4, "-b ", null, "", "Multiplier requires result holder to be an array of length >= 4"); test.checkAdd("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null); test.checkAdd("-b %i #[}X4", ih, 'i', 1, "-b ", null, "[}X4", null); // test.checkPrintHelp(""); // test.checkPrintUsage(""); test = new ArgParserTest(); test.checkAdd( "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg", ih, 'i', 1, "-intarg ", new RngCheck[] { new RngCheck(1), new RngCheck(2), new RngCheck(9, OPEN, 18, CLOSED), new RngCheck(22, CLOSED, 27, CLOSED), new RngCheck(33, CLOSED, 38, OPEN), new RngCheck(45, OPEN, 48, OPEN), }, "test int arg", null); MTest[] tests; tests = new MTest[] { new MTest("-intarg 1", new Long(1)), new MTest("-intarg 3", new MErr('r', "3")), new MTest("-intarg 9", new MErr('r', "9")), new MTest("-intarg 11", new Long(11)), new MTest("-intarg 18", new Long(18)), new MTest("-intarg 22", new Long(22)), new MTest("-intarg 25", new Long(25)), new MTest("-intarg 27", new Long(27)), new MTest("-intarg 33", new Long(33)), new MTest("-intarg 35", new Long(35)), new MTest("-intarg 38", new MErr('r', "38")), new MTest("-intarg 45", new MErr('r', "45")), new MTest("-intarg 46", new Long(46)), new MTest("-intarg 48", new MErr('r', "48")), new MTest("-intarg 100", new MErr('r', "100")), new MTest("-intarg 0xbeef", new MErr('r', "0xbeef")), new MTest("-intarg 0x2f", new Long(0x2f)), new MTest("-intarg 041", new Long(041)), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd( "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg", dh, 'f', 1, "-farg ", new RngCheck[] { new RngCheck(1.0), new RngCheck(2.0), new RngCheck(9.0, OPEN, 18.0, CLOSED), new RngCheck(22.0, CLOSED, 27.0, CLOSED), new RngCheck(33.0, CLOSED, 38.0, OPEN), new RngCheck(45.0, OPEN, 48.0, OPEN), }, "test float arg", null); tests = new MTest[] { new MTest("-farg 1", new Double(1)), new MTest("-farg 3", new MErr('r', "3")), new MTest("-farg 9", new MErr('r', "9")), new MTest("-farg 9.0001", new Double(9.0001)), new MTest("-farg 11", new Double(11)), new MTest("-farg 18", new Double(18)), new MTest("-farg 22", new Double(22)), new MTest("-farg 25", new Double(25)), new MTest("-farg 27", new Double(27)), new MTest("-farg 33", new Double(33)), new MTest("-farg 35", new Double(35)), new MTest("-farg 37.9999", new Double(37.9999)), new MTest("-farg 38", new MErr('r', "38")), new MTest("-farg 45", new MErr('r', "45")), new MTest("-farg 45.0001", new Double(45.0001)), new MTest("-farg 46", new Double(46)), new MTest("-farg 47.9999", new Double(47.9999)), new MTest("-farg 48", new MErr('r', "48")), new MTest("-farg 100", new MErr('r', "100")), new MTest("-farg 0", new MErr('r', "0")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd( "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg", s3, 's', 1, "-sarg ", new RngCheck[] { new RngCheck("1"), new RngCheck("2"), new RngCheck("AA", OPEN, "AZ", CLOSED), new RngCheck("BB", CLOSED, "BX", CLOSED), new RngCheck("C3", CLOSED, "C8", OPEN), new RngCheck("d5", OPEN, "d8", OPEN), }, "test string arg", null); tests = new MTest[] { new MTest("-sarg 1", "1"), new MTest("-sarg 3", new MErr('r', "3")), new MTest("-sarg AA", new MErr('r', "AA")), new MTest("-sarg AM", "AM"), new MTest("-sarg AZ", "AZ"), new MTest("-sarg BB", "BB"), new MTest("-sarg BL", "BL"), new MTest("-sarg BX", "BX"), new MTest("-sarg C3", "C3"), new MTest("-sarg C6", "C6"), new MTest("-sarg C8", new MErr('r', "C8")), new MTest("-sarg d5", new MErr('r', "d5")), new MTest("-sarg d6", "d6"), new MTest("-sarg d8", new MErr('r', "d8")), new MTest("-sarg zzz", new MErr('r', "zzz")), new MTest("-sarg 0", new MErr('r', "0")), }; test.checkMatches(tests, MULTI_WORD); test = new ArgParserTest(); test.checkAdd("-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}", c3, 'c', 1, "-carg ", new RngCheck[] { new RngCheck('1'), new RngCheck('2'), new RngCheck('a', OPEN, 'z', CLOSED), new RngCheck('A', CLOSED, 'Z', CLOSED), new RngCheck('\001', CLOSED, '\007', OPEN), new RngCheck('4', OPEN, '8', OPEN), }, "", null); tests = new MTest[] { new MTest("-carg 1", new Character('1')), new MTest("-carg 3", new MErr('r', "3")), new MTest("-carg a", new MErr('r', "a")), new MTest("-carg m", new Character('m')), new MTest("-carg z", new Character('z')), new MTest("-carg A", new Character('A')), new MTest("-carg 'L'", new Character('L')), new MTest("-carg 'Z'", new Character('Z')), new MTest("-carg \\001", new Character('\001')), new MTest("-carg \\005", new Character('\005')), new MTest("-carg '\\007'", new MErr('r', "'\\007'")), new MTest("-carg '4'", new MErr('r', "'4'")), new MTest("-carg 6", new Character('6')), new MTest("-carg 8", new MErr('r', "8")), new MTest("-carg '\\012'", new MErr('r', "'\\012'")), new MTest("-carg 0", new MErr('r', "0")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=", new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "", null); tests = new MTest[] { new MTest("-foo=-51", new MErr('r', "-51")), new MTest("-foo=-0x32", new Long(-0x32)), new MTest("-foo=-0x33", new MErr('r', "-0x33")), new MTest("-foo=-0777", new MErr('r', "-0777")), new MTest("-foo=-07", new Long(-07)), new MTest("-foo=0", new Long(0)), new MTest("-foo=100", new Long(100)), new MTest("-foo=0x5e", new Long(0x5e)), new MTest("-foo=066", new Long(066)), new MTest("-foo=06677", new MErr('r', "06677")), new MTest("-foo=0xbeef", new MErr('r', "0xbeef")), new MTest("-foo=foo", new MErr('m', "foo")), new MTest("-foo=-51d", new MErr('m', "-51d")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null); tests = new MTest[] { new MTest("-foo2=-51", new Long(-51)), new MTest("-foo2=-0x33", new Long(-0x33)), new MTest("-foo2=-0777", new Long(-0777)), new MTest("-foo2=06677", new Long(06677)), new MTest("-foo2=0xbeef", new Long(0xbeef)), new MTest("-foo2=foo", new MErr('m', "foo")), new MTest("-foo2=-51d", new MErr('m', "-51d")), new MTest("-foo2=-51", new Long(-51)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null); tests = new MTest[] { new MTest("-foo3 -51 678 0x45", new long[] { -51, 678, 0x45 }), new MTest("-foo3 55 16f 55", new MErr('m', "16f")), new MTest("-foo3 55 16", new MErr('v', "3")), }; test.checkMatches(tests, MULTI_WORD); Vector<String> vec = new Vector<String>(100); test.checkAdd("-foov3 %iX3", vec, 'i', 3, "-foov3 ", null, "", null); tests = new MTest[] { new MTest("-foov3 -1 2 4", new long[] { -1, 2, 4 }, 0), new MTest("-foov3 10 3 9", new long[] { 10, 3, 9 }, 1), new MTest("-foov3 123 1 0", new long[] { 123, 1, 0 }, 2), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-foov %i", vec, 'i', 1, "-foov ", null, "", null); tests = new MTest[] { new MTest("-foov 11", new Long(11), 0), new MTest("-foov 12", new Long(12), 1), new MTest("-foov 13", new Long(13), 2), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ", new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "", null); tests = new MTest[] { new MTest("-foo4 -49 78", new long[] { -49, 78 }), new MTest("-foo4 -48 102", new MErr('r', "102")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=", new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "", null); tests = new MTest[] { new MTest("-oct=-063", new MErr('r', "-063")), new MTest("-oct=-0x32", new MErr('m', "-0x32")), new MTest("-oct=-0777", new MErr('r', "-0777")), new MTest("-oct=-07", new Long(-07)), new MTest("-oct=0", new Long(0)), new MTest("-oct=100", new Long(64)), new MTest("-oct=0xae", new MErr('m', "0xae")), new MTest("-oct=66", new Long(066)), new MTest("-oct=06677", new MErr('r', "06677")), new MTest("-oct=0xbeef", new MErr('m', "0xbeef")), new MTest("-oct=foo", new MErr('m', "foo")), new MTest("-oct=-51d", new MErr('m', "-51d")), new MTest("-oct=78", new MErr('m', "78")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null); tests = new MTest[] { new MTest("-oct2=-063", new Long(-063)), new MTest("-oct2=-0777", new Long(-0777)), new MTest("-oct2=06677", new Long(06677)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=", new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "", null); tests = new MTest[] { new MTest("-dec=-063", new MErr('r', "-063")), new MTest("-dec=-0x32", new MErr('m', "-0x32")), new MTest("-dec=-0777", new MErr('r', "-0777")), new MTest("-dec=-07", new Long(-07)), new MTest("-dec=0", new Long(0)), new MTest("-dec=100", new Long(100)), new MTest("-dec=0xae", new MErr('m', "0xae")), new MTest("-dec=66", new Long(66)), new MTest("-dec=06677", new MErr('r', "06677")), new MTest("-dec=0xbeef", new MErr('m', "0xbeef")), new MTest("-dec=foo", new MErr('m', "foo")), new MTest("-dec=-51d", new MErr('m', "-51d")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null); tests = new MTest[] { new MTest("-dec2=-063", new Long(-63)), new MTest("-dec2=-0777", new Long(-777)), new MTest("-dec2=06677", new Long(6677)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=", new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "", null); tests = new MTest[] { new MTest("-hex=-06", new Long(-0x6)), new MTest("-hex=-0x3g2", new MErr('m', "-0x3g2")), new MTest("-hex=-0777", new MErr('r', "-0777")), new MTest("-hex=-017", new Long(-0x17)), new MTest("-hex=0", new Long(0)), new MTest("-hex=64", new Long(0x64)), new MTest("-hex=5e", new Long(0x5e)), new MTest("-hex=66", new MErr('r', "66")), new MTest("-hex=06677", new MErr('r', "06677")), new MTest("-hex=0xbeef", new MErr('m', "0xbeef")), new MTest("-hex=foo", new MErr('m', "foo")), new MTest("-hex=-51d", new MErr('r', "-51d")), new MTest("-hex=-51g", new MErr('m', "-51g")), new MTest("-hex=", new MErr('c', "")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null); tests = new MTest[] { new MTest("-hex2=-0777", new Long(-0x777)), new MTest("-hex2=66", new Long(0x66)), new MTest("-hex2=06677", new Long(0x6677)), new MTest("-hex2=-51d", new Long(-0x51d)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-char=%c{['b','m']}", ch, 'c', 1, "-char=", new RngCheck[] { new RngCheck('b', CLOSED, 'm', CLOSED), }, "", null); tests = new MTest[] { new MTest("-char=a", new MErr('r', "a")), new MTest("-char=b", new Character('b')), new MTest("-char='b'", new Character('b')), new MTest("-char='\142'", new Character('b')), new MTest("-char='\141'", new MErr('r', "'\141'")), new MTest("-char=\142", new Character('b')), new MTest("-char=\141", new MErr('r', "\141")), new MTest("-char=m", new Character('m')), new MTest("-char=z", new MErr('r', "z")), new MTest("-char=bb", new MErr('m', "bb")), new MTest("-char='b", new MErr('m', "'b")), new MTest("-char='", new MErr('m', "'")), new MTest("-char=a'", new MErr('m', "a'")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-char2=%c", ch, 'c', 1, "-char2=", null, "", null); tests = new MTest[] { new MTest("-char2=a", new Character('a')), new MTest("-char2='\141'", new Character('\141')), new MTest("-char2=\141", new Character('\141')), new MTest("-char2=z", new Character('z')), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-charv3 %cX3", vec, 'c', 3, "-charv3 ", null, "", null); tests = new MTest[] { new MTest("-charv3 a b c", new char[] { 'a', 'b', 'c' }, 0), new MTest("-charv3 'g' f '\\n'", new char[] { 'g', 'f', '\n' }, 1), new MTest("-charv3 1 \001 3", new char[] { '1', '\001', '3' }, 2), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-charv=%c", vec, 'c', 1, "-charv=", null, "", null); tests = new MTest[] { new MTest("-charv=d", new Character('d'), 0), new MTest("-charv='g'", new Character('g'), 1), new MTest("-charv=\111", new Character('\111'), 2), }; vec.clear(); test.checkMatches(tests, ONE_WORD); test.checkAdd("-bool=%b{true}", bh, 'b', 1, "-bool=", new RngCheck[] { new RngCheck(true), }, "", null); tests = new MTest[] { new MTest("-bool=true", new Boolean(true)), new MTest("-bool=false", new MErr('r', "false")), new MTest("-bool=fals", new MErr('m', "fals")), new MTest("-bool=falsem", new MErr('m', "falsem")), new MTest("-bool=truex", new MErr('m', "truex")), new MTest("-bool=foo", new MErr('m', "foo")), new MTest("-bool=1", new MErr('m', "1")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-boo2=%b{true,false}", bh, 'b', 1, "-boo2=", new RngCheck[] { new RngCheck(true), new RngCheck(false), }, "", null); tests = new MTest[] { new MTest("-boo2=true", new Boolean(true)), new MTest("-boo2=false", new Boolean(false)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null); tests = new MTest[] { new MTest("-boo3=true", new Boolean(true)), new MTest("-boo3=false", new Boolean(false)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null); tests = new MTest[] { new MTest("-boo3 true false true", new boolean[] { true, false, true }), new MTest("-boo3 true fals true", new MErr('m', "fals")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-boov3 %bX3", vec, 'b', 3, "-boov3 ", null, "", null); tests = new MTest[] { new MTest("-boov3 true true false", new boolean[] { true, true, false }, 0), new MTest("-boov3 false false true", new boolean[] { false, false, true }, 1), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-boov %b", vec, 'b', 1, "-boov ", null, "", null); tests = new MTest[] { new MTest("-boov true", new Boolean(true), 0), new MTest("-boov false", new Boolean(false), 1), new MTest("-boov true", new Boolean(true), 2), new MTest("-boov", new Boolean(true), 3), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null); tests = new MTest[] { new MTest("-v3", new boolean[] { true, true }), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-vf %v{false,true}X2", b3, 'v', 2, "-vf ", new RngCheck[] { new RngCheck(false), new RngCheck(true), }, "", null); tests = new MTest[] { new MTest("-vf", new boolean[] { false, false }), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-str=%s{(john,zzzz]}", sh, 's', 1, "-str=", new RngCheck[] { new RngCheck("john", OPEN, "zzzz", CLOSED), }, "", null); tests = new MTest[] { new MTest("-str=john", new MErr('r', "john")), new MTest("-str=joho ", "joho "), new MTest("-str=joho ", "joho "), new MTest("-str=zzzz", "zzzz"), new MTest("-str= joho", new MErr('r', " joho")), new MTest("-str=jnhn ", new MErr('r', "jnhn ")), new MTest("-str=zzzzz", new MErr('r', "zzzzz")), new MTest("-str=\"joho\"", new MErr('r', "\"joho\"")), new MTest("-str=\"joho", new MErr('r', "\"joho")), new MTest("-str=joho j", "joho j"), // new MErr('m', "joho j")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-str2=%s", sh, 's', 1, "-str2=", null, "", null); tests = new MTest[] { new MTest("-str2= jnhn", " jnhn"), new MTest("-str2=zzzzz", "zzzzz"), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-str3 %sX3", s3, 's', 3, "-str3 ", null, "", null); tests = new MTest[] { new MTest("-str3 foo bar johnny", new String[] { "foo", "bar", "johnny" }), new MTest("-str3 zzzzz \"bad foo", new String[] { "zzzzz", "\"bad", "foo" }), // new MErr('m', "\"bad")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-strv3 %sX3", vec, 's', 3, "-strv3 ", null, "", null); tests = new MTest[] { new MTest("-strv3 foo bar \"hihi\"", new String[] { "foo", "bar", "\"hihi\"" }, 0), new MTest("-strv3 a 123 gg", new String[] { "a", "123", "gg" }, 1), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-strv=%s", vec, 's', 1, "-strv=", null, "", null); tests = new MTest[] { new MTest("-strv=d", "d", 0), new MTest("-strv='g'", "'g'", 1), new MTest("-strv=\\111", "\\111", 2), }; vec.clear(); test.checkMatches(tests, ONE_WORD); test.checkAdd("-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=", new RngCheck[] { new RngCheck(-0.001, OPEN, 1000.0, CLOSED), }, "", null); tests = new MTest[] { new MTest("-float=-0.000999", new Double(-0.000999)), new MTest("-float=1e-3", new Double(0.001)), new MTest("-float=12.33e1", new Double(123.3)), new MTest("-float=1e3", new Double(1e3)), new MTest("-float=1000.000", new Double(1000.0)), new MTest("-float=-0.001", new MErr('r', "-0.001")), new MTest("-float=-1e-3", new MErr('r', "-1e-3")), new MTest("-float=1000.001", new MErr('r', "1000.001")), new MTest("-float=.", new MErr('m', ".")), new MTest("-float= 124.5 ", new Double(124.5)), new MTest("-float=124.5x", new MErr('m', "124.5x")), new MTest("-float= foo ", new MErr('m', " foo ")), new MTest("-float=1e1", new Double(10)), new MTest("-float=1e ", new MErr('m', "1e ")), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-float2=%f", dh, 'f', 1, "-float2=", null, "", null); tests = new MTest[] { new MTest("-float2=-0.001", new Double(-0.001)), new MTest("-float2=-1e-3", new Double(-1e-3)), new MTest("-float2=1000.001", new Double(1000.001)), }; test.checkMatches(tests, ONE_WORD); test.checkAdd("-f3 %fX3", d3, 'f', 3, "-f3 ", null, "", null); tests = new MTest[] { new MTest("-f3 -0.001 1.23e5 -9.88e-4", new double[] { -0.001, 1.23e5, -9.88e-4 }), new MTest("-f3 7.88 foo 9.0", new MErr('m', "foo")), new MTest("-f3 7.88 . 9.0", new MErr('m', ".")), new MTest("-f3 7.88 3.0 9.0x", new MErr('m', "9.0x")), }; test.checkMatches(tests, MULTI_WORD); test.checkAdd("-fv3 %fX3", vec, 'f', 3, "-fv3 ", null, "", null); tests = new MTest[] { new MTest("-fv3 1.0 3.444 6.7", new double[] { 1.0, 3.444, 6.7 }, 0), new MTest("-fv3 13e-5 145.678 0.0001e45", new double[] { 13e-5, 145.678, 0.0001e45 }, 1), new MTest("-fv3 11.11 3.1245 -1e-4", new double[] { 11.11, 3.1245, -1e-4 }, 2), new MTest("-fv3 1.0 2 3", new double[] { 1.0, 2.0, 3.0 }, 3), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); test.checkAdd("-fv %f", vec, 'f', 1, "-fv ", null, "", null); tests = new MTest[] { new MTest("-fv -15.1234", new Double(-15.1234), 0), new MTest("-fv -1.234e-7", new Double(-1.234e-7), 1), new MTest("-fv 0.001111", new Double(0.001111), 2), }; vec.clear(); test.checkMatches(tests, MULTI_WORD); ArgHolder<Integer> intHolder = new ArgHolder<Integer>(Integer.class); ArgHolder<String> strHolder = new ArgHolder<String>(String.class); ArgParser parser = new ArgParser("test"); parser.addOption("-foo %d #an int", intHolder); parser.addOption("-bar %s #a string", strHolder); args = new String[] { "zzz", "-cat", "-foo", "123", "yyy", "-bar", "xxxx", "xxx" }; String[] unmatchedCheck = new String[] { "zzz", "-cat", "yyy", "xxx" }; String[] unmatched = parser.matchAllArgs(args, 0, 0); test.checkStringArray("Unmatched args:", unmatched, unmatchedCheck); vec.clear(); for (int i = 0; i < args.length;) { try { i = parser.matchArg(args, i); if (parser.getUnmatchedArgument() != null) { vec.add(parser.getUnmatchedArgument()); } } catch (Exception e) { } } unmatched = vec.toArray(new String[0]); test.checkStringArray("My unmatched args:", unmatched, unmatchedCheck); System.out.println("\nPassed\n"); }
3
public void LoadContent() { gameFrame.getContentPane().add(ContinueButton); random1 = (int) (Math.random()*4 + 1); do { random2 = (int) (Math.random()*4 + 1); } while (random1 == random2); switch (random1) { case 1: disp1 = sora; break; case 2: disp1 = shiro; break; case 3: disp1 = jibril; break; case 4: disp1 = steph; break; default: System.err.println("randomerr"); } switch (random2) { case 1: disp2 = sora; break; case 2: disp2 = shiro; break; case 3: disp2 = jibril; break; case 4: disp2 = steph; break; default: System.err.println("randomerr"); } mode = 0; ContinueButton.setText("CONTINUE"); }
9
public AIConnection[] getListInTurnOrderAndMoveToNextTurn(){ // TODO: Dead players are currently not purged anymore. Verify that works... // purgeDeadPlayersFromRing(); // TODO: build in check here to skip over passing players // TODO: test this code while(true){ currentPlayer = currentPlayer.next; if(currentPlayer.connection.hasToPass){ currentPlayer.connection.hasToPass = false; } else { // player doesn't have to pass his turn, but he hasn't respawned yet. Respawn him. if(currentPlayer.connection.needsRespawn && !currentPlayer.connection.hasToPass){ currentPlayer.connection.respawn(); } break; // we found a player who doesn't have to pass his turn } } LinkedList<AIConnection> templist = new LinkedList<AIConnection>(); RingNode tempPlayer = currentPlayer; // it's currentPlayers turn. do { templist.add(tempPlayer.connection); tempPlayer = tempPlayer.next; } while(tempPlayer != currentPlayer); AIConnection[] connectionArrayWorkaroundForJavasStupidTypeSystem = new AIConnection[0]; return templist.toArray(connectionArrayWorkaroundForJavasStupidTypeSystem); }
5
private static int search(int[] table, int value) { int index = 0; if (table[index + 32] <= value) { index += 32; } if (table[index + 16] <= value) { index += 16; } if (table[index + 8] <= value) { index += 8; } if (table[index + 4] <= value) { index += 4; } if (table[index + 2] <= value) { index += 2; } if (table[index + 1] <= value) { index += 1; } if (table[index] > value) { index -= 1; } if (index < 0 || table[index] != value) { return -1; } return index; }
9
@Override public Roleschool addRoleFromGson(String json, long id) { Roleschool role = null; if (json.contains("Teacher")) { role = gson.fromJson(json, Teacher.class); } if (json.contains("Student")) { role = gson.fromJson(json, Student.class); } if (json.contains("Assistantteacher")) { role = gson.fromJson(json, Assistantteacher.class); } em.getTransaction().begin(); Person person = em.find(Person.class, id); if (person != null && role != null) { person.setRoles(role); } em.getTransaction().commit(); return role; }
5
@Override public String toString() { String name = getName(); String append = ""; if(name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Long" + append + ": " + value; }
2
public void PassengersOnBoarding(BusStop busStop,OutputFile screen) { //set the current bus stop currentBusStop = busStop; //set the average persons for the bus stop busStop.SetAverageNumberOfPersons(); //set the average person wait time busStop.SetAveragePersonsWaitTime(this); //check //person getting on the bus Person got; while((busStop.Count() > 0) && (Increment())) { got = busStop.GetPerson(); //set time person got on the bus got.SetOnBusTicks(this.firstTicks); //set person wait time got.SetWaitTime(this.GetFirstTicks()-got.GetFirstTicks()); passengers.add(got); //set empty flag to false this.SetEmpty(false); screen.WriteToFile("Time:,"+GetFirstTicks()+", --> ON"+", GetOn: "+ (got.GetStartBusStop()+1)+", Bus #"+GetBusNumber()+", person #"+(got.GetPersonNumber()+1)+", GetOff: "+ (got.GetStopBusStop()+1)+", Priority: "+got.GetPriority()+", PASSENGERS: "+ passengers.size()); if(verbose) System.out.println("Time:,"+GetFirstTicks()+", --> ON"+", GetOn: "+ (got.GetStartBusStop()+1)+", Bus #"+GetBusNumber()+", person #"+(got.GetPersonNumber()+1)+", GetOff: "+ (got.GetStopBusStop()+1)+", Priority: "+got.GetPriority()+", PASSENGERS: "+ passengers.size()); } //get iterator for the BusStop Iterator iter = busStop.GetIterator(); //update person left at stop while(iter.hasNext()) { ((Person)iter.next()).IncrementLeftByBus(); } //indicate how much left at the stop SetTotalLeftAtBusStop(busStop.Count()); //set minimum capacity this.SetMinimumPassenger(this.GetPassengerQuantity()); //set maximum capacity this.SetMaximumPassenger(this.GetPassengerQuantity()); }
4
public void play() { System.out.println("Starting the game..."); for (double gameNumber = 0; gameNumber < mGames; gameNumber++) { double x1 = mRandom.nextTrueDouble(); double x2 = mRandom.nextTrueDouble(); System.out.println("X1=" + x1 + "\nX2=" + x2); for (Stat stat : mStats) { Player targetPlayer = stat.getPlayer(); System.out.println("Playing with Player " + targetPlayer.getName()); // TODO x1 should NEVER be == x2 boolean playerAcceptedNumber = targetPlayer.willAcceptFirstEnvelope(new Envelope(x1), new SecureEnvelope(x2)); System.out.println("Player " + (playerAcceptedNumber ? "accepted" : "rejected") + " the first number"); boolean won = (playerAcceptedNumber && x1 > x2) || (!playerAcceptedNumber && x2 > x1); System.out.println("Player " + (won ? "wins" : "loses")); stat.registerGamePlayed(won); } } System.out.println("Game over. Results for " + (int) mGames + " games played"); for (Stat stat : mStats) { Player targetPlayer = stat.getPlayer(); System.out.println("Player " + targetPlayer.getName()); System.out.println("Wins: " + stat.getWins()); System.out.println("Success rate : " + 100 * stat.getWins() / stat.getGamesPlayed() + "%"); } }
8
public static Node treeDelete(Node root,Node z){ if(z.left == null){ root = transplant(root,z,z.right); } else if(z.right == null){ root = transplant(root,z,z.left); } else{ Node y = minimum(z.right); if( y.p != z){ root = transplant(root,y,y.right); y.right = z.right; y.right.p = y; } root = transplant(root,z,y); y.left = z.left; y.left.p = y; } return root; }
3
public String toString(){ return Integer.toString(value) + "(" + Integer.toString(id) + ")"; }
0
public void shift(int base_position){ int[] z = findZ(base_position); System.out.println(String.format("z1, z2:%3d, %3d", z[0], z[1])); System.out.println("Before shift:");this.print(); // (z[0] , base_position-1] 区间全部左移 for (int i = z[0]+1; i != base_position; ++i){ if (mHistorgram.containsKey(i)){ mHistorgram.put(i-1, mHistorgram.get(i)); } } mHistorgram.put(base_position-1,0); // [ base_position+1 , z[1] ) 区间的全部右移 for (int i = z[1]-1; i != base_position; --i){ if (mHistorgram.containsKey(i)){ mHistorgram.put(i+1, mHistorgram.get(i)); } } mHistorgram.put(base_position+1,0); System.out.println("After shift:");this.print(); }
4
public static int signingCost(Application app) { // // TODO: Signing cost is based on transport factors, attraction, no. // already employed, etc. Implement all of that. int transport = 0, incentive = 0, guildFees = 0 ; guildFees += Background.HIRE_COSTS[app.position.standing] ; if (! app.applies.inWorld()) { // ...This could potentially be much higher, depending on origin point. transport += 100 ; } else if (app.applies.mind.work() == null) { guildFees = 0 ; } if (app.employer instanceof Venue) { final Venue venue = (Venue) app.employer ; int numEmployed = venue.personnel.numPositions(app.position) ; if (numEmployed == 0) { guildFees = 0 ; transport /= 2 ; } else if (numEmployed == 1) { guildFees /= 2 ; } else guildFees *= 1 + ((numEmployed - 2) / 2f) ; } return guildFees + transport + incentive ; }
5
@Test public void testReleasePortNumberRunning() { LOGGER.log(Level.INFO, "----- STARTING TEST testReleasePortNumberRunning -----"); try { server1.startThread(); } catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) { exception = true; } waitListenThreadStart(server1); try { server1.close(); } catch (IOException | ServerSocketCloseException | TimeoutException e) { exception = true; } waitServerState(server1, Server.CLOSED); Server server3 = null; try { LOGGER.log(Level.INFO, "Building Server3"); server3 = new Server(game, port, true); } catch (IOException | ServerSocketCloseException | TimeoutException e) { exception = true; } Assert.assertEquals(server3.getState(), Server.LISTEN, "Server not set as state LISTEN. Port could not be listened on"); try { server3.close(); } catch (IOException | ServerSocketCloseException | TimeoutException e) { exception = true; } waitServerState(server3, Server.CLOSED); Assert.assertFalse(exception, "Exception found"); LOGGER.log(Level.INFO, "----- TEST testReleasePortNumberRunning COMPLETED -----"); }
4
public void render(Graphics g) { g.drawImage(image, map.mapXOffset + mapX, map.mapYOffset + mapY, null); if (owned) { //if owned, a blue rectangle appears around it on sides where there is unowned land g.setColor(Color.RED); Point listPoint = map.getListLocation(this); if (!map.tileIsOwned(listPoint.x, listPoint.y-1)) //on top g.drawLine(map.mapXOffset + mapX, map.mapYOffset + mapY+1, map.mapXOffset + mapX + Tile.SIZE, map.mapYOffset + mapY+1); if (!map.tileIsOwned(listPoint.x, listPoint.y+1)) //on botton g.drawLine(map.mapXOffset + mapX, map.mapYOffset + mapY + Tile.SIZE-1, map.mapXOffset + mapX + Tile.SIZE, map.mapYOffset + mapY + Tile.SIZE-1); if (!map.tileIsOwned(listPoint.x+1, listPoint.y)) //on right g.drawLine(map.mapXOffset + mapX + Tile.SIZE-1, map.mapYOffset + mapY, map.mapXOffset + mapX + Tile.SIZE-1, map.mapYOffset + mapY + Tile.SIZE-1); if (!map.tileIsOwned(listPoint.x-1, listPoint.y)) //on right g.drawLine(map.mapXOffset + mapX-1, map.mapYOffset + mapY, map.mapXOffset + mapX-1, map.mapYOffset + mapY + Tile.SIZE-1); //g.drawRect(map.mapXOffset + mapX, map.mapYOffset + mapY, Tile.SIZE-1, Tile.SIZE-1); } for (int i = 0; i < inventory.size(); i++) { if (inventory.get(i) != null) { try { inventory.get(i).getItemGround(mapX + map.mapXOffset, mapY + map.mapYOffset).render(g); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } }
8
public final void CompleteTrade() { for (final IItem item : exchangeItems) { byte flag = item.getFlag(); if (ItemFlag.KARMA_EQ.check(flag)) { item.setFlag((byte) (flag - ItemFlag.KARMA_EQ.getValue())); } else if (ItemFlag.KARMA_USE.check(flag)) { item.setFlag((byte) (flag - ItemFlag.KARMA_USE.getValue())); } MapleInventoryManipulator.addFromDrop(chr.getClient(), item, false); } if (exchangeMeso > 0) { chr.gainMeso(exchangeMeso - GameConstants.getTaxAmount(exchangeMeso), false, true, false); } exchangeMeso = 0; if (exchangeItems != null) { // just to be on the safe side... exchangeItems.clear(); } chr.getClient().getSession().write(MaplePacketCreator.TradeMessage(tradingslot, (byte) 0x06)); }
5
private void dummy() { }
0
private static void sort(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = i; j < array.length; j++) { if (array[j] > array[i]) { array[j] = array[i] ^ array[j]; array[i] = array[i] ^ array[j]; array[j] = array[i] ^ array[j]; } } } }
3
public int verschilInMaanden(Datum d) { int verschilInJaren = this.verschilInJaren(d); if (this.kleinerDan(d) && this.getJaar() == d.getJaar()) { int verschilMaanden = d.getMaand() - this.getMaand(); return verschilInJaren * 12 + verschilMaanden; } if (this.kleinerDan(d)) { int overschotMaanden = 12 - this.getMaand(); return verschilInJaren * 12 + overschotMaanden + d.getMaand(); } if (!this.kleinerDan(d) && this.getJaar() == d.getJaar()) { int verschilMaanden = this.getMaand() - d.getMaand(); return verschilInJaren * 12 + verschilMaanden; } if (!this.kleinerDan(d)) { int overschotMaanden = 12 - d.getMaand(); return verschilInJaren * 12 + overschotMaanden + this.getMaand(); } return 0; }
6
public void addDataSet(DataSet set) { this.datasets.add(set); }
0
public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); String header_guide =rpc.Helper.getIncludeGuide(rpc.Context.Get().getCurrentPackage(), rpc.Helper.PathType.eParamsHeader); stringBuffer.append(TEXT_1); stringBuffer.append(header_guide); stringBuffer.append(TEXT_2); stringBuffer.append(header_guide); stringBuffer.append(TEXT_3); stringBuffer.append(rpc.Helper.getRelativePath(rpc.Context.Get().getCurrentPackage(), rpc.Helper.PathType.eInterfaceHeader)); stringBuffer.append(TEXT_4); for(ClassDoc cls: rpc.Context.Get().getCurrentPackage().interfaces()) { stringBuffer.append(TEXT_5); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_6); int methodId = 1; for(MethodDoc method: cls.methods()) { stringBuffer.append(TEXT_7); stringBuffer.append(method.name()); stringBuffer.append(TEXT_8); stringBuffer.append(methodId++ ); stringBuffer.append(TEXT_9); for(Parameter param: method.parameters()) { stringBuffer.append(TEXT_10); stringBuffer.append(rpc.Helper.parameterStorage(param)); stringBuffer.append(TEXT_11); } stringBuffer.append(TEXT_12); } stringBuffer.append(TEXT_13); } stringBuffer.append(TEXT_14); for(ClassDoc cls: rpc.Context.Get().getCurrentPackage().interfaces()) { stringBuffer.append(TEXT_15); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_16); for(MethodDoc method: cls.methods()) { stringBuffer.append(TEXT_17); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_18); stringBuffer.append(method.name()); stringBuffer.append(TEXT_19); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_20); stringBuffer.append(method.name()); stringBuffer.append(TEXT_21); } } stringBuffer.append(TEXT_22); for(ClassDoc cls: rpc.Context.Get().getCurrentPackage().allClasses()) { if(rpc.Helper.isStructure(cls) || rpc.Helper.isEnum(cls) ) { stringBuffer.append(TEXT_23); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_24); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_25); stringBuffer.append(rpc.Helper.convertCPPType(cls)); stringBuffer.append(TEXT_26); } } stringBuffer.append(TEXT_27); stringBuffer.append(header_guide); stringBuffer.append(TEXT_28); return stringBuffer.toString(); }
8
Map(String name, Tile[][] map) throws MapNotRectangularException { //check if array is rectangular { int x = map.length; int y = map[0].length; int ytemp; for(Tile[] array : map){ ytemp = array.length; if(y != ytemp){ throw new MapNotRectangularException(); } } this.groesseX = x; this.groesseY = y; } this.map = map; this.name = name; //attach each Tile from the array with its respective translation for(int x = 0; x < groesseX; x++){ for(int y = 0; y < groesseY; y++){ Tile t = map[x][y]; attachChild(t); t.setLocalTranslation(1 + x, 1 + y, 0.0f); } } }
4
@Override public int attack(double agility, double luck) { System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn..."); return 0; }
0
final int[] method3042(int i, int i_75_) { anInt9143++; if (i_75_ != 255) aClass348_Sub42_Sub12_9144 = null; int[] is = ((Class348_Sub40) this).aClass191_7032.method1433(0, i); if (((Class191) ((Class348_Sub40) this).aClass191_7032).aBoolean2570) { int[] is_76_ = this.method3048((aBoolean9147 ? Class299_Sub2.anInt6325 - i : i), i_75_ + 633706082, 0); if (!aBoolean9140) ArrayUtils.arrayCopy(is_76_, 0, is, 0, Class348_Sub40_Sub6.anInt9139); else { for (int i_77_ = 0; ((Class348_Sub40_Sub6.anInt9139 ^ 0xffffffff) < (i_77_ ^ 0xffffffff)); i_77_++) is[i_77_] = is_76_[Class239_Sub22.anInt6076 + -i_77_]; } } return is; }
5
@SuppressWarnings("unchecked") public static JSONObject executeShScript(String cmd, JSONObject jsonResp){ log.info("starting shell script execution ... :" + cmd); try { Process process = Runtime.getRuntime().exec(cmd); String outStr = "", s = ""; BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((s = br.readLine()) != null) { outStr += s; } log.info("Output String : " + outStr); String errOutput = "" ; BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream())); while (br2.ready() && (s = br2.readLine()) != null) { errOutput += s; } log.info("Error String : " + errOutput); if(errOutput.contains("Syntax error")){ jsonResp.put("status", "1"); jsonResp.put("message", "Failed to start modsecurity"); } else{ jsonResp.put("status", "0"); jsonResp.put("message", outStr); } } catch (IOException e) { jsonResp.put("status", "1"); jsonResp.put("message", "Error: internal service is down"); log.info("Error Message: " + e.getMessage()); //e.printStackTrace(); } return jsonResp; }
5
public void update(float delta) { setX(getX() + direction.x * delta); setY(getY() + direction.y * delta); animationTime += delta; setRegion(direction.x < 0 ? left.getKeyFrame(animationTime) : direction.x > 0 ? right.getKeyFrame(animationTime) : direction.y < 0 ? down.getKeyFrame(animationTime) : direction.y > 0 ? up.getKeyFrame(animationTime) : still.getKeyFrame(animationTime)); }
4
private static void loadWindowOptions() { File inputFile = new File("windows.conf"); if (!inputFile.exists()) { return; } try { window_props.load(new FileInputStream(inputFile)); } catch (IOException e) { System.out.println(e); } }
2
public boolean setInputFormat(Instances instanceInfo) throws Exception { Attribute att; Attribute attNew; Vector allLabels; Enumeration enm; int i; FastVector values; FastVector atts; Instances instNew; super.setInputFormat(instanceInfo); m_AttIndex.setUpper(instanceInfo.numAttributes() - 1); att = instanceInfo.attribute(m_AttIndex.getIndex()); if (!att.isNominal()) throw new UnsupportedAttributeTypeException("Chosen attribute not nominal."); // merge labels allLabels = new Vector(); enm = att.enumerateValues(); while (enm.hasMoreElements()) allLabels.add(enm.nextElement()); for (i = 0; i < m_Labels.size(); i++) { if (!allLabels.contains(m_Labels.get(i))) allLabels.add(m_Labels.get(i)); } // generate index array if (getSort()) Collections.sort(allLabels); m_SortedIndices = new int[att.numValues()]; enm = att.enumerateValues(); i = 0; while (enm.hasMoreElements()) { m_SortedIndices[i] = allLabels.indexOf(enm.nextElement()); i++; } // generate new header values = new FastVector(); for (i = 0; i < allLabels.size(); i++) values.addElement(allLabels.get(i)); attNew = new Attribute(att.name(), values); atts = new FastVector(); for (i = 0; i < instanceInfo.numAttributes(); i++) { if (i == m_AttIndex.getIndex()) atts.addElement(attNew); else atts.addElement(instanceInfo.attribute(i)); } instNew = new Instances(instanceInfo.relationName(), atts, 0); instNew.setClassIndex(instanceInfo.classIndex()); // set new format setOutputFormat(instNew); return true; }
9
private SeedMenuItem() { super("From seed"); setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String seed = showSeedPrompt("New Project"); if (seed != null) { String worldTypePreference = Options.instance.worldType.get(); SaveLoader.Type worldType = null; if (worldTypePreference.equals("Prompt each time")) { worldType = choose("New Project", "Enter world type\n", SaveLoader.selectableTypes); } else { worldType = SaveLoader.Type.fromMixedCase(worldTypePreference); } String mapTypePreference = Options.instance.mapType.get(); if (mapTypePreference.equals("Climate Control")) { MinecraftUtil.setBiomeInterface(Util.ccInterface); } else { MinecraftUtil.setBiomeInterface(Util.mcInterface); } if (seed.equals("")) { seed = "" + (new Random()).nextLong(); } if (worldType != null) { window.clearProject(); window.setProject(new Project(seed, worldType.getValue())); } } } }); }
5
static void run(int number) { try { System.out.println("================================================"); DetailsLogger.startNewLog(detailsLogPrefix + "." + number + ".xml"); DetailsLogger.logParams(prop); Individual sampleIndividual = new IntegerIndividual(weights.size(), 0, K); Population pop = new Population(); pop.setPopulationSize(popSize); pop.setSampleIndividual(sampleIndividual); pop.createRandomInitialPopulation(); EvolutionaryAlgorithm ea = new EvolutionaryAlgorithm(); HromadkyFitness fitness = new HromadkyFitness(weights, K); ea.setFitnessEvaluator(new ConcurrentInverseFitnessEvaluator(fitness)); ea.addMatingSelector(new SUSSelector()); //ea.addMatingSelector(new TournamentSelector()); ea.addMatingSelector(new BigTournamentSelector()); ea.addOperator(new OnePtXOver(xoverProb)); ea.addOperator(new IntegerMutation(mutProb, mutProbPerBit)); //ea.addOperator(new SwappingMutationOperator(0.1, 0.01)); ea.addEnvironmentalSelector(new SUSSelector()); //ea.addEnvironmentalSelector(new TournamentSelector()); ea.addEnvironmentalSelector(new BigTournamentSelector()); ea.setElite(eliteSize); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fitnessFilePrefix + "." + number)); OutputStreamWriter progOut = new OutputStreamWriter(new FileOutputStream(objectiveFilePrefix + "." + number)); double lastObj = Double.MAX_VALUE; long start = System.nanoTime(); for (int i = 1; i <= maxGen; i++) { ea.evolve(pop); IntegerIndividual bestInd = (IntegerIndividual)pop.getBestIndividual(); double diff = bestInd.getObjectiveValue(); if(i == maxGen || i % 1000 == 0 || diff != lastObj){ if(i%1000 == 0){ long now = System.nanoTime(); double timeDiffSec = (now - start) / 1000000000; System.out.println("SPEED: "+Math.round(i/timeDiffSec)+" gen/s"); } lastObj = diff; System.out.println(number + "|" + i + ": " + diff + " " + Arrays.toString(fitness.getBinWeights(bestInd))); best[number] = diff; } StatsLogger.logFitness(pop, out); StatsLogger.logObjective(pop, progOut); } OutputStreamWriter bestOut = new OutputStreamWriter(new FileOutputStream(bestPrefix + "." + number)); IntegerIndividual bestInd = (IntegerIndividual)pop.getBestIndividual(); for (int i = 0; i < bestInd.toIntArray().length; i++) { bestOut.write(weights.get(i) + " " + bestInd.toIntArray()[i] + System.getProperty("line.separator")); } out.close(); progOut.close(); bestOut.close(); } catch (IOException e) { e.printStackTrace(); } DetailsLogger.writeLog(); }
7
public boolean equals(Vari vertailtava) { return punainen == vertailtava.punainen() && vihrea == vertailtava.vihrea() && sininen == vertailtava.sininen() && peittavyys == vertailtava.peittavyys(); }
3
@Override public Ingredient retrieveIngredient(String name) throws DataStoreException{ name = name.toLowerCase(); if( isIngredientCacheValid ){ for ( Ingredient ingredient : ingredientCache ) { if( ingredient.getSingular().equals("name")){ return ingredient; } } } Ingredient result = null; try ( Connection conn = getConnection(); ResultSet rs = executeStatement(conn, "SELECT name_singular, name_plural, common FROM ingredients WHERE " + "name_singular='" + escapeQuotes(name) + "' OR " + "name_plural='" + escapeQuotes(name) + "'")){ if(rs != null){ while(rs.next()){ String singular = rs.getString("name_singular"); String plural = rs.getString("name_plural"); Boolean common = rs.getBoolean("common"); result = new Ingredient(singular, plural, common); } } } catch (SQLException e){ LOGGER.error("Exception while retrieving ingredient: " + e.getMessage()); throw new DataStoreException(e.getMessage()); } return result; }
6
public String getActualSql(Object[] args) { String[] tableNames = null; String sql; if (genericIndexes != null) { for (Integer index : genericIndexes) { if (index != null) { Object arg = args[index]; if (arg != null) { tableNames = (String[]) ArrayHelper.add(tableNames, arg.toString()); } } } } if (tableNames != null) { sql = SqlFormatter.formatSql(preparedSql, tableNames); } else { sql = preparedSql; } return sql; }
5
public FeatureVector predictExtract(GuideDecision decision) throws MaltChainedException { if (decision instanceof SingleDecision) { throw new GuideException("A branched decision model expect more than one decisions. "); } featureModel.update(); final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex); if (instanceModel == null) { initInstanceModel(singleDecision.getTableContainer().getTableContainerName()); } FeatureVector fv = instanceModel.predictExtract(singleDecision); if (decisionIndex+1 < decision.numberOfDecisions()) { if (singleDecision.continueWithNextDecision()) { if (children == null) { children = new HashMap<Integer,DecisionModel>(); } DecisionModel child = children.get(singleDecision.getDecisionCode()); if (child == null) { child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1), branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol()); children.put(singleDecision.getDecisionCode(), child); } child.predictExtract(decision); } } return fv; }
7
private double traverseCost(Node node, Node newNode, Agent agent) { if (agent == null) { // default agent Location loc1 = node.location, loc2 = newNode.location; int dx = Math.abs(loc1.x - loc2.x), dy = Math.abs(loc1.y - loc2.y); return costs[grid[newNode.location.x][newNode.location.y]] + 0.1 * (dx + dy - 1); } else { return 1; } }
1
public static Player getPlayer(String name) { for (World world : worlds) for (Player cyclePlayer : world.getPlayers()) if (cyclePlayer.getUsername().equalsIgnoreCase(name)) return cyclePlayer; return null; }
3
public void setREM(int REM) { this.REM = REM; if (REM==0) CharInfo[15] = 0; else if(REM==1) CharInfo[15] = 1; else if(REM==2) CharInfo[15] = 2; else if(REM==3) CharInfo[15] = 3; else this.code.setValid(false); }
4
@SuppressWarnings("unchecked") public FenetreFichier(final Portail p1, final Fichier fileModif, final Groupe gp) { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 379, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblFichier = new JLabel(fileModif.nom); lblFichier.setFont(new Font("Calibri", Font.BOLD, 25)); lblFichier.setBounds(120, 11, 175, 35); contentPane.add(lblFichier); JLabel lblNom = new JLabel("Nom : "); lblNom.setBounds(25, 86, 46, 14); contentPane.add(lblNom); textField = new JTextField(fileModif.nom); textField.setBounds(81, 83, 86, 20); contentPane.add(textField); textField.setColumns(10); JButton btnNewButton = new JButton("V"); btnNewButton.setBounds(131, 228, 50, 23); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("X"); btnNewButton_1.setBounds(191, 228, 46, 23); contentPane.add(btnNewButton_1); final JComboBox comboBox_1 = new JComboBox(); comboBox_1.setBounds(55, 160, 112, 20); contentPane.add(comboBox_1); JLabel lblRelation = new JLabel("Relation"); lblRelation.setBounds(81, 135, 62, 14); contentPane.add(lblRelation); JLabel lblFichier_1 = new JLabel("Fichier"); lblFichier_1.setBounds(224, 135, 46, 14); contentPane.add(lblFichier_1); // Remplissage des ComboBox // Relation RelationFichier obj1 = gp.getRelation(fileModif); System.out.println("DEBUG OBJET = " + obj1); Object[] RelationArray = new Object[2]; if (obj1 != null) { RelationArray[0] = obj1.getFichier2(); RelationArray[1] = obj1.getRel().name(); } comboBox_1.addItem("Aucune"); comboBox_1.addItem(Relation.values()[0]); comboBox_1.addItem(Relation.values()[1]); comboBox_1.addItem(Relation.values()[2]); // comboBox_1.addItem(Relation.values()[3]); if (RelationArray[1] != null) { comboBox_1.setSelectedItem(Relation.valueOf(RelationArray[1] .toString())); ; } // Liste des fichiers final JComboBox comboBox = new JComboBox(); for ( int k = 0 ; k < gp.getListFichier().size() ; k++) { comboBox.addItem(gp.getListFichier().get(k)); } comboBox.setBounds(204, 160, 120, 20); contentPane.add(comboBox); if (RelationArray[0] != null) { System.out.println("COMBO FICHIER = " +comboBox.getSelectedIndex()); System.out.println(gp.getIndexByFile((Fichier)RelationArray[0])); comboBox.setSelectedIndex(gp.getIndexByFile((Fichier)RelationArray[0])); } btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // gp.updateFichier(gp.getFichierById(fileModif.id),textField); gp.updateFichier(fileModif, textField); System.out.println(" Combo "+comboBox_1.getSelectedItem().toString() ); if (!comboBox_1.getSelectedItem().toString().equals( "Aucune")) { fileModif.setRelationFichier(comboBox_1.getSelectedItem() .toString() + ";;" + comboBox.getSelectedItem().toString()); gp.addRelation(fileModif, (Fichier)comboBox.getSelectedItem(), (Relation)comboBox_1.getSelectedItem()); } setVisible(false); } }); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); // p1.AfficheEnt(p1); } }); }
5
public String preferredGender() { final boolean male = actor.traits.male() ; if (actor.traits.hasTrait(ORIENTATION, "Heterosexual")) { return male ? "Female" : "Male" ; } if (actor.traits.hasTrait(ORIENTATION, "Homosexual")) { return male ? "Male" : "Female" ; } return Rand.yes() ? "Male" : "Female" ; }
5
public synchronized void release() { state = STATE_RELEASED; }
0
public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); switch(key) { case KeyEvent.VK_CONTROL: fire(); break; case KeyEvent.VK_LEFT : bL = false; break; case KeyEvent.VK_UP : bU = false; break; case KeyEvent.VK_RIGHT : bR = false; break; case KeyEvent.VK_DOWN : bD = false; break; case KeyEvent.VK_A : superFire(); break; } locateDirection(); }
6
public Rol buscarRol (String name){ Rol rol=null; ArrayList<Rol> dbRol = tablaRoles(); for (Rol r : dbRol){ if(r.getNombre().equals(name)){ rol = r; } } return rol; }
2
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String uniId = request.getParameter("uni_id"); HttpSession session = request.getSession(true); session.setAttribute("uni_id", uniId); UniDatabaseManager uDm = new UniDatabaseManager(); List<University> ul = null; try { ul = uDm.universityList(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Integer> uIdList = new ArrayList<Integer>(); List<String> uNameList = new ArrayList<String>(); List<String> uLocationList = new ArrayList<String>(); List<String> uIntroList = new ArrayList<String>(); for (int i = 0; i < ul.size(); i++) { int uId = ul.get(i).getId(); String uName = ul.get(i).getName(); String uLocation = ul.get(i).getLocation(); String uIntro = ul.get(i).getIntro(); uIdList.add(uId); uNameList.add(uName); uLocationList.add(uLocation); uIntroList.add(uIntro); } for (int j = 0; j < uIdList.size(); j++) { int u_id = Integer.parseInt(uniId); if (u_id == uIdList.get(j)) { String uniName = uNameList.get(j); session.setAttribute("uni_name", uniName); String uniLocation = uLocationList.get(j); session.setAttribute("uni_location", uniLocation); } } response.sendRedirect("uni.jsp"); }
4
public int binarySearchTail (ArrayList<String> word, String key,int first, int last){ int mid = first + ((last-first)/2); if (word.size() == 0){ return 0; } if (first>last){ return mid; } if (key.equals(word.get(mid))){ return mid; } if(word.get(mid).compareTo(key)>0){ return binarySearchTail(word, key, first, mid-1); } if(word.get(mid).compareTo(key)<0){ return binarySearchTail(word,key,mid+1, last); } else{ return mid; } }
5
public IVPBoolean lessThanOrEqualTo(IVPNumber num, Context c, HashMap map, DataFactory factory) { IVPBoolean result = factory.createIVPBoolean(); map.put(result.getUniqueID(), result); boolean resultBoolean = false; if(getValueType().equals(IVPValue.INTEGER_TYPE) && num.getValueType().equals(IVPValue.INTEGER_TYPE)){ resultBoolean = c.getInt(getUniqueID()) <= c.getInt(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE) && num.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) <= c.getDouble(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) <= c.getInt(num.getUniqueID()); }else{ resultBoolean = c.getInt(getUniqueID()) <= c.getDouble(num.getUniqueID()); } } } c.addBoolean(result.getUniqueID(), resultBoolean); return result; }
5
private void notifyConnectionClosed() { if(_dataModelConnection != null){ // hierdurch werden laufende Operationen in der 2. Verbindung unterbrochen, die die folgenden Aktionen blockieren können. // Deswegen am Anfang der Methode ausführen. _dataModelConnection.disconnect(false, ""); } List<DavConnectionListener> connectionListenersCopy = new ArrayList<DavConnectionListener>(_connectionListeners); for(DavConnectionListener davConnectionListener : connectionListenersCopy) { try { davConnectionListener.connectionClosed(this); } catch(Exception e) { _debug.warning("Fehler beim Verarbeiten der connectionClosed-Meldung", e); } } synchronized(_lock) { if(_implicitUnsubscriber != null) { _implicitUnsubscriber.interrupt(); _implicitUnsubscriber = null; } _isConnected = false; _isLoggedIn = false; if(_dataModel instanceof DafDataModel && _dataModelConnection == null) { ((DafDataModel) _dataModel).close(); } if(_subscriptionManager != null) { _subscriptionManager.close(); } if(_cacheManager != null) { _cacheManager.close(); } } DataFactory.forget(getDataModel()); }
8
@Override public PermissionType getType() { return PermissionType.CONSOLE; }
0
public Polynomial add(Polynomial P2) { PolynomialImp result=new PolynomialImp(""); for(Term t1:this.terms){ boolean found=false; for(Term t2:P2){ //sum if the second term is equal to the term in the first one, break if(t1.getExponent()==t2.getExponent()){ found=true; TermImp newTerm = new TermImp(t1.getCoefficient()+t2.getCoefficient(),t1.getExponent()); result.addTerm(newTerm); break; } } //if there is not a term with the same exponent add at the end of the polynomial if(!found){ TermImp newTerm = new TermImp(t1.getCoefficient(),t1.getExponent()); result.addTerm(newTerm); } } //takes care of the terms not added in the second polynomial for(Term t1:P2){ boolean notFound=true; for(Term t2:this.terms){ //checks if it was already added if(t1.getExponent()==t2.getExponent()){ notFound=false; } } //add if exponent not found if(notFound){ TermImp newTerm = new TermImp(t1.getCoefficient(),t1.getExponent()); result.addTerm(newTerm); } } return result; }
8
public static void readFiniteAutomataFromFile(Set<String> states, Set<String> alphabet, List<Element> transitionFunction, StringBuilder startState, Set<String> finalStates) { try { FileInputStream fstream = new FileInputStream("D:\\IdeaProjects\\Compilatoare\\src\\Files\\2.finiteAutomata.txt"); DataInputStream in; in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); Integer n = 0; try { n = Integer.parseInt(strLine); } catch (Exception e) { System.out.println("Not a number!"); } strLine = br.readLine(); String temp[] = strLine.split(" "); for (int i = 0; i < n; i++) { states.add(temp[i]); } strLine = br.readLine(); Integer n2 = 0; try { n2 = Integer.parseInt(strLine); } catch (Exception e) { System.out.println("Not a number!"); } strLine = br.readLine(); String temp2[] = strLine.split(" "); for (int i = 0; i < n2; i++) { alphabet.add(temp2[i]); } strLine = br.readLine(); Integer nt = 0; try { nt = Integer.parseInt(strLine); } catch (Exception e) { System.out.println("Not a number!"); } for (int i = 0; i < nt; i++) { strLine = br.readLine(); String temp3[] = strLine.split(" "); Element element = new Element(temp3[0], temp3[1], temp3[2]); transitionFunction.add(element); } strLine = br.readLine(); startState.append(strLine); strLine = br.readLine(); Integer n3 = 0; try { n3 = Integer.parseInt(strLine); } catch (Exception e) { System.out.println("Not a number!"); } strLine = br.readLine(); String temp3[] = strLine.split(" "); for (int i = 0; i < n3; i++) { finalStates.add(temp3[i]); } in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
9
public DecisionTree parse(File f) throws FileNotFoundException, XMLStreamException { DecisionTree result = null; DecisionTreeNode root = null; String[] labels = null; //Open XML file InputStream is = new FileInputStream(f); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(is); //Read XML while(reader.hasNext()) { if(reader.getEventType() == XMLStreamConstants.START_ELEMENT) { switch(reader.getLocalName()) { case "tree": root = parseNode(reader, labels); break; case "target_labels": //Parse labels labels = new String[reader.getAttributeCount()]; for(int i=0; i < reader.getAttributeCount(); i++) { int labelIndex = Integer.parseInt(reader.getAttributeLocalName(i).substring(1)); labels[labelIndex] = reader.getAttributeValue(i); } break; } } reader.next(); } result = new DecisionTree(root); return result; }
5
@Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { world.render(0, 0); for (GameObject item : items) { item.render(gc, sbg, g); } player.render(gc, sbg, g); cm.render(gc, sbg, g); if(gameOverPopupOpened){ gameOver_popup.draw(0, 0); } else if (gameWonPopupOpened){ gameWon_popup.draw(0, 0); font1.drawString(500, 195, player.starsQuant + ""); font1.drawString(500, 238, Universal.currentVariables.size() + ""); font2.drawString(500, 270, (40 + (player.starsQuant * 20)) - (Universal.currentVariables.size() * 2) + ""); } else if(premioPopupOpened){ premio_popup.draw(0, 0); } // HUD if(hudIsVisible){ switch (player.starsQuant) { case 0: esferas_0.draw(coord_esferasIndicator.x, coord_esferasIndicator.y); break; case 1: esferas_1.draw(coord_esferasIndicator.x, coord_esferasIndicator.y); break; case 2: esferas_2.draw(coord_esferasIndicator.x, coord_esferasIndicator.y); break; case 3: esferas_3.draw(coord_esferasIndicator.x, coord_esferasIndicator.y); break; } stopButton.draw(coord_stopButton.x, coord_stopButton.y); } }
9
@RequestMapping(value = "/{worldId}/{mapId}", method = RequestMethod.GET) @ResponseBody public List<Event> getEventsByWorldAndMap(@PathVariable int worldId, @PathVariable int mapId){ List<Event> result = new ArrayList<Event>(); List<Event> events = data.getEvents(); for(Event event : events) { if(event.getWorldId() == worldId && event.getMapId() == mapId) { result.add(event); } } return result; }
3
private String FTP_response(String data) { Pattern p1 = Pattern.compile("USER"); Matcher m1 = p1.matcher(data); Pattern p2 = Pattern.compile("PUT"); Matcher m2 = p2.matcher(data); if (data == null) return "500 Unknown command\r\n"; else if (m1.find()) return "220 Welcome.\r\n"; else if (m2.find()) return "226 OK\r\n"; else return "200 OK\r\n"; }
3
private void checkMinMaxRelation(final Messager messager, final AnnotationMirror mirror, final AnnotationValue valueMin, final AnnotationValue valueMax) { if (valueMin != null && valueMax != null) { final SourcePosition srcPosition = mirror.getPosition(); final Integer validMinValue = getValidIntegerValue(valueMin); final Integer validMaxValue = getValidIntegerValue(valueMax); if (validMinValue != null && validMaxValue != null && validMinValue > validMaxValue) { messager.printError(srcPosition, "max must be greater then min"); } } }
5
public void configureForSave(OutlinerDocument doc, String protocolName, String currentDirectory) { lazyInstantiate(); // adjust title setDialogTitle("Save: " + protocolName); // adjust approve button setApproveButtonToolTipText("Save file as named"); // Set the Accessory state setAccessory(saveAccessory); // Set the Accessory GUI state. saveLineEndComboBox.setSelectedItem(doc.settings.getLineEnd().cur); saveEncodingComboBox.setSelectedItem(doc.settings.getSaveEncoding().cur); saveFormatComboBox.setSelectedItem(doc.settings.getSaveFormat().cur); // Set the current directory location or selected file. // grab the file's name String currentFileName = doc.getFileName(); // if it's an imported file ... if (PropertyContainerUtil.getPropertyAsBoolean(doc.getDocumentInfo(), DocumentInfo.KEY_IMPORTED)) { // trim any extension off the file name String trimmedFileName = StanStringTools.trimFileExtension(currentFileName); // obtain the current default save format's extension String extension = (Outliner.fileFormatManager.getSaveFormat(doc.settings.getSaveFormat().cur)).getDefaultExtension(); // addemup setSelectedFile(new File(trimmedFileName + "." + extension)); } else { if (!currentFileName.equals("")) { // set up using the filename setSelectedFile(new File(currentFileName)); } else { // use the current directory setCurrentDirectory(new File(currentDirectory)); // start with the window title String title = doc.getTitle(); // obtain the current default save format's extension String extension = (Outliner.fileFormatManager.getSaveFormat(doc.settings.getSaveFormat().cur)).getDefaultExtension(); // addemup setSelectedFile(new File(title + "." + extension)); } } this.dialogType = JFileChooser.SAVE_DIALOG; }
2
@Override public void parseArgs(String[] args) { if (args.length < 1) usage(null); // Parse command line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-f")) { // List in a file? if ((i + 1) < args.length) fileName = args[++i]; else usage("Option '-f' without file argument"); } else if (args[i].equals("-pc")) { // Use only protein coding genes onlyProteinCoding = true; } else if (args[i].equals("-ud")) { // Expand upstream & downstream if ((i + 1) < args.length) expandUpstreamDownstream = Gpr.parseIntSafe(args[++i]); else usage("Option '-ud' without file argument"); } else if ((genomeVer == null) || genomeVer.isEmpty()) { // Genome version genomeVer = args[i]; } else geneIds.add(args[i]); } }
9
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
public Map<Integer, Double> getRankedTagList(int userID, int resID) { Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>(); this.tagRecencies = new ArrayList<Map<Integer, Double>>(); // TODO: calculate your recommendations here and return the top-10 (=REC_LIMIT) tags with probability value // have also a look on the other calculator classes! if (this.userMaps != null && userID < this.userMaps.size()) { Map<Integer, Double> userMap = this.userMaps.get(userID); Map<Integer, Double> recMap = this.tagRecencies.get(userID); for (Map.Entry<Integer, Double> entry : userMap.entrySet()) { resultMap.put(entry.getKey(), entry.getValue().doubleValue() * recMap.get(entry.getKey()).doubleValue()); } } if (this.resMaps != null && resID < this.resMaps.size()) { Map<Integer, Double> resMap = this.resMaps.get(resID); for (Map.Entry<Integer, Double> entry : resMap.entrySet()) { Double val = resultMap.get(entry.getKey()); resultMap.put(entry.getKey(), val == null ? entry.getValue().doubleValue() : val.doubleValue() + entry.getValue().doubleValue()); } } Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(); Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap)); sortedResultMap.putAll(resultMap); int count = 0; for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) { if (count++ < 10) { returnMap.put(entry.getKey(), entry.getValue()); } else { break; } } return returnMap; //Ahora calculo en base a TF-IDF //DecimalFormat df = new DecimalFormat("0.0000"); // Obtener el perfil del usuario con el "Me Gusta" para cada etiqueta //SparseVector userVector = makeUserVector(userID); // Loop sobre cada elemento requerido y su puntuación // El dominio del vector de salida es lo que se conseguirá //for (VectorEntry e: resID.fast(VectorEntry.State.EITHER)) //{ // El Score del item representado por e. // Obtener el vector del item para este item en particular // SparseVector iv = model.getItemVector(e.getKey()); // Se calcula el coseno del item y el perfil del ususario //Se guarda en el vector de salida // double numerator = iv.dot(userVector); // double denominator = iv.norm() * userVector.norm(); // double cosineSimilarity = numerator / denominator; // try // { // double rounded = df.parse(df.format(cosineSimilarity)).doubleValue(); // logger.info("Cos similarity for item {} and user {} is {}", e.getKey(), userID, rounded); // resID.set(e.getKey(), rounded); // } // catch (ParseException e1) // { // logger.error("Error while parsing double", e1); // } //} }
9
public Sound get(String fileName, double volume, double pitch, boolean shouldLoop) throws IOException { fileName = filePath + fileName; SoftReference<SoundData> ref = loaded.get(fileName); SoundData data = ref == null ? null : ref.get(); if (data == null) { loaded.remove(fileName); data = new SoundData(device, fileName); loaded.put(fileName, new SoftReference<SoundData>(data)); } return new Sound(device, data, volume, pitch, shouldLoop); }
2
public boolean hasFinalState(State[] states, Automaton automaton) { for (int k = 0; k < states.length; k++) { if (automaton.isFinalState(states[k])) return true; } return false; }
2
public void followBall() { try { if(!getMem().isObjVisible("ball")) { turn(45); return; } if(getMem().isObjVisible("ball")) { ObjBall ball = getMem().getBall(); if((ball.getDirection() > 5.0) || (ball.getDirection() < -5.0)) { turn(ball.getDirection() * (1 + (5 * getMem().getAmountOfSpeed()))); } if(ballInGoalzone(ball)){ //System.out.println("flag in defendGoal"); defendGoal(ball); } else { //System.out.println("flag in positionGoalie"); positionGoalie(ball); } } } catch (UnknownHostException e) { System.out.println("Error in Goalie.followBall()"); e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7
public void draw() { int leftBound = (int) Math.floor(GLGuru.getXDisplacement() / Object.TILE_SIZE); int rightBound = (int) Math.ceil((GLGuru.getXDisplacement() + ChristmasCrashers.getWindowWidth()) / Object.TILE_SIZE); int bottomBound = (int) Math.floor(GLGuru.getYDisplacement() / Object.TILE_SIZE); int topBound = (int) Math.ceil((GLGuru.getYDisplacement() + ChristmasCrashers.getWindowHeight()) / Object.TILE_SIZE); // ArrayIndexOutOfBoundsException prevention if (leftBound < 0) leftBound = 0; if (rightBound >= WIDTH) rightBound = WIDTH; if (bottomBound < 0) bottomBound = 0; if (topBound >= HEIGHT) topBound = HEIGHT; for (int i = leftBound; i < rightBound; i++) for (int j = bottomBound; j < topBound; j++) if(objects[i][j].getType().getTexture() != null) RenderMonkey.renderTexturedRectangle(i * Object.TILE_SIZE, j * Object.TILE_SIZE, Object.TILE_SIZE, Object.TILE_SIZE, objects[i][j].getType().getTexture()); }
7
public static void main(String[] args) { if (args.length == 0 || (args.length == 1 && args[0].equals("-i"))) { Runnable task = new CalculatorInteractive(); task.run(); } else if (args.length == 1) { Runnable task = new CalculatorBatch(new File(args[0])); task.run(); } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof CoachCarriage)) return false; CoachCarriage other = (CoachCarriage) obj; if (coachNumber != other.coachNumber) return false; return true; }
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Departamento)) { return false; } Departamento other = (Departamento) object; if ((this.idDepartamento == null && other.idDepartamento != null) || (this.idDepartamento != null && !this.idDepartamento.equals(other.idDepartamento))) { return false; } return true; }
5
public void setMediator(Mediator mediator) { this.mediator = mediator; }
0
public static void init(String username, String interfaceName) { instance = new ClientFinder(username, interfaceName); }
0
public static String[] sort(String[] a, int W) { int N = a.length; int R = 256; // extend ASCII alphabet size String[] aux = new String[N]; for (int d = W-1; d >= 0; d--) { // sort by key-indexed counting on dth character // compute frequency counts int[] count = new int[R+1]; for (int i = 0; i < N; i++) count[a[i].charAt(d) + 1]++; // compute cumulates for (int r = 0; r < R; r++) count[r+1] += count[r]; // move data for (int i = 0; i < N; i++) aux[count[a[i].charAt(d)]++] = a[i]; // copy back for (int i = 0; i < N; i++) a[i] = aux[i]; } return a; }
5
protected void cleanUp() { // signal to unpause setPaused(false); // close the mixer (stops any running sounds) Mixer mixer = AudioSystem.getMixer(null); if (mixer.isOpen()) { mixer.close(); } }
1
@Override public int[] getWindowIndices(int idx) { Date beginning = getWindowBounds(idx)[0]; Date end = getWindowBounds(idx)[1]; int first = -1; int last = -1; if (current.get(0).getStart().after(end) || current.get(current.size() - 1).getStart().before(beginning)) return null; for (int i = 0; i < current.size(); i++) { if (current.get(i).getStart().before(beginning)) continue; else if (first < 0) { first = i; } if (current.get(i).getStart().equals(end) || current.get(i).getStart().after(end)) { last = i; break; } } if (first < 0) return null; if (last < 0) { last = current.size(); } return new int[]{first,last}; }
9
public static void recursiveZipDirectory(File sourceFolder, ZipOutputStream zipStream) throws IOException { String[] dirList = sourceFolder.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < dirList.length; i++) { File f = new File(sourceFolder, dirList[i]); if (f.isDirectory()) { recursiveZipDirectory(f, zipStream); continue; } else { FileInputStream input = new FileInputStream(f); ZipEntry anEntry = new ZipEntry(f.getPath()); zipStream.putNextEntry(anEntry); while((bytesIn = input.read(readBuffer)) != -1) zipStream.write(readBuffer, 0, bytesIn); input.close(); } } }
3
public static boolean transform(InstructionContainer ic, StructuredBlock last) { return transformNormal(ic, last) || transformJikesString(ic, last); }
1
private void setupUI() { /* Creates a draw panel that has a background, we do all our drawing on here */ //http://stackoverflow.com/questions/10961023/move-a-jlabel-to-front drawPanel = new DrawPanel(); drawPanel.setLayout(null); try { // Pretty much the cleanest way I've seen this done... drawPanel.setBackgroundImage(new ImageIcon(ImageIO.read(getClass().getResource("resources/mainBackground.png"))).getImage()); } catch (IOException e) { e.printStackTrace(); } setCursor(CURSOR_HAND,false); //set cursor, do not wait drawPanel.setPreferredSize(new Dimension(520, 480)); drawPanel.setMaximumSize(new Dimension(520, 480)); /* Creates a credits panel */ creditsPanel = new DrawPanel(); creditsPanel.setLayout(null); try { // Pretty much the cleanest way I've seen this done... creditsPanel.setBackgroundImage(new ImageIcon(ImageIO.read(getClass().getResource("resources/creditsPanel.png"))).getImage()); } catch (IOException e) { e.printStackTrace(); // This doesn't print the error correctly... } creditsPanel.setPreferredSize(new Dimension(520, 480)); creditsPanel.setMaximumSize(new Dimension(520, 480)); creditsPanel.addMouseListener(new MouseListener(){ //glass pane window for credits @Override public void mouseClicked(MouseEvent arg0) { getGlassPane().setVisible(false); } @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} }); setGlassPane(creditsPanel); getGlassPane().setVisible(false); /* Set the application icon [windows only]*/ ArrayList<Image> icons = new ArrayList<Image>(3); try { icons.add(new ImageIcon(ImageIO.read(getClass().getResource("resources/icon32.png"))).getImage()); icons.add(new ImageIcon(ImageIO.read(getClass().getResource("resources/icon16.png"))).getImage()); } catch (IOException e1) { e1.printStackTrace(); } setIconImages(icons); /* Creates a directions/status panel at the bottom */ JPanel directionsPanel = new JPanel(); directionsPanel.setLayout(new BoxLayout(directionsPanel,BoxLayout.LINE_AXIS)); directionsPanel.add(Box.createHorizontalGlue()); directionsLabel = new JLabel("Select new game from the actions menu to start a new game."); directionsLabel.setHorizontalAlignment(SwingConstants.CENTER); // Centers the text directionsLabel.setForeground(Color.WHITE); directionsPanel.add(directionsLabel); directionsPanel.add(Box.createHorizontalGlue()); directionsPanel.setBackground(new Color(32,21,6)); //Draw circles to look like pieces. These pieces however will do nothing, as this is the title screen. pieces = new GamePieceButton[3][8]; snapCoordinates = coordinates.getSnapCoordinates(); for(int r = 0; r < 3; r++){ for(int p = 0; p < 8; p++){ Point pt = snapCoordinates[r][p]; pieces[r][p] = new GamePieceButton(new GamePiece(r,p), this); pieces[r][p].setBounds(pt.x-15, pt.y-15, 30, 30); //this draws from the top left. snap coordinates returns the centerpoint so move a radius up-left to make it draw properly pieces[r][p].setMode(GamePieceButton.DEMO_MODE); pieces[r][p].addActionListener(this); drawPanel.add(pieces[r][p]); } } add(drawPanel); // Add it to the main Frame //add(creditsPanel); add(directionsPanel, BorderLayout.SOUTH); }
5
@Override public void dec(Integer... a) { // TODO Auto-generated method stub }
0
public boolean isSyncMark(int headerstring, int syncmode, int word) { boolean sync = false; if (syncmode == INITIAL_SYNC) { //sync = ((headerstring & 0xFFF00000) == 0xFFF00000); sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 } else { sync = ((headerstring & 0xFFF80C00) == word) && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if (sync) sync = (((headerstring >>> 10) & 3)!=3); // filter out invalid layer if (sync) sync = (((headerstring >>> 17) & 3)!=0); // filter out invalid version if (sync) sync = (((headerstring >>> 19) & 3)!=1); return sync; }
5
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed int origen = this.cbxeorigen.getSelectedIndex(); int simbolo = this.cbxsimbolo.getSelectedIndex(); int destino = this.cbxedestino.getSelectedIndex(); if (this.rbbefinal.isSelected()) { destino = destino * -1; } this.table_trans.setValueAt(destino, origen, simbolo + 1); this.rbbefinal.setSelected(false); this.cbxeorigen.setSelectedIndex(0); this.cbxsimbolo.setSelectedIndex(0); this.cbxedestino.setSelectedIndex(0); }//GEN-LAST:event_jButton3ActionPerformed
1
static public boolean readBoolean(String strPrompt) { do { try { String strBool = readLineFromConsole(strPrompt).toLowerCase(); if (strBool.equals("s") || strBool.equals("y")) { return true; } else if (strBool.equals("n")) { return false; } } catch (NumberFormatException ex) { Logger.getLogger(Console.class.getName()).log(Level.SEVERE, null, ex); } } while (true); }
5
public String extractConfigSudoku9(Map<String, String> allRequestParams){ Set<String> keys = allRequestParams.keySet(); String[][] orderedValues = new String[9][9]; for (String key: keys){ String value = allRequestParams.get(key); //The strings are expected to be in y<number>x<number> form //In this case we are lucky that the number has only one digit if(key.substring(0,1).equals("y") && key.substring(2,3).equals("x")) { int x = Integer.parseInt(key.substring(3,4)); int y = Integer.parseInt(key.substring(1,2)); orderedValues[y][x] = value; } } String config = ""; for (int y = 0; y < 9; y++){ for(int x = 0; x < 9; x++){ String value = orderedValues[y][x]; if(value == null) value = "0"; if(value.equals("")) value = "0"; config += value; } } return config; }
7
public static int cal(int x){ if(x < 0){ return 0; }else{ return x + cal(x); } }
1
@Override public Response list() throws IOException { if(currentUser != null) { return new ListResponse(proxyCli.getCombinedFileList()); } return new MessageResponse("You have to login first to perform this action!"); }
1
@Id @GenericGenerator(name = "generator", strategy = "increment") @GeneratedValue(generator = "generator") @Column(name = "box_id") public int getBoxId() { return boxId; }
0