text
stringlengths
14
410k
label
int32
0
9
public void drawHealthBars(SpriteBatch sb){ Color tint = sb.getColor(); for(Entity e: healthBars.keySet()){ for(int i = 0; i < e.getMaxHealth(); i++){ if(i<=e.getHealth()) if(e.frozen) sb.setColor(Color.CYAN); else sb.setColor(Color.RED); else sb.setColor(Color.GRAY); sb.draw(pixel, e.getPixelPosition().x + i - (int)(e.getMaxHealth()/2f), e.getPixelPosition().y + e.rh + 5); } sb.setColor(tint); } }
4
public int getTotalTermCount(SQLconnection sqLconnection, int paperID) { String query = "select totalcount from papertermcount where paperID=" + paperID; int count = 0; ResultSet rs = sqLconnection.Query(query); try { rs.next(); count = rs.getInt("totalcount"); rs.close(); } catch (SQLException e) { e.printStackTrace(); } return count; }
1
private static int DFS(TreeNode node) { if (node.left == null && node.right == null) { return 1; } if (node.left != null && node.right == null) { return DFS(node.left) + 1; } if (node.left == null && node.right != null) { return DFS(node.right) + 1; } return Math.min(DFS(node.left), DFS(node.right)) + 1; }
6
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // Paint background, border //------------ Collision detection //Check the pellets roundCheck(1);//pellets single and doubleshots //Rocket check roundCheck(0);//0 is rockets //check the takeover rockets roundCheck(3); //------------Drawing // Draw the balls. for (Ball b : Data.m_balls) { if (b.painted){ b.draw(g,Color.BLUE); } else { b.draw(g, Color.BLACK); } } // Draw the gun m_gun.draw(g); // Draw all flying pellets for (Pellet p : Data.p_list) { p.draw(g); } //Draw the rockets for (Rocket r:Data.r_list) { r.draw(g); } for (TakeOverRocket tar:Data.tar_list) { tar.draw(g); } //Draw the explosion particles for(Explosion expl : Data.exp_list){ for(Pellet pExplosion:expl.explosionParticles){ if((int)(Math.random()*10)>5){ g.setColor(Color.red); }else{ g.setColor(Color.yellow); } pExplosion.draw(g); } } }
8
public static void update() { for(Keybind keybinds : Keybind.values()) { keybinds.key.setHeld(keybinds.key.isPressed()); keybinds.key.update(); } }
1
@EventHandler public void GhastWither(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Ghast.Wither.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof Fireball) { Fireball a = (Fireball) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getGhastConfig().getBoolean("Ghast.Wither.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, plugin.getGhastConfig().getInt("Ghast.Wither.Time"), plugin.getGhastConfig().getInt("Ghast.Wither.Power"))); } } }
7
public String longestCommonPrefix(String[] strs) { if(strs.length ==0) return ""; if(strs.length ==1) return strs[0]; for(int i =0;;i++){ for(int j=0;j< strs.length;j++){ if(i >= strs[j].length()) return strs[j].substring(0, i); else{ if(strs[j].charAt(i) != strs[0].charAt(i)) return strs[0].substring(0, i); } } } }
6
@Override public String toString() { switch(this) { case BIANCO: return "BIANCO"; case NERO: return "NERO"; case NULL: return "NULL"; default: throw new IllegalArgumentException(); } }
3
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(AjouterService.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AjouterService.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AjouterService.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AjouterService.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 AjouterService().setVisible(true); } }); }
6
@Override public int delete(Integer idMetier) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
0
public String toString() { StringBuilder sb = new StringBuilder(); int c1 = 18; int sc = 6; // Print header sb.append(String.format("%" + c1 + "s |", "Category")); for (Player player : players) { sb.append(String.format(" %-" + (sc * 3 + 4) + "s |", player.getName())); } sb.append("\n"); for (Category category : Category.allCategories) { sb.append(String.format("%" + c1 + "s |", category.getTitle() + (category.isComputed() ? "=" : ":"))); for (Player player : players) { for (int i = 0; i < 3; i++) { Integer score = category.getScore(player, i); sb.append(String.format(" %" + sc + "s ", score == null ? "" : score.toString())); } sb.append(" |"); } sb.append("\n"); } sb.append(String.format("%" + c1 + "s |", "Grand Total")); for (Player player : players) { sb.append(String.format(" %" + (sc * 3 + 4) + "s |", player.getGrandTotal())); } sb.append("\n"); return sb.toString(); }
7
void init() { addTypeConverter(String.class, Long.class, Long::valueOf); addTypeConverter(String.class, Long.TYPE, Long::valueOf); addTypeConverter(String.class, Integer.class, Integer::valueOf); addTypeConverter(String.class, Integer.TYPE, Integer::valueOf); addTypeConverter(String.class, Byte.class, Byte::valueOf); addTypeConverter(String.class, Byte.TYPE, Byte::valueOf); addTypeConverter(String.class, Short.class, Short::valueOf); addTypeConverter(String.class, Short.TYPE, Short::valueOf); addTypeConverter(String.class, Boolean.class, ExtraConverters::toBoolean); addTypeConverter(String.class, Boolean.TYPE, ExtraConverters::toBoolean); addTypeConverter(String.class, Float.class, Float::valueOf); addTypeConverter(String.class, Float.TYPE, Float::valueOf); addTypeConverter(String.class, Double.class, Double::valueOf); addTypeConverter(String.class, Double.TYPE, Double::valueOf); addTypeConverter(String.class, Character.class, (instance) -> (instance != null) ? instance.charAt(0) : (char) (byte) 0); addTypeConverter(String.class, Character.TYPE, (instance) -> (instance != null) ? instance.charAt(0) : (char) (byte) 0); addTypeConverter(String.class, Double.TYPE, Double::valueOf); addTypeConverter(String.class, BigDecimal.class, BigDecimal::new); addTypeConverter(Number.class, Long.class, (instance) -> ExtraConverters.toNumber(instance, Long.class)); addTypeConverter(Number.class, Long.TYPE, (instance) -> ExtraConverters.toNumber(instance, Long.class)); addTypeConverter(Number.class, Integer.class, (instance) -> ExtraConverters.toNumber(instance, Integer.class)); addTypeConverter(Number.class, Integer.TYPE, (instance) -> ExtraConverters.toNumber(instance, Integer.class)); addTypeConverter(Number.class, Byte.class, (instance) -> ExtraConverters.toNumber(instance, Byte.class)); addTypeConverter(Number.class, Byte.TYPE, (instance) -> ExtraConverters.toNumber(instance, Byte.class)); addTypeConverter(Number.class, Short.class, (instance) -> ExtraConverters.toNumber(instance, Short.class)); addTypeConverter(Number.class, Short.TYPE, (instance) -> ExtraConverters.toNumber(instance, Short.class)); addTypeConverter(Number.class, Boolean.class, ExtraConverters::toBoolean); addTypeConverter(Number.class, Boolean.TYPE, ExtraConverters::toBoolean); addTypeConverter(Number.class, Float.class, (instance) -> ExtraConverters.toNumber(instance, Float.class)); addTypeConverter(Number.class, Float.TYPE, (instance) -> ExtraConverters.toNumber(instance, Float.class)); addTypeConverter(Number.class, Double.class, (instance) -> ExtraConverters.toNumber(instance, Double.class)); addTypeConverter(Number.class, Double.TYPE, (instance) -> ExtraConverters.toNumber(instance, Double.class)); addTypeConverter(Number.class, BigDecimal.class, ExtraConverters::toBigDecimal); addTypeConverter(Object.class, String.class, Object::toString); addTypeConverter(Character.class, Boolean.class, ExtraConverters::toBoolean); addTypeConverter(Number.class, Boolean.TYPE, ExtraConverters::toBoolean); addTypeConverter(LocalDateTime.class, LocalDate.class, (LocalDateTime instance) -> instance.toLocalDate()); addTypeConverter(LocalDate.class, LocalDateTime.class, (LocalDate instance) -> instance.atStartOfDay()); addTypeConverter(LocalDateTime.class, Date.class, ExtraConverters::localDateTimeToDate); addTypeConverter(Date.class, LocalDateTime.class, ExtraConverters::dateToLocalDateTime); addTypeConverter(String.class, LocalDateTime.class,ExtraConverters::stringToLocalDateTime); addTypeConverter(LocalDateTime.class, String.class,ExtraConverters::localDateTimeToString); addTypeConverter(String.class, LocalDate.class,ExtraConverters::stringToLocalDate); addTypeConverter(LocalDate.class, String.class,ExtraConverters::localDateToString); }
2
public int roomChooser(){ list.clear(); for(int i=0; i<map.size(); i++){ int[] tmp = new int[6]; tmp = getValue(i); if ((tmp[0]==1)&&(tmp[1]==1)){ list.add(i); } } int l = list.size(); int m = (int)(Math.random()*l); return list.get(m); }
3
public void addPeriod(Period per) { this.periods.add(per); }
0
@Override public void run() { long lastCycle = 0; long systemTime; while (isRunning()) { systemTime = System.currentTimeMillis(); if ((systemTime - lastCycle) > cycleLength) { if (getTasks().size() > 0) { Iterator<ITask> it = getTasks().iterator(); while (it.hasNext()) { if (!it.next().run()) it.remove(); } } long timeTaken = System.currentTimeMillis() - systemTime; if (timeTaken > cycleLength) { System.out.println("Engine overloaded by " + ((timeTaken / cycleLength) * 100) + "%"); } else { try { sleep(cycleLength - timeTaken); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
7
private void drawPhysicsVariables() { g2d.setTransform(identity); g2d.setColor(Color.RED); Ship s = DataController.getInstance().getPlayerShip(); double dX = (s.getDest()==null)?0:s.getDest().getX(); double dY = (s.getDest()==null)?0:s.getDest().getY(); String temp; temp = String.format("Name: %s", s.getName()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 15); temp = String.format("Position: (%.2f,%.2f)",s.getPosition().getX(), s.getPosition().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 30); temp = String.format("Center: (%.2f,%.2f)", s.getCenter().getX(), s.getCenter().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 45); temp = String.format("Velocity: (%.2f,%.2f)", s.getXVelocity(), s.getYVelocity()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 60); temp = String.format("NetVelocity: %.2f Moving: %.2f", s.getNetVelocity(), s.getMoving()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 75); temp = "Accelerate: "+s.isAccel()+" Reverse: "+s.istReverse(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 90); temp = "TurnLeft: "+s.isTurnLeft()+" TurnRight: "+s.isTurnRight(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 105); temp = "Alive: "+s.isAlive()+" Initialized: "+s.isInitialized(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 120); temp = String.format("Facing: %.2f TurnSpeed: %.0f", s.getFacing(), s.getTurnSpeed()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 135); temp = String.format("Offset: (%.2f,%.2f)", dX, dY); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 150); temp = String.format("Dest: (%.2f,%.2f)", dX+s.getCenter().getX(), dY+s.getCenter().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, 165); s = DataController.getInstance().getShipAt(secondShip); if(s != null) { dX = (s.getDest()==null)?0:s.getDest().getX(); dY = (s.getDest()==null)?0:s.getDest().getY(); temp = String.format("Name: %s", s.getName()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-170); temp = String.format("Position: (%.2f,%.2f)",s.getPosition().getX(), s.getPosition().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-155); temp = String.format("Center: (%.2f,%.2f)", s.getCenter().getX(), s.getCenter().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-140); temp = String.format("Velocity: (%.2f,%.2f)", s.getXVelocity(), s.getYVelocity()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-125); temp = String.format("NetVelocity: %.2f Moving: %.2f", s.getNetVelocity(), s.getMoving()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-110); temp = "Accelerate: "+s.isAccel()+" Reverse: "+s.istReverse(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-95); temp = "TurnLeft: "+s.isTurnLeft()+" TurnRight: "+s.isTurnRight(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-80); temp = "Alive: "+s.isAlive()+" Initialized: "+s.isInitialized(); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-65); temp = String.format("Facing: %.2f TurnSpeed: %.0f", s.getFacing(), s.getTurnSpeed()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-50); temp = String.format("Offset: (%.2f,%.2f)", dX, dY); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-35); temp = String.format("Dest: (%.2f,%.2f)", dX+s.getCenter().getX(), dY+s.getCenter().getY()); g2d.drawChars(temp.toCharArray(), 0, temp.length(), bounds.width-200, bounds.height-20); } }
5
public void transferResultToNextGen(NeighbourhoodMatrix nextgen, PVector source, TemplateMatrix templateCopy) { // transfer non-zero cells from rectified to correct target octant Octant oct = new Octant(source.heading()); for(int col=0; col<3; col++) for (int row=0; row<3; row++) { PVector v = templateCopy.getCell(col, row).getWind(); if (v.mag() > 0){ Coords cr = oct.rotatedColAndRow(col, row); CellBase cell = nextgen.getCell(cr.col, cr.row); if (cell instanceof WindCell){ handleWindCellTarget(v, cell); } else if (cell instanceof ObstacleCell){ // TODO: add obstacle handling } } } }
5
private static int booleanString(boolean b){ if(b){ return 1; } else{ return 0; } }
1
private boolean light(int xa, int ya, int dir) { List<Light> lights = level.getLights(x, y, dir); if (lights.size() <= 0) return false; Light light = lights.get(0); if (light.intensity > 30) return false; if (light.dir == 3) { light.x--; } else if (light.dir == 1) { light.x++; } else if (light.dir == 0) { light.y--; } else if (light.dir == 2) { light.y++; } return true; /* for (int i = 0; i < lights.size(); i++) { if (light) }*/ }
6
public void Add(Tick t) { synchronized(ticks) { if (!ticks.contains(t)) ticks.add(t); } }
1
public static List<Laureate> filterByPrizeYearRange( List<Laureate> inputList, String startYear, String endYear) { List<Laureate> outputList = new ArrayList<Laureate>(); int sYear = Integer.getInteger(startYear); int eYear = Integer.getInteger(endYear); // parse input, keep what matchs the terms. for (Laureate Awinner : inputList) { int year = Integer.getInteger(Awinner.getYear()); if (year >= sYear) { if (year <= ((eYear < 0) ? (year + 1) : eYear)) { outputList.add(Awinner); } } } return outputList; }
4
public Place getPlaceInDirection(Place currentPlace, String direction) { int x = currentPlace.getLocation().getX(); int y = currentPlace.getLocation().getY(); if (direction.equals("East") && x + 1 < myLength) return myPlaceGrid[x + 1][y]; else if (direction.equals("South") && y + 1 < myWidth) return myPlaceGrid[x][y + 1]; else if (direction.equals("West") && x - 1 >= 0 ) return myPlaceGrid[x - 1][y]; else if (direction.equals("North") && y - 1 >= 0) return myPlaceGrid[x][y - 1]; return null; }
8
public synchronized boolean isBeenPlayed() { boolean result = !(game == null) && !game.hasStarted() || isWaitingForUsers; if (playerCount == 0) { result = false; game = null; } return result; }
3
@RequestMapping(value = {"/MovimientoBancario/{idMovimientoBancario}"}, method = RequestMethod.GET) public void read(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idMovimientoBancario") int idMovimientoBancario) { try { ObjectMapper jackson = new ObjectMapper(); String json = jackson.writeValueAsString(movimientoBancarioDAO.read(idMovimientoBancario)); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json; charset=UTF-8"); noCache(httpServletResponse); httpServletResponse.getWriter().println(json); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
2
@Override public Clock deepCopy() { LogicClock newClock = new LogicClock(); newClock.clock = this.clock; return newClock; }
0
public void log(String str) { FileWriter fw = null; try { fw = new FileWriter(this.logFile, true); String date = new Date().toString(); fw.write(date + " : " + str); fw.write(LINE_SEPARATOR); } catch (IOException e) { System.err.println("Couldn't log this : " + str); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
private int getDeciSeconds() { if (last == null || !last.hasNext()) { // less than min, but more than the half int half = (Math.round(MIN_SECONDS / 2) - 1) * 10; return (new Random()).nextInt(half) + half; } else { int sec = last.getSeconds(); if ((new Random()).nextBoolean()) { return (sec * 10) + (new Random()).nextInt(sec * 4); } else { return (sec * 10) - (new Random()).nextInt(sec * 2); } } }
3
protected static String pwdElaborate( String p ){ String[] words; String answer; int numLenght = 10; if ( p.equals( "-an" ) ) { charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; numLenght = 62; } else if ( p.equals( "-a" ) ) { charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; numLenght = 52; } else if ( p.equals( "-n" ) ) { charset = "1234567890"; numLenght = 10; } else if ( p.equals( "-ans" ) ) { charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!£()*+@#[]£$%&/=?^'|"; numLenght = 82; } System.out.print( "Please insert the length of the password: " ); n = inputInt(); words = new String[n]; System.out.println( "\n" ); if (n > 25) { System.out.println( "Warning: as the password is longer, it uses more system resources!" ); System.out.print( "Do you want to continue? " ); answer = inputStr(); System.out.println( "\r\n" ); if ( answer.equals( "yes") || answer.equals( "y" ) ) { for( int j = 0 ; j < n ; j++ ){ int a = (int)( Math.random() * numLenght ); words[j] = charset.substring( a, a + 1 ); buffer += words[j]; } } else buffer = "\r\nError: too many characters!\r\n"; } else { for( int j = 0 ; j < n ; j++ ) { int a = (int)( Math.random() * numLenght ); words[j] = charset.substring( a, a + 1 ); buffer += words[j]; } } return buffer; }
9
public boolean doTransformations() { StructuredBlock last = flowBlock.lastModified; return (!isEntered && CompleteSynchronized.enter(this, last)) || (isEntered && object == null && CompleteSynchronized .combineObject(this, last)); }
4
public String getId() { return id; }
0
@Override public NormalLikeDistribution[] getOrderDistributions(double mean, double sd) { double[] divisors = new double[numberOfOrderPeriods]; double sum = 0; for (int i = 0; i < numberOfOrderPeriods;i++){ divisors[i] = i+1; sum += i+1; } RealSinglePointDistribution emptyOrder = new RealSinglePointDistribution(0); NormalLikeDistribution[] orderDistributions = new NormalLikeDistribution[numberOfOrderPeriods+offSet]; for (int i = 0; i < orderDistributions.length; i++){ if (i < offSet) orderDistributions[i] = emptyOrder; else { double orderMean = (divisors[i-offSet]/(sum*1.0))*mean; double orderSd = Math.sqrt(((divisors[i-offSet]/(sum*1.0))*(sd*sd))); orderDistributions[i] = new NormalDistribution(orderMean, orderSd); } } return orderDistributions; }
3
public boolean isInString(String string, String s) { int stringLength = string.length(); int lowestCount = d; for (int i = 0; i < stringLength - this.k + 1; i++) { String compare = string.substring(i, i + this.k); int count = 0; for (int j = 0; j < this.k; j++) { if (compare.charAt(j) != s.charAt(j)) { count++; } } if (count <= lowestCount) { return true; } } return false; }
4
public void gravarTurmasDeDisciplinasEmArquivo(String nomeArquivo) throws IOException { BufferedWriter gravador = null; try { gravador = new BufferedWriter(new FileWriter(nomeArquivo)); for (Disciplina disciplina : this.disciplina) { gravador.write(disciplina.getCodigo() + "\n"); gravador.write(disciplina.getTurmas().size() + "\n"); for (int k = 0; k < disciplina.getTurmas().size(); k++) { Turma t = disciplina.getTurmas().get(k); gravador.write(t.getNumero() + "\n"); } } } finally { if (gravador != null) { gravador.close(); } } }
3
public void setSelected(int selected) { this.selected = selected; if (selected >= 0) { sel.setText(Integer.toString(selected)); } else { sel.setText(""); } sel.revalidate(); }
1
public static boolean isGetter(Method method) { if(!method.getName().startsWith("get")) return false; if(method.getParameterTypes().length != 0) return false; if(void.class.equals(method.getReturnType())) return false; return true; }
3
@EventHandler public void onChat(AsyncPlayerChatEvent event) { final Player player = event.getPlayer(); if (player.getName().equalsIgnoreCase("jacklin213") || player.hasPermission("linbot.access")) { String msg = event.getMessage(); String[] words = msg.split(" "); if (words[0].startsWith("!")) { final String[] args = this.toArgs(words); final String cmdName = this.toCmdName(words[0]); final LinBotCommand cmd = plugin.commandHandler.matchCommand(cmdName); if (this.execptionCheck(cmdName)) { event.setCancelled(true); plugin.MSG.commandReply(player, msg); } if (plugin.getOnline() == false) { if (this.offlineCmd(cmdName)) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { cmd.executeCmd(player, cmdName, args); } }, 10); return; } event.setMessage(msg); return; } if(plugin.isSleep()) plugin.commandHandler.matchCommand("sleep").executeCmd(Bukkit.getConsoleSender(), "sleep", null); if (cmd != null) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { cmd.executeCmd(player, cmdName, args); } }, 10); } } } }
8
final public String selectexpr() throws ParseException { /*@bgen(jjtree) SEL */ SimpleNode jjtn000 = new SimpleNode(JJTSEL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t; String s; String sel = ""; try { t = jj_consume_token(SELECT); sel += t.image.toString(); s = conditions(); sel += s; jj_consume_token(25); s = expression(); jj_consume_token(26); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; sel += "(" + s + ")"; jjtn000.value = sel; {if (true) return sel;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
9
protected boolean sendAck(int tag,boolean status,int gridletId,int destId) { boolean success = false; switch (tag) { case GridSimTags.GRIDLET_PAUSE_ACK: case GridSimTags.GRIDLET_RESUME_ACK: case GridSimTags.GRIDLET_SUBMIT_ACK: int[] array = new int[ARRAY_SIZE]; array[0] = gridletId; if (status) { array[1] = GridSimTags.TRUE; } else { array[1] = GridSimTags.FALSE; } super.sim_schedule( outputPort_, GridSimTags.SCHEDULE_NOW, tag, new IO_data(array, 8, destId) ); success = true; break; default: System.out.println(super.get_name() + ".sendAck(): Invalid tag ID."); break; } return success; }
4
public void shuttleSort(boolean printpasses) { for (int pass = 1; pass < elements.length; pass++) { for (int i = pass; i > 0; i--) { T current = elements[i]; T other = elements[i - 1]; int compResult = current.compareTo(other); if (compResult > 0) { //current is larger break; } if (compResult < 0) { //current is smaller elements[i - 1] = current; elements[i] = other; } } if (printpasses) { System.out.println(this); } } }
5
@Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("version_check")) { int value = (Integer) evt.getNewValue(); if (value == RESULT_UP_TO_DATE) { setVisible(false); Application.window = new BotWindow(); Application.window.init(true); System.out.println("UP_TO_DATE"); } else if (value == RESULT_OUT_OF_DATE) { BotWindow.error("Out of date!", "Fluid has been updated, re-download the new version at http://www.fluidbot.com/"); System.out.println("OUT_OF_DATE"); System.exit(0); } else if (value == RESULT_FALLBACK) { setVisible(false); BotWindow.warn("Friendly Reminder", "To stay updated, always use the updater to launch Fluid."); Application.window = new BotWindow(); Application.window.init(false); System.out.println("FALLBACK_OFFLINE_MODE"); } } }
4
public boolean isAdmin(String forumId, User user) { for (int i = 0; i < forums.size(); i++) { if (forums.get(i).getId().equals(forumId)) return forums.get(i).isAdmin(user); } return false; }
2
/*package protected */boolean fireDockableStateWillChange(DockableStateWillChangeEvent e) { DockingDesktop desk = e.getFutureState().getDesktop(); if(desk.getMaximizedDockable() != null) { // veto events coming from autohide and floating components if a component is maximized // @todo : this could be improved by disabling the dock and attach properties of // the remaining visible dockables to avoid having the user don't understand // why a button doesn't react. if(desk.getMaximizedDockable() != e.getCurrentState().getDockable()) { if(e.getFutureState().isDocked()) { if(e.getCurrentState().isHidden()) { return false; // refused } else if(e.getCurrentState().isFloating()) { return false; } } } } // dispatch events and listen to vetoes for(int i = 0; i < dockableStateWillChangeListeners.size(); i++) { DockableStateWillChangeListener listener = dockableStateWillChangeListeners.get(i); listener.dockableStateWillChange(e); if(! e.isAccepted()) { // stop as soon as the operation is cancelled return false; } } return true; }
7
private boolean jj_3_8() { if (jj_3R_26()) return true; return false; }
1
@Override public void validate() { Graphics g = getGraphics(); final FontMetrics fontMetrics = g.getFontMetrics(); String[] allLines = content.split("\n"); int allLinesN = allLines.length; int nLines = 0; int h = 0; for (int i = 0; i < allLinesN; ++i) { h += fontMetrics.getHeight(); if (h <= textArea.getPreferredSize().height) { ++nLines; } else { break; } } String[] lineContents = new String[nLines]; visibleContent = ""; for (int i = 0; i < lineContents.length; ++i) { String l = ""; String lin = allLines[i]; int w = 0; for (char c : lin.toCharArray()) { w += fontMetrics.charWidth(c); if (w <= textArea.getPreferredSize().width) { l += c; } else { break; } } lineContents[i] = l; visibleContent += l + "\n"; } updateLineContent(visibleContent, true); textArea.setText(visibleContent.trim()); }
5
public void expand(double factor) { if(factor < this.min) { this.min = factor; } if(factor > this.max) { this.max = factor; } }
2
@Test public void testLoadFromCacheSuccessOnCustomPage() { AbstractPage p = AbstractPage.bakeAPage(null,"http://noctura.bandcamp.com/album/demos", null, null); assertEquals(true, p.loadFromCache()); assertEquals("Demos", p.getTitle()); assertEquals(7, p.childPages.size()); boolean found = false; for (AbstractPage childPage: p.childPages) { if (childPage.url.toString().equals( "http://noctura.bandcamp.com/track/dont-save-me-acoustic-for-x103")) found = true; } assertEquals(true, found); }
2
public void initialize() { if (GameApplet.thisApplet != null) { Enumeration localEnumeration = getEnvironment().getObjects().elements(); while (localEnumeration.hasMoreElements()) { Object localObject = localEnumeration.nextElement(); if (!(localObject instanceof Cannon)) continue; this.shooter = ((Cannon)localObject); return; } } }
3
public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Counting words"); int n = scan.nextInt(); String[] wordsStr = new String[n]; for(int i=0; i<n; i++) { wordsStr[i] = scan.next(); } Arrays.sort(wordsStr); for(int i=0; i<n; i++) { System.out.println(wordsStr[i]); } }
2
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true) public void onQuit(PlayerQuitEvent event) throws IOException { Player player = event.getPlayer(); if (DataBase.isInCombat(player)) { long end = DataBase.getEndingTime(player); if (!Clock.isEnded(end)) { if (player.getGameMode() != GameMode.CREATIVE) { if (Configuration.dropItemsEnabled()) { dropItems(player); } if (Configuration.dropArmorEnabled()) { dropArmor(player); } if (Configuration.dropExpEnabled()) { dropExp(player); } } } } }
6
static private int jjMoveStringLiteralDfa14_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(12, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(13, active0); return 14; } switch(curChar) { case 116: return jjMoveStringLiteralDfa15_0(active0, 0x2000000L); default : break; } return jjStartNfa_0(13, active0); }
3
public boolean isRelationalOp() { return val.equals(LT) || val.equals(LE) || val.equals(EQ) || val.equals(NE) || val.equals(GT) || val.equals(GE); }
5
public boolean Check(ArrayList<Integer> slv){ HashSet<Integer> tmp = new HashSet(); for (int i : slv){ tmp.addAll(sets.get(i)); } return nodes.equals(tmp); }
1
public static String getSystemTmpDirectory () { if (systemTmpDir != null) { return (systemTmpDir); } String dir = getProperty("java.io.tmpdir"); if (dir == null) { dir = getProperty("TMP"); } if (dir == null) { dir = getProperty("TEMP"); } if (dir == null) { dir = getProperty("TMPDIR"); } if (dir != null) { systemTmpDir = dir; return (dir); } if (!isWindows()) { systemTmpDir = "/tmp"; return (systemTmpDir); } String drive = getProperty("SystemDrive"); if (drive != null) { char c = drive.charAt(drive.length() - 1); if (c != '\\' && c != '/') { systemTmpDir = drive + "\\TEMP"; } else { systemTmpDir = drive + "TEMP"; } return (systemTmpDir); } systemTmpDir = "\\TEMP"; return (systemTmpDir); }
9
public long getNumberOfSamples() { if (this.isMpeg) { // audioInputStream.getFrameLength() returns -1 for MP3s // thus another method is needed: // the following WORKAROUND will approximate the number of samples only // - usually it is SMALLER! return this.durationMicrosec / 1000 * (long) this.sampleRate / 1000; } else return this.audioInputStream.getFrameLength(); }
1
public static void main(String[] args) { // TODO Auto-generated method stub boolean vorhanden = false; Person[] personen = new Person[0]; do { String nachname = Tastatur.inputString("Nachname: "); String vorname = Tastatur.inputString("Vorname: "); String geschlecht = Tastatur.inputString("Geschlecht (w/m) :"); int alter = Tastatur.inputint("Alter: "); Person neuerDat = new Person(nachname, vorname, geschlecht, alter); for (int k = 0; k < personen.length; k++) { if (neuerDat.equals(personen[k])) { personen[k] = neuerDat; vorhanden = true; } } if (vorhanden == true) { vorhanden = false; } else{ personen=erweitern(personen); personen[personen.length-1] = neuerDat; } } while(Tastatur.inputchar("Weitere Daten einlesen: (j/n)")=='j'); for (int i = 0; i < personen.length; i++) { System.out.println(personen[i].toString()); } }
5
protected long getNextCallId() { final ReentrantLock l = lock; l.lock(); try { if (++prevCallId > Long.MAX_VALUE) { prevCallId = Long.MIN_VALUE; } return prevCallId; } finally { l.unlock(); } }
1
public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int result = 0; int n = in.nextInt(); int k = in.nextInt(); List<Integer> n_table = new ArrayList<Integer>(); for (int i = 0 ; i < n ; i++){ n_table.add(0); } do { if (n_table.size()<= k){ k = n_table.size(); } int j = 0; int num_on_owl = k; while (j<num_on_owl) { n_table.set(j,(n_table.get(j)+1)); if (n_table.get(j)==2){ n_table.remove(j); num_on_owl--; j--; } j++; } result++; Collections.sort(n_table); }while (n_table.size()>0); out.println(result); out.flush(); }
5
private final void checkSliderPosition() { if (isVertical) { if (slider.getYD() < y + scrollBarThickness) slider.setY(y + scrollBarThickness); else if (slider.getYD() + slider.getHeightD() > y + height - scrollBarThickness) slider.setY(y + height - slider.getHeightD() - scrollBarThickness); if (isVertical)// Make slider gradient vertical too { GradientPaint g1 = slider.gradientUp; GradientPaint g2 = slider.gradientDown; slider.gradientUp = new GradientPaint(slider.getXI() + (slider.getWidthI() / 3), slider.getYI(), g1.getColor1(), slider.getXI() + slider.getWidthI() + (slider.getWidthI() / 3), slider.getYI(), g1.getColor2(), g1.isCyclic()); slider.gradientDown = new GradientPaint(slider.getXI() + (slider.getWidthI() / 3), slider.getYI(), g2.getColor1(), slider.getXI() + slider.getWidthI() + (slider.getWidthI() / 3), slider.getYI(), g2.getColor2(), g2.isCyclic()); } } else { if (slider.getXD() < x + scrollBarThickness) slider.setX(x + scrollBarThickness); else if (slider.getXD() + slider.getWidthD() > x + width - scrollBarThickness) slider.setX(x + width - slider.getWidthD() - scrollBarThickness); } }
6
private void btnReplaceItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnReplaceItemActionPerformed {//GEN-HEADEREND:event_btnReplaceItemActionPerformed if (!archive.fileExists(selectedPath)) throw new UnsupportedOperationException("oops, bug"); JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setDialogTitle("Choose a file to import"); String lastfile = Preferences.userRoot().get("lastFileReplaced", null); if (lastfile != null) fc.setSelectedFile(new File(lastfile)); if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; String selfile = fc.getSelectedFile().getPath(); Preferences.userRoot().put("lastFileReplaced", selfile); try { FileBase srcfile = new ExternalFile(selfile, "r"); FileBase dstfile = archive.openFile(selectedPath); dstfile.setLength(srcfile.getLength()); dstfile.setContents(srcfile.getContents()); dstfile.save(); trySave(); dstfile.close(); srcfile.close(); } catch (IOException ex) { lblStatusLabel.setText("Failed to replace file: "+ex.getMessage()); } setFileDescription(treeNodes.get(selectedPath)); }//GEN-LAST:event_btnReplaceItemActionPerformed
4
private void cargarSetPrueba(){ DefaultTableModel temp = (DefaultTableModel) this.tablaSetPruebas.getModel(); String csvFile = "dataset/diabetes_prueba.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { double maximo0 = normalizacion.obtenerMaximo(0, csvFile); double maximo1 = normalizacion.obtenerMaximo(1, csvFile); double maximo2 = normalizacion.obtenerMaximo(2, csvFile); double maximo3 = normalizacion.obtenerMaximo(3, csvFile); double maximo4 = normalizacion.obtenerMaximo(4, csvFile); double maximo5 = normalizacion.obtenerMaximo(5, csvFile); double maximo6 = normalizacion.obtenerMaximo(6, csvFile); double maximo7 = normalizacion.obtenerMaximo(7, csvFile); double minimo0 = normalizacion.obtenerMinimo(0, csvFile); double minimo1 = normalizacion.obtenerMinimo(1, csvFile); double minimo2 = normalizacion.obtenerMinimo(2, csvFile); double minimo3 = normalizacion.obtenerMinimo(3, csvFile); double minimo4 = normalizacion.obtenerMinimo(4, csvFile); double minimo5 = normalizacion.obtenerMinimo(5, csvFile); double minimo6 = normalizacion.obtenerMinimo(6, csvFile); double minimo7 = normalizacion.obtenerMinimo(7, csvFile); br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] patron = line.split(cvsSplitBy); if(normalizar.equals("NO")){ Object nuevo[]= {patron[0], patron[1], patron[2], patron[3], patron[4], patron[5], patron[6], patron[7], "-"}; temp.addRow(nuevo); }else if(normalizar.equals("MAX")){ Object nuevo[]= {String.valueOf(Double.valueOf(patron[0])/maximo0), String.valueOf(Double.valueOf(patron[1])/maximo1), String.valueOf(Double.valueOf(patron[2])/maximo2), String.valueOf(Double.valueOf(patron[3])/maximo3), String.valueOf(Double.valueOf(patron[4])/maximo4), String.valueOf(Double.valueOf(patron[5])/maximo5), String.valueOf(Double.valueOf(patron[6])/maximo6), String.valueOf(Double.valueOf(patron[7])/maximo7), "-" }; temp.addRow(nuevo); }else if(normalizar.equals("MAX/MIN")){ Object nuevo[]= {String.valueOf((double)(Double.valueOf(patron[0])-minimo0)/(double)(maximo0-minimo0)), String.valueOf((double)(Double.valueOf(patron[1])-minimo1)/(double)(maximo1-minimo1)), String.valueOf((double)(Double.valueOf(patron[2])-minimo2)/(double)(maximo2-minimo2)), String.valueOf((double)(Double.valueOf(patron[3])-minimo3)/(double)(maximo3-minimo3)), String.valueOf((double)(Double.valueOf(patron[4])-minimo4)/(double)(maximo4-minimo4)), String.valueOf((double)(Double.valueOf(patron[5])-minimo5)/(double)(maximo5-minimo5)), String.valueOf((double)(Double.valueOf(patron[6])-minimo6)/(double)(maximo6-minimo6)), String.valueOf((double)(Double.valueOf(patron[7])-minimo7)/(double)(maximo7-minimo7)), "-" }; temp.addRow(nuevo); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { System.out.println("Error accediendo al csv prueba"); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
9
public static void takeTurn(int turn) { int food = AntColony.node[13][13].food; // The queen eats one unit of food in node 13,13 per turn if (food == 0) AntColony.endSim = true; else AntColony.node[13][13].setFoodAmount(food - 1); // The queen hatches a new ant once per day (every ten turns) if (turn % 10 == 0) { Ant ant; ForagerAnt foragerAnt; int antIDNum = AntColony.activeAnts.getLast().getIDNum() + 1; int antAge = 0; int antMode = 0; int antLocX = 13; int antLocY = 13; boolean antIsAlive = true; Stack<ColonyNodeView> moveHist = new Stack<ColonyNodeView>(); // Creates a new ant: 25% Scout, 25% Soldier, 50% Forager int rNum; rNum = RandomNumGen.randomNumber(0, 3); if (rNum == 0) { ant = new Ant(antIDNum, "scout", antAge, antIsAlive, antMode, antLocX, antLocY); AntColony.node[13][13].setScoutCount(AntColony.node[13][13].scouts + 1); AntColony.activeAnts.add(ant); } else if (rNum == 2) { ant = new Ant(antIDNum, "soldier", antAge, antIsAlive, antMode, antLocX, antLocY); AntColony.node[13][13].setSoldierCount(AntColony.node[13][13].soldiers + 1); AntColony.activeAnts.add(ant); } else { foragerAnt = new ForagerAnt(antIDNum, "forager", antAge, antIsAlive, antMode, antLocX, antLocY, moveHist); AntColony.node[13][13].setForagerCount(AntColony.node[13][13].foragers + 1); AntColony.activeAnts.add(foragerAnt); foragerAnt.movementHistory.push(AntColony.node [foragerAnt.getLocationX()][foragerAnt.getLocationY()]); } } }
4
public Matrix minus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions."); Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] - B.data[i][j]; return C; }
4
public static String[] dealString(String str){ String[] s = str.split(":"); //s[0] s[0] = s[0].trim(); int first = s[0].indexOf(" "); int last = s[0].lastIndexOf(" "); //ոֵλòͬ޳ if(first<last){ String[] subStr = s[0].split(" "); StringBuffer sb = new StringBuffer(); sb.append(subStr[0]); for(int i=1; i<subStr.length; i++){ if(!subStr[i-1].equals("") && subStr[i].equals("")){ sb.append(" "); }else if(subStr[i-1].equals("") && !subStr[i].equals("")){ sb.append(subStr[i]); }else{ continue; } } s[0] = sb.toString(); } //s[1] s[1] = s[1].trim(); String mailName; String size; if(!s[1].contains("=")){ s[1] = s[1].replace("<", "").replace(">", "").trim(); return s; }else{ int left = s[1].indexOf("<"); int right = s[1].indexOf(">"); mailName = s[1].substring(left+1, right).trim(); int lastCh = str.indexOf("="); size = str.substring(lastCh+1).trim(); } String[] ss = {s[0], mailName, size}; return ss; }
7
public static BufferedImage crop(BufferedImage image) { int width = image.getWidth(), height = image.getHeight(), minX = width, maxX = 0, minY = height, maxY = 0; for( int x = 0; x < width; x++) for( int y = 0; y < height; y++ ) { if( (image.getRGB(x, y) & 0x00FFFFFF) != 0 ) { if( x < minX ) minX = x; else if( x > maxX ) maxX = x; if( y < minY ) minY = y; else if( y > maxY) maxY = y; } } int w = maxX - minX, h = maxY - minY; BufferedImage cropped = new BufferedImage(w, h, image.getType()); for( int i = 0; i < h; i++ ) for( int j = 0; j < w; j++ ) { cropped.setRGB(j, i, image.getRGB(minX+j, minY+i)); } return cropped; }
9
public State getStateForVariable(String variable, VariableDependencyGraph graph) { State[] states = graph.getStates(); for (int k = 0; k < states.length; k++) { if (states[k].getName().equals(variable)) return states[k]; } return null; }
2
public static void validateNumericTypes(Number number1, Number number2) { if ((number1 instanceof Integer) && (number2 instanceof Integer)) { return; } if ((number1 instanceof Long) && (number2 instanceof Long)) { return; } if ((number1 instanceof Double) && (number2 instanceof Double)) { return; } throw new RuntimeException("Unsupported Number types: " + number1.getClass().toString() + " " + number2.getClass().toString()); }
6
@Test public void findDuplicateTypeHand_whenFourJacks_returnsFourOfaKind() { Hand hand = findDuplicateTypeHand(quadsJacksWithTenKicker()); assertEquals(HandRank.FourOfAKind, hand.handRank); assertEquals(Rank.Jack, hand.ranks.get(0)); assertEquals(Rank.Ten, hand.ranks.get(1)); }
0
private void populateElements() { JPanel content = (JPanel) this.getContentPane(); content.setLayout(new GridBagLayout()); content.setBorder(new EmptyBorder(10, 5, 6, 5)); GridBagConstraints c; int x = 0, y = 0; c = new GridBagConstraints(); c.insets = new Insets(0, 7, 0, 0); c.weightx = 0; c.gridx = x++; c.gridy = y; c.fill = GridBagConstraints.BOTH; content.add(new JLabel("Username"), c); c = new GridBagConstraints(); c.insets = new Insets(0, 7, 0, 7); c.weightx = 1; c.gridx = x--; c.gridy = y++; c.fill = GridBagConstraints.BOTH; content.add((this.username = new HintField("Username")).make(), c); c = new GridBagConstraints(); c.insets = new Insets(0, 7, 0, 0); c.weightx = 0; c.gridx = x++; c.gridy = y; c.fill = GridBagConstraints.BOTH; content.add(new JLabel("Password"), c); c = new GridBagConstraints(); c.insets = new Insets(0, 7, 0, 7); c.weightx = 1; c.gridx = x--; c.gridy = y++; c.fill = GridBagConstraints.BOTH; content.add((this.password = new PasswordHintField("Password")).make(), c); JPanel buttons = new JPanel(new GridBagLayout()); c = new GridBagConstraints(); c.gridx = x = 0; c.gridy = 0; c.fill = GridBagConstraints.BOTH; buttons.add(this.editUser = new JButton("Edit user"), c); c = new GridBagConstraints(); c.gridx = ++x; c.gridy = 0; c.fill = GridBagConstraints.BOTH; buttons.add(this.newUser = new JButton("Add user"), c); c = new GridBagConstraints(); c.weightx = 1; c.gridx = ++x; c.gridy = 0; c.fill = GridBagConstraints.BOTH; buttons.add(new JPanel(), c); c = new GridBagConstraints(); c.gridx = ++x; c.gridy = 0; c.fill = GridBagConstraints.BOTH; buttons.add(this.submit = new JButton("Login"), c); c = new GridBagConstraints(); c.weightx = 1; c.gridwidth = 2; c.gridx = 0; c.gridy = y; c.fill = GridBagConstraints.BOTH; content.add(buttons, c); this.editUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Session.startNewSession(Login.this.username.getText(), new String(Login.this.password.getPassword())); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { AddEditUser panel = new AddEditUser(true, Login.this); JFrame frame = new JFrame(); frame.setContentPane(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setMinimumSize(new Dimension(500, 0)); frame.setLocationRelativeTo(Login.this); frame.setVisible(true); Login.this.dispose(); } }); } }); } catch (SQLException e1) { ErrorLogger.error(e1, "Authentication failure", true, true); } catch (AuthenticationException e1) { ErrorLogger.error(e1, "Username or password incorrect.", false, true); if (e1.type == AuthenticationException.exceptionType.ACTIVE) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { int result = JOptionPane .showConfirmDialog( Login.this, "Reactivate user?", "Reactivate", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { try { Session.activateUser(Login.this.username .getText()); } catch (SQLException e2) { ErrorLogger .error(e2, "Failed to reactivate user", true, true); } } } }); } }); } } } }); this.newUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Session.startNewSession(Login.this.username.getText(), new String(Login.this.password.getPassword())); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { AddEditUser panel = new AddEditUser(false, Login.this); JFrame frame = new JFrame(); frame.setContentPane(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setMinimumSize(new Dimension(500, 0)); frame.setLocationRelativeTo(Login.this); frame.setVisible(true); Login.this.setVisible(false); } }); } }); } catch (SQLException e1) { ErrorLogger.error(e1, "Authentication failure", true, true); } catch (AuthenticationException e1) { ErrorLogger.error(e1, "Username or password incorrect.", false, true); } } }); this.submit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Session.startNewSession(Login.this.username.getText(), new String(Login.this.password.getPassword())); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainWindow frame = new MainWindow(); frame.setVisible(true); Login.this.dispose(); } }); } }); } catch (SQLException e1) { ErrorLogger.error(e1, "Authentication failure", true, true); } catch (AuthenticationException e1) { ErrorLogger.error(e1, "Username or password incorrect.", false, true); } } }); }
9
public Memorable next(Memorable previous){ Memorable last = future.remove(0); future.add(null); if(last!=null){ int d=last.lastSucceed(); for(int i=d-1;i<future.size();i++){ if(future.get(i)==null){ if(i-1>0 && future.get(i-1)==last){ continue; } if(i+1<future.size() && future.get(i+1)==last){ continue; } future.set(i,last); break; } } } if(future.get(0)==null){ future.set(0,memorables.get((int) (Math.random()*memorables.size()))); // Memorable best=null; // float sumErrorRate=0; // for(Memorable memorable:memorables){ // if(best==null){ // best=memorable; // } // if(previous==memorable)continue; // float errorRate = memorable.errorRate(); // float weight=1f+2f*Collections.frequency(last,memorable); // float weightedErrorRate = errorRate*weight; // sumErrorRate+=weightedErrorRate; // if(Math.random()<weightedErrorRate/sumErrorRate){ // best=memorable; // } // } } return future.get(0); }
8
public void testWithFieldAdded3() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); try { test.withFieldAdded(null, 6); fail(); } catch (IllegalArgumentException ex) {} }
1
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public String getTooltipExtraText(final Province current) { final int id = current.getId(); if (!editor.Main.map.isLand(id)) return ""; final String rel = Text.getText(mapPanel.getModel().getHistString(id, "religion")); if (rel.length() == 0) return ""; String owner = mapPanel.getModel().getHistString(id, "owner"); String ctryRel = null; if (owner != null) { if (Utilities.isNotACountry(owner) /*noCountryPattern.matcher(owner).matches()*/) { // don't add anything owner = "-"; } else { owner = owner.toUpperCase(); ctryRel = Text.getText(mapPanel.getModel().getHistString(owner, "religion")); } } else { owner = "-"; } final StringBuilder text = new StringBuilder(rel).append("<br />"); if (!owner.equals("-") && ctryRel != null) text.append(Text.getText(owner)).append(": ").append(ctryRel); return text.toString(); }
6
public static boolean isExponent(int c) { return c == 'e' || c == 'E'; }
1
final public void subArea(ParseArea area) throws ParseException { ParseSubArea subArea = new ParseSubArea(); jj_consume_token(SUBAREA); jj_consume_token(56); label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ATYPE: case IDENT: ; break; default: jj_la1[6] = jj_gen; break label_1; } subAreaLine(subArea); } jj_consume_token(57); area.addSubArea(subArea); }
4
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(Mainmenue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Mainmenue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Mainmenue.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Mainmenue.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 Mainmenue().setVisible(true); } }); }
6
public void render(GameContainer gc, StateBasedGame sb, Graphics gr) { int invx = 1000; int invy = 200; if(draw){ invbg.draw(invx, invy); PlayerInventory plinv = ((Player)this.owner).getPD().getInv(); if(plinv.getEqweapon() != null){ plinv.getEqweapon().getIcon().draw(invx + 4, invy + 2); } if(plinv.getEqarmor() != null){ plinv.getEqarmor().getIcon().draw(invx + 43, invy + 2); } gr.drawString("EXP = " + ((Player)this.owner).getPD().getExp(), invx, invy + 50); } }
3
@Override public List<Autor> listAll() { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; List<Autor> autores = new ArrayList<>(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LIST); rs = pstm.executeQuery(); while (rs.next()){ Autor a = new Autor(); a.setId_autor(rs.getInt("id_autor")); a.setNome(rs.getString("nome_au")); a.setSobrenome(rs.getString("sobrenome_au")); a.setEmail(rs.getString("email_au")); autores.add(a); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar autores " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return autores; }
3
private void sendToNeighbours(Byte[] data) { try { lock.lock(); TreeSet<Byte> neighbours = networkTreeMap.get(deviceID); if(neighbours != null){ for(Byte nb : neighbours) { send(nb, data); // System.out.println("Sending to neighbour: " + nb); } } } catch (CallbackException e) { e.getException().printStackTrace(); } finally { lock.unlock(); } }
3
public String getClassName() { if ( kind == FragKind.aligned || kind == FragKind.merged ) return style; else if ( style != null ) return "inserted-"+style; else return "inserted"; }
3
@Override public void e(float sideMot, float forMot) { if (this.passenger == null || !(this.passenger instanceof EntityHuman)) { super.e(sideMot, forMot); this.W = 0.5F; // Make sure the entity can walk over half slabs, // instead of jumping return; } EntityHuman human = (EntityHuman) this.passenger; if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) { // Same as before super.e(sideMot, forMot); this.W = 0.5F; return; } this.lastYaw = this.yaw = this.passenger.yaw; this.pitch = this.passenger.pitch * 0.5F; // Set the entity's pitch, yaw, head rotation etc. this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166 this.aO = this.aM = this.yaw; this.W = 1.0F; // The custom entity will now automatically climb up 1 // high blocks sideMot = ((EntityLiving) this.passenger).bd * 0.5F; forMot = ((EntityLiving) this.passenger).be; if (forMot <= 0.0F) { forMot *= 0.25F; // Make backwards slower } sideMot *= 0.75F; // Also make sideways slower float speed = 0.35F; // 0.2 is the default entity speed. I made it // slightly faster so that riding is better than // walking this.i(speed); // Apply the speed super.e(sideMot, forMot); // Apply the motion to the entity try { Field jump = null; jump = EntityLiving.class.getDeclaredField("bc"); jump.setAccessible(true); if (jump != null && this.onGround) { // Wouldn't want it jumping // while // on the ground would we? if (jump.getBoolean(this.passenger)) { double jumpHeight = 0.5D; this.motY = jumpHeight; // Used all the time in NMS for // entity jumping } } } catch (Exception e) { e.printStackTrace(); } }
8
@Override public int[] sort(int[] target, boolean asc) { int length = 0; if (asc) { for (int data : target) { length++; for (int i = 0; i < length; i++) { if (data < target[i]) { int headOfMoving = target[i]; target[i] = data; int tmp; for (++i; i < length; i++) { tmp = target[i]; target[i] = headOfMoving; headOfMoving = tmp; } break; } } } } else { for (int data : target) { length++; for (int i = 0; i < length; i++) { if (data > target[i]) { int headOfMoving = target[i]; target[i] = data; int tmp; for (++i; i < length; i++) { tmp = target[i]; target[i] = headOfMoving; headOfMoving = tmp; } break; } } } } return target; }
9
public Boolean tileMatchesAvailable(){ /* for (int i = 0; i < getX(); i++) { for (int u = 0; u < getY(); u++) { if (cells[i][u]!= 0) { for (int direction = 0; direction < 4; direction++) { int [] vector = getVector(direction); int other = cells[i+vector[0]][u+vector[1]]; if (other!=0 && other == cells[i][u]) { return true; // These two tiles can be merged } } } } } return false;*/ PlayingField cp1 = this.makeCopy(); PlayingField cp2 = this.makeCopy(); PlayingField cp3 = this.makeCopy(); PlayingField cp4 = this.makeCopy(); if(cp1.up()>0 || cp2.down() >0 || cp3.left()>0 || cp4.right()>0){ return true; } return false; }
4
private void saveContact() throws SQLException { // TODO: When adding new and editing given contacts, check for doubles in the database. Give them visible IDs to make the difference when contacts really have the same names. if (checkFieldsForSaving()) { clsContactsDetails mContactDetails = new clsContactsDetails(); //Differentiate between the two saving modes new and modify. clsContacts.enmSavingMode mSavingMode = null; if (this.pStatus == enmStatus.New) { mSavingMode = clsContacts.enmSavingMode.New; } else if (this.pStatus == enmStatus.Modify) { mSavingMode = clsContacts.enmSavingMode.Modify; int mID = ((clsContactsTableModel) tblContacts.getModel()).getID(tblContacts.getSelectedRow()); int mIDModifications = ((clsContactsTableModel) tblContacts.getModel()).getIDModifications(tblContacts.getSelectedRow()); mContactDetails.setID(mID); mContactDetails.setIDModification(mIDModifications); } //Create the contact details. mContactDetails.setFirstName(txtFirstName.getText()); mContactDetails.setMiddleName(txtMiddleName.getText()); mContactDetails.setLastName(txtLastName.getText()); mContactDetails.setBirthday(dtpBirthday.getDate()); mContactDetails.setGender(getGender()); mContactDetails.setStreet(txtStreet.getText()); mContactDetails.setPostcode(txtPostcode.getText()); mContactDetails.setCity(txtCity.getText()); mContactDetails.setCountry(txtCountry.getText()); mContactDetails.setAvailability(txtAvailability.getText()); mContactDetails.setComment(txtComment.getText()); int mIDContacts = this.pModel.saveContact(mSavingMode, mContactDetails); if (mIDContacts > 0) { this.pStatus = enmStatus.View; setComponents(); //Select the created or modified row. if (mSavingMode == clsContacts.enmSavingMode.New) { this.pSelectedRow = getRowOfID(mIDContacts); } selectContact(); } } }
5
private void getData_with_index(ByteBuffer buf, final int index, OnDataListener dataListener) throws SQLException { int offset = index; final int idx[] = new int[6]; getIndex(buf, offset * 10, idx); int wordid = -1; if ((idx[3] == 0) && ((idx[5] - idx[1]) > 0)) { //word wordid = dataListener.OnWordData(WordFlag.Normal, index, buf, idx[0], idx[4] - idx[0]); dataListener.OnXmlData(wordid, index, buf, idx[1], idx[5] - idx[1]); } else if ((idx[3] == 0) && ((idx[5] - idx[1]) == 0)) { //impossible } else if ((idx[3] > 0) && ((idx[5] - idx[1]) > 0)) { //word + index wordid = dataListener.OnWordData(WordFlag.Normal_Reference, index, buf, idx[0] + idx[3] * 4, (idx[4] - idx[0]) - idx[3] * 4); dataListener.OnXmlData(wordid, index, buf, idx[1], idx[5] - idx[1]); getReferenceData(wordid, index, buf, idx[3], idx[0], dataListener); } else if ((idx[3] > 0) && ((idx[5] - idx[1]) == 0)) { //only index wordid = dataListener.OnWordData(WordFlag.Reference, index, buf, idx[0] + idx[3] * 4, (idx[4] - idx[0]) - idx[3] * 4); getReferenceData(wordid, index, buf, idx[3], idx[0], dataListener); } }
8
edge moveUpRight() { edge f = this; while ((null != f) && ( f.tail.leftEdge != f)) f = f.tail.parentEdge; //go up the tree until f is a leftEdge if ( null == f ) return f; //triggered at end of search else return(f.tail.rightEdge); //and then go right }
3
public void run() { LevelLoader loader = new LevelLoader(this, "arena.svg"); loader.loadObjects(); addPhysicsObjects(); while (true) { lastFrame = System.currentTimeMillis(); try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { System.err.println("Failed to sleep in Model loop. Error:"); e.printStackTrace(); } if (GameState.isModelRunning()) { addPhysicsObjects(); removeDeadPhysicsObjects(); checkEvents(); try { for (PhysicsObject object : physicsObjects) { if (object instanceof Enemy) { ((Enemy) object).goTo(player.getPosition()); } } world.step(GameState.TIME_STEP, GameState.VELOCITY_ITERATIONS, GameState.POSITION_ITERATIONS); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } elapsedTime += System.currentTimeMillis() - lastFrame; } } }
6
public void choice(int selection, GameGrid grid) { switch (selection) { case 1: setGridSize(grid); break; case 2: setAlivecells(grid); break; case 3: setRandomCellsAlive(grid); break; case 4: getCurrentSetup(grid); break; case 5: startGame(); break; case 6: endGame(); break; default: System.out.println("Invalid choice try again\n"); } }
6
public List<User> getFollowers(String userEmail) { initConnection(); List<User> followerList = new ArrayList<User>(); String preparedString = null; PreparedStatement preparedQuery = null; try { //Prepare Statement - Get users that are following currently logged-in user ("Followers") preparedString = "SELECT * FROM friends " + "INNER JOIN users ON users.email = friends.email " + "WHERE friend = ?;"; preparedQuery = (PreparedStatement) connection.prepareStatement(preparedString); preparedQuery.setString(1, userEmail); //TODO: Remove debug System.out.println("Select Followers with SQL: [" + preparedQuery.toString() + "] "); //Execute Statement ResultSet resultSet = preparedQuery.executeQuery(); while (resultSet.next()) { User nextUser = new User(); nextUser.setEmail(resultSet.getString("email")); nextUser.setFirstName(resultSet.getString("firstname")); nextUser.setLastName(resultSet.getString("lastname")); followerList.add(nextUser); } } catch (SQLException e) { e.printStackTrace(); } finally { try { //Finally close stuff to return connection to pool for reuse preparedQuery.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return followerList; }
3
private void initMessage() throws InvalidDataException { if( code == CloseFrame.NOCODE ) { reason = Charsetfunctions.stringUtf8( super.getPayloadData() ); } else { ByteBuffer b = super.getPayloadData(); int mark = b.position();// because stringUtf8 also creates a mark try { b.position( b.position() + 2 ); reason = Charsetfunctions.stringUtf8( b ); } catch ( IllegalArgumentException e ) { throw new InvalidFrameException( e ); } finally { b.position( mark ); } } }
2
public Map<String, UUID> call() throws Exception { Map<String, UUID> uuidMap = new HashMap<String, UUID>(); int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); for (int i = 0; i < requests; i++) { HttpURLConnection connection = createConnection(); String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); writeBody(connection, body); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); UUID uuid = UUIDFetcher.getUUID(id); uuidMap.put(name, uuid); } if (rateLimiting && i != requests - 1) { Thread.sleep(100L); } } return uuidMap; }
4
mainWindow(){ int i,j,r; JButton titleScreen=new JButton(new ImageIcon(getClass().getResource("TitleScreen.jpg"))); this.ventana.setSize(700, 485); panel.setLayout(null); titleScreen.setBounds(0, 0, 700, 485); panel.add(titleScreen); titleScreen.addActionListener(this); this.ventana.getContentPane().add(panel); this.ventana.setVisible(true); while(vulaux){ try{ sleep(200); }catch(InterruptedException e){ System.out.println("got interrupted!"); }} ventana.remove(panel); panel=new JPanel(); panel.setLayout(null); Random generador = new Random(); for(i=0;i<15;i++){ for(j=0;j<15;j++){ r=generador.nextInt(99)+1; if(r<=5){ buttonMatrix[i][j]=comodinCreator.crearBloque(); buttonMatrix[i][j].boton.setBounds(i*30, j*30, 25, 25); this.panel.add(buttonMatrix[i][j].boton); buttonMatrix[i][j].boton.addActionListener(this); } else{ buttonMatrix[i][j]=colorCreator.crearBloque(); buttonMatrix[i][j].boton.setBounds(i*30, j*30, 25, 25); this.panel.add(buttonMatrix[i][j].boton); buttonMatrix[i][j].boton.addActionListener(this); } } } this.ventana.getContentPane().add(panel); this.ventana.setVisible(true); destruccion(); }
5
public void driver() { System.out.println("audo drive"); }
0
public void run() throws IOException { System.out.println("started processing " + dirName); //all transcripts from ensembl, sorted getAllTranscripts(); Collections.sort(allTranscr); trSize = allTranscr.size(); //number of transcripts //all files to use ArrayList<String> fNames = null; if (fileList == null){ fNames = getFileNames();//get file names and sample names } else{ TextFile flist = new TextFile(fileList, false); fNames = new ArrayList<String>(Arrays.asList(flist.readAsArray(1, TextFile.tab))); sampleNames = new String[fNames.size()]; flist.close(); flist = new TextFile(fileList, false); sampleNames = flist.readAsArray(0, TextFile.tab); flist.close(); } samplesSize = fNames.size(); //number of samples makeTable(fNames); //print the result if (! normalizeByLength) printTable(); else printTableNormByLength(); }
2
public Tea() { this.setName("Coffee"); this.setPrice(new BigDecimal(15)); }
0
public People(int peopleCount) { people = new Person[peopleCount]; viruses = new Viruses(); for (int i = 0; i < peopleCount; i++) { int x = 0, y = 0; boolean keepGoing = true; while (keepGoing) { x = getRandomInRange(0, GamePanel.WIDTH - Person.RADIUS*2); y = getRandomInRange(0, GamePanel.HEIGHT - Person.RADIUS*2); keepGoing = false; for (int j = 0; j < i; j++) { if (occupiesSameSpace(people[j].getX(), people[j].getY(), x, y)) { keepGoing = true; break; } } } people[i] = new Person(x, y, viruses.getRandomVirus()); } Statistics.setupPeople(people); }
4
private static int addValue(String line, PriorityQueue<Integer> lowestH, PriorityQueue<Integer> highestH) { int val = Integer.parseInt(line); long mid = highestH.isEmpty() ? Long.MIN_VALUE : highestH.peek(); // add if( val > mid) highestH.add(val); else lowestH.add(val); // balance if(highestH.size() > lowestH.size() + 1) lowestH.add(highestH.poll()); else if(highestH.size() < lowestH.size()) highestH.add(lowestH.poll()); // return mid if(highestH.size() > lowestH.size()) return highestH.peek(); else return lowestH.peek(); }
5
@Override public boolean handle(Request r, Response resp) { String templatePath = Profile.getInstance().getTemplatePathFor(r, TEMPLATE_NAME); // load the template Templator tr = new Templator(); Template t; try { t = tr.newTemplate(templatePath); } catch (FileNotFoundException e) { resp.setBody("Specified template file not found."); return true; } t.putVariable("title", "User"); List<User> possibles = Profile.getInstance().getPossibleUsers(); if (r.getGetVars().isSet("i")) { // select the user int i = -1; try { i = Integer.parseInt( r.getGetVars().getValue("i") ); if (i < 0 || i > possibles.size()) throw new NumberFormatException(); } catch (NumberFormatException e) { t.putVariable("body", "Illegal user selection..."); t.writeTo(resp); return true; } resp.setCookie(new Cookie(STClient.COOKIE_USERID, String.valueOf(possibles.get(i).getId())) ); t.putVariable("body", "Successfully logged in for this session as " + possibles.get(i).getName() + "!"); t.putVariable("refresh", "1;URL="+STServer.getHomeLink()); } else { int i=0; for (User u : possibles) t.putObject(new AbstractHandler.SelectItem(u.getName(), i++)); // we already have a user, so this is optional if (r.getUser() != null) t.putVariable("homeLink", STServer.getHomeLink()); } t.writeTo(resp); return true; }
7
public void setLivingAnimations(EntityLiving var1, float var2, float var3, float var4) { EntityWolf var5 = (EntityWolf)var1; if(var5.isWolfAngry()) { this.wolfTail.rotateAngleY = 0.0F; } else { this.wolfTail.rotateAngleY = MathHelper.cos(var2 * 0.6662F) * 1.4F * var3; } if(var5.isWolfSitting()) { this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F); this.wolfMane.rotateAngleX = 1.2566371F; this.wolfMane.rotateAngleY = 0.0F; this.wolfBody.setRotationPoint(0.0F, 18.0F, 0.0F); this.wolfBody.rotateAngleX = 0.7853982F; this.wolfTail.setRotationPoint(-1.0F, 21.0F, 6.0F); this.wolfLeg1.setRotationPoint(-2.5F, 22.0F, 2.0F); this.wolfLeg1.rotateAngleX = 4.712389F; this.wolfLeg2.setRotationPoint(0.5F, 22.0F, 2.0F); this.wolfLeg2.rotateAngleX = 4.712389F; this.wolfLeg3.rotateAngleX = 5.811947F; this.wolfLeg3.setRotationPoint(-2.49F, 17.0F, -4.0F); this.wolfLeg4.rotateAngleX = 5.811947F; this.wolfLeg4.setRotationPoint(0.51F, 17.0F, -4.0F); } else { this.wolfBody.setRotationPoint(0.0F, 14.0F, 2.0F); this.wolfBody.rotateAngleX = 1.5707964F; this.wolfMane.setRotationPoint(-1.0F, 14.0F, -3.0F); this.wolfMane.rotateAngleX = this.wolfBody.rotateAngleX; this.wolfTail.setRotationPoint(-1.0F, 12.0F, 8.0F); this.wolfLeg1.setRotationPoint(-2.5F, 16.0F, 7.0F); this.wolfLeg2.setRotationPoint(0.5F, 16.0F, 7.0F); this.wolfLeg3.setRotationPoint(-2.5F, 16.0F, -4.0F); this.wolfLeg4.setRotationPoint(0.5F, 16.0F, -4.0F); this.wolfLeg1.rotateAngleX = MathHelper.cos(var2 * 0.6662F) * 1.4F * var3; this.wolfLeg2.rotateAngleX = MathHelper.cos(var2 * 0.6662F + 3.1415927F) * 1.4F * var3; this.wolfLeg3.rotateAngleX = MathHelper.cos(var2 * 0.6662F + 3.1415927F) * 1.4F * var3; this.wolfLeg4.rotateAngleX = MathHelper.cos(var2 * 0.6662F) * 1.4F * var3; } float var6 = var5.getInterestedAngle(var4) + var5.getShakeAngle(var4, 0.0F); this.wolfHeadMain.rotateAngleZ = var6; this.wolfRightEar.rotateAngleZ = var6; this.wolfLeftEar.rotateAngleZ = var6; this.wolfSnout.rotateAngleZ = var6; this.wolfMane.rotateAngleZ = var5.getShakeAngle(var4, -0.08F); this.wolfBody.rotateAngleZ = var5.getShakeAngle(var4, -0.16F); this.wolfTail.rotateAngleZ = var5.getShakeAngle(var4, -0.2F); if(var5.getWolfShaking()) { float var7 = var5.getEntityBrightness(var4) * var5.getShadingWhileShaking(var4); GL11.glColor3f(var7, var7, var7); } }
3
private StockStorage() { try { File fXmlFile = new File(fileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); } catch (Exception ex) { Logger.getLogger(StockStorage.class.getName()).log(Level.SEVERE, null, ex); } }
1