text
stringlengths
14
410k
label
int32
0
9
public Piece(Position position, String couleur) { this.position = position; this.Couleur = couleur; this.Image = ""; this.positionDuMechant = null; this.DejaDeplace = false; this.NombreDeDeplacement = 0; for (int i = 0 ; i < 8 ; i++) for(int j = 0 ; j < 8 ; j++) this.PositionPossible[i][j] = 0; }
2
private void renderWall(double x0, double y0, double x1, double y1) { double xo0 = ((x0 - 0.5) - xCam) * 2; double yo0 = ((y0 - 0.5) - yCam) * 2; double xx0 = xo0 * rCos - yo0 * rSin; double u0 = ((-0.5) - zCam) * 2; double l0 = ((+0.5) - zCam) * 2; double zz0 = yo0 * rCos + xo0 * rSin; double xo1 = ((x1 - 0.5) - xCam) * 2; double yo1 = ((y1 - 0.5) - yCam) * 2; double xx1 = xo1 * rCos - yo1 * rSin; double u1 = ((-0.5) - zCam) * 2; double l1 = ((+0.5) - zCam) * 2; double zz1 = yo1 * rCos + xo1 * rSin; double xPixel0 = (xx0 / zz0 * fov + width / 2); double xPixel1 = (xx1 / zz1 * fov + width / 2); if (xPixel0 >= xPixel1) return; int xp0 = (int) Math.floor(xPixel0); int xp1 = (int) Math.floor(xPixel1); if (xp0 < 0) xp0 = 0; if (xp1 > width) xp1 = width; for (int x = xp0; x < xp1; x++) { double pr = (x - xPixel0) / (xPixel1 - xPixel0); double u = (u0) + (u1 - u0) * pr; double l = (l0) + (l1 - l0) * pr; double zz = (zz0) + (zz1 - zz0) * pr; double yPixel0 = (int) (u / zz * fov + height / 2); double yPixel1 = (int) (l / zz * fov + height / 2); if (yPixel0 >= yPixel1) return; int yp0 = (int) Math.floor(yPixel0); int yp1 = (int) Math.floor(yPixel1); if (yp0 < 0) yp0 = 0; if (yp1 > height) yp1 = height; for (int y = yp0; y < yp1; y++) { double pry = (y - yPixel0) / (yPixel1 - yPixel0); pixels[x + y * width] = 0xff00ff; zBuffer[x + y * width] = 0; } } /* * for (int i = 0; i < 1000; i++) { if (zz > 0) { int xPixel = (int) (xx / zz * fov + width / 2); int yPixel = (int) (yy / zz * fov + height / 2); if (xPixel >= 0 && yPixel >= 0 && xPixel < width && yPixel < height) { zBuffer[xPixel + yPixel * width] = zz * 4; pixels[xPixel + yPixel * width] = 0xff00ff; } } } */ }
8
public static Iterator toIterator(Object value, char delimiter) { if (value == null) { return IteratorUtils.emptyIterator(); } if (value instanceof String) { String s = (String)value; if (s.indexOf(delimiter) > 0) { return split((String)value, delimiter).iterator(); } else { return IteratorUtils.singletonIterator(value); } } else if (value instanceof Collection) { return ((Collection)value).iterator(); } else if (value.getClass().isArray()) { return IteratorUtils.arrayIterator(value); } // else if (value instanceof Iterator) // { // Iterator iterator = (Iterator) value; // IteratorChain chain = new IteratorChain(); // while (iterator.hasNext()) // { // chain.addIterator(toIterator(iterator.next(), delimiter)); // } // return (Iterator) value; // } else { return IteratorUtils.singletonIterator(value); } }
5
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(FormCadastrarPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormCadastrarPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormCadastrarPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormCadastrarPessoa.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 FormCadastrarPessoa().setVisible(true); } }); }
6
public boolean Chk_Pkmn(String str){ boolean bl = false; Reader reader = new Reader(); try{ // pokomon_name.txtからポケモン名を取得. String txt_pkmn[] = reader.txtReader(Const.POKEMONNAME_NORMAL); // 範囲チェック. if (!(util.isRange(str.length(), 0, 10))){ return bl; } // 対象ポケモン名がpokemon_name.txtに存在するか判定. for (String t:txt_pkmn){ if (str.equals(t)){ // 存在する場合はtrue. bl = true; } } }catch(Exception e){ e.printStackTrace(); } return bl; }
4
public DNode getPrev(DNode v) throws IllegalStateException{ if(isEmpty()) throw new IllegalStateException("List is empty"); return v.getPrev(); }
1
public FullGridFactory getGridFactory() { if (inputStream != null) if (gameTypeSelect.getSelectedItem().equals(GameType.RACE_MODE)) return new FileGridFactory(inputStream); else return new FileGridFactoryCTF(inputStream); else if (gameTypeSelect.getSelectedItem().equals(GameType.RACE_MODE)) return new RandomGridFactory(getWidth(), getHeight()); else return new RandomGridFactoryCTF(getWidth(), getHeight()); }
3
void paintFlow(CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha) { int[] opacityData = opacityBuffer.data; int by = srcRect.top; for (int j = dstRect.top; j < dstRect.bottom; j++, by++) { int srcOffset = srcRect.left + by * w; int dstOffset = dstRect.left + j * width; for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++) { int brushAlpha = (brush[srcOffset] & 0xff) * alpha; if (brushAlpha != 0) { int opacityAlpha = Math.min(255 * 255, opacityData[dstOffset] + (255 - opacityData[dstOffset] / 255) * brushAlpha / 255); opacityData[dstOffset] = opacityAlpha; } } } }
3
public DataSource assemble(ServletConfig config) throws ServletException { DataSource _ds = null; String dataSourceName = config.getInitParameter("data-source"); System.out.println("Data Source Parameter" + dataSourceName); if (dataSourceName == null) throw new ServletException("data-source must be specified"); Context envContext = null; try { Context ic = new InitialContext(); System.out.println("initial context " + ic.getNameInNamespace()); envContext = (Context) ic.lookup("java:/comp/env"); System.out.println("envcontext " + envContext); listContext(envContext, ""); } catch (Exception et) { throw new ServletException("Can't get contexts " + et); } // _ds = (DataSource) ic.lookup("java:"+dataSourceName); // _ds = (DataSource) ic.lookup("java:comp/env/" ); try { _ds = (DataSource) envContext.lookup(dataSourceName); if (_ds == null) throw new ServletException(dataSourceName + " is an unknown data-source."); } catch (NamingException e) { throw new ServletException("Cant find datasource name " +dataSourceName+" Error "+ e); } CreateSchema(_ds); return _ds; }
4
@Override public String toString() { return "{id=" + id + ",intencity=" + intencity + ",fw1=" + firewallId1 +",fw2=" + firewallId2 + ",managerFw=" + managerFirewallId + "}"; }
0
private boolean evaluateProposition(Proposition prop){ switch(prop){ case IS_FRONT_CLEAR: return karel.isFrontClear(); case IS_LEFT_CLEAR: return karel.isLeftClear(); case IS_RIGHT_CLEAR: return karel.isRightClear(); case IS_FACING_NORTH: case IS_FACING_SOUTH: case IS_FACING_EAST: case IS_FACING_WEST: return isFacing(prop); case NEXT_TO_BEEPER: return world.getContents(karel.getX(), karel.getY()) == Contents.BEEPER; } throw new IllegalArgumentException("Unknown proposition used"); }
8
public int lengthOfLongestSubstring(String s) { // Start typing your Java solution below // DO NOT write main() function if (s == null) return 0; int length = s.length(); if (length <= 1) { return length; } int[] f = new int[length]; f[0] = 1; int max = 1; Map<Character, Integer> charMap = new HashMap<Character, Integer>(); charMap.put(s.charAt(0), 0); for (int i = 1; i < length; i++) { if (charMap.get(s.charAt(i)) == null) { f[i] = f[i - 1] + 1; } else { int last = charMap.get(s.charAt(i)); if (i - 1 - f[i - 1] > last) { f[i] = f[i - 1] + 1; } else { f[i] = i - last; } } charMap.put(s.charAt(i), i); if (f[i] > max) max = f[i]; } return max; }
6
public static void main(String[] args) { System.out.println("Simple client for financial modeling server"); System.out.println("Trying to connect"); System.out.println(HOSTNAME + ": " + PORT); System.out.println("Run client with params: <HOST> <PORT> <TIME_OUT> for changing default settings"); try { if (args.length == 3) { HOSTNAME = args[0]; PORT = Integer.parseInt(args[1]); CONNECT_TIMEOUT = Integer.parseInt(args[2]); } NioSocketConnector connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(new ClientSessionHandler()); ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT)); future.awaitUninterruptibly(); IoSession session = future.getSession(); session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); } catch (Exception ex) { System.out.println("Oooops!\nSome errors occurred"); System.out.println(ex.fillInStackTrace()); System.exit(-1); } }
2
public String getRepeatedChars(String one, String two) { Map<Character, Integer> charFrequency; StringBuilder builder = new StringBuilder(); String longer; if (one.length() > two.length()) { charFrequency = makeCharFrequencyMap(two); longer = one; } else { charFrequency = makeCharFrequencyMap(one); longer = two; } boolean done = false; String values = keysToString(charFrequency.keySet()); for (int i = 0; i < values.length() ; i++) { if (charFrequency.isEmpty()) { done = true; } else { int frequency = charFrequency.get(values.charAt(i)); int index = longer.indexOf(values.charAt(i)); if (index != -1 && frequency > 0) { builder.append(values.charAt(i)); charFrequency.put(values.charAt(i), --frequency); while (frequency > 0 && !done) { frequency = charFrequency.get(values.charAt(i)); index = longer.indexOf(values.charAt(i), ++index); if (index == -1 || frequency < 1) { done = true; } else { charFrequency.put(values.charAt(i), --frequency); builder.append(values.charAt(i)); } } } charFrequency.remove(values.charAt(i)); } } return builder.toString(); }
9
public static List<MorrisBoard> generateMove(MorrisBoard crtBoard) { List<MorrisBoard> possibleBoard = new ArrayList<MorrisBoard> (); for (int indexMoveFrom = 0; indexMoveFrom < MorrisBoard.TOTALPOS; indexMoveFrom++) { MorrisIntersection intersection = crtBoard.getIntersection(indexMoveFrom); if (intersection.isWhite()) { List<MorrisIntersection> neighbors = intersection.getNeighbor(); for (Iterator<MorrisIntersection> iter = neighbors.iterator(); iter.hasNext(); ) { MorrisIntersection nghb = iter.next(); if (nghb.isEmpty()) { MorrisBoard newBoard = new MorrisBoard(crtBoard); newBoard.setEmpty(indexMoveFrom); int indexMoveTo = nghb.getIndex(); newBoard.addWhite(indexMoveTo); if (newBoard.closeMill(indexMoveTo)) { generateRemove(newBoard, possibleBoard); } else { possibleBoard.add(newBoard); } } } } } return possibleBoard; }
5
public void visit_fneg(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
public static void createUI(String type, String userName) { if (type.equals("Login")) { new LoginUI(); } else { switch (type) { case "Admin": new AdminUI(userName); break; case "SchoolDean": new SchoolDeanUI(userName); break; case "DeptAD": new DeptADUI(userName); break; case "Teacher": new TeacherUI(userName); break; case "Student": new StudentUI(userName); break; default: System.err.println("Error:不存在的界面"); } } }
6
public void testToStandardHours_overflow() { Duration test = new Duration(((long) Integer.MAX_VALUE) * 3600000L + 3600000L); try { test.toStandardHours(); fail(); } catch (ArithmeticException ex) { // expected } }
1
@Override public void actionPerformed(ActionEvent event) { if (event.getSource() == addItem) { String name = itemName.getText(); String key = itemKey.getText(); String type = types[itemType.getSelectedIndex()]; Item item; try { item = new Item(name, key, type); } catch (GameReaderException e) { e.printStackTrace(); return; } boolean sectionFound = false; // Look for existing section. If it exists, add the item for (Section section : sections) { if (section.getKey().equals(sectionKey.getText())) { sectionFound = true; section.addItem(item); break; } } // If the section does not exist, create it and add the item to it if (!sectionFound) { Section section = new Section(sectionKey.getText()); section.addItem(item); sections.add(section); } // Reset text fields itemName.setText("Item Name"); itemKey.setText("Item Key"); } // Create the config file else if (event.getSource() == write) { GlobalAppHandler.getInstance().disableBackButton(); try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(appData.getLocalLocation() + File.separator + "game.wild"))); bw.write("game-name: " + gameName.getText() + "\n"); bw.write("main-key: " + mainKey.getText() + "\n"); for (Section section : sections) { bw.write("section-key: " + section.getKey() + "\n"); for (Item item : section.getItems()) { bw.write("item: " + item.getName() + ", " + item.getKey() + "; " + item.getTypeString() + "\n"); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } GlobalAppHandler.getInstance().enableBackButton(); } }
9
public void expression3() { if(have(Token.Kind.NOT)){ expectRetrieve(Token.Kind.NOT); have(NonTerminal.EXPRESSION3); expression3(); } else if(have(Token.Kind.OPEN_PAREN)){ expectRetrieve(Token.Kind.OPEN_PAREN); have(NonTerminal.EXPRESSION0); expression0(); expectRetrieve(Token.Kind.CLOSE_PAREN); } else if(have(NonTerminal.DESIGNATOR)){ designator(); } else if(have(NonTerminal.CALL_EXPRESSION)){ callExpression(); } else if(have(NonTerminal.LITERAL)){ literal(); } else System.out.println("Something wrong in expression3"); }
5
private boolean inBoundingBox(int mouseX, int mouseY) { int x = this.x + (depth < DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0); int y = this.y + (depth < DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0); int width = this.width - (depth < DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0) + (depth > DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0); int height = this.height - (depth < DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0) + (depth > DEPTH_ON_CLICK ? (int) (depth - DEPTH_ON_CLICK) : 0); return (mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height); }
9
private synchronized int waitSum() { int waitSum = 0; for (int count : waitEntry) waitSum += count; return waitSum; }
1
public static boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; if (target < matrix[0][0] || target > matrix[m - 1][n - 1]) return false; int low = 0; int high = m * n; int mid = 0; while (low <= high) { mid = (low + high) / 2; int val = matrix[mid / n][mid % n]; if (target == val) { return true; } else if (target < val) { high = mid - 1; } else { low = mid + 1; } } return false; }
5
@Override public void init() { /* 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(Fridge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Fridge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Fridge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Fridge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ initComponents(); jButton1.addActionListener(this); jButton2.addActionListener(this); jButton3.addActionListener(this); jButton4.addActionListener(this); jButton5.addActionListener(this); jButton6.addActionListener(this); jButton7.addActionListener(this); jButton8.addActionListener(this); jButton9.addActionListener(this); jButton10.addActionListener(this); jButton11.addActionListener(this); jButton12.addActionListener(this); jButton13.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = jTextField1.getText(); String number = jTextField2.getText(); String age = jTextField3.getText(); String twitterHandle = jTextField4.getText(); People newPerson = new People(name,number,age,twitterHandle); addressBook.addPerson(newPerson); jTextArea1.setText(name + " has been added to the book."); } } ); jButton14.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(jTextField5.getText().matches("")) { searched = addressBook.searchNumber(jTextField6.getText()); } else if(jTextField6.getText().matches("")) { searched = addressBook.searchName(jTextField5.getText()); } else searched = addressBook.searchBoth(jTextField5.getText(), jTextField6.getText()); String text = ""; for(int i = 0; i < searched.getSize(); i++) { People temp = searched.getPerson(i); text = text + temp.outputPerson(temp) + "\r\n"; } jTextArea1.setText(text); } } ); }
9
private List<Opdracht> toonOpdrachtenVanCategorie() { List<Opdracht> tempList = new ArrayList<Opdracht>(); for (Opdracht opdr : opdrachtCatalogusModel.getOpdrachten()) { if (quizCreatieView.getCategorie().getSelectedItem() .equals(OpdrachtCategorie.Aardrijkskunde) && opdr.getOpdrachtCategorie().equals( OpdrachtCategorie.Aardrijkskunde)) { tempList.add(opdr); } else if (quizCreatieView.getCategorie().getSelectedItem() .equals(OpdrachtCategorie.Nederlands) && opdr.getOpdrachtCategorie().equals( OpdrachtCategorie.Nederlands)) { tempList.add(opdr); } else if (quizCreatieView.getCategorie().getSelectedItem() .equals(OpdrachtCategorie.Wetenschappen) && opdr.getOpdrachtCategorie().equals( OpdrachtCategorie.Wetenschappen)) { tempList.add(opdr); } else if (quizCreatieView.getCategorie().getSelectedItem() .equals(OpdrachtCategorie.Wiskunde) && opdr.getOpdrachtCategorie().equals( OpdrachtCategorie.Wiskunde)) { tempList.add(opdr); } } /* * if(quizCreatieView.getCategorie().getSelectedItem() * .equals(OpdrachtCategorie.Alles)){ tempList = opdrachten; } */ return tempList; }
9
@Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String lines[] = value.toString().split(inputDelimiter); String outputLine = ""; boolean checked = false; for (String line : lines) { if (line.equals(target)) checked = true; } if (checked) { for (String aLine : lines) { outputLine = outputLine + aLine + outputDelimiter; } context.write(NullWritable.get(), new Text(outputLine.substring(0, outputLine.length() - 1))); } }
4
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
9
public void run() { playing = true; while (true) { gun.init(); playGame(); if (!playing) break; System.out.print("Would you like to play again [y/n]? (n): "); try { if (IOGeneric.getString().toLowerCase().charAt(0) != 'y') break; } catch (BadInput e) { break; } catch (StringIndexOutOfBoundsException e) { break; } } }
5
public int solution( String input ) { final Deque<Character> stack = new ArrayDeque<Character>(); boolean isProperlyFormed = true; for ( int i = 0; i < input.length(); i++ ) { char character = input.charAt( i ); if ( isOpenBracket( character ) ) { stack.push( character ); } else if ( isClosingBracket( character ) ) { Character openingBracket = stack.peek(); if ( openingBracket == null ) { isProperlyFormed = false; break; } else if ( isFamily( openingBracket, character ) ) { stack.pop(); } else { isProperlyFormed = false; break; } } } return stack.isEmpty() && isProperlyFormed ? 1 : 0; }
7
public void follow() { if(centerX < -95 || centerX > 810){ movementSpeed = 0; } else if (Math.abs(robot.getCenterX()-centerX) < 5){ movementSpeed = 0; } else { if (robot.getCenterX() >= centerX) { movementSpeed = 1; } else { movementSpeed = -1; } } }
4
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
public static void recursive(String strPath) { File file = new File(strPath); if(file.isDirectory() && !file.getName().equals(".svn")) { File[] listfiles = file.listFiles(); for(File f : listfiles) { recursive(f.getAbsolutePath()); } } else if (file.isFile() && (file.getName().contains("Jedis") || file.getName().contains("jedis") || file.getName().contains("Redis") || file.getName().contains("redis")) && file.getName().endsWith("java")) { pomFiles.add(file); } }
9
public void readFrom(InputStream in) throws IOException { byte[] arr = new byte[32]; int[] off = { arr.length, arr.length }; ArrayList<Byte> bytes = new ArrayList<>(); try { if (readInt(in, arr, off) < version) return; int i; while ((i = readInt(in, arr, off)) != -1) { objectIds.add(i); } while (true) { Tile t = new Tile(readInt(in, arr, off), readInt(in, arr, off), readInt(in, arr, off)); int count = 0; while (true) { byte next = nextByte(in, arr, off); bytes.add(next); if (next == LINE_TERM[count]) { if (++count >= LINE_TERM.length) { for (int j = 0; j < LINE_TERM.length; j++) bytes.remove(bytes.size() - 1); break; } } else { count = 0; } } byte[] retArr = new byte[bytes.size()]; int loc = 0; for (byte s : bytes) { retArr[loc++] = s; } data.put(t, retArr); add(t); bytes.clear(); } } catch (EOFException ignored) { } }
9
@Override public Connection crearConexion() { try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ausiasyield", "root", "bitnami"); return connection; } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (SQLException ex) { throw new RuntimeException(ex); } }
2
public void updateGrbit() { grbit = 0; grbit |= valType; grbit |= (errStyle << 4); grbit |= (IMEMode << 10); if( fStrLookup ) { grbit = (grbit | BITMASK_FSTRLOOKUP); } if( fAllowBlank ) { grbit = (grbit | BITMASK_FALLOWBLANK); } if( fSuppressCombo ) { grbit = (grbit | BITMASK_FSUPRESSCOMBO); } if( fShowInputMsg ) { grbit = (grbit | BITMASK_FSHOWINPUTMSG); } if( fShowErrMsg ) { grbit = (grbit | BITMASK_FSHOWERRORMSG); } grbit |= (typOperator << 20); }
5
public String getRatioOfTwoArray(List<String> list1, List<String> list2) { int common = 0; int total = 0; if (list1.size() > list2.size()) { total = list1.size(); for (String obj : list2) { if (list1.contains(obj)) { common++; } else { total++; } } } else { total = list2.size(); for (String obj : list1) { if (list2.contains(obj)) { common++; } else { total++; } } } if (common <= 5) return ""; else return common + " " + total; }
6
public static double compositeSimpsonsRule(SingleVarEq f, double a, double b, int steps){ // N must be positive and even if(steps < 0 || steps % 2 != 0){ throw new IllegalArgumentException("Steps must be positive and even"); } double h = (b - a) / steps; double endSum = f.at(a) + f.at(b); // sum the end points double oddSum = 0; // Temporary variables to hold the partial sums double evenSum = 0; for(int i = 0; i < steps; i++){ double x = a + (i * h); if(i % 2 == 0){ // i is even evenSum += f.at(x); }else{ oddSum += f.at(x); } } double sum = h * (endSum + 2 * evenSum + 4 * oddSum) / 3; return sum; }
4
public UWECImage createMosaic(UWECImage image) { // scales our mosaic image image.scaleImage(horzMosaicSize, vertMosaicSize); // create a new blank uwecimage UWECImage blankMosaic = new UWECImage(horzMosaicSize, vertMosaicSize); // create threads and total number of tiles to be used int numOfThreads = (horzNumTiles); // should be 192 //64 TileFinderThread[] tft = new TileFinderThread[numOfThreads]; Thread[] ts = new Thread[numOfThreads]; // start threads for (int i = 0; i < numOfThreads; i++) { tft[i] = new TileFinderThread(blankMosaic, image, tileWidth, tileHeight, imageAL, i); ts[i] = new Thread(tft[i]); ts[i].start(); } // wait for all of the tile threads and merge them for (int i = 0; i < numOfThreads; i++) { try { ts[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } return blankMosaic; }
3
public void init() { matches = Competition.getInstance().getCodeRedSchedule(); batteryList = new ArrayList<>(); for (Match match : matches) { batteryList.add(match.getBattery()); } if (matches == null) { matches = new ArrayList<>(); } }
2
protected static Instances getMiningSchemaAsInstances(Element model, Instances dataDictionary) throws Exception { ArrayList<Attribute> attInfo = new ArrayList<Attribute>(); NodeList fieldList = model.getElementsByTagName("MiningField"); int classIndex = -1; int addedCount = 0; for (int i = 0; i < fieldList.getLength(); i++) { Node miningField = fieldList.item(i); if (miningField.getNodeType() == Node.ELEMENT_NODE) { Element miningFieldEl = (Element)miningField; String name = miningFieldEl.getAttribute("name"); String usage = miningFieldEl.getAttribute("usageType"); // TO-DO: also missing value replacement etc. // find this attribute in the dataDictionary Attribute miningAtt = dataDictionary.attribute(name); if (miningAtt != null) { if (usage.length() == 0 || usage.equals("active") || usage.equals("predicted")) { attInfo.add(miningAtt); addedCount++; } if (usage.equals("predicted")) { classIndex = addedCount - 1; } } else { throw new Exception("Can't find mining field: " + name + " in the data dictionary."); } } } Instances insts = new Instances("miningSchema", attInfo, 0); // System.out.println(insts); if (classIndex != -1) { insts.setClassIndex(classIndex); } return insts; }
8
public Set getDeclarables() { Set used = new SimpleSet(); if (type == FOR) { incrInstr.fillDeclarables(used); if (initInstr != null) initInstr.fillDeclarables(used); } cond.fillDeclarables(used); return used; }
2
public InfoRequest(final String id, String... emails) { this.id = id; for (String email : emails) { addEmail(email); } }
1
public Game() { //create the JFrame and add the display to it frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1024, 600); frame.setVisible(true); frame.add(display); //initialize room Environment room = new YourRoom(); //initialize lab Environment lab = new Docs_Lab(); //initialize garden environments Environment nwg = new Northwestgarden(); Environment ng = new Northgarden(); Environment wg = new WestGarden(); Environment swg = new Southwestgarden(); Environment cg = new Centergarden(); Environment neg = new Northeastgarden(); Environment eg = new Eastgarden(); Environment seg = new Southeastgarden(); Environment sg = new Southgarden(); //initialize dungeon environments Environment nw_dungeon = new Northwestdungeon(); Environment w_dungeon = new Westdungeon(); Environment sw_dungeon = new Southwestdungeon(); Environment cell_dungeon = new jailcell(); Environment s_dungeon = new SouthDungeon(); Environment se_dungeon = new SoutheastDungeon(); Environment e_dungeon = new EastDungeon(); Environment ne_dungeon = new NortheastDungeon(); Environment atrium = new Atrium(); Environment jailer_room = new JailerRoom(); //initialize palace environments Environment lc_palace = new Leftcenterpalace(); Environment ln_palace = new Leftnorthpalace(); Environment ls_palace = new Leftsouthpalace(); Environment ne_palace = new Northeastpalace(); Environment nw_palace = new Northwestpalace(); Environment rn_palace = new Rightnorthpalace(); Environment rs_palace = new Rightsouthpalace(); Environment se_palace = new Southeastpalace(); Environment sw_palace = new Southwestpalace(); //initialize tower environments Environment n_tower = new Northtower(); Environment c_tower = new Centertower(); Environment s_tower = new Southtower(); //area that acts as "filler" for areas the player can't go in the array Environment empty = new Empty(); //environments that can be travelled to via passages are added here environments.add(room); environments.add(nwg); environments.add(nw_dungeon); environments.add(sw_palace); environments.add(s_tower); environments.add(lab); // garden area [col][row] garden[1][0] = ng; garden[0][1] = wg; garden[0][2] = swg; garden[1][1] = cg; garden[2][0] = neg; garden[2][1] = eg; garden[2][2] = seg; garden[1][2] = sg; //fill dungeon with empty environments first for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { dungeon[i][j] = empty; } } // dungeon area [col][row] dungeon[0][1] = nw_dungeon; dungeon[0][2] = w_dungeon; dungeon[0][3] = sw_dungeon; dungeon[0][4] = cell_dungeon; dungeon[1][3] = s_dungeon; dungeon[2][3] = se_dungeon; dungeon[2][2] = e_dungeon; dungeon[2][1] = ne_dungeon; dungeon[3][0] = atrium; dungeon[3][1] = jailer_room; //fill palace with empty environments first for(int i = 0; i < 4; i++) { for(int j = 0; j < 3; j++) { palace[i][j] = empty; } } // palace area [col][row] palace[0][0] = nw_palace; palace[1][0] = ln_palace; palace[2][0] = rn_palace; palace[3][0] = ne_palace; palace[1][1] = lc_palace; palace[0][2] = sw_palace; palace[1][2] = ls_palace; palace[2][2] = rs_palace; palace[3][2] = se_palace; //fill palace with empty environments first for(int i = 0; i < 1; i++) { for(int j = 0; j < 3; j++) { tower[i][j] = empty; } } // tower area [col][row] tower[0][0] = n_tower; tower[0][1] = c_tower; tower[0][2] = s_tower; //the initial text when you start the game display.setOutput("Saving Sylvester, Copyright 2014 Immortal Porpoises \n\nNote: please limit commands to 2 words, " + "i.e. \"look room,\" \"examine bear,\" \"take bear,\" \"enter door,\" etc. \nTo view your inventory, simply " + "type \"view inventory.\" To get help, type \"help me.\" Case and punctuation do not matter." + "\n\n\"and so Sylvester breathed his last. \n The End.\" \n\n We open at the close." + "\n You snap the book shut - the latest work by your favorite fantasy author, P.F. Tollers and" + " wipe a tear away. \"Why did Sylvester have to die?\" you wonder out loud. \"He was the best " + "character in the series.\" This thought overcomes you, and you break down in pitiful sobs." + "\n Time passes, and a few hours later, you are in your room, sobbing violently in the fetal position" + " and holding a giant pink fluffy teddy bear. You throw the teddy bear across the room, walk " + "intently to your computer and promptly begin whining to the world through various social " + "media. Strangely enough, you are suddenly struck by the feeling that someone is watching you. " + "You rise from your desk to look around."); //continue to update the game until the user exits the window for(;;) { updateGame(); } }
7
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>(); Arrays.sort(candidates); if (target == 0) { rst.add(new ArrayList<Integer>()); return rst; } for (int i= 0 ; i < candidates.length && candidates[i] <= target; i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); search(i,target,candidates,tmp,rst); while (i < candidates.length - 1 && candidates[i + 1] == candidates[i]) i++; } return rst; }
5
private static void heapsort(int a[]) { int n = a.length; int parent, left, right, max; makeHeap(a); System.out.println("array after converting into heap...\n"); for (int k : a) System.out.print(k + " "); for (int i = n - 1; i > 0; i--) { swap(a, 0, i); parent = 0; while (true) { left = (2 * parent) + 1; right = (2 * parent) + 2; if (left < i && right < i) { max = (a[left] > a[right] ? left : right); if (a[max] > a[parent]) { swap(a, max, parent); parent = max; } else break; } else if (left < i) { if (a[left] > a[parent]) { swap(a, left, parent); break; } } else break; } } }
9
public void update(Observable o, Object arg) { // TODO Auto-generated method stub }
0
protected void createRandomChromosomes() { int[] newChromosomes = new int[numberOfChromosomes]; int crossSum = 0; boolean startFromEnd = false; if (getRandom() < 0.5) { startFromEnd = true; } for (int i = 0; i < newChromosomes.length; i++) { if (getRandom() < 0.25) { continue; } int nextValue = createRandomChromosomeValue(); if (crossSum + nextValue > maxCrossSum) { nextValue = maxCrossSum - crossSum; } crossSum += nextValue; int position = i; if (startFromEnd) { position = newChromosomes.length - (i + 1); } newChromosomes[position] = nextValue; } this.chromosomes = newChromosomes; }
5
private void saveResource(String username) { if (!MyFactory.getResourceService().hasRight(MyFactory.getCurrentUser(), Resource.USER_MNG)) { return; } User user = MyFactory.getUserService().queryUserByName(username); List<String> displayNames = new ArrayList<String>(); int count = resourcePanel.getComponentCount(); for (int i = 0; i < count; i++) { if (resourcePanel.getComponent(i) instanceof JCheckBox) { JCheckBox cb = (JCheckBox) resourcePanel.getComponent(i); if (cb.isSelected()) { displayNames.add(cb.getText()); } } } ResourceService resourceService = MyFactory.getResourceService(); int[] resource = new int[displayNames.size()]; int i = 0; for (String name : displayNames) { name = name.replace(".", "").replaceAll("\\d", ""); resource[i] = resourceService.queryResourceId(name); i++; } user.setResource(resource); if (MyFactory.getUserService().update(user)) { JOptionPane.showMessageDialog(null, "保存成功"); } else { JOptionPane.showMessageDialog(null, "保存失败,请重试"); } }
6
@Override protected void loadPlays(Position position, Player cpu, int largestCapture){ FactoryOfPlays factory = new FactoryOfCapturingsForPiece(position,cpu.getBoard()); int bestEvaluation=-100; for(AbstractPlay play:factory){ int evaluation = evaluate(play,cpu,largestCapture); if(evaluation>=bestEvaluation){ if (evaluation != bestEvaluation) bestPlays.clear(); bestPlays.add(play); bestEvaluation=evaluation; } } maxEvaluation=bestEvaluation; }
3
public void answerCase(int id, String user) { switch(id){ case 1: //connected to server, got welcome message send(id, userName, null, Main.mainData.userName); break; case 2: //username accepted userName = message; Main.gui.serverMessage("Username: " + message + " accepted!"); send(id, userName, null, "OK"); break; case 3: //username not accepted... get new from GUI GUI.messageInputField.setEditable(true); UserNameFailWindow fail = new UserNameFailWindow(); fail.setVisible(true); break; case 4: //got MOT send(id, userName, null, "OK"); break; case 5: //list of rooms listRooms = chopStrings(message); GUI.messageInputField.setEditable(true); send(id, userName, null, "OK"); break; case 6: //welcome to room send(id, userName, null, "OK"); break; case 7: //list of users send(id, userName, null, "OK"); GUI.userList = chopStrings(message); GUI.setMemberList(); break; case 8: //send messages System.out.println("ready to type!"); break; } }
8
public Contact[] sortContacts() { //Stored the stored Contact[] Contact[] sortedContactArray = new Contact[addedContactCount]; //Create a copy of the original Contact[] so the original Contact[] won't be contaminated after sorted. System.arraycopy(contacts, 0, sortedContactArray, 0, addedContactCount); int sortedContactLength = sortedContactArray.length; //Testing message - show pre-sort Contact[] System.out.println("Pre-sort array ..."); for (int i=0; i<sortedContactLength; i++) { System.out.print(sortedContactArray[i].getLastName() + " " + sortedContactArray[i].getFirstName() + " , "); } System.out.println("\n"); //End testing message //Insertion sort; example @ http://java2novice.com/java-interview-programs/insertion-sort/ //Loop through the Contact[], starting at 2nd position (Contact[1]) until the end. //Store the string at current position -> cP //Start position counter (pP) = current loop - 1 //Compare the String at current position (cP) with the one before it (pP) and we get an int (x) as result. //If x is positive, that means the current string (cP) should comes before the the string at (pP) //So, we copy cP by pP, and move the position counter (pP) back 1 //we continue to check again as long as pP > -1 (>= 0, so not out of bound) and compare the string at pP to cP for (int j = 1; j < sortedContactLength; j++) { String currentLastName = sortedContactArray[j].getLastName(); String currentFirstName = sortedContactArray[j].getFirstName(); Contact currentContact = sortedContactArray[j]; //hold the current contact @ loop position int previousPosition = j-1; //previous position pointer //as long as pP != out of bound (> -1) ... we want to compare string @ pP to string @ cP; + means cP comes before pP, = means they are the same, - means cP comes after pP while ( (previousPosition > -1) && ( sortedContactArray[previousPosition].getLastName().compareToIgnoreCase(currentLastName) > 0) ) { sortedContactArray[previousPosition + 1] = sortedContactArray[previousPosition]; previousPosition-- ; } //in the case cP == pP, we want to compare by their first name if ((previousPosition > -1) && (sortedContactArray[previousPosition].getLastName().compareToIgnoreCase(currentLastName) == 0)) { while ((previousPosition > -1) && ( sortedContactArray[previousPosition].getFirstName().compareToIgnoreCase(currentFirstName) > 0) ) { sortedContactArray[previousPosition + 1] = sortedContactArray[previousPosition]; previousPosition-- ; } } //in the case //1. pP = -1 (that means cP is at the first position, Contact[0]) //or ... //2. String @ pP < String @ cP (that means alphabetically correct) sortedContactArray[previousPosition + 1] = currentContact; } //Test messages - Updated array System.out.println("Updated array ..."); for (int i=0; i<sortedContactLength; i++) { System.out.print(sortedContactArray[i].getLastName() + " " + sortedContactArray[i].getFirstName() + " , "); } System.out.println("\n"); //Ends test messages ... return sortedContactArray; }
9
static public String composeMultipleApiCommands(String... commands) { StringBuilder apiCmd = new StringBuilder(256); apiCmd.append("(LIST "); for (Object command : commands) { apiCmd.append(command); } apiCmd.append(')'); return apiCmd.toString(); }
1
@Override public Pixel[][] getDisplay() { Pixel[][] display = new Pixel[thisTick.length][thisTick[0].length]; for (int row = 0; row < thisTick.length; row++) { for (int col = 0; col < thisTick[row].length; col++) { display[row][col] = new Pixel(row, col, thisTick[row][col] == null ? PixelType.emptyPixel.id : thisTick[row][col].id); } } return display; }
3
public ChocolateChip() { print("ChocolateChip()"); }
0
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(clickDay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(clickDay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(clickDay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(clickDay.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 clickDay().setVisible(true); } }); }
6
public static void processT(String tempDir) throws FileNotFoundException, NoSuchElementException, IOException, ProcessException { File trigramSortedInterDataFile = FileUtil.getFileInDirectoryWithSuffix(tempDir, TrigramExternalSort.DATA_SUFFIX); File unigramDataFile = FileUtil.getFileInDirectoryWithSuffix(tempDir, UnigramPreprocess.DATA_SUFFIX); File unigramCountFile = FileUtil.getFileInDirectoryWithSuffix(tempDir, UnigramPreprocess.COUNT_SUFFIX); String trigramDataFilePathname = tempDir + File.separator + FileUtil.getFilenameWithoutSuffix(trigramSortedInterDataFile) + '.' + DATA_SUFFIX; String trigramCountFilePathname = tempDir + File.separator + FileUtil.getFilenameWithoutSuffix(trigramSortedInterDataFile) + '.' + COUNT_SUFFIX; try ( BufferedReader trigramSortedInterData = new BufferedReader(new FileReader(trigramSortedInterDataFile)); BufferedWriter trigramData = new BufferedWriter(new FileWriter(trigramDataFilePathname)); BufferedWriter trigramCount = new BufferedWriter(new FileWriter(trigramCountFilePathname)); ){ String unigramDataName = FileUtil.getFilenameWithoutSuffix(unigramDataFile.getCanonicalPath(), UnigramPreprocess.DATA_SUFFIX); String trigramDataName = FileUtil.getFilenameWithoutSuffix(trigramDataFilePathname, TrigramCountSummation.DATA_SUFFIX); // Add header to the files IOUtil.writePreprocTrigramHeader(trigramData, new File(unigramDataName), new File(trigramDataName), "data"); IOUtil.writePreprocTrigramHeader(trigramCount, new File(unigramDataName), new File(trigramDataName), "count"); int gram1ID = 0, gram2ID = 0, prevGram1ID = 0, prevGram2ID = 0; long freq = 0, count = 0; boolean isFirstGram = true; double rt; long[] uCount = Unigram.readCounts(WordrtPreproc.TEXT, unigramDataFile, unigramCountFile); cMax = Unigram.readCMax(unigramCountFile); DecimalFormat df = new DecimalFormat("#.###"); for (String inputLine; (inputLine = trigramSortedInterData.readLine()) != null; ) { StringTokenizer line = new StringTokenizer(inputLine); gram1ID = Integer.parseInt(line.nextToken()); gram2ID = Integer.parseInt(line.nextToken()); if (isFirstGram) { prevGram1ID = gram1ID; prevGram2ID = gram2ID; freq = Long.parseLong(line.nextToken()); trigramData.write(Integer.toString(gram1ID)); isFirstGram = false; } else if (gram1ID == prevGram1ID && gram2ID == prevGram2ID) { freq += Long.parseLong(line.nextToken()); } else { rt = computeRT(uCount[prevGram1ID], uCount[prevGram2ID], freq); if (rt > 0.001) { trigramData.write("\t" + prevGram2ID + "\t" + df.format(rt)); count++; } if (prevGram1ID != gram1ID) trigramData.write("\n" + Integer.toString(gram1ID)); prevGram1ID = gram1ID; prevGram2ID = gram2ID; freq = Long.parseLong(line.nextToken()); } } rt = computeRT(uCount[prevGram1ID], uCount[prevGram2ID], freq); if (prevGram1ID != gram1ID) trigramData.write("\n" + gram1ID); if (rt > 0.001) { trigramData.write("\t" + prevGram2ID + "\t" + df.format(rt)); count++; } trigramCount.write(Long.toString(count)); } }
8
private void addState(Element element, StateMachineBuilder builder) throws BadStateMachineSpecification{ // this will be refactored when something other than basic state is instroduced if (element.hasAttribute(ENABLE_ASPECT_TAG)) { int properties = StateMachineBuilder.STATE_PROPERTIES_BASIC; properties |= (Boolean.parseBoolean(element.getAttribute(ENABLE_ASPECT_TAG))? StateMachineBuilder.STATE_PROPERTIES_ASPECT:0); builder.addState(element.getAttribute(ELEMENT_NAME_TAG), properties); } else { builder.addState(element.getAttribute(ELEMENT_NAME_TAG)); } fillAttributes(element, builder, standardStateTags); // special treatment for predefined attributes Class stateClass = getClass(element, State.class); if (stateClass != null) builder.addProperty(StateMachineBuilder.STATE_CLASS_PROPERTY, stateClass); if (element.hasAttribute(IS_FINAL_STATE_TAG) && Boolean.parseBoolean(element.getAttribute(IS_FINAL_STATE_TAG))) builder.markStateAsFinal(); if (element.hasAttribute(IS_INITIAL_STATE_TAG) && Boolean.parseBoolean(element.getAttribute(IS_INITIAL_STATE_TAG))) builder.markStateAsInitial(); }
7
public String getClientId() { return clientId; }
0
protected boolean isCollision(Vector3d v3d) { Transform3D t3d = new Transform3D(); tg.getTransform(t3d); Matrix4d m4d = new Matrix4d(); t3d.get(m4d); GMatrix gm1 = new GMatrix( 4, 1, new double[] { v3d.x, v3d.y, v3d.z, 0.0 } ); GMatrix gm2 = new GMatrix( 4, 4, new double[] { m4d.m00, m4d.m01, m4d.m02, 0.0, m4d.m10, m4d.m11, m4d.m12, 0.0, m4d.m20, m4d.m21, m4d.m22, 0.0, 0.0, 0.0, 0.0, 0.0 } ); gm1.mul(gm2, gm1); double[] d = new double[4]; gm1.getColumn(0, d); Vector3d v3d0 = new Vector3d(); v3d0.x = speed == SLOW ? d[0] * 20.0 : d[0] * 2.0; v3d0.y = speed == SLOW ? d[1] * 20.0 : d[1] * 2.0; v3d0.z = speed == SLOW ? d[2] * 20.0 : d[2] * 2.0; PickSegment ps = new PickSegment( new Point3d(m4d.m03, m4d.m13, m4d.m23), new Point3d( m4d.m03 + v3d0.x, m4d.m13 + v3d0.y, m4d.m23 + v3d0.z ) ); SceneGraphPath[] sgpa = bg.pickAll(ps); if (!(sgpa == null)) { for (int i = 0; i < sgpa.length; i++) { if (sgpa[i].getObject() instanceof Shape3D) { Shape3D s3d = (Shape3D) sgpa[i].getObject(); PickResult pr = new PickResult(sgpa[i], ps); if (pr.numIntersections() > 0) { return true; } } } } return false; }
7
public static void toggleToPlayersTownyChannel( String sender, String channel, boolean hasTown, Boolean hasNation ) throws SQLException { BSPlayer p = PlayerManager.getPlayer( sender ); if ( !hasTown ) { p.sendMessage( Messages.TOWNY_NONE ); return; } if ( p.getChannel().equals( channel ) ) { channel = getServersDefaultChannel( p.getServerData() ); p.sendMessage( Messages.TOWNY_OFF_TOGGLE ); } else if ( channel.equals( "Town" ) ) { p.sendMessage( Messages.TOWNY_TOGGLE ); } else if ( channel.equals( "Nation" ) ) { if ( hasNation ) { p.sendMessage( Messages.TOWNY_NATION_TOGGLE ); } else { p.sendMessage( Messages.TOWNY_NATION_NONE ); return; } } Channel c = getChannel( channel ); setPlayersChannel( p, c, false ); }
5
public void loadConfigFiles(){ try { loadPlayerConfigFile(playerFile); loadCardConfigFile(cardFile); } catch (FileNotFoundException e) { System.out.println(e); } catch (BadConfigFormatException e) { System.out.println(e); } }
2
public int count() { return count; }
0
public static void dropLocalDatabaseAndUser(MySQLIdentity root, MySQLIdentity newIdentity) throws SQLException, MySQLException { if((root.host == null) || (newIdentity.host == null)) { throw new MySQLException("Host not specified");} if(root.host.equals(newIdentity.host) == false) { throw new MySQLException("Hosts must not be different");} MySQLIdentity rootAtNewDatabase = MySQLService.createMyIdentity(root.host, newIdentity.databaseName, root.user, root.password); MySQLService.quickExec(rootAtNewDatabase, "DROP USER '" + newIdentity.user + "'@'" + newIdentity.host + "';"); MySQLService.quickExec(rootAtNewDatabase, "DROP DATABASE " + newIdentity.databaseName + ";"); }
3
public Browser getGroup() { if (this.parent != null) { return parent.getGroup(); } return this; }
1
public boolean pass(int[] bowl, int bowlId, int round, boolean canPick, boolean musTake) { counter++; if(counter==1){ for(int i=0;i<12;i++){ bowSize+=bowl[i]; } //update(bowSize*6); } update(bowl,bowlId,round); if (musTake){ return true; } if(canPick==false) return false; //no enough information if (info.size()<=1) { return false; } if (round==0) { futureBowls=nplayer-position-counter; //return round0(bowl,bowlId,round,canPick,musTake); } else { futureBowls=nplayer-counter+1; //return round1(bowl,bowlId,round,canPick,musTake); } double b=score(bowl); double PrB=1, p=probLessThan(b); for (int i = 0; i < futureBowls; i++) { PrB*=p; } double PrA=1-PrB; double ExA=exptGreaterThan(b); double ExB=exptLessThan(b); double Ex2=PrA*ExA+PrB*ExB; double tStar=search(); double fTStar=f(tStar); //double fb=f(b,futureBowls); //double fb1=f(b+1, futureBowls); if(fTStar>b) { // return false; } else { return true; } }
8
private void buildProfitsArray(int[] prices, int[] leftProfits, int[] rightProfits) { int min = Integer.MAX_VALUE; for (int i = 0; i < leftProfits.length; i++) { if (prices[i] < min) { min = prices[i]; } //leftProfits[i] = i == 0 ? 0 : Math.max(leftProfits[i - 1], prices[i] - min); leftProfits[i] = i; if (i == 0) { leftProfits[i] = 0; } else { leftProfits[i] = Math.max(leftProfits[i - 1], prices[i] - min); } } int max = Integer.MIN_VALUE; for (int i = rightProfits.length - 1; i >= 0; i--) { if (prices[i] > max) { max = prices[i]; } //rightProfits[i] = i == rightProfits.length - 1 ? 0 : Math.max(rightProfits[i + 1], max - prices[i]); rightProfits[i] = i; if (i == rightProfits.length - 1) { rightProfits[i] = 0; } else { rightProfits[i] = Math.max(rightProfits[i + 1], max - prices[i]); } } }
6
private int hasPresencePort() { return (port == null || port > NO_PORT) ? hasPresence(host) : 0; }
2
public static void main(String[] args) { boolean error = false; String path = "BIGxml.xml"; try { if (args.length > 0) { if (isValidXML(args[0])) { path = args[0]; } else { System.out .println("Invalid file path. Path must be to a valid XML file"); error = true; } } else { System.out.println("Enter a valid Floor Path XML File"); path = in.nextLine(); if (!isValidXML(path)) { error = true; System.out.println("Invalid XML file path"); } } if (!error) { final FloorPlan fp = startRobot(path); final Robot r = new Robot(0, 0, fp); SwingUtilities.invokeLater(new Runnable() { public void run() { HomeUI ex = new HomeUI(fp, r); } }); } } catch (Exception exp) { logger.log(Level.SEVERE, "Error starting robot with file", exp); } }
5
private void buildLists() { Iterator iter = roots().iterator(); preOrder = new NodeList(); postOrder = new NodeList(); final Set visited = new HashSet(); // Calculate the indices of the nodes. while (iter.hasNext()) { final GraphNode root = (GraphNode) iter.next(); Assert.isTrue(nodes.containsValue(root), "Graph does not contain " + root); number(root, visited); } // Mark all nodes that were not numbered as having an index of -1. This // information is used when removing unreachable nodes. iter = nodes.values().iterator(); while (iter.hasNext()) { final GraphNode node = (GraphNode) iter.next(); if (!visited.contains(node)) { node.setPreOrderIndex(-1); node.setPostOrderIndex(-1); } else { Assert.isTrue(node.preOrderIndex() >= 0); Assert.isTrue(node.postOrderIndex() >= 0); } } }
3
public static String getAlias(Class<? extends ConfigurationSerializable> clazz) { DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); if (delegate != null) { if ((delegate.value() == null) || (delegate.value() == clazz)) { delegate = null; } else { return getAlias(delegate.value()); } } if (delegate == null) { SerializableAs alias = clazz.getAnnotation(SerializableAs.class); if ((alias != null) && (alias.value() != null)) { return alias.value(); } } return clazz.getName(); }
7
public void run(){ if(true) return; Socket c; try { while((c = socket.accept()) != null){ c.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3
public static char getCharFromPiece(Piece in) throws IllegalArgumentException{ char out; switch(in){ case KING:{ out = ChessConstants.KING_PIECE_CHAR; break; } case QUEEN:{ out = ChessConstants.QUEEN_PIECE_CHAR; break; } case BISHOP:{ out = ChessConstants.BISHOP_PIECE_CHAR; break; } case KNIGHT:{ out= ChessConstants.KNIGHT_PIECE_CHAR; break; } case ROOK:{ out = ChessConstants.ROOK_PIECE_CHAR; break; } default:{ String errorMsg = "Unknow piece type '"+in.name()+"'"; IllegalArgumentException exception; exception = new IllegalArgumentException(errorMsg); throw exception; } } return out; }
5
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(TwoPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TwoPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TwoPlayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TwoPlayer.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 TwoPlayer().setVisible(true); } }); }
6
@Override public int getNeighborCountOf(int x, int y) { int count = 0; if (cellLivesAt(x, y + 1)) { count++; } if (cellLivesAt(x, y - 1)) { count++; } if (cellLivesAt(x - 1, y)) { count++; } if (cellLivesAt(x - 1, y + 1)) { count++; } if (cellLivesAt(x - 1, y - 1)) { count++; } if (cellLivesAt(x + 1, y)) { count++; } if (cellLivesAt(x + 1, y + 1)) { count++; } if (cellLivesAt(x + 1, y - 1)) { count++; } return count; }
8
public void execute(int ticksLeft) { boolean runMain = !playerQueue.isEmpty(); if (runMain) { // Set ticks left this.ticksLeft = ticksLeft; // Fetch the max number of threads currentThreads = cfg.spawnFinderThreads; // Find a reasonable number of threads to run the main task in for (; currentThreads > 1 && playerQueue.size() / currentThreads <= 2; --currentThreads); // Execute the main tasks for (int i = 0; i < currentThreads; ++i) executor.execute(this); } else currentThreads = 0; // Run any tasks in the worker queue (Probably full) Runnable task; while ((task = syncWorkerQueue.poll()) != null) { task.run(); } }
5
public int indexOf(int gridletId, int userId) { ResGridlet gl = null; int i = 0; Iterator<ResGridlet> iter = super.iterator(); while (iter.hasNext()){ gl = iter.next(); if (gl.getGridletID()==gridletId && gl.getUserID()==userId) { return i; } i++; } return -1; }
3
public void addAccount(BankAccount account) throws IllegalArgumentException { if (! canHaveAsAccount(account)) throw new IllegalArgumentException(); accounts.add(account); }
1
private boolean canEventResponse() { // 豁サ菴薙�辟。逅� if(dead) return false; if(getCriticalDamege() == CriticalDamegeType.CUT) return false; // 縺�s縺�s逶エ蜑阪�蜍輔¢縺ェ縺�憾諷九�辟。逅� if(shitting) return false; // 蜃コ逕」逶エ蜑阪�蜍輔¢縺ェ縺�憾諷九�辟。逅� if(birth) return false; // 縺吶▲縺阪j繧「繝九Γ繝シ繧キ繝ァ繝ウ荳ュ縺ッ辟。逅� if(sukkiri) return false; // 縺コ繧阪⊆繧堺クュ繧ら┌逅� if(peropero) return false; // 莉悶�繧、繝吶Φ繝亥ョ溯。御クュ繧ら┌逅� if(currentEvent != null) return false; return true; }
7
public void setQuantity(String quant) { String[] strings = quant.split("-|\\s"); for (String string : strings) { System.out.println(string); } if (strings.length>=2) { System.out.println(""+strings.length); for (String string : strings) { if (checkIfNumber(string)) { this.quantity = Double.valueOf(string); } else{ measurement = com.gurey.measurement.measurement.grabMeasurement(string); } } System.out.println("Mes "+measurement); System.out.println("Qua "+quantity); } }
4
private void setCorrectLocationDefault(Attributes attrs) { // find the value to be set, then set it if (attrs.getValue(0).equals("fontname")) { quizSlideDef.setCorrectFont(attrs.getValue(1)); } else if (attrs.getValue(0).equals("fontsize")) { quizSlideDef.setCorrectSize(Float.valueOf(attrs.getValue(1))); } else if (attrs.getValue(0).equals("fontcolor")) { quizSlideDef.setCorrectColour(new Color(Integer.valueOf(attrs .getValue(1).substring(1), 16))); } else if (attrs.getValue(0).equals("alpha")) { quizSlideDef.setCorrectAlpha(Float.valueOf(attrs.getValue(1))); } else if (attrs.getValue(0).equals("backgroundcolor")) { quizSlideDef.setCorrectBkColour(new Color(Integer.valueOf(attrs .getValue(1).substring(1), 16))); } else if (attrs.getValue(0).equals("backgroundalpha")) { quizSlideDef.setCorrectBkAlpha(Float.valueOf(attrs.getValue(1))); } }
6
public int size() { return count; }
0
public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); }
9
public void tick() { /** Ticking the buttons */ for (int i = 0; i < buttons.size(); i++) { buttons.get(i).tick(); if (buttons.get(i).getTitle().equalsIgnoreCase("online") && buttons.get(i).getClicked()) { main.menus.get(3).init(); } } }
3
public void createRoleOnIncident(ArrayList<BERoleTime> roleTime, int roleNumber) { if (roleTime == null) { BLLError.getInstance().functionError(); return; } if (roleNumber > 4 || roleNumber < 1) { BLLError.getInstance().functionError(); return; } for (BERoleTime tmpRoleTimes : roleTime) { if (tmpRoleTimes == null) { BLLError.getInstance().functionError(); return; } } for (BERoleTime tmpRoleTimes : roleTime) { BERole prevRole = tmpRoleTimes.getM_role(); for (BERole role : BLLRead.getInstance().readRoles()) { if (role.getM_id() == roleNumber) { try { tmpRoleTimes.setM_role(role); dalCreate.createRoleTime(tmpRoleTimes); } catch (SQLException ex) { tmpRoleTimes.setM_role(prevRole); BLLError.getInstance().functionError(); return; } BLLRead.getInstance().addToRoleTime(tmpRoleTimes); break; } } } }
9
@Override public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { // 处理下自己的业务 BeanMappingField currentField = invocation.getContext().getCurrentField(); if (value == null && StringUtils.isNotEmpty(currentField.getDefaultValue()) && currentField.isMapping() == false) { if (currentField.getSrcField().getClazz() != null) {// 有指定对应的SrcClass Convertor convertor = ConvertorHelper.getInstance().getConvertor(String.class, currentField.getSrcField().getClazz()); if (convertor != null) { // 先对String字符串进行一次转化 value = convertor.convert(currentField.getDefaultValue(), currentField.getSrcField().getClazz()); } } if (value == null) { // 不存在对默认值处理的convertor,不予处理,后续尝试下自定义的convertor value = currentField.getDefaultValue(); } } return invocation.proceed(value); }
6
public static void OBRADI_init_deklarator(){ String linija = mParser.ParsirajNovuLiniju(); // ucitaj <izravni_deklarator> int trenLabela = Izrazi.mBrojacLabela++; int stogPrijeIzravnogDek_Lok = (NaredbenaStrukturaPrograma.mStog == null) ? 0 : NaredbenaStrukturaPrograma.mStog.size(); int stogPrijeIzravnogDek_Glo = NaredbenaStrukturaPrograma.mGlobalniDjelokrug.size(); Ime_Velicina_Adresa izravni_deklarator = OBRADI_izravni_deklarator(trenLabela); int stogPoslijeIzravnogDek_Lok = (NaredbenaStrukturaPrograma.mStog == null) ? 0 : NaredbenaStrukturaPrograma.mStog.size(); int stogPoslijeIzravnogDek_Glo = NaredbenaStrukturaPrograma.mGlobalniDjelokrug.size(); int razlikaStoga_Lok = stogPoslijeIzravnogDek_Lok - stogPrijeIzravnogDek_Lok; int razlikaStoga_Glo = stogPoslijeIzravnogDek_Glo - stogPrijeIzravnogDek_Glo; linija = mParser.DohvatiProviriVrijednost(); UniformniZnak uz_op_pridruzi = UniformniZnak.SigurnoStvaranje(linija); if (uz_op_pridruzi != null && uz_op_pridruzi.mNaziv.equals("OP_PRIDRUZI")){ // doslo je do pridruzivanja pa makni nule sa stoga if (NaredbenaStrukturaPrograma.mStog == null){ for (int i = 0; i < razlikaStoga_Glo; ++i){ mIspisivac.DodajPreMainKod("POP R0", "deklaracija " + izravni_deklarator.mIme + ": biti ce pridruzivanje pa micem null inicjalizaciju"); NaredbenaStrukturaPrograma.mGlobalniDjelokrug.remove(NaredbenaStrukturaPrograma.mGlobalniDjelokrug.size()-1); } }else{ for (int i = 0; i < razlikaStoga_Lok; ++i){ mIspisivac.DodajKod("POP R0", "deklaracija " + izravni_deklarator.mIme + ": biti ce pridruzivanje pa micem null inicjalizaciju"); NaredbenaStrukturaPrograma.mStog.remove(NaredbenaStrukturaPrograma.mStog.size()-1); } } linija = mParser.ParsirajNovuLiniju(); // ucitaj OP_PRIDRUZI linija = mParser.ParsirajNovuLiniju(); // ucitaj <inicijalizator> OBRADI_inicijalizator(trenLabela); } if (NaredbenaStrukturaPrograma.mStog == null){ mIspisivac.DodajPreMainKod("POP R0", "deklaracija " + izravni_deklarator.mIme + ": dohvacanje vrijednosti"); mIspisivac.DodajPreMainKod("STORE R0, (G_" + izravni_deklarator.mIme.toUpperCase() + ")", "deklaracija " + izravni_deklarator.mIme + ": spremanje na odrediste"); mIspisivac.DodajGlobalnuVarijablu("G_" + izravni_deklarator.mIme.toUpperCase(), "DW %D 0"); NaredbenaStrukturaPrograma.mGlobalniDjelokrug.get(NaredbenaStrukturaPrograma.mGlobalniDjelokrug.size()-1).mIme = izravni_deklarator.mIme; }else{ NaredbenaStrukturaPrograma.mStog.get(NaredbenaStrukturaPrograma.mStog.size()-1).mIme = izravni_deklarator.mIme; } return; }
8
public int getAVO() { return avoid; }
0
public void connect(TreeLinkNode root) { if (root ==null) return; if (root.next !=null&&root.right !=null&&root.next.left!=null){ root.right.next = root.next.left; } if (root.left!=null&&root.right!=null){ root.left.next = root.right; } connect(root.left); connect(root.right); }
6
public IntelligentLine(Connector from, Connector to) { super(from, to); cpFrom = from.getParent(); cpTo = to.getParent(); panel = cpFrom.getPanel(); for (Component c : cpFrom.getPanel().getElements()) add(c); // add(cpFrom); // add(cpTo); Point mp = Component.getMidPoint(cpFrom, cpTo); add(mp); addOthers(50, 50); buildMap(); if (ndFrom == null || ndTo == null) return; ndFrom.setCost(0); expand(ndFrom); }
3
public long read5bytes() throws IOException { long b0 = read(); long b1 = read(); long b2 = read(); long b3 = read(); long b4 = read(); if (le) return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) | (b4 << 32); else return b4 | (b3 << 8) | (b2 << 16) | (b1 << 24) | (b0 << 32); }
1
public static Connection getCon() { if (con == null) con = initConnection(); return con; }
1
protected void fillOutCopyStats(final Modifiable E, final Modifiable E2) { if((E2 instanceof MOB)&&(!((MOB)E2).isGeneric())) { for(final GenericBuilder.GenMOBCode stat : GenericBuilder.GenMOBCode.values()) { if(stat != GenericBuilder.GenMOBCode.ABILITY) // because this screws up gen hit points { E.setStat(stat.name(), CMLib.coffeeMaker().getGenMobStat((MOB)E2,stat.name())); } } } else if((E2 instanceof Item)&&(!((Item)E2).isGeneric())) { for(final GenericBuilder.GenItemCode stat : GenericBuilder.GenItemCode.values()) { E.setStat(stat.name(),CMLib.coffeeMaker().getGenItemStat((Item)E2,stat.name())); } } else for(final String stat : E2.getStatCodes()) { E.setStat(stat, E2.getStat(stat)); } }
8
public static QuestPoint createQuest(QuestType type){ QuestPoint quest = null; switch(type){ case TEXTQUEST: quest = new TextQuest(); break; case CHOICEQUEST: quest = new ChoiceQuest(); break; case FIELDQUEST: quest = new FieldQuest(); break; case ORDERQUEST: quest = new OrderQuest(); break; case DECISIONQUEST: quest = new DecisionQuest(); break; default: quest = new TextQuest(); break; } return quest; }
5
@Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { generateQuotes(); Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
2
@Override public List list(Integer firstResult, Integer maxResults) throws Exception { try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); //Query q = session.getNamedQuery("find.all"); Query q = session.getNamedQuery(getNamedQueryToFindByRange()); q.setFirstResult(firstResult); q.setMaxResults(maxResults); List lst = q.list(); return lst; } catch (HibernateException e) { throw new Exception(e.getCause().getMessage()); } finally { releaseSession(session); } }
1
public void testAdd_DurationFieldType_int3() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.add((DurationFieldType) null, 6); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); }
1
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Endereco other = (Endereco) obj; if (this.idEndereco != other.idEndereco && (this.idEndereco == null || !this.idEndereco.equals(other.idEndereco))) { return false; } return true; }
5
public static VertexIdTranslate fromString(String s) { if ("none".equals(s)) { return identity(); } String[] lines = s.split("\n"); int vertexIntervalLength = -1; int numShards = -1; for(String ln : lines) { if (ln.startsWith("vertex_interval_length=")) { vertexIntervalLength = Integer.parseInt(ln.split("=")[1]); } else if (ln.startsWith("numShards=")) { numShards = Integer.parseInt(ln.split("=")[1]); } } if (vertexIntervalLength < 0 || numShards < 0) throw new RuntimeException("Illegal format: " + s); return new VertexIdTranslate(vertexIntervalLength, numShards); }
6
@RequestMapping(value = "/hall-event-speaker-list/{hallEventId}", method = RequestMethod.GET) @ResponseBody public SpeakerListResponse eventSpeakerList( @PathVariable(value = "hallEventId") final String hallEventIdStr ) { Boolean success = true; String errorMessage = null; List<Speaker> speakerList = null; Long hallEventId = null; try { hallEventId = controllerUtils.convertStringToLong(hallEventIdStr, true); speakerList = speakerPresenter.findSpeakersByHallEventId(hallEventId); } catch (UrlParameterException e) { success = false; errorMessage = "Hall event ID is wrong or empty"; } return new SpeakerListResponse(success, errorMessage, speakerList); }
1
public void perform(Request r) throws Exception { PaxosMessage commit = new PaxosMessage(); commit.setRequest(r); commit.setMessageType(PaxosMessageEnum.REPLICA_COMMIT); commit.setSrcId(this.processId); commit.setSlot_number(slotNumber); //check if already performed. for(Entry<Integer,Request> entry : decisions.entrySet()) { //writeToLog("inside perform"+entry); if(entry.getKey() < slotNumber && entry.getValue().equals(r)) { writeToLog("request already performed returning for slot"+entry.getKey()+", which is before"+slotNumber); System.out.println(this.processId+" Sending commit message for slot:"+slotNumber+" to all leaders"); List<String> leaders = this.main.leaders; for(String leader : leaders) { //writeToLog(this.processId+" proposing to leader!"); sendMessage(leader, commit); } slotNumber++; return; } } System.out.println(this.processId+" Sending commit message for slot:"+slotNumber+" to all leaders"); List<String> leaders = this.main.leaders; for(String leader : leaders) { //writeToLog(this.processId+" proposing to leader!"); sendMessage(leader, commit); } //writeToLog(this.processId+"performing "+r); //writeToLog(this.processId+" map before perfoming the change "+r+":\n"+accntMap); BankCommand bc = r.getbCommand(); BankAccount src = accntMap.get(bc.getSrcAccntId()); BankAccount dest = accntMap.get(bc.getDestAccntId()); switch(bc.getCommandEnum()) { case DEPOSIT: src.setBalance(src.getBalance()+bc.getAmt()); break; case WITHDRAW: src.setBalance(src.getBalance() - bc.getAmt()); break; case TRANSFER: src.setBalance(src.getBalance() - bc.getAmt()); dest.setBalance(dest.getBalance()+bc.getAmt()); break; case GETBALANCE: break; } writeToLog(this.processId+" map after perfoming at slot "+slotNumber+" the change "+r+":\n"+accntMap); PaxosMessage clientReply = new PaxosMessage(); Request cReq = new Request(r.getClientId(), r.getClientCommandId(), "Request Performed", bc); clientReply.setMessageType(PaxosMessageEnum.CLIENTRESP); clientReply.setRequest(cReq); clientReply.setSrcId(this.processId); writeToLog(this.processId+" sending response to client "+r.getClientId()+" for "+r.getClientCommandId()); sendMessage(r.getClientId(), clientReply); slotNumber++; }
9