text
stringlengths
14
410k
label
int32
0
9
public boolean isStrike() { if (first == 10) return true; else return false; }
1
private static SecretKey getSecretKey(String publicKey, String privateKey) throws Exception { // 初始化公钥 byte[] pubKeyBytes = SecurityCoder.base64Decoder(publicKey); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); // 初始化私钥 byte[] priKeyBytes = SecurityCoder.base64Decoder(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyBytes); Key priKey = keyFactory.generatePrivate(pkcs8KeySpec); KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory .getAlgorithm()); keyAgree.init(priKey); keyAgree.doPhase(pubKey, true); // 生成本地密钥 SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM); return secretKey; }
0
private boolean updateSession(Response re) { byte[] token = re.getSessionToken(); try { if (token == null || token.length == 0) { throw new NotLoggedInException("Your session has expired. Please log in again to continue."); } if (userProfile != null) { if (!Arrays.equals(token, userProfile.getSessionToken())) { userProfile.setSessionToken(token); } else { // If the new token is the same as the old one, something went wrong throw new NotLoggedInException("Your session appears to be invalid. You have been logged out for security reasons. Please log in again to continue"); } } else if (userId != null) { // If the user profile isn't populated, but the user id is known // then call an update request, and pull in the new profile data // from the response UpdateProfileRequest rq = new UpdateProfileRequest(); rq.setSenderId(userId); rq.setSessionToken(token); boolean success = Comms.sendMessage(rq); if (success) { // Receive response and handle try { UpdateProfileResponse res = (UpdateProfileResponse) Comms.receiveMessage(); handle(res); } catch (ClassCastException ex) { Alerter.getHandler().severe("Profile Update Failure", "Response from server was malformed. Please try again."); } } } else { throw new NotLoggedInException("You don't appear to have logged in to the system. Please try again."); } return true; } catch (NotLoggedInException ex) { showLogin(); Alerter.getHandler().warning("Session Timeout", ex.getMessage()); return false; } }
8
private void leave(StateEnum state, final C context) { if (context.isTerminated()) { return; } try { if (isTrace()) log.info("when leave %s for %s <<<", state, context); handlers.callOnStateLeaved(state, context); if (isTrace()) log.info("when leave %s for %s >>>", state, context); } catch (Exception e) { doOnError(new ExecutionError(state, null, e, "Execution Error in [whenLeave] handler", context)); } }
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String for which page to forward to (assigned after switch) String goToThisPage = null; // Get parameter String director = request.getParameter("director"); /////////////////////////////////////////////////////////// // !! Important Note !! // // You would probably have the logic for determining // which web page to go to in its own class, not all // gummed up in here. But for the tutorial I keep it // in here. /////////////////////////////////////////////////////////// // Check if parameter is null, ie, was not supplied. if(director == null){ director = DirectorEnums.NO_VALUE.name(); // Assign String name of an enum. } // Convert parameter to uppercase (Enum.ValueOf() uses uppercase argument) director = director.toUpperCase(); // Define outside of try-catch DirectorEnums enumDirector; // Get enum associated with parameter try{ enumDirector = DirectorEnums.valueOf(director); // Attempts to return Enum constant given a String argument. }catch (IllegalArgumentException e){ enumDirector = DirectorEnums.INCORRECT_VALUE; // If String not in enum set, assign an enum from the set. } // Switch statement using enum switch (enumDirector) { case ABOUT: goToThisPage = "/Video_15_about.jsp"; break; // These cases lumped together because individual pages were not created for each of them. case ERROR: case INCORRECT_VALUE: case NO_VALUE: goToThisPage = "/Video_15_error.jsp"; break; case INDEX: goToThisPage = "/index.jsp"; break; case LOGIN: goToThisPage = "/Video_15_login.jsp"; break; default: goToThisPage = null; break; } /* * The method of forwarding taught in Video #12: * * request.getRequestDispatcher(goToThisPage).forward(request, response); * * John wants to show another way this time: */ getServletContext().getRequestDispatcher(goToThisPage).forward(request, response); }
8
@Override public boolean validGameID(int id){ if(id >= 0 && id < gameModels.size()){ return true; } else return false; }
2
private void check(File f, String[] splits, int i, String file) throws IOException{ if(splits.length-1==i){ String s = splits[i]; s = "\\Q"+s+".xsm\\E"; final Pattern pattern = Pattern.compile(s.replace("*", "\\Q.*\\E").replace("?", "\\Q.\\E")); File[] files = f.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if(pathname.isFile()){ return pattern.matcher(pathname.getName()).matches(); } return false; } }); for(File f2:files){ String file2; String n = f2.getName(); int index = n.lastIndexOf('.'); if(index!=-1){ n = n.substring(0, index); } if(file==null){ file2 = n; }else{ file2 = file + "." + n; } if(compiled.contains(file2)) continue; compiled.add(file2); processFile(file, file2, f2); } }else{ f = new File(f, splits[i]); if(file==null){ file = splits[i]; }else{ file += "."+splits[i]; } if(f.exists()){ check(f, splits, i+1, file); } } }
8
@Override public Card turn(Card[] table, int stepNum) { Iterator<Card> iterBatchOnHand; Card card; // Мы ходим первыми? if (stepNum == 0) { // Мы назначали козырь? if (getTrumpSetterFlag()) { // Ходим любой return batchOnHand.remove(); } else { // Не назначали козыря, ходим простой картой for (int i = 0; i < batchOnHand.size(); i++) { if (!IsItTrump(batchOnHand.get(i), trump)) { card = batchOnHand.get(i); batchOnHand.remove(i); return card; } } // Обычной карты не нашли, ходим любой return batchOnHand.remove(); } } else { // Первый ход был по козырю ? if (IsItTrump(table[0], trump)) { // если по козырю, тогда перебираем все карты и смотрим, есть ли // в колоде козырь iterBatchOnHand = batchOnHand.iterator(); while (iterBatchOnHand.hasNext()) { // козырь нашелся? card = iterBatchOnHand.next(); if (IsItTrump(card, trump)) { // если да,ходим ломаем цикл batchOnHand.remove(card); return card; } } // если козырь так и не нашли ходим первой return batchOnHand.remove(); } else { // если не по козырю ходим в масть, если можно, если нет то // ходим любой(наример первой в колоде) iterBatchOnHand = batchOnHand.iterator(); while (iterBatchOnHand.hasNext()) { // масть нашлась? card = iterBatchOnHand.next(); if (suitTest(card, table[0].getSuitId())) { // если да,ходим и ломаем цикл batchOnHand.remove(card); return card; } } // если масть так и не нашли ходим первой return batchOnHand.remove(); } } }
9
public static ArrayList<ItemSet> findRuleSubsets(ItemSet candidates, ArrayList<ItemSet> sets){ ArrayList<ItemSet> allRuleSets = sets; if(!allRuleSets.contains(candidates)){ allRuleSets.add(candidates); } for(int i = 0; i < candidates.getItemSet().size();i++){ ArrayList<Item> subset = new ArrayList<Item>(candidates.getItemSet()); subset.remove(i); ItemSet newSet = new ItemSet(subset); findRuleSubsets(newSet, allRuleSets); } return allRuleSets; }
2
private void initFileList() { fileList = new HashSet<FileModel>(); File folder = new File(dir); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { fileList.add(new FileModel(listOfFiles[i].getName(),0)); } } }
2
private void drawGrid(Graphics g, Tile[][] grid) { for (int i = 0; grid != null && i < grid.length; i++) for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] != null && grid[i][j].getActive()) { Tile current = grid[i][j]; g.setColor(current.getColor()); g.fillRect(current.getX()*32, current.getY()*32, 32, 32); } } }
5
public static void putRandomInput(Comparable[] a) { Random r = new Random(); for (int i = 0; i < a.length; i++) a[i] = Math.abs(r.nextInt()); }
1
public void testFactory_parseDays_String() { assertEquals(0, Days.parseDays((String) null).getDays()); assertEquals(0, Days.parseDays("P0D").getDays()); assertEquals(1, Days.parseDays("P1D").getDays()); assertEquals(-3, Days.parseDays("P-3D").getDays()); assertEquals(2, Days.parseDays("P0Y0M2D").getDays()); assertEquals(2, Days.parseDays("P2DT0H0M").getDays()); try { Days.parseDays("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Days.parseDays("P1DT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } }
2
public void toggleDecodingMethod(int methodID) { if(methodID > 0) { if(!CipherHandler.activeCiphers.containsKey(methodID)) { CipherHandler.activeCiphers.put(methodID, new CipherPanel(methodID).createPanel(this)); } else CipherHandler.activeCiphers.remove(methodID); parent.updateDecoderPanel(); if(isLiveDecode()) parent.executeCiphers(); } }
3
public static void render(){ for(int i = 0; i < ACTIONSLOTS; i++){ GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor3f(0f, 0f, 0f); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY()); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 + 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY()); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 + 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY() + 32 + 4); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 32 + 4); GL11.glEnd(); GL11.glColor3f(0.6f, 0.6f, 0.6f); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY() + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY() + 32 + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 32 + 2); GL11.glEnd(); if(i == selectedSlot){ GL11.glColor3f(0.4f, 0.8f, 0.4f); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY() + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32, Game.PLAYER.getCameraY() + 32 + 2); GL11.glVertex2f(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 32 + 2); GL11.glEnd(); } GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glColor3f(1, 1, 1); if(actionBar[i] != null){ actionBar[i].render(Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32, Game.PLAYER.getCameraY() + 2); int stacks = 0; for (Item item : Inventory.getInventory()) { if(item != null && item.getClass() == actionBar[i].getClass()){ stacks += item.getStacks(); } } if(actionBar[i].isStackable()){ String msg = Integer.toString(stacks); Font.render(msg,Game.PLAYER.getCameraX() + Game.SCREEN_WIDTH / 2 - ACTIONSLOTS*17 + i*2 + i*32 + 32 - 8*msg.length(), Game.PLAYER.getCameraY() + 2); } } if(hoveredItem != null){ Font.render(hoveredItem.getName(), Mouse.getX() + Game.PLAYER.getCameraX(), Mouse.getY() + Game.PLAYER.getCameraY() + 10); } } }
8
private void modifyObjectClass(SootClass cl) { // TODO Auto-generated method stub //add 'implements' relation cl.addInterface(poolObj); //add finalizePoolObject() method SootMethod finalize = new SootMethod("finalizePoolObject", new ArrayList<Type>(), VoidType.v(), Modifier.PUBLIC); cl.addMethod(finalize); JimpleBody body = Jimple.v().newBody(finalize); finalize.setActiveBody(body); Local this_local = Jimple.v().newLocal("this_ref", RefType.v(cl)); body.getLocals().add(this_local); body.getUnits().add(Jimple.v().newIdentityStmt(this_local, Jimple.v().newThisRef(RefType.v(cl)))); body.getUnits().add(Jimple.v().newReturnVoidStmt()); //add initializePoolObject // Set<SootMethod> init_set = new HashSet<SootMethod>(); //add reset method corresponding to every init() for(SootMethod m : cl.getMethods()){ if(m.getName().equals("<init>")) { //init_set.add(m); addResetMethod(m); } } ////getMethod("void <init>()>").retrieveActiveBody()); System.out.println(Scene.v().getSootClass("java.lang.Object").getFields()); for(SootMethod m : Scene.v().getSootClass("java.lang.Object").getMethods()){ // System.out.println(m.retrieveActiveBody()); } }
3
private void printLocationInfo() { String presentCharacters = "Present characters: "; boolean found = false; for (Character character : characters.values()) { if (character.getLocation() == player.getLocation()) { presentCharacters += character.getName() + "; "; found = true; } } if (!found) { presentCharacters = "There doesn't seem to be anybody else here."; } else { presentCharacters = presentCharacters.substring(0, presentCharacters.length() - 2) + "."; } System.out.println("You are " + player.getLocation().getDescription() + "\n" + player.getLocation().getItemsString() + "\n" + presentCharacters + "\n" + player.getLocation().getExitString()); }
3
private void signUpButtonActionPerformed(java.awt.event.ActionEvent evt) { String psw, cpsw; String u_name; String fname; String lname; String emailId; psw = new String(password.getPassword()); cpsw = new String(confirmPsw.getPassword()); u_name = userName.getText(); fname = firstName.getText(); lname = lastName.getText(); emailId = email.getText(); if (u_name.isEmpty()|| fname.isEmpty()|| lname.isEmpty() || emailId.isEmpty() || psw.isEmpty() || cpsw.isEmpty()) { JOptionPane.showMessageDialog(window,"Enter into all the fields","Empty Fileds",JOptionPane.PLAIN_MESSAGE ); } else{ if( psw.equals(cpsw)) { //add a row to the table String[] array = new String[5]; array[0] = u_name; array[1] = psw; array[2] = u_name; array[3] = fname; array[4] = emailId; //System.out.println(array[0] + "\t" + array[1] + "\t" + array[2] + "\t" + array[3] + "\t" + array[4]); // send data to the controller to add it to the model audienceTableController.addRow(array); this.setVisible(false); } else{ JOptionPane.showMessageDialog(window,"Passwords entered are not matching","Incorrect Passwords",JOptionPane.PLAIN_MESSAGE ); } } }
7
static private final void step6() { j = k; if (b[k] == 'e') { int a = m(); if (a > 1 || a == 1 && !cvc(k-1)) k--; } if (b[k] == 'l' && doublec(k) && m() > 1) k--; }
7
private boolean checkSquare(int row,int col,int val) { int rowStart = (-1)*(row % 3); int colStart = (-1)*(col % 3); for(int i = rowStart; i < rowStart+3;i++) { for(int j = colStart; j < colStart+3;j++) { if(b[row+i][col+j] == val) return false; } } return true; }
3
public void loadBoardDimensions(String layoutFile) throws BadConfigFormatException, FileNotFoundException { FileReader reader = new FileReader(layoutFile); Scanner scan = new Scanner(reader); String temp; int lineCount = 0; int cellCount = 0; int cellCount2 = 0; temp = scan.nextLine(); lineCount++; String[] tempLine = temp.split(","); cellCount = tempLine.length; temp = scan.nextLine(); lineCount++; while( scan.hasNextLine() ) { lineCount++; if( scan.hasNextLine() ) { scan.nextLine(); /*String[] tempLine2 = temp.split(","); cellCount2 = tempLine2.length; if (cellCount2 != cellCount) throw new BadConfigFormatException();*/ } } numRows = lineCount; numColumns = cellCount; // System.out.println("loaded board as rows: " + numRows + " & columns: " + numColumns); }
2
public static int toInteger(Object value) { if(value != null && Double.class.isAssignableFrom(value.getClass()) ){ return ((Double)value).intValue(); } else if(value != null && String.class.isAssignableFrom(value.getClass()) ){ String text = (String)value; if( text.isEmpty()){ return 0; } else { if(text.contains(".")){ return Integer.valueOf((text.split("\\."))[0]); } return Integer.valueOf(value.toString()); } } return 0; }
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(BewegungGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BewegungGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BewegungGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BewegungGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BewegungGUI().setVisible(true); } }); }
6
private static Mat generateBoardProjection(Mat boardThreshold, boolean ui) throws VisionException { // Find the polygon enclosing the blue connect four board LinkedList<MatOfPoint> contours = new LinkedList<MatOfPoint>(); Mat hierarchy = new Mat(); Imgproc.findContours(boardThreshold, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0)); int maxContourIndex = 0; double maxArea = 0; for (int i = 0; i < contours.size(); i++) { double area = Imgproc.contourArea(contours.get(i)); if (area > maxArea) { maxArea = area; maxContourIndex = i; } } // Calculate the percent of the image the detected blue area makes up double percentSpace = maxArea / (boardThreshold.width() * boardThreshold.height()) * 100; System.out.println("The board occupies " + Math.round(percentSpace) + "% of the image."); // Throw an exception if the detected blue area is too small if (percentSpace < 20) { throw new VisionException( "A sufficiently large board could not be detected."); } // Find possible border lines of the enclosing polygon Mat newImage = Mat.zeros(boardThreshold.size(), boardThreshold.type()); Imgproc.drawContours(newImage, contours, maxContourIndex, new Scalar( 255)); Mat lines = new Mat(); Imgproc.HoughLines(newImage, lines, 1, Math.PI / 180, 75); LinkedList<Line> detectedLines = new LinkedList<Line>(); for (int i = 0; i < lines.cols(); i++) { double[] info = lines.get(0, i); Line line = new Line(info[0], info[1]); Core.clipLine( new Rect(0, 0, boardThreshold.width(), boardThreshold .height()), line.getPt1(), line.getPt2()); detectedLines.push(line); } System.out.println("There are " + detectedLines.size() + " lines that were detected."); if (ui) { Mat debugImage = originalBoardImage.clone(); Imgproc.drawContours(debugImage, contours, maxContourIndex, new Scalar( 0, 0, 255), 3); for (Line line : detectedLines) { Core.line(debugImage, line.getPt1(), line.getPt2(), new Scalar(0, 255, 0), 3); } showResult(debugImage); } // Get the corners of the polygon and apply the transform Mat corners1 = calculateBorderFromLines(detectedLines); Size resultSize = originalBoardImage.size(); double[] data1 = { 0, 0 }; double[] data2 = { resultSize.width, 0 }; double[] data3 = { resultSize.width, resultSize.height }; double[] data4 = { 0, resultSize.height }; Mat corners2 = new Mat(new Size(4, 1), CvType.CV_32FC2); corners2.put(0, 0, data1); corners2.put(0, 1, data2); corners2.put(0, 2, data3); corners2.put(0, 3, data4); Mat transform = Imgproc.getPerspectiveTransform(corners1, corners2); Mat dst = new Mat(resultSize, originalBoardImage.type()); Imgproc.warpPerspective(originalBoardImage, dst, transform, dst.size()); return dst; }
6
public static void main(String[] args) { riverDB = readCSV ("/home/arno/workspace/CampPlaner/data/river.csv"); System.out.println (riverDB); try { System.out.println ("saving..."); riverDB.write ("riverdb.xml"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Serializer serializer = new Persister(); File file = new File("riverdb.xml"); try { System.out.println ("loading..."); riverDB = serializer.read(RiverDB.class, file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println (riverDB); }
2
public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == e.VK_W) { } if (keyCode == e.VK_S) { } if (keyCode == e.VK_A) { } if (keyCode == e.VK_D) { } }
4
@Override public String toString() { String wString = ""; switch (this) { case ROCK: wString = "R"; break; case PAPER: wString = "P"; break; case SCISSORS: wString = "S"; break; } return wString; }
3
public void testWithFieldAdded_nullField_zero() { MonthDay test = new MonthDay(9, 6); try { test.withFieldAdded(null, 0); fail(); } catch (IllegalArgumentException ex) {} }
1
public String convertHarga(int harga){ // jadi tar kalo 50000 jadi 50.000 dst... // harga = 444; int ribuan[] = new int[10]; int counter=0; String temphasil=""; while(harga/1000!=0){ ribuan[counter] = harga%1000; counter++; //temphasil = temphasil + ribuan+"."; harga = harga /1000; // dicari lagi sisanya } //dimasukin ke string temphasil = harga + "."; for (int i=counter-1;i>=0;i--){ //udah sisa ratusan if(i!=0){ if (ribuan[i]==0){//sisa harga 0 temphasil = temphasil + "000"+"."; }else if (ribuan[i]<10){ // sisa harga satuan temphasil = temphasil + "00"+ribuan[i]+"."; }else if (ribuan[i]<100){ //sisa harga puluhan temphasil = temphasil +"0"+ ribuan[i]+"."; }else{//sisa harga ratusan temphasil = temphasil + ribuan[i]+"."; } }else{ if (ribuan[i]==0){//sisa harga 0 temphasil = temphasil + "000"; }else if (ribuan[i]<10){ // sisa harga satuan temphasil = temphasil + "00"+ribuan[i]; }else if (ribuan[i]<100){ //sisa harga puluhan temphasil = temphasil +"0"+ ribuan[i]; }else{//sisa harga ratusan temphasil = temphasil + ribuan[i]; } } } return temphasil; }
9
public void execute( String line, Map<String, EntityUser> users, Map<String, EntityDocument> documents, ConstantTime constantTime) { this.st = new StringTokenizer(line); this.users = users; this.documents = documents; String commandName = st.nextToken(); if (commandName.equals(SET_USER_INFO)) { user = getUser(st.nextToken()); userType = UserType.valueOf(st.nextToken().toUpperCase()); time = Long.parseLong(st.nextToken()); constantTime.setNanoTime(time); EntityUser newUserType = new EntityUser(); newUserType.setType(userType); new SetUserInfoImpl(user.getId(), newUserType).genLoad(); } else if (commandName.equals(VOTE_USER)) { voter = getUser(st.nextToken()); delegate = getUser(st.nextToken()); voteUserDecision = VoteUserDecision.valueOf(st.nextToken().toUpperCase()); time = Long.parseLong(st.nextToken()); Id voterId = voter.getId(); Id delegateId = delegate.getId(); constantTime.setNanoTime(time); new VoteUserImpl(voterId, delegateId, voteUserDecision).genLoad(); } else if (commandName.equals(GET_USER_INFO)) { user = getUser(st.nextToken()); showVotes = Boolean.parseBoolean(st.nextToken()); votesTime = Long.parseLong(st.nextToken()); userResult = readUserResult(); Id userId = user.getId(); GetUserInfoResult result = new GetUserInfoImpl(userId, showVotes, votesTime).genLoad(); simplifyResult(result, userResult); Assert.assertEquals(userResult, result); } else if (commandName.equals(VOTE_DOCUMENT)) { voter = getUser(st.nextToken()); document = getDocument(documents, st.nextToken()); voteDocumentDecision = VoteDocumentDecision.valueOf(st.nextToken().toUpperCase()); } else if (commandName.equals(GET_DOCUMENT_INFO)) { document = getDocument(documents, st.nextToken()); showVotes = Boolean.parseBoolean(st.nextToken()); votesTime = Long.parseLong(st.nextToken()); documentResult = readDocumentResult(); } }
5
public static boolean isInputPressed(GameContainer container, List<Integer> input) { for (Integer key : input) { if (container.getInput().isKeyPressed(key)) { return true; } } return false; }
2
public List<String> findStrings(String expr) throws XPathExpressionException { List<String> strings = new ArrayList<String>(); NodeList nodes = findNodes(expr); for(int i=0; i<nodes.getLength(); i++) { strings.add(nodes.item(i).getNodeValue()); } return strings; }
1
public void setCommandButtonFontstyle(Fontstyle fontstyle) { if (fontstyle == null) { this.buttonComFontStyle = UIFontInits.COMBUTTON.getStyle(); } else { this.buttonComFontStyle = fontstyle; } somethingChanged(); }
1
public void updateTeam(String newId) { if (id != null) { PreparedStatement st = null; String q = "UPDATE team SET id = ?, name = ?, location = ? WHERE id = ?"; try { conn = dbconn.getConnection(); st = conn.prepareStatement(q); st.setInt(1, Integer.valueOf(newId)); st.setString(2, this.name); st.setString(3, this.location); st.setInt(4, this.id.intValue()); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); st.close(); } catch (SQLException e) { System.out.println("Unable to close connection"); } } } else { System.out.println("Unable to update team because id is null"); } }
3
@Override public List<AdminNotice> getNoticeList() { log.debug("get admin notice list"); Connection conn = null; Statement statement = null; ResultSet rs = null; ArrayList<AdminNotice> list = new ArrayList<AdminNotice>(); StringBuilder sql = new StringBuilder(); sql.append(" select note_id, note_type, note_msg, note_usr, note_dt "); sql.append(" from admin_notice "); sql.append(" order by note_dt desc "); try { conn = DataSource.getInstance().getConnection(); statement = conn.createStatement(); log.debug(sql.toString()); rs = statement.executeQuery(sql.toString()); while (rs.next()) { AdminNotice note = new AdminNotice(); note.setNoteId(rs.getLong("note_id")); note.setNoteType(rs.getString("note_type")); note.setNoteMsg(rs.getString("note_msg")); note.setNoteUsr(rs.getInt("note_usr")); note.setNoteDt(rs.getDate("note_dt")); list.add(note); } } catch (Exception e) { log.error("failed to get admin notice", e); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) {} } if (statement != null) { try { statement.close(); } catch (Exception e) {} } if (conn != null) { try { conn.close(); } catch (Exception e) {} } } return list; }
8
public static void main(String[] args) { // LinkedHashMap<Integer, Compra> compras = new LinkedHashMap<>(); // compras.put(1, new Compra(1,2,"bolis")); // compras.put(2, new Compra(2,4,"pera")); // compras.put(3, new Compra(3,8,"gafas")); LinkedHashMap<Integer, Persona> personas = new LinkedHashMap<>(); // personas.put(1, new Persona(1,"Auri")); // personas.put(2, new Persona(2,"Kvothe")); FicherosDatos fd = new FicherosDatos(); //fd.guardarCompra("1compras", compras); //fd.escribirPersona("prueba.xml", personas); //personas=fd.leerPersonaXStream("prueba.xml"); for (Persona p: personas.values()) { System.out.println(p); } }
1
public void run() { String command; try { while (true) { command = input.readLine(); if (command.startsWith("MOVE")) { System.out.println(command); //TODO make the split command more readable if (legalMove(Integer.parseInt(command.split(" ")[1]), this)) { output.println("LEGAL_MOVE"); checkEndOfGame(); } else { output.println("MESSAGE Illegal move"); } } else if (command.startsWith("RESET")) { reset(); } } } catch (IOException e) { e.printStackTrace(); } }
5
public static void main(String[] args){ int sum=0; for(int i=2;i<1e7;i++){ int dsum=0; for(char c:Integer.toString(i).toCharArray()){ dsum+=Math.pow(Integer.parseInt(""+c), 5); } if (dsum==i){ sum+=i; System.out.println(i);} } System.out.println(sum); }
3
public void refresh(Camera camera) { for(GraphicForm gForm : graphForms) gForm.refresh(camera); }
1
public static boolean isBlue(int c) { int r = (c >> 16) & 0xFF; int g = (c >> 8) & 0xFF; int b = c & 0xFF; return (r < 100 && r > 60) && (g < 115 && g > 80) && (b < 215 && b > 190); }
5
public static CtMethod delegator(CtMethod delegate, CtClass declaring) throws CannotCompileException { try { return delegator0(delegate, declaring); } catch (NotFoundException e) { throw new CannotCompileException(e); } }
1
public String getDescription() { if (fullDescription == null) { if (description == null || isExtensionListInDescription()) { fullDescription = description == null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if (extensions != null) { fullDescription += "." + (String) extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", ." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; }
6
public static void main(String[] args){ Set<Long> pent = new HashSet<Long>(); for(long i=1;i<1e4;i++){ pent.add(i*(3*i-1)/2); } Long min = Long.MAX_VALUE; for(Long a : pent){ for(Long b : pent){ if (pent.contains(a+b) && pent.contains(Math.abs(a-b)) && a!=b){ if (Math.abs(a-b) < min){ System.out.println(a + "-" + b); min = Math.abs(a-b); } } } } System.out.println(min); }
7
@Override public Object getValueAt(int rowIndex, int columnIndex) { // Pega o contato referente a linha especificada. Contato contato = linhas.get(rowIndex); switch (columnIndex) { case ID: return contato.getId(); case NOME: return contato.getNome(); case APELIDO: return contato.getApelido(); case DATANASCIMENTO: return contato.getDataNascimento(); case TELEFONERES: return contato.getTelefoneResidencial(); case TELEFONECEL: return contato.getTelefoneCelular(); case CIDADE: return contato.getCidade(); case ESTADO: return contato.getEstado(); default: // Não deve ocorrer, pois só existem 7 colunas throw new IndexOutOfBoundsException("Número excedido de colunas"); } }
8
@Override public void closeWindows() { System.out.println("closeWindows"); }
0
private Secteur chargerUnEnregistrement(ResultSet rs) throws DaoException { try { Secteur secteur = new Secteur(null,null); secteur.setCode(rs.getString("SEC_CODE")); secteur.setLibelle(rs.getString("SEC_LIBELLE")); return secteur; } catch (SQLException ex) { throw new DaoException("DaoSecteur - chargerUnEnregistrement : pb JDBC\n" + ex.getMessage()); } }
1
public boolean run() { Utils.getString("city/index"); Utils.getString("casino/slotmachine"); try { JSONObject data = Utils.getJSON("casino/slotmachineData/0"); // {"jackpot":"192028","fortunes":"990","error":"ok","freispiele":0,"spiele":100,"bet":0} int min = 100; if (modus == 2) { min = 250; } else if (modus == 3) { min = 500; } if (min > Integer.valueOf(data.getString("fortunes"))) { return false; } data = Utils.getJSON("casino/slotmachineData/" + modus); // {"jackpot":192079,"fortunes":890,"oldFortunes":890,"gewinn":0,"gfortunes":0,"error":"ok","freispiele":0,"spiele":99} wonMoney = data.getInt("gewinn"); return true; } catch (JSONException e) { return false; } }
4
public void addScore (final String score) { this.scores.add(score); }
0
private static void performPerHalogenoSubstitution(BuildState state, Fragment perhalogenFrag, Element subBracketOrRoot) throws StructureBuildingException { List<Fragment> fragmentsToAttachTo = findAlternativeFragments(subBracketOrRoot); List<Atom> atomsToHalogenate = new ArrayList<Atom>(); for (Fragment fragment : fragmentsToAttachTo) { FragmentTools.convertSpareValenciesToDoubleBonds(fragment); for (Atom atom : fragment.getAtomList()) { int substitutableHydrogen = calculateSubstitutableHydrogenAtoms(atom); if (substitutableHydrogen > 0 && FragmentTools.isCharacteristicAtom(atom)){ continue; } for (int i = 0; i < substitutableHydrogen; i++) { atomsToHalogenate.add(atom); } } } if (atomsToHalogenate.size() == 0){ throw new RuntimeException("Failed to find any substitutable hydrogen to apply " + perhalogenFrag.getTokenEl().getValue() + " to!"); } List<Fragment> halogens = new ArrayList<Fragment>(); halogens.add(perhalogenFrag); for (int i = 0; i < atomsToHalogenate.size() - 1; i++) { halogens.add(state.fragManager.copyFragment(perhalogenFrag)); } for (int i = 0; i < atomsToHalogenate.size(); i++) { Fragment halogen = halogens.get(i); Atom from = halogen.getOutAtom(0).getAtom(); halogen.removeOutAtom(0); state.fragManager.createBond(from, atomsToHalogenate.get(i), 1); } for (int i = 1; i < atomsToHalogenate.size(); i++) { state.fragManager.incorporateFragment(halogens.get(i), perhalogenFrag); } }
9
public void doBetting(GameVars gv, CustomPoker cp) { boolean ripe = false; int idx = betOffset; int lastPlayerToRaise = -1; while (!ripe) { idx = idx%players.size(); if (idx != -1 && idx == lastPlayerToRaise) { ripe = true; break; } if (lastPlayerToRaise == -1) lastPlayerToRaise = idx; int playerNum = players.get(idx); boolean playerFolded = false; for (int i = 0; i < foldedPlayers.size(); ++i) if (playerNum == foldedPlayers.get(i)) playerFolded = true; if (!playerFolded) { int choice = cp.whatAction(gv, this, playerNum); if (choice == CustomPoker.RAISE) lastPlayerToRaise = idx; } ++idx; } removeFoldedPlayers(); System.out.println("Pot's ripe! "+totalMoney+" gold"); }
8
@EventHandler public void CaveSpiderJump(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getCaveSpiderConfig().getDouble("CaveSpider.Jump.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getCaveSpiderConfig().getBoolean("CaveSpider.Jump.Enabled", true) && damager instanceof CaveSpider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getCaveSpiderConfig().getInt("CaveSpider.Jump.Time"), plugin.getCaveSpiderConfig().getInt("CaveSpider.Jump.Power"))); } }
6
public static void sayit(int tc,String msg){ String tmsg[]=msg.split("<4;2>0:"); String player = tmsg[0]; String capplayer=player; player=player.toLowerCase().trim(); String u1=GosLink.prps("muser1"); String u2=GosLink.prps("muser2"); if (TC1.ghost ==1 || TC2.ghost == 1){tmsg[1]=tmsg[1]+"\n";} if (!player.equals(u1.toLowerCase())){ if (!player.equals(u2.toLowerCase())){ if (tc == 1){ dw.append("Server 2: "); TC2.write("gos "+capplayer+": "+tmsg[1].trim());} else{ dw.append("Server 1: " ); TC1.write("gos "+capplayer+": "+tmsg[1].trim());} } } }
5
private ITaggedValue getTaggedValue(String tagKey, boolean isCreateIfNotExist) { ITaggedValue ret = null; boolean isInTransaction = TransactionManager.isInTransaction(); try { ProjectAccessor projectAccessor = ProjectAccessorFactory.getProjectAccessor(); IModel project = projectAccessor.getProject(); for (ITaggedValue ite : project.getTaggedValues()) { if (ite.getKey().equalsIgnoreCase(tagKey)) { ret = ite; break; } } if (ret == null && isCreateIfNotExist) { if (!isInTransaction) TransactionManager.beginTransaction(); ret = projectAccessor.getModelEditorFactory().getBasicModelEditor() .createTaggedValue(project, tagKey, ""); if (!isInTransaction) TransactionManager.endTransaction(); } } catch (Exception exp) { exp.printStackTrace(); if (!isInTransaction && TransactionManager.isInTransaction()) { TransactionManager.abortTransaction(); } } return ret; }
9
private void tryToCookIt(final Order o) { EnumItemType food = o.choice; if(mRole.mItemInventory.get(food) < mItemThreshold) { if(!mRole.mHasCreatedOrder.get(food)) { mRole.mItemsDesired.put(food,baseNeed); } } if(mRole.mItemInventory.get(food) == 0) { print("Out of choice " + food); o.waiter.msgOutOfFood(o.choice.toString(), o.table); orders.remove(o); if(!mRole.mHasCreatedOrder.get(food)) { mRole.mItemsDesired.put(food,baseNeed); } return; } print("Cooking " + o.choice); o.s = OrderState.Cooking; for(int i=1;i<=NGRILLS;i++) { if(!grills.get(i)) { o.n = i; grills.put(i, true); break; } } if(o.n == 0) o.n = 1; DoGoToGrill(o); DoAddFoodItem(o); cookingTimer.schedule(new TimerTask() { //runs a new timer to "cook" the food public void run() { msgOrderDone(o); } },mCookTimes.get(food)); mRole.mItemInventory.put(food,mRole.mItemInventory.get(food)-1); }
7
private boolean calculateVelocities() { boolean end1 = true, end2 = true; for (Point p : frontier.innerBorder) { velocities[p.x][p.y] = calculateVelocity(p); if (end1 && velocities[p.x][p.y] < 0) { end1 = false; } } for (Point p : frontier.outerBorder) { velocities[p.x][p.y] = calculateVelocity(p); if (end2 && velocities[p.x][p.y] > 0) { end2 = false; } } // System.out.println(end1 + " " + end2); return end1 && end2; }
7
public void visitJumpInsn(final int opcode, final Label label) { buf.setLength(0); buf.append(tab2).append(OPCODES[opcode]).append(' '); appendLabel(label); buf.append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitJumpInsn(opcode, label); } }
1
public ResultatenScherm(final Spel spel) { ArrayList<GekozenAntwoord> gekozenAntwoorden = spel.getGekozenAntwoorden(); setBackground(new Color(43, 43, 43)); setBorder(null); setLayout(new MigLayout("", "[grow][77px][grow]", "[grow][20px,growprio 50,grow][grow]")); JPanel panel = JPanelFactory.createBackgroundJPanel(); add(panel, "cell 1 1,grow"); panel.setLayout(new MigLayout("", "[grow,fill][95px]", "[20px,growprio 50,grow]")); panel_1 = JPanelFactory.createTransparentJPanel(); panel.add(panel_1, "cell 1 0,grow"); panel_1.setLayout(new MigLayout("", "[95px][90px]", "[20px,growprio 50,grow][20px]")); JLabel dtrpnScore = new JLabel(); panel_1.add(dtrpnScore, "cell 0 0 2 1,grow"); dtrpnScore.setBackground(new Color(0, 0, 0, 0)); dtrpnScore.setForeground(Color.BLACK); int aantalGoed = 0; int aantalFout = 0; for (GekozenAntwoord gk : gekozenAntwoorden) if (gk.isGoed()) aantalGoed++; else aantalFout++; Vraag vraag = spel.getHuidigeVraag(); int jokers = vraag.getHoeveelJokersGebruikt(); StringBuilder builder = new StringBuilder(); builder.append("<html>Aantal <span style=\"color: green; font-weight:bold;\">goed</span>: "); builder.append(aantalGoed); if (jokers > 0) builder.append("<b> + " + Math.min(aantalFout, jokers) + "</b>"); builder.append("<br/>"); builder.append("Aantal <span style=\"color: red; font-weight:bold;\">fout</span>: "); builder.append(aantalFout); builder.append("<br/>"); builder.append("Hoeveel goed hebben: "); builder.append(spel.getHoeveelGoedVerplicht()); builder.append("<br/>"); builder.append("Jokers gebruikt: "); builder.append(vraag.getHoeveelJokersGebruikt()); builder.append("<br/>"); builder.append("Jokers over: "); builder.append(spel.getJokerAantal()); builder.append("<br/>"); builder.append("Score: "); builder.append(spel.getEindScore()); builder.append(", tijd: "); builder.append(spel.getTimer().getTime()); builder.append(" sec"); if (!spel.magDoorspelen()) builder.append("<br /><br /><b>Je hebt verloren.</b>"); else if (spel.moetDoorspelen()) builder.append("<br /><br /><b>Je moet doorspelen.</b>"); builder.append("</html>"); dtrpnScore.setText(builder.toString()); NiceButton btnStoppen = new NiceButton("Stoppen"); NiceButton btnNewButton = new NiceButton("Verder"); btnStoppen.setEnabled(!spel.moetDoorspelen()); panel_1.add(btnStoppen, "cell 0 1,grow"); panel_1.add(btnNewButton, "cell 1 1,grow"); btnNewButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { spel.volgendeVraag(); } }); btnStoppen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { spel.eindigSpel(); } }); onderdelen = JPanelFactory.createTransparentJPanel(); panel.add(onderdelen, "cell 0 0,alignx left,growy"); onderdelen.setLayout(new MigLayout("", "[200px:n,grow,fill][10px][200px:n,grow,fill]", "[20px][20px][20px][20px][20px][20px][20px][20px][20px]")); int i = 0; for (GekozenAntwoord gk : gekozenAntwoorden) { JLabel txt = JLabelFactory.createAntwoordJLabel(gk.getHuidigeOnderdeel().getTekst()); onderdelen.add(txt, "cell 0 " + i + ",grow"); onderdelen.add(JLabelFactory.createAntwoordJLabel("="), "cell 1 " + i + ",grow"); JLabel txtBoolean = JLabelFactory.createAntwoordJLabel(gk.getGekozenOnderdeel().getAntwoord()); txtBoolean.setFont(new Font("Lucida Grande", Font.BOLD, 13)); if (gk.isGoed()) txtBoolean.setForeground(new Color(43, 111, 43)); else if (jokers > 0) { txtBoolean.setForeground(new Color(244, 77, 50)); txtBoolean.setText("<html><s>" + txtBoolean.getText() + "</s></html>"); jokers--; } else txtBoolean.setForeground(Color.RED); onderdelen.add(txtBoolean, "cell 2 " + i + ",grow"); i++; } }
8
public static Matrice getShortestPaths(Matrice mat){ Matrice A = new Matrice(mat.getData()); for(int k=0; k < mat.getNbLines(); k++){ for(int i=0; i< mat.getNbLines(); i++){ for(int j=0; j< mat.getNbColumns(); j++){ if((A.getValueAt(i,k) + A.getValueAt(k,j)) < A.getValueAt(i,j) ) A.setValueAt(i,j, (double) Math.min(mat.getValueAt(i,j),(mat.getValueAt(i,k)+mat.getValueAt(k,j) ) ) ); } } } return A; }
4
@Override public void draw(Graphics2D g) { if(flicker) flickerTimer++; if(flickerTimer > 50){ flickerTimer = 0; flicker = false; } if(flickerTimer % 5 == 0) { super.draw(g); } }
3
@Override public Item swap(Item newItem) { Item temp = null; try{ temp = weaponItem; //weaponItem = null; weaponItem = (WeaponItem) newItem; return temp; }catch(Exception e){ weaponItem = (WeaponItem) temp; temp= null; return newItem; } //return temp; }
1
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) { if (c != null && string != null) { try { return Enum.valueOf(c, string.trim().toUpperCase()); } catch (IllegalArgumentException ex) { } } return null; }
3
public void setHmac(Key key){ Mac hmac = null; try { hmac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { System.err.println("NoSuchAlgorithmException (HmacSHA256 not valid): " + e.getMessage()); } try { hmac.init(key); } catch (InvalidKeyException e) { System.err.println("InvalidKeyException: " + e.getMessage()); } byte[] message = this.toString().getBytes(); if(hmac!=null){ hmac.update(message); byte[] hash = hmac.doFinal(); base64hash = Base64.encode(hash); } }
3
private LLNode exchangeUp(LLNode t) { LLNode left = t.prev.left; LLNode right = t.prev.right; LLNode prev = t.prev.prev; LLNode cleft=t.left; LLNode cright=t.right; int vcheck=t.prev.val; LLNode cprev = t; if(!isEqual(t,left)){ t.left=left; if(t.left!=null){ t.left.prev=t; } }else{ t.left=t.prev; } if(!isEqual(t,right)){ t.right=right; if(t.right!=null){ t.right.prev=t; } }else{ t.right=t.prev; } t.prev.left=cleft; t.prev.right=cright; t.prev.prev=t; t.prev = prev; if(t.prev!=null){ if(t.prev.left.val==vcheck){ t.prev.left=t; }else{ t.prev.right=t; } } return t; }
6
public void setPriceCode(int arg) { switch (arg) { case REGULAR: price = new RegularPrice(); break; case NEW_RELEASE: price = new NewReleasePrice(); break; case CHILDRENS: price = new ChildrensPrice(); break; default: throw new IllegalArgumentException("Incorrect Price Code"); } }
3
private static String testDataToStiring(classifiedData Data){ String out = ""; //Add Cedd data int i = 0; for(i = 0; i < Data.getCEDDData().length; i++){ out = out + Data.getCEDDData()[i] + ","; } // System.out.println("CEDD data added for image " + Data.getImgName() + " is: " + i); //Add FCTH data out = out + Data.getFCTHData()[0]; int j = 1; for(j = 1; j < Data.getFCTHData().length; j++){ out = out +"," + Data.getFCTHData()[j] ; } // System.out.println("FCTH data added for image " + Data.getImgName() + " is: " + j); out = out + ",?"; return out; }
2
public void getInput() { String command; Scanner inFile = new Scanner(System.in); do { this.display(); command = inFile.nextLine(); command = command.trim().toUpperCase(); switch (command) { case "D": gameMenuControl.displayBoard(); break; case "N": gameMenuControl.startNewGame(); break; case "P": gameMenuControl.displayPreferencesMenu(); break; case "R": gameMenuControl.displayStatistics(); break; /*case "H": HelpMenuView helpMenu = Sudoku.getHelpMenu(); helpMenu.getInput(null); break;*/ case "Q": break; default: new SudokuError().displayError("Invalid command. Please enter a valid command."); continue; } } while (!command.equals("Q")); return; }
6
@Override protected void paintComponent(Graphics g){ super.paintComponent(g); g.drawString("test", 0, 0); }
0
private void nextEvent() { if (eventCount >= TOTAL_EVENTS) { state = BanditState.DONE; if (currentUser.isLogging()) { game.log.sendByteBySocket(SocketToParallelPort.TRIGGER_BANDIT_DONE); } } else { eventCount++; if (winCount >= TOTAL_WIN) { state = BanditState.LOSE; loseCount++; } else if (loseCount >= TOTAL_LOSE) { state = BanditState.WIN; winCount++; } else if (score < LOW_SCORE_LIMIT) { state = BanditState.WIN; winCount++; } else if (Library.RANDOM.nextDouble() > winCount / (eventCount + 1.0)) { state = BanditState.WIN; winCount++; } else { state = BanditState.LOSE; loseCount++; } if (state == BanditState.WIN) { currentImage = winImage; if (currentUser.isLogging()) { game.log.sendByteBySocket(SocketToParallelPort.TRIGGER_BANDIT_WIN); } } else { currentImage = loseImage; if (currentUser.isLogging()) { game.log.sendByteBySocket(SocketToParallelPort.TRIGGER_BANDIT_LOSE); } } } }
9
public void dismissBox() { dispose(); // CLIP.stop(); }
0
private void reset(JCheckBoxMenuItem... checkBoxMenuItems) { for (JCheckBoxMenuItem checkBoxMenuItem : checkBoxMenuItems) { checkBoxMenuItem.setState(false); } }
1
@Override public List<Player> findWinner() { sortHands(); // Find the top score List<Player> winners = new ArrayList<Player>(); for (int i = currentPlayers.size() - 1; i >= 0; i--) { if (Hand.getHandValue_OneCard(currentPlayers .get(currentPlayers.size() - 1).getHands().get(0)) == Hand .getHandValue_OneCard(currentPlayers.get(i).getHands() .get(0))) winners.add(currentPlayers.get(i)); } // Give out the pot to the players for (Player winner : winners) winner.collectChips(pot / winners.size()); // Remove any broke players for (Player player : currentPlayers) if (player.getChipCount() < 1) currentPlayers.remove(currentPlayers); gameNumber++; return winners; }
5
public Zone retrieveZone(String zoneName) { if(zones != null) { //Iterate through zones, returning the zone with name specified by //zoneName. Once a zone is returned the method terminates for(int i=0; i< zones.size(); i++) { if(zones.get(i).name == zoneName) return zones.get(i); } } //This is only executed if no zone is found if(Debug.localMouse) System.out.println("No zone of that name found"); return null; }
4
@Override public String toString() { StringBuilder sb = new StringBuilder("User("); boolean first = true; sb.append("firstName:"); if (this.firstName == null) { sb.append("null"); } else { sb.append(this.firstName); } first = false; if (!first) sb.append(", "); sb.append("lastName:"); if (this.lastName == null) { sb.append("null"); } else { sb.append(this.lastName); } first = false; if (!first) sb.append(", "); sb.append("status:"); if (this.status == null) { sb.append("null"); } else { sb.append(this.status); } first = false; if (!first) sb.append(", "); sb.append("id:"); sb.append(this.id); first = false; if (!first) sb.append(", "); sb.append("email:"); if (this.email == null) { sb.append("null"); } else { sb.append(this.email); } first = false; sb.append(")"); return sb.toString(); }
8
boolean isPerpendicularAttackPlacementNotHarming(int position, int dimension, char[] boardElements) { return isAttackPlaceHorizontallyRightNotHarming(position, boardElements, dimension, attackPlacesOnTheRight(position, dimension)) && isAttackPlaceHorizontallyLeftNotHarming(position, boardElements, dimension, attackPlacesOnTheLeft(position, dimension)) && isAttackPlaceVerticallyAboveNotHarming(position, boardElements, dimension, numberOfLinesAbove(position, dimension)) && isAttackPlaceVerticallyBelowNotHarming(position, boardElements, dimension, numberOfLinesBelow(position, dimension, boardElements)); }
3
@BeforeClass public static void beforeClass() { System.out.println("Testing WordReader Started."); _dictionary = new WordReader("/dict4test.txt"); }
0
public static void main(String[] args) { int x = 7; System.out.println("x = " + Integer.toBinaryString(x)); System.out.println("x <<= 1 = " + Integer.toBinaryString(x <<= 1)); System.out.println("x <<= 1 = " + Integer.toBinaryString(x <<= 1)); System.out.println("x <<= 1 = " + Integer.toBinaryString(x <<= 1)); x = 7; System.out.println("x = " + Integer.toBinaryString(x)); System.out.println("x >>= 1 = " + Integer.toBinaryString(x >>= 1)); System.out.println("x >>= 1 = " + Integer.toBinaryString(x >>= 1)); System.out.println("x >>= 1 = " + Integer.toBinaryString(x >>= 1)); }
0
public boolean onCommand(Player player, String[] args) { File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); if(player.hasPermission(getPermission())){ if(args.length < 1){ String notEnoughArgs = Language.getString("Language.Error.Not_enough_args"); UtilSendMessage.sendMessage(player, notEnoughArgs); return true; }if(args.length > 0){ String arenaName = args[0]; if(ArenaManager.getArenaManager().getArenaByName(arenaName) != null){ Arena arena = ArenaManager.getArenaManager().getArenaByName(arenaName); if(arena.getStatus() != Status.JOINABLE || !arena.getPlayers().isEmpty()){ String end = Language.getString("Language.Arena.End"); String succes = Language.getString("Language.Force.Stop").replaceAll("%arena", arenaName); arena.stop(end, Status.JOINABLE); UtilSendMessage.sendMessage(player, succes); return true; }else{ String cantStop = Language.getString("Language.Force.Can_not_stop").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, cantStop); return true; } }else{ String doesntExist = Language.getString("Language.Error.Arena_does_not_exist").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, doesntExist); return true; } } }else{ String notPerm = Language.getString("Language.Error.Not_permission"); UtilSendMessage.sendMessage(player, notPerm); return true; } return true; }
6
public JointAppointmentFinalized(Appointment appt) { this.appt = appt; }
0
public void setHeight(Double height) { this.height = height; }
0
public void performStructureConsistencyVerification(Tile topTile){ int jWidthTop = 0; int kWidthTop = 0; int jWidthBot = 0; int kWidthBot = 0; int total = 0; System.out.println("DATASTRUCTURE CONSISTENCY VERIFICATION"); Tile leftCornerTile = topTile; while(leftCornerTile.leftDown != null){ leftCornerTile = leftCornerTile.leftDown; jWidthTop++; } System.out.println("\tlength of the J/UP edge: " + jWidthTop); Tile rightCornerTile = topTile; while(rightCornerTile.rightDown != null){ rightCornerTile = rightCornerTile.rightDown; kWidthTop++; } System.out.println("\tlength of the K/UP edge: " + kWidthTop); Tile bottomTileLeft = leftCornerTile; while(bottomTileLeft.rightDown != null){ bottomTileLeft = bottomTileLeft.rightDown; kWidthBot++; } System.out.println("\tlength of the K/DOWN edge: " + kWidthBot); Tile bottomTileRight = rightCornerTile; while(bottomTileRight.leftDown != null){ bottomTileRight = bottomTileRight.leftDown; jWidthBot++; } System.out.println("\tlength of the J/DOWN edge: " + jWidthBot); if(bottomTileLeft == bottomTileRight){ System.out.println("\tBottom tile from the left equals the one from the right"); } else { System.out.println("\tBottom tile from the left does NOT equal the one from the right"); } System.out.println("Verifying center up/down linkage"); Tile topToBottomIterator = topTile; int topToBottomCounter = 0; while(topToBottomIterator.down != null){ topToBottomIterator = topToBottomIterator.down; topToBottomCounter++; } if(topToBottomIterator == bottomTile){ System.out.println("downwards-linkage verified in " + topToBottomCounter + " steps."); } else{ System.out.println("downwards-linkage verification failed: failed to reach bottom after " + topToBottomCounter + " steps."); } Tile bottomToTopIterator = bottomTile; int bottomToTopCounter = 0; while(bottomToTopIterator.up != null){ bottomToTopIterator = bottomToTopIterator.up; bottomToTopCounter++; } if(bottomToTopIterator == topTile){ System.out.println("upwards-linkage verified in " + bottomToTopCounter + " steps."); } else { System.out.println("upwards-linkage failed: failed to reach bottom after " + bottomToTopCounter + " steps"); } }
9
public final void setAlias(String name) { if (name != null) { Identifier rep = getRepresentative(); rep.wasAliased = true; rep.alias = name; } }
1
@Test public void testInsert() { int size = 10000; int range = 10000; Random r = new Random(); int[] test = new int[size]; for(int i=0;i<size;i++) test[i] = r.nextInt(range); long start = System.currentTimeMillis(); for(int i=0;i<size;i++) instance.insert(i, test[i]); long end = System.currentTimeMillis(); System.out.println(String.format("(Indexed priority queue)Inserting cost : %d ms", end-start)); PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); start = System.currentTimeMillis(); for(int i=0;i<size;i++) queue.offer(test[i]); end = System.currentTimeMillis(); System.out.println(String.format("(Priority queue)Inserting cost : %d ms", end-start)); int[] test2 = new int[size]; for(int i=0;i<size;i++) test2[i] = r.nextInt(range); start = System.currentTimeMillis(); for(int i=0;i<size;i++) instance.change(i, test[2]); end = System.currentTimeMillis(); System.out.println(String.format("(Indexed priority queue)Changing cost : %d ms", end-start)); int[] res = new int[size]; start = System.currentTimeMillis(); for(int i=0;i<size;i++) res[i] = instance.delMin(); end = System.currentTimeMillis(); System.out.println(String.format("(Indexed priority queue)Deleting cost : %d ms", end-start)); for(int i=1;i<size;i++) if(res[i]<res[i-1]) System.out.println(String.format("Wrong Info: i-1: %d, i: %d", res[i-1],res[i])); }
8
public boolean contains(int x, int y) { return x1 <= x && y1 <= y && x2 >= x && y2 >= y; }
3
public void addScore(int score){ scores.add(score); //Calculates average score int total = 0; for(int s : scores){ total+=s; } if(score < lowscore || lowscore == 0){ lowscore = score; } if(score > highscore){ highscore = score; } //Checks for zero division if(scores.size() != 0){ avgscore = total / scores.size(); }else{ System.out.println("Error calculating average score, arraylist has no values"); } }
5
public ArrayList<ArrayList<Integer>> rangeCombine(int startN, int endN, int k) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); int countInRange = endN - startN + 1; if (startN > endN || countInRange < k) return result; // count in range same as k, only one comb if (countInRange == k) { ArrayList<Integer> newList = new ArrayList<Integer>(); for (int i = startN; i <= endN; i++) { newList.add(new Integer(i)); } result.add(newList); return result; } // choose one, then every data in range should form one list if (k == 1) { for (int i = startN; i <= endN; i++) { ArrayList<Integer> newList = new ArrayList<Integer>(); newList.add(new Integer(i)); result.add(newList); } return result; } for (int i = startN; i <= endN; i++) { ArrayList<ArrayList<Integer>> restComb = rangeCombine(i + 1, endN, k - 1); System.out.println("For node " + i + " Rest Combos are:"); printCombs(restComb); for (int j = 0; j < restComb.size(); j++) { ArrayList<Integer> curRestComb = restComb.get(j); ArrayList<Integer> newComb = new ArrayList<Integer>(); // add cur in the first place newComb.add(new Integer(i)); for (int m = 0; m < curRestComb.size(); m++) { newComb.add(curRestComb.get(m)); } result.add(newComb); } } System.out.println("For node [" + startN + "," + endN + "] All combos are:"); printCombs(result); return result; }
9
protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } }
1
public static URL getCharacterPortraitURL(long characterID, short size) throws ApiException { if(Arrays.binarySearch(characterPortraitSizes, size) < 0) throw new ApiException("Invallid image size: "+Short.toString(size)+". Allowed sizes are: "+Arrays.toString(characterPortraitSizes)); try { return new URL(IMAGE_SERVICE_URL+"/Character/"+Long.toString(characterID)+"_"+Short.toString(size)+".jpg"); } catch (MalformedURLException e) { throw new ApiException("Problem getting character portrait url for characterID: "+Long.toString(characterID)+" with size: "+Short.toString(size), e); } }
2
public static void main(String args[]) throws IOException { System.out.println(" ___ \n" + " / _ \\ \n" + "/ /_\\ \\_ __ __ _ _ __ __ _ _ __ ___ __ _ _ __ \n" + "| _ | '_ \\ / _` | '__/ _` | '_ ` _ \\ / _` | '__|\n" + "| | | | | | | (_| | | | (_| | | | | | | (_| | | \n" + "\\_| |_/_| |_|\\__, |_| \\__,_|_| |_| |_|\\__,_|_| \n" + " __/ | \n" + " |___/ "); System.out.println("MUD Server Version " + version); System.out.println("Starting on port " + port); try { serverSocket = new ServerSocket(port); } catch (IOException e) { System.out.println("Could not listen on port: " + port); System.exit(-1); } System.out.println("Now accepting connections!"); System.out.println("Maximum connections: " + maxConnections); globalVars = new GlobalVars(); mysql = new MySQL(); new Thread(mysql).start(); IRCBot ircbot = new IRCBot(globalVars); new Thread(ircbot).start(); Runnable console = new ConsoleHandler(globalVars, ircbot); new Thread(console).start(); KeepAlive kAlive = new KeepAlive(globalVars); new Thread(kAlive).start(); NPC npc = new NPC(globalVars); new Thread(npc).start(); Environment environment = new Environment(globalVars); new Thread(environment).start(); while (!shutdownServer) { Socket s = serverSocket.accept(); Runnable client = new ClientHandler(globalVars, kAlive, ircbot, environment, s); new Thread(client).start(); } serverSocket.close(); }
2
public boolean InsertarProveedor(Proveedor p){ if (p!=null) { cx.Insertar(p); return true; }else { return false; } }
1
public static void main(String[] args) { if (args.length != 1) { System.err.println("Please input the robot name!"); return; } String[] answer = null; if (args[0].equalsIgnoreCase("Judy")) { answer = JudyAnswer; } else if (args[0].equalsIgnoreCase("Max")) { answer = MaxAnswer; } if (null == answer) { System.err.println("Can not find the robot!"); return; } while (true) { Scanner input = new Scanner(System.in); String question = input.next(); int matchIndex = -1; for (int i = 0; i < questionList.length; i++) { if (questionList[i].equalsIgnoreCase(question)) { matchIndex = i; break; } } if (matchIndex == -1) { System.out.println("No match answer!"); } else { System.out.println(answer[matchIndex]); } if (question.equalsIgnoreCase("Bye")) { System.out.println("The robot exists!"); input.close(); break; } } }
9
public void run() { ReplyMessage sysinfo; try { while(comm.isOpen()) { sysinfo = comm.execute(new SystemStatusRequest()); System.out.println(sysinfo); Thread.sleep(2000); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
@Override public String getColumnName(int column){ String name = "??"; switch (column){ case 0: name ="RaavareID"; break; case 1: name ="Raavare Navn"; break; case 2: name ="Kostpris pr. stk."; break; case 3: name ="Antal Total"; break; case 4: name ="Kostpris Ialt"; break; } return name; }
5
public static final void next(boolean goUp, long[] x, long[] n) { if(goUp == false) { if(!isLeaf(x)) {leftChild(x,n);} else next(true,x,n); } else { if(isRoot(x)) done(n); else { long[] p = {0,0,0,0}; parent(x,p); if(isLeft(x)) {rightChild(p,n);} else next(true,p,n); } } }
4
private void printTaskTrees() { System.out.println("Task Trees:"); for (Iterator iter = taskTrees.iterator(); iter.hasNext(); ) { Tree nextTree = (Tree)iter.next(); Tree.printTree(nextTree); } }
1
@Override public void add(Task taskBean) { try { connection = getConnection(); ptmt = connection.prepareStatement("INSERT INTO Task(description, title, id_owner) VALUES(?,?,?);"); ptmt.setString(1, taskBean.getDescription()); ptmt.setString(2, taskBean.getTitle()); ptmt.setInt(3, taskBean.getIdOwner()); ptmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(TaskDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
5
public CacheIndice(RandomAccessFile dataFile, RandomAccessFile indexFile, int id) { this.maxFileSize = 99999999; this.id = id; this.dataFile = dataFile; this.indexFile = indexFile; try { for (int i = 0; i < indexFile.length() / 6L; i++) { byte[] data = null; data = get(i); if (data != null) this.files.add(new ByteArray(data)); else this.files.add(null); } } catch (IOException e) { e.printStackTrace(); } }
3
public static void main(String[] args) { String use = ""; LookAndFeelInfo[] available = UIManager.getInstalledLookAndFeels(); for(LookAndFeelInfo info : available) { if(info.toString().contains("Nimbus")) { use = info.toString(); } } try { UIManager.setLookAndFeel(use); } catch (ClassNotFoundException ex) {} catch (InstantiationException ex) {} catch (IllegalAccessException ex) {} catch (UnsupportedLookAndFeelException ex) {} //new LoginScreen(); new MainGUI(new User(1)); }
6
private static void parseValueElement(Element element, ConfigurableEmitter.Value value) { if (element == null) { return; } String type = element.getAttribute("type"); String v = element.getAttribute("value"); if (type == null || type.length() == 0) { // support for old style which did not write the type if (value instanceof SimpleValue) { ((SimpleValue) value).setValue(Float.parseFloat(v)); } else if (value instanceof RandomValue) { ((RandomValue) value).setValue(Float.parseFloat(v)); } else { Log.warn("problems reading element, skipping: " + element); } } else { // type given: this is the new style if (type.equals("simple")) { ((SimpleValue) value).setValue(Float.parseFloat(v)); } else if (type.equals("random")) { ((RandomValue) value).setValue(Float.parseFloat(v)); } else if (type.equals("linear")) { String min = element.getAttribute("min"); String max = element.getAttribute("max"); String active = element.getAttribute("active"); NodeList points = element.getElementsByTagName("point"); ArrayList<Vector2f> curve = new ArrayList<Vector2f>(); for (int i = 0; i < points.getLength(); i++) { Element point = (Element) points.item(i); float x = Float.parseFloat(point.getAttribute("x")); float y = Float.parseFloat(point.getAttribute("y")); curve.add(new Vector2f(x, y)); } ((LinearInterpolator) value).setCurve(curve); ((LinearInterpolator) value).setMin(Integer.parseInt(min)); ((LinearInterpolator) value).setMax(Integer.parseInt(max)); ((LinearInterpolator) value).setActive("true".equals(active)); } else { Log.warn("unkown type detected: " + type); } } }
9
public static void printPokerCombInOrder(int minRank, int maxRank) { int hand[] = new int[5]; int answerHand[][] = new int[2598960][5]; double maxValue = maxRank * Math.pow(13, 5); double minValue = minRank * Math.pow(13, 5); System.out.println("max Value: " + minValue); System.out.println("min Value: " + minValue); boolean array[] = new boolean[52]; for(int i=0; i<5; i++) { array[i] = true; } int stength; int numAnswers = 0; while(array != null) { hand = getHand(array); stength = getHandStrength(hand); if(stength >= minValue && stength <= maxValue) { answerHand[numAnswers] = hand; numAnswers++; } array = PokerUtilityFunctions.getNextCombination(array); } System.out.println("Number of answer: " + numAnswers); //TODO: faster sort function than O(n^2) please? //TODO 2: only calc hand strength once. System.out.println("Sort the answers:"); for(int i=0; i<numAnswers; i++) { for(int j=i; j<numAnswers; j++) { if(getHandStrength(answerHand[i]) > getHandStrength(answerHand[j])) { swap(i, j, answerHand); } } } System.out.println("print answers from weakest to strongest:"); for(int i=0; i<numAnswers; i++) { for(int j=0; j<5; j++) { System.out.print(DeckFunctions.getCardString(answerHand[i][j]) + " "); } System.out.println(); } }
9
public Perceptron getPerceptron(String name) { for (String a : perceptrons.keySet()) { if (name.equalsIgnoreCase(a)) { return perceptrons.get(a); } } return null; }
2