text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) { List<String> a = new LinkedList<String>(); a.add("Amy"); a.add("Carl"); a.add("Erica"); List<String> b = new LinkedList<String>(); b.add("Bob"); b.add("Doug"); b.add("Frances"); b.add("Gloria"); // merge the words from b into a ListIterator<String> aIter = a.listIterator(); Iterator<String> bIter = b.iterator(); while (bIter.hasNext()) { if (aIter.hasNext()) aIter.next(); aIter.add(bIter.next()); } System.out.println(a); // remove every second word from b bIter = b.iterator(); while (bIter.hasNext()) { bIter.next(); // skip one element if (bIter.hasNext()) { bIter.next(); // skip next element bIter.remove(); // remove that element } } System.out.println(b); // bulk operation: remove all words in b from a a.removeAll(b); System.out.println(a); }
4
public static void main(String[] args) throws IOException { InputStream inputStream = Tongues.class.getResourceAsStream("A-small-practice.in"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferReader = new BufferedReader(inputStreamReader); int numLines = Integer.parseInt(bufferReader.readLine()); String line; List<String> myList = new ArrayList<String>(); for (int i = 0; i < numLines; i++) { myList.add(bufferReader.readLine()); } List<String> decodeList = Tongues.decodeList(myList); for (int i = 0; i < numLines; i++) { line = decodeList.get(i); line = String.format("Case #%1$d: %2$s ", i+1, line); System.out.println(line); } bufferReader.close(); inputStreamReader.close(); inputStream.close(); }
2
@XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "KeyInfo") public JAXBElement<KeyInfoType> createKeyInfo(KeyInfoType value) { return new JAXBElement<KeyInfoType>(_KeyInfo_QNAME, KeyInfoType.class, null, value); }
0
public boolean collision(double x1, double y1, double x2, double y2, int imgW2, int imgH2){ if(x1 > x2 && x1 < x2 + imgW2){ if(y1 > y2 && y1 < y2 + imgH2){ return false; } }else if(x1 < x2 && x1 > x2 - imgW2){ if(y1 < y2 && y1 > y2 - imgH2){ return false; } } return true; }
8
@Override public void onEnable() { if (setupEconomy()) { FreeForAll.instance = this; FreeForAll.ffaconfig = new FFAConfig(this); ffaconfig.load(); loadArenas(); new Queue().runTaskTimer(this, 20, 20); System.out.println("[FreeForAll] arenas loaded."); try { DB = new MySQLc(this); usingDataBaseLeaderBoards = true; try { engineManager.registerEngine(new LeaderboardEngine(DB)); } catch (EngineException ex) { System.out.println(ex.getMessage()); } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println("Can't load database"); } System.out.println("[FreeForAll] Starting base engines..."); try { engineManager.registerEngine(new InventoryEngine()); } catch (EngineException ex) { System.out.println(ex.getMessage()); } try { engineManager.registerEngine(new OfflineStorageEngine()); } catch (EngineException ex) { System.out.println(ex.getMessage()); } try { engineManager.registerEngine(new StorageEngine()); } catch (EngineException ex) { System.out.println(ex.getMessage()); } try { engineManager.registerEngine(new KillStreakEngine()); } catch (EngineException ex) { System.out.println(ex.getMessage()); } try { engineManager.registerEngine(new DebugEngine()); } catch (EngineException ex) { System.out.println(ex.getMessage()); } System.out.println("[FreeForAll] Done starting base engines."); ffapl = new FFAPlayerListener(this); System.out.println("[FreeForAll] has been enabled."); if (this.getDescription().getVersion().contains("EB")) { Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[FreeForAll] YOU ARE USING AN EXPERIMENTAL BUILD. USE AT YOUR OWN RISK."); } } else { System.out.println("[FreeForAll] unable to load vault."); getServer().getPluginManager().disablePlugin(this); } }
9
public void get() { String s = getClipboardData(); s = s.trim(); if (s.equals("")) { return; } int comboCount = stringCombo.getItemCount(); boolean containsIt = false; for (int i = 0; i < comboCount; ++i) { if (stringCombo.getItemAt(i).toString().trim().equals(s)) { containsIt = true; } } if (!containsIt) { stringCombo.addItem(s); stringCombo.setSelectedItem(s); } }
4
public static byte[] read(String filePath) throws IOException, FileNotFoundException { if (filePath == null) { return null; } FileInputStream fis = new FileInputStream(new File(filePath)); int size = fis.available(); ByteArrayOutputStream baos = new ByteArrayOutputStream(size); byte[] data = null; if (size < BUFFER_SIZE) { data = new byte[size]; } else { data = new byte[BUFFER_SIZE]; } while (true) { int count = fis.read(data); if (count == -1) { break; } baos.write(data); } fis.close(); return baos.toByteArray(); }
4
public void drawBackground(Graphics g) { for (int x = 0; x < 30; x++) { for (int y = 0; y < 20; y++) { for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { Chunk chunk = Main.world.chunks[0]; Square square = chunk.chunk[x][y]; Color color = square.colors[r][c]; g.setColor(color); g.fillRect(32 * x + 4 * r, gameHeight - (32 * y + 4 * c), 4, 4); } } } } }
4
private boolean plantable(MOB mob, Item I2) { if((I2!=null) &&(I2 instanceof RawMaterial) &&(CMLib.flags().canBeSeenBy(I2,mob)) &&(I2.container()==null) &&(((I2.material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_VEGETATION) ||(I2.material()==RawMaterial.RESOURCE_COTTON) ||(I2.material()==RawMaterial.RESOURCE_HEMP) ||((I2.material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_WOODEN))) return true; return false; }
8
public List<Transition> getTransitions(StateEnum stateFrom) { Map<EventEnum, Transition> transitionMap = transitionFromState.get(stateFrom); return transitionMap == null ? Collections.<Transition>emptyList() : new ArrayList<Transition>(transitionMap.values()); }
1
@Override public void init() { setSize(800, 480); setBackground(Color.BLACK); setFocusable(true); addKeyListener(this); // Frame frame = (Frame) this.getParent().getParent(); // frame.setTitle("Q-Bot Alpha"); try { base = getDocumentBase(); } catch (Exception e) { // TODO: handle exception } // Image Setups character = getImage(base, "data/character.png"); character2 = getImage(base, "data/character2.png"); character3 = getImage(base, "data/character3.png"); characterDown = getImage(base, "data/down.png"); characterJumped = getImage(base, "data/jumped.png"); heliboy = getImage(base, "data/heliboy.png"); heliboy2 = getImage(base, "data/heliboy2.png"); heliboy3 = getImage(base, "data/heliboy3.png"); heliboy4 = getImage(base, "data/heliboy4.png"); heliboy5 = getImage(base, "data/heliboy5.png"); background = getImage(base, "data/background.png"); tiledirt = getImage(base, "data/tiledirt.png"); tilegrassTop = getImage(base, "data/tilegrasstop.png"); tilegrassBot = getImage(base, "data/tilegrassbot.png"); tilegrassLeft = getImage(base, "data/tilegrassleft.png"); tilegrassRight = getImage(base, "data/tilegrassright.png"); anim = new Animation(); anim.addFrame(character, 1250); anim.addFrame(character2, 50); anim.addFrame(character3, 50); anim.addFrame(character2, 50); hanim = new Animation(); hanim.addFrame(heliboy, 100); hanim.addFrame(heliboy2, 100); hanim.addFrame(heliboy3, 100); hanim.addFrame(heliboy4, 100); hanim.addFrame(heliboy5, 100); hanim.addFrame(heliboy4, 100); hanim.addFrame(heliboy3, 100); hanim.addFrame(heliboy2, 100); currentSprite = anim.getImage(); }
1
public static String randomString(final int size) { return randomObject(new RandomObjectFunction<String>() { public String get() { StringBuilder sb = new StringBuilder(size); for (int i = 0; i < size; i++) { char c = (char) ((r.nextBoolean() ? 'A' : 'a') + r .nextInt('z' - 'a')); sb.append(c); } return sb.toString(); } }); }
2
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); int nCase = 0; while ((line = in.readLine()) != null && line.length() != 0) { if (nCase++ != 0) out.append("\n"); String[] vars = line.trim().split(" "); size = vars.length; map = new int[200]; map2 = new char[size + 1]; ady = new ArrayList[size + 1]; parents = new int[size + 1]; int id = 1; for (int i = 0; i < size; i++) { char l = vars[i].charAt(0); map[l] = id; map2[id++] = l; } for (int i = 0; i <= size; i++) ady[i] = new ArrayList<Integer>(30); String[] ins = in.readLine().trim().split(" "); for (int i = 0; i < ins.length; i += 2) { int a = map[ins[i].charAt(0)]; int b = map[ins[i + 1].charAt(0)]; ady[a].add(b); parents[b]++; } for (int i = 1; i < parents.length; i++) if (parents[i] == 0) { parents[i]++; ady[0].add(i); } ans = new ArrayList<String>(); DFS(0, 0, 0, ""); Collections.sort(ans); for (String path : ans) out.append(path + "\n"); } System.out.print(out); }
9
public final void waitForStatus() throws FatalError { getCharacter(); while (User.getCurrentLivePoints() != User.getMaxLivePoints()) { Output.printTabLn("Warte bis Leben aufgefüllt ist.", 2); Control.sleep(300, 2); getCharacter(); } }
1
private Entity checkRegexPatterns(String text) { Entity plausible = null; String temp = text; if(Character.isUpperCase(temp.charAt(0))) { if(temp.contains("'")) { if(temp.contains("'s")) { temp = temp.replaceAll("'s", ""); } else if(temp.contains("s'")) { temp = temp.replace("s'", ""); } else if(temp.contains("es'")) { temp = temp.replace("es'", ""); } } if(regex.isName(temp)) { plausible = Entity.PERSON; } if(regex.isLocation(temp)) { plausible = Entity.LOCATION; } if(plausible == Entity.OTHER) { plausible = Entity.ORGAINIZATION; } } if(regex.isTime(temp)) { plausible = Entity.TIME; } return plausible; }
9
public boolean addMaster(File file, int resID) { if (file == null || resID == -1) { return false; } int fileSize = file.getSizeInByte(); Object[] packet = new Object[2]; packet[0] = file; packet[1] = myID_; int tag = DataGridTags.FILE_ADD_MASTER; super.send(super.output, 0.0, tag, new IO_data(packet,fileSize,resID)); // wait for the result back tag = DataGridTags.FILE_ADD_MASTER_RESULT; FilterDataResult type = new FilterDataResult(file.getName(), tag); Sim_event ev = new Sim_event(); super.sim_get_next(type, ev); boolean result = false; try { packet = (Object[]) ev.get_data(); // get the data String resName = GridSim.getEntityName(resID); // resource name int msg = ((Integer) packet[2]).intValue(); // get the result if (msg == DataGridTags.FILE_ADD_SUCCESSFUL) { result = true; System.out.println(super.get_name() + ".addMaster(): " + file.getName() + " has been added to " + resName); } else { System.out.println(super.get_name() + ".addMaster(): " + "Error in adding " + file.getName() + " to " + resName); } } catch (Exception e) { result = false; System.out.println(super.get_name() + ".addMaster(): Exception"); } return result; }
4
public String getCoef() { return coef; }
0
public String toString() { final StringBuffer buf = new StringBuffer(30); buf.append("DM "); if (mc == MC_PROPREAD_REQ) buf.append("prop-read.req"); else if (mc == MC_PROPREAD_CON) buf.append("prop-read.con"); else if (mc == MC_PROPWRITE_REQ) buf.append("prop-write.req"); else if (mc == MC_PROPWRITE_CON) buf.append("prop-write.con"); else if (mc == MC_PROPINFO_IND) buf.append("prop-info.ind"); else if (mc == MC_RESET_REQ) return "DM reset.req"; else if (mc == MC_RESET_IND) return "DM reset.ind"; buf.append(" objtype ").append(iot); buf.append(" instance ").append(oi); buf.append(" pid ").append(pid); buf.append(" start ").append(start); if (isNegativeResponse()) buf.append(" ").append(getErrorMessage()); else { buf.append(" elements ").append(elems); if (data.length > 0) buf.append(" data ").append(DataUnitBuilder.toHex(data, " ")); } return buf.toString(); }
9
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(VtnAgrega_oModificaProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VtnAgrega_oModificaProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VtnAgrega_oModificaProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VtnAgrega_oModificaProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new VtnAgrega_oModificaProveedor().setVisible(true); } }); }
6
@Override Apfloat pValue(GeneSet geneSet) { // Count number of p-values less or equal to 'pValueCutOff' int count = 0, tot = 0; for (String geneId : geneSet) { if (geneSets.hasValue(geneId)) { if (isTopScore(geneId)) count++; tot++; } } // No genes have values? We are done if (tot <= 0) return ONE; if (debug) { // Calculate and show 'leading edge fraction' double leadingEdgeFraction = ((double) count) / ((double) tot); Timer.showStdErr("Gene set: " + geneSet.getName() + "\tsize: " + geneSet.size() + "\tsize (eff): " + geneSet.sizeEffective() + "\t" + count + "\tleadingEdgeFraction: " + leadingEdgeFraction); } // Calculate p-value double pvalueFisher = FisherExactTest.get().fisherExactTestUp(count, N, D, tot); return new Apfloat(pvalueFisher); }
5
public int findLongestArithmeticProgress(int[] a) { int maxLen = 0; if (a.length< 2) { return 0; } if (a.length < 3) { return 2; } int[][] l = new int[a.length][a.length]; for (int middle = 1; middle < a.length - 1; middle++) { int first = middle - 1; int third = middle + 1; while(first > -1 && third < a.length) { if (a[first] + a[third] == a[middle] * 2) { l[middle][third] = l[first][middle] + 1; if (l[middle][third] > maxLen) { maxLen = l[middle][third]; } third++; first--; } else if (a[first] + a[third] < a[middle] * 2) { third++; } else { first--; } } } return maxLen+2; }
8
public static int parseInt(String num) { if(num != null && num.isEmpty()) { throw new ArithmeticException("Input cannot be null or blank"); } char [] numArray = num.toCharArray(); // 1. "1" -> 1 //2. "25" -> 2*10 + 5 // 3. "235" -> 2*100 + 3* 10 +5 ... 2 . result=2, pop 3, result 2*10 +3 . Pop 5. Result = 23*10 + 5 = 235 //4. "1abc" -> Throws exception int result = 0; //"235" 2,3,5 . 2, 2*10+3 = 23. 5 23*10+5 = 235. 0 000. boolean isNegative = false; int startCount = 0; if(numArray[0] == '-') { isNegative = true; startCount++; } for(int i=startCount; i<numArray.length; i++) { int number = numArray[i]; if(!(number >= '0' && number <= '9')) //Check isNumeric { throw new ArithmeticException("Input is non-numeric"); } result = result * 10 + (number - '0'); } if(isNegative) { result *= -1; } return result; }
7
private boolean jj_3R_48() { if (jj_scan_token(LEFTB)) return true; if (jj_3R_9()) return true; if (jj_scan_token(RIGHTB)) return true; return false; }
3
@Override public void onMouseButtonPress(int buttonID) { for(GuiButton button : buttons) { if(button.isMouseOver()) { Sound.button_hit.play(); button.onClick(); } } }
2
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(Loja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Loja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Loja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Loja.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 Loja().setVisible(true); } }); }
6
@Override public void logicUpdate(GameTime gameTime) { if (!viewPort.getTopLeftLocation().equals(previousViewPortLocation)) { previousViewPortLocation = viewPort.getTopLeftLocation(); // The 'previous'viewport location at this point really the current. updateMapPosition(previousViewPortLocation); } }
1
public boolean canInject(final BeanKey bean) { if (bean == null) { return false; } if (bean == this) { return true; } if (beanType.equals(bean.getBeanType()) && qualifier == null) { return true; } if (GenericsHelper.isAssignableFrom(beanType, bean.getBeanType())) { if (isTheSameQualifier(qualifier, bean.getQualifier())) { return true; } else if (hasTheAnyQualifier()) { return true; } } return false; }
7
private void renderBlocks(Screen screen) { for (int y = HIDDEN_ROWS; y < rows.length; y++) { Block[] row = rows[y]; for (int x = 0; x < row.length; x++) { Block block = row[x]; if (block == null) { //screen.renderBlank(x*BLOCK_SCALE+getX(), y*BLOCK_SCALE+getY(), BLOCK_SCALE, BLOCK_SCALE, 0x00ff00); } else { screen.render(x*BLOCK_SCALE+getX(), (y-HIDDEN_ROWS)*BLOCK_SCALE+getY(), Tetromino.getSprite(block.getType())); } } } }
3
@EventHandler private void onPlayerConnect(PlayerLoginEvent evt) { // Bukkit.broadcastMessage(evt.getPlayer().getName()); String reason = pds.getBanReason(evt.getPlayer().getName()); if (evt.getPlayer().isBanned()) { evt.setKickMessage(reason); evt.disallow(Result.KICK_BANNED, evt.getKickMessage()); } else { // Bukkit.getLogger().warning("Poop"); WarnLevel.addPlayer(evt.getPlayer()); WarnLevel.setPoints(evt.getPlayer(), pds.getDataLevel(evt.getPlayer().getName())); // Bukkit.broadcastMessage("" + evt.getPlayer()); } if (!pds.hasFile(evt.getPlayer().getName())) { playerDataSave.saveDataFirst(evt.getPlayer().getName()); } }
2
public void windowClosing(WindowEvent e) { w.dispose(); if (quit) { System.exit(0); } }
1
private int normalizeCharClass(StringBuilder newPattern, int i) { StringBuilder charClass = new StringBuilder(); StringBuilder eq = null; int lastCodePoint = -1; String result; i++; charClass.append("["); while(true) { int c = normalizedPattern.codePointAt(i); StringBuilder sequenceBuffer; if (c == ']' && lastCodePoint != '\\') { charClass.append((char)c); break; } else if (Character.getType(c) == Character.NON_SPACING_MARK) { sequenceBuffer = new StringBuilder(); sequenceBuffer.appendCodePoint(lastCodePoint); while(Character.getType(c) == Character.NON_SPACING_MARK) { sequenceBuffer.appendCodePoint(c); i += Character.charCount(c); if (i >= normalizedPattern.length()) break; c = normalizedPattern.codePointAt(i); } String ea = produceEquivalentAlternation( sequenceBuffer.toString()); charClass.setLength(charClass.length()-Character.charCount(lastCodePoint)); if (eq == null) eq = new StringBuilder(); eq.append('|'); eq.append(ea); } else { charClass.appendCodePoint(c); i++; } if (i == normalizedPattern.length()) throw error("Unclosed character class"); lastCodePoint = c; } if (eq != null) { result = "(?:"+charClass.toString()+eq.toString()+")"; } else { result = charClass.toString(); } newPattern.append(result); return i; }
9
protected final void update() { float var1 = MathHelper.sin(this.sheep.yRot * 3.1415927F / 180.0F); float var2 = MathHelper.cos(this.sheep.yRot * 3.1415927F / 180.0F); var1 = -0.7F * var1; var2 = 0.7F * var2; int var4 = (int)(this.mob.x + var1); int var3 = (int)(this.mob.y - 2.0F); int var5 = (int)(this.mob.z + var2); if(this.sheep.grazing) { if(this.level.getTile(var4, var3, var5) != Block.GRASS.id) { this.sheep.grazing = false; } else { if(++this.sheep.grazingTime == 60) { this.level.setTile(var4, var3, var5, Block.DIRT.id); if(this.random.nextInt(5) == 0) { this.sheep.hasFur = true; } } this.xxa = 0.0F; this.yya = 0.0F; this.mob.xRot = (float)(40 + this.sheep.grazingTime / 2 % 2 * 10); } } else { if(this.level.getTile(var4, var3, var5) == Block.GRASS.id) { this.sheep.grazing = true; this.sheep.grazingTime = 0; } super.update(); } }
5
public static <T extends Model> T findLast(final Class<T> cls) { final String tableName = Reflection.getSimpleClassName(cls); final List<T> list = Model.where(cls, "_id=(select max(_id) from " + tableName + ")"); T model = null; if (list != null && list.size() > 0) { model = list.iterator().next(); } return model; }
2
public static void findMinimumWindow(String s, String t) { char[] needToFind = new char[256]; char[] hasFound = new char[256]; for( int i = 0 ; i< t.length(); i++) { needToFind[t.charAt(i)] ++; } // how many elements have been found int count = 0; int start = 0; int end = 0; int minstart = -1; int minend = -1; int minLength = Integer.MAX_VALUE; while(end < s.length()) { if(needToFind[s.charAt(end)] == 0) { end++; continue; } hasFound[s.charAt(end)] ++; if(hasFound[s.charAt(end)] <= needToFind[s.charAt(end)]) { count ++; } // we have reached at a window .. now try shrinking it as much as you can without breaking the constraint if(count == t.length()) { while (hasFound[s.charAt(start)] == 0 || hasFound[s.charAt(start)] > needToFind[s.charAt(start)]) { if(hasFound[s.charAt(start)] > needToFind[s.charAt(start)]) { hasFound[s.charAt(start)] --; } start ++; } if(end - start+1 < minLength) { minLength = end - start +1; minstart = start; minend = end; } } end ++; } System.out.println(s.substring(minstart, minend+1)); }
9
public Double getAttribute(int index){ if( index < attributes.length ) { return attributes[index]; } else return null; }
1
public synchronized void drain() { if (m_line!=null && m_line.isActive()) { long t=0; long waitTime=AMAudioFormat.bytes2Ms(m_bufferSize, m_format)+50; if (Debug.DEBUG || Debug.TRACE) { Debug.println(this, "drain() simulation ("+waitTime+"ms..."); t=System.currentTimeMillis(); } try { wait(waitTime); } catch (InterruptedException ie) {} if (Debug.TRACE) { Debug.println(this, "drain() exit: "+(System.currentTimeMillis()-t)+"ms"); } } }
6
public static FontInfo getFont(String font) { String lowerFont = font.toLowerCase(); if (lowerFont == "helvetica") { return HELVETICA; } else if (lowerFont == "times new roman" || lowerFont == "times_new_roman" || lowerFont == "timesnewroman") { return TIMES_NEW_ROMAN; } // uh what? throw new AssertionError("Unknown font: " + font); }
4
public static List<String> getAlphabetCombination(int order) { if (order <0 || order>3) { throw new IllegalArgumentException("Supports order 1,2, or 3"); } switch(order) { case 1: return ALPHABET_COMBINATIONS_1; case 2: return ALPHABET_COMBINATIONS_2; case 3: return ALPHABET_COMBINATIONS_3; } return null; }
5
@Override public void onPluginEnable(PluginEnableEvent event) { if (plugin.economy != null) { if (plugin.economy.isEnabled()) { //System.out.println("[" + plugin.getDescription().getName() + "] Payment method enabled: " + plugin.economy.getName() + "."); } } if (plugin.permission != null) { if (plugin.permission.isEnabled()) { //System.out.println("[" + plugin.getDescription().getName() + "] Permission method enabled: " + plugin.permission.getName() + "."); } } }
4
public static boolean isPrime(int number) { if (number < 0) { throw new IllegalArgumentException(); } if (number <= 1) { return false; } for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { return false; } } return true; }
4
@Override public void beforePhase(PhaseEvent event) { System.out.println("Depois da fase: "+ getPhaseId()); if (event.getPhaseId().equals(PhaseId.RENDER_RESPONSE)){ Session session = FacesContextUtil.getRequestSession(); try { session.getTransaction().commit(); } catch (Exception e) { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } finally{ session.close(); } } }
3
protected int clock_interpolate(CycleCount delta_t, short buf[], int n, int interleave) { int s = 0; int i; for (;;) { int /* cycle_count */next_sample_offset = sample_offset + cycles_per_sample; int /* cycle_count */delta_t_sample = next_sample_offset >> FIXP_SHIFT; if (delta_t_sample > delta_t.delta_t) { break; } if (s >= n) { return s; } for (i = 0; i < delta_t_sample - 1; i++) { clock(); } if (i < delta_t_sample) { sample_prev = (short) output(); clock(); } delta_t.delta_t -= delta_t_sample; sample_offset = next_sample_offset & FIXP_MASK; short sample_now = (short) output(); buf[s++ * interleave] = (short) (sample_prev + (sample_offset * (sample_now - sample_prev) >> FIXP_SHIFT)); sample_prev = sample_now; } for (i = 0; i < delta_t.delta_t - 1; i++) { clock(); } if (i < delta_t.delta_t) { sample_prev = (short) output(); clock(); } sample_offset -= delta_t.delta_t << FIXP_SHIFT; delta_t.delta_t = 0; return s; }
7
public void watch(Source source) { // make sure the source exists: if (source == null) return; // make sure we aren't already watching this source: if (streamingSources.contains(source)) return; ListIterator<Source> iter; Source src; // Make sure noone else is accessing the list of sources: synchronized (listLock) { // Any currently watched source which is null or playing on the // same channel as the new source should be stopped and removed // from the list. iter = streamingSources.listIterator(); while (iter.hasNext()) { src = iter.next(); if (src == null) { iter.remove(); } else if (source.channel == src.channel) { src.stop(); iter.remove(); } } // Add the new source to the list: streamingSources.add(source); } }
5
protected void handleErrorAndCallConnector() { try { RequestScopeObject scopeObj=RequestScope.getRequestObj(); SwingObjectsExceptions e = scopeObj.getErrorObj(); boolean isCall=true; if(e!=null) { CommonUI.showErrorDialogForComponent(e); switch(e.getErrorSeverity()) { case ERROR: case SEVERE: isCall=false; break; default: // call connector break; } } if(isCall) { DataMapper.mapGUI(scopeObj.getContainer()); callConnector(scopeObj); } }catch(SwingObjectRunException e) { e.printStackTrace(); CommonUI.showErrorDialogForComponent(e); }catch(Exception e) { e.printStackTrace(); CommonUI.showErrorDialogForComponent(new SwingObjectRunException(e, this.getClass())); } }
6
@Override public void mutateStackForInfixTranslation(Stack<Token> operatorStack, StringBuilder output) { if (this.isOpen()) { operatorStack.push(this); } else { Token next; while ((next = operatorStack.peek()) instanceof OperatorToken || next instanceof FunctionToken || (next instanceof ParenthesesToken && !((ParenthesesToken) next).isOpen())) { output.append(operatorStack.pop().getValue()).append(" "); } operatorStack.pop(); } }
5
public void putInternal(final int key, final FastSparseSet<Integer> value, boolean remove) { int index = 0; int ikey = key; if (ikey < 0) { index = 2; ikey = -ikey; } else if (ikey >= VarExprent.STACK_BASE) { index = 1; ikey -= VarExprent.STACK_BASE; } FastSparseSet<Integer>[] arr = elements[index]; if (ikey >= arr.length) { if (remove) { return; } else { arr = ensureCapacity(index, ikey + 1, false); } } FastSparseSet<Integer> oldval = arr[ikey]; arr[ikey] = value; int[] arrnext = next[index]; if (oldval == null && value != null) { size++; changeNext(arrnext, ikey, arrnext[ikey], ikey); } else if (oldval != null && value == null) { size--; changeNext(arrnext, ikey, ikey, arrnext[ikey]); } }
8
public String layer_string() { switch (h_layer) { case 1: return "I"; case 2: return "II"; case 3: return "III"; } return null; }
3
public void whiteTurn(int sx, int sy, int ex, int ey) { int piece = board.getPiece(sx, sy); board.whiteTurn(sx, sy, ex, ey); if (board.getMoveW()) { setInfo(0); turns++; if (cm.canAttackKing(board.getBoard(), piece, ex, ey)) { setInfo(2); cm.addSquares(); if (!cm.canKingMove() && !cm.canTakeDownAttacker(ex, ey)) { setInfo(4); } } } if (board.getBlack(4) == 99) { setInfo(4); } }
5
public Result allocate(String type, int n) throws IOException { ArrayList<ByteBuffer> bufs = new ArrayList<ByteBuffer>(n); long start = System.currentTimeMillis(); if (type.equalsIgnoreCase("onheap")) { for (int i = 0; i < n; i++) // 1200*1M to produce OOM with a 1G heap { ByteBuffer bb = ByteBuffer.allocate(1024*1024); bufs.add(bb); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } else if (type.equalsIgnoreCase("offheap")) { for (int i = 0; i < n; i++) { ByteBuffer bb = ByteBuffer.allocateDirect(1024*1024); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } bufs.add(bb); } } long end = System.currentTimeMillis(); System.out.printf("Cost %d ms\n", end-start); for(ByteBuffer bb : bufs) { destroyDirectBuffer(bb); } bufs.clear(); //System.gc(); return new Result(n, (int) (end-start)); }
7
private boolean outOfBound(double x, double dx, double xBound){ return (x + dx < 0) || (x + dx > xBound ); }
1
public void rotarAtrasIzquierda() { if (direccion.equals(Direccion.derecha)) { rotar(tipoTrans.enZ, -135); } else if (direccion.equals(Direccion.adelante)) { rotar(tipoTrans.enZ, 135); } else if (direccion.equals(Direccion.atras)) { rotar(tipoTrans.enZ, -45); } else if (direccion.equals(Direccion.izquierda)) { rotar(tipoTrans.enZ, 45); } else if (direccion.equals(Direccion.atDer)) { rotar(tipoTrans.enZ, -90); } else if (direccion.equals(Direccion.adDer)) { rotar(tipoTrans.enZ, 180); } else if (direccion.equals(Direccion.adIzq)) { rotar(tipoTrans.enZ, 90); } direccion = Direccion.atIzq; }
7
private static Camera makecam(Class<? extends Camera> ct, String... args) throws ClassNotFoundException { try { try { Constructor<? extends Camera> cons = ct .getConstructor(String[].class); return (cons.newInstance(new Object[]{args})); } catch (IllegalAccessException e) { } catch (NoSuchMethodException e) { } try { return (ct.newInstance()); } catch (IllegalAccessException e) { } } catch (InstantiationException e) { throw (new Error(e)); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) throw ((RuntimeException) e.getCause()); throw (new RuntimeException(e)); } throw (new ClassNotFoundException( "No valid constructor found for camera " + ct.getName())); }
8
public void gameUpdated(GameUpdateType type) { // find our super parent frame -- needed for dialogs Component c = this; while (null != c.getParent()) c = c.getParent(); switch (type) { case ERROR: boardFrame.bp.repaint(); boardPanel.repaint(); controlPanel.play.setEnabled(false); controlPanel.step.setEnabled(false); controlPanel.pause.setEnabled(false); controlPanel.stop.setEnabled(false); controlPanel.begin.setEnabled(true); configPanel.setEnabled(true); JOptionPane.showMessageDialog((Frame) c, errorMessage, "Game Over", JOptionPane.INFORMATION_MESSAGE); boardFrame.bp.repaint(); boardPanel.repaint(); break; case GAMEOVER: if(!is_recursive) { fast = false; controlPanel.play.setEnabled(false); controlPanel.step.setEnabled(false); controlPanel.pause.setEnabled(false); controlPanel.stop.setEnabled(false); controlPanel.begin.setEnabled(true); configPanel.setEnabled(true); String s = "All flights reached destination at time " + (engine.getCurrentRound()) + "; power used=" + engine.getBoard().powerUsed + "; delay=" + engine.getBoard().delay; JOptionPane.showMessageDialog((Frame) c, s, "Game Over", JOptionPane.INFORMATION_MESSAGE); } break; case MOVEPROCESSED: controlPanel.roundText.setText("" + engine.getCurrentRound()); controlPanel.powerText.setText("" + engine.getPower()); controlPanel.delayText.setText("" + engine.getDelay()); boardFrame.round.setText("Round: " + engine.getCurrentRound()); boardFrame.bp.repaint(); boardPanel.repaint(); break; case STARTING: controlPanel.roundText.setText("0"); controlPanel.powerText.setText("0"); controlPanel.delayText.setText("0"); break; case MOUSEMOVED: configPanel.setMouseCoords(BoardPanel.MouseCoords); case REPAINT: boardFrame.bp.repaint(); boardPanel.repaint(); default: // nothing. } }
8
@Basic @Column(name = "item_cost_price") public BigDecimal getItemCostPrice() { return itemCostPrice; }
0
@Override protected void logBindInfo(Method method) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("绑定" + getDescription() + "到方法[" + method + "]成功"); } }
1
private static int onOff(int source) { assert((source >= 0) && (source < Simulator.numNodes())); if(m_nodeStates == null) { m_nodeStates = new int [Simulator.numNodes()]; for(int n = 0; n < m_nodeStates.length; n++) m_nodeStates[n] = 0; } // advance state: off -> on OR on -> off if(m_nodeStates[source] == 0) { if(Simulator.randDouble() < Config.burstAlpha()) { m_nodeStates[source] = 1; } } else if (Simulator.randDouble() < Config.burstBeta()) { m_nodeStates[source] = 0; } // generate packet if(m_nodeStates[source] == 1) { double r1 = (Config.injectionRate() * (1.0 + Config.burstBeta() / Config.burstAlpha())) / (double)Config.packetSize(); if (Simulator.randDouble() < r1) return Config.packetSize(); } return 0; }
8
public PacketCodec(ImmutableBiMap<Integer, Class<? extends Packet>> packetMapping) { this.packetMapping = packetMapping; }
1
static ArrayList<Integer> KMP(char[] p) { ArrayList<Integer> r = new ArrayList<>(); int i = 1, j = 0, n = t.length, m = p.length; while (i < n) { while (j >= 0 && t[i] != p[j]) j = b[j]; i++; j++; if (j == m) { if (ids[i - m - 1] != ids[i - m] && ids[i - m] == ids[i - 1]) r.add(ids[i - 1]); j = b[j]; } } return r; }
6
@Override public String toString() { String txt = ""; switch (locType) { case LATLONG: txt = this.name + delim + this.lat + delim + this.lon; break; case NORTHINGEASTING: txt = this.name + delim + this.northing + delim + this.easting; break; case XY: txt = this.name + delim + this.x + delim + this.y; break; } return txt; }
3
public static void rectangle(double x, double y, double halfWidth, double halfHeight) { if (halfWidth < 0) throw new RuntimeException("half width can't be negative"); if (halfHeight < 0) throw new RuntimeException("half height can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*halfWidth); double hs = factorY(2*halfHeight); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
4
@Override public void doCharacterCollision(ArrayList<Collision> collisions, StageObject stageObject) { /** * @todo remove tempory fix */ Collision collision = collisions.get(0); if (stageObject instanceof StageMario) { if (hadCollision) { if (!stage.getMario().isBig()) { stage.getMario().setGrow(true); } setAlive(false); stage.getMario().setInit(true); stage.getMario().setFlowerPower(true); } } if (stageObject instanceof Questionmark) { hadCollision = true; hit = true; changeAni = true; } }
4
private void button6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button6MouseClicked if(numberofpins < 4) { if(numberofpins == 0) { Login_form.setString1("5"); } if(numberofpins == 1) { Login_form.setString2("5"); } if(numberofpins == 2) { Login_form.setString3("5"); } if(numberofpins == 3) { Login_form.setString4("5"); } numberofpins +=1; jLabel2.setText(Integer.toString(numberofpins)); } else { System.out.print(Timetable_main_RWRAF.checkDelete()); JOptionPane.showMessageDialog(null,"You've already entered your 4 digit pin!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE); }// TODO add your handling code here: }//GEN-LAST:event_button6MouseClicked
5
@SuppressWarnings("rawtypes") private void chooseTargetShire() { Shire myShire = Me.myShire(); Library library = myShire.getLibrary(); SK_ k = SK_.valToSK.get(Me.FB.randomValueInPriority()); KnowledgeBlock kb = library.findKnowledge(k); if (kb != null) {kb.useKnowledge(Me);} else {sendScout(k);} Clan myShireGov = myShire.getGovernor(); if (targetShire == null && (myShireGov == null || myShireGov.myOrder() != Me.myOrder())) { targetShire = myShire; } if (targetShire == null) { Me.addReport(GobLog.nowhereToAttack()); } }
5
private void gestureProcessing(Frame frame) { if (!frame.fingers().empty()) { // Configure Custom Gesture Settings controller.config().setFloat("Gesture.KeyTap.MinDownVelocity ", 30); controller.config().setFloat("Gesture.Swipe.MinVelocity ", 1000); controller.config().save(); controller.enableGesture(Type.TYPE_SWIPE); controller.enableGesture(Type.TYPE_KEY_TAP); controller.enableGesture(Type.TYPE_SCREEN_TAP); controller.enableGesture(Type.TYPE_CIRCLE); GestureList gestureList = frame.gestures(); for (Gesture gesture : gestureList) { if(gesture.type() == Type.TYPE_KEY_TAP) { KeyTapGesture tap = new KeyTapGesture(gesture); if(tap.state() ==State.STATE_STOP) { for (LeapParameterListener lpl : listeners) { lpl.onNewGesture(GestureType.KEY_PRESS, tap.hands().rightmost().palmPosition()); } System.out.println("Key Gesture FINALLY!!"); } } if(gesture.type() == Type.TYPE_SWIPE) { SwipeGesture swipe = new SwipeGesture(gesture); if (swipe.state() == State.STATE_STOP) { for (LeapParameterListener lpl : listeners) { lpl.onNewGesture(GestureType.SWIPE, swipe.direction()); } System.out.println("Swipe Gesture!!"); } } } } }
8
private void calcularCalificacion(){ ArrayList<Respuesta> nuevaListaRespuestaUsuario = new ArrayList(); int index = -1; int calificacion = 0; ArrayList<Respuesta> grupos = obtenerTodosGrupos(); int indicadorGrupo = 0; for (int i = 0; i < _respuestaUsuario.size(); i++) { for (int j = 0; j < _respuestaUsuario.get(i).size(); j++) { for (int k = 0; k < _respuestaUsuario.get(i).get(j).size(); k++) { index = _respuestaUsuario.get(i).get(j).indexOf(_respuestasComparar.get(i).get(j).get(k).getRespuesta()); if(index>-1){ nuevaListaRespuestaUsuario.add(_respuestasComparar.get(i).get(j).get(index)); if(j == indicadorGrupo || j == (indicadorGrupo-4)){ agregarRespuestaHojaCalculo(grupos.get(indicadorGrupo).getRespuesta(),_respuestasComparar.get(i).get(j).get(index).getRespuesta(), String.valueOf(_respuestasComparar.get(i).get(j).get(index).getPonderacion())); indicadorGrupo++; }else{ agregarRespuestaHojaCalculo(_respuestasComparar.get(i).get(j).get(index).getRespuesta(), String.valueOf(_respuestasComparar.get(i).get(j).get(index).getPonderacion())); } index = -1; }else{ if(j == indicadorGrupo || j == (indicadorGrupo-4)){ agregarRespuestaHojaCalculo(grupos.get(indicadorGrupo).getRespuesta(),_respuestaUsuario.get(i).get(j).get(k), "0"); indicadorGrupo++; }else{ agregarRespuestaHojaCalculo(_respuestaUsuario.get(i).get(j).get(k), "0"); } } } } } for (int i = 0; i < nuevaListaRespuestaUsuario.size(); i++) { calificacion+= nuevaListaRespuestaUsuario.get(i).getPonderacion(); } _calificacion+=calificacion; agregarRespuestaHojaCalculo("Total", String.valueOf(calificacion)); System.out.println(calificacion); }
9
public String getSearchSearchArg() { _read.lock(); try { return _searchSearchArg; } finally { _read.unlock(); } }
0
@Override protected void onTopic(String channel, String topic, String setBy, long date, boolean changed) { for (ChannelEventsListener listener : channelEventsListeners) { if ( listener.getChannelName().equals(channel) ) { listener.topicChanged(setBy, topic); break; } } }
2
@Override public void run() { while (true) { watchdog.set(false); try { Thread.sleep(65); } catch (InterruptedException ex) { //System.out.println("Watchdog: whimper"); return; } if (watchdog.get() == false) { //System.out.println("Watchdog: growl"); sensorDataIsValid.set(false); } } }
3
static public String numberToString(Number n) throws JSONException { if (n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; }
6
private void drawRobotArm() { Mass shoulder = null; Mass elbow = null; Mass hand = null; for (Mass mass : networkGraph.getMasses()) { switch (mass.getType()) { case SHOULDER: shoulder = mass; break; case ELBOW: elbow = mass; break; case HAND: hand = mass; } } g2.setColor(ARM_COLOR); g2.setStroke(ARM_STROKE); if (shoulder != null && elbow != null) { int shoulderX = (int) (xScale * shoulder.getX()); int shoulderY = (int) (yScale * shoulder.getY() * MASS_AND_SPRING_Y_SCALING); int elbowX = (int) (xScale * elbow.getX()); int elbowY = (int) (yScale * elbow.getY() * MASS_AND_SPRING_Y_SCALING); g2.drawLine(shoulderX, shoulderY, elbowX, elbowY); } if (elbow != null && hand != null) { int elbowX = (int) (xScale * elbow.getX()); int elbowY = (int) (yScale * elbow.getY() * MASS_AND_SPRING_Y_SCALING); int handX = (int) (xScale * hand.getX()); int handY = (int) (yScale * hand.getY() * MASS_AND_SPRING_Y_SCALING); g2.drawLine(elbowX, elbowY, handX, handY); } }
8
public JpaDao() { boolean create = false; try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/", "carletti", "carletti"); Statement stmt = connection.createStatement(); try { stmt.executeUpdate("USE carletti;"); ResultSet rs = stmt .executeQuery("SELECT * from users LIMIT 1;"); if (!rs.next()) throw new Exception("RECREATE!!!"); System.out.println("Database exists!"); } catch (Throwable e) { stmt.executeUpdate("DROP DATABASE IF EXISTS carletti;"); stmt.executeUpdate("CREATE DATABASE carletti;"); stmt.executeUpdate("USE carletti;"); System.out.println("Database created!"); create = true; } } catch (Exception e) { System.out.println("Error interacting with database: " + e.getMessage()); } emf = Persistence.createEntityManagerFactory("Carletti"); em = emf.createEntityManager(); tx = em.getTransaction(); if (create) createSomeObjects(); }
4
static public void initialize(actor.interfaces.Movable newListener) { if (enabled) { listener = newListener; al = ALFactory.getAL(); ALut.alutInit(); checkForALErrorsWithMessage("Failed to initialize OpenAl"); sources = new LinkedList<Source>(); /* * Queue our sound events based on their distance from the camera */ events = new PriorityQueue<Event>(16, new Comparator<Event>() { @Override public int compare(Event event1, Event event2) { float d1 = event1.getPosition().minus( listener.getPosition()).magnitude2(); float d2 = event2.getPosition().minus( listener.getPosition()).magnitude2(); if (d1 > d2) return -1; else if (d2 > d1) return 1; else return 0; } }); Library.initialize(); for (int i = 0; i < MAX_SOURCES; i++) try { sources.add(new Source()); } catch (RuntimeException e) { System.err.println(e.toString()); System.err .println("Error when generating OpenAL Sources. Successfully generated " + i + " sources of " + MAX_SOURCES); break; } } }
5
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; if (m < 1) return 0; int n = obstacleGrid[0].length; if (n < 1) return 0; if (obstacleGrid[0][0] != 0) return 0; int[] dp = new int[n]; dp[0] = 1; // Initialize first row for (int j = 1; j < n; j++) { if (obstacleGrid[0][j] == 1) dp[j] = 0; else dp[j] = dp[j - 1]; } for (int i = 1; i < m; i++) { dp[0] = obstacleGrid[i][0] == 0 ? dp[0] : 0; for (int j = 1; j < n; j++) { dp[j] = obstacleGrid[i][j] == 0 ? dp[j] + dp[j - 1] : 0; } } return dp[n - 1]; }
9
Log4JMembersInjector(Field field) { this.field = field; this.logger = Logger.getLogger(field.getDeclaringClass()); field.setAccessible(true); }
0
* @param hitDelay The delay before hitting the target. * @param attackStyle The attack style used. * @param weaponId The weapon id. * @param hit The hit done. * @param gfxId The gfx id. * @param startHeight The start height of the original projectile. * @param endHeight The end height of the original projectile. * @param speed The speed of the original projectile. * @param delay The delay of the original projectile. * @param curve The curve of the original projectile. * @param startDistanceOffset The start distance offset of the original projectile. */ private void checkSwiftGlovesEffect(Player player, int hitDelay, int attackStyle, int weaponId, int hit, int gfxId, int startHeight, int endHeight, int speed, int delay, int curve, int startDistanceOffset) { Item gloves = player.getEquipment().getItem(Equipment.SLOT_HANDS); if (gloves == null || !gloves.getDefinitions().getName().contains("Swift glove")) { return; } if (hit != 0 && hit < ((max_hit / 3) * 2) || new Random().nextInt(3) != 0) { return; } player.getPackets().sendGameMessage("You fired an extra shot."); World.sendProjectile(player, target, gfxId, startHeight - 5, endHeight - 5, speed, delay, curve - 5 < 0 ? 0 : curve - 5, startDistanceOffset); delayHit(hitDelay, weaponId, attackStyle, getRangeHit(player, getRandomMaxHit(player, weaponId, attackStyle, true))); if (hit > (max_hit - 10)) { target.addFreezeDelay(10000, false); target.setNextGraphics(new Graphics(181, 0, 96)); } }
7
public static void main(String[] args) throws NotExistException { Map map = new Map(); map.setRobot(1); map.setRobot(3); map.setRobot(5); for (int i = 0; i < 30; i++) { try { map.progress(); } catch (NotExistException exception) { exception.getMessage(); } } }
2
public void setCtrPosId(int ctrPosId) { this.ctrPosId = ctrPosId; }
0
void setExampleWidgetPopupMenu() { Control[] controls = getExampleControls(); for (int i = 0; i < controls.length; i++) { final Control control = controls [i]; control.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { Menu menu = control.getMenu(); if (menu != null && samplePopup) { menu.dispose(); menu = null; } if (menu == null && popupMenuButton.getSelection()) { menu = new Menu(shell, SWT.POP_UP | (control.getStyle() & (SWT.RIGHT_TO_LEFT | SWT.LEFT_TO_RIGHT))); MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Sample popup menu item"); specialPopupMenuItems(menu, event); control.setMenu(menu); samplePopup = true; } } }); } }
5
void createBuffers(int width, int height, String options) { if (g != null) g.dispose(); if (frontImageBuffer != null) frontImageBuffer.flush(); if (backImageBuffer != null) backImageBuffer.flush(); options = options != null ? options.toLowerCase() : ""; bufferSize = new Dimension(width, height); stretchToFit = options.contains("stretch"); // if buffers are requested _after_ the window has been realized // then faster volatile images are possible // BUT volatile images silently fail when tested Vista IE8 and // JRE1.6 boolean useVolatileImages = false; if (useVolatileImages) { try { // Paint silently fails when tested in IE8 Vista JRE1.6.0.14 backImageBuffer = createVolatileImage(width, height); frontImageBuffer = createVolatileImage(width, height); } catch (Exception ignored) { } } if (!GraphicsEnvironment.isHeadless()) { try { GraphicsConfiguration config = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); backImageBuffer = config.createCompatibleImage(width, height); frontImageBuffer = config.createCompatibleImage(width, height); } catch (Exception ignored) { } } // as a fall-back we can still use slower BufferedImage with // arbitrary RGB model if (frontImageBuffer == null) { // System.err.println("Creating BufferedImage buffers"); backImageBuffer = new BufferedImage(bufferSize.width, bufferSize.height, BufferedImage.TYPE_INT_RGB); frontImageBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } master.flipBuffer();// set up graphics, including font and color // state paintImmediately = true; // actually, user has not yet called // flipBuffer }
9
public List<Double> getStat(String statIndex, Date currDate) { List<Double> retList = new ArrayList<Double>(); try { View view = client.getView("get", "get_thread_vm"); Query query = new Query(); query.setIncludeDocs(true).setLimit(20); query.setStale(Stale.FALSE); ViewResponse result = client.query(view, query); for (ViewRow row : result) { String wrkString = row.getDocument().toString(); wrkString = wrkString.substring(1, wrkString.length()).substring(0, wrkString.length() - 2); String[] statVals = wrkString.split(","); String dblToParse = null; String dateToParse = null; for(String vals : statVals) { String[] pairs = vals.split(":"); String key = pairs[0].substring(1, pairs[0].length()).substring(0, pairs[0].length() - 2); if (key.equals(statIndex)) dblToParse = pairs[1].substring(1, pairs[1].length()).substring(0, pairs[1].length() - 2); if (key.equals("date_time")) { String[] dateParts = vals.split("\":\""); dateToParse = dateParts[1].substring(0, dateParts[1].length() - 1); } } Date dateToCheck = dateFormat.parse(dateToParse); if (currDate.compareTo(dateToCheck) < 0) retList.add(Double.parseDouble(dblToParse)); } } catch (Exception ex) { System.out.println(ex.getMessage().toString()); System.exit(1); } return retList; }
6
@Override public TLValue evaluate() { for(TLNode stat : statements) { TLValue value = stat.evaluate(); if(value != TLValue.VOID) { // return early from this block if value is a return statement return value; } } // return VOID or returnStatement.evaluate() if it's not null return returnStatement == null ? TLValue.VOID : returnStatement.evaluate(); }
3
private void switchOptions() { switch (switchMode) { case (SWITCH_RENDERER): { isIdle=true; if (buffer.usesRenderer(IRenderer.RENDERER_OPENGL)) { keyMapper.destroy(); buffer.disableRenderer(IRenderer.RENDERER_OPENGL); buffer.enableRenderer(IRenderer.RENDERER_SOFTWARE, IRenderer.MODE_OPENGL); openGL=false; if (fullscreen) { device.setFullScreenWindow(null); } frame.hide(); frame.dispose(); initializeFrame(); } else { frame.hide(); buffer.enableRenderer(IRenderer.RENDERER_OPENGL, IRenderer.MODE_OPENGL); buffer.disableRenderer(IRenderer.RENDERER_SOFTWARE); openGL=true; keyMapper.destroy(); keyMapper=new KeyMapper(); } isIdle=false; break; } } switchMode=0; }
3
public void getMapReset(int mapId) { if (mapId == 1) { // Lille map globalPosX = 1; globalPosY = 0; xStart = Run.window.screen.width/2 - (Screen.blockSize * 5); yStart = Run.window.screen.height/2 - (Screen.blockSize * 4); outOfPlaceHor = false; outOfPlaceVer = false; Run.player.setPlayer(270, 125, true); getMap(); } if (mapId == 2) { //Stort map (Main map) - kommer ud af lille map globalPosX = 0; globalPosY = 0; xStart = -480; yStart = -200; outOfPlaceHor = true; outOfPlaceVer = true; Run.player.setPlayer(450, 218, false); getMap(); } }
2
public void modeChange(int mode) { switch (mode) { case CPController.M_DRAW: curSelectedMode = curDrawMode; break; case CPController.M_FLOODFILL: curSelectedMode = floodFillMode; break; case CPController.M_RECT_SELECTION: curSelectedMode = rectSelectionMode; break; case CPController.M_MOVE_TOOL: curSelectedMode = moveToolMode; break; case CPController.M_ROTATE_CANVAS: curSelectedMode = rotateCanvasMode; break; } }
5
@Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { Schema schemaAnnotation = null; for (Annotation annotation : annotations) { if (annotation.annotationType().equals(Schema.class)) { schemaAnnotation = (Schema) annotation; break; } } if (schemaAnnotation != null) { ObjectMapper mapper = locateMapper(type, mediaType); JsonParser jp = mapper.getFactory().createJsonParser(entityStream); jp.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); URL schemaLocation = schemaLookup.getSchemaURL(schemaAnnotation.value()); JsonSchema jsonSchema = cache.getSchema(schemaLocation); JsonNode jsonNode = mapper.readTree(jp); List<ErrorMessage> validationErrors = jsonSchema.validate(jsonNode); if (validationErrors.isEmpty()) { return mapper.reader().withType(mapper.constructType(genericType)).readValue(jsonNode); } throw new WebApplicationException(generateErrorMessage(validationErrors)); } else { return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); } }
4
public static Type convertType(String name) { if (name.equals("pool")) return Type.Pool; else if (name.equals("qemu")) return Type.VmQemu; else if (name.equals("node")) return Type.Node; else if (name.equals("storage")) return Type.Storage; else return Type.Unknown; }
4
public void stop() { if (isMovingRight() == false && isMovingLeft() == false) { speedX = 0; } if (isMovingRight() == false && isMovingLeft() == true) { moveLeft(); } if (isMovingRight() == true && isMovingLeft() == false) { moveRight(); } }
6
public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
6
public int getTaille() { return taille; }
0
@SuppressWarnings("unchecked") private List<Column> getTableColumns(Table table, List<String> primaryKeys, List<String> indices, Map<Object, Object> uniqueIndices, Map<Object, Object> uniqueColumns) throws SQLException { List<Column> pkList = new ArrayList<Column>(); List<Column> columns = new LinkedList<Column>(); ResultSet columnRs = getColumnsResultSet(table); while (columnRs.next()) { int sqlType = columnRs.getInt("DATA_TYPE"); String sqlTypeName = columnRs.getString("TYPE_NAME"); if ("INT".equals(sqlTypeName)) { sqlTypeName = "INTEGER"; } if ("TEXT".equals(sqlTypeName)) { sqlTypeName = "VARCHAR"; } if ("DATETIME".equals(sqlTypeName)) { sqlTypeName = "TIMESTAMP"; } String columnName = columnRs.getString("COLUMN_NAME"); String columnDefaultValue = columnRs.getString("COLUMN_DEF"); boolean isNullable = (DatabaseMetaData.columnNullable == columnRs.getInt("NULLABLE")); int size = columnRs.getInt("COLUMN_SIZE"); int decimalDigits = columnRs.getInt("DECIMAL_DIGITS"); String comment = columnRs.getString("REMARKS");// 列字段注释 boolean isPk = primaryKeys.contains(columnName); boolean ifFk = table.getImportedKeys().getHasImportedKeyColumn(columnName); boolean isIndexed = indices.contains(columnName); String uniqueIndex = (String) uniqueIndices.get(columnName); List<String> columnsInUniqueIndex = null; if (uniqueIndex != null) { columnsInUniqueIndex = (List<String>) uniqueColumns.get(uniqueIndex); } boolean isUnique = columnsInUniqueIndex != null && columnsInUniqueIndex.size() == 1; if (isUnique) { log.debug("unique column:" + columnName); } Column column = new Column(table, sqlType, sqlTypeName, columnName, size, decimalDigits, isPk, ifFk, isNullable, isIndexed, isUnique, columnDefaultValue, comment); columns.add(column); if (isPk) { pkList.add(column); } } table.setPrimaryKeyColumns(pkList); columnRs.close(); return columns; }
8
@Override public W<DeltaMSet> delta(DC obj) { if(obj instanceof MSet) { MSet that=(MSet)obj; Set<Pair<T,PT<Integer>>> baseSetA=this.getBaseSet(); Set<Pair<T,PT<Integer>>> baseSetB=that.getBaseSet(); Set<Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>>> phiMax=getPhiMax(getAllPhis(baseSetA,baseSetB)); Equality equ=getPhiEqu(phiMax); int m=this.size(); int n=that.size(); double diffMeasure=(2*getPhiSim(phiMax).getValue()+Similarity.sizeBalance(m,n))/(m+n); if(equ.getValue() && m==n && phiMax.size()==m) { return new W( new Equality(true),new Similarity(1.0),new DeltaMSet.Id(this));} else { return new W( new Equality(false), new Similarity(diffMeasure), new DeltaMSet( dMax(phiMax), getMSet(baseSetA.less(dom(phiMax))), getMSet(baseSetB.less(codom(phiMax))) ) ); } } else { throw new RuntimeException(obj+"should be of type MSet");} }
4
private boolean isKeyCurrent() { return ( nNode>0 && sRecno>0 && nKey>=0 && sRecno==recno && pgR[nKey] == recno); }
4
public final void setRowHeight(int height) { if (mRowHeight != height) { mRowHeight = height; invalidateAllRowHeights(); } }
1
private void init() { util = new Utility(this); try { String out = new Scanner(new URL(McCheckVersionPath).openStream(), "UTF-8").useDelimiter("\\A").next(); con.log("Log","McLauncher version: " + McVersion + " Checked version: " +out); //Compare versions if(!util.testSameVersion(out,McVersion) && util.newerVersion(out, McVersion)){ btnUpdate.setVisible(true); //Disabled for now } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Statistics so i can see usage util.noteInfo("Launch"); //Set default mod icon to show setModImg("http://www.mclama.com/Downloads/ModIcon.png"); //Hide the tags from the jTable so we can sort through it later int tindex = tableDownloads.getColumnModel().getColumnIndex("Tags"); TableColumn col = tableDownloads.getColumnModel().getColumn(tindex); tableDownloads.getColumnModel().removeColumn(col); //0modname, 1author, 2version, 3mod_tags, 4description, 5required_mods, //6updates, 7download_url, 8update_url, 9icon_url, 10downloads, 11mod_page, 12copyright setModDownloads(); /* * Options */ if(tglbtnNewModsFirst.isSelected()) Collections.reverse(Arrays.asList(dlModList)); //reverse our list of mods data. }
5
public String getSBIName(String inSBICode){ if (SBICode.containsKey(inSBICode)) return SBICode.get(inSBICode); System.out.println("key not found:" + inSBICode); //Changes in SBI http://www.kvk.nl/over-de-kvk/over-het-handelsregister/wat-staat-er-in-het-handelsregister/overzicht-sbi-codes/ switch (inSBICode) { case "6321": return "persagentschappen"; case "6329": return "overige dienstverlenende activiteiten op het gebied van informatie"; } return inSBICode; }
3
public void setValue(ELContext context, Object base, Object property, Object val) { if (context == null) { throw new NullPointerException(); } if (base == null || property == null){ return; } if (isReadOnly) { throw new PropertyNotWritableException( ELUtil.getExceptionMessageString(context, "resolverNotwritable", new Object[] { base.getClass().getName() })); } BeanProperty bp = getBeanProperty(context, base, property); Method method = bp.getWriteMethod(); if (method == null) { throw new PropertyNotWritableException( ELUtil.getExceptionMessageString(context, "propertyNotWritable", new Object[] { base.getClass().getName(), property.toString()})); } try { method.invoke(base, new Object[] {val}); context.setPropertyResolved(base, property); } catch (ELException ex) { throw ex; } catch (InvocationTargetException ite) { throw new ELException(ite.getCause()); } catch (Exception ex) { if (null == val) { val = "null"; } String message = ELUtil.getExceptionMessageString(context, "setPropertyFailed", new Object[] { property.toString(), base.getClass().getName(), val }); throw new ELException(message, ex); } }
9
public String getName() { return this._name; }
0
public static String[][] leer(String nombreArchivo) { File archivo = null; FileReader fr = null; BufferedReader br = null; String texto=""; try { // Apertura del fichero y creacion de BufferedReader para poder // hacer una lectura comoda (disponer del metodo readLine()). archivo = new File ("..\\Mundial\\"+nombreArchivo+".txt"); fr = new FileReader (archivo); br = new BufferedReader(fr); // Lectura del fichero String linea; while((linea=br.readLine())!=null){ texto=texto+linea; texto=texto+"\n"; } } catch(Exception e){ e.printStackTrace(); }finally{ // En el finally cerramos el fichero, para asegurarnos // que se cierra tanto si todo va bien como si salta // una excepcion. try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ e2.printStackTrace(); } } String[] separado, masSeparado; separado= texto.split("\n"); String[][] chevere=new String [separado.length][8]; // 8 es igual al numero de parametros que entra for (int i=0; i<separado.length; i++){ masSeparado=separado[i].split(";"); for(int j=0; j<masSeparado.length;j++) chevere[i][j]=masSeparado[j]; } return chevere; }
6
@Override public void run() { try { ServerSocket server = new ServerSocket(Config.BIND_PORT, 50, InetAddress.getByName(Config.BIND_ADDRESS)); Socket socket; while ((socket = server.accept()) != null) { try { DataInputStream reader = new DataInputStream(socket.getInputStream()); int packetID = Varint.readVarInt(reader); Packet packet = getNewPacket(packetID); if (packet == null) packet = getNewPacket(Varint.readVarInt(reader)); if (packet == null) { System.out.println("Unkown Packet ID received: " + packetID); reader.close(); socket.close(); continue; } packet.read(reader); DataOutputStream writer = new DataOutputStream(socket.getOutputStream()); if (packet instanceof Packet254ServerPing) this.a( (Packet254ServerPing) packet, reader, writer ); else if (packet instanceof Packet2Handshake) this.a( (Packet2Handshake) packet, writer ); else if (packet instanceof Packet0Handshake) this.a( (Packet0Handshake) packet, reader, writer ); writer.flush(); writer.close(); reader.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); continue; } } } catch (Exception e) { e.printStackTrace(); } }
8
public static void defaultOptionHandler(Stella_Object self, StorageSlot slot, Stella_Object tree) { { Stella_Object parsedvalue = null; if (slot.type() == Stella.SGT_STELLA_BOOLEAN) { parsedvalue = Stella_Object.coerceToBoolean(tree); } else { if (tree != null) { parsedvalue = Stella_Object.permanentCopy(tree); } } if ((((Integer)(Stella.$SAFETY$.get())).intValue() >= 2) && (parsedvalue != null)) { if (!Stella_Object.isaP(parsedvalue, slot.type().typeToWrappedType())) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationError(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR); { Stella.STANDARD_ERROR.nativeStream.println(); Stella.STANDARD_ERROR.nativeStream.println(" Illegal value for `" + ((Keyword)(KeyValueList.dynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_OPTION_KEYWORD, null))) + "' option: `" + Stella_Object.deUglifyParseTree(tree) + "'."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } return; } } StandardObject.writeSlotValue(((StandardObject)(self)), slot, parsedvalue); } }
6