text
stringlengths
14
410k
label
int32
0
9
public static List<String> getQuotes() { List<String> ff = new LinkedList<String>(); try { HttpURLConnection con = (HttpURLConnection) new URL("http://www.bash.org/?random").openConnection(); StringBuilder sb = new StringBuilder(); con.connect(); InputStream input = con.getInputStream(); byte[] buf = new byte[2048]; int read; while ((read = input.read(buf)) > 0) { sb.append(new String(buf, 0, read)); } final String find = "<p class=\"qt\">"; int firstPost = sb.indexOf(find); StringBuilder send = new StringBuilder(); for (int i = firstPost + find.length(); i < sb.length(); i++) { char ch = sb.charAt(i); if (ch == '<') { if (sb.charAt(i + 1) == '/') { if (sb.charAt(i + 2) == 'p') { break; } } } if (ch == '<') { if (sb.charAt(i + 1) == 'b') { if (sb.charAt(i + 2) == 'r') { ff.add(ignore(send.toString())); send = new StringBuilder(); } } send.append(ch); } } input.close(); con.disconnect(); } catch (Exception e) { System.err.println("[Bash Bot] There has been an error displaying the Bash."); e.printStackTrace(); } return ff; }
9
private void parseAttributes(ArrayList<XmlAttr> attrList) { // Sort attributes by key name Collections.sort(attrList, new Comparator<XmlAttr>() { public int compare(XmlAttr o1, XmlAttr o2) { return o1.key.compareTo(o2.key); } }); boolean added; boolean ignore; // Read and create uniques combinations for (int i = 0; i < attrList.size(); ++i) { ignore = false; XmlAttr attr = attrList.get(i); for (int j = 0; j < TAG_IGNORE.length; ++j) if (attr.key.equals(TAG_IGNORE[j])) ignore = true; // Don't parse ignored tags. if (!ignore) { added = false; for (int j = 0; j < baseItemList.size(); ++j) { // Find if combination exist if (attr.equals(baseItemList.get(j).key, baseItemList.get(j).value)) { ++baseItemList.get(j).count; baseItemList.get(j).addFiles(currentFile); attr.id = baseItemList.get(j).id; added = true; } } // If not found, add this combination if (!added) { attr.addFiles(currentFile); baseItemList.add(attr); } } } // Creates all tuples (n > 1) for (int i = 1; i < attrList.size(); ++i) createTuple(attrList, new ArrayList<XmlAttr>(), 0, i + 1); }
8
public Character convert(String source) { if (source.length() == 0) { return null; } if (source.length() > 1) { throw new IllegalArgumentException( "Can only convert a [String] with length of 1 to a [Character]; string value '" + source + "' has length of " + source.length()); } return source.charAt(0); }
2
private static String getQualifiedName(int baseNameLength, String classPath) { logger.info("Computing fully qualified name from" + classPath + " by removing " + baseNameLength + " characters from the start"); // A plugin cannot be an internal class if ((! classPath.endsWith(".class")) || (classPath.indexOf('$') != -1)) { return null; } classPath = classPath.substring(baseNameLength).replace(File.separatorChar, '.'); // removing .class at end logger.info("Fully qualified name of the class: " + classPath); return classPath.substring(0, classPath.lastIndexOf('.')); }
2
@Transactional public int update(Object o) throws DataAccessException { StringBuilder qry = new StringBuilder(); StringBuilder strFieldColumn = new StringBuilder(); StringBuilder strWherePkClause = new StringBuilder(); List<Object> val = new ArrayList<Object>(); qry.append("update "); Class<?> c = o.getClass(); final String strTableName = c.getAnnotation(Table.class).name(); qry.append(strTableName); final PrimaryKey objPk = getPrimaryKey(c); final String strPrimaryKeyName = objPk.key(); Field objPkField = null; try { objPkField = c.getDeclaredField(strPrimaryKeyName); final String strPkColumnName = objPkField.getAnnotation(Column.class).name(); Annotation[] annotations; Field[] fields = c.getDeclaredFields(); Column clmn; Object pk = null; boolean blnFlag = false; boolean blnPkFlag = false; for (Field f : fields) { f.setAccessible(true); annotations = f.getAnnotations(); for (Annotation a : annotations) { if (a instanceof Column) { clmn = (Column)a; if (blnFlag) { strFieldColumn.append(","); } else { strFieldColumn.append(" set "); } blnFlag = true; if (clmn.name().equalsIgnoreCase(strPkColumnName)) { strWherePkClause.append(clmn.name() + "=?"); pk = f.get(o); blnPkFlag = true; } strFieldColumn.append(clmn.name() + "=?"); val.add(f.get(o)); } } } if (blnPkFlag) { qry.append(strFieldColumn.toString() + " Where " + strWherePkClause.toString()); val.add(pk); } else { qry.append(strFieldColumn.toString()); this.setUniqueKeyData(qry, val, o); } } catch (NoSuchFieldException | IllegalAccessException e) { log.debug(e.getMessage(), e); } log.debug(qry.toString()); return simpleJdbcTemplate.update(qry.toString(), val.toArray()); }
8
public void serialEvent(SerialPortEvent spe) { int[] msgToChildren = NetworkProtocol.msgToChildren; if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {//If one byte of data came in try { byte charVal = (byte)input.read(); if (charVal == START_BYTE && dataPacketFlag == false) { //Stores start byte dataPacketFlag = true; netText[byteCounter++] = charVal; window.logAreaText.append("RxD-"); logText = new String(new byte[] {charVal}); window.logAreaText.append(logText); } else if (charVal != STOP_BYTE && dataPacketFlag == true) { //Stores actual data logText = new String(new byte[] {charVal}); window.logAreaText.append(logText); netText[byteCounter++] = charVal; } else if (charVal == STOP_BYTE && dataPacketFlag == true) { //Stores stop byte dataPacketFlag = false; if (netText[1] != msgToChildren[0]) { //botID parent... parseChildMsg(byteCounter); printChildMsg(byteCounter); NetworkProtocol.setSuccessPcktRxd(true); numRxD++; } logText = new String(new byte[] {charVal}); window.logAreaText.append(logText); window.logAreaText.append("\n"); byteCounter = 0; } } catch (Exception e) { logText = "Failed to read data." + "(" + e.toString() + ")"; window.logAreaText.setForeground(Color.red); window.logAreaText.append(logText + "\n"); System.err.println(e.toString()); } } }
9
public void calculateShortestPath() { this.parent = this.startWord; this.wordParent.put(this.startWord, this.parent); char alphabetLetter; int i; //label used for breaking loop outerLoop: while(!(this.queue.isEmpty())) { char[] splitWord = this.queue.get(0).toCharArray(); for(i = 0; i < splitWord.length; i++) { String testWord; for(alphabetLetter = 'a'; alphabetLetter <= 'z'; alphabetLetter++) { char[] splitWordEdit = this.queue.get(0).toCharArray(); splitWordEdit[i] = alphabetLetter; testWord = new String(splitWordEdit); checkWordExists(testWord); if(testWord.equals(this.endWord)) { System.out.println("End word found!"); break outerLoop; } } } this.queue.remove(0); } printLadder(); System.out.println("Done!"); }
4
public File getCsvData() { List<DataLead> leads = selectAll(); if(leads == null) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Can't get data. "); return null; } File tmp = createCsvFile(); if(tmp == null) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Can't create tmp file. "); return null; } try { /** * Create an output stream with UTF-8 encoding. */ FileOutputStream fos = new FileOutputStream(tmp); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); /** * Write file line by line. */ for (DataLead l : leads) { for (int i = 0; i < l.size(); ++i) { osw.write(l.get(i)); if (i < l.size() - 1) { osw.write(","); } } /** * Windows line delimiter. */ osw.write("\r\n"); } osw.flush(); osw.close(); return tmp; } catch (FileNotFoundException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. File ont found. " + e.getMessage()); return null; } catch (UnsupportedEncodingException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Unsupported encoding." + e.getMessage()); return null; } catch (IOException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. IO exception." + e.getMessage()); return null; } }
8
public List<Product> getAll() { List<Product> products = null; try { beginTransaction(); products = session.createCriteria(Product.class).list(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { closeSesion(); } return products; }
1
public static List<String> getMapId(String search) { List<String> ret = new ArrayList<String>(); ret.add("<<MapId Search: " + search + ">>"); MapleData data; MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File(System.getProperty("net.sf.odinms.wzpath") + "/" + "String.wz")); data = dataProvider.getData("Map.img"); List<Pair<Integer, String>> mapPairList = new LinkedList<Pair<Integer, String>>(); for (MapleData mapAreaData : data.getChildren()) { for (MapleData mapIdData : mapAreaData.getChildren()) { int mapIdFromData = Integer.parseInt(mapIdData.getName()); String mapNameFromData = MapleDataTool.getString(mapIdData.getChildByPath("streetName"), "NO-NAME") + " - " + MapleDataTool.getString(mapIdData.getChildByPath("mapName"), "NO-NAME"); mapPairList.add(new Pair<Integer, String>(mapIdFromData, mapNameFromData)); } } int i = 0; for (Pair<Integer, String> mapPair : mapPairList) { if (mapPair.getRight().toLowerCase().contains(search.toLowerCase())) { ret.add(mapPair.getLeft() + " - " + mapPair.getRight()); i++; } if (i >= 20) { break; } } return ret; }
5
public HBox initHeader(String titleText) { HBox header = new HBox(); header.setAlignment(Pos.CENTER_LEFT); header.getStyleClass().add("popUpHeader"); header.setPrefHeight(28); Button closeBtn = new Button(); closeBtn.getStyleClass().add("close-button"); closeBtn.setPrefSize(16, 16); closeBtn.setMinSize(16, 16); closeBtn.setMaxSize(16, 16); closeBtn.setCursor(Cursor.HAND); closeBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { closePopUp(); } }); StackPane sp = new StackPane(); sp.getChildren().add(closeBtn); sp.setAlignment(Pos.CENTER_RIGHT); Label titleLbl = new Label(titleText); titleLbl.getStyleClass().add("popUpHeaderLbl"); header.getChildren().addAll(titleLbl, sp); HBox.setHgrow(sp, Priority.ALWAYS); addDragListeners(header); return header; }
0
public float getMinGain() { float gainMin = -9999.0f; if (audioDevice instanceof JavaSoundAudioDevice) { JavaSoundAudioDevice jsAudio = (JavaSoundAudioDevice) audioDevice; gainMin = jsAudio.getMinGain(); } return gainMin; }
1
public void moveToEx(float x, float y, int random) throws IOException { LOG.debug("Moving to {} {} (and waiting until we reach it, until we're blocked or dead)"); int blocked = 0; int status = this.getMapLoading(); this.moveEx(x, y, random); pingSleep(0); float distanceToTarget = 0; do { try { Thread.sleep(150); } catch (InterruptedException ex) { // ignore } boolean isDead = this.isDead(); if (isDead) { LOG.debug("The player is dead"); break; } int oldStatus = status; status = this.getMapLoading(); if (oldStatus != status) { break; } boolean isMoving = this.isMoving(-2); if (!isMoving) { LOG.debug("Blocked"); blocked++; this.moveEx(x, y, random); } float[] newCoords = this.getCoords(-2); distanceToTarget = this.computeDistanceEx(newCoords[0], newCoords[1], x, y); } while (distanceToTarget > 220 && blocked < 14); LOG.debug("Moved"); }
6
private static void ForWithContinue() { int[] numbers = { 10, 20, 30, 40, 50 }; System.out.println("Begin of ForWithBreak"); for (int x : numbers) { if (x == 30) { continue; } System.out.print(x); System.out.print("\n"); } System.out.println("End of ForWithContinue"); System.out.println("\n"); }
2
private void findExits() throws SlickException { Collections.sort(plan); Integer idchoose = 0; int possibility = MIN_CHOISABLE; int MinDistance = MIN_DISTANCE_TO_EXIT; for (int i = 0; i < exitNumber; i++) { // Pour le nombre de sortie de la // zone boolean goodChoice = false; int tryCounter = 0; // Tentative de choisir une sortie while (!goodChoice) { idchoose = plan.size() - 1 - (int) (possibility * Math.random()); goodChoice = (!plan.get(idchoose).isExit()) /* * Si on a pas déjà * choisi cette * Sortie */ && (Math.abs(plan.get(idchoose).posX) /* * Et si on est * assez loin de * l'entrée */ + Math.abs(plan.get(idchoose).posY) > MinDistance); tryCounter++; /* Si on a du mal a trouver une sortie */ if (tryCounter > possibility * 2) { /* * on elargie le choix (garantie fin de la boucle si nb * tableau > nb de sortie) */ possibility += 5; MinDistance--; if (id == 0) System.out.println("SAFE ! " + possibility + " " + MinDistance); } } plan.get(idchoose).markAsExit(); } }
5
public Game(FullGridFactory gridFactory) { if (gridFactory == null) throw new IllegalArgumentException("Gamefacotry can't be null!"); this.gridFactory = gridFactory; init(); powerFailureFactory = gridFactory.getPowerFailureFactory(); }
1
BaseColor getBadgeBackgroundColor() { String badgeBackgroundColorString = null; if (detectBadgeTypeFromName) { final String adultLeaderBadgeTag = PropertyFileReader.getProperty( "adultLeaderBadgeTag", "A_"); final String youthCounselorBadgeTag = PropertyFileReader .getProperty("youthCounselorBadgeTag", "Y_"); final String specialNeedsYouthBadgeTag = PropertyFileReader .getProperty("specialNeedsYouthBadgeTag", "S_"); if (fileName.contains(adultLeaderBadgeTag)) { badgeBackgroundColorString = PropertyFileReader.getProperty( "badgeBackgroundColorAdultLeader", "#FFFFFF"); fileNameWithoutPrefix = fileName.replace(adultLeaderBadgeTag, ""); } else if (fileName.contains(youthCounselorBadgeTag)) { badgeBackgroundColorString = PropertyFileReader.getProperty( "badgeBackgroundColorYouthCounselor", "#FFFA83"); fileNameWithoutPrefix = fileName.replace( youthCounselorBadgeTag, ""); } else if (fileName.contains(specialNeedsYouthBadgeTag)) { badgeBackgroundColorString = PropertyFileReader.getProperty( "badgeBackgroundColorSpecialNeedsYouth", "#CADBFE"); fileNameWithoutPrefix = fileName.replace( specialNeedsYouthBadgeTag, ""); } // If the background color string is still null, then the badge type // was not specified. // Kill the process. if (badgeBackgroundColorString == null || fileNameWithoutPrefix == null) { throw new IllegalStateException( String.format( "Name badge picture '%s' did not contain a filename tag. Tags are necessary for determining badge type.", filePath + fileSeparator + fileName)); } currentFile = new File(filePath + fileSeparator + fileName); renamedFile = new File(filePath + fileSeparator + fileNameWithoutPrefix); return WebColors.getRGBColor(badgeBackgroundColorString); } return badgeColor; }
6
public void filter(byte[] samples, int offset, int length) { for (int i=0; i<filters.length; i++) { filters[i].filter(samples, offset, length); } }
1
public void clearControllers() { // Reset the ArrayList activeControllers = new ArrayList<JInputController>(); }
0
public byte[] addHeaders(byte[] data) { List<Byte> result = new ArrayList<Byte>(); // Header byte result.add((byte)0x03); // Timestamp long timediff = System.currentTimeMillis() - startTime; result.add((byte)((timediff & 0xFF0000) >> 16)); result.add((byte)((timediff & 0x00FF00) >> 8)); result.add((byte)(timediff & 0x0000FF)); // Body size result.add((byte)((data.length & 0xFF0000) >> 16)); result.add((byte)((data.length & 0x00FF00) >> 8)); result.add((byte)(data.length & 0x0000FF)); // Content type result.add((byte)0x11); // Source ID result.add((byte)0x00); result.add((byte)0x00); result.add((byte)0x00); result.add((byte)0x00); // Add body for (int i = 0; i < data.length; i++) { result.add(data[i]); if (i % 128 == 127 && i != data.length - 1) result.add((byte)0xC3); } byte[] ret = new byte[result.size()]; for (int i = 0; i < ret.length; i++) ret[i] = result.get(i); return ret; }
4
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int len = Integer.parseInt(br.readLine()); String[] l = br.readLine().split(" "); String[] p = br.readLine().split(" "); int[][] result = new int[len][len]; for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { // not taking current i int v1 = 0; try { v1 = result[i - 1][j]; } catch (Exception e) { } // taking it int v2 = 0; if (j >= i) v2 = Integer.parseInt(p[i]); try { v2 = v2 + result[i][j - Integer.parseInt(l[i])]; } catch (Exception e) { } result[i][j] = v1 > v2 ? v1 : v2; } } System.out.println(result[len - 1][len - 1]); }
6
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == kuldesGomb) { kuldes(); } else if (e.getSource() == manualisOktatasMenupont) { manualisOktatasAblakMegnyitas(); } else if(e.getSource() == mentesMenupont){ tudastarMentese(); } else if(e.getSource() == betoltesMenupont){ tudastarBeolvasas(); } else if(e.getSource()==logolMenupont){ vanlogolas=!vanlogolas; if(vanlogolas==true) logolMenupont.setText(off); else if(vanlogolas==false) logolMenupont.setText(on); } }
7
private void nextTurn() { if (this.currentPlayerTurn == 1) { // Minimum 2 players, so always change to P2. this.currentPlayer = this.P2; // Change from P1 to P2 this.currentPlayerTurn = 2; return; } if (this.currentPlayerTurn == 2) { if (this.numPlayers == 2) { // If 2 players, go back to P1. Otherwise, P3. this.currentPlayer = this.P1; this.currentPlayerTurn = 1; return; } this.currentPlayer = this.P3; this.currentPlayerTurn = 3; return; } if (this.currentPlayerTurn == 3) { if (this.numPlayers == 3) { // If 3 players, go back to P1, Otherwise, P4. this.currentPlayer = this.P1; this.currentPlayerTurn = 1; return; } this.currentPlayer = this.P4; this.currentPlayerTurn = 4; return; } if (this.currentPlayerTurn == 4) { if (this.numPlayers == 4) { // If 4 players, go back to P1. Otherwise, P5. this.currentPlayer = this.P1; this.currentPlayerTurn = 1; return; } this.currentPlayer = this.P5; this.currentPlayerTurn = 5; return; } if (this.currentPlayerTurn == 5) { // Max 5 player game, have to go back to P1. this.currentPlayer = this.P1; this.currentPlayerTurn = 1; } }
8
public InputFileChooserView() { display = new Display(); shell = new Shell(display); Monitor primary = display.getPrimaryMonitor(); Rectangle r = primary.getBounds(); shell.setBounds((int) (r.width * 0.1), (int) (r.height * 0.1), (int) (r.width * 0.8), (int) (r.height * 0.8)); Point shellSize = shell.getSize(); shell.setMinimumSize(600, 600); FormLayout layout = new FormLayout(); shell.setLayout(layout); shell.setText("CLC processor"); instantiateWidgets(); layoutWidgets(shellSize); polygonListSC.setContent(polygonList); polygonListSC.setExpandHorizontal(true); polygonListSC.setExpandVertical(true); polygonList.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { int listItemHeight = polygonList.computeSize(SWT.DEFAULT, SWT.DEFAULT).y / polygonList.getItemCount(); if (e.count == -3) { int topIndex = polygonList.getSelectionIndex(); // polygonList.setSelection(++topIndex); polygonListSC.setOrigin(polygonListSC.getOrigin().x, polygonListSC.getOrigin().y + listItemHeight * 10); } else if (e.count == 3) { int topIndex = polygonList.getSelectionIndex(); // polygonList.setSelection(--topIndex); polygonListSC.setOrigin(polygonListSC.getOrigin().x, polygonListSC.getOrigin().y - listItemHeight * 10); } } }); settlementListSC.setContent(settlementList); settlementListSC.setExpandHorizontal(true); settlementListSC.setExpandVertical(true); settlementList.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { int listItemHeight = settlementList.computeSize(SWT.DEFAULT, SWT.DEFAULT).y / settlementList.getItemCount(); if (e.count == -3) { int topIndex = settlementList.getSelectionIndex(); settlementList.setSelection(++topIndex); settlementListSC.setOrigin(settlementListSC.getOrigin().x, settlementListSC.getOrigin().y + listItemHeight); } else if (e.count == 3) { int topIndex = settlementList.getSelectionIndex(); settlementList.setSelection(--topIndex); settlementListSC.setOrigin(settlementListSC.getOrigin().x, settlementListSC.getOrigin().y - listItemHeight); } } }); neighbourListSC.setContent(neighbourList); neighbourListSC.setExpandHorizontal(true); neighbourListSC.setExpandVertical(true); neighbourList.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { int listItemHeight = neighbourList.computeSize(SWT.DEFAULT, SWT.DEFAULT).y / neighbourList.getItemCount(); if (e.count == -3) { int topIndex = neighbourList.getSelectionIndex(); neighbourList.setSelection(++topIndex); neighbourListSC.setOrigin(neighbourListSC.getOrigin().x, neighbourListSC.getOrigin().y + listItemHeight); } else if (e.count == 3) { int topIndex = neighbourList.getSelectionIndex(); neighbourList.setSelection(--topIndex); neighbourListSC.setOrigin(neighbourListSC.getOrigin().x, neighbourListSC.getOrigin().y - listItemHeight); } } }); excludedNeighbourListSC.setContent(excludedNeighbourList); excludedNeighbourListSC.setExpandHorizontal(true); excludedNeighbourListSC.setExpandVertical(true); excludedNeighbourList.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { int listItemHeight = excludedNeighbourList.computeSize( SWT.DEFAULT, SWT.DEFAULT).y / excludedNeighbourList.getItemCount(); if (e.count == -3) { int topIndex = excludedNeighbourList.getSelectionIndex(); excludedNeighbourList.setSelection(++topIndex); excludedNeighbourListSC.setOrigin( excludedNeighbourListSC.getOrigin().x, excludedNeighbourListSC.getOrigin().y + listItemHeight); } else if (e.count == 3) { int topIndex = excludedNeighbourList.getSelectionIndex(); excludedNeighbourList.setSelection(--topIndex); excludedNeighbourListSC.setOrigin( excludedNeighbourListSC.getOrigin().x, excludedNeighbourListSC.getOrigin().y - listItemHeight); } } }); }
8
@Override public boolean onKeyUp(int key) { Iterator<IScreenItem> it = screenItems.iterator(); while(it.hasNext()) { IScreenItem item = it.next(); if(item.onKeyUp(key)) { return true; } } return false; }
2
static protected Location parseLocationLine(String line) { if(log.isDebugEnabled()) log.debug("parseLocationLine:" + line); String latitude, longitude; int latitudeSign = 1, longitudeSign = 1; if(log.isDebugEnabled()) log.debug("line:" + line); latitude = line.replaceAll("^.*LATITUDE ", ""); latitude = line.replaceAll("^[.][.][.].*", ""); if(latitude.matches(".*SOUTH.*")) latitudeSign = -1; latitude = line.replaceAll(".*SOUTH.*", ""); latitude = line.replaceAll(".*NORTH.*", ""); longitude = line.replaceAll("^.*LONGITUDE ", ""); longitude = longitude.replaceAll("^.*OR ABOUT.*", ""); if(longitude.matches(".*WEST.*")) longitudeSign = -1; latitude = line.replaceAll(".*WEST.*", ""); latitude = line.replaceAll(".*EAST.*", ""); return new Location(latitude, longitude, latitudeSign, longitudeSign); }
4
@Test public void testLoadMemory() { Data[] testArray = new Data[2]; testArray[0] = testInstr; Instruction testInstr2 = new BranchInstr(Opcode.BRZ, 5); testArray[1] = testInstr2; memory.loadMemory(testArray); for (int i = 0; i < 2; i++) { assertEquals(testArray[i], memory.accessAddress(i)); } }
1
public void reserveSmallConstants(GrowableConstantPool gcp) { for (int i = 0; i < fields.length; i++) fields[i].reserveSmallConstants(gcp); for (int i = 0; i < methods.length; i++) methods[i].reserveSmallConstants(gcp); }
2
@Override public int fight() { return super.fight(); }
0
@Override public void Consultar() throws SQLException { try { Conexion.GetInstancia().Conectar(); ResultSet rs = Conexion.GetInstancia().EjecutarConsulta("SELECT Nom_Cliente,Dir_Cliente,Tel_Cliente,Ape_Cliente ,Email_Cliente,Tip_Cliente,SalPen_Cliente FROM Cliente WHERE CedRuc_Cliente ='"+ObCliente.getCedRuc_Persona()+"'"); while(rs.next()) { ObCliente.setNom_Persona(rs.getString("Nom_Cliente")); ObCliente.setDir_Persona(rs.getString("Dir_Cliente")); ObCliente.setTel_Persona(rs.getString("Tel_Cliente")); ObCliente.setApe_Persona(rs.getString("Ape_Cliente")); ObCliente.setEmail_Persona(rs.getString("Email_Cliente")); ObCliente.setTip_Cliente(rs.getString("Tip_Cliente")); ObCliente.setSalPen_Cliente(rs.getDouble("SalPen_Cliente")); } } catch(SQLException ex) { throw ex; } finally { Conexion.GetInstancia().Desconectar(); } }
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 ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Frm_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Frm_Principal(); } }); //Listener que capitura o evento "minimizar" }
6
public void testRowCount() { DataSet ds = null; try { final DelimitedColumnNamesInFile testDelimted = new DelimitedColumnNamesInFile(); ds = testDelimted.getDsForTest(); // check that we parsed in the right amount of rows assertEquals(6, ds.getRowCount()); } catch (final Exception ex) { ex.printStackTrace(); } finally { } }
1
public static ArrayList<History> showHistory() { ArrayList<History> histories = new ArrayList<History>(); Database db = dbconnect(); try { db.prepare("SELECT * FROM ticket_history ORDER BY changed_on desc"); ResultSet rs = db.executeQuery(); while(rs.next()) { histories.add(HistoryObject(rs)); } db.close(); } catch (SQLException e) { Error_Frame.Error(e.toString()); } return histories; }
2
private Color stripColor(ColorRGB colorInfo) { colorInfo.setR(colorInfo.getR() < 0 ? 0 : colorInfo.getR() > 1 ? 1 : colorInfo.getR()); colorInfo.setG(colorInfo.getG() < 0 ? 0 : colorInfo.getG() > 1 ? 1 : colorInfo.getG()); colorInfo.setB(colorInfo.getB() < 0 ? 0 : colorInfo.getB() > 1 ? 1 : colorInfo.getB()); return new Color((int) (colorInfo.getR() * 255), (int) (colorInfo.getG() * 255), (int) (colorInfo.getB() * 255)); }
6
@DBCommand public boolean delete(CommandSender sender, Iterator<String> args) { if(!sender.hasPermission("db.delete")) { sender.sendMessage(RED + "You don't have permission to use this command!"); return true; } if(!args.hasNext()) { sender.sendMessage("Not enough parameters!"); return true; } mm.removeMinigame(mm.getMinigame(args.next())); return true; }
2
public void event() { }
0
public static void validateNumericType(Number number) { if (!(number instanceof Integer) && !(number instanceof Double) && !(number instanceof Long)) { throw new RuntimeException("Unsupported Number type: " + number.getClass().toString()); } }
3
@Override public void update(Observable arg0, Object arg1) { //arg1 ist der name (String) des Spielers der den schauen Befehl ausgeführt hat. if(arg1 == null) try { sendeAenderungenAnAlle(); } catch(RemoteException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } else { String name = ((String[]) arg1)[0]; String richtung = ((String[]) arg1)[1]; try { _connectedClients.get(name).zeigeVorschau( _spiel.packeVorschauPaket(name, richtung)); } catch(RemoteException e) { e.printStackTrace(); } } }
3
@Override public void keyPressed(KeyEvent e) { // this.editor.textPane.setText(""); // this.editor.textPane.setText(""+e.getKeyCode()); if(e.getKeyCode() == 17) this.editor.strgPressed = true; else if(this.editor.strgPressed && e.getKeyCode() == 120) this.editor.textPane.setText(FileHandling.openFromFile()); else if(this.editor.strgPressed && e.getKeyCode() == 121) FileHandling.saveToFile(this.editor.textPane.getText()); else if(this.editor.strgPressed && e.getKeyCode() == 122) this.editor.textPane.setText(Crypter.encrypt(this.editor.textPane.getText())); else if(this.editor.strgPressed && e.getKeyCode() == 123) this.editor.textPane.setText(Crypter.decrypt(this.editor.textPane.getText())); }
9
private Message collectMessageFromR(int r) { while (true) { if (isSuspect(r)) { // r is been suspected, no need to block any further return null; } // try to receive the message synchronized (valMessages) { if(valMessages.containsKey(r)){ return valMessages.get(r); } } try { Thread.sleep(100L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4
private void resetLabels() { for (JLabel label : labels) { //label.setBorder(BorderFactory.createLineBorder(Color.white)); label.setFont(new java.awt.Font("Tahoma", 0, FONT_SIZE)); label.setMaximumSize(LABEL_SIZE); label.setMinimumSize(LABEL_SIZE); label.setPreferredSize(LABEL_SIZE); } }
1
public void adjustWater() { for(Molecule mole : getMolecules()) if(mole instanceof Water) mole.setScale(((temp-250)/200.0)*20.0+1); }
2
@Override public void execute(Game game, HashMap<String, String> strings, Entity target) throws ScriptException { if (game.getPlayer().menuOpen) { System.out.println("What?"); } else { PokedexPage p = PokedexPage.newMenu(game, game.getWorld(), Pokemon.getPokemon(parseString(args[0], strings))); game.getPlayer().menuOpen = true; synchronized (p) { try { p.wait(); } catch (InterruptedException e) {} } game.getPlayer().menuOpen = false; } }
2
public void startWithComputer() { System.out.println(WELCOME_MESSAGE); gameField.showField(); int maxMoves = (int)Math.pow(gameField.getFieldSize(),2) + 1; while(!gameField.checkWin() && move != maxMoves) { if (move % 2 != 0) { int x = requestX(); int y = requestY(); if (gameField.isFill(x, y)) { System.out.println(CELL_IS_FILLED_MESSAGE); gameField.showField(); continue; } gameField.putX(x,y); makeMove(); } else { if (checkVerticalWin(1)) { finishVerticalLine(criticalVertical,2); makeMove(); continue; } if (checkHorizontalWin(1)) { finishHorizontalLine(criticalHorizontal,2); makeMove(); continue; } if(checkLeftDiagonalWin(1)) { finishLeftDiagonal(2); makeMove(); continue; } if(checkRightDiagonalWin(1)) { finishRightDiagonal(2); makeMove(); continue; } else { notCriticalMove(); makeMove(); } } } if (gameField.checkWin()) { showWinner(); } else { System.out.println(DRAW_MESSAGE); } }
9
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { if (root == null) return res; Stack<Integer> stk = new Stack<Integer>(); stk.push(root.val); pathSumRec(root, sum, stk); return res; }
1
public void setDestination(Teleporter destination) { if (destination == null || destination == this) throw new IllegalArgumentException("The given Teleporter is invalid!"); if (this.destination != null) throw new IllegalStateException("Destination is already set!"); this.destination = destination; }
3
@Override public void updateRecord() { comps = null; byte[] first = firstPtg.getRecord(); byte[] last = lastPtg.getRecord(); // KSC: this apparently is what excel wants: if( wholeRow ) { first[5] = 0; } if( wholeCol ) { first[3] = 0; first[4] = 0; } // the last record has an extra identifier on it. byte[] newrecord = new byte[PTG_AREA3D_LENGTH]; newrecord[0] = 0x3B; System.arraycopy( first, 1, newrecord, 1, 2 ); System.arraycopy( first, 3, newrecord, 3, 2 ); System.arraycopy( last, 3, newrecord, 5, 2 ); System.arraycopy( first, 5, newrecord, 7, 2 ); System.arraycopy( last, 5, newrecord, 9, 2 ); record = newrecord; if( parent_rec != null ) { if( parent_rec instanceof Formula ) { ((Formula) parent_rec).updateRecord(); } else if( parent_rec instanceof Name ) { ((Name) parent_rec).updatePtgs(); } } }
5
private boolean jj_3R_49() { if (jj_3R_61()) return true; return false; }
1
@Override public void actionPerformed(ActionEvent e) { OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(); OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode()); if (textArea == null) { return; } Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) { ToggleMoveableAction.toggleMoveableAndClearText(node, tree, layout); } else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) { ToggleMoveableAction.toggleMoveableAndClear(node, tree, layout); } }
3
public void draw(Graphics g) { switch (gamestate) { case 0: menu.draw(g); break; case 1: world.draw(g); break; default: break; } g.drawImage(cursor, Keyboard.getMouseX() - 8, Keyboard.getMouseY() - 8, null); }
2
public static Matrix multiply(Matrix matrixA, Matrix matrixB) throws IllegalSizesException, MatrixIndexOutOfBoundsException, IncorrectFormatOfData { Matrix matrixC = null; int rowsA = matrixA.getRowsCount(); int colsA = matrixA.getColsCount(); int rowsB = matrixB.getRowsCount(); int colsB = matrixB.getColsCount(); System.out.println("Multiplication of matrixes A" + rowsA + "x" + colsA + " and B" + rowsB + "x" + colsB + "."); if ((rowsA != colsB) && (colsA != rowsB)) { throw new IllegalSizesException("Illegal matrix dimensions."); } dataTypeA = matrixA.getDataType(); dataTypeB = matrixB.getDataType(); //creates the matrix analising data type of matrixes A and B if (dataTypeA.equals(dataTypeB)) { matrixC = MatrixSelector.getMatrix(rowsA, colsB, DataType.getDataType(dataTypeA)); //throw new IncorrectFormatOfData("Data of matrixes are not identical."); } else { matrixC = MatrixSelector.getMatrix(rowsA, colsB, DataType.DOUBLE); } System.out.println("Type of data is " + dataTypeA + "."); matrixC = MatrixSelector.getMatrix(rowsA, colsB, DataType.getDataType(dataTypeA)); //temporary variable double temp = 0; //It is one-tenth of the number of rows of the matrix int stepProgress = rowsA / 10; //run time long startTime = System.currentTimeMillis(); for (int i = 0; i < rowsA; i++) { if ((rowsA >= 1000) && (i % stepProgress == 0)) { //Multiplication progress System.out.println("Multiplication progress " + i / stepProgress * 10 + "%."); } for (int j = 0; j < colsB; j++) { for (int k = 0; k < colsA; k++) { temp += matrixA.getValue(i, k) * matrixB.getValue(k, j); } matrixC.setValue(i, j, temp); temp = 0; } } //run time long endTime = System.currentTimeMillis(); long time = endTime - startTime; System.out.println("Multiplication of matrixes lasted " + time + " ms."); return matrixC; }
8
private int readBytes(byte[] b, int offs, int len) throws BitstreamException { int totalBytesRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { break; } totalBytesRead += bytesread; offs += bytesread; len -= bytesread; } } catch (IOException ex) { throw newBitstreamException(STREAM_ERROR, ex); } return totalBytesRead; }
3
public Color getColorForDisk(int num) { try { byte[] bytesOfMessage = String.valueOf(num).getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] d = md.digest(bytesOfMessage); return new Color((int)d[0] + 128, (int)d[1] + 128, (int)d[2] + 128); } catch (Exception ex) { return null; } }
1
public String getPrecisionAff() { // On renvoie des mots compréhensibles (en fonction des infos données sur le site officiel) switch (this.precision) { case "3": return "Très bonne"; case "2": return "Bonne"; case "1": return "Convenable"; case "0": return "Moyenne"; case "A": return "Potable"; case "B": return "Médiocre"; default: return "-"; } }
6
private void showP(File file) { try { p = DataIO.properties(new FileReader(file), "Parameter"); List<String> dims = DataIO.keysByMeta(p, "role", "dimension"); List<String> dims2d = DataIO.keysForBounds(p, 2); dimCombo.removeAllItems(); dimCombo.addItem("---- GENERAL ----"); dimCombo.addItem(" <ALL>"); dimCombo.addItem(" <SCALARS>"); dimCombo.addItem("------ DIMS -----"); for (String s : dims) { dimCombo.addItem(" " + s); } dimCombo.addItem("------- 2D -------"); for (String s : dims2d) { dimCombo.addItem(" " + s); } dimCombo.setSelectedIndex(1); } catch (IOException ex) { ex.printStackTrace(); } }
3
public static JSONObject toJSONObject(String string) throws JSONException { String n; JSONObject o = new JSONObject(); Object v; JSONTokener x = new JSONTokener(string); o.put("name", x.nextTo('=')); x.next('='); o.put("value", x.nextTo(';')); x.next(); while (x.more()) { n = unescape(x.nextTo("=;")); if (x.next() != '=') { if (n.equals("secure")) { v = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { v = unescape(x.nextTo(';')); x.next(); } o.put(n, v); } return o; }
3
public void setThirdCorner(Rectangle thirdCorner) { this.thirdCorner = thirdCorner; }
0
public void testToStandardMinutes_overflow() { Duration test = new Duration(((long) Integer.MAX_VALUE) * 60000L + 60000L); try { test.toStandardMinutes(); fail(); } catch (ArithmeticException ex) { // expected } }
1
@Deprecated public static void loadLevel(String title, GameContainer gc) throws SlickException { nodes = new ArrayList<Node>(); wires = new ArrayList<Wire>(); Scanner scan = new Scanner(Level.class.getClassLoader().getResourceAsStream("levels.dat")); // find header for level String next; do { next = scan.next(); } while (!next.equalsIgnoreCase(title)); // find "nodes" header scan.next(); // parse nodes while (scan.hasNextInt()) { if (scan.nextInt() != nodes.size()) { scan.close(); throw new IllegalArgumentException(); } nodes.add(Node.createNode(scan.nextFloat(), scan.nextFloat(), X_SIZE, Y_SIZE, gc)); } System.out.println(gc.getWidth() + " " + gc.getHeight()); for (Node node : nodes) System.out.println(node.getCenterX() + " " + node.getCenterY()); // skip "connections" header scan.next(); while (scan.hasNextInt()) { // read in values from next line String[] values = scan.nextLine().split(" "); // create wires from values for (int i = 1; i < values.length; i++) wires.add(new Wire(nodes.get(Integer.parseInt(values[0])), nodes.get(Integer.parseInt(values[i])))); } // close scan scan.close(); }
6
public Stack() {}
0
@Override public void run(){ Random random = new Random(); driveTime = 0; startTime = System.currentTimeMillis(); for(int i = 0; i < laps; i++){ int lapTime = random.nextInt(100); driveTime += lapTime; try { Thread.sleep(lapTime); } catch (InterruptedException e) { interrupt(); crashed = true; } } if(this.isInterrupted()){ System.out.println("CRASH!"); } endTime = System.currentTimeMillis(); totalTime = endTime - startTime; }
3
public void getAlternateLabel(StringBuffer s) throws Exception { //StringBuffer s = new StringBuffer(); FastVector tmp = (FastVector)m_ranges.elementAt(0); if (m_classObject != null && m_training.classAttribute().isNominal()) { s.append("Classified by " + m_classObject.getClass().getName()); } else if (((Double)tmp.elementAt(0)).intValue() == LEAF) { if (m_training.classAttribute().isNominal()) { double high = -1000; int num = 0; double count = 0; for (int noa = 0; noa < m_training.classAttribute().numValues(); noa++) { if (((Double)tmp.elementAt(noa + 1)).doubleValue() > high) { high = ((Double)tmp.elementAt(noa + 1)).doubleValue(); num = noa + 1; } count += ((Double)tmp.elementAt(noa + 1)).doubleValue(); } s.append(m_training.classAttribute().value(num-1) + "(" + count); if (count > high) { s.append("/" + (count - high)); } s.append(")"); } else { if (m_classObject == null && ((Double)tmp.elementAt(0)).intValue() == LEAF) { setLinear(); } s.append("Standard Deviation = " + Utils.doubleToString(((Double)tmp.elementAt(1)) .doubleValue(), 6)); } } else { s.append("Split on "); s.append(m_training.attribute(m_attrib1).name() + " AND "); s.append(m_training.attribute(m_attrib2).name()); } //return s.toString(); }
9
@Override public Result findSimilarTo(Signal signal) throws RemoteException { boolean finished = false; while (!finished) { waitForBalacing.acquireAndRelease(); receivedSignals.incrementAndGet(); if (channel.isConnected()) { List<Future<Result>> futureResults = new ArrayList<>(); List<Result> results = new LinkedList<>(); for (final Address address : channel.getView().getMembers()) { futureResults.add(dispatcher.<Result>send(address, new MyMessage<Signal>(signal, Operation.QUERY))); } for (final Future<Result> future : futureResults) { try { results.add(future.get()); } catch (DegradedModeException e) { // RETRY System.out.println("findSimilar: node down! Retrying..."); continue; } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } Result result = results.remove(0); for (Result res: results) { Iterable<Item> items = res.items(); for (Item item: items) { result = result.include(item); } } return result; } else { return worker.process(signal); } } return null; }
8
public SynthesisFilter(int channelnumber, float factor, float[] eq0) { if (d==null) { d = load_d(); d16 = splitArray(d, 16); } v1 = new float[512]; v2 = new float[512]; samples = new float[32]; channel = channelnumber; scalefactor = factor; setEQ(eq); //setQuality(HIGH_QUALITY); reset(); }
1
public void update() { up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W]; down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S]; left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A]; right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D]; if (up) direction = 0; else if (right) direction = 1; else if (down) direction = 2; else if (left) direction = 3; else direction = -1; }
8
public String request(String method, String path, Response data, Map<String, String> options) { HttpURLConnection connection = null; String answer = null; try { StringBuffer sb = new StringBuffer(); sb.append("?api_key=" + apiKey); if(method.equals("GET")) { sb.append(prepareGet(data)); } URL url = new URL(apiUri + path + sb.toString()); connection = createConnection(url, method, options); if(method.equals("POST") || method.equals("PUT")) { writeXml(connection, data); } status = connection.getResponseCode(); answer = getResponse(connection); } catch(SSLHandshakeException e) { System.err.println("SSL verification is failing. This might be because of an attack. Contact support@authy.com"); } catch(Exception e) { e.printStackTrace(); } return answer; }
5
private FloatingPoint getOperatorValue(TokenOperator token, FloatingPoint[] values) { FloatingPoint floatingPoint = null; // TODO Implement new way to caculate floating point number without // using Float String original = token.getOriginal(); float value = 0.0f; if (original.equals("*")) { value = getFloatNumber(values[0]) * getFloatNumber(values[1]); } else if (original.equals("/")) { if (values[1].getValue() != 0) { value = getFloatNumber(values[0]) / getFloatNumber(values[1]); } } else if (original.equals("+")) { value = getFloatNumber(values[0]) + getFloatNumber(values[1]); } else if (original.equals("-")) { value = getFloatNumber(values[0]) - getFloatNumber(values[1]); } floatingPoint = getFloatingPoint(value); return floatingPoint; }
5
protected void setHandler(Handler handler){ if (handler==null) this.handler=new DefaultHandler(); else this.handler=handler; }
1
public static ArrayList<String> getVoteSummary(Proposal proposal) { // Create an index of options -> numVotes Map<Integer, Integer> voteCount = new HashMap<Integer, Integer>(); VoteModel voteModel = new VoteModel(); for (Integer i : proposal.getVotes()) { Vote vote = (Vote) voteModel.get(i); if (voteCount.containsKey(vote.getOptionID())) { Integer num = voteCount.get(vote.getOptionID()); voteCount.put(vote.getOptionID(), new Integer(++num)); } else { voteCount.put(vote.getOptionID(), new Integer(1)); } } ArrayList<String> results = new ArrayList<String>(); // Loop through the index and find which key has the highest value for (Integer option : voteCount.keySet()) { results.add(proposal.getOptions().get(option) + " had " + voteCount.get(option) + " votes"); } return results; }
3
public CheckResultMessage checkL1(int day) { return checkReport.checkL1(day); }
0
private static int converterComando(String cmd) throws Exception { cmd = cmd.toLowerCase(); if (cmd.equals("mover")) return 1; if (cmd.equals("olhar")) return 2; if (cmd.equals("atacar")) return 3; if (cmd.equals("largar")) return 4; if (cmd.equals("pegar")) return 5; throw new Exception("Comando " + cmd + " nao e valido"); }
5
private static Box initialize() { Box[] nodes = new Box[7]; nodes[1] = new Box(1); int[] s = {1, 4, 7}; for (int i = 0; i < 3; ++i) { nodes[2] = new Box(21 + i); nodes[1].add(nodes[2]); int lev = 3; for (int j = 0; j < 4; ++j) { nodes[lev - 1].add(new Product(lev * 10 + s[i])); nodes[lev] = new Box(lev * 10 + s[i] + 1); nodes[lev - 1].add(nodes[lev]); nodes[lev - 1].add(new Product(lev * 10 + s[i] + 2)); lev++; } } return nodes[1]; }
2
public ByteBuffer readBuf() { ByteBuffer buf = readBuf; buf.flip(); buf.position(readPos); if (buf.remaining() == 0) { if (bufs.isEmpty()) { // There's nothing to read, so we won't return this buffer. // We can clear it just in case... readBuf.clear(); readPos = 0; return null; } else { buf = bufs.remove(); } } if (bufs.isEmpty()) { writeBuf = readBuf = ByteBuffer.allocate(BUF_LEN); } else { readBuf = bufs.remove(); } readPos = 0; length -= buf.remaining(); return buf; }
3
public void advice(String msg) { System.out.println("Called ..." + LoggerUtils.getSig() + "; msg:" + msg); }
0
public void mouseDown(MouseEvent e) { if(e.getButton() == e.BUTTON1) { for(UIContent content : Contents) { content.contentMouseDown(e); } } }
2
@Override public Value run(CodeBlock b) throws InterpreterException { if (args_ != null || getArgsNumber()==0) { Value[] vals = new Value[getArgsNumber()]; for (int i = 0; i < vals.length; i++) { vals[i] = args_[i].run(b); } try { Value v = function_.evaluate(vals); return v; } catch (Exception e) { throw new InterpreterException(e.getMessage(), getLine()); } } return new Value(); }
4
protected String processTmplFile(File inFolder, File file) throws IOException { final String template = FileUtils.readFileToString(file); Map<String, String> parameters = new HashMap<>(); Map<String, String> dependencies = listReferencedFiles(template); Map<String, String> imagesDependencies = listImages(template, inFolder); for (String key : globals.stringPropertyNames()) { parameters.put(key, globals.getProperty(key)); } for (String dep : dependencies.keySet()) { if (!fileMap.containsKey(dep)) { File tmplFile = new File(inFolder.getAbsolutePath() + File.separator + dep); String result = processTmplFile(inFolder, tmplFile); FileInfo fileInfo = new FileInfo(result); fileMap.put(dep, fileInfo); } parameters.put(dependencies.get(dep), fileMap.get(dep).getText()); } for (String iDep : imagesDependencies.keySet()) { parameters.put(iDep, imagesDependencies.get(iDep)); } String result = null; Engine engine = Engine.getEngine(); try { Template template1 = engine.parseTemplate(template); result = (String) template1.evaluate(parameters); } catch (ParseException ex) { java.util.logging.Logger.getLogger(FilesystemWalker.class.getName()).log(Level.SEVERE, null, ex); } return result; }
5
protected void createDdlProcedure(Connection connection2) { BufferedReader br = null; try { StringBuilder sql = new StringBuilder(); FileReader fr = new FileReader("rev_tbl.sql"); br = new BufferedReader(fr); String line = null; Statement statement = connection.createStatement(); while ((line = br.readLine()) != null) { if (line.trim().equalsIgnoreCase("go")) { statement.execute(sql.toString()); sql.setLength(0); } else { sql.append(line).append("\n"); } } if (sql.length() > 0) { statement.execute(sql.toString()); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
8
public void convertToSlopeIntersect(){ if (_y == 0){ if (_x != 1){ _c /= _x; _x = 1; } } else if (_y != 1){ _x /= _y; _c /= _y; _y = 1; } }
3
public void randomPrefabFromFile(int x, int y) throws IOException{ String path = "data/houses.pfl"; FileInputStream in = new FileInputStream(path); Random rand = new Random(System.currentTimeMillis()); int cPrefabs = in.read(); long skip = rand.nextInt(cPrefabs); skip = (skip * 24 * 24) + (skip * 2); in.skip(skip); width = in.read(); height = in.read(); for (int i = 0; i < width; i++){ for (int j = 0; j < height; j++){ Boot.getWorldObj().getTileAtCoords(x + i, y + j).setTileID(in.read()); } } in.close(); }
2
void updateAnsSet(String s, int a, int b) { for (int i = 0; i < checkSet.length; i++) { if (!checkSet[i]) { continue; } if ((getA(s, answerSet[i]) != a) || (getB(s, answerSet[i]) != b)) { checkSet[i] = false; } } }
4
public static String getIpAddr() { HttpServletRequest request = BaseAction.getHttpServletRequest(); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }
9
public static void OPNB_ADPCM_CALC_CHA( YM2610 F2610, ADPCM_CH ch ) { int/*UINT32*/ step; int data; ch.now_step += ch.step; if ( ch.now_step >= (1<<ADPCM_SHIFT) ) { step = ch.now_step >> ADPCM_SHIFT; ch.now_step &= (1<<ADPCM_SHIFT)-1; /* end check */ if ( (ch.now_addr+step) > (ch.end<<1) ) { ch.flag = 0; F2610.adpcm_arrivedEndAddress |= ch.flagMask; return; } do{ if( (ch.now_addr&1)!=0 ) data = ch.now_data & 0x0f; else { ch.now_data = pcmbufA.read(ch.now_addr>>1);//*(pcmbufA+(ch.now_addr>>1)); data = (ch.now_data >> 4)&0x0f; } ch.now_addr++; ch.adpcmx += jedi_table[ch.adpcmd+data]; //Limit( ch.adpcmx,ADPCMA_DECODE_MAX, ADPCMA_DECODE_MIN ); if ( ch.adpcmx > ADPCMA_DECODE_MAX ) ch.adpcmx = ADPCMA_DECODE_MAX; else if ( ch.adpcmx < ADPCMA_DECODE_MIN ) ch.adpcmx = ADPCMA_DECODE_MIN; ch.adpcmd += decode_tableA1[data]; //Limit( ch.adpcmd, 48*16, 0*16 ); if ( ch.adpcmd > 48*16 ) ch.adpcmd = 48*16; else if ( ch.adpcmd < 0*16 ) ch.adpcmd = 0*16; /**** calc pcm * volume data ****/ ch.adpcml = ch.adpcmx * ch.volume; }while(--step!=0); } /* output for work of output channels (out_ch[OPNxxxx])*/ //*(ch.pan) += ch.adpcml; ch.pan.write(ch.pan.read()+ ch.adpcml); }
8
public String getItemTypeName() { String n = ""; if(itemType != null) { n = itemType.getName(); } return n; }
1
public static java.util.List<Puntaje> leer(int numerDeDiscosDeseado, boolean porMovimientos) { BufferedReader br = null; FileReader fileWriter = null; File file; java.util.List<Puntaje> puntuaciones = new LinkedList<Puntaje>(); try { file = new File(RUTA); fileWriter = new FileReader(file); br = new BufferedReader(fileWriter); String nombre; while ((nombre = br.readLine()) != null) { int movimientos = Integer.parseInt(br.readLine()); long tiempo = Long.parseLong(br.readLine()); int numeroDeDiscos = Integer.parseInt(br.readLine()); if (numeroDeDiscos == numerDeDiscosDeseado) { puntuaciones.add(new Puntaje(nombre, movimientos, tiempo, numeroDeDiscos, porMovimientos)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { } try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException ex) { } } return puntuaciones; }
7
public static void saltar() { file = new File("."); ruta = file.getAbsolutePath(); Thread hilo = new Thread() { @Override public void run() { try { Thread.sleep(1); FileInputStream fis; Player player; try{ fis = new FileInputStream(ruta + "/src/sounds/saltar.mp3"); }catch (FileNotFoundException e){ fis = new FileInputStream(ruta + "/complementos/saltar.mp3"); } BufferedInputStream bis = new BufferedInputStream(fis); player = new Player(bis); player.play(); stop(); } catch (InterruptedException | JavaLayerException | FileNotFoundException e) { System.out.println(" error " + e); } } }; hilo.start(); }
2
private static ArrayList<Score> createScores(String scores) { if(scores == null) { return null; } ArrayList<Score> list = new ArrayList<Score>(); String[] scoreList = scores.split(";"); for(String s : scoreList) { String[] s2 = s.split(":"); Score score = new Score(s2[0], s2[1]); list.add(score); } return list; }
2
public static void main(String[] args) { final String path = "C:\\Users\\Ferium\\Documents\\NetBeansProjects\\Netlife\\src\\Files\\sample.txt"; // Checks boolean tests from the Units class boolean test1 = Units.CheckGetCommandList(path); System.out.println("Test 1: " + test1); boolean test2 = Units.CheckisCatalog(path); System.out.println("Test 2: " + test2); boolean test3 = Units.CheckGetFileName(); System.out.println("Test 3: " + test3); boolean test4 = Units.CheckIsMove(); System.out.println("Test 4: " + test4); //Not all methods are tested if(test1 && test2 && test3 && test4){ System.out.println("All tests have passed"); } else{ System.out.println("One or more tests have failed"); } }
4
public FileAttribute getFileAttribute(String lfn) { // check first int rcID = getReplicaCatalogueID(); if (rcID == -1 || lfn == null) { return null; } int eventTag = DataGridTags.CTLG_GET_FILE_ATTR; FileAttribute fAttr = null; // sends a request to this RC sendEvent(eventTag, lfn, rcID); // waiting for a response from the RC Sim_type_p tag = new Sim_type_p(DataGridTags.CTLG_FILE_ATTR_DELIVERY); // only look for this type of ack Sim_event ev = new Sim_event(); super.sim_get_next(tag, ev); try { fAttr = (FileAttribute) ev.get_data(); } catch (Exception e) { fAttr = null; System.out.println(super.get_name() + ".getFileAttribute(): Exception"); } return fAttr; }
3
public static void main(String[] args) { // Create Display try { Display.setDisplayMode (new DisplayMode(800, 600)); Display.create (); Display.setTitle("Hello!!"); } catch (LWJGLException ex) { Logger.getLogger(LWJGL_Example2.class.getName()).log(Level.SEVERE, null, ex); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640, 480, 0, 1, -1); glMatrixMode(GL_MODELVIEW); // Game Loop while (!Display.isCloseRequested()) { if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { Display.destroy(); System.exit(0); } else if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { System.out.println ("up!"); } else if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { System.out.println ("left!"); } else if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { System.out.println ("right!"); } else if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { System.out.println ("down!"); } Display.update(); Display.sync(60); } Display.destroy(); }
7
protected final Archive createArchive() throws Exception { ProtectionDomain protectionDomain = getClass().getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); URI location = (codeSource == null ? null : codeSource.getLocation().toURI()); String path = (location == null ? null : location.getSchemeSpecificPart()); if (path == null) { throw new IllegalStateException("Unable to determine code source archive"); } File root = new File(path); if (!root.exists()) { throw new IllegalStateException( "Unable to determine code source archive from " + root); } return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); }
5
@Test public void findHandFromCardSet_whenThreePairsExist_returnsHighestTwoPair() { Hand hand = findHandFromCardSet(twoKingsTwoQueensTwoJacksSix()); assertEquals(HandRank.TwoPair, hand.handRank); assertEquals(Rank.King, hand.ranks.get(0)); assertEquals(Rank.Queen, hand.ranks.get(1)); assertEquals(Rank.Jack, hand.ranks.get(2)); }
0
private static TileFlip extractFlipRaw(long item) { long t = item; if (isSet(t, true, true, true )) return TileFlip.HVD; else if (isSet(t, true, true, false )) return TileFlip.HV; else if (isSet(t, true, false, true )) return TileFlip.HD; else if (isSet(t, true, false, false )) return TileFlip.H; else if (isSet(t, false, true, true )) return TileFlip.VD; else if (isSet(t, false, true, false)) return TileFlip.V; else if (isSet(t, false, false, true )) return TileFlip.D; else return TileFlip.NONE; }
7
@Override @Execute public void postLogic(IChassis chassis) { if(!GL11.glGetBoolean(GL11.GL_TEXTURE_2D)) GL11.glDisable(GL11.GL_TEXTURE_2D); if(this.camera != null) this.camera.applyMatrices(); Iterator<GUIElement> it = this.guiElements.values().iterator(); while(it.hasNext()) { GUIElement element = it.next(); if(element.isActive()) element.postLogic(chassis); } }
4
public Map<Integer, Integer> rand() { int[] tem = new int[MAX]; boolean b; for (int key = 0; key < MAX; key++) { b = true; int element = (int) (Math.random() * MAX + ONE); for (int t = 0; t < MAX; t++) { if (element == tem[t] && key > 0) { key = key - 1; b = false; } } if (b) { this.getRamdomListe().put(key, element); tem[key] = element; } } return getRamdomListe(); }
5
private void jButtonOpretKundeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpretKundeActionPerformed String fornavn = jTextFieldFornavn.getText(); String efternavn = jTextFieldEfternavn.getText(); String navn = fornavn + " " + efternavn; String adresse = jTextFieldAdresse.getText(); String postnr = jTextFieldPostnr.getText(); String by = jTextFieldBy.getText(); String email = jTextFieldEmail.getText(); String nr = jTextFieldNr.getText(); if (navn.contains(" ") && !adresse.equals("") && postnr.length() == 4 && !by.equals("") && email.contains("@") && nr.length() == 8) { control.createCustomer(navn, adresse, postnr, by, email, nr); control.saveCustomer(); jTextFieldFornavn.setText(""); jTextFieldEfternavn.setText(""); jTextFieldAdresse.setText(""); jTextFieldPostnr.setText(""); jTextFieldBy.setText(""); jTextFieldEmail.setText(""); jTextFieldNr.setText(""); } else { JOptionPane.showMessageDialog(null, "Udfyld alle felter"); } }//GEN-LAST:event_jButtonOpretKundeActionPerformed
6
final int method2571(int i, int i_48_, int[] is, String string, int i_49_, int i_50_, RasterToolkit[] class105s, int i_51_, int i_52_, Random random) { try { anInt4047++; if (string == null) return 0; random.setSeed((long) i_48_); int i_53_ = (random.nextInt() & 0x1f) + 192; method2579(i_53_ << 1698302424 | 0xffffff & i_50_, i ^ ~0x79, i_53_ << -2007048616 | i_49_ & 0xffffff); int i_54_ = string.length(); if (i != -1) aClass138_4062 = null; int[] is_55_ = new int[i_54_]; int i_56_ = 0; for (int i_57_ = 0; (i_57_ ^ 0xffffffff) > (i_54_ ^ 0xffffffff); i_57_++) { is_55_[i_57_] = i_56_; if ((0x3 & random.nextInt() ^ 0xffffffff) == -1) i_56_++; } method2566(class105s, null, i_52_, is, is_55_, i_51_, string, 174); return i_56_; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("da.BA(" + i + ',' + i_48_ + ',' + (is != null ? "{...}" : "null") + ',' + (string != null ? "{...}" : "null") + ',' + i_49_ + ',' + i_50_ + ',' + (class105s != null ? "{...}" : "null") + ',' + i_51_ + ',' + i_52_ + ',' + (random != null ? "{...}" : "null") + ')')); } }
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(loadingForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(loadingForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(loadingForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(loadingForm.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 loadingForm().setVisible(true); } }); }
6
@Override public void run() { double time = System.currentTimeMillis(); try { isDrawing.acquire(); } catch (InterruptedException ex) { Logger.getLogger(RedrawRoutine.class.getName()).log(Level.SEVERE, null, ex); System.exit(-1); } while (true) { try { //Make sure that if all else fails, you sleep for at least a millisecond //to let the other logic run. isDrawing.release(); Thread.sleep((long)(1)); if (time<FRAME_TIME) { Thread.sleep((long)(FRAME_TIME-time)); } //When game logic relenquishes control, move forward. isDrawing.acquire(); //Refresh the page, making sure to count how long it takes. time = System.currentTimeMillis(); refreshView(); time = System.currentTimeMillis()-time; //Display the time. Commented out, but you can see how long it takes to //render a frame by uncommenting the following line: //g2d.drawString(""+time, 10, 10); //Draw the image to the buffer. graphics = buffer.getDrawGraphics(); graphics.drawImage(bufImage, 0, 0, null); //I don't know what this is for, but it's important. I //got it from sample code online, and still need to figure out //what this code's purpose is. if(!buffer.contentsLost()) { buffer.show(); } } catch (InterruptedException ex) { Logger.getLogger(RedrawRoutine.class.getName()).log(Level.SEVERE, null, ex); } } }
5
private static String date_format(double t, int methodId) { StringBuffer result = new StringBuffer(60); double local = LocalTime(t); /* Tue Oct 31 09:41:40 GMT-0800 (PST) 2000 */ /* Tue Oct 31 2000 */ /* 09:41:40 GMT-0800 (PST) */ if (methodId != Id_toTimeString) { appendWeekDayName(result, WeekDay(local)); result.append(' '); appendMonthName(result, MonthFromTime(local)); result.append(' '); append0PaddedUint(result, DateFromTime(local), 2); result.append(' '); int year = YearFromTime(local); if (year < 0) { result.append('-'); year = -year; } append0PaddedUint(result, year, 4); if (methodId != Id_toDateString) result.append(' '); } if (methodId != Id_toDateString) { append0PaddedUint(result, HourFromTime(local), 2); result.append(':'); append0PaddedUint(result, MinFromTime(local), 2); result.append(':'); append0PaddedUint(result, SecFromTime(local), 2); // offset from GMT in minutes. The offset includes daylight // savings, if it applies. int minutes = (int) Math.floor((LocalTZA + DaylightSavingTA(t)) / msPerMinute); // map 510 minutes to 0830 hours int offset = (minutes / 60) * 100 + minutes % 60; if (offset > 0) { result.append(" GMT+"); } else { result.append(" GMT-"); offset = -offset; } append0PaddedUint(result, offset, 4); if (timeZoneFormatter == null) timeZoneFormatter = new java.text.SimpleDateFormat("zzz"); // Find an equivalent year before getting the timezone // comment. See DaylightSavingTA. if (t < 0.0 || t > 2145916800000.0) { int equiv = EquivalentYear(YearFromTime(local)); double day = MakeDay(equiv, MonthFromTime(t), DateFromTime(t)); t = MakeDate(day, TimeWithinDay(t)); } result.append(" ("); java.util.Date date = new Date((long) t); synchronized (timeZoneFormatter) { result.append(timeZoneFormatter.format(date)); } result.append(')'); } return result.toString(); }
8