text
stringlengths
14
410k
label
int32
0
9
public void clickOnMouseLeftButton(Field logicField, GraphicCell gCell, GraphicField gField) { // GraphicCell graphicCell1 = gCell; if (ActionCounters.getCounter() < GraphicField.NUMBER_OF_CELL && !Field.gameOver) { Cell[][] array = logicField.getArray(); Cell cell = array[gCell.getgX()][gCell.getgY()]; boolean cellIsClearOrNot = cell.getIsClean(); logicField.userMove((byte) gCell.getgX(), (byte) gCell.getgY()); if (cellIsClearOrNot) { gCell.setClean(false); gCell.setZero(false); cell.userMove(); } else { System.out.println("Ничего не ставлю, просто делаю Repaint()"); gCell.repaint(); return; } gCell.repaint(); ActionCounters.addOneAction(); if (logicField.checkForWin()) { Gui.gamePanel.getContentPane().repaint(); return; } Byte[] coordinatesCell; coordinatesCell = logicField.compMove(); if (coordinatesCell == null) { System.out.println("Компьютеру некуда ходить!!!"); Field.isWin = true; Field.isLose = true; Gui.gamePanel.getContentPane().repaint(); return; } int xx = coordinatesCell[0]; int yy = coordinatesCell[1]; GraphicCell graphicCell = gField.array[xx][yy]; graphicCell.setClean(false); graphicCell.setZero(true); graphicCell.repaint(); ActionCounters.addOneAction(); if (logicField.checkForWin()) { Gui.gamePanel.getContentPane().repaint(); } } }
6
public String parseToString(SecondaryStructure ss1, SecondaryStructure ss2, Geometry gg) { //return information needed in appropriate manner String stRes = cutToSize(gg.getStart(), 12); String endRes = cutToSize(gg.getEnd(), 10); String type = ""; if(ss1.getSSType().equals("S")) { type += "B"; } if(ss1.getSSType().equals("H")) { type += "A"; } if(ss1.getSSType().equals("T")) { type += "T"; } if(ss2.getSSType().equals("S")) { type += "B"; } if(ss2.getSSType().equals("H")) { type += "A"; } if(ss2.getSSType().equals("T")) { type += "T"; } type = cutToSize(type, 10); String d = cutToSize(gg.getD(), 8); String delta = cutToSize(gg.getDelta(), 8); String theta = cutToSize(gg.getTheta(), 8); String rho = cutToSize(gg.getRho(), 8); String bin = binMe(type, d, delta, theta, rho, Integer.parseInt(ss1.firstResidue().getResNum()), Integer.parseInt(ss2.lastResidue().getResNum())); return AnalyzeOneProtein.pdbID + " " + bin + " " + stRes + "" + endRes + "" + type + " " + d + " " + delta + " " + theta + " " + rho + ""; }
6
public void onRobotDeath(RobotDeathEvent event) { // If the robot that has died was our target, remove it as the target if (event.getName().equals(Observer.TARGET)) { Observer.TARGET = null; } }
1
public void endNode() { depth-- ; Node node = (Node)elementStack.pop(); if (node.clazz != null && node.isCollection) { if (node.fieldAlready) { readyForNewLine = true; } finishTag(); writer.write("]"); } else if (tagIsEmpty) { readyForNewLine = false; writer.write("{}"); finishTag(); } else { finishTag(); if (node.fieldAlready) { writer.write("}"); } } readyForNewLine = true; if (depth == 0 && ((mode & DROP_ROOT_MODE) == 0 || (depth > 0 && !node.isCollection))) { writer.write("}"); writer.flush(); } }
9
public static void UpperProducer(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Media set producer = CONCAT( UPPER( LEFT( producer, 1 ) ) , SUBSTRING( producer, 2 ))"); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ e.printStackTrace(); } }
4
@Test public void testSizeOfListInFile() throws IOException { cm.addFutureMeeting(contacts, new GregorianCalendar(2015,3,2)); cm.addNewPastMeeting(contacts, new GregorianCalendar(2013,5,3), "meeting"); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("contacts.txt")); List inputData = null; try { inputData = (ArrayList) ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } assertEquals(3, inputData.size()); }
1
protected static boolean compareBiomesById(final int p_151616_0_, final int p_151616_1_) { if (p_151616_0_ == p_151616_1_) { return true; } else if (p_151616_0_ != BiomeGenBase.mesaPlateau_F.biomeID && p_151616_0_ != BiomeGenBase.mesaPlateau.biomeID) { try { return BiomeGenBase.getBiome(p_151616_0_) != null && BiomeGenBase.getBiome(p_151616_1_) != null ? BiomeGenBase.getBiome(p_151616_0_).equals(BiomeGenBase.getBiome(p_151616_1_)) : false; } catch (Throwable throwable) { throw new RuntimeException(throwable); } } else { return p_151616_1_ == BiomeGenBase.mesaPlateau_F.biomeID || p_151616_1_ == BiomeGenBase.mesaPlateau.biomeID; } }
7
@Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return nameList.get(rowIndex); case 1: return regDateList.get(rowIndex); case 2: return lastLogDateList.get(rowIndex); case 3: return userIdList.get(rowIndex); default: return "0"; } }
4
* @param active Whether or not the active version of the color is needed. * @return The foreground color. */ public static Color getListForeground(boolean selected, boolean active) { if (selected) { Color color = UIManager.getColor("List.selectionForeground"); //$NON-NLS-1$ if (!active) { Color background = getListBackground(selected, active); boolean isBright = Colors.isBright(color); if (isBright == Colors.isBright(background)) { return isBright ? Color.BLACK : Color.WHITE; } } return color; } return Color.BLACK; }
4
public String getStudentType(Student student) { if (student.getCategory() == Student.Category.PRIMARIA) return "PRIMARIA"; else return "INFANTIL"; }
1
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
private void updateSet(String line) { if(line.equalsIgnoreCase("SpriteSet")) currentSet = Types.VGDL_SPRITE_SET; if(line.equalsIgnoreCase("InteractionSet")) currentSet = Types.VGDL_INTERACTION_SET; if(line.equalsIgnoreCase("LevelMapping")) currentSet = Types.VGDL_LEVEL_MAPPING; if(line.equalsIgnoreCase("TerminationSet")) currentSet = Types.VGDL_TERMINATION_SET; }
4
protected int widestDim(double[][] nodeRanges, double[][] universe) { final int classIdx = m_Instances.classIndex(); double widest = 0.0; int w = -1; if (m_NormalizeNodeWidth) { for (int i = 0; i < nodeRanges.length; i++) { double newWidest = nodeRanges[i][WIDTH] / universe[i][WIDTH]; if (newWidest > widest) { if (i == classIdx) continue; widest = newWidest; w = i; } } } else { for (int i = 0; i < nodeRanges.length; i++) { if (nodeRanges[i][WIDTH] > widest) { if (i == classIdx) continue; widest = nodeRanges[i][WIDTH]; w = i; } } } return w; }
7
private static int[] getNextArray (String pattern) { int size = pattern.length(); int[] next = new int[size]; next[0] = -1; // initialize nxet[0] = -1 if (size == 1) { return next; } next[1] = 0; // if the length of pattern > 1, initialize next[1] = 0; int j = 1; int k = next[1]; while (j < size - 1) { if (pattern.charAt(j) == pattern.charAt(k)) { next[j + 1] = k + 1; j++; } else if (k == 0) { // not match next[j + 1] = 0; j++; } else { k = next[k]; // k go back } } return next; }
4
public ResourceType getResourceTypeByName(String name) { ResourceType resourceType = null; for (int i = 0; i < resourceTypes.size(); i++) { resourceType = resourceTypes.get(i); if (resourceType.getName().equals(name)) { return resourceType; } } return resourceType; }
2
public void setComment(String comment) { this.comment = comment; }
0
public Tile[][] generateZBlock() { Tile[][] piece = new Tile[3][2]; for (int i = 0; i < piece.length; i++) for (int j = 0; j < piece[i].length; j++) { if ((i == 0 && j==0) || (i==1) || (i==2 && j==1)) { piece[i][j] = new Tile(Color.RED); piece[i][j].setX(i); piece[i][j].setY(j); } else { piece[i][j] = new Tile(Color.white); piece[i][j].setX(i); piece[i][j].setY(j); piece[i][j].setActive(false); } } return piece; }
7
public static void main(String args[]) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ String input = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); input = br.readLine(); } catch (IOException io) { io.printStackTrace(); } if (input == null || input.length() == 0 || input.length() > 50 || input.contains("1")) return; List<String> possibles = new ArrayList<String>(); int iterator = (1 << (input.length())) - 1; for (int i = 0; i <= iterator; i++) { String binaries = String.format("%" + input.length() + "s", Integer.toBinaryString(i)).replace(' ', '0'); char[] inputCopy = Arrays.copyOf(input.toCharArray(), input.length()); for (int j = 0; j < inputCopy.length; j++) { char c = binaries.charAt(j); if (c == '1') { inputCopy[j] = '1'; } } String inputCopyString = new String(inputCopy).replaceAll("1", ""); possibles.add(inputCopyString); } Collections.sort(possibles); System.out.println(possibles.get(possibles.size() - 1)); }
8
@Override public void toString(String indent, StringBuilder buffer) { int len = this.tags.size(); buffer.append("{ "); for (Map.Entry<String, NamedBinaryTag> entry : this.getValue().entrySet()) { buffer.append(entry.getKey()).append(": ").append(", "); } if (len > 0) { buffer.replace(buffer.length() - 2, buffer.length() - 1, " }"); } else { buffer.append('}'); } }
2
protected void handlePixelValue() { System.out.println("PIXEL VALUE"); BufferedImage img = this.getBufferedImage(); int displayPixel = 0; switch (displayedToolIndex) { case 1: displayPixel = img.getRGB((int)cover.getStartPoint().getX(), (int)cover.getStartPoint().getY()); break; case 2: int red=0, green=0, blue=0, total=0; int beginX, endX, beginY, endY; if (cover.getStartPoint().getX() > cover.getEndPoint().getX()) { beginX = (int) cover.getEndPoint().getX(); endX = (int) cover.getStartPoint().getX(); beginY = (int) cover.getEndPoint().getY(); endY = (int) cover.getStartPoint().getY(); } else { endX = (int) cover.getEndPoint().getX(); beginX = (int) cover.getStartPoint().getX(); beginY = (int) cover.getStartPoint().getY(); endY = (int) cover.getEndPoint().getY(); } double deltaY = (endY - beginY); double deltaX = (endX-beginX); double slope = deltaY/deltaX; System.out.println("SLOPE: " + slope); for (int x = beginX; x < endX; x++) { System.out.println(x + ", " + beginY); int pixel = img.getRGB(x, beginY); red += (pixel & 0xFF0000) >> 16; green += (pixel & 0x00FF00) >> 8; blue += (pixel & 0x0000FF); beginY += slope; total++; } displayPixel = (((red/total) << 16) | ((green/total) << 8) | (blue/total)); break; case 3: int[] arr = new int[(int)(Math.abs(cover.getEndPoint().getX()-cover.getStartPoint().getX()) * (int)Math.abs(cover.getEndPoint().getY()-cover.getStartPoint().getY()))]; arr = img.getRGB((int)cover.getStartPoint().getX(), (int)cover.getStartPoint().getY(), (int)Math.abs(cover.getEndPoint().getX()-cover.getStartPoint().getX()), (int)Math.abs(cover.getEndPoint().getY()-cover.getStartPoint().getY()), arr, 0, (int)Math.abs(cover.getEndPoint().getX()-cover.getStartPoint().getX())); displayPixel = averageValues(arr); break; } this.setPixelValue(displayPixel); }
5
public void writeTermsToFile(String strNumber, Hashtable<String, Double> oTermVsTFIDF) throws IOException { String strKey = null; Double maxValue = Double.MIN_VALUE; String strTerms = ""; int len = oTermVsTFIDF.size() < 5 ? oTermVsTFIDF.size() : 5; for (int i = 0; i < len; ++i) { for (Map.Entry<String, Double> entry : oTermVsTFIDF.entrySet()) { if (entry.getKey().length() > 2 && entry.getValue() > maxValue && !stopwordsMap.containsKey(entry.getKey() .toLowerCase()) && entry.getKey().matches("[a-zA-Z]+")) { maxValue = entry.getValue(); strKey = entry.getKey(); } } strTerms = strTerms + " " + strKey; oTermVsTFIDF.remove(strKey); strKey = null; maxValue = Double.MIN_VALUE; } oBufferedWriter.write(strNumber + " " + strTerms.trim() + "\n"); System.out.println(strTerms); }
7
public byte [] readControl (byte type, byte request, short value, short index, short length) throws IOException { byte data [] = new byte [length & 0xffff]; int status; if (length >= MAX_CONTROL_LENGTH || (type & ControlMessage.DIR_TO_HOST) == 0) throw new IllegalArgumentException (); if (Windows.trace) System.out.println ( "Dev.readControl, rqt 0x" + Integer.toHexString (0xff & type) + ", req 0x" + Integer.toHexString (0xff & request) + ", value 0x" + Integer.toHexString (0xffff & value) + ", index 0x" + Integer.toHexString (0xffff & index) + ", len " + Integer.toString (0xffff & length) ); status = controlMsg (fd, type, request, value, index, data, 0, (short) data.length); if (status >= 0) { if (status != data.length) { byte temp [] = new byte [status]; System.arraycopy (data, 0, temp, 0, status); data = temp; } return data; } throw new USBException ("control read error", -status); }
5
@Test public void testTotalwithRemoveEveryThing(){ for (int i=0;i<3;i++){ Main.addToTable(originalItemList.get(i), 2); } for (int i=0;i<3;i++){ Main.removeFromTable(0); } assertEquals(0, Main.getTotal()); }
2
@Override public Map<String, String> obtainUserRecord(String username) { Map<String, String> userRecord = new HashMap<String, String>(); // Find an user record in the entity bean User, passing a primary key of // username. User user = emgr.find(entity.User.class, username); // Determine whether the user exists if (user != null) { // Obtain the user record String email = user.getEmail(); String firstName = user.getFirstName(); String lastName = user.getLastName(); userRecord.put("EMAIL", email); userRecord.put("FIRST_NAME", firstName); userRecord.put("LAST_NAME", lastName); } return userRecord; }
1
public void addConfirmedUser(long uid) { if(!this.isRemoving()) return; this.aWaitingId.remove(uid); if(this.aWaitingId.size()<=0) { this.finalizeRemovalWithoutChecking(); } else { try { this.save(); } catch (SQLException e) { e.printStackTrace(); } } }
3
public void DBReadAllRooms(RoomnumberSet set) { final List<String> newAreasToCreate=new Vector<String>(); if(set==null) DBReadAllAreas(); if(CMLib.map().numAreas()==0) return; final RoomnumberSet unloadedRooms=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); final Map<String,Room> rooms=DBReadRoomData(null,set,set==null,newAreasToCreate,unloadedRooms); // handle stray areas for(final String areaName : newAreasToCreate) { Log.sysOut("Area","Creating unhandled area: "+areaName); final Area A=CMClass.getAreaType("StdArea"); A.setName(areaName); DBCreate(A); CMLib.map().addArea(A); for(final Map.Entry<String,Room> entry : rooms.entrySet()) { final Room R=entry.getValue(); if(R.getArea().Name().equals(areaName)) R.setArea(A); } } DBReadRoomExits(null,rooms,set==null,unloadedRooms); DBReadContent(null,null,rooms,unloadedRooms,set==null,true); if(set==null) CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Finalizing room data)"); for(final Map.Entry<String,Room> entry : rooms.entrySet()) { final Room thisRoom=entry.getValue(); thisRoom.startItemRejuv(); thisRoom.recoverRoomStats(); } if(set==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) a.nextElement().getAreaStats(); } }
9
@EventHandler(priority = EventPriority.NORMAL) public void onDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player && event.getCause() != DamageCause.VOID && event.getCause() != DamageCause.LAVA && event.getCause() != DamageCause.FIRE) { Player player = (Player) event.getEntity(); if (BowSpleef.invConfig.contains(player.getName())) { event.setCancelled(true); } } }
5
@Override public List<IProducto> filtrarProductos(List<IProducto> productos) { Boolean hubo_coincidencias = true; List<IProducto> prodsAplican = new ArrayList<IProducto>(); // productos que coinciden con un registro de la oferta List<IProducto> productos_encontrados = new ArrayList<IProducto>(); // copia de los registros de la oferta List<RegistroProducto> copia_registros = new ArrayList<RegistroProducto>( registro_productos); while (hubo_coincidencias) { /* * Por cada registro de la oferta, busca en todos los productos si * alguno coincide. Si encuentra uno, lo agrega a los productos * encontrados y saca ese registro de la lista copia de registros */ for (RegistroProducto registro : registro_productos) { for (IProducto producto : productos) { if (producto.validarRegistroProducto(registro)) { if (copia_registros.contains(registro)) { productos_encontrados.add(producto); copia_registros.remove(registro); } } } } // Termina si no encuentra combos if (!copia_registros.isEmpty()) { hubo_coincidencias = false; } else { for (IProducto producto : productos_encontrados) { productos.remove(producto); } ProductoCombo combo = new ProductoCombo(productos_encontrados); productos.add(combo); prodsAplican.add(combo); } productos_encontrados.clear(); copia_registros.clear(); copia_registros.addAll(registro_productos); } return prodsAplican; }
7
public void populateRestaurantPriceMap(int restaurantId, String[] inputTokens) { Restaurant res = restaurantMap.get(restaurantId); boolean checkFlag = true; int tokensLength = inputTokens.length; for (int i = 1; i < tokensLength; i++) { String item = inputTokens[i].trim(); Float price; if (res.checkItem(item)) { price = res.getItemPrice(item); } else if (res.checkItemInMeal(item)) { // check the item present in // the meal price = res.getMealPrice(item); } else { // If one of the requested item is missing then remove the // restaurant from the priceMap if (priceMap.get(restaurantId) != null) { priceMap.remove(restaurantId); } checkFlag = false; break; } // check already items of this restaurant added to the priceMap if (priceMap.get(restaurantId) == null) { priceMap.put(restaurantId, price); } else { priceMap.put(restaurantId, price + priceMap.get(restaurantId)); } } if (checkFlag) { Float price = getMinimumPriceForRestaurant(res, Arrays.asList(inputTokens).subList(1, tokensLength)); if (price != 0 && priceMap.get(restaurantId) > price) { priceMap.put(restaurantId, price); } } }
8
private static int findMatchingParenthesis(String regex, int index) { int count = 0; for (int i = index + 1; i < regex.length(); ++i) { if (count == 0 && regex.charAt(i) == ')') return i; else if (regex.charAt(i) == '(') ++count; else if (regex.charAt(i) == ')') --count; } return -1; }
5
private void readStudentList(File file) { BufferedReader FILE; try { String currentLine; FILE = new BufferedReader(new FileReader(file)); while ((currentLine = FILE.readLine()) != null) { String[] arg = currentLine.split(","); Student newStudent = new Student(Integer.parseInt(arg[0])); newStudent.setFirstName(arg[1]); newStudent.setLastName(arg[2]); newStudent.setGender(arg[3]); newStudent.setRace(arg[4]); for (int i = 0; i < Integer.parseInt(arg[5]); i++) { currentLine = FILE.readLine(); newStudent.avoid(new Student(Integer.parseInt(currentLine))); } students.add(newStudent); } FILE.close(); } catch (IOException e) { e.printStackTrace(); } for (Student student : students) { for (int i = 0; i < student.getAvoiding().size(); i++) { for (Student checkingstudent : students) { if (student.getAvoiding().get(i).equals(checkingstudent)) { student.getAvoiding().set(i, checkingstudent); } } } } }
7
private void voegOpdrachtToeAanQuiz() { try { if (!isToegevoegdeOpdracht(quiz.getOpdrachten(), quizWijzigenView .getListOpdrachten().getSelectedValue())) { for (Opdracht opdracht : opdrachtCatalogus.getOpdrachten()) { if (opdracht.equals(quizWijzigenView.getListOpdrachten() .getSelectedValue())) { quiz.getOpdrachten().add(opdracht); quizWijzigenView.setOpdrachtenInQuiz(quiz); } } } } catch (IllegalArgumentException e) { System.out.println(e); } catch (Exception e) { System.out.println(e); } }
5
public Set<String> getDownloadFileTypes(){ return this.downloadFileTypes; }
0
public SQLPermissionGroup(String n) { super(n); }
0
public void apply() { if (mStrategy != null) { mStrategy.findElement(); } }
1
@Override public void Borrar(Object value) { Session session = null; try { Liga ejecutivo = (Liga) value; session = NewHibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(ejecutivo); session.getTransaction().commit(); } catch (Exception e) { System.out.println(e.getMessage()); session.getTransaction().rollback(); } finally { if (session != null) { // session.close(); } } }
2
public static byte toByte(Object object) { if (object instanceof Number) { return ((Number) object).byteValue(); } try { return Byte.valueOf(object.toString()); } catch (NumberFormatException e) { } catch (NullPointerException e) { } return 0; }
3
public void write8bytes(long n) throws IOException { long b0 = n & 0xff; long b1 = (n & 0xff00) >> 8; long b2 = (n & 0xff0000) >> 16; long b3 = (n & 0xff000000) >>> 24; long b4 = (n & 0xff00000000L) >> 32; long b5 = (n & 0xff0000000000L) >> 40; long b6 = (n & 0xff000000000000L) >> 48; long b7 = (n & 0xff00000000000000L) >>> 56; if (le) { write(b0); write(b1); write(b2); write(b3); write(b4); write(b5); write(b6); write(b7); } else { write(b7); write(b6); write(b5); write(b4); write(b3); write(b2); write(b1); write(b0); } }
1
public int[] generate(int nplayers, int bowlsize) { Random random = new Random(); int nfruits = nplayers * bowlsize; int left = nfruits; int[] dist = new int[12]; for (int i = 1; i < 11; i++) { int cnt = random.nextInt(left); dist[i] = cnt; left -= cnt; } dist[0] = left; return dist; }
1
public void actionPerformed (ActionEvent ev) { //System.out.println(ev.getActionCommand()); // Clic BOUTON "Source" if (ev.getActionCommand().equals(txtBtSource)) {actionBtSource();} // Clic BOUTON "Dest" else if (ev.getActionCommand().equals(txtBtDest)) {actionBtDest();} // Action sur BT START else if(ev.getActionCommand().equals(txtBtStart)) {actionBtStart();} // Clic MENU "Charger" else if(ev.getActionCommand().equals(txtMenuCharger)) {actionMenuCharger();} // Clic MENU "Sauver" else if(ev.getActionCommand().equals(txtMenuSauver)) {actionMenuSauver();} // Clic MENU "Aide" else if(ev.getActionCommand().equals(txtMenuAide)) {actionMenuAide();} // Clic MENU "A propos..." else if(ev.getActionCommand().equals(txtMenuApropos)) {actionMenuApropos();} // MENU Quitter else if(ev.getActionCommand().equals(txtMenuQuitter)) {System.exit(0);} }
8
public void addPayment() { this.setTotal(this.getTotal()+this.calcPayment()); }
0
private static float pointIntersectsCircleOuterDetection( float pointX, float pointY, float speedX, float speedY, float radius, float outerCenterX, float outerCenterY, float outerRadius) { // Rearrange the parameters to form the quadratic equation double offsetPointX = pointX - outerCenterX; double offsetPointY = pointY - outerCenterY; double effectiveRadius = outerRadius - radius; double sqSpeedX = speedX * speedX; double sqSpeedY = speedY * speedY; double sqEffectiveRadius = effectiveRadius * effectiveRadius; double sqOffsetPointX = offsetPointX * offsetPointX; double sqOffsetPointY = offsetPointY * offsetPointY; double termA = sqSpeedX + sqSpeedY; double termB = 2.0 * (speedX * offsetPointX + speedY * offsetPointY); double termC = sqOffsetPointX + sqOffsetPointY - sqEffectiveRadius; double b2minus4ac = termB * termB - 4.0 * termA * termC; if (b2minus4ac < 0) { return Float.MAX_VALUE; } double rootB2minus4ac = Math.sqrt(b2minus4ac); double sol1 = (-termB + rootB2minus4ac) / (2.0 * termA); double sol2 = (-termB - rootB2minus4ac) / (2.0 * termA); // return the smaller positive solution if (sol1 > 0 && sol2 > 0) { return (float)Math.min(sol1, sol2); } else if (sol1 > 0) { return (float)sol1; } else if (sol2 > 0) { return (float)sol2; } else { return Float.MAX_VALUE; } }
5
public void visitForceChildren(final TreeVisitor visitor) { if (visitor.reverse()) { index.visit(visitor); array.visit(visitor); } else { array.visit(visitor); index.visit(visitor); } }
1
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(opciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(opciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(opciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(opciones.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 opciones().setVisible(true); } }); }
6
protected void setup() { if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "Hello World! This is Agent '" + getLocalName() + "'!"); world = new World(); new WumpusGUI(this).setVisible(true); dfd = new DFAgentDescription(); dfd.setName(this.getAID()); /* * Der Agent wird in den Yellow Pages registriert */ sd = new ServiceDescription(); sd.setName(WumpusConsts.GAME_SERVICE_NAME); sd.setType(WumpusConsts.GAME_SERVICE_TYPE); dfd.addServices(sd); try { if (DFService.search(this, gameAgent).length > 0) { if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "DEregister game '" + WumpusConsts.GAME_SERVICE_TYPE + "'"); DFService.deregister(this, gameAgent); } if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "Register game '" + WumpusConsts.GAME_SERVICE_TYPE + "'"); DFService.register(this, dfd); } catch (FIPAException e) { if(log.isLoggable(Logger.WARNING)) log.log(Logger.WARNING, "ERROR: " + e.getMessage()); e.printStackTrace(); } /* * Der Topic-Kanal für die Kommunikation mit allen spielenden Agenten * wird erzeugt. (Um allen den Tod des Wumpus verkünden zu können.) */ TopicManagementHelper hlp; try { hlp = (TopicManagementHelper) this.getHelper(TopicManagementHelper.SERVICE_NAME); this.topic = hlp.createTopic(WumpusConsts.GAME_TOPIC_NAME); } catch (ServiceException e) { throw new RuntimeException(e); } // /* // * Das Finite State Machine Behaviour, in dem sie // * für das Spiel benötigten Behaviour zusammengefasst // * sind, wird erzeugt und zum Agenten hinzugefügt. // */ // GameBehaviour fsm = new GameBehaviour(this); // this.addBehaviour(fsm); PlayGameBehaviour pgb = new PlayGameBehaviour(); this.addBehaviour(pgb); }
7
protected boolean isInt(Object obj) { return (obj != null && obj instanceof Integer); }
1
public void addProduct(Product p) { this.products.put(p.getCode(), p); }
0
public static int search_var_by_name(Variable_table variable_table, String name) { int num = variable_table.variable_name.size(); for (int i = 0; i < num; i++) { if (variable_table.variable_name.get(i).toString().equals(name)) { return i; } } return -1; }
2
public void setDatetime(Date datetime) { this.datetime = datetime; }
0
private void performDelete(Node z) { // create a node pointer y Node y; // if z has no left or right subtree if (z.left == null || z.right == null) { // set y to z y = z; } else { // set y as the successor of z y = successor(z); } // create a node pointer x Node x; // if y has a left subtree if (y.left != null) { // set x as that subtree x = y.left; } else { //otherwise set x as the right subtree of y x = y.right; } // if x is not null if (x != null) { // set the parent of x as the parent of y. x.parent = y.parent; } // if the parent of y is null if (y.parent == null) { // set x as the root root = x; } else if (y.equals(y.parent.left)) { // otherwise if y is the parent of the left subtree of y // set it to x y.parent.left = x; } else { // otherwise set the right subtree of the parent of y to x y.parent.right = x; } // if y is not z if (y != z) { // set the element of z to y z.key = y.key; } // decrease the size by 1 size--; }
7
public static String propertiesToString(BaseProperties props){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { props.store(baos, null); } catch (IOException e) { LOG.error("Caught IOException while trying to flush properties: " + e.getLocalizedMessage() + " because of: " + e.getCause()); } return baos.toString(); }
1
@Test public void addsAndPopsLikeAGoodStack() { assertTrue(stack.pop() == 1 && stack.pop() == 11 && stack.pop() == 3 && stack.pop() == 2); }
3
Transaction openWrite(Transaction me) { boolean cacheHit = false; // already open for read? // not in a transaction if (me == null) { // restore object if latest writer aborted if (writer.isAborted()) { rVersion.recover(); writer = Transaction.COMMITTED; } return null; } if (!me.isActive()) { throw new AbortedException(); } if (me == writer) { return null; } switch (writer.getStatus()) { case ACTIVE: return writer; case COMMITTED: rVersion.backup(); break; case ABORTED: rVersion.recover(); break; default: throw new PanicException(FORMAT, writer.getStatus()); } writer = me; if (!cacheHit) { me.memRefs++; manager.openSucceeded(); } LocalReadSet.getLocal().release(this); return null; }
8
public synchronized static LinkedList<Theater> getAllTheaters(int zone){ if(theaters.size() == 0) return null; LinkedList<Theater> result = new LinkedList<Theater>(); for(Theater t : theaters) if(t.getZone() == zone) result.add(t); if(result.size() == 0) return null; return result; }
4
public void CheckDyeCape() { boolean GoOn = true; int CapeXP = 0; int NewCape = -1; switch (useitems[0]) { case 1763: //red dye NewCape = 1007; CapeXP = 2; case 1767: //blue dye NewCape = 1021; CapeXP = 2; case 1765: //yellow dye NewCape = 1023; CapeXP = 2; case 1771: //green dye NewCape = 1027; CapeXP = 3; case 1773: //purple dye NewCape = 1029; CapeXP = 3; case 1769: //orange dye NewCape = 1031; CapeXP = 3; default: sendMessage("Nothing interesting is happening."); GoOn = false; break; } if (GoOn == true) { deleteItem(useitems[0], useitems[3], playerItemsN[useitems[3]]); deleteItem(useitems[1], useitems[2], playerItemsN[useitems[2]]); addItem(NewCape, 1); addSkillXP((CapeXP * crafting[3]), playerCrafting); } }
7
public void clearLevel(int no) { for (int i=0; i<height; ++i) { for (int j=0; j<width; ++j) { stack[i][j].setLayer(no, null); } } }
2
@Override public String getDesc() { return "HolyCrossAttack"; }
0
public void setFunApellidos(String funApellidos) { this.funApellidos = funApellidos; }
0
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Invoke the painter for the background if (painter != null) { Dimension d = getSize(); Graphics2D g2 = (Graphics2D) g; g2.setPaint(painter); g2.fill( new Rectangle(0, 0, d.width, d.height) ); } // Draw the image if (image == null ) return; switch (style) { case SCALED : drawScaled(g); break; case TILED : drawTiled(g); break; case ACTUAL : drawActual(g); break; case DETAIL_HOR : drawDetailHor(g); break; case BORDER : drawBorder(g); break; default: drawScaled(g); } }
7
public boolean isAnyLiquid(AxisAlignedBB par1AxisAlignedBB) { int var2 = MathHelper.floor_double(par1AxisAlignedBB.minX); int var3 = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); int var4 = MathHelper.floor_double(par1AxisAlignedBB.minY); int var5 = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); int var6 = MathHelper.floor_double(par1AxisAlignedBB.minZ); int var7 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); if (par1AxisAlignedBB.minX < 0.0D) { --var2; } if (par1AxisAlignedBB.minY < 0.0D) { --var4; } if (par1AxisAlignedBB.minZ < 0.0D) { --var6; } for (int var8 = var2; var8 < var3; ++var8) { for (int var9 = var4; var9 < var5; ++var9) { for (int var10 = var6; var10 < var7; ++var10) { Block var11 = Block.blocksList[this.getBlockId(var8, var9, var10)]; if (var11 != null && var11.blockMaterial.isLiquid()) { return true; } } } } return false; }
8
private void factor() { int n = R.numRows(); // Internal CRS matrix storage int[] colind = R.getColumnIndices(); int[] rowptr = R.getRowPointers(); double[] data = R.getData(); // Temporary storage of a dense row double[] Rk = new double[n]; // Find the indices to the diagonal entries int[] diagind = findDiagonalIndices(n, colind, rowptr); // Go down along the main diagonal for (int k = 0; k < n; ++k) { // Expand current row to dense storage Arrays.fill(Rk, 0); for (int i = rowptr[k]; i < rowptr[k + 1]; ++i) Rk[colind[i]] = data[i]; for (int i = 0; i < k; ++i) { // Get the current diagonal entry double Rii = data[diagind[i]]; if (Rii == 0) throw new RuntimeException("Zero pivot encountered on row " + (i + 1) + " during ICC process"); // Elimination factor double Rki = Rk[i] / Rii; if (Rki == 0) continue; // Traverse the sparse row i, reducing on row k for (int j = diagind[i] + 1; j < rowptr[i + 1]; ++j) Rk[colind[j]] -= Rki * data[j]; } // Store the row back into the factorisation matrix if (Rk[k] == 0) throw new RuntimeException( "Zero diagonal entry encountered on row " + (k + 1) + " during ICC process"); double sqRkk = Math.sqrt(Rk[k]); for (int i = diagind[k]; i < rowptr[k + 1]; ++i) data[i] = Rk[colind[i]] / sqRkk; } Rt = new UpperCompRowMatrix(R, diagind); }
8
private void drawCloudMap(Graphics graphics) { BufferedImage buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics gr = buffer.getGraphics(); for (int x = 0; x < mapWidth; x++) { for (int y = 0; y < mapHeight; y++) { double emptyAverage = 1; for (int t = 0; t < converter.numOfTileTypes(); t++) { emptyAverage -= tileTypeAverages[t][x][y]; } double r = emptyAverage * backgroundColor.getRed(); double g = emptyAverage * backgroundColor.getGreen(); double b = emptyAverage * backgroundColor.getBlue(); for (int t = 0; t < converter.numOfTileTypes(); t++) { Color tileColor = converter.colorReprisentation(t); r += tileTypeAverages[t][x][y] * tileColor.getRed(); g += tileTypeAverages[t][x][y] * tileColor.getGreen(); b += tileTypeAverages[t][x][y] * tileColor.getBlue(); } if (state == State.SELECTED) gr.setColor(new Color((int) (r / 1.1), (int) (g / 1.1), (int)b)); else gr.setColor(new Color((int)r, (int)g, (int)b)); gr.fillRect(x * blockWidth, y * blockHeight, blockWidth, blockHeight); } } int panelWidth = getWidth(); int panelHeight = getHeight(); gr.setColor(Color.black); switch (state) { case SELECTED: case INSPECTED: gr.setColor(Color.blue); case MOUSEOVER: gr.drawRect(1, 1, panelWidth - 3, panelHeight - 3); gr.drawRect(2, 2, panelWidth - 5, panelHeight - 5); case IDLE: gr.drawRect(0, 0, panelWidth - 1, getHeight() - 1); break; } gr.setColor(Color.black); Graphics2D graphics2d = (Graphics2D) graphics; graphics2d.drawImage(buffer, null, 0, 0); }
9
public static String getMergeSql(String table, String colnames, String keynames) { StringBuilder sb = new StringBuilder(); sb.append("MERGE INTO " + table + " a "); sb.append(" USING (SELECT "); String[] colnamelist = colnames.split(","); for (int i = 0; i < colnamelist.length; i++) { String col = colnamelist[i].trim(); sb.append(" ? " + col); if (i < colnamelist.length - 1) sb.append(","); } sb.append(" FROM dual) b "); sb.append("ON ("); String[] keynamelist = keynames.split(","); for (int i = 0; i < keynamelist.length; i++) { String keyname = keynamelist[i].trim(); sb.append(" a." + keyname + "= b." + keyname); if (i < keynamelist.length - 1) sb.append(" AND "); } sb.append(") " + "WHEN MATCHED THEN "); String updatenames = ""; for (int i = 0; i < colnamelist.length; i++) { String colname = colnamelist[i].trim(); if (!(keynames + ",").contains(colname + ",")) { updatenames += " a." + colname + "= b." + colname; updatenames += (" ,"); } } if (updatenames.endsWith(",")) updatenames = updatenames.substring(0, updatenames.length() - 1); sb.append(" UPDATE SET " + updatenames); sb.append(" WHEN NOT MATCHED THEN INSERT (" + colnames + ") "); sb.append(" VALUES ("); for (int i = 0; i < colnamelist.length; i++) { String col = colnamelist[i].trim(); sb.append(" b." + col); if (i < colnamelist.length - 1) sb.append(","); } sb.append(")"); return sb.toString(); }
9
public void SetMaximumPassenger(int maximumPassenger) { if(maximumPassenger > this.maximumPassenger) this.maximumPassenger = maximumPassenger; }
1
public void deadRemoval() { ArrayList<Integer> dead = new ArrayList<Integer>(); int i = 0; for (Asteroid a : asteroids) { if (!a.getAlive()) { dead.add(i); } i++; } i = 0; for (int d : dead) { asteroids.remove(d - i); i++; } dead.clear(); i = 0; for (Laser l : lasers) { if (!l.getAlive()) { dead.add(i); } i++; } i = 0; try { for (int d : dead) { lasers.remove(d - i); i++; } } catch (Exception e) { } }
7
public void actionPerformed(ActionEvent e) { String nick = GUIMain.userList.getSelectedValue().toString(); if (nick.startsWith("@")) { nick = nick.replace("@", ""); } else if (nick.startsWith("$")) { nick = nick.replace("$", ""); } else if (nick.startsWith("+")) { nick = nick.replace("+", ""); } else if (nick.startsWith("%")) { nick = nick.replace("%", ""); } else if (nick.startsWith("~")) { nick = nick.replace("~", ""); } Command.voice(nick); }
5
public static void insertCarte(Carte carte) { PreparedStatement stat; try { stat = ConnexionDB.getConnection().prepareStatement("insert into carte (serialNumber) values (?)"); stat.setString(1, carte.getSerialNumber()); stat.executeUpdate(); } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } }
2
public void initializeConverter(Automaton automaton) { MAP = new HashMap(); State[] states = automaton.getStates(); State initialState = automaton.getInitialState(); // Do the variables. VARIABLE = new LinkedList(); for (char c = 'A'; c <= 'Z'; c++) VARIABLE.add("" + c); // Map the initial state to S. if (initialState != null) { VARIABLE.remove(START_VARIABLE); MAP.put(initialState, START_VARIABLE); } // Assign variables to the other states. List stateList = new ArrayList(Arrays.asList(states)); stateList.remove(initialState); Collections.sort(stateList, new Comparator() { public int compare(Object o1, Object o2) { return ((State) o1).getID() - ((State) o2).getID(); } public boolean equals(Object o) { return false; } }); Iterator it = stateList.iterator(); while (it.hasNext()) { State state = (State) it.next(); MAP.put(state, VARIABLE.removeFirst()); } }
3
@Override public void setNull(int intId, String strTabla, String strCampo) throws Exception { Statement oStatement; try { oStatement = (Statement) oConexionMySQL.createStatement(); String strSQL = "UPDATE " + strTabla + " SET " + strCampo + " = null WHERE id = " + Integer.toString(intId); oStatement.executeUpdate(strSQL); } catch (SQLException e) { throw new Exception("mysql.setNull: Error al modificar el registro: " + e.getMessage()); } }
1
private ServiceManager() { }
0
public RuleBased(GenData gen) throws IOException{ this.data = gen; writer = new BufferedWriter(new FileWriter("featureMatrix.txt")); y = new BufferedWriter(new FileWriter("label.txt")); for(User u:data.userMap.values()){ u.addDiffFeature(); for(int i=0; i<featuresize; i++){ if(u.features.get(i) > maxPerFeature[i]){ maxPerFeature[i] = u.features.get(i); } } } for(Business b:data.businessMap.values()){ labels.add(b.stars); List<Double> sample; double [] featureForWeight = new double[featuresize]; int numuser = 0; for(User u:b.users){ numuser++; sample = u.multiply(b, maxPerFeature); aggregate(sample, featureForWeight); } for(int i=0; i<featuresize; i++){ writer.write(featureForWeight[i]+"\t"); } y.write(numuser*b.stars+"\n"); writer.write("\n"); } writer.close(); y.close(); // add reading the weights learnt and then call calcCredibility }
6
public boolean isIn(double x1, double y1){ if ((x <= x1) && (x1 <= (x + length)) && (y <= y1) && (y1 <= (y + height)) ){ return true; }else return false; }
4
public void AddPoint(double x, double y, int index) { if (index > PointArray.length - 1) { index = PointArray.length; } else if (index < 0) { index = 0; } double temp[] = new double[PointArray.length + 2]; for (int i = 0; i <= temp.length - 1; i++) { if (i > index + 1) { temp[i] = PointArray[i - 2]; } else if (i < index) { temp[i] = PointArray[i]; } else if (i == index) { temp[i] = x; } else { temp[i] = y; } } PointArray = temp; }
6
private void lifeCycle() { String s = ""; int attempt_number = 0; do { try { s = readInput(); if (s.length()==0) { break; } action(s); attempt_number++; } catch (IOException e) { e.printStackTrace(); } } while (attempt_number<=VALUE_ITERATIONS_NUMBER-1); printResults(); }
3
private String fontTypeToString(int fontType) { if (fontType == FONT_OPEN_TYPE) { return "Open Type Font"; } else if (fontType == FONT_TRUE_TYPE) { return "True Type Font"; } else if (fontType == FONT_TYPE_0) { return "Type 0 Font"; } else if (fontType == FONT_TYPE_1) { return "Type 1 Font"; } else if (fontType == FONT_TYPE_3) { return "Type 3 Font"; } else { return "unkown font type: " + fontType; } }
5
@Override public String toString() { StringBuilder buf1 = new StringBuilder(); if (isPrinter()) { for (MoneyPrinter printer : printers) { buf1.append(printer.toString()); } } StringBuilder buf2 = new StringBuilder(); if (isParser()) { for (MoneyParser parser : parsers) { buf2.append(parser.toString()); } } String str1 = buf1.toString(); String str2 = buf2.toString(); if (isPrinter() && isParser() == false) { return str1; } else if (isParser() && isPrinter() == false) { return str2; } else if (str1.equals(str2)) { return str1; } else { return str1 + ":" + str2; } }
9
public void update() { shift = (int) (Math.random()*4); if (Math.random() < .5) { for (int i = 0; i < shift;i++) { if (!collisionCheck(getX() + 1,getY())) addX(1); else break; } }else { for (int i = 0; i < shift;i++) { if (!collisionCheck(getX() - 1,getY())) addX(-1); else break; } } //TODO SINKING IN WATER if (getY() > 0 && inLoc[getX()][getY()-1] != null && (inLoc[getX()][getY()-1] instanceof FallingParticle) && !(inLoc[getX()][getY()-1] instanceof Water)) { swap(inLoc[getX()][getY()-1]); } super.update(); }
9
public void cal(int x, int y, int m, int n, int[][] matrix) { if (n <= 0 || m <= 0) return; for (int i = 0; i < n; i++) res.add(matrix[x][i + y]); for (int i = 1; i < m; i++) res.add(matrix[x + i][y + n - 1]); for (int i = 1; i < n; i++) if (x + m - 1 > x) res.add(matrix[x + m - 1][y + n - 1 - i]); for (int i = 1; i < m - 1; i++) if (x + m - 1 - i > 0 && n != 1) res.add(matrix[x + m - 1 - i][y]); cal(x + 1, y + 1, m - 2, n - 2, matrix); }
9
public void broadCast(String s){ for (BTHandler h:this.handler){ h.send(s.getBytes()); } }
1
public int getExperience() { return experience; }
0
public String toString() { switch (typecode) { case TC_LONG: return "long"; case TC_FLOAT: return "float"; case TC_DOUBLE: return "double"; case TC_NULL: return "null"; case TC_VOID: return "void"; case TC_UNKNOWN: return "<unknown>"; case TC_ERROR: default: return "<error>"; } }
7
private boolean onJonkinMuunPalikanVieressa(Sijainti sijainti) { if(palikat.isEmpty()) return true; for(Palikka palikka : palikat) if(palikka != null && onVieressa(((TetriminoPalikka)palikka).sijainti(), sijainti)) return true; return false; }
4
public void build() { for (Field f : this.bagFields) { try { Object value = f.get(this); if (value != null) { ResourceBag.class.cast(value).build(); } } catch (IllegalAccessException e) { throw new RuntimeException("Failed to access a resource bag!", e); } } }
3
private Node fixUp(Node h) { if (isRedNode(h.right)) h = rotateLeft(h); if (isRedNode(h.left) && isRedNode(h.left.left)) h = rotateRight(h); if (isRedNode(h.left) && isRedNode(h.right)) flipColors(h); return h; }
5
public void listenSocket() { try { server = new ServerSocket( 80 ); } catch( IOException e ) { System.out.println( "Could not listen on port 80" ); System.exit( -1 ); } while( true ) { try { client = server.accept(); } catch( IOException e ) { System.out.println( "Accept failed: 80" ); System.exit( -1 ); } try { socketNum = (int) (Math.random() * MAX_PORT_NUM); while( socketNum.intValue() < 80 ) { socketNum = (int) (Math.random() * MAX_PORT_NUM); } usedPorts.add( socketNum ); in = new BufferedReader( new InputStreamReader( client. getInputStream() ) ); out = new PrintWriter( client.getOutputStream(), true ); System.out.println( "Po uruchomieniu wątku" ); } catch( IOException e ) { System.out.println( "Accept failed: 80" ); System.exit( -1 ); } try { //line = "NP " + socketNum; line = "404"; out.println( line ); } catch( Exception e ) { System.out.println( "Read failed" ); System.exit( -1 ); } } }
6
public String getTripFrom() { if (river == null) return "<?>"; return river.getTripFrom(); }
1
@Override protected DataSet doParse() { try { return doFixedLengthFile(getDataSourceReader()); } catch (final IOException e) { LOGGER.error("error accessing/reading data", e); } return null; }
1
public void computeLCS() { int diag = 0; for (int i = 1; i < seq1.length; i++) { diag = 0; for (int j = 1; j < seq2.length; j++) { diag = length[j]; if (seq1[i] == seq2[j]) { length[j] = length[j] + 1; } else if (length[j] < length[j-1]) { length[j] = length[j-1]; } } } }
4
public void setMusicLoudness(MusicLoudness musicLoudness) { this.musicLoudness = musicLoudness; }
0
private void setStationType(Player player) { // List<TicketType> ticketTypes = new ArrayList<TicketType>(); // gets all the possible edges the player can transverse given their current node and loops through them for (Edge a : player.getNodeNeighbours()) { // adds each edge type to the ticketTypes list if (a.type().equals(Edge.EdgeType.Bus)) ticketTypes.add(TicketType.Bus); else if (a.type().equals(Edge.EdgeType.Taxi)) ticketTypes.add(TicketType.Taxi); else if (a.type().equals(Edge.EdgeType.Underground)) ticketTypes.add(TicketType.Underground); } /* * After adding all the ticketTypes for each edge, if the array contains * a bus and underground combination - it is a taxi/bus/underground * station If the array contains a bus type, it is a taxi/bus station * Otherwise it is just a taxi station Sets the player station type to * this station type */ if (ticketTypes.contains(TicketType.Bus) && ticketTypes.contains(TicketType.Underground)) player.setStationType(Player.currentStationType.BusTaxiUnderground); else if (ticketTypes.contains(TicketType.Bus)) player.setStationType(Player.currentStationType.BusTaxi); else player.setStationType(Player.currentStationType.Taxi); }
7
public boolean intersectsBelow(RPChromosomeRegion testRegion) { // Only need to test if some part of this region is below and some within test region. if (startChromID < testRegion.startChromID || (startChromID == testRegion.startChromID && startBase < testRegion.startBase)) { if (endChromID > testRegion.startChromID || (endChromID == testRegion.startChromID && endBase > testRegion.startBase)) return true; else return false; } else return false; }
6
static final void method3012(int i, int i_44_, int i_45_, int i_46_, int i_47_, byte i_48_, int i_49_, int i_50_) { anInt6918++; int i_51_ = 0; int i_52_ = i; int i_53_ = 0; int i_54_ = -i_50_ + i_45_; int i_55_ = -i_50_ + i; int i_56_ = i_45_ * i_45_; int i_57_ = i * i; int i_58_ = i_54_ * i_54_; int i_59_ = i_55_ * i_55_; int i_60_ = i_57_ << -2100977983; int i_61_ = i_56_ << 804146657; int i_62_ = i_59_ << -1847202623; int i_63_ = i_58_ << -673422751; int i_64_ = i << 1215643457; int i_65_ = i_55_ << 1293803873; int i_66_ = i_60_ + (-i_64_ + 1) * i_56_; int i_67_ = i_57_ + -(i_61_ * (i_64_ - 1)); int i_68_ = i_62_ + (-i_65_ + 1) * i_58_; int i_69_ = -((i_65_ + -1) * i_63_) + i_59_; int i_70_ = i_56_ << 455767874; int i_71_ = i_57_ << -682134078; int i_72_ = i_58_ << -1899579550; int i_73_ = i_59_ << -700391294; int i_74_ = 3 * i_60_; int i_75_ = (-3 + i_64_) * i_61_; int i_76_ = 3 * i_62_; int i_77_ = i_63_ * (-3 + i_65_); int i_78_ = i_71_; int i_79_ = i_70_ * (-1 + i); int i_80_ = 51 / ((i_48_ - -63) / 44); int i_81_ = i_73_; int i_82_ = (-1 + i_55_) * i_72_; int[] is = AnimationDefinition.anIntArrayArray255[i_49_]; Class135_Sub2.method1156(-27, i_47_ - i_54_, is, -i_45_ + i_47_, i_46_); Class135_Sub2.method1156(-27, i_47_ + i_54_, is, -i_54_ + i_47_, i_44_); Class135_Sub2.method1156(-27, i_45_ + i_47_, is, i_47_ + i_54_, i_46_); while (i_52_ > 0) { boolean bool = i_55_ >= i_52_; if ((i_66_ ^ 0xffffffff) > -1) { while (i_66_ < 0) { i_67_ += i_78_; i_66_ += i_74_; i_78_ += i_71_; i_51_++; i_74_ += i_71_; } } if (bool) { if ((i_68_ ^ 0xffffffff) > -1) { while (i_68_ < 0) { i_69_ += i_81_; i_68_ += i_76_; i_53_++; i_81_ += i_73_; i_76_ += i_73_; } } if ((i_69_ ^ 0xffffffff) > -1) { i_69_ += i_81_; i_68_ += i_76_; i_76_ += i_73_; i_53_++; i_81_ += i_73_; } i_69_ += -i_77_; i_68_ += -i_82_; i_77_ -= i_72_; i_82_ -= i_72_; } if ((i_67_ ^ 0xffffffff) > -1) { i_67_ += i_78_; i_66_ += i_74_; i_78_ += i_71_; i_51_++; i_74_ += i_71_; } i_67_ += -i_75_; i_66_ += -i_79_; i_75_ -= i_70_; i_52_--; i_79_ -= i_70_; int i_83_ = -i_52_ + i_49_; int i_84_ = i_49_ - -i_52_; int i_85_ = i_51_ + i_47_; int i_86_ = -i_51_ + i_47_; if (bool) { int i_87_ = i_47_ + i_53_; int i_88_ = -i_53_ + i_47_; Class135_Sub2.method1156(-27, i_88_, AnimationDefinition.anIntArrayArray255[i_83_], i_86_, i_46_); Class135_Sub2.method1156(-27, i_87_, AnimationDefinition.anIntArrayArray255[i_83_], i_88_, i_44_); Class135_Sub2.method1156(-27, i_85_, AnimationDefinition.anIntArrayArray255[i_83_], i_87_, i_46_); Class135_Sub2.method1156(-27, i_88_, AnimationDefinition.anIntArrayArray255[i_84_], i_86_, i_46_); Class135_Sub2.method1156(-27, i_87_, AnimationDefinition.anIntArrayArray255[i_84_], i_88_, i_44_); Class135_Sub2.method1156(-27, i_85_, AnimationDefinition.anIntArrayArray255[i_84_], i_87_, i_46_); } else { Class135_Sub2.method1156(-27, i_85_, AnimationDefinition.anIntArrayArray255[i_83_], i_86_, i_46_); Class135_Sub2.method1156(-27, i_85_, AnimationDefinition.anIntArrayArray255[i_84_], i_86_, i_46_); } } }
9
public CompilationUnit getCompilationUnit(Lexer lexer) { for (CompilationUnit unit: units) { if (unit.getLexer().equals(lexer)) return unit; } return null; }
2
public static HttpServletRequest addBill(HttpServletRequest request){ Models.DatabaseModel.Bill bill = new Models.DatabaseModel.Bill(); Models.DatabaseModel.Patient patient = new Models.DatabaseModel.Patient(); int patientID; if (request.getParameter("patientID") == null){ patientID = patient.addPatient(request.getParameter("patientName")); } else { patientID = Integer.parseInt(request.getParameter("patientID")); } patient = patient.findPatient(patientID); int billID = bill.addBill(patientID, Integer.parseInt(request.getParameter("consultationCost"))); bill = bill.findBill(billID); Models.ViewModel.Bill billView = new Models.ViewModel.Bill(bill, patient, bill.getBillTotalCost(billID)); ArrayList<Models.DatabaseModel.BillItem> billItems = Models.DatabaseModel.BillItem.listBillItems(bill.getId()); ArrayList<Models.DatabaseModel.Medicine> medicines = Models.DatabaseModel.Medicine.listMedicines(); billView.setMedicines(medicines); billView.setBillItems(getBillItems(billItems, medicines)); request.setAttribute("billView", billView); request.setAttribute("view", "billview.jsp"); return request; }
1
public static String encryptMD5(String pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); StringBuffer stringBuffer = new StringBuffer(); int n; byte[] b = md.digest(); for (int i = 0; i < b.length; i++) { n = b[i]; if (n < 0) { n += 256; } // stringBuffer.append(Integer.toHexString(n / 16) + Integer.toHexString(n % 16)); if (n < 16) { stringBuffer.append("0"); } stringBuffer.append(Integer.toHexString(n)); } return stringBuffer.toString(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
4
public Chromo<T> getFittestChromo() { return new Chromo<>(fittestChromo.getGenes(), fittestChromo.getFitness()); }
0
public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; }
7
public Set<Map.Entry<Double,Integer>> entrySet() { return new AbstractSet<Map.Entry<Double,Integer>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TDoubleIntMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TDoubleIntMapDecorator.this.containsKey(k) && TDoubleIntMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Double,Integer>> iterator() { return new Iterator<Map.Entry<Double,Integer>>() { private final TDoubleIntIterator it = _map.iterator(); public Map.Entry<Double,Integer> next() { it.advance(); double ik = it.key(); final Double key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); int iv = it.value(); final Integer v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Double,Integer>() { private Integer val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Double getKey() { return key; } public Integer getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Integer setValue( Integer value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Double,Integer> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Double key = ( ( Map.Entry<Double,Integer> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Double, Integer>> c ) { throw new UnsupportedOperationException(); } public void clear() { TDoubleIntMapDecorator.this.clear(); } }; }
8
public void addServiceListener(IServiceListener listener) { this._listeners.add(listener); }
0
public Response signup(Response resp, JSONObject data) { try { if(data.has("name") && !v.isNullOrEmpty(data.getString("name")) && data.has("email") && v.isValidEmail(data.getString("email")) && data.has("website") && v.isValidURL(data.getString("website"))) { User user = UserDAO.instance().get(d.hasher(data.getString("email"))); if(user.getKey() != null) { } else { user.setEmail(data.getString("email")); user.setDate(new Date().getTime()); user.setName(data.getString("name")); user.setDomain(data.getString("website")); user.setStatus(UserStatus.NEW.getValue()); UserDAO.instance().set(user); Linker linker = LinkerDAO.instance().get(KeyBuilder.LIVE_NEW_USER_STACK.getValue()); linker.setKey(KeyBuilder.LIVE_NEW_USER_STACK.getValue()); Set<String> newUsersList = linker.getList(); newUsersList.add(user.getKey()); LinkerDAO.instance().set(linker); resp = resp.change(200, resp, "Success."); } log.info("customer mail id-->"+data.getString("email")); MailingService.sendMail("registration",data.getString("email")); return resp; } throw new Exception(); } catch(Exception e) { e.printStackTrace(); resp = resp.change(500, resp, e.getMessage()); } return resp; }
8