text
stringlengths
14
410k
label
int32
0
9
private long[] readCPU(final Process pc) throws Exception { try { long[] returnCPUInfo = new long[2]; pc.getOutputStream().close(); InputStreamReader inputReader = new InputStreamReader(pc.getInputStream()); LineNumberReader lineNumberInput = new LineNumberReader(inputReader); String readInput = lineNumberInput.readLine(); if (readInput == null || readInput.length() < faultLength) { return null; } int captionID = readInput.indexOf("Caption"); int commandID = readInput.indexOf("CommandLine"); int readOperationCountID = readInput.indexOf("ReadOperationCount"); int userModeTimeID = readInput.indexOf("UserModeTime"); int kernelModeTimeID = readInput.indexOf("KernelModeTime"); int writeOperationCountID = readInput.indexOf("WriteOperationCount"); long idelTime = 0, kernelTime = 0, userTime = 0; while ((readInput = lineNumberInput.readLine()) != null) { if (readInput.length() < writeOperationCountID) { continue; } String caption = readInput.substring(captionID, commandID - 1).trim(); String command = readInput.substring(commandID, kernelModeTimeID - 1).trim(); if (command.indexOf("wmic.exe") >= 0) { continue; } if (caption.equals("System Idle Process") || caption.equals("System")) { idelTime += Long.valueOf(Bytes.substring(readInput, kernelModeTimeID, readOperationCountID - 1).trim()).longValue(); idelTime += Long.valueOf(Bytes.substring(readInput, userModeTimeID, writeOperationCountID - 1).trim()).longValue(); continue; } kernelTime += Long.valueOf(Bytes.substring(readInput, kernelModeTimeID, readOperationCountID - 1).trim()).longValue(); userTime += Long.valueOf(Bytes.substring(readInput, userModeTimeID, writeOperationCountID - 1).trim()).longValue(); } returnCPUInfo[0] = idelTime; returnCPUInfo[1] = kernelTime + userTime; return returnCPUInfo; } catch (Exception e) { } finally { try { pc.getInputStream().close(); } catch (Exception e) { } } return null; }
9
@Transactional public void finishById(Integer id) { tasksDao.setFinishedById(id, true); }
0
@Test public void testCheckDefeat() { GameController gc = new GameController(paddle1,paddle2,ball,view,padq1,ballq1); int radius = Ball.getSize(); //ball is not near paddle zone boolean b = gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y=300 ball.setPosition(250, 300, 0); b= gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y>300 x< 155+radius ball.setPosition(154+radius,350,0); b = gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y>300, x>445-radius ball.setPosition(446-radius,500,0); b = gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y>300 x= 155+radius ball.setPosition(155+radius,500,0); b = gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y>300, x=445-radius ball.setPosition(445-radius,500,0); b = gc.checkDefeat(); if(b) fail("Failure Trace: "); //ball y>300 x> 155+radius x < 445-radius //pad position > ball position + paddlesize + radius + 10 //should be true ball.setPosition(300,500,0); paddle1.setPosition(150,500); b = gc.checkDefeat(); if(!b) fail("Failure Trace: "); //ball y>300 x> 155+radius x < 445-radius //pad position < ball position + radius + 10 //should be true ball.setPosition(170,500,0); paddle1.setPosition(350,500); b = gc.checkDefeat(); if(!b) fail("Failure Trace: "); //ball y>300 x> 155+radius x < 445-radius // ball position + radius + 10 < pad position <ball position + paddlesize + radius + 10 //should be false ball.setPosition(250,500,0); paddle1.setPosition(250,500); b = gc.checkDefeat(); if(b) fail("Failure Trace: "); }
9
public void testAdd_DurationFieldType_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.add((DurationFieldType) null, 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); }
1
public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); }
8
public void mousePressed(MouseEvent e) { // Selects to create a handler for resizing if (!graph.isCellSelected(cell)) { graphContainer.selectCellForEvent(cell, e); } // Initiates a resize event in the handler mxCellHandler handler = graphContainer.getSelectionCellsHandler().getHandler( cell); if (handler != null) { // Starts the resize at index 7 (bottom right) handler.start(SwingUtilities.convertMouseEvent((Component) e .getSource(), e, graphContainer.getGraphControl()), index); e.consume(); } }
2
@Override public List<Editor> listAll() { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; List<Editor> editores = new ArrayList<>(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LIST); rs = pstm.executeQuery(); while (rs.next()){ Editor ed = new Editor(); ed.setId_editor(rs.getInt("id_editora")); ed.setNome(rs.getString("nome_ed")); ed.setEmail(rs.getString("email_ed")); ed.setUrl(rs.getString("url_ed")); ed.setCidade(rs.getString("cidade_ed")); ed.setEndereco(rs.getString("endereco_ed")); editores.add(ed); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar editores " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return editores; }
3
private static void sendCommand(String cmd) { boolean com = false; cmd = cmd.substring(1); if (cmd.contains(" ")) { String cmdPar[] = cmd.split(" "); for(int i = 0; i < commands.length; i++) { for(int j = 1; j < commands[i].length; j++) { if(cmdPar[0].equalsIgnoreCase(commands[i][j])) { runCommandWithPar(commands[i][0], cmdPar[1]); com = true; } } } } else { for(int i = 0; i < commands.length; i++) { for(int j = 1; j < commands[i].length; j++) { if(cmd.equalsIgnoreCase(commands[i][j])) { runCommand(commands[i][0]); com = true; } } } } if (!com) GUI.Append("No such command /" + cmd); }
8
public static Unit findHighPriorityTargetIfPossible(Collection<Unit> enemyBuildings) { for (Unit unit : enemyBuildings) { UnitType type = unit.getType(); if (type.isSporeColony() || type.isMissileTurret() || type.isBase()) { if (isProperTarget(unit)) { return unit; } } } return null; }
5
public Level() { if (!(this instanceof LevelEditor) && JOptionPane.showOptionDialog(null, "Skip tutorials?", "Tutorial", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == JOptionPane.YES_OPTION) { try { maxLives = Integer.parseInt(JOptionPane.showInputDialog(null, "How many lives? (enter a numerical value)")); } catch (Exception ex) { maxLives = 3; } lives = maxLives; currentLevel = 6; score = 1; } if (!(this instanceof LevelEditor)) { generate(currentLevel); } }
4
synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { __typeCode = pgrid.service.corba.PeerReferenceHelper.type (); __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (pgrid.service.corba.PeerArrayHelper.id (), "PeerArray", __typeCode); } return __typeCode; }
1
@Override public int compareTo(BString other) { // same object if (other == this) return 0; int p = start; int pOther = other.start; while (true) { // same length, all bytes matched if (p == end && pOther == other.end) return 0; // a bit unusual ordering here; of two strings where one is the prefix of the other, // the longest comes first if (p == end) return +1; if (pOther == other.end) return -1; int bComp = compareBytes(bytes[p], other.bytes[pOther]); if (bComp != 0) return bComp; ++p; ++pOther; } }
7
public boolean contains(T test) { if (test == null) { for (int i = 0; i < array.length; i++) if (array[i] == null) return true; } else { for (int i = 0; i < array.length; i++) if (test.equals(get(i))) return true; } return false; }
5
@Deprecated public void draw(int screenX, int screenY, int xStart, int yStart, int xStop, int yStop){ for (int x = xStart; x < xStop; x++){ for (int y = yStart; y < yStop; y++){ contents[x][y].draw(screenX + (x * Standards.TILE_SIZE), screenY + (y * Standards.TILE_SIZE)); } } }
2
private static void solve70(){ double small = 2.0; for (int i = 2000; i < 5000; i++) { for (int j = 2000; j < 5000; j++) { if (i != j && i*j < 1_000_000_0) { if (isPrime(i) && isPrime(j)) { int phi = (i - 1) * (j - 1); if (small > (double) (i * j) / phi) { if (isPermutable(i * j, phi)) { small = (double) (i * j) / phi; System.out.println("SMALL DETECTED" + "A:" + i + " B:" + j + " Value:" + (double) (i * j) / phi); // System.out.println("VAL:" + (double) (i * j) // / phi + " " + i * j + " " + phi); } } } } } } }
8
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(PuntoVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PuntoVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PuntoVenta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PuntoVenta.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 PuntoVenta().setVisible(true); } }); }
6
private int strcmp(String s1, int i1, String s2, int i2) { int l1 = s1.length() - i1; int l2 = s2.length() - i2; int len = l1; boolean diff = false; if (len > l2) { len = l2; } while (len-- > 0) { if (s1.charAt(i1++) != s2.charAt(i2++)) { diff = true; break; } } if (diff == false && l1 != l2) { if (l1 > l2) { return s1.charAt(i1); } else { return -s2.charAt(i2); } } return s1.charAt(i1-1) - s2.charAt(i2-1); }
6
private void analisaRegistro() { System.out.println("ENTROU22"); if (!acabouListaTokens()) { nextToken(); if (tipoDoToken[0].equals("Identificador")) { nomeRegistro = tipoDoToken[1]; if (!acabouListaTokens()) { nextToken(); if (tipoDoToken[1].equals(" {")) { if (!acabouListaTokens()) { nextToken(); this.listaDeCamposRegistro(); } else { System.out.println("FIM DE ARQUIVO!"); } } } else { System.out.println("FIM DE ARQUIVO!"); } } } else { System.out.println("FIM DE ARQUIVO!"); } }
5
private String[][] createScoreList(String string){ if (string==null){ return null; } else { int savedScores = numbersOfSymbols(string, DATA_DIVIDER2); String temp[][] = new String[savedScores][2]; for (int a=0; a < savedScores; a++){ for (int b=0; b < 2; b++){ String indexThingie=DATA_DIVIDER1; if(b==1){ indexThingie+=DATA_DIVIDER1; } temp[a][b]=string.substring(0, string.indexOf(indexThingie)); string = string.substring(string.indexOf(indexThingie)+indexThingie.length(), string.length()); } } return temp; } }
4
public static CommandManager getInstance(){ if (instance == null){ synchronized (CommandManager.class) { if (instance == null){ instance = new CommandManager(); } } } return instance; }
2
private int compareFitness(int particle1, int particle2){ double p1 = fitness.get(particle1); double p2 = fitness.get(particle2); if(maximum){ if(p1 > p2){ return particle1; }else{ return particle2; } }else{ if(p1 < p2){ return particle1; }else{ return particle2; } } }
3
public static void main(String[] args) { BinaryTree BT = new BinaryTree(); Scanner in = new Scanner(System.in); int n = in.nextInt(); Node root = null; for (int i = 0; i < n; i++) { root = BT.addToTree(root, in.nextInt()); } System.out.println(findPredecessor(root, root.left).v); }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Curso)) { return false; } Curso other = (Curso) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public ResultSet select(String query){ try{ Statement stm = this.con.createStatement(); ResultSet rs = stm.executeQuery(query); // stm.close(); return rs; } catch(SQLException e){ LogHandler.writeStackTrace(log, e, Level.SEVERE); return null; } }
1
private boolean jj_2_3(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_3(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(2, xla); } }
1
public int searchForEmployeeIndex(String firstName, String lastName) { if (arrayDirty) { insertionSort(); } final int count = employees.size(); for (int i = 0; i < count; ++i) { final Employee employee = employees.get(i); if ( lastName.equalsIgnoreCase(employee.getLastName()) && firstName.equalsIgnoreCase(firstName)) { return i; } } return -1; }
4
@Override public void setMiscText(String text) { super.setMiscText(text); final Vector<String> V=CMParms.parse(text); dayFlag=false; doneToday=false; lockupFlag=false; sleepFlag=false; sitFlag=false; openTime=-1; closeTime=-1; lastClosed=-1; Home=null; shopMsg=null; for(int v=0;v<V.size();v++) { String s=V.elementAt(v).toUpperCase(); if(s.equals("DAY")) dayFlag=true; else if(s.equals("SLEEP")) sleepFlag=true; else if(s.equals("LOCKUP")) lockupFlag=true; else if(s.equals("SIT")) sitFlag=true; else if(s.startsWith("HOURS=")) { s=s.substring(6); final int x=s.indexOf('-'); if(x>=0) { openTime=CMath.s_int(s.substring(0,x)); closeTime=CMath.s_int(s.substring(x+1)); } } else if(s.startsWith("HOME=")) Home=V.elementAt(v).substring(5); else if(s.startsWith("SHOPMSG=")) shopMsg=V.elementAt(v).substring(8); } }
9
public boolean write(int id, byte... file) { synchronized(this) { try { byte header[] = new byte[6]; int length = file.length; int position = (int) ((data.length() + 519L) / 520L); // writing the header[0] = (byte) (length >> 16); header[1] = (byte) (length >> 8); header[2] = (byte) length; header[3] = (byte) (position >> 16); header[4] = (byte) (position >> 8); header[5] = (byte) position; index.seek(id * 6); index.write(header, 0, 6); int offset = 0; int blockIndex = 0; byte[] header2 = new byte[8]; while (offset < length) { position++; // simple data.seek(position * 520); header2[0] = (byte) (id >> 8); header2[1] = (byte) id; header2[2] = (byte) (blockIndex >> 8); header2[3] = (byte) blockIndex; header2[4] = (byte) (position >> 16); header2[5] = (byte) (position >> 8); header2[6] = (byte) position; header2[7] = (byte) id; data.write(header2, 0, 8); int amt = length - offset; if (amt > 512) { amt = 512; } data.write(file, offset, amt); offset += amt; blockIndex++; } return true; } catch(Exception e) { e.printStackTrace(); } } return false; }
3
private void initializeBoard(int bl, int wa, int pi) { // Put the blocks on the board. int k= 0; // invariant: k blocks have been added. while (k < bl) { int xx = JManApp.rand(0, width-1); int yy = JManApp.rand(0, height-1); if(isEmpty(xx, yy)) { placePiece(Piece.BLOCK, xx, yy); k= k+1; } } // Put the walkers on the board. k= 0; // invariant: k walkers have been added. while (k < wa) { int xx = JManApp.rand(0, width-1); int yy = JManApp.rand(0, height-1); if(isEmpty(xx, yy)){ placePiece(Piece.WALKER, xx, yy); k= k+1; } } // Put the pillars on the board. k= 0; // invariant: k pillars have been added. while(k < pi) { int xx = JManApp.rand(0, width-1); int yy = JManApp.rand(0, height-1); if(isEmpty(xx, yy)) { placePiece(Piece.PILLAR, xx, yy); k= k+1; } } }
6
public static void jar(File directory, File jarfile) { try { final URI base = directory.toURI(); final Deque<File> queue = new LinkedList<File>(); queue.push(directory); final OutputStream out = new FileOutputStream(jarfile); Closeable res = null; final JarOutputStream zout = new JarOutputStream(out); res = zout; while (!queue.isEmpty()) { directory = queue.pop(); for (final File kid : directory.listFiles()) { String name = base.relativize(kid.toURI()).getPath(); if (kid.isDirectory()) { queue.push(kid); name = name.endsWith("/") ? name : name + "/"; zout.putNextEntry(new JarEntry(name)); } else { zout.putNextEntry(new JarEntry(name)); copy(kid, zout); zout.closeEntry(); } } } res.close(); } catch (final IOException e) { e.printStackTrace(); } }
5
public JavaSerializer(Class cl, ClassLoader loader) { introspectWriteReplace(cl, loader); if (_writeReplace != null) _writeReplace.setAccessible(true); ArrayList primitiveFields = new ArrayList(); ArrayList compoundFields = new ArrayList(); for (; cl != null; cl = cl.getSuperclass()) { Field []fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; // XXX: could parameterize the handler to only deal with public field.setAccessible(true); if (field.getType().isPrimitive() || (field.getType().getName().startsWith("java.lang.") && ! field.getType().equals(Object.class))) primitiveFields.add(field); else compoundFields.add(field); } } ArrayList fields = new ArrayList(); fields.addAll(primitiveFields); fields.addAll(compoundFields); _fields = new Field[fields.size()]; fields.toArray(_fields); _fieldSerializers = new FieldSerializer[_fields.length]; for (int i = 0; i < _fields.length; i++) { _fieldSerializers[i] = getFieldSerializer(_fields[i].getType()); } }
9
private void checkForNumber() { int offs = this.currentPos; Element element = this.getParagraphElement(offs); String elementText = ""; try { // this gets our chuck of current text for the element we're on elementText = this.getText(element.getStartOffset(), element .getEndOffset() - element.getStartOffset()); } catch (Exception ex) { // whoops! System.out.println("no text"); } int strLen = elementText.length(); if (strLen == 0) { return; } int i = 0; if (element.getStartOffset() > 0) { // translates backward if neccessary offs = offs - element.getStartOffset(); } mode = TEXT_MODE; if ((offs >= 0) && (offs <= strLen - 1)) { i = offs; while (i > 0) { // the while loop walks back until we hit a delimiter char charAt = elementText.charAt(i); if ((charAt == ' ') | (i == 0) | (charAt == '(') | (charAt == ')') | (charAt == '{') | (charAt == '}') /* | */) { // if i // == 0 // then // we're // at // the // begininng if (i != 0) { i++; } mode = NUMBER_MODE; break; } else if (!(charAt >= '0' & charAt <= '9' | charAt == '.' | charAt == '+' | charAt == '-' | charAt == '/' | charAt == '*' | charAt == '%' | charAt == '=')) { mode = TEXT_MODE; break; } i--; } } }
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
9
@Override public void mousePressed(MouseEvent e) { if ( ! toolBar.isAddingLink() && ! toolBar.isEditingLink() && ! toolBar.isRemovingLink()) { try { if (tree.getSelectedSquare() != null) { this.clickX = ((e.getX() - (lblMap.getWidth() - 32 * map .getWidth()) / 2) / 32); this.clickY = ((e.getY() - (lblMap.getHeight() - 32 * map .getWidth()) / 2) / 32); } } catch (SpriteException | CompressionException e1) { e1.printStackTrace(); } } else { this.clickX = 0xFF; } }
5
private boolean execEstimateUsingFeatureFrequencies(VectorMap queryParam, StringBuffer respBody, DBAccess dbAccess) { try { int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt"); String clientName = (String) queryParam.getVal(clntIdx); int ftrsIdx = queryParam.qpIndexOfKeyNoCase("ftrs"); String ftrNames = null; if (ftrsIdx != -1) { ftrNames = (String) queryParam.getVal(ftrsIdx); } int usrIdx = queryParam.qpIndexOfKeyNoCase("usr"); if (usrIdx == -1) { WebServer.win.log.error("-Missing argument: usr"); return false; } String user = (String) queryParam.getVal(usrIdx); int ftrIdx = queryParam.qpIndexOfKeyNoCase("ftr"); if (ftrIdx == -1) { WebServer.win.log.error("-Missing argument: ftr"); return false; } String ftrPattern = (String) queryParam.getVal(ftrIdx); String[] ftrs = ftrPattern.split("\\|"); respBody.append(DBAccess.xmlHeader("/resp_xsl/estimation_profile.xsl")); respBody.append("<result>\n"); String sql = "SELECT " + DBAccess.UPROFILE_TABLE_FIELD_VALUE + " FROM " + DBAccess.UPROFILE_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UPROFILE_TABLE_FIELD_USER + "='" + user + "' AND " + DBAccess.UPROFILE_TABLE_FIELD_FEATURE + "=?"; PreparedStatement selectFtr = dbAccess.getConnection().prepareStatement(sql); sql = "SELECT " + DBAccess.FEATURE_STATISTICS_TABLE_FIELD_VALUE + " FROM " + DBAccess.FEATURE_STATISTICS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.FEATURE_STATISTICS_TABLE_FIELD_USER + "='" + user + "' AND " + DBAccess.FEATURE_STATISTICS_TABLE_FIELD_FEATURE + "=? AND " + DBAccess.FEATURE_STATISTICS_TABLE_FIELD_TYPE + "=" + DBAccess.STATISTICS_FREQUENCY; PreparedStatement selectFtrFreq = dbAccess.getConnection().prepareStatement(sql); String sql1 = "SELECT " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_DST + " ftr," + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_WEIGHT + " FROM " + DBAccess.UFTRASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_USR + "='' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_SRC + "=? AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_PHYSICAL; String sql2 = "SELECT " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_SRC + " ftr," + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_WEIGHT + " FROM " + DBAccess.UFTRASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_USR + "='' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_DST + "=? AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_PHYSICAL; sql = "(" + sql1 + ") UNION (" + sql2 + ")"; PreparedStatement assocs = dbAccess.getConnection().prepareStatement(sql); for (int i = 0; i < ftrs.length; i++) { assocs.setString(1, ftrs[i]); assocs.setString(2, ftrs[i]); ResultSet rs = assocs.executeQuery(); ArrayList<String> coFeatures = new ArrayList<String>(40); ArrayList<Float> coFeatureWeights = new ArrayList<Float>(40); while (rs.next()) { coFeatures.add(rs.getString(1)); coFeatureWeights.add(rs.getFloat(2)); } rs.close(); int numOfnownCoFtrs = 0; float weight = 0.0f; float sum = 0.0f; int j = 0; for (String feature : coFeatures) { selectFtr.setString(1, feature); rs = selectFtr.executeQuery(); if (rs.next()) { numOfnownCoFtrs++; float val = rs.getFloat(1); rs.close(); selectFtrFreq.setString(1, feature); rs = selectFtrFreq.executeQuery(); rs.next(); float freq = rs.getFloat(1); weight += val * freq * coFeatureWeights.get(j); sum += freq * coFeatureWeights.get(j); } else { rs.close(); } j++; } if (numOfnownCoFtrs > 0) { String record = "<row><ftr>" + ftrs[i] + "</ftr><val>" + (weight / sum) + "</val><factors>" + (numOfnownCoFtrs * 1.0 / coFeatureWeights.size()) + "</factors></row>"; respBody.append(record); } else { String record = "<row><ftr>" + ftrs[i] + "</ftr><val>uknown</val><factors>" + (numOfnownCoFtrs * 1.0 / coFeatureWeights.size()) + "</factors></row>"; respBody.append(record); } } selectFtr.close(); selectFtrFreq.close(); assocs.close(); respBody.append("</result>"); } catch (SQLException ex) { WebServer.win.log.error(ex.toString()); ex.printStackTrace(); return false; } return true; }
9
public boolean drawShape(mxGraphicsCanvas2D canvas, mxCellState state, mxRectangle bounds, boolean background) { Element elt = (background) ? bgNode : fgNode; if (elt != null) { String direction = mxUtils.getString(state.getStyle(), mxConstants.STYLE_DIRECTION, null); mxRectangle aspect = computeAspect(state, bounds, direction); double minScale = Math.min(aspect.getWidth(), aspect.getHeight()); double sw = strokewidth.equals("inherit") ? mxUtils.getDouble( state.getStyle(), mxConstants.STYLE_STROKEWIDTH, 1) * state.getView().getScale() : Double .parseDouble(strokewidth) * minScale; lastMoveX = 0; lastMoveY = 0; canvas.setStrokeWidth(sw); Node tmp = elt.getFirstChild(); while (tmp != null) { if (tmp.getNodeType() == Node.ELEMENT_NODE) { drawElement(canvas, state, (Element) tmp, aspect); } tmp = tmp.getNextSibling(); } return true; } return false; }
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Album)) { return false; } Album other = (Album) object; if ((this.albumid == null && other.albumid != null) || (this.albumid != null && !this.albumid.equals(other.albumid))) { return false; } return true; }
5
private static String getStringFromDocument(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
1
public TextViewPanel(Grid initGame){ super(); setBackground(Color.BLACK); game = initGame; this.setFont(new Font(Font.MONOSPACED, Font.BOLD, 22)); }
0
static public int extractZipToFolder(File pZipFile, File pDestinationDirectory) throws ZipException, IOException { if(!pDestinationDirectory.isDirectory()){ throw new ExInternal(pDestinationDirectory.getAbsolutePath() + " is not a valid directory"); } ZipFile lZipFile = new ZipFile(pZipFile); Enumeration<? extends ZipEntry> lZipFileEntries = lZipFile.entries(); int lFileCount = 0; // Process each entry while(lZipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry lEntry = lZipFileEntries.nextElement(); String lCurrentEntry = lEntry.getName(); File lDestFile = new File(pDestinationDirectory, lCurrentEntry); File lDestinationParent = lDestFile.getParentFile(); // create the parent directory structure if needed lDestinationParent.mkdirs(); if(!lEntry.isDirectory()) { lFileCount++; InputStream lInput = lZipFile.getInputStream(lEntry); FileOutputStream lOutput = new FileOutputStream(lDestFile); IOUtils.copy(lInput, lOutput); lInput.close(); lOutput.flush(); lOutput.close(); } } return lFileCount; }
4
Operation transactOperation(Operation src, boolean updated) throws OperationServiceException { Account account = src.getAccount(); BigDecimal repositoryBalance; if (updated) { repositoryBalance = getRollbackBalance(src); } else { repositoryBalance = account.getBalance(); } BigDecimal cost = src.getCost(); OperationType type = src.getOperationType(); BigDecimal updatedBalance = null; if (type == OperationType.expense || type == OperationType.transferFrom) { updatedBalance = repositoryBalance.subtract(cost); AmountValidator.notNegative(updatedBalance, IS_TOO_MUCH_TRANSACTION_AMOUNT); } if (type == OperationType.income || type == OperationType.transferTo) { updatedBalance = repositoryBalance.add(cost); } if (updatedBalance == null) { throw new OperationServiceException(INVALID_OPERATION_TYPE); } account.setBalance(updatedBalance); accountService.update(account); if (updated) { manager.merge(src); } else { manager.persist(src); } manager.flush(); return src; }
7
public String getApellido1() { return apellido1; }
0
public Explorer() { String date = (new SimpleDateFormat("EEEE, d MMMM yyyy")).format(new Date()); m_LogPanel.logMessage("Weka Explorer"); m_LogPanel.logMessage("(c) " + Copyright.getFromYear() + "-" + Copyright.getToYear() + " " + Copyright.getOwner() + ", " + Copyright.getAddress()); m_LogPanel.logMessage("web: " + Copyright.getURL()); m_LogPanel.logMessage("Started on " + date); m_LogPanel.statusMessage("Welcome to the Weka Explorer"); // intialize pre-processpanel m_PreprocessPanel.setLog(m_LogPanel); m_TabbedPane.addTab( m_PreprocessPanel.getTabTitle(), null, m_PreprocessPanel, m_PreprocessPanel.getTabTitleToolTip()); // initialize additional panels String[] tabs = ExplorerDefaults.getTabs(); Hashtable<String, HashSet> tabOptions = new Hashtable<String, HashSet>(); for (int i = 0; i < tabs.length; i++) { try { // determine classname and additional options String[] optionsStr = tabs[i].split(":"); String classname = optionsStr[0]; HashSet options = new HashSet(); tabOptions.put(classname, options); for (int n = 1; n < optionsStr.length; n++) options.add(optionsStr[n]); // setup panel ExplorerPanel panel = (ExplorerPanel) Class.forName(classname).newInstance(); panel.setExplorer(this); m_Panels.add(panel); if (panel instanceof LogHandler) ((LogHandler) panel).setLog(m_LogPanel); m_TabbedPane.addTab( panel.getTabTitle(), null, (JPanel) panel, panel.getTabTitleToolTip()); } catch (Exception e) { e.printStackTrace(); } } // setup tabbed pane m_TabbedPane.setSelectedIndex(0); for (int i = 0; i < m_Panels.size(); i++) { HashSet options = tabOptions.get(m_Panels.get(i).getClass().getName()); m_TabbedPane.setEnabledAt(i + 1, options.contains("standalone")); } // setup notification for dataset changes m_PreprocessPanel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { for (int i = 0; i < m_Panels.size(); i++) { m_Panels.get(i).setInstances(m_PreprocessPanel.getInstances()); m_TabbedPane.setEnabledAt(i + 1, true); } } }); // add listeners for changes in the capabilities m_PreprocessPanel.setExplorer(this); addCapabilitiesFilterListener(m_PreprocessPanel); for (int i = 0; i < m_Panels.size(); i++) { if (m_Panels.get(i) instanceof CapabilitiesFilterChangeListener) addCapabilitiesFilterListener((CapabilitiesFilterChangeListener) m_Panels.get(i)); } // add components to layout setLayout(new BorderLayout()); add(m_TabbedPane, BorderLayout.CENTER); add(m_LogPanel, BorderLayout.SOUTH); }
8
@SuppressWarnings("unchecked") public Class<Reducer<Writable, Writable, Writable, Writable>> loadClass () throws IOException, ClassNotFoundException { /* Load Jar file */ String jarFilePath = this.task.getJarEntry().getLocalPath(); if (MapReduce.Core.DEBUG) { System.out.println("DEBUG RunReducer.loadClass(): JarFilePath:" + jarFilePath); } JarFile jarFile = new JarFile(jarFilePath); Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = { new URL("jar:file:" + jarFilePath +"!/") }; ClassLoader cl = URLClassLoader.newInstance(urls); Class<Reducer<Writable, Writable, Writable, Writable>> reducerClass = null; /* Iterate .class files */ while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if(je.isDirectory() || !je.getName().endsWith(".class")){ continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); if (className.equals(this.task.getReducerClassName())) { reducerClass = (Class<Reducer<Writable, Writable, Writable, Writable>>) cl.loadClass(className); } } return reducerClass; }
5
@Override public void load(String input) { StringBuilder sb = new StringBuilder(); ImagePanel imgPanel = MainWindow.MAIN_WINDOW.getImagePanel(); for(String str : input.split("\n")) { if (str.startsWith("img")){ sb.setLength(0); sb.append(str+"\n"); } else if (str.startsWith("anim")) { sb.setLength(0); sb.append(str+"\n"); } else if (str.startsWith("endimg")) { String data = sb.toString(); ImageData imgData = imgPanel.addSnippedImage(parseLoadRect(data)); if (imgData != null){ loadImageData(imgData, data); } else { System.out.println("Corrupt data file."); break; } } else if (str.startsWith("endanim")) { String data = sb.toString(); Animation tmpAnim = new Animation(); MainWindow.MAIN_WINDOW.getSheetData().getAnimations().add(tmpAnim); loadAnimData(tmpAnim, data); } else { sb.append(str+"\n"); } } }
6
public CtClass getSuperclass() throws NotFoundException { String supername = getClassFile2().getSuperclass(); if (supername == null) return null; else return classPool.get(supername); }
1
@Override public boolean delete(int prenodeid, int nownodeid) { boolean flag = false; System.out.println(prenodeid + " " + nownodeid); Timenode prenode = getTimenode(prenodeid); Timenode nownode = getTimenode(nownodeid); prenode.setNextnode(nownode.getNextnode()); nownode.setDisplay("false"); if (update(nownode) && update(prenode)) flag = true; return flag; }
2
public static boolean isName(String name) { if (isNull(name)) { return false; } for (char c : name.trim().toCharArray()) { if (((!isChar(c)) && (!Character.isWhitespace(c))) || (c == CharPool.COMMA)) { return false; } } return true; }
5
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (plugin.allMuted) { plugin.allMuted = false; for (ProxiedPlayer data : plugin.getProxy().getPlayers()) { data.sendMessage(plugin.PLAYER_ALL_UNMUTED); } } else { plugin.allMuted = true; for (ProxiedPlayer data : plugin.getProxy().getPlayers()) { data.sendMessage(plugin.PLAYER_ALL_MUTED); } } }
4
protected void downloadEagerResources() { synchronized (this) { if (eager_resources_started_flag) return; } //update the flag synchronized (this) { eager_resources_started_flag = true; } List<CacheResource> eagerResources = new ArrayList<CacheResource>(); for (ClassPathEntry entry : classPath) { //check os of classpath Entry //skip this jar if it is not for this OS if (entry.getOs() != null && !entry.getOs().equals(NativeLibDesc.currentOS())) { logger.info("skipping non-os classpath entry: " + entry.getResourceURL()); continue; } if (entry.getDownloadType() == ClassPathEntry.EAGER && (entry.isJar() || entry.isZip())) { eagerEntries.put(entry.getResourceURL(), entry); eagerResources.add(new CacheResource(entry.getResourceURL(), entry.getCachePolicy())); } else { lazyEntries.put(entry.getResourceURL(), entry); } } //Download the resources CacheManager cm = Boot.getCacheManager(); cm.downloadResources(this.getExecutableDesc(), eagerResources, cm.getDefaultListener(), true); //Update downloaded status and initialize the jars Collection<ClassPathEntry> entries = eagerEntries.values(); for (ClassPathEntry entry : entries) { entry.downloaded_flag = true; entry.initializeJar(); } unPackNatives(); }
8
public void run() { BufferedImage image = null; try { URL imgUrl = new URL(link); image = ImageIO.read(imgUrl); ImageIO.write(image, "png", new File(filename)); } catch(Exception ex) {} System.out.println("Downloaded to " + filename); }
1
protected List<PhysicalAgent> loadMobsFromFile(Environmental scripted, String filename) { filename=filename.trim(); List monsters=(List)Resources.getResource("RANDOMMONSTERS-"+filename); if(monsters!=null) return monsters; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); monsters=new Vector<PhysicalAgent>(); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"MOBS")!=null) { final String error=CMLib.coffeeMaker().addMOBsFromXML(xml,monsters,null); if(error.length()>0) { logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(monsters.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMMONSTERS-"+filename,monsters); } else { logError(scripted,"XMLLOAD","?","No MOBs in XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } return monsters; }
9
public static String capitalFirst(String input) { String[] table = input.split(" "); String output = ""; for (int i = 0; i < table.length; i++) { if (i > 0) { output += " "; } if (table[i].equalsIgnoreCase("and") || table[i].equalsIgnoreCase("or") || table[i].equalsIgnoreCase("with") || table[i].equalsIgnoreCase("in") || table[i].equalsIgnoreCase("a") || table[i].equalsIgnoreCase("over")) { output += table[i].toLowerCase(); } else { output += singleWordCapitalFirst(table[i]); } } return output; }
8
private void battle() throws IOException { boolean end =false; String line = null; while(!end && !closed){ //все что в цикле сугубо для того чтоб комп не вис) line = inputStream.readUTF(); if(line.equals("$lost$")){ this.lost = true; } else if (line.equals("m")){ this.X = inputStream.readFloat(); this.Y = inputStream.readFloat(); this.bitmapAngle = inputStream.readFloat(); this.targetX = inputStream.readFloat(); this.targetY = inputStream.readFloat(); } else if (line.equals("$fire$")){ fired = true; this.xFire = inputStream.readFloat(); this.yFire = inputStream.readFloat(); }else if(line.equals("$stop$")){ end =true; }else close(); } }
6
public void pause() { pause = true; timer.cancel(); timer.purge(); }
0
private void getClassAndMethod() { try { Throwable throwable = new Throwable(); throwable.fillInStackTrace(); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter( stringWriter ); throwable.printStackTrace( printWriter ); String traceString = stringWriter.getBuffer().toString(); StringTokenizer tokenizer = new StringTokenizer( traceString, "\n" ); tokenizer.nextToken(); String line = tokenizer.nextToken(); while ( line.indexOf( this.getClass().getName() ) == -1 ) { line = tokenizer.nextToken(); } while ( line.indexOf( this.getClass().getName() ) >= 0 ) { line = tokenizer.nextToken(); } int start = line.indexOf( "at " ) + 3; int end = line.indexOf( '(' ); String temp = line.substring( start, end ); int lastPeriod = temp.lastIndexOf( '.' ); sourceClassName = temp.substring( 0, lastPeriod ); sourceMethodName = temp.substring( lastPeriod + 1 ); } catch ( Exception ex ) { // ignore - leave class and methodname unknown } classAndMethodFound = true; }
3
public void setPWFieldFontsize(int fontsize) { if (fontsize <= 0) { this.pWFieldFontSize = UIFontInits.PWFIELD.getSize(); } else { this.pWFieldFontSize = fontsize; } somethingChanged(); }
1
public String toString() { String ret = ""; int roundheight = (int)Math.ceil(height); int roundwidth = (int)Math.ceil(width); for(int j = 0; j < roundheight; j++) { for(int i=0; i < roundwidth; i++) { if((i == 0) || (j == 0) || (i == (roundwidth-1)) || (j == (roundheight-1))) { ret += frame; if(i == (roundwidth-1)) ret += "\n"; } else ret += content; } } return ret; }
7
public void comment(String s) { if (inStartTag) { maybeWriteTopLevelAttributes(); inStartTag = false; write(">"); newline(); } if (!inText) indent(); write("<!--"); int start = 0; level++; for (;;) { int i = s.indexOf('\n', start); if (i < 0) { if (start > 0) { newline(); indent(); write(s.substring(start)); level--; newline(); indent(); } else { level--; if (s.length() != 0) { write(' '); write(s); if (s.charAt(s.length() - 1) != ' ') write(' '); } } break; } newline(); indent(); write(s.substring(start, i)); start = i + 1; } write("-->"); if (!inText) newline(); }
8
private boolean checkWordForDuplicate (String motherLangWord, String translation) throws SQLException { boolean hasDuplicate = false; Connection conn = null; try { conn = DriverManager.getConnection(Utils.DB_URL); PreparedStatement motherLangWordPStat = conn.prepareStatement("SELECT motherlang_word FROM word WHERE motherlang_word = '" + motherLangWord + "'"); PreparedStatement translationPStat = conn.prepareStatement("SELECT foreignlang_word FROM word WHERE foreignlang_word = '"+ translation +"'"); ResultSet motherLangWordResSet = motherLangWordPStat.executeQuery(); ResultSet translationResSet = translationPStat.executeQuery(); if (motherLangWordResSet.next() && translationResSet.next()) { hasDuplicate = true; } } catch (SQLException e) { e.printStackTrace(); } finally { conn.close(); return hasDuplicate; } }
3
private void addDataEx(){ /* SensorDao dao = new SensorDao(); Sensor sensor = dao.getOne(1); */ Sensor sensor = new Sensor(); sensor.setAddDate(new Date(System.currentTimeMillis())); sensor.setUnity("s"); sensor.setStatementFrequency(1222); sensor.setName("Sensor_Test"); sensor.setSensorType(SensorType.GRAPH); sensor.setGpsLocation(-0.127512, 51.507222); Data input = new Data(); input.setDate(System.currentTimeMillis()); input.setIsOnPhone(false); input.setValue("11"); input.setSensor(sensor); input.setSensorId(1); try { ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); WebResource webResource = client.resource(URL_SERVEUR); ClientResponse response = webResource.path("rest").path("data").path("post").accept("application/json").type("application/json").post(ClientResponse.class, input); if (response.getStatus() != Response.Status.CREATED.getStatusCode()) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String output = response.getEntity(String.class); System.out.println("Data : " + output); } catch (Exception e) { e.printStackTrace(); } }
2
public void warn(final String msg) { if(disabled) return; else logger.warning("" + route_name + "-" + connection_id + "[warn]: " + msg); }
1
public static Cons parseColumnSpecs(Stella_Object relconst, Stella_Object columnspecs, Object [] MV_returnarray) { if (!(Stella_Object.consP(columnspecs))) { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); stream000.nativeStream.println("PARSING ERROR: Illegal variable/column specifications: `" + columnspecs + "'."); Logic.helpSignalPropositionError(stream000, RDBMS.KWD_ERROR); } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } throw ((ParsingError)(ParsingError.newParsingError(stream000.theStringReader()).fillInStackTrace())); } } { Cons relationargs = Stella.NIL; Cons axioms = Stella.NIL; { Stella_Object columnspec = null; Cons iter000 = ((Cons)(columnspecs)); int i = Stella.NULL_INTEGER; int iter001 = 1; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest, iter001 = iter001 + 1) { columnspec = iter000.value; i = iter001; { PropertyList columninfo = RDBMS.parseOneColumnSpec(columnspec); Stella_Object type = columninfo.lookup(RDBMS.KWD_TYPE); Stella_Object name = columninfo.lookup(RDBMS.KWD_NAME); Stella_Object var = columninfo.lookup(RDBMS.KWD_VARIABLE); Stella_Object modulename = columninfo.lookup(RDBMS.KWD_MODULE_NAME); Stella_Object modulereference = columninfo.lookup(RDBMS.KWD_MODULE_REFERENCE); if (type != null) { relationargs = Cons.cons(Cons.consList(Cons.cons(var, Cons.cons(type, Stella.NIL))), relationargs); } else { relationargs = Cons.cons(var, relationargs); } if (name != null) { axioms = Cons.cons(Cons.list$(Cons.cons(RDBMS.SYM_RDBMS_RELATION_COLUMN_NAME, Cons.cons(relconst, Cons.cons(Cons.cons(IntegerWrapper.wrapInteger(i), Cons.cons(name, Stella.NIL)), Stella.NIL)))), axioms); } if (modulename != null) { axioms = Cons.cons(Cons.list$(Cons.cons(RDBMS.SYM_RDBMS_RELATION_COLUMN_MODULE_NAME, Cons.cons(relconst, Cons.cons(Cons.cons(IntegerWrapper.wrapInteger(i), Cons.cons(modulename, Stella.NIL)), Stella.NIL)))), axioms); } if (modulereference != null) { axioms = Cons.cons(Cons.list$(Cons.cons(RDBMS.SYM_RDBMS_RELATION_COLUMN_MODULE_REFERENCE, Cons.cons(relconst, Cons.cons(Cons.cons(IntegerWrapper.wrapInteger(i), Cons.cons(modulereference, Stella.NIL)), Stella.NIL)))), axioms); } } } } { Cons _return_temp = relationargs.reverse(); MV_returnarray[0] = axioms.reverse(); return (_return_temp); } } }
6
public boolean deleteTestEmployees(Connection con) { boolean didItWork = true; ArrayList<Integer> empno = new ArrayList(); String SQLString1 = "SELECT medarbejderno " + "FROM medarbejder " + "WHERE navn = 'test'"; String SQLString2 = "DELETE FROM medarbejderdetails " +"WHERE medarbejderno = ?"; String SQLString3 = "DELETE FROM medarbejder" + " WHERE navn = 'test'"; PreparedStatement statement = null; try { statement = con.prepareStatement(SQLString1); ResultSet rs = statement.executeQuery(); while(rs.next()) { empno.add(rs.getInt(1)); } statement = con.prepareStatement(SQLString2); for(int i = 0; i < empno.size(); i++) { statement.setInt(1, empno.get(i)); if(statement.executeUpdate() == 0) { didItWork = false; } } statement = con.prepareStatement(SQLString3); if(statement.executeUpdate() == 0) { didItWork = false; } } catch (Exception e) { System.out.println("Fejl i TheMapper - deleteTestEmployees"); didItWork = false; } return didItWork; }
5
public boolean hasErrorOrWarning() { return isErrorProteinLength() || isErrorStartCodon() || isErrorStopCodonsInCds() // Errors || isWarningStopCodon() // Warnings ; }
3
public startGui(boolean bol, String ip, int Port){ //Manual_Server = bol; catalogue.setmanualServer(bol); if(!bol){ getServerNames(); } else{ Server = new ServerList(ip, Port); serverlist = Server.getServerList(); } StartGui(); if(bol){ ManualyServer(ip, Port); } }
2
* @param terminal New terminal to be used. * @param source Specifies if the new terminal is the source or target. * @param constraint Constraint to be used for this connection. */ public void cellConnected(Object edge, Object terminal, boolean source, mxConnectionConstraint constraint) { if (edge != null) { model.beginUpdate(); try { Object previous = model.getTerminal(edge, source); // Updates the constraint setConnectionConstraint(edge, terminal, source, constraint); // Checks if the new terminal is a port, uses the ID of the port in the // style and the parent of the port as the actual terminal of the edge. if (isPortsEnabled()) { // Checks if the new terminal is a port String id = null; if (isPort(terminal) && terminal instanceof mxICell) { id = ((mxICell) terminal).getId(); terminal = getTerminalForPort(terminal, source); } // Sets or resets all previous information for connecting to a child port String key = (source) ? mxConstants.STYLE_SOURCE_PORT : mxConstants.STYLE_TARGET_PORT; setCellStyles(key, id, new Object[] { edge }); } model.setTerminal(edge, terminal, source); if (isResetEdgesOnConnect()) { resetEdge(edge); } fireEvent(new mxEventObject(mxEvent.CELL_CONNECTED, "edge", edge, "terminal", terminal, "source", source, "previous", previous)); } finally { model.endUpdate(); } } }
6
private List<String> replaceInUnescapedSegmentsInternal(Pattern pPattern, String pReplacement, int pReplaceLimit){ List<String> lReplacedStringsList = new ArrayList<String>(); int lReplaceCount = 0; for(ScriptSegment lSegment : mSegmentList){ if(lSegment instanceof UnescapedTextSegment) { //Match on the contents of this unescaped segment Matcher lMatcher = pPattern.matcher(lSegment.getContents()); StringBuffer lNewContents = new StringBuffer(); while (lMatcher.find() && (pReplaceLimit == -1 || lReplaceCount < pReplaceLimit)) { //Make a record of the string we replaced lReplacedStringsList.add(lMatcher.group()); lMatcher.appendReplacement(lNewContents, pReplacement); lReplaceCount++; } lMatcher.appendTail(lNewContents); //Replace the contents of the segment with the processed string lSegment.setContents(lNewContents.toString()); } } return lReplacedStringsList; }
5
private void initializeThread() { Thread outputter = new Thread(new Runnable() { @Override public void run() { while (true) { String message = packetFactory.receiveMessage().trim(); if (message.startsWith("/m/")) { message = message.replace("/m/", ""); } log(message); } } }); outputter.start(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { packetFactory.sendMessage("/dc/" + username); System.exit(0); } }); }
2
public int next_tick( int tick, boolean key_on ) { tick = tick + 1; if( looped && tick >= loop_end_tick ) { tick = loop_start_tick; } if( sustain && key_on && tick >= sustain_tick ) { tick = sustain_tick; } return tick; }
5
static public CycList convertMapToPlist(final Map map) { final CycList plist = new CycList(); if (map != null) { for (final Iterator<Map.Entry> i = map.entrySet().iterator(); i.hasNext();) { final Map.Entry entry = i.next(); plist.add(entry.getKey()); plist.add(entry.getValue()); } } return plist; }
2
void connectGenerator (Synthesizer synth) throws SynthIfException { Generator freq = ((Input)inputs.elementAt (0)).getGenerator(); Generator phase = ((Input)inputs.elementAt (1)).getGenerator(); if (phase == null) synth.add (phase = new Constant (synth, 0)); Generator amp = ((Input)inputs.elementAt (2)).getGenerator(); if (type == SIN) ((SinGenerator)generator).setParameters (freq, phase, amp); if (type == TRIANGLE) ((TriangleGenerator)generator).setParameters (freq, phase, amp); if (type == SQUARE) ((SquareGenerator)generator).setParameters (freq, phase, amp); if (type == SAWTOOTH) ((SawtoothGenerator)generator).setParameters (freq, phase, amp); if (type == WAVE) { if (wave == null) throw new SynthIfException ("Empty wave in oscillator"); ((WaveGenerator)generator).setParameters (wave.getWave(), freq, phase, amp, interpolate); } }
7
public void start(String args[]) { // TODO quit if wrong arguments try { this.host = args[0]; this.tcpPort = Integer.parseInt(args[1]); this.analyticServerRef = args[2]; } catch(NumberFormatException e) { logger.error("Seconds argument has to be an integer"); } catch(ArrayIndexOutOfBoundsException e) { logger.error("Too few arguments"); } PropertyConfigurator.configure("src/log4j.properties"); readProperties(); managementClient = new ManagementClient(analyticServerRef); managementClient.start(); managementClient.processInput("!subscribe .*"); for (int i = 0; i<clients; i++) { LoadTestClient client = new LoadTestClient(host, tcpPort); testClients.add(client); //client.loginClient(); if (auctionsPerMin > 0) client.createAuctions(auctionsPerMin, auctionDuration); if (bidsPerMin > 0) client.bidAuctions(bidsPerMin); executorService.execute(client); } LoadTestClient updater = new LoadTestClient(host, tcpPort); testClients.add(updater); updater.updateList(updateIntervalSec); executorService.execute(updater); //Press enter to shut down the loadtest client BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); try { input.readLine(); input.close(); } catch (IOException ex) { logger.error("IO Exception on System Standard Input"); } shutdown(); }
6
public boolean setSize(int players, int mapSize) { boolean condition = false; //added for validation if(players >= 2 && players <= 4) { while(mapSize < 5 || mapSize > 50) { System.out.print("Size of map should be between 5 and 50. Please re-enter size : "); mapSize = keyboard.nextInt(); } condition = true; } else if(players >=5 && players <= 8) { while(mapSize<8 || mapSize > 50) { System.out.println("Size of map should be between 8 and 50. Please re-enter size : "); mapSize = keyboard.nextInt(); } condition = true; } colorMapping = new int[mapSize][mapSize]; Map.size = mapSize; return condition; }
8
private boolean loadNetwork(String file, boolean forDraw){ boolean loaded = false; Network net = null; //Try to load from a file if (file != null){ File f = new File(file); if (f.isFile()){ try{ net = new Network(file); loaded = true; } catch (Exception e){ System.out.println("Warning! Could not load Casandra weights!"); } } } //Otherwise, create a new network if (!loaded){ int inputs = nodeCount(forDraw, true); net = new Network(new int[]{inputs, forDraw ? inputs*2 : inputs*3, nodeCount(forDraw, false)}); } //Validate network size else if (net.inputNodes() != nodeCount(forDraw, true) || net.outputNodes() != nodeCount(forDraw, false)) return false; //Save network if (forDraw){ drawNet = net; drawNet_file = file; } else{ playNet = net; playNet_file = file; } return true; }
8
@Override public Void call() { final String timestamp = this.writer.timestamp.format(new Date()); this.markers.clear(); for (final World world : this.writer.plugin.getServer().getWorlds()) { for (final Ocelot ocelot : world.getEntitiesByClass(Ocelot.class)) { if (!ocelot.isTamed() || !(ocelot.getOwner() instanceof OfflinePlayer)) continue; final OfflinePlayer owner = (OfflinePlayer) ocelot.getOwner(); final Map<String, Object> marker = new HashMap<String, Object>(); marker.put("id", this.getType().id); marker.put("msg", owner.getName()); marker.put("world", ocelot.getLocation().getWorld().getName()); marker.put("x", ocelot.getLocation().getX()); marker.put("y", ocelot.getLocation().getY()); marker.put("z", ocelot.getLocation().getZ()); marker.put("timestamp", timestamp); this.markers.add(marker); } } return null; }
4
public boolean updateModel(Piece piece, PossibleTile pt) { for (Piece p : this.gm.getBoard().getPieces()) { if (p instanceof Pawn) { Pawn pawn = (Pawn) p; pawn.setPossibleToPassant(false); } } Board b = this.gm.getBoard(); if ( b.isWhiteTurn() == piece.isWhite() && b.isWhiteTurn() == this.isWhite ) { ArrayList<PossibleTile> tiles = new ArrayList<PossibleTile>(); tiles.add(new PossibleTile(piece.getX(), piece.getY(), piece)); tiles.add(pt); b.nextTurn(); b.removePiece(piece); Piece clone = pt.getOriginalPiece(); clone.setX(pt.getX()); clone.setY(pt.getY()); clone.setSelected(false); b.addPiece(clone); if (pt.hasPieceToRemove()) { Piece removedPiece = pt.getRemovePiece(); b.removePiece(removedPiece); this.gm.resetMoveRule(); if (piece instanceof Pawn) { this.gm.resetMoveRule(); if (!((Pawn)clone).canPromote()) { b.addMove(new int[] {clone.getUID(), pt.getX(), pt.getY(), removedPiece.getUID()}); } } else { b.addMove(new int[] {clone.getUID(), pt.getX(), pt.getY()}); } } else { if (piece instanceof Pawn) { this.gm.resetMoveRule(); if (!((Pawn)clone).canPromote()) { b.addMove(new int[] {clone.getUID(), pt.getX(), pt.getY()}); } } else { this.gm.increaseMoveRule(); b.addMove(new int[] {clone.getUID(), pt.getX(), pt.getY()}); } } this.gm.getBoard().setPrevTiles(tiles); this.gm.updateBoard(b, false); return true; } return false; }
9
public static boolean deletEvent(String eventName) { ResultSet rs=null; Connection con=null; PreparedStatement ps=null; boolean result=true; try{ String sql="DELETE FROM EVENTS WHERE UPPER(NAME)=(?)"; con=ConnectionPool.getConnectionFromPool(); ps=con.prepareStatement(sql); ps.setString(1, eventName.toUpperCase()); ps.executeUpdate(); } catch(Exception ex) { ex.printStackTrace(); } finally{ if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con!=null) { try { ConnectionPool.addConnectionBackToPool(con);; } catch (Exception e) { e.printStackTrace(); } } } return result; }
7
@Override public void draw(Graphics2D g2d) { AffineTransform at = new AffineTransform(); at.translate(loc.x - turrets[upg].getWidth() / 2, loc.y - turrets[upg].getHeight() / 2); if (isFailing()) g2d.drawImage(turrets[0], at, null); else { if (faction == 1) { g2d.drawImage(turrets[upg], at, null); if (hasDragon) { g2d.drawImage(dragonT, (int) loc.x, (int) loc.y - turrets[0].getHeight() / 5 * 4, turrets[0].getWidth() / 6, turrets[0].getHeight() / 2, null); } g2d.drawImage(bHouse, (int) loc.x - turrets[0].getWidth() / 8, (int) loc.y - turrets[1].getHeight() / 3, turrets[0].getWidth() / 4, turrets[0].getHeight() / 4, null); if (hasChurch) { g2d.drawImage(blChurch, (int) loc.x - (turrets[0].getWidth() / 3), (int) loc.y - turrets[0].getHeight() / 2, turrets[0].getWidth() / 4, turrets[0].getHeight() / 3, null); } } else { g2d.drawImage(turrets[upg], at, null); if (hasDragon) { g2d.drawImage(dragonT, (int) loc.x - (turrets[upg].getWidth() / 8), (int) loc.y - turrets[upg].getHeight() / 5 * 4, turrets[upg].getWidth() / 6, turrets[upg].getHeight() / 2, null); } g2d.drawImage(rHouse, (int) loc.x, (int) loc.y - turrets[upg].getHeight() / 3, turrets[upg].getWidth() / 4, turrets[upg].getHeight() / 4, null); if (hasChurch) { g2d.drawImage(reChurch, (int) loc.x - (turrets[upg].getWidth() / 3), (int) loc.y - turrets[upg].getHeight() / 2, turrets[upg].getWidth() / 4, turrets[upg].getHeight() / 3, null); } } } if (this.highlighted) { // need a health bar to indicate they are // highlighted float remHPs = ((float) this.hp / (float) this.hpLimits[upg]) * (float) 100; g2d.setColor(Color.black); g2d.fillRect((int) this.getLoc().x, (int) this.getLoc().y - 35, 100, 5); if (this.hpLimits[upg] / this.hp < 1.5) g2d.setColor(Color.green); else if (this.hpLimits[upg] / this.hp < 3) g2d.setColor(Color.yellow); else g2d.setColor(Color.red); g2d.fillRect((int) this.getLoc().x, (int) this.getLoc().y - 35, (int) remHPs, 5); } }
9
public static synchronized boolean checkConnection() { if (closed) return false; final int timeout = 5000; try { if (conn != null && conn.isValid(timeout)) return true; } catch (SQLException e) { // Consider as broken connection } final String url; { String url_ = "jdbc:mysql://" + Connection.db_hostname + ":" + Connection.db_port + "/" + Connection.db_database + "?user=" + Connection.db_username + "&zeroDateTimeBehavior=convertToNull"; if (Connection.db_password != null && Connection.db_password.length() > 0) url_ += "&password=" + Connection.db_password; url = url_; } java.sql.Connection con = conn; try { con = DriverManager.getConnection(url); try { if (conn != null) conn.close(); } catch (SQLException e) { System.err.println("Error closing existing JDBC: " + e.getLocalizedMessage()); con.close(); return false; } // Set new connection conn = con; return true; } catch (SQLException e) { System.err.println("New JDBC Connection failed: " + e.getLocalizedMessage()); return false; } }
9
public void draw(Graphics page) { planeImage.drawImage(page, xLocation, yLocation);//Draws the plane on the component //Draws the collision Border if(this.getBorderVisibility()) { drawCollisionBorder(page,xLocation,yLocation,planeImage.getWidth(),planeImage.getHeight()); } }
1
private void carregaClientes(){ ClienteDAO daoCliente = new ClienteDAO(); try { listaClientes = daoCliente.listarTodos(); } catch (ErroValidacaoException ex) { Logger.getLogger(frmVenda.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } catch (Exception ex) { Logger.getLogger(frmVenda.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } cbxCliente.removeAllItems(); for(Cliente c : listaClientes){ cbxCliente.addItem(c); } }
3
public void selectIndex(){ if (index >= 0) { if (index > commands.size()) index = commands.size() - 1; if (commands.size() - index >= 0) { log("ConsoleUpClicked"); msg = commands.get(commands.size() - index); } } }
3
private void process(ArrayList<Gridspot> path , int max, pair<Gridspot,Gridspot> a) { ArrayList<Gridspot> revise = new ArrayList<Gridspot>(path); ArrayList<Gridspot> state ; boolean flag = true; assignQuacks(a); Gridspot temp ;//= revise.get(revise.size()-2); for(int i =0; i < path.size(); i++) { temp = revise.get(revise.size()-2-i); int size = revise.size(); for(int u = 0; u < i+1; u++) revise.remove(revise.get(size-u-1)); state = new ArrayList<Gridspot>(revise); temp.pQuack.toArray(); while(temp.sizeQuack() > 0) // Temp is the second to last Gridspot in the path { revise = new ArrayList<Gridspot>(state); pairI<Integer,Gridspot> pair = temp.popTop(); // The pair is the first waypoint on temp if(revise.size()+pair.getL() <= max*3) // if the projected size is less than or equal to max, continue { while(pair.getR() != a.getL()) // while Spot on the waypoint is not the goal, continue { if(!revise.contains(pair.getR())) { revise.add(pair.getR()); pair = pair.getR().popTop(); // move on to the next waypoint // add each element in the path to the list if (pair == null) break; } else { flag = false; break; } } if (flag) { revise.add(a.getL()); _paths.add(revise); // add the paths to the path collection } else flag = true; } } assignQuacks(a); } }
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HttpResponseEvent that = (HttpResponseEvent) o; if (request != null ? !request.equals(that.request) : that.request != null) return false; if (response != null ? !response.equals(that.response) : that.response != null) return false; return true; }
7
@Override public void handle(KeyEvent event) { final KeyCode keyCode = event.getCode(); switch(keyCode) { case UP: if(moveDirection != Direction.DOWN) nextMoveDirection = Direction.UP; break; case DOWN: if(moveDirection != Direction.UP) nextMoveDirection = Direction.DOWN; break; case LEFT: if(moveDirection != Direction.RIGHT) nextMoveDirection = Direction.LEFT; break; case RIGHT: if(moveDirection != Direction.LEFT) nextMoveDirection = Direction.RIGHT; break; } }
8
public void adjustColors(int redOff, int greenOff, int blueOff) { for (int i = 0; i < pallete.length; i++) { int red = pallete[i] >> 16 & 0xff; red += redOff; if (red < 0) { red = 0; } else if (red > 255) { red = 255; } int green = pallete[i] >> 8 & 0xff; green += greenOff; if (green < 0) { green = 0; } else if (green > 255) { green = 255; } int blue = pallete[i] & 0xff; blue += blueOff; if (blue < 0) { blue = 0; } else if (blue > 255) { blue = 255; } pallete[i] = (red << 16) + (green << 8) + blue; } }
7
public void addTreasureBox(double x, double y, double width, double height, String note) { Element treasureBoxModule = doc.createElement("treasurebox"); campaignModule.appendChild(treasureBoxModule); Element coordinatesModule = doc.createElement("coordinates"); treasureBoxModule.appendChild(coordinatesModule); Element xElement = doc.createElement("x"); xElement.appendChild(doc.createTextNode(Double.toString(x))); coordinatesModule.appendChild(xElement); Element yElement = doc.createElement("y"); yElement.appendChild(doc.createTextNode(Double.toString(y))); coordinatesModule.appendChild(yElement); Element widthElement = doc.createElement("width"); widthElement.appendChild(doc.createTextNode(Double.toString(width))); coordinatesModule.appendChild(widthElement); Element heightElement = doc.createElement("height"); heightElement.appendChild(doc.createTextNode(Double.toString(height))); coordinatesModule.appendChild(heightElement); Element noteModule = doc.createElement("note"); noteModule.appendChild(doc.createTextNode(note)); treasureBoxModule.appendChild(noteModule); }
0
private int calculateNeighbourhoodBest(int i, int k, int j){ if(maximum){ return maxBest(i,j,k); }else{ return minBest(i,j,k); } }
1
public String toString() { try { return this.toJSON().toString(4); } catch (JSONException e) { return "Error"; } }
1
public String getPlayerClass( Player p ) { if ( perm == null ) { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration( net.milkbowl.vault.permission.Permission.class ); if ( permissionProvider == null ) { System.out.println( "Vault plugin was not detected. Please install it or else we can not properly format chat." ); } else { perm = permissionProvider.getProvider(); } } if ( perm != null ) { String[] groups; try { groups = perm.getPlayerGroups( p ); } catch ( UnsupportedOperationException e ) { getLogger().info( "Valut Exception: " + e.getMessage() ); groups = new String[0]; } List<String> classes = getConfig().getStringList( "classes" ); if ( groups.length > 1 ) for ( String grp : groups ) { if ( classes.contains( grp.toLowerCase() ) ) { return grp; } } } return getConfig().getString( "global.defaultClass", "Awakened" ); }
7
@Override public void Write(IOClient p, Server server) { PacketPrepareEvent event = new PacketPrepareEvent(p, this, server); server.getEventSystem().callEvent(event); if (event.isCancelled()) return; Player player; if (p instanceof Player) { player = (Player)p; } else return; try { ByteBuffer bb = ByteBuffer.allocate(7); bb.order(ByteOrder.BIG_ENDIAN); bb.put(ID); bb.putShort(player.getLevel().width); bb.putShort(player.getLevel().height); bb.putShort(player.getLevel().depth); player.WriteData(bb.array()); } catch (IOException e) { e.printStackTrace(); } }
3
public CheckResultMessage checkFileName() { return report.checkFileName(); }
0
public void rotarAdelanteIzquierda() { if (direccion.equals(Direccion.derecha)) { rotar(tipoTrans.enZ, 135); } else if (direccion.equals(Direccion.adelante)) { rotar(tipoTrans.enZ, 45); } else if (direccion.equals(Direccion.atras)) { rotar(tipoTrans.enZ, -135); } else if (direccion.equals(Direccion.izquierda)) { rotar(tipoTrans.enZ, -45); } else if (direccion.equals(Direccion.atDer)) { rotar(tipoTrans.enZ, 180); } else if (direccion.equals(Direccion.atIzq)) { rotar(tipoTrans.enZ, -90); } else if (direccion.equals(Direccion.adDer)) { rotar(tipoTrans.enZ, 90); } direccion = Direccion.adIzq; }
7
public void setFrequency (CommandSender sender, String inputString) throws IOException{ if (new File("plugins/CakesMinerApocalypse/").mkdirs()) { System.out.println("Frequencies file created"); } File myFile = new File("plugins/CakesMinerApocalypse/frequencies.txt"); if (myFile.exists()){ Scanner inputFileCheck = new Scanner(myFile); int j = 0; while (inputFileCheck.hasNext()) { inputFileCheck.nextLine(); j++; } int size = (j + 1) / 2; String[] nameArray = new String[size]; String[] circleArray = new String[size]; inputFileCheck.close(); Scanner inputFile = new Scanner(myFile); for (int i = 0; i < size; i++) { nameArray[i] = inputFile.nextLine(); circleArray[i] = inputFile.nextLine(); } boolean isInFile = false; for (int i = 0; i < size; i++) { if (nameArray[i].equalsIgnoreCase(sender.getName())){ circleArray[i] = inputString; sender.sendMessage("Frequency " + inputString + " set successfully!"); isInFile = true; } } inputFile.close(); PrintWriter outputFile = new PrintWriter("plugins/CakesMinerApocalypse/frequencies.txt"); for (int i = 0; i < size; i++) { outputFile.println(nameArray[i]); outputFile.println(circleArray[i]); } if (!isInFile){ outputFile.println(sender.getName()); outputFile.println(inputString); } outputFile.close(); } else{ PrintWriter outputFile = new PrintWriter("plugins/CakesMinerApocalypse/frequencies.txt"); outputFile.println(sender.getName()); outputFile.println(inputString); sender.sendMessage("frequency " + inputString + " set successfully!"); outputFile.close(); } }
8
public ArrayList<String> findAllDictWords(ArrayList<String> excluded){ //iterates through all words in the dictionary, checking them against excluded and checking if they are on the board Iterator<String> iter=dict.iterator(); String word; ArrayList<String> foundWords=new ArrayList<String>(); boolean isExcluded; while(iter.hasNext()){ word=iter.next(); //check against excluded isExcluded=false; for(int x=0;x<excluded.size();x++){ if(excluded.get(x).equals(word)){ isExcluded=true; break;//stop checking the excluded list } } if(!isExcluded){ if(gB.isOnBoard(word)){ foundWords.add(word); } } } return foundWords; }
5
public void paintComponent(Graphics g) { Rectangle visible = getVisibleRect(); int height = ARROW_LENGTH + icons[0].getIconHeight(); int max = icons.length - 1 - visible.y / height; int min = icons.length - 1 - (visible.y + visible.height) / height; try { min = Math.max(min, 0); g = g.create(); g.translate(0, height * (icons.length - 1 - max)); for (int i = max; i >= min; i--) { drawArrow(g); drawIcon(g, icons[i]); } g.dispose(); } catch (Throwable e) { System.err.println(e); } }
2
public String dealWith(Long testObject) { if (testObject > 3) { return "大于3退出了!"; } return "全部通过了!"; }
1
private void writeColFields( Column col ) { flds.append( SPACE ); flds.append( "private " ); String fldType = col.getFldType(); flds.append( fldType ); flds.append( makeSpace( FLD_SPACE, fldType ) ); flds.append( col.getFldName() ); flds.append( ";" ); if ( col.getComments() != null ) { flds.append( makeSpace( 20, col.getFldName() ) ); flds.append( col.getComments() ); } flds.append( "\n" ); }
1
@Override public void setupTest(JavaSamplerContext context) { super.setupTest(context); String hbaseZK = context.getParameter("hbase.zookeeper.quorum"); conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", hbaseZK); if (table == null) { String tableName = context.getParameter("tableName"); byte[] tableNamebyte = tableName.getBytes(); boolean autoFlush = Boolean.valueOf(context.getParameter("autoFlush")); long writeBufferSize = Long.valueOf(context.getParameter("writeBufferSize")); int poolSize = Integer.parseInt(context.getParameter("poolSize")); try { table = JMeterHTablePool.getinstancePool(conf,poolSize,tableNamebyte,autoFlush,writeBufferSize).tablePool.getTable(tableName); } catch (Exception e) { System.out.println("htable pool error"); } } if( methedType == null ){ methedType = context.getParameter("putOrget"); } if( keyNumLength == 0){ keyNumLength = Integer.parseInt(context.getParameter("keyNumLength")); } if(cfs == null){ String cf = context.getParameter("cf"); cfs = cf.split(","); } if( qualifiers == null ){ String qualifier = context.getParameter("qualifier"); qualifiers = qualifier.split(","); } if( values == null ){ String valueLength = context.getParameter("valueLength"); values = Strings.repeat('v', Integer.parseInt(valueLength)); } if( writeToWAL == true ){ writeToWAL = Boolean.valueOf(context.getParameter("writeToWAL")); } if( keyRondom == true ){ keyRondom = Boolean.valueOf(context.getParameter("keyRondom")); } }
9