text
stringlengths
14
410k
label
int32
0
9
public void setExpiryDate(XMLGregorianCalendar value) { this.expiryDate = value; }
0
public void applyCareer(Human actor) { subject = actor ; applyBackgrounds(actor) ; // // We top up basic attributes to match. actor.traits.initDNA(0) ; actor.health.setupHealth( Visit.clamp(Rand.avgNums(2), 0.26f, 0.94f), 1, 0 ) ; // // For now, we apply gender at random, though this might be tweaked a bit // later. We also assign some random personality and/or physical traits. while (true) { final int numP = actor.traits.personality().size() ; if (numP >= 5) break ; final Trait t = (Trait) Rand.pickFrom(PERSONALITY_TRAITS) ; actor.traits.incLevel(t, Rand.range(-2, 2)) ; if (numP >= 3 && Rand.yes()) break ; } actor.traits.incLevel(HANDSOME, Rand.rangeAvg(-2, 2, 2)) ; actor.traits.incLevel(TALL , Rand.rangeAvg(-2, 2, 2)) ; actor.traits.incLevel(STOUT , Rand.rangeAvg(-2, 2, 2)) ; applySystem((System) homeworld, actor) ; applySex(actor) ; // // Finally, specify name and (TODO:) a few other details of appearance. for (String name : Wording.namesFor(actor)) { if (fullName == null) fullName = name ; else fullName+=" "+name ; } ///I.say("Full name: "+fullName) ; // // Along with current wealth and equipment- applyGear(vocation, actor) ; }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; BasicResourceDefinition other = (BasicResourceDefinition) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
6
@Override public void actionPerformed(ActionEvent src) { Object source = src.getSource(); if (source == btnReset) { resetAllTrain(); } else if (source == btnAddLocomotive) { getLocomotiveInfo(); } else if (source == btnAddPassengerCar) { getPassengerCarInfo(); } else if (source == btnAddFreightCar) { getFreightCarInfo(); } else if (source == btnBoard) { getBoard(); } else if (source == btnRemoveCarriage) { RemoveCarriage(); } }
6
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Email)) { return false; } Email other = (Email) object; if ((this.idEmail == null && other.idEmail != null) || (this.idEmail != null && !this.idEmail.equals(other.idEmail))) { return false; } return true; }
5
private void gameUpdate(long delta) { hero.tick(delta); myControle.tick(delta); for(int i = 0; i < bullets.size(); i++) { bullets.get(i).tick(delta); } }
1
public GetUserInfoResult genLoad() { EntityUser user = EntityUser.load(userId); EntityUser delegate = null; List<EntityUser> userVotes = null; if (showVotes) { userVotes = getVotes(user); HashoutUserToDelegate hashoutUserToDelegate = new HashoutUserToDelegate(); List<EntityUserAndVote> userDelegateVotes = VoteFilter.filterVotes(hashoutUserToDelegate.loadEntities(userId.getKey()), votesTime); if (userDelegateVotes.size() > 1) { throw new GetUserInfoException("More then one delegate: " + userId); } if (userDelegateVotes.size() == 1) { delegate = userDelegateVotes.get(0).getUser(); } } List<UserActionResult> userActions = genUserActions(userId); return new GetUserInfoResult(user, userActions, delegate, userVotes); }
3
public void printList() { for (int i=0; i<size(); i++) { System.out.println(this.get(i).getX() + " " + this.get(i).getY()); } }
1
public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int aleatorio, intentos; int numero, continua; boolean continuar=true; while(continuar){ intentos = 0; aleatorio = (int)(Math.random()*1000 + 1); do{ System.out.println("Adivine un numero entre 1 y 1000: "); numero = entrada.nextInt(); if(numero > aleatorio){ System.out.println("Demasiado alto. Intente de nuevo."); intentos++; } else if(numero < aleatorio){ System.out.println("Demasiado bajo. Intente de nuevo."); intentos++; } else{ System.out.println("Felicidades. Adivino el numero!"); intentos++; } }while(numero != aleatorio); do{ if(intentos == 10){ System.out.println("Aja!. Sabia usted el secreto!."); } else if(intentos < 10){ System.out.println("Ya sabia usted el secreto o tuvo suerte!."); } else{ System.out.println("Deberia haberlo hecho mejor!."); } System.out.println("¿Desea jugar otra vez?. Para salir escriba <0>. Si desea jugar escriba <1>."); continua = entrada.nextInt(); if(continua == 0){ continuar = false; break; } else if(continua == 1){ continuar = true; break; } }while(true); } }
9
private void placePitsAndSlime(){ Random rand = new Random(); int pitCount = rand.nextInt(3) + 3; int x, y; //Assign Pits for(int i = 0; i < pitCount; i++){ x = rand.nextInt(10); y = rand.nextInt(10); if(grid[x][y] != RoomState.EMPTY) i--; else grid[x][y] = RoomState.PIT; } //Assign Slime for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid.length; j++){ if(grid[i][j] == RoomState.PIT){ assignSlime(i-1, j); assignSlime(i+1, j); assignSlime(i, j+1); assignSlime(i, j-1); } } } }
5
public Skill getEnum() { switch (skill) { case 0: return Skill.ATTACK; case 1: return Skill.DEFENCE; case 2: return Skill.STRENGTH; case 3: return Skill.CONSTITUTION; case 4: return Skill.RANGED; // guess case 5: return Skill.PRAYER; case 6: return Skill.MAGIC; case 18: return Skill.SLAYER; case 20: return Skill.RUNECRAFTING; } return null; }
9
public int addFuelToCar(int litresAdded) { if(isCarRented() == false || getFuelInCar() == getFuelCapacity()){ return 0; } else { int fuelTotal = fuelInCar + litresAdded; int fuel = Math.min(fuelTotal, fuelCapacity); fuelInCar = fuel; if (litresAdded >= (fuelCapacity - fuelInCar)){ return fuelCapacity - fuelInCar; } else { return litresAdded; } } }
3
@Override public void destroy() { node = null; }
0
public ArrayList<Position> possibleMoves(){ ArrayList<Position> d = new ArrayList<Position>(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { Position position = new Position(super.position().x() + i, super.position().y() + j); if (position().x() + i <= 8 && position().y() + j <= 8 && position.x() + i >= 0 && position.y() + j >= 0 && (super.board.getPiece(position) == null || super.board.getPiece(position).team() == !super.team())) if(!position.equals(super.position())){ d.add(position); } } } return d; }
9
private int findWordLimit(int index, BreakIterator words, boolean direction, String s) { // Fix for 4256660 and 4256661. // Words iterator is different from character and // sentence iterators // in that end of one word is not necessarily start of // another word. // Please see java.text.BreakIterator JavaDoc. The code // below is // based on nextWordStartAfter example from // BreakIterator.java. int last = (direction == NEXT) ? words.following(index) : words.preceding(index); int current = (direction == NEXT) ? words.next() : words.previous(); while (current != BreakIterator.DONE) { for (int p = Math.min(last, current); p < Math.max(last, current); p++) { if (Character.isLetter(s.charAt(p))) { return last; } } last = current; current = (direction == NEXT) ? words.next() : words.previous(); } return BreakIterator.DONE; }
6
private int getAngleNearEnemy(){ int vzdalenost = 2000; int angle, min_x = 0,min_y = 0; /** * Zjištění nejližšího nepřítele */ for (int i=0;i<enemies.size();i++) { // Výpočet vzdalenost X,Y souradnice int pomx = Math.abs(x - enemies.get(i).getX()); int pomy = Math.abs(y - enemies.get(i).getY()); // Výpočet uhlopříčky int pom_vzdalenost = (int) Math.sqrt(Math.pow(pomx, 2)+Math.pow(pomy, 2)); if(pom_vzdalenost < vzdalenost){ vzdalenost = pom_vzdalenost; min_x=Math.abs(enemies.get(i).getX()-x); min_y=Math.abs(enemies.get(i).getY()-y); enX = enemies.get(i).getX(); enY = enemies.get(i).getY(); } } /*************************************/ if(enX >=x && enY >=y){ // KVADRANT 4 double pom1 = (double) min_x/min_y; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle += 270 + direction; } else if(enX >=x && enY <=y){ // KVADRANT 1 double pom1 = (double) min_y/min_x; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle+=direction; } else if(enX <=x && enY <=y){ // KVADRANT 2 double pom1 = (double) min_x/min_y; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle+=90;angle+=direction; } else { // KVADRANT 3 double pom1 = (double) min_y/min_x; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle += 180 + direction; } return angle; }
8
@Override public void componentActivated(AbstractComponent source) { //Handles the Mouse Interactions //TODO: Add logic to check for overlays if(gameTypeBox.isActivated()){ if(source == gameTypeBox.pvaiButton){ Globals.playerTwoAI = true; Globals.GAME.enterState(Globals.GAME.GAMESCREENSTATE, new FadeOutTransition(), new FadeInTransition()); } else if(source == gameTypeBox.pvpButton){ Globals.playerTwoAI = false; Globals.GAME.enterState(Globals.GAME.GAMESCREENSTATE, new FadeOutTransition(), new FadeInTransition()); } } else if(stat.isActivated()){ if(source == showStatistics){ stat.toggle(); } } else{ if(source == menu.areas[Menu.NEWGAME]){ //Show GameTypeBox gameTypeBox.toggle(); } if(source == menu.areas[Menu.LOADGAME]){ //Show GameTypeBox Globals.loadGame = true; Globals.GAME.enterState(Globals.GAME.GAMESCREENSTATE, new FadeOutTransition(), new FadeInTransition()); } else if(source == menu.areas[Menu.STATISTICS]){ stat.toggle(); } else if(source == menu.areas[Menu.QUITGAME]){ menu.shouldExit = true; } } }
9
public void setIntelligentY(int intelligentY) { this.intelligentY = intelligentY; }
0
private String IaddResourceNode(String resource_id) { String node_id = null; OrientGraph graph = null; try { node_id = getResourceNodeId(resource_id); if(node_id != null) { //System.out.println("Node already Exist: region=" + region + " agent=" + agent + " plugin=" + plugin); } else { graph = factory.getTx(); //add something Vertex v = graph.addVertex("class:resourceNode"); v.setProperty("resource_id", resource_id); graph.commit(); node_id = v.getId().toString(); } } catch(com.orientechnologies.orient.core.storage.ORecordDuplicatedException exc) { //eat exception.. this is not normal and should log somewhere } catch(com.orientechnologies.orient.core.exception.OConcurrentModificationException exc) { //eat exception.. this is normal } catch(Exception ex) { long threadId = Thread.currentThread().getId(); System.out.println("addResourceNode: thread_id: " + threadId + " Error " + ex.toString()); } finally { if(graph != null) { graph.shutdown(); } } return node_id; }
5
@Override public void keyPressed(KeyEvent keyEvent) { if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT) { iDireccion = 1; } if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) { iDireccion = 2; } if (iDireccionProyectil == 0 && keyEvent.getKeyCode() == KeyEvent.VK_SPACE){ iDireccionProyectil = 1; } }
4
public void setAddress1(String address1) { this.address1 = address1; }
0
static public String[] findCoauthor(HashMap<String, String[]> coauthorResult, String personName){ String coauthorArray[] = coauthorResult.get(personName); String temp[] = null; String tempString = null; String ResultArray[] = new String[coauthorArray.length]; ResultArray[0] = coauthorArray[0]; for(int i = 1; i < coauthorArray.length; i++){ tempString = coauthorArray[i]; temp = tempString.split(":"); ResultArray[i] = temp[0]; } return ResultArray; }
1
private static float maximum(float a, float b, float c, float d) { if (a > b) { if (a > c) { return a > d ? a : d; } else { return c > d ? c : d; } } else if (b > c) { return b > d ? b : d; } else { return c > d ? c : d; } }
7
@GET @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public List<SocialCommunity<?>> getCommunities( @QueryParam("query") String query, @QueryParam("communitiesTypes") CommunityType[] communitiesTypes, @QueryParam("page") Integer page) { EnumSet<CommunityType> communitiesTypesSet = EnumSet .noneOf(CommunityType.class); communitiesTypesSet.addAll(Arrays.asList(communitiesTypes)); /* * Integer countforEachType = null; Integer offsetForEachType = null; if * (!communitiesTypesSet.isEmpty() && count != null) { * Preconditions.checkArgument(communitiesTypesSet.size() <= count, * "Count can not be less than communityType quantity"); * countforEachType = count / communitiesTypesSet.size(); if (offset != * null) { Preconditions.checkArgument(communitiesTypesSet.size() < * count, "Count can not be less than communityType quantity"); * offsetForEachType = offset / communitiesTypesSet.size(); } * * } */ List<SocialCommunity<?>> list = new ArrayList<SocialCommunity<?>>(); for (CommunityType communityType : communitiesTypesSet) { list.addAll(socialManagerConfiguration.getSocialManager( communityType).getCommunities(query, page)); } return list; }
4
public static final void exampleSynchronousQueries() { System.out.println("Starting Cyc synchronous query examples."); try { ELMt inferencePSC = access.makeELMt("InferencePSC"); CycFormulaSentence query = CycLParserUtil.parseCycLSentence("(isa ?X Dog)", true, access); InferenceWorkerSynch worker = new DefaultInferenceWorkerSynch(query, inferencePSC, null, access, 10000); try { List answers = worker.performSynchronousInference(); // Note: workers are 1-shot, don't call more than once System.out.println("Got " + answers.size() + " inference answers: " + answers); } finally { // If inference resources are not released, they can accumulate, causing a memory leak. worker.releaseInferenceResources(60000); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finished."); }
1
private void updateShop(final ShopCharacter shop, final PlayerCharacter player){ for(final Item item : shop.getInventory()){ // create item panel JPanel shopItem = new JPanel(); shopItem.setPreferredSize(new Dimension(250, 70)); shopItem.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); shopItem.setOpaque(false); // create item image ItemIcon itemIcon = new ItemIcon(item); shopItem.add(itemIcon); // create item info panel JPanel itemInfo = new JPanel(); itemInfo.setPreferredSize(new Dimension(120, 70)); itemInfo.setBorder(new EmptyBorder(2, 10, 0, 0)); itemInfo.setOpaque(false); itemInfo.setLayout(new BoxLayout(itemInfo, BoxLayout.Y_AXIS)); shopItem.add(itemInfo); // create item name label JLabel itemName = new JLabel(item.getName()); itemName.setFont(new Font("Verdana", Font.BOLD, 14)); itemName.setBorder(new EmptyBorder(0,0,6,0)); itemName.setForeground(Color.WHITE); itemInfo.add(itemName); // create item value label JLabel itemValue = new JLabel("Value: " + item.getItemValue()+""); itemValue.setFont(new Font("Verdana", Font.PLAIN, 11)); itemValue.setForeground(Color.WHITE); itemInfo.add(itemValue); // create item sellValue label JLabel itemSellValue = new JLabel("Sell for: " + ((item.getItemValue()*shop.getShopBuyBackFactor())/100)+""); itemSellValue.setFont(new Font("Verdana", Font.PLAIN, 11)); itemSellValue.setForeground(Color.WHITE); itemInfo.add(itemSellValue); // create item effect label JLabel itemEffect = new JLabel(); if(item instanceof WeaponItem){ itemEffect.setText("Damage: " + ((WeaponItem) item).getAttackDamage()); } else if (item instanceof ArmorItem){ itemEffect.setText("Armor: " + ((ArmorItem) item).getDefenceRating()); } else if(item instanceof LifeItem){ itemEffect.setText("Life: " + ((LifeItem) item).getLifeValue()); } itemEffect.setFont(new Font("Verdana", Font.PLAIN, 11)); itemEffect.setForeground(Color.WHITE); itemInfo.add(itemEffect); // create button are JPanel buttonArea = new JPanel(); buttonArea.setPreferredSize(new Dimension(60, 50)); buttonArea.setOpaque(false); buttonArea.setLayout(new BoxLayout(buttonArea, BoxLayout.Y_AXIS)); shopItem.add(buttonArea); // create sell button JButton sell = new JButton("Sell!"); sell.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ sellItem(item, player, shop); requestFocusInWindow(); } }); // create buy button JButton buy = new JButton("Buy!"); buy.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ buyItem(item, player); requestFocusInWindow(); } }); buttonArea.add(Box.createVerticalGlue()); buttonArea.add(buy); buttonArea.add(sell); shopPanel.add(shopItem); } }
4
public void installListeners() { keyListener = new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { JediWindowModel model = window.model; if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (model.getJediFiles().size() > model.getSelectedElement() + 1) { model.setSelectedElement(model.getSelectedElement() + 1); } if (model.getSelectedElement() > model.getFirstElement() + window.MAX_FILES -1) { model.setFirstElement(model.getFirstElement()+1); } } else if (e.getKeyCode() == KeyEvent.VK_UP) { if (model.getSelectedElement() > 0 ) { model.setSelectedElement(model.getSelectedElement() - 1); } if (model.getSelectedElement() < model.getFirstElement()) { model.setFirstElement(model.getFirstElement() - 1); } } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (!model.getJediFiles().get(model.getSelectedElement()).isFile()) { window.currentPath = model.getJediFiles().get(model.getSelectedElement()).getPath(); } model.setSelectedElement(0); model.setFirstElement(0); window.strategy.initJediFiles(window.currentPath, model.getJediFiles()); } window.repaint(); } @Override public void keyReleased(KeyEvent e) { } }; window.addKeyListener(keyListener); }
8
private JPanel createSavedSettingsPanel() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder("Gespeicherte Einstellungen")); panel.setLayout(new BorderLayout()); _savedSettingsTable.setRowSelectionAllowed(true); _savedSettingsTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); _savedSettingsTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); _savedSettingsTable.addFocusListener( new FocusAdapter() { public void focusGained(FocusEvent e) { if(_lastUsedSettingsTable.getSelectedRowCount() > 0) { _lastUsedSettingsTable.clearSelection(); } } } ); _savedSettingsTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { // zur Ermittlung, ob eine neue Zeile ausgewählt wurde -> Abfrage spart doppelten Ausführung int row = -1; public void valueChanged(ListSelectionEvent e) { if(_savedSettingsTable.getSelectedRowCount() == 1 && _savedSettingsTable.getSelectedRow() != row) { row = _savedSettingsTable.getSelectedRow(); final SettingsData settingsData = (SettingsData)_savedSettingsList.get(row); if(settingsData.isValid()) { _savedSettingsTable.setCursor(new Cursor(Cursor.WAIT_CURSOR)); preselectListsBySettings(settingsData); _savedSettingsTable.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } else if(_savedSettingsTable.getSelectedRowCount() == 0) { row = -1; } checkButtonStatus(); } } ); _savedSettingsTableModel.addColumn("Titel"); _savedSettingsTableModel.addColumn("Modulname"); _savedSettingsTableModel.addColumn("Attributgruppe"); _savedSettingsTableModel.addColumn("Aspekt"); _savedSettingsTableModel.addColumn("SV"); _savedSettingsTableModel.addColumn("Objekte"); _savedSettingsTable.setModel(_savedSettingsTableModel); ColumnHeaderToolTips headerToolTips = new ColumnHeaderToolTips(); // Tooltip für die Spalte SV zuweisen und die Breite der Spalten initialisieren for(int i = 0, n = _savedSettingsTable.getColumnCount(); i < n; i++) { TableColumn column = _savedSettingsTable.getColumnModel().getColumn(i); String headerValue = (String)column.getHeaderValue(); if(headerValue.equals("SV")) { headerToolTips.setToolTip(column, "Simulationsvariante"); column.setPreferredWidth(30); } else { column.setPreferredWidth(200); } } _savedSettingsTable.getTableHeader().addMouseMotionListener(headerToolTips); JScrollPane scrollPane = new JScrollPane(_savedSettingsTable); panel.add(scrollPane, BorderLayout.CENTER); return panel; }
7
public void addUso(String cod, double area) { if (usos == null) usos = new HashMap<String, Double>(); if (usos.get(cod) == null) usos.put(cod, area); else { double a = usos.get(cod); a += area; usos.put(cod, a); } }
2
public AnnotationVisitor visitAnnotationDefault() { AnnotationVisitor av = mv.visitAnnotationDefault(); return av == null ? av : new RemappingAnnotationAdapter(av, remapper); }
1
public TurnHandler(boolean clockwise) { this.clockwise = clockwise; }
0
public static void moviesToFile(String infilename, String outfilename) { File file = new File(outfilename); List<UserMovie> list = readData(infilename); Collections.sort(list); FileWriter fw = null; try { fw = new FileWriter(file); for(int i=0; i<list.size(); i++){ fw.append(list.get(i)+"\n"); } fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4
public Strat getrand(int r) { if (r == 0) { return tStrats.get((int) new Random().nextInt(tStrats.size())); } else if (r == 1) { return zStrats.get((int) new Random().nextInt(zStrats.size())); } else if (r == 2) { return pStrats.get((int) new Random().nextInt(pStrats.size())); } else if (r == 3) { return rStrats.get((int) new Random().nextInt(rStrats.size())); } return null; }
4
private Collection<Object[]> getParameterArrays() throws Exception { Method testClassMethod = getDeclaredMethod(this.getClass(), "getTestClass"); Class<?> returnType = testClassMethod.getReturnType(); if (returnType == Class.class) { return getParameterArrays4_3(); } else { return getParameterArrays4_4(); } }
2
@Override public void run() { if (players[0].getPlayerType() == Const.LAN) { try { String name = in.readUTF(); this.setPlayer1Name(name); out.writeUTF(players[1].getName()); } catch (Exception ex) { System.out.println(ex); } } else { try { out.writeUTF(players[0].getName()); String name = in.readUTF(); this.setPlayer2Name(name); } catch (Exception ex) { System.out.println(ex); } } Value win; while ((win = MainFrame.getInstance().getGameField().getWinner()) == null) { onMove = MainFrame.getInstance().getGameField().getCheckCount() % 2; Point played = players[onMove].play(); if(players[onMove].getPlayerType()==Const.HUMAN){ try { out.writeInt(played.getY()); out.writeInt(played.getX()); } catch (IOException ex) { System.out.println(ex); JOptionPane.showMessageDialog(MainFrame.getInstance(), "Vypadlo spojeni", "Connection Error",JOptionPane.ERROR_MESSAGE); } } MainFrame.getInstance().getGameField().markPoint(played, players[onMove].getMark()); } if (win == Value.O) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "The Winner is " + players[0]); } else { JOptionPane.showMessageDialog(MainFrame.getInstance(), "The Winner is " + players[1]); } try { socket.close(); in.close(); out.close(); players[0].close(); players[1].close(); } catch (IOException ex) { } }
8
public void showTip(String tipText, Point pt) { if (getRootPane() == null) return; // draw in glass pane to appear on top of other components if (glassPane == null) { getRootPane().setGlassPane(glassPane = new JPanel()); glassPane.setOpaque(false); glassPane.setLayout(null); // will control layout manually glassPane.add(tip = new JToolTip()); tipTimer = new Timer(TIP_DELAY, new ActionListener() { public void actionPerformed(ActionEvent evt) { glassPane.setVisible(false); } }); tipTimer.setRepeats(false); } if (tipText == null) return; // set tip text to identify current origin of pannable view tip.setTipText(tipText); // position tip to appear at upper left corner of viewport tip.setLocation(SwingUtilities.convertPoint(this, pt, glassPane)); tip.setSize(tip.getPreferredSize()); // show glass pane (it contains tip) glassPane.setVisible(true); glassPane.repaint(); // this timer will hide the glass pane after a short delay tipTimer.restart(); }
3
@SuppressWarnings({ "rawtypes", "unchecked" }) public void lock(TransactionId tid, Permissions permission) throws TransactionAbortedException { if (permission == Permissions.READ_ONLY) { if (lock.getReadHoldCount() == 0) { try { while(!lock.readLock().tryLock()) { wait(); } } catch(InterruptedException e) { throw new TransactionAbortedException(tid + " aborted"); } } } else { if (lock.getWriteHoldCount() == 0) { if (!lock.writeLock().tryLock()) { if (!tryUpgradeLock(tid)) { try { while(!lock.writeLock().tryLock()) { wait(); } } catch(InterruptedException e) { throw new TransactionAbortedException(tid + " aborted"); } } } } } }
9
public static void export(String filename) throws Exception { try { BufferedWriter writer = new BufferedWriter(new FileWriter(new File( filename))); manager = new MovieManager("imdblist", "movies"); set = manager.getCompleteResultSet(); writer.write("<html><body><table width=80%>\n"); while (set.next()) { writer.write("<tr><td align=center valign=middle><img height=150 src=\"" + set.getString("posterurl") + "\"</td><td><h1>" + set.getString("title") + "</h1>" + "<p>" + set.getString("country") + " " + set.getString("year") + ", Released: " + set.getString("releasedate") + "</p>" + "<p><b>Director:</b> " + set.getString("director") + "<br><b>Genres:</b> "); for (int i = 1; i <= 5; i++) { String g = set.getString("genre" + i); if (g.length() > 0) { writer.write((i > 1 ? ", " : "") + g); } } writer.write("<br><b>Actors:</b> "); for (int i = 1; i <= 5; i++) { String g = set.getString("actor" + i); if (g.length() > 0) { writer.write((i > 1 ? ", " : "") + g); } } writer.write("</td></tr>\n"); } writer.write("</table></body></html>"); writer.close(); } catch (IOException e) { e.printStackTrace(); throw new Exception(e.getMessage()); } }
8
public static void clearList(){ listAllWords.clearList(); }
0
@Override public boolean isCellEditable(int row, int col) { switch (col) { case 0: case 2: case 3: return true; } return false; }
3
private int[] getSurroundings(int xCoord, int yCoord) { int[] surroundings = new int[3]; //System.out.println("origin = " + xCoord + ", " + yCoord); for(int y = yCoord - 1; y <= yCoord + 1; y++) { for(int x = xCoord - 1; x <= xCoord + 1; x++) { if(!((validateX(x) == xCoord) && (validateY(y) == yCoord))){ //System.out.println("\tchecking: " + validateX(x) + ", " + validateY(y)); if(cellContents(validateX(x), validateY(y)) == FISH) { // System.out.println("\t\tfish found"); surroundings[FISH]++; } else if(cellContents(validateX(x), validateY(y)) == SHARK) { // System.out.println("\t\tshark found"); surroundings[SHARK]++; } } } } return surroundings; }
6
public Result recognizeFromResult(Result r) { //get phonemes ArrayList<PhonemeContainer> phonemesSpeech = pc.getPhonemes(r); //get best result String[] phonemes = phonemesSpeech.get(0).getPhonemes(); //ad to phone frontend pfe.addPhonemes(phonemes); //start postprocessing r = null; edu.cmu.sphinx.result.Result result; while ((result = recognizer.recognize())!= null) { if(r == null) r= new Result(); String refPhoneme = ""; for(String s: phonemes) refPhoneme = refPhoneme + s + " "; //get phoneme sequence of hypotheses String[] s2 = result.getBestPronunciationResult().split(" "); Pattern p = Pattern.compile(".*\\[(.*)\\]"); String hypPhoneme = ""; //get phonemes for hypotheses phoneme sequence for(String s: s2) { Matcher m = p.matcher(s); if(m.find()){ String[] s3 = m.group(1).split(","); for(String s4: s3) hypPhoneme = hypPhoneme + s4 + " "; } } //set the phoneme sequences in the result r.setRefPhoneme(refPhoneme); r.setHypPhoneme(hypPhoneme); //get best result String resultText = result.getBestFinalResultNoFiller(); if(resultText.equals("")) return null; r.addResult(resultText); //add rest to 10-best list int i = 0; for(Token t: result.getResultTokens()) { if(i>=9) break; r.addResult(t.getWordPathNoFiller()); i++; } } return r; }
9
public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } }
1
public void updatePlayer(PlayerUpdate newdata){ x = newdata.x; y = newdata.y; }
0
@Override public boolean colides(SchlangenKopf head) { if (super.colides(head) ? true : (nextGlied == null ? false : nextGlied.colides(head))) { head.die(); return true; } return false; }
3
public void buttonClick(int position){ if(turn <10){ btnEmptyClicked = true; if(isMyTurn) { btnEmpty[position].setText("X"); btnEmpty[position].setFont(new Font("sansserif",Font.BOLD,32)); isMyTurn = false; } else { btnEmpty[position].setFont(new Font("sansserif",Font.BOLD,32)); btnEmpty[position].setText("O"); isMyTurn = true; } btnEmpty[position].setEnabled(false); pnlPlayingField.requestFocus(); turn++; } if(btnEmptyClicked) { checkWin(); btnEmptyClicked = false; } }
3
private boolean isAttackPlaceLeftNotHarming(int position, char[] boardElements, int dimension) { if (isPossibleToPlaceLeft(position, dimension)) { if (isPossibleToPlaceOnNextLine(boardElements, position + dimension) && isBoardElementAnotherFigure(boardElements[positionLeftBelow(position, dimension)])) { return false; } if (isPossibleToPlaceOnPreviousLine(position - dimension) && isBoardElementAnotherFigure(boardElements[positionLeftAbove(position, dimension)])) { return false; } } return true; }
5
public boolean PointInLineRect(Vector2 point) { return (((point.X >= mPoint1.X && point.X <= mPoint2.X) || (point.X <= mPoint1.X && point.X >= mPoint2.X)) && ((point.Y >= mPoint1.Y && point.Y <= mPoint2.Y) || (point.Y <= mPoint1.Y && point.Y >= mPoint2.Y))); }
7
@Basic @Column(name = "employee_id") public int getEmployeeId() { return employeeId; }
0
public static void main(String[] args) { try { new CounterSwipeServer().startServer(); } catch (Exception e) { System.out.println("I/O failure: " + e.getMessage()); e.printStackTrace(); } }
1
public boolean removeWord(String word) { if(word.length() == 0) return true; char the_char = word.charAt(0); int childPos = getChildPos(the_char); if(this.children[childPos] == null) return false; if(word.length() == 1 ){ if(this.children[childPos].is_word){ if(this.children[childPos].is_leaf){ this.children[childPos] = null; this.is_leaf = true; return true; }else{ this.children[childPos].is_word = false; return true; } }else{ return true; } }else{ if(!this.children[childPos].is_leaf){ boolean child_result = this.children[childPos].removeWord(word.substring(1)); if(child_result){ if(this.children[childPos].is_leaf && (!this.children[childPos].is_word)){ // We need to do cleaning this.is_leaf = true; this.children[childPos] = null; return true; } else return true; }else{ return false; } }else return false; } }
9
private static void tr(final String s) { if (BloatBenchmark.TRACE) { System.out.println(s); } }
1
public double sin(int a){ //normalizing if(a>360){ a %= 360; }else if(a<0){ a %= 360; a += 360; } //return if(a <= 90){ return sin[a]; }else if(a <= 180){ return sin[180 - a]; }else if(a <= 270){ return -sin[a - 180]; }else{ return -sin[360 - a]; } }
5
public HacklabSignDriver(String serialPortName) { this.portName = serialPortName; if(numBoards < 1 || numBoards > 12) { throw new IllegalArgumentException("numBoards is out of range: " + numBoards); } // open the serial port CommPortIdentifier portIdentifier; try { portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName); if(portIdentifier.isCurrentlyOwned()) { System.err.println("Error: Port is currently in use: " + serialPortName); System.exit(-1); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(),2000); if(commPort instanceof SerialPort) { port = (SerialPort) commPort; port.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); port.disableReceiveFraming(); port.disableReceiveTimeout(); port.disableReceiveThreshold(); in = port.getInputStream(); out = port.getOutputStream(); } else { System.err.println("Port is not a serial port: " + serialPortName); } } } catch (NoSuchPortException e) { e.printStackTrace(); System.exit(-1); } catch (PortInUseException e) { e.printStackTrace(); System.exit(-1); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } System.out.println("SignDriver waiting 3s for startup..."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }
9
public ClassInfo getClassInfo() { if (clazz != null) return clazz; else if (ifaces.length > 0) return ifaces[0]; else return ClassInfo.javaLangObject; }
2
private void killAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_killAllButtonActionPerformed try { logger.log(Level.INFO, "Killing all processes on device: " + deviceManager.getSelectedAndroidDevice().toString()); logger.log(Level.INFO, "ADB Output: " + adbController.executeADBCommand(true, false, deviceManager.getSelectedAndroidDevice(), new String[]{"am", "kill-all"})); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while attempting to kill all processes: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_killAllButtonActionPerformed
1
public static <E> Map<E,int[]> intArrayMapCopy(Map<E,int[]> map) { Map<E,int[]> copy = null; if (map instanceof HashMap<?,?>) { copy = new HashMap<E,int[]>(); } else if (map instanceof TreeMap<?,?>) { copy = new TreeMap<E,int[]>(); } for (E e : map.keySet()) { int[] cts = map.get(e); int[] cpy = new int[cts.length]; System.arraycopy(cts,0,cpy,0,cts.length); copy.put(e,cpy); } return copy; }
7
public boolean parseField(String name, String value) { if (name != null && value != null) { DeviceField filed = EnumUtils.lookup(DeviceField.class, name); if (filed != null){ return filed.handle(getDevice(), value); } else{ return false; } } return false; }
3
@Override public void moveCursor(int x, int y) { if(x < 0) x = 0; if(x >= size().getColumns()) x = size().getColumns() - 1; if(y < 0) y = 0; if(y >= size().getRows()) y = size().getRows() - 1; textPosition.setColumn(x); textPosition.setRow(y); refreshScreen(); }
4
public BinSmotif(Smotifs binMe) { try { String bin = binMe.getBin(); String path = bin.substring(0,1) + "/" + bin.substring(1,2) + "/" + bin.substring(2,3) + "/" + bin.substring(3,4) + "/" + bin.substring(4,5); String totalPath = "C:/emacs/Bioinformatics-Project/Bins" + path + "/" + bin + "output.txt"; File file = new File(totalPath); boolean exists = file.exists(); if(exists) { BufferedWriter buffy = new BufferedWriter(new FileWriter(totalPath, true)); buffy.write(binMe.toString()); buffy.newLine(); buffy.close(); } else { PrintWriter out = new PrintWriter(new FileWriter(totalPath)); out.println("Bin dssp/pdb startres endres Distance (d) Hoist (delta) Packing (theta) Meridian (Rho)"); out.println(binMe.toString()); out.close(); } } catch (Exception e) { e.printStackTrace(); } }
2
@Test public void resolve() { int sqrt = ((int) Math.sqrt(N)) + 1; Primes.isPrime(sqrt); print(largest(N)); }
0
public String mkString(Class clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException { List<String> list = new ArrayList<String>(); String result = clazz.getSimpleName() + " "; if (!Modifier.isAbstract(clazz.getModifiers())){ obj = clazz.newInstance(); } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { String fieldName = getFieldName(field); String fieldValue = ""; field.setAccessible(true); if (field.isAnnotationPresent(MaxAmountOfDisplayedObjects.class)) { if (Map.class.isAssignableFrom(field.getType())) { fieldValue = getFieldValue(field, ValueType.MAP_VALUE ); } else if (Iterable.class.isAssignableFrom(field.getType())) { fieldValue = getFieldValue(field, ValueType.ITERABLE_VALUE ); } else fieldValue = getFieldValue(field,ValueType.OTHER_VALUE); } else { fieldValue = getFieldValue(field,ValueType.OTHER_VALUE); } if (field.isAnnotationPresent(NeedNull.class) || fieldValue != null ) { list.add(fieldName + p + fieldValue); } } Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(ResultOfTheMethod.class)) { list.add(getMethod(method)); } } return result + list.toString(); }
9
private String read() throws IOException { String line = br.readLine(); if(line == null) return ""; return line; }
1
public synchronized void moveDown(boolean pressed) { downPressed = pressed; if (pressed) { if (timeToNextDownMove <= 0) { tetromino.tryMove(this, Direction.DOWN); timeToNextDownMove = AUTO_REPEAT_TICKS; } else timeToNextDownMove--; } else timeToNextDownMove = 0; }
2
private void render() { // System.out.println("rendering..."); if (first) { c = new Chat(); first = false; } BufferStrategy bs = this.getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); s.render(game); System.arraycopy(s.pixels, 0, pixels, 0, getGamewidth() * getGameheight()); g.drawImage(img, 0, 0, getGamewidth() + 10, getGameheight() + 10, null); sine++; g.setFont(new Font("Lucida Console", 0, 50)); g.setColor(Color.WHITE); g.drawString(fps + " fps", 20, 50); g.drawString("X: " + Render3D.me.getX(), 100, 100); g.drawString("Z: " + Render3D.me.getZ(), 150, 150); for (int i = 0; i < Render3D.me.getHearts(); i++) { try { g.drawImage(ImageIO.read(Texture.class.getResource("/res/heart_b.png")), i * 55, 0, 55, 50, this); } catch (Exception e) { } } if (chat) { c.setGraphics(g); c.drawChat(); } else { c.reset(); } if (run.multiplayer) { sendLoc(); } g.dispose(); bs.show(); }
6
public final double grad(int var1, double var2, double var4, double var6) { int var8 = var1 & 15; double var9 = var8 < 8?var2:var4; double var11 = var8 < 4?var4:(var8 != 12 && var8 != 14?var6:var2); return ((var8 & 1) == 0?var9:-var9) + ((var8 & 2) == 0?var11:-var11); }
6
private void fixBounds() { if (x < xmin) x = xmin; if (y < ymin) y = ymin; if (x > xmax) x = xmax; if (y > ymax) y = ymax; }
4
private static void splitRange( final Object builder, final int valSize, final int precisionStep, long minBound, long maxBound ) { if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); if (minBound > maxBound) return; for (int shift=0; ; shift += precisionStep) { // calculate new bounds for inner precision final long diff = 1L << (shift+precisionStep), mask = ((1L<<precisionStep) - 1L) << shift; final boolean hasLower = (minBound & mask) != 0L, hasUpper = (maxBound & mask) != mask; final long nextMinBound = (hasLower ? (minBound + diff) : minBound) & ~mask, nextMaxBound = (hasUpper ? (maxBound - diff) : maxBound) & ~mask; if (shift+precisionStep>=valSize || nextMinBound>nextMaxBound) { // We are in the lowest precision or the next precision is not available. addRange(builder, valSize, minBound, maxBound, shift); // exit the split recursion loop break; } if (hasLower) addRange(builder, valSize, minBound, minBound | mask, shift); if (hasUpper) addRange(builder, valSize, maxBound & ~mask, maxBound, shift); // recurse to next precision minBound = nextMinBound; maxBound = nextMaxBound; } }
9
public PrintWriter getWriter() throws java.io.IOException { if (_outputState==DISABLED) return __nullServletWriter; if (_outputState!=NO_OUT && _outputState!=WRITER_OUT) throw new IllegalStateException(); // If we are switching modes, flush output to try avoid overlaps. if (_out!=null) _out.flush(); /* if there is no writer yet */ if (_writer==null) { /* get encoding from Content-Type header */ String encoding = _httpResponse.getCharacterEncoding(); if (encoding==null) { if (_servletHttpRequest!=null) { /* implementation of educated defaults */ String mimeType = _httpResponse.getMimeType(); encoding = _servletHttpRequest.getServletHandler() .getHttpContext().getEncodingByMimeType(mimeType); } if (encoding==null) encoding = StringUtil.__ISO_8859_1; _httpResponse.setCharacterEncoding(encoding,true); } /* construct Writer using correct encoding */ _writer = new ServletWriter(_httpResponse.getOutputStream(), encoding); } _outputState=WRITER_OUT; return _writer; }
8
public void act() { //Initial. Stores the locations which can be reached in the first location. //Push it into the stack if(init==0) { last=this.getLocation(); next = last; crossLocation.push(getValid(last)); init=1; } if (isEnd == true) { //to show step count when reach the goal if (hasShown == false) { String msg = stepCount.toString() + " steps"; JOptionPane.showMessageDialog(null, msg); hasShown = true; } } else { if(!crossLocation.isEmpty()) { //peak's size is greater than 0, needs to move forward from one of the locations. if(crossLocation.peek().size()!=0) { for(Location loc: crossLocation.peek()) { Actor redrock=getGrid().get(loc); //Find the end of the maze. if(redrock instanceof Rock && redrock.getColor().getRGB()==Color.RED.getRGB()) { isEnd=true; return; } } //random choose a direction to move. double r = Math.random()*crossLocation.peek().size(); next=crossLocation.peek().get((int)Math.floor(r)); //After a success move, top of stack directionlist sotres the //direction from the last location to local location. directionlist.push(this.getDirection()); last=getLocation(); //After a success move, top of the stack locationlist stores the //last location it just been on. locationlist.push(last); if(canMove()) { move(); stepCount++; crossLocation.push(getValid(next)); last=next; return; } } //peak's size is 0, need to fall back. else { Location putflower=getLocation(); this.moveTo(locationlist.pop()); this.setDirection(directionlist.pop()); Flower flower = new Flower(getColor()); flower.putSelfInGrid(getGrid(), putflower); //a two-time pop and a push means to pop the top //and renew the element below the top crossLocation.pop(); crossLocation.pop(); crossLocation.push(getValid(getLocation())); return; } } } }
9
private void menu_closeConnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menu_closeConnActionPerformed Globals.global_connection.close_connection(); this.setTitle("Kurs project,3105,Ratnikov,Chuglov. Connection state = " + Globals.global_connection.get_connection_state()); // TODO add your handling code here: }//GEN-LAST:event_menu_closeConnActionPerformed
0
@Override public void run() { initialize(); newGeneration = new Chromosome[popsize]; for (int k = 0; k < nGenerations; k++) { evaluate(population); Arrays.sort(population); System.out.println( "Iter: " + k + " Dur: " + population[0].getActualDuration() ); // Elitism for (int i = 0; i < elitism; i++) newGeneration[i] = (Chromosome) population[i].clone(); for (int i = elitism; i < popsize; i++) { Chromosome child = crossover(tourPick(), randomChoice()); mutate(child); newGeneration[i] = child; } Chromosome[] pom = population; population = newGeneration; newGeneration = pom; if (configuration != null) configuration.increase(); } evaluate(population); Arrays.sort(population); this.bestIndividual = (Individual) population[0]; System.out.println("GA Best Project Duration: " + this.bestIndividual.getActualDuration() ); }
4
public static void main(String[] args) { int numOfGuesses = 0; GameHelper helper = new GameHelper(); SimpleDotCom theDotCom = new SimpleDotCom(); int randomNum = (int) (Math.random() * 5); int[] locations = {randomNum, randomNum+1, randomNum+2}; theDotCom.setLocationCells(locations); boolean isAlive = true; while (isAlive == true) { String guess = helper.getUserInput("enter a number"); String result = theDotCom.checkYourself(guess); numOfGuesses++; if (result.equals("kill")) { isAlive = false; System.out.println("You took " + numOfGuesses + " guesses"); } } }
2
public static void sendData(String message, String IP, int PORT){ String multicast = IP; int port = PORT; Logger logger = LoggerFactory.getLogger(DaemonStorageProcess.class); InetAddress group = null; try { group = InetAddress.getByName(multicast); } catch (UnknownHostException e) { e.printStackTrace(); } //create Multicast socket to to pretending group MulticastSocket s = null; try { s = new MulticastSocket(port); } catch (IOException e) { e.printStackTrace(); } if (group != null && s != null) try { s.joinGroup(group); } catch (IOException e) { e.printStackTrace(); } byte[] b = message.getBytes(); DatagramPacket dp = new DatagramPacket(b, b.length, group, port); try { s.send(dp); } catch (IOException e) { e.printStackTrace(); } java.util.Date date = new java.util.Date(); logger.info("data send"); }
6
public List<ReceptDTO> getReceptList() throws DALException { List<ReceptDTO> list = new ArrayList<ReceptDTO>(); ResultSet rs = Connector.doQuery("SELECT * FROM recept"); try { while (rs.next()) { list.add(new ReceptDTO(rs.getInt(1), rs.getString(2))); } } catch (SQLException e) { throw new DALException(e); } return list; }
2
@Before(value = "") public void before() throws Throwable { log.info("Beginning method: "); }
0
public Logging() { String time = getFilenameDateTime(); logfilename = "log/log" + time + ".xml"; msgfilename = "log/.msg" + time; start = "\t<start date=\"" + getLogDate() + "\" time=\"" + getLogTime() + "\" />\n"; try { File file = new File("log/"); if (!file.exists()) file.mkdir(); else if (!file.isDirectory()) throw new IOException(file.getAbsolutePath() + " is not a directory"); fMessages = new File(msgfilename); if (!fMessages.exists()) fMessages.createNewFile(); oswMessage = new OutputStreamWriter(new FileOutputStream(fMessages), encoding); } catch (Exception e) { e.printStackTrace(); return; } }
4
public Row getByKey(String tableName, String key) throws DBUnavailabilityException, DataBaseRequestException, DataBaseTableException { if (key == null) { throw new DataBaseRequestException("key shouldn't be null"); } String firstCharAtName = key.substring(0, 1); DataBase db = getDataBaseByKey(firstCharAtName); return db.getByKey(tableName, key); }
1
public static Dir getDir(int id) {//Great for iterating over all Dirs in a for loop // ex: for(int d=0;d<4;d++) // square.transform(Dir.getDir(d)); switch (id) { case 0: return Dir.North; case 1: return Dir.East; case 2: return Dir.South; case 3: return Dir.West; default: if (id<0) return Dir.Down; else return Dir.Up; } }
5
public void busRemoved (Bus bus) throws IOException { if (model == null) return; synchronized (busses) { Bus newBusses [] = new Bus [busses.length - 1]; HubNode newHubs [] = new HubNode [newBusses.length]; int index, nodeIndex = -1; HubNode node = null; // which one went? for (int i = index = 0; i < busses.length; i++) { if (busses [i] == bus) { nodeIndex = i; node = hubs [i]; } else { newBusses [index] = busses [i]; newHubs [index] = hubs [i]; index++; } } System.err.println ("rm bus: " + node); busses = newBusses; hubs = newHubs; if (model != null) model.nodesWereRemoved (this, new int [] { nodeIndex }, new TreeNode [] { node }); } }
4
@Override void write(DataOutput dataoutput) { try { if (!this.list.isEmpty()) { this.type = ((NBTBase) this.list.get(0)).getTypeId(); } else { this.type = 0; } dataoutput.writeByte(this.type); dataoutput.writeInt(this.list.size()); for (int i = 0; i < this.list.size(); ++i) { ((NBTBase) this.list.get(i)).write(dataoutput); } } catch (IOException e) { throw new NBTWriteException(e); } }
3
public void setDescription(String description) { this.description = description; }
0
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
@SuppressWarnings({ "unchecked", "rawtypes" }) public void run() { //References the instance of the plugin and config for easier accessing ms = MojangStatus.getInstance(); config = ms.getConfig(); try { //Retrieve status info URL url = new URL("http://status.mojang.com/check"); Scanner s = new Scanner(url.openStream()); this.json = s.next(); s.close(); //Parse JSON data this.gson = new Gson(); Type listType = new StatusChecker.ListType(this).getType(); this.jsonObject = ((ArrayList) this.gson.fromJson(this.json, listType)); if(config.debug) ms.getLogger().log(Level.FINE, "[Mojang Status] Successfully downloaded JSON"); } catch (IOException ex) { ms.getLogger().log(Level.FINE, "Error when trying to retrieve Mojang server status data."); if(config.debug) ex.printStackTrace(); } try { //Expected format is: //[{"minecraft.net":"green"},{"login.minecraft.net":"green"},{"session.minecraft.net":"green"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"green"},{"sessionserver.mojang.com":"green"}] //Sets the service status to offline when the corresponding jsonObject has the value "red" ms.setStatus(Service.MINECRAFTNET, !((String) ((HashMap) this.jsonObject.get(0)).get("minecraft.net")). equalsIgnoreCase("red")); ms.setStatus(Service.LOGINMINECRAFT, !((String) ((HashMap) this.jsonObject.get(1)).get("login.minecraft.net")). equalsIgnoreCase("red")); ms.setStatus(Service.SESSIONMINECRAFT, !((String) ((HashMap) this.jsonObject.get(2)).get("session.minecraft.net")). equalsIgnoreCase("red")); ms.setStatus(Service.ACCOUNTMOJANG, !((String) ((HashMap) this.jsonObject.get(3)).get("account.mojang.com")). equalsIgnoreCase("red")); ms.setStatus(Service.AUTHMOJANG, !((String) ((HashMap) this.jsonObject.get(4)).get("auth.mojang.com")). equalsIgnoreCase("red")); ms.setStatus(Service.SKINSMINECRAFT, !((String) ((HashMap) this.jsonObject.get(5)).get("skins.minecraft.net")). equalsIgnoreCase("red")); ms.setStatus(Service.AUTHSERVERMOJANG, !((String) ((HashMap) this.jsonObject.get(6)).get("authserver.mojang.com")). equalsIgnoreCase("red")); ms.setStatus(Service.SESSIONSERVERMOJANG, !((String) ((HashMap) this.jsonObject.get(7)).get("sessionserver.mojang.com")).equalsIgnoreCase("red")); } catch (Exception ex) { //JSON data have an unexpected format, just ignore it ms.getLogger().log(Level.FINE, "The downloaded JSON data are invalid or empty"); if(config.debug) ex.printStackTrace(); } }
5
public void generate_cffile(int operations_count, int file_minindex, int file_maxindex) { System.out.println("inside generating config file"); int remaining_ops = operations_count; int line_index = 1; int read_ops = (int) Math.floor(0.7 * operations_count); int write_ops = (int) Math.ceil(0.3* operations_count); char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); StringBuilder sb = new StringBuilder(); Random random_string = new Random();// generate random strings for write // operations Random file = new Random();// generates the index of file on which an // operation has to be performed Random opr_select = new Random();// randomly select a number between 0 // and 100. If the number falls // between 0 and 90 then perform // read else write System.out.println("path for config file--------" + path); while (remaining_ops > 0) { int file_index = file.nextInt(file_maxindex - file_minindex + 1);// generate // file // index // on // which // we // need // to // perform // some // operation String file_name = "file" + String.valueOf(file_index) + ".txt"; int opr_index = opr_select.nextInt(); if (opr_index < 70) {// perform read operation if (read_ops > 0) {// check if read operations left is greater // than 0 perform read else do write FileFeatures.appendText(path, line_index + " " + nodeId + " " + file_name + " R"); read_ops = read_ops - 1; } else {// generate random text to write for (int i = 0; i < 10; i++) { char c = chars[random_string.nextInt(chars.length)]; sb.append(c); } FileFeatures.appendText(path, line_index + " " + nodeId + " " + file_name + " W " + sb.toString()); sb.delete(0, sb.length()); write_ops = write_ops - 1; } } else { if (write_ops > 0) { for (int i = 0; i < 10; i++) { char c = chars[random_string.nextInt(chars.length)]; sb.append(c); } FileFeatures.appendText(path, line_index + " " + nodeId + " " + file_name + " W " + sb.toString()); sb.delete(0, sb.length()); write_ops = write_ops - 1; } else { FileFeatures.appendText(path, line_index + " " + nodeId + " " + file_name + " R"); read_ops = read_ops - 1; } } remaining_ops--; line_index++; } }
6
public void nextModel(LineageState state) { state.setCurrentTime(getNextEventTime()); double time = getNextEventTime(); if (time == Long.MAX_VALUE) { // assert false:state.getLinagesActive(); throw new RuntimeException("Model does not permit full coalescent of linages.\n Check for zero migration rates or for exp population growth pastward"); } // we have severl posible states. // -1 we have important events at time zero.... ie newSamples // 1 the current event is before the model end.. we increment events but not a model // 2 the current events == the the model end. we increment events and the model // 3 the current events are after the model. We just incremet the model // this covers the 2 cases where the events need to be increment // System.out.println("PreCurrentEventLoop:"+currentEvent); while (currentEvent != null && currentEvent.getEventTime() == time) { // System.out.println("EventsMoveLoop:"+currentEvent); currentEvent.processEventCoalecent(state); if (eventIterator.hasNext()) { currentEvent = eventIterator.next(); } else { currentEvent = null; } } // if ((time >= currentModel.getEndTime() || currentEvent == null) && modelIterator.hasNext() && time > 0) { currentModel = modelIterator.next(); } state.setCurrentMaxTime(getNextEventTime()); state.setSelectionData(currentModel.getSelectionData()); // System.out.println("SelectionData? "+currentModel.getSelectionData()+"\t"+state.getSelectionData()); }
8
public static final ISkill getSkill(final int id) { if (skills.size() != 0) { return skills.get(Integer.valueOf(id)); } System.out.println("Loading SkillFactory :::"); final MapleDataProvider datasource = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/Skill.wz")); final MapleDataDirectoryEntry root = datasource.getRoot(); int skillid; MapleData summon_data; SummonSkillEntry sse; for (MapleDataFileEntry topDir : root.getFiles()) { // Loop thru jobs if (topDir.getName().length() <= 8) { for (MapleData data : datasource.getData(topDir.getName())) { // Loop thru each jobs if (data.getName().equals("skill")) { for (MapleData data2 : data) { // Loop thru each jobs if (data2 != null) { skillid = Integer.parseInt(data2.getName()); skills.put(skillid, Skill.loadFromData(skillid, data2)); summon_data = data2.getChildByPath("summon/attack1/info"); if (summon_data != null) { sse = new SummonSkillEntry(); sse.attackAfter = (short) MapleDataTool.getInt("attackAfter", summon_data, 999999); sse.type = (byte) MapleDataTool.getInt("type", summon_data, 0); sse.mobCount = (byte) MapleDataTool.getInt("mobCount", summon_data, 1); SummonSkillInformation.put(skillid, sse); } } } } } } } return null; }
8
public void settingsKey(int k, Character c) { HUD hud = null; for (int i = (huds.size() - 1); i >= 0; i--) { hud = huds.get(i); if (hud.getName().equals("ScreenKeys")) { hud.settingsKey(k, c); } } }
2
public static void main(String[] args) { GameData g = new GameData(6); String[] tribes = new String[] { "banana", "apple" }; g.setTribeNames(tribes[0], tribes[1]); Contestant c1 = null, c2 = null; try { c1 = new Contestant("a2", "Al", "Sd", tribes[1]); c2 = new Contestant("as", "John", "Silver", tribes[0]); } catch (InvalidFieldException e) { // wont happen. } try { g.addContestant(c1); g.addContestant(c2); } catch (InvalidFieldException ie) { } g.startSeason(5); User u1; try { u1 = new User("First", "last", "flast"); User u2 = new User("Firsto", "lasto", "flasto"); g.addUser(u1); g.addUser(u2); u1.setPoints(10); u2.setPoints(1); } catch (InvalidFieldException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { System.out.println(g.toJSONObject().toString()); } catch (ParseException e1) { e1.printStackTrace(); } }
4
*/ public void deselectAll () { checkWidget (); CTableItem[] oldSelection = selectedItems; selectedItems = new CTableItem [0]; if (isFocusControl () || (getStyle () & SWT.HIDE_SELECTION) == 0) { for (int i = 0; i < oldSelection.length; i++) { redrawItem (oldSelection [i].index, true); } } for (int i = 0; i < oldSelection.length; i++) { oldSelection[i].getAccessible(getAccessible(), 0).selectionChanged(); } if (oldSelection.length > 0) getAccessible().selectionChanged(); }
5
public void showEndScreen() { main.textFont(font, 130); main.text("Game Over!", 30, 150); main.textFont(font, 30); main.text("[R]etry", 680, 480); if (main.rightBar.score == 10 && main.opponent != null) { main.textFont(font, 50); main.text("Get some practice an come back.", 30, 350); return; } main.textFont(font, 100); main.text("Congratulations", 30, 300); main.textFont(font, 50); if (main.leftBar.score == 10 && main.opponent != null) { main.text("You defeated a machine...", 100, 400); return; } if (main.leftBar.score == 10) { main.text("Player 1 wins!", 250, 400); return; } if (main.rightBar.score == 10) { main.text("Player 2 wins!", 250, 400); return; } }
6
public void move(int xa, int ya) { if(xa != 0 && ya != 0){ if(diagonal<4){ move(xa, 0); move(0, ya); diagonal++; }else{ diagonal = 0; } return; } if (xa > 0) dir = 1; if (xa < 0) dir = 3; if (ya > 0) dir = 2; if (ya < 0) dir = 0; if (!collision(xa, ya)) { x += xa; y += ya; } }
8
public void saveOrder() throws Exception{ orderSQL="INSERT INTO ORDERS(USERNAME,"; orderSQL += " SHIPPING_ADDRESS, SHIPPING_ZIPCODE, SHIPPING_CITY)"; orderSQL += " VALUES(?,?,?,?)"; try{ // load the driver and get a connection Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url); // turn off autocommit to handle transactions yourself con.setAutoCommit(false); orderPstmt = con.prepareStatement(orderSQL); orderPstmt.setString(1, buyerName); orderPstmt.setString(2, shippingAddress); orderPstmt.setString(3, shippingZipcode); orderPstmt.setString(4, shippingCity); orderPstmt.execute(); // now handle all items in the cart saveOrderItems(); sb.clear(); con.commit(); // end the transaction } catch(Exception e){ try{ con.rollback(); // failed, rollback the database } catch(Exception ee){} throw new Exception("Error saving Order", e); } finally{ try { rs.close(); } catch(Exception e) {} try { stmt.close(); } catch(Exception e) {} try{ orderPstmt.close(); } catch(Exception e){} try{ orderItemPstmt.close(); } catch(Exception e){} try{ con.close(); } catch(Exception e){} } }
7
public void start() { Timer time = new Timer(); TimerTask task = new TimerTask() { /** * Actions to do */ @Override public void run() { localNet.progress(); localNet.showNet(); if (!localNet.hasSafe()) { this.cancel(); } } }; time.schedule(task, 1000, 3000); }
1
public void forward_packet(Node sender, Packet packet) { try { //latência do canal de transferência sleep((long) this.latency); } catch (InterruptedException e) { e.printStackTrace(); } //identifica qual das extremidades está enviando Node receiver = null; if (sender.equals(this.point_A)) receiver = this.point_B; else if (sender.equals(this.point_B)) receiver = this.point_A; else { System.err.println("You can't send packets if you don't belong to me!"); return; } synchronized (receiver) { receiver.receive_packet(this, packet); } if(this.sniffer != null) //Se este link tem um sniffer.... this.sniffer.write_capture(packet); }
4
@Override public AbstractActionPanel getAction() { if ( owner.getSelected() ) { return new ActionPanelBlank(); } else { return new ActionPanelBlank(); } }
1
public void run() { long beforeTime, afterTime, timeDiff, sleepTime; long overSleepTime = 0L; int noDelays = 0; long excess = 0L; gameStartTime = System.nanoTime(); prevStatsTime = gameStartTime; beforeTime = gameStartTime; running = true; while(running) { theModel.update(); theFrame.setBreakoutModel(theModel); gameRender(); paintScreen(); afterTime = System.nanoTime(); timeDiff = afterTime - beforeTime; sleepTime = (period - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { Thread.sleep(sleepTime/1000000L); // nano -> ms } catch(InterruptedException ex){} overSleepTime = (System.nanoTime() - afterTime) - sleepTime; } else { // sleepTime <= 0; the frame took longer than the period excess -= sleepTime; // store excess time value overSleepTime = 0L; if (++noDelays >= NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); /* If frame animation is taking too long, update the game state without rendering it, to get the updates/sec nearer to the required FPS. */ int skips = 0; while((excess > period) && (skips < MAX_FRAME_SKIPS)) { excess -= period; theModel.update(); // update state but don't render theFrame.setBreakoutModel(theModel); skips++; } framesSkipped += skips; storeStats(); } printStats(); System.exit(0); // so window disappears }
6
@Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 2) return Boolean.class; else if(columnIndex == 3) return Boolean.class; return super.getColumnClass(columnIndex); }
3
public void pedirPath(File[] dir) { ArrayList<String> ficheros = new ArrayList(); if(getPath().equals("")){ Interfaz.dirAct.setText(("Carpeta: \"\\\"")); }else{ Interfaz.dirAct.setText("Carpeta: \"" + getPath() + "\""); } int i=0; for (final File fileEntry : dir) { if (booleans[i]) { ficheros.add("1" + fileEntry.getName()); } else{ ficheros.add("2" + fileEntry.getName()); } i++; } Interfaz.setList(ficheros); }
3
private static void printHeroList() { for(HeroSlot heroslot : heroSlots){ System.out.println(heroslot.toString()); } }
1