text
stringlengths
14
410k
label
int32
0
9
public CheckResultMessage checkF01(int day) { int r1 = get(20, 5); int c1 = get(21, 5); int r2 = get(27, 5); int c2 = get(28, 5); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue(r1, c1 + day, 5).compareTo( getValue(r2 + 2 + day, c2 + 2, 6))) { return error("支付机构汇总报表<" + fileName + ">向备付金银行缴存现金形式备付金 F01 = H03:" + day + "日错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if (0 != getValue1(r1, c1 + day, 5).compareTo( getValue1(r2 + 2 + day, c2 + 2, 6))) { return error("支付机构汇总报表<" + fileName + ">向备付金银行缴存现金形式备付金 F01 = H03:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">向备付金银行缴存现金形式备付金 F01 = H03:" + day + "日正确"); }
5
public LsCommand execute() throws IOException { Path path = Paths.get(ls.getPath()); LsVisitor visitor = new LsVisitor(path, ls.getGlob()); Files.walkFileTree(path, Collections.EMPTY_SET, ls.getDepth(), visitor); this.listing = visitor.getListing(); // sort listing if(ls.getSortOrder().size() > 0) { List<Comparator> comparators = new ArrayList<Comparator>(); Iterator<Ls.OrderBy> it = ls.getSortOrder().iterator(); while(it.hasNext()) { Ls.OrderBy orderBy = it.next(); if(orderBy.getProperty().equals("name")) { if(orderBy.getOrder() == SortOrder.DESC) { comparators.add(desc(SORT_BY_NAME)); } else { comparators.add(SORT_BY_NAME); } } else if(orderBy.getProperty().equals("size")) { if(orderBy.getOrder() == SortOrder.DESC) { comparators.add(desc(SORT_BY_SIZE)); } else { comparators.add(SORT_BY_SIZE); } } else if(orderBy.getProperty().equals("created")) { if(orderBy.getOrder() == SortOrder.DESC) { comparators.add(desc(SORT_BY_CREATED)); } else { comparators.add(SORT_BY_CREATED); } } } sortBy(getComparator(comparators.toArray(new Comparator[comparators.size()]))); } return this; }
8
public boolean canMove(){ int rangee = -1; for(boolean bool[] : tetrominoes.get(tetrominoes.size()-1).getEmplacement().getCoordoneeJeu()){ rangee++; for(int x=0; x< coordonneJeu.getNombreColonne(); x++) if(true==bool[x]&& bool[x]== !coordonneJeu.IsEmpty(x, rangee)){ return false; } } return true; }
4
private void pause() { fallTimer.stop(); paused = true; this.add(resumeButton); this.remove(gameGrid); this.remove(holdGrid); for (int i = 0; i < QUEUE_SIZE; ++i) { this.remove(inQueueGrid[i]); } repaintGrid(); this.add(resumeButton); }
1
Manager() { LOGGER.log(Level.INFO, "Loading profiles."); profiles = FrolfUtil.loadProfiles(); currentProfile = null; try { LOGGER.log(Level.INFO, "Loading courses."); courses = FrolfUtil.loadCourseCatalog(); LOGGER.log(Level.INFO, "Loading discs."); discs = FrolfUtil.loadDiscs(); } catch (IOException e) { e.printStackTrace(); } // TODO discs should be a part of the profile definition LOGGER.log(Level.INFO, "Loading player bags."); for (String username : profiles.keySet()) { LOGGER.log(Level.INFO, "Loading bag for " + username); ArrayList<String> discNames = FrolfUtil.readDiscsForUser(username); for (String discName : discNames) { profiles.get(username).addDiscToBag(discs.getDisc(discName)); } } currentProfile = profiles.get(defaultProfile); }
3
public static void main(String[] args) { // First we set up the BasicDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up data source."); DataSource dataSource = setupDataSource("jdbc:mysql://localhost:3306/uiip"); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery("select * from studenti;"); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while(rset.next()) { for(int i=1;i<=numcols;i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch(SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch(Exception e) { } try { if (stmt != null) stmt.close(); } catch(Exception e) { } try { if (conn != null) conn.close(); } catch(Exception e) { } } }
9
private void onLeftReleased(){ if(selectedNode == null){ for(Node node : this.getNodes()){ double radiusSquared = node.size * node.size, dx = mouseX - node.position.x, dy = mouseY - node.position.y, distSquared; distSquared = dx * dx + dy * dy; if(distSquared <= radiusSquared){ selectedNode = node; selectedIndicator.select(node); return; } } } else{ // set target for selectedNode for(Node node : this.getNodes()){ if(node != selectedNode){ double radiusSquared = node.size * node.size, dx = mouseX - node.position.x, dy = mouseY - node.position.y, distSquared; distSquared = dx * dx + dy * dy; if(distSquared <= radiusSquared){ this.growTowards(selectedNode, node); return; } } } } }
6
public void printTopWords(int k, String betaFile) { double loglikelihood = calculate_log_likelihood(); System.out.format("Final Log Likelihood %.3f\t", loglikelihood); String filePrefix = betaFile.replace("topWords.txt", ""); debugOutput(filePrefix); Arrays.fill(m_sstat, 0); System.out.println("print top words"); for (_Doc d : m_trainSet) { for (int i = 0; i < number_of_topics; i++) m_sstat[i] += m_logSpace ? Math.exp(d.m_topics[i]) : d.m_topics[i]; } Utils.L1Normalization(m_sstat); try { System.out.println("beta file"); PrintWriter betaOut = new PrintWriter(new File(betaFile)); for (int i = 0; i < topic_term_probabilty.length; i++) { MyPriorityQueue<_RankItem> fVector = new MyPriorityQueue<_RankItem>( k); for (int j = 0; j < vocabulary_size; j++) fVector.add(new _RankItem(m_corpus.getFeature(j), topic_term_probabilty[i][j])); betaOut.format("Topic %d(%.3f):\t", i, m_sstat[i]); for (_RankItem it : fVector) { betaOut.format("%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value); System.out.format("%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value); } betaOut.println(); System.out.println(); } betaOut.flush(); betaOut.close(); } catch (Exception ex) { System.err.print("File Not Found"); } }
9
public static Language getInstance() { return language; }
0
@Override protected void fireEditingStopped() { super.fireEditingStopped(); }
0
public boolean stem() { int v_1; int v_2; int v_3; int v_4; // (, line 72 // do, line 74 v_1 = cursor; lab0: do { // call mark_regions, line 74 if (!r_mark_regions()) { break lab0; } } while (false); cursor = v_1; // backwards, line 75 limit_backward = cursor; cursor = limit; // (, line 75 // do, line 76 v_2 = limit - cursor; lab1: do { // call main_suffix, line 76 if (!r_main_suffix()) { break lab1; } } while (false); cursor = limit - v_2; // do, line 77 v_3 = limit - cursor; lab2: do { // call consonant_pair, line 77 if (!r_consonant_pair()) { break lab2; } } while (false); cursor = limit - v_3; // do, line 78 v_4 = limit - cursor; lab3: do { // call other_suffix, line 78 if (!r_other_suffix()) { break lab3; } } while (false); cursor = limit - v_4; cursor = limit_backward; return true; }
8
public double getBalance(){ return this.balance; }
0
public synchronized void open(Decoder decoder) throws JavaLayerException { if (!isOpen()) { this.decoder = decoder; openImpl(); setOpen(true); } }
1
public final String getCancelView() { // Default to successView if cancelView is invalid if (this.cancelView == null || this.cancelView.length() == 0) { return getSuccessView(); } return this.cancelView; }
2
public static String multiLineToolTip(int len, String input) { String s = ""; int length = len; if (input == null) return ""; if (input.length() < length) return input; int i = 0; int lastSpace = 0; while (i + length < input.length()) { String temp = input.substring(i, i + length); lastSpace = temp.lastIndexOf(" "); s += temp.substring(0, lastSpace) + "<br>"; i += lastSpace + 1; } s += input.substring(i, input.length()); s = "<html>" + s + "</html>"; return s; }
3
public ArrayList<Assessoria> consultar(String id){ ArrayList<Assessoria> ass = new ArrayList<>(); try { if(id.equals("")){ sql="SELECT * FROM tb_assessoria;"; }else{ sql="SELECT * FROM tb_assessoria WHERE cod = '"+id+"';"; } ConsultarSQL(sql, true); while (rs.next()) { Assessoria a = new Assessoria(); a.setId(rs.getString("id")); a.setCod(rs.getInt("cod")); a.setNome(rs.getString("nome")); a.setCidade(rs.getString("cidade")); a.setBairro(rs.getString("bairro")); a.setEndereco(rs.getString("endereco")); a.setNome_advogado(rs.getString("nome_advogado")); a.setTelefone_assessoria(rs.getString("telefone")); System.out.println("Ass: "+rs.getString("nome")); ass.add(a); } } catch (SQLException ex) { Logger.getLogger(DaoAssessoria.class.getName()).log(Level.SEVERE, null, ex); } return ass; }
3
public static void gerarArquivoRedeNeural(String nome, MultiLayerPerceptron rna, Double[] entradas) { try { FileWriter fileWriter = new FileWriter(nome); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); double discretizacao = 0.05; for (int i = 0; i < 20; i++) { rna.inicializarPesos(entradas.length); rna.executar(entradas); for (int j = 0; j < entradas.length; j++) { bufferedWriter.write(entradas[j].toString().replace('.', ',') + ";"); entradas[j] = entradas[j] + discretizacao; } for (Double saida : rna.getCamadaDeSaida().getVetorSaida()) { bufferedWriter.write(saida.toString().replace('.', ',') + ";"); } bufferedWriter.write("\n"); } for (int k = 0; k < rna.getCamadasIntermediarias().size(); k++) { bufferedWriter.write("\nPESOS CAMADA INTERMEDIARIA " + (k + 1) + "\n"); Double[][] pesos = rna.getCamadasIntermediarias().get(k) .getPesos(); for (int i = 0; i < pesos.length; i++) { for (int j = 0; j < pesos[i].length; j++) { bufferedWriter.write("W" + (i + 1) + (j + 1) + "= " + pesos[i][j].toString().replace('.', ',') + ";"); } } bufferedWriter.write("\n"); } bufferedWriter.write("\nPESOS CAMADA DE SAIDA\n"); Double[][] pesos = rna.getCamadaDeSaida().getPesos(); for (int i = 0; i < pesos.length; i++) { for (int j = 0; j < pesos[i].length; j++) { bufferedWriter.write("W" + (i + 1) + (j + 1) + "= " + pesos[i][j].toString().replace('.', ',') + ";"); } } bufferedWriter.write("\n"); bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
9
public void play() { try { new Thread() { public void run() { clip.setFramePosition(0); clip.start(); } }.start(); } catch (Throwable e) { e.printStackTrace(); } }
1
@EventHandler public void IronGolemResistance(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.Resistance.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getIronGolemConfig().getBoolean("IronGolem.Resistance.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, plugin.getIronGolemConfig().getInt("IronGolem.Resistance.Time"), plugin.getIronGolemConfig().getInt("IronGolem.Resistance.Power"))); } }
6
private void createFile(){ if ((nameTextField != null) && (pathFileTextField != null)){ algorythmFile = new AlgorythmFile( nameTextField.getText(), algoTypeComboBox.getSelectedItem().toString(), file ); } else JOptionPane.showMessageDialog(this, "Error! File hasn't added to base!", "Data Transfer", JOptionPane.ERROR_MESSAGE); }
2
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random) { if (!par1World.isRemote) { if (par1World.getBlockLightValue(par2, par3 + 1, par4) < 4 && Block.lightOpacity[par1World.getBlockId(par2, par3 + 1, par4)] > 2) { par1World.setBlockWithNotify(par2, par3, par4, Block.dirt.blockID); } else if (par1World.getBlockLightValue(par2, par3 + 1, par4) >= 9) { for (int var6 = 0; var6 < 4; ++var6) { int var7 = par2 + par5Random.nextInt(3) - 1; int var8 = par3 + par5Random.nextInt(5) - 3; int var9 = par4 + par5Random.nextInt(3) - 1; int var10 = par1World.getBlockId(var7, var8 + 1, var9); if (par1World.getBlockId(var7, var8, var9) == Block.dirt.blockID && par1World.getBlockLightValue(var7, var8 + 1, var9) >= 4 && Block.lightOpacity[var10] <= 2) { par1World.setBlockWithNotify(var7, var8, var9, this.blockID); } } } } }
8
int classend(int poffset) { switch (p.luaByte(poffset++)) { case L_ESC: if (poffset == p.length()) { error("malformed pattern (ends with %)"); } return poffset + 1; case '[': if (p.luaByte(poffset) == '^') poffset++; do { if (poffset == p.length()) { error("malformed pattern (missing ])"); } if (p.luaByte(poffset++) == L_ESC && poffset != p.length()) poffset++; } while (p.luaByte(poffset) != ']'); return poffset + 1; default: return poffset; } }
8
public String Imprimir() { String impresion=""; for (int i=0; i < matriz.length; i++) { for (int j =0; j < matriz[0].length; j++) { if(i==j) { impresion +="X"; } else { impresion +="_"; } } impresion +="\n"; } return impresion; }
3
@Test public void evaluatePostfix6() throws DAIndexOutOfBoundsException, DAIllegalArgumentException, NumberFormatException, NotEnoughOperandsException, BadPostfixException { try { String whatItStartsAs = "23+59+2/3++952+-89*-+"; postfix.addLast("5"); postfix.addLast("9"); postfix.addLast("+"); postfix.addLast("2"); postfix.addLast("/"); postfix.addLast("3"); postfix.addLast("+"); postfix.addLast("+"); postfix.addLast("9"); postfix.addLast("5"); postfix.addLast("2"); postfix.addLast("+"); postfix.addLast("-"); postfix.addLast("8"); postfix.addLast("9"); postfix.addLast("*"); postfix.addLast("-"); postfix.addLast("+"); String result = calc.evaluatePostfix(postfix); String expected = "-55.0"; assertEquals(expected, result); } catch (DAIndexOutOfBoundsException e) { throw new DAIndexOutOfBoundsException(); } catch (DAIllegalArgumentException e) { throw new DAIllegalArgumentException(); } catch (NumberFormatException e) { throw new NumberFormatException(); } catch (NotEnoughOperandsException e) { throw new NotEnoughOperandsException(); } catch (BadPostfixException e) { throw new BadPostfixException(); } }
5
public int partition(T[] data, int length, int start, int end) { // TODO Auto-generated method stub if(data == null || length <=0 || start < 0 || end >= length){ throw new IndexOutOfBoundsException("argument error!"); } Random r = new Random(); //nextInt(0,n+1) create an int in [0, n+1) == [0, n]; int index = r.nextInt(end-start+1)+start; swap(data , index , end); int small = start; for(int i = start ; i <= end ; i++){ if(data[i].compareTo(data[end]) < 0){ if( small != i){ swap(data, small , i); } small++; } } swap(data , small , end); return small; }
7
public static void main(String[] args) { int length = Integer.parseInt(JOptionPane.showInputDialog("Input the Number (2k - 1)")); int intArray[][] = new int[length][length]; if (length % 2 != 0) { makeArray(intArray); JOptionPane.showMessageDialog(null, "Take a look at the console!"); output(intArray); snake(intArray); } else { JOptionPane.showMessageDialog(null, "Wrong Number"); } }
1
public static void main(String[] args) { MyTargetTest myTarget = new MyTargetTest(); myTarget.target(); }
0
public static synchronized String checkOneLink(URL linkURL) { // System.out.printf("LinkChecker.checkLink(%s)%n", linkURL); try { final String canonURLString = uc.canonicalize(linkURL.toString()); if (cache.contains(canonURLString)) return "(already checked)"; cache.add(canonURLString); linkURL = new URL(canonURLString); // Open it; if the open fails we'll likely throw an exception URLConnection luf = linkURL.openConnection(); String proto = linkURL.getProtocol(); if (proto.equals("http") || proto.equals("https")) { HttpURLConnection huf = (HttpURLConnection)luf; int response = huf.getResponseCode(); if (response == -1) return "Server error: bad HTTP response"; if (Utilities.isRedirectCode(response)) { String newUrl = huf.getHeaderField("location"); // XXX?? return "(redirect to " + newUrl + ")" + ' ' + checkOneLink(new URL(newUrl)); } return huf.getResponseCode() + " " + huf.getResponseMessage(); } else if (proto.equals("file")) { // Only useful on localhost return "(File; ignored)"; } else return "(non-HTTP; ignored)"; } catch (SocketException e) { return "DEAD: " + e.toString(); } catch (IOException e) { return "DEAD"; } }
8
public String getBeforeIndex(byte type, int index) { if (index < 0 || index > getText().length() - 1) { return null; } switch (type) { case CHARACTER: if (index == 0) { return null; } return getText().substring(index - 1, index); case WORD: { String s = this.getText(); BreakIterator words = BreakIterator.getWordInstance(); words.setText(s); int end = findWordLimit(index, words, PREVIOUS, s); if (end == BreakIterator.DONE) { return null; } int start = words.preceding(end); if (start == BreakIterator.DONE) { return null; } return s.substring(start, end); } case SENTENCE: { String s = getText(); BreakIterator sentence = BreakIterator.getSentenceInstance(); sentence.setText(s); int end = sentence.following(index); end = sentence.previous(); int start = sentence.previous(); if (start == BreakIterator.DONE) { return null; } return s.substring(start, end); } default: return null; } }
9
public QuickCodePopupMenu(SourceFileEditor editor) { super("Quick Code"); this.editor = editor; // Construct Menu items); JMenu opCodes = new JMenu("Insert OpCode"); // OpCode menu items are auto-generated later on JMenu statements = new JMenu("Build"); JMenuItem includeDirective = new JMenuItem("Include directive"); JMenuItem macro = new JMenuItem("Macro"); JMenuItem macroCall = new JMenuItem("Macro Call"); JMenuItem label = new JMenuItem("Label"); JMenuItem data = new JMenuItem("Data value"); JMenuItem string = new JMenuItem("String value"); JMenuItem comment = new JMenuItem("Comment"); // Add menu items add(opCodes); // Loop through OpCodes and create menu items for(final OpCode opCode : OpCode.values()) { JMenuItem opCodeMenuItem = new JMenuItem(opCode.name()); opCodeMenuItem.setToolTipText(opCode.getDescription()); opCodeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildOpCodeStatement(opCode); if(statement != null) { insertTextAtCaret(statement); } } }); opCodes.add(opCodeMenuItem); } add(statements); statements.add(includeDirective); statements.addSeparator(); statements.add(macro); statements.add(macroCall); statements.addSeparator(); statements.add(label); statements.add(data); statements.add(string); statements.addSeparator(); statements.add(comment); // Add listeners includeDirective.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildIncludeDirective(); if(statement != null) { insertTextAtCaret(statement); } } }); macro.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildMacro(); if(statement != null) { insertTextAtCaret(statement); } } }); macroCall.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildMacroCall(); if(statement != null) { insertTextAtCaret(statement); } } }); label.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildLabel(); if(statement != null) { insertTextAtCaret(statement); } } }); data.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildData(); if(statement != null) { insertTextAtCaret(statement); } } }); string.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildString(); if(statement != null) { insertTextAtCaret(statement); } } }); comment.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String statement = buildComment(); if(statement != null) { insertTextAtCaret(statement); } } }); }
9
@Override public Object getValueAt(int row, int col) { Time_Sheet vo = vos.get(row); switch (col) { case 0: return vo.getPosition().getName(); case 1: return vo.getFireman().getFirstName() + " " + vo.getFireman().getLastName(); case 2: date.setTimeInMillis(vo.getStartTime().getTime()); return "" + date.get(Calendar.DAY_OF_MONTH)+"/"+(date.get(Calendar.MONTH)+1)+" " + MyUtil.p0(date.get(Calendar.HOUR_OF_DAY)) + ":" + MyUtil.p0(date.get(Calendar.MINUTE)); case 3: date.setTimeInMillis(vo.getEndTime().getTime()); return "" + date.get(Calendar.DAY_OF_MONTH)+"/"+(date.get(Calendar.MONTH)+1)+" " + MyUtil.p0(date.get(Calendar.HOUR_OF_DAY)) + ":" + MyUtil.p0(date.get(Calendar.MINUTE)); case 4: int hours = 0; try { hours = hoursCalculator.getHoursForTimeSheeet(vo); } catch (SQLException ex) { Logger.getLogger(ViewObjectTimeSheetTableModel.class.getName()).log(Level.SEVERE, null, ex); } return hours; case 5: if(vo.getAcceptedByTeamleaderId()!= 0){ return true; }else{ return false; } } return null; }
8
public void doNewGame(){}
0
private void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(outputStream); pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (header == null || header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (header != null) { for (String key : header.keySet()) { String value = header.get(key); pw.print(key + ": " + value + "\r\n"); } } pw.print("Connection: keep-alive\r\n"); if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw); } else { sendAsFixedLength(outputStream, pw); } outputStream.flush(); safeClose(data); } catch (IOException ioe) { // Couldn't write? No can do. } }
9
private double getMaxValue(Angle angle, double time, double timeStep, double epsilon, double delta, FirstOrderIntegrator integrator, double[] initialState) { double max = 0; double timeOfMax = 0; double t = timeStep; while (t <= time){ if (stop) { return 0; } t+=10*timeStep; double[] finalState; finalState = new double[] { 0, 0, 0, 0, 0, 0, 0 }; FirstOrderDifferentialEquations ode = new LibrationODE(1000, epsilon, delta, 0.001078011072); integrator.integrate(ode, 0.0, initialState, t, finalState); double angleToPlot = AngleFactory.create(finalState, angle); if (angleToPlot >= max) { max = angleToPlot; timeOfMax = t; } } t = max(timeOfMax - 20, 0.0); while (t <= min(time, timeOfMax + 20)){ if (stop) { return 0; } t+=timeStep; double[] finalState; finalState = new double[] { 0, 0, 0, 0, 0, 0, 0 }; FirstOrderDifferentialEquations ode = new LibrationODE(1000, epsilon, delta, 0.001078011072); integrator.integrate(ode, 0.0, initialState, t, finalState); double angleToPlot = AngleFactory.create(finalState, angle); if (angleToPlot >= max) { max = angleToPlot; timeOfMax = t; } } return max; }
6
private void handleAwayStatusResponse(int code) { boolean isAway = (code == RPL_NOWAWAY); if (serverEventsListener != null) serverEventsListener.awayStatusChanged(isAway); for (ChannelEventsListener listener : channelEventsListeners) listener.awayStatusChanged(isAway); for (PrivateMessagingListener listener : privateMessagingListeners) listener.awayStatusChanged(isAway); }
3
public WorldListener(TotalPermissions p) { plugin = p; }
0
@Override public InputStream getInputStream() { try { boolean spawn=true; if(!this.downloading) { this.downloading=true; if(song.delay()==-1) spawn=false; if(song.save()) { OutputStream[] os=new OutputStream[2]; os[0]=this.out; os[1]=new FileOutputStream(song.fileName()); this.song.download(os,spawn); } else { this.song.download(this.out,spawn); } } if(spawn) Thread.sleep(song.delay()); return new GmByteInputStream(out,(int)song.getLength()); //return Gs.cache.getInputStream(song.getId()); } catch (Exception e) { PMS.debug("GSPMSSong exception occured "+e.toString()); return null; } }
5
public void setVertex1(final int x, final int y, final int z) { if (this.x1 != null && this.y1 != null && this.z1 != null && this.x1 == x && this.y1 == y && this.z1 == z) return; this.x1 = x; this.y1 = y; this.z1 = z; this.refresh(); }
6
public void creeper(Boolean mode){ if (mode != null){ creeper = mode; }else{ creeper = true; } }
1
public P335B() { Scanner sc = new Scanner(System.in); s = sc.next(); final int N = s.length(); markPrev = new int[101]; markCurr = new int[101]; for (int i = 0; i < 101; i++) { markPrev[i] = markCurr[i] = -1; } next = new ArrayList<ArrayList<Link>>(); for (int i = 0; i < 101; i++) { next.add(new ArrayList<Link>()); } for (int i = 0; i < 26; i++) { letterPos.add(new TreeSet<Integer>()); } for (int i = 0; i < N; i++) { process(i); if (markPrev[100] >= 0) { break; } } int length = 0; for (int i = 100; i >= 1; i--) { if (markPrev[i] >= 0) { length = i; break; } } Link link = getTail(length); char[] result = new char[length]; int len = length; int pos = link.pos; result[0] = result[length-1] = s.charAt(pos); for (int i = 1; i < (length+1)/2; i++) { len -= 2; link = getLink(len, link.index); pos = link.pos; result[i] = result[length-i-1] = s.charAt(pos); } for (int i = 0; i < length; i++) { System.out.printf("%c", result[i]); } System.out.println(); }
9
public static Graph wireScaleFreeBA( Graph g, int k, Random r ) { final int nodes = g.size(); if( nodes <= k ) return g; // edge i has ends (ends[2*i],ends[2*i+1]) int[] ends = new int[2*k*(nodes-k)]; // Add initial edges from k to 0,1,...,k-1 for(int i=0; i < k; i++) { g.setEdge(k,i); ends[2*i]=k; ends[2*i+1]=i; } int len = 2*k; // edges drawn so far is len/2 for(int i=k+1; i < nodes; i++) // over the remaining nodes { for (int j=0; j < k; j++) // over the new edges { int target; do { target = ends[r.nextInt(len)]; int m=0; while( m<j && ends[len+2*m+1]!=target) ++m; if(m==j) break; // we don't check in the graph because // this wire method should accept graphs // that already have edges. } while(true); g.setEdge(i,target); ends[len+2*j]=i; ends[len+2*j+1]=target; } len += 2*k; } return g; }
8
int[] getCentromereSortOrder() { int[] centro; if (haplostruct.length==2) { //bivalent if (rand.nextBoolean()) centro = new int[] {0,0,1,1}; else centro = new int[] {1,1,0,0}; } else { //parallel multivalent (Quadrivalent overrides this method) int[] chr = tools.shuffleArray(Tools.seq(haplostruct.length)); /* for a 4-valent: {a,b,c,d}, 6-valent: {a,b,c,d,e,f) etc * with a:d = randomized 0:3 or a:f = randomized 0:5 * The first meiotic division separates ab/cd, abc/def etc: */ int[][] gam = new int[4][haplostruct.length/2]; /* gam[0..4] are the 4 gametes and will contain the ORDERED * sets of centromere alleles */ for (int p=0; p<haplostruct.length/2; p++) { gam[0][p] = chr[p]; gam[1][p] = chr[p]; gam[2][p] = chr[p+haplostruct.length/2]; gam[3][p] = chr[p+haplostruct.length/2]; } /* we have now for 4-valent: { {a,b}, {a,b}, {c,d}, {c,d} }, * for 6-valent: { {a,b,c}, {a,b,c}, {d,e,f}, {d,e,f} } * and similar for higher multivalents */ // randomize the order in each gamete: for (int g=0; g<4; g++) { gam[g] = tools.shuffleArray(gam[g]); } //next, put gam[0..3] consecutively into centro: centro = new int[2*haplostruct.length]; for (int g=0; g<4; g++) { System.arraycopy(gam[g], 0, centro, g*(centro.length/4), centro.length/4); } } //quadrivalent or higher return centro; } //getCentromereSortOrder
5
@Override public void paintBorder(Graphics g) { if (paintBorder) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(color); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Area area = new Area(shape); for (int i = 1; i <= thickness; i++) { float scaleI; scaleI = ((float) i) / thickness; if (i == pVal || i == pVal - 1 || i == pVal + 1) { g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER)); } else { g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, scaleI * pVal / thickness)); } AffineTransform trans = new AffineTransform(); float scaleS = scaleI * left + scale; trans.scale(scaleS, scaleS); trans.translate(thickness - i, thickness - i); Area drawArea = area.createTransformedArea(trans); g2.draw(drawArea); } if (pTimer.isRunning() && ++pVal == thickness) { pTimer.stop(); } g2.dispose(); } }
7
public boolean prayer() { if (playerLevel[playerPrayer] >= prayer[1]) { if (actionTimer == 0 && prayer[0] == 1 && playerEquipment[playerWeapon] >= 1) { //actionAmount++; prayer[0] = 2; } if (actionTimer == 0 && prayer[0] == 2) { deleteItem(prayer[4], prayer[5], playerItemsN[prayer[5]]); addSkillXP((prayer[2] * prayer[3]), playerPrayer); sendMessage("You bury the bones."); resetPR(); } } else { sendMessage("You need "+prayer[1]+" "+statName[playerPrayer]+" to bury these bones."); resetPR(); return false; } return true; }
6
@Override public void propertyChange(PropertyChangeEvent evt) { rosterTableModel.fireTableStructureChanged(); rosterTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int i = 2; i < rosterTable.getColumnCount(); i++) rosterTable.getColumnModel().getColumn(i).setPreferredWidth(45); }
1
public void persistCSVData(List<User> rawusers, List<Interest> interests, List<Availability> availabilities, Model model) throws Exception{ Map<Integer, UserData> users = persistAdresses(availabilities, persistInterests(interests, persistUsers(rawusers))); for (UserData user : users.values()) { model.insertUser(new UserData(user.id, user.lastName, user.firstName, user.gender, user.age, user.email, user.address, user.sport)); } }
1
public void deleteByKey(long pBlogId){ this.blogModelBS.deleteByKey(pBlogId); }
0
private static int countMp3Files(File directory) throws IOException { int numMp3s = 0; for(File file : directory.listFiles()) { if (file.isDirectory()) { numMp3s += countMp3Files(file); } else if (file.getName().endsWith(".mp3")) { MP3 mp3 = new MP3(file); numMp3s++; } } return numMp3s; }
3
public void run() { this.done = false; try { if (serverMode) { client = new Socket(objectatHost, objectatPort); StringWriter stringWriter = new StringWriter(); String eventXML = ""; while (!this.done) { } } if (clientMode) { this.client = new Socket(objectatHost, objectatPort); if (this.client.isConnected()) { this.logger.log(ObjectatLogLevel.DEBUG, this.getClass() + ": Starting client reader"); this.objectatClientReader = new ObjectatClientReader(this.client.getInputStream(), this.logger); this.objectatClientReaderThread = new Thread(this.objectatClientReader); this.objectatClientReaderThread.start(); this.logger.log(ObjectatLogLevel.DEBUG, this.getClass() + ": Starting client writer"); this.objectatClientWriter = new ObjectatClientWriter(this.client.getOutputStream(), this.logger, this.objectatEventJAXBContext); this.logger.log(ObjectatLogLevel.DEBUG, this.getClass() + ": Sending client message"); this.objectatClientWriter.writeString("CLIENT"); while (!this.done) { while (this.objectatClientReader.getBufferedMessages().size() > 0) { //this.logger.log(ObjectatLogLevel.DEBUG, this.getClass() + ": " + this.objectatClientReader.getBufferedMessages().get(0)); this.objectatClientReader.getBufferedMessages().remove(0); } try { Thread.sleep(10); } catch (Exception e) { } } this.objectatClientReader.setDone(true); } } } catch (Exception e) { // TODO // Catch/make more specific exception this.logger.log(ObjectatLogLevel.ERROR, this.getClass() + ": Exception while starting client. Exception: " + e.getMessage()); } }
8
public synchronized static void appendTextPane(Color color, String message, JTextPane box) { StyledDocument doc = box.getStyledDocument(); Style style = box.addStyle("style", null); /*if (color == null) { color = new Color(255, 255, 255); }*/ StyleConstants.setForeground(style, color); box.setCaretPosition(doc.getLength()); try { doc.insertString(box.getCaretPosition(), message, style); } catch (BadLocationException e) { e.printStackTrace(); } box.setCaretPosition(doc.getLength()); try { cleanUpChat(box); } catch (BadLocationException e) { e.printStackTrace(); } }
2
public static char[] findLongestCommonSubstringUsingTries(char[] s1, char[] s2) { int[][] length = new int[s1.length][s2.length]; int maxLength = 0; int maxi=-1; for(int i=0;i<s1.length; i++){ for( int j=0; j< s2.length; j++) { // if the characters match if(s1[i] == s2[j]){ // increase the length by 1 since i-1 and j-1 substrings length[i][j] = 1+ (i-1>=0 && j-1>=0 ? length[i-1][j-1]: 0); //reconstruction logic if(maxLength < length[i][j]) { maxLength = length[i][j]; maxi = i; } } else { //otherwise find maximum of matching length by adding the last character on both the sides length[i][j] = 0; } } } char[] response = new char[maxLength]; while(maxLength>0){ response[maxLength-1] = s1[maxi]; maxLength--; maxi--; } return response; }
7
private static List<PositionEntity> getMovePositionsKing(final ChessBoardEntity b, final ChessmenEntity c) { List<PositionEntity> result = new ArrayList<PositionEntity>(); PositionEntity p = null; p = new PositionEntity(c.getPosition().getX() - 1, c.getPosition().getY() - 1); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX(), c.getPosition().getY() - 1); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX() + 1, c.getPosition().getY() - 1); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX() - 1, c.getPosition().getY()); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX() + 1, c.getPosition().getY()); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX() - 1, c.getPosition().getY() + 1); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX(), c.getPosition().getY() + 1); if (enablePosition(b, p)) { result.add(p); } p = new PositionEntity(c.getPosition().getX() + 1, c.getPosition().getY() + 1); if (enablePosition(b, p)) { result.add(p); } return result; }
8
@Override public boolean isValid() { return data != null && fa.isValid(); }
1
public static void main(String[] args) throws FileNotFoundException { //------------------------------------------------- // Generate Random strings + Write to file //------------------------------------------------- PrintStream diskWriter = new PrintStream(PASSWORD_DUMP_FILENAME); for (int kk = 1; kk <= ITEM_COUNT_MAX; kk++) { String rndStr = RandomString(MAX_STR_LENGTH); System.out.println(String.format("%3d. %s", kk, rndStr)); diskWriter.println(rndStr); } diskWriter.close(); System.out.println("---------------------------"); System.out.println(String.format("%d random strings have been generated in %s", ITEM_COUNT_MAX, PASSWORD_DUMP_FILENAME)); System.out.println("Re-Read from File"); System.out.println("---------------------------"); Scanner diskScanner = new Scanner(new File(PASSWORD_DUMP_FILENAME)); //------------------------------------------------- // Read back the content of the file line by line // + strip symbols to leave only AlphaNum text //------------------------------------------------- int lineNumber = 1; while (diskScanner.hasNextLine()) { String lineRead = diskScanner.nextLine(); char[] lineAlphaNum = new char[lineRead.length()]; int charFoundCount = 0; // keep only alphanum chars (discarding symbols) for (int kk = 0; kk < lineRead.length(); kk++) { char charRead = lineRead.charAt(kk); if ((charRead >= 48 && charRead <= 57) // 0-9 || (charRead >= 65 && charRead <= 90) // A-Z || (charRead >= 97 && charRead <= 122) // a-z ) { lineAlphaNum[charFoundCount++] = charRead; } } System.out.print(String.format("%3d. ", lineNumber++)); System.out.println(String.format("%s -> %s", lineRead, new String(lineAlphaNum))); } diskScanner.close(); }
9
public Set<ChessPiece> filterMoves(Set<ChessPiece> possibleMoves, ChessPiece[][] board) { ChessPiece[][] tempBoard = new ChessPiece[8][8]; Set<ChessPiece> checkedMoves = new HashSet<ChessPiece>(); //copy the board over piece by piece, to eliminate aliasing //also, find the coordinates of the selected piece for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { tempBoard[i][j] = board[i][j]; if(board[i][j] == this) { tempBoard[i][j] = new ChessPiece(i,j); } } } for(ChessPiece move : possibleMoves) { int rowMove = -1; int colMove = -1; for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { if(tempBoard[i][j] == move) { rowMove = i; colMove = j; i = 8; //to break from outerloop break; } } } ChessPiece previousPiece = tempBoard[rowMove][colMove]; tempBoard[rowMove][colMove] = this; if(!ChessBoard.inCheck(this.color, tempBoard)) { checkedMoves.add(move); } tempBoard[rowMove][colMove] = previousPiece; } return checkedMoves; }
8
public void setCurrentPath(String relativePath){ File file = new File(ProjectMgr.getAssetsPath() ,relativePath); if(!file.exists()){return;} while(file.getParent() != null && !file.getParent().equals(ProjectMgr.getAssetsPath())){ file = file.getParentFile(); } String folder = file.getName(); folderList.setCurrentItem(folder); assetTree.setCurrentItemByPath(relativePath); }
3
public void put(String name, Scriptable start, Object value) { int info = findInstanceIdInfo(name); if (info != 0) { if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", name); } int attr = (info >>> 16); if ((attr & READONLY) == 0) { if (start == this) { int id = (info & 0xFFFF); setInstanceIdValue(id, value); } else { start.put(name, start, value); } } return; } if (prototypeValues != null) { int id = prototypeValues.findId(name); if (id != 0) { if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", name); } prototypeValues.set(id, start, value); return; } } super.put(name, start, value); }
9
private ArrayList<Value> convertInsertValuesType(Table tableDef, ArrayList<String> values) throws Error{ ArrayList<Value> valueList = new ArrayList<Value>(); ArrayList<Attribute> attrList = tableDef.getAttrList(); String tableName = tableDef.getTableName(); int attrSize = attrList.size(); if(attrSize != values.size()){ throw new Error("INSERT: The Number Of Values Not Match, Table " + tableName + " Has " + attrList.size() + " Values"); } for(int i = 0; i < attrSize; i++){ Attribute attribute = attrList.get(i); String strValue = values.get(i); try{ Attribute.Type type = attribute.getType(); if( type == Attribute.Type.INT ){ int intValue = Integer.parseInt(strValue); Value value = new Value(intValue); valueList.add(value); } else if(type == Attribute.Type.CHAR){ //Check type and length if( (attribute.getLength() + 2 < strValue.length()) || strValue.charAt(0) != '"' && strValue.charAt(0) != '\'' ){ throw new NumberFormatException(); } Value charValue = new Value(strValue); valueList.add(charValue); } else if(type == Attribute.Type.DECIMAL){ double doubleVal = Double.parseDouble(strValue); Value doubleValue = new Value(doubleVal); valueList.add(doubleValue); } } catch(NumberFormatException ex){ throw new Error("INSERT: Value " + strValue + " Has Wrong Type Or Length Exceeded"); } } return valueList; }
9
public void collide(Car other) { carPhysics.collide(other.carPhysics); }
0
public void setUpNeuron() throws Exception { List<Integer> weights = new ArrayList(Arrays.asList(new Integer[]{Integer.MAX_VALUE/2,Integer.MAX_VALUE/2})); n= new MyNeuron(weights, new IMyNeuronFunction<Integer>() { @Override public Integer process(List<Integer> inData, List<Integer> weights, Integer threshold) throws Exception { if(inData.size()!=weights.size()) { throw new Exception("inData size doesnt match weights size"); } if(threshold==null) { throw new Exception("threshold cannot be null"); } double total=0; for(int i =0; i<inData.size(); i++) { System.out.println("n:"+mapIntegerToSpecialDouble(inData.get(i))+" w:"+mapIntegerToSpecialDouble(weights.get(i))); System.out.println("t:"+mapIntegerToSpecialDouble(threshold)); total+=mapIntegerToSpecialDouble(inData.get(i))*mapIntegerToSpecialDouble(weights.get(i)); } double answer=1.0 / (1.0 + Math.exp((-total) / mapIntegerToSpecialDouble(threshold))); System.out.println("a:"+answer); return mapSpecialDoubleToInteger(answer); } private double mapIntegerToSpecialDouble(Integer in) //returns double between -1 and 1 { if(in>=0) { return (double)in/(double)Integer.MAX_VALUE; } else { return (double)in/(double)Integer.MIN_VALUE; } } private int mapSpecialDoubleToInteger(double in) { if(in>=0) { return (int)(Integer.MAX_VALUE*in); } else { return (int)(Integer.MIN_VALUE*in); } } }, Integer.MAX_VALUE/2); }
5
@Override public void focusGained(FocusEvent e) { recordRenderer(e.getComponent()); textArea.hasFocus = true; }
0
@Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || this.getClass() != object.getClass()) { return false; } return this.uri.equals(((Equivalence) object).getUri()) ; }
3
private static char[][] getMap(int mapNumber) throws FileNotFoundException, IOException{ /* this makes sure the numberformat is correct with numberlength changes*/ String mapNumberTransformation = "00" + Integer.toString(mapNumber); mapNumberTransformation = mapNumberTransformation.substring(mapNumberTransformation.length()-3); /* */ //Find the parsed map according to a given number BufferedReader br = new BufferedReader(new FileReader( myUrlToMapsInDropbox + mapNumberTransformation + ".in")); //basic variable definition String[] mapRows = new String[200]; String maprow; int maxColLen = -1; int rowLen = 0; //To read the map and save it as a char[][] i need to know which row has the most amount of signs, //As long as theres another row to read, read it and see if is is longer than the longest row found for(; (maprow = br.readLine()) != null; rowLen++ ){ mapRows[rowLen] = maprow; maxColLen = Math.max(maxColLen, maprow.length()); } //now that sizes are know, its time to actually save the map. char[][] map = new char[rowLen][maxColLen]; for(int r = 0; r < rowLen ; r++){ for(int c = 0; c < mapRows[r].length(); c++){ map[r][c] = mapRows[r].charAt(c); //if the player is found, then the startpositino is found for the testing if(mapRows[r].charAt(c)=='@' || mapRows[r].charAt(c)=='+'){ pR = r; pC = c; } } for (int c= mapRows[r].length(); c < maxColLen; c++){ map[r][c] = ' '; } } return map; }
6
public static void update(MySQLObjectMapping updateObj) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException, SQLException { Class clazz = updateObj.getClass(); List<Field> ids = updateObj.getIdFields(); StringBuilder whereConditionBuilder = new StringBuilder(" WHERE "); StringBuilder queryBuilder = new StringBuilder(" UPDATE "); queryBuilder.append(clazz.getSimpleName().toLowerCase()); queryBuilder.append(" SET"); Field[] fields = clazz.getDeclaredFields(); Field[] publicFields = clazz.getFields(); for (int i = 0; i < publicFields.length; i++) { if (!ids.contains(fields[i])) { String fieldname = upperCaseFirstCharacterAndID(fields[i].getName()); queryBuilder.append(" "); queryBuilder.append(fieldname); queryBuilder.append("="); Object fieldValue = fields[i].get(updateObj); if (fields[i].getType().equals(Date.class)) { queryBuilder.append("'"); queryBuilder.append(((Date) fieldValue).toString()); queryBuilder.append("'"); } else if (fields[i].getType().equals(Boolean.class)) { queryBuilder.append((Boolean) fieldValue); } else if (fields[i].getType().equals(Integer.class)){ queryBuilder.append((Integer) fieldValue); } else { queryBuilder.append("'"); queryBuilder.append((String) fieldValue); queryBuilder.append("'"); } if(i < (publicFields.length-1)) queryBuilder.append(","); } else { whereConditionBuilder.append(" "); whereConditionBuilder.append(upperCaseFirstCharacterAndID(fields[i].getName())); whereConditionBuilder.append("="); Object fieldValue = fields[i].get(updateObj); if (fields[i].getType().equals(Date.class)) { whereConditionBuilder.append("'"); whereConditionBuilder.append(((Date) fieldValue).toString()); whereConditionBuilder.append("'"); } else if (fields[i].getType().equals(Boolean.class)) { whereConditionBuilder.append((Boolean) fieldValue); } else if (fields[i].getType().equals(Integer.class)){ whereConditionBuilder.append((Integer) fieldValue); } else { whereConditionBuilder.append("'"); whereConditionBuilder.append((String) fieldValue); whereConditionBuilder.append("'"); } } } executeUpdate(queryBuilder.toString() + whereConditionBuilder.toString()); }
9
@Override public void paintComponent(Graphics g) { super.paintComponent(g); int w = getWidth(); int h = getHeight(); g.setColor(selected ? Color.yellow : (color == Side.WHITE) ? DARKBROWN : LIGHTBROWN); g.fillOval(0, 0, w, h); g.setColor((color == Side.WHITE) ? LIGHTBROWN : DARKBROWN); g.fillOval(4, 4, w - 8, h - 8); }
3
public void draw(Graphics g, ImageObserver observer) { if (image != null) g.drawImage(image, x, y, width, heigth, observer); }
1
public static String toStringBytes(byte[] octets){ String aRetourner = "["; for(int i = 0;i<octets.length;i++){ if (i == 0){ aRetourner += " "+octets[i]; }else{ aRetourner += ", "+octets[i]; } } aRetourner += "]"; return aRetourner; }
2
private static int[] resolveBounds(Rectangle in, boolean warp) { int x = Math.round((float)in.x / (float)32); int y = Math.round((float)in.y / (float)32); int width = Math.round((float)in.width / (float)32); int height = Math.round((float)in.height / (float)32); if (!warp) { if (width > 1) --width; if (height > 1) --height; } x += width / 2; y += height / 2; if (warp) { width -= 2; height -= 2; } return new int[]{x, y, width, height}; }
4
public ArrayList<String> getPicturePaths() { return PicturePaths; }
0
static final boolean activate(CellRenderer self, Event event, Widget widget, String path, Rectangle backgroundArea, Rectangle cellArea, CellRendererState flags) { boolean result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } if (event == null) { throw new IllegalArgumentException("event can't be null"); } if (widget == null) { throw new IllegalArgumentException("widget can't be null"); } if (path == null) { throw new IllegalArgumentException("path can't be null"); } if (backgroundArea == null) { throw new IllegalArgumentException("backgroundArea can't be null"); } if (cellArea == null) { throw new IllegalArgumentException("cellArea can't be null"); } if (flags == null) { throw new IllegalArgumentException("flags can't be null"); } synchronized (lock) { result = gtk_cell_renderer_activate(pointerOf(self), pointerOf(event), pointerOf(widget), path, pointerOf(backgroundArea), pointerOf(cellArea), numOf(flags)); return result; } }
7
private LegacyInstr decode_22(int word1) throws InvalidInstruction { // get value of bits logical[12:15] int value = (word1) & 0x0000F; switch ( value ) { case 0x00002: return decode_STPD_2(word1); case 0x0000F: return decode_PUSH_0(word1); case 0x0000D: return decode_STPI_0(word1); case 0x00009: return decode_STPI_1(word1); case 0x00001: return decode_STPI_2(word1); case 0x0000E: return decode_STPD_0(word1); case 0x0000A: return decode_STPD_1(word1); case 0x0000C: return decode_ST_0(word1); case 0x00000: return decode_STS_0(word1); default: return null; } }
9
public static int getSmallestShipNotDestroyed() { ArrayList<Integer> shipSizesLeft = new ArrayList<Integer>(); for(int size : BattleShipGame.shipSizes) shipSizesLeft.add(new Integer(size)); for(Ship ship : sunkShips) shipSizesLeft.remove(new Integer(ship.getSize())); int smallest = 10000; for(Integer in : shipSizesLeft) if(in.intValue() < smallest) smallest = in.intValue(); return smallest; }
4
ArrayList<String> getGoldRanking(String query) { //int numResults = 100; ArrayList<String> gold; String queryTerms = query.replaceAll(" ", "+"); try{ FileInputStream streamIn = new FileInputStream(this.wikiDirectory +queryTerms +".ser"); ObjectInputStream objectinputstream = new ObjectInputStream(streamIn); gold = (ArrayList<String>) objectinputstream.readObject(); return gold; }catch(Exception ex){} gold = new ArrayList<String>(); String url = "http://de.wikipedia.org/w/index.php?title=Spezial%3ASuche&search=" +queryTerms +"&fulltext=Search&profile=default"; String wikipage = ""; try { wikipage = (String) new WebFile(url).getContent(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (UnknownServiceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String[] lines = wikipage.split("\n"); for(int i=0;i<lines.length;i++){ //if(lines[i].startsWith("<li><div class='mw-search-results-heading'>")){ if(lines[i].startsWith("<li>")){ Pattern p = Pattern.compile("title=\"(.*)\""); Matcher m = p.matcher(lines[i]); m.find(); gold.add(m.group(1)); //debug //System.out.println("m.group(1): " + m.group(1)); } } try { FileOutputStream fout = new FileOutputStream(this.wikiDirectory +queryTerms +".ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(gold); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //debug //System.out.println("gold return: " + gold); return gold; }
8
public int synthesis(Packet op){ Info vi=vd.vi; // first things first. Make sure decode is ready opb.readinit(op.packet_base, op.packet, op.bytes); // Check the packet type if(opb.read(1)!=0){ // Oops. This is not an audio data packet return (-1); } // read our mode and pre/post windowsize int _mode=opb.read(vd.modebits); if(_mode==-1) return (-1); mode=_mode; W=vi.mode_param[mode].blockflag; if(W!=0){ lW=opb.read(1); nW=opb.read(1); if(nW==-1) return (-1); } else{ lW=0; nW=0; } // more setup granulepos=op.granulepos; sequence=op.packetno-3; // first block is third packet eofflag=op.e_o_s; // alloc pcm passback storage pcmend=vi.blocksizes[W]; if(pcm.length<vi.channels){ pcm=new float[vi.channels][]; } for(int i=0; i<vi.channels; i++){ if(pcm[i]==null||pcm[i].length<pcmend){ pcm[i]=new float[pcmend]; } else{ for(int j=0; j<pcmend; j++){ pcm[i][j]=0; } } } // unpack_header enforces range checking int type=vi.map_type[vi.mode_param[mode].mapping]; return (FuncMapping.mapping_P[type].inverse(this, vd.mode[mode])); }
9
public static IpInfo getIpInfo(final String ipAddress) { IpInfo ipLookup = new IpInfo(); if (!IPAddressValidator.getInstance().validate(ipAddress)){ ipLookup.setErrorMsg("Invalid IP Address"); }else{ sortServicesByPriority(); try { for (int i = 0; i < serviceList.size(); i++) { ipLookup = serviceList.get(i).getIpValue(ipAddress); if (StringUtil.isNullSpacesOrEmpty(ipLookup.getErrorMsg())) { return ipLookup; } } } catch (Exception e) { e.printStackTrace(); } } return ipLookup; }
4
@Override public boolean equals(Object obj) { if (obj == this.value) return true; if (obj instanceof Value) { Value v = (Value) obj; return this.type == v.type && (this.value == v.value || (this.value != null && this.value.equals(v.value))); } else { return (this.value.equals(obj)); } }
5
public void tick() { super.tick(); if (isWalking) { ref++; moveDir(getFacing()); if (ref == 16) { ref = 0; isWalking = false; setTextureRegion(sprites.getSprite(getFacing())); synchronized (this) { this.notifyAll(); } } } }
2
public final static boolean isNumberFollowedByString(final String str) { if((str==null)||(str.length()<2)) return false; if(!Character.isDigit(str.charAt(0))) return false; int dex=1; for(;dex<str.length();dex++) if(Character.isLetter(str.charAt(dex))) break; else if(!Character.isDigit(str.charAt(dex))) return false; if(dex>=str.length()) return false; for(;dex<str.length();dex++) if(!Character.isLetter(str.charAt(dex))) return false; return true; }
9
public void eat(int id, int slot) { if (c.duelRule[6]) { c.sendMessage("You may not eat in this duel."); return; } if (System.currentTimeMillis() - c.foodDelay >= 1500 && c.constitution > 0) { c.getCombat().resetPlayerAttack(); c.attackTimer += 2; c.startAnimation(829); c.getItems().deleteItem(id,slot,1); FoodToEat f = FoodToEat.food.get(id); if (c.constitution < (f.getId() == 15272 ? (c.maxConstitution * 1.1) : c.maxConstitution)) { c.constitution += f.getHeal() * 10; if (c.constitution > (f.getId() == 15272 ? (c.maxConstitution * 1.1) : c.maxConstitution)) c.constitution = (int) (f.getId() == 15272 ? (c.maxConstitution * 1.1) : c.maxConstitution); } c.foodDelay = System.currentTimeMillis(); c.sendMessage("You eat the " + f.getName() + "."); } }
8
public Texture getTexture(String path) throws IOException { if (textures.containsKey(path)) { return textures.get(path); } else { Texture t = new Texture(getImageFromName(path)); textures.put(path, t); return t; } }
1
@Override public void componentResized(ComponentEvent e) { Component comp = e.getComponent(); int width = comp.getWidth(); int height = comp.getHeight(); boolean resize = false; if (width < minWidth) { resize = true; width = minWidth; } if (height < minHeight) { resize = true; height = minHeight; } if (resize) { comp.setSize(width, height); } }
3
public Weapon(Class<? extends T> projectileType, long coolDown, int maxAmmo) { this.projectileType = projectileType; lastShot = 0; this.coolDown = coolDown; this.maxAmmo = maxAmmo; this.currentAmmo = maxAmmo; try { ctor = getCtor(); } catch (SecurityException e) { e.printStackTrace(); return; } }
2
private Object spawnChoiceWindow(String title, String prompt, Object[] choices) { //This will create the dialogue window dialogSpawner = new JOptionPane(prompt, JOptionPane.QUESTION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, choices, null); final JDialog dialog = dialogSpawner.createDialog(null, title); dialog.setModal(false); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); Thread t = new Thread() { public void run () { try { SwingUtilities.invokeAndWait(new Runnable() { public void run () { dialog.setVisible(true); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }; t.start(); Object result = null; while(result == null || result.equals(JOptionPane.UNINITIALIZED_VALUE)) { result = dialogSpawner.getValue(); } dialog.dispose(); return result; }
4
public static File criar(String tipoArquivo, String conteudo) throws Exception { if ( "apresentacao".equals(tipoArquivo) || "texto".equals(tipoArquivo) || "planilha".equals(tipoArquivo) ) { IDocumento documento = AbstractDocumento.factory(tipoArquivo, conteudo); return documento.criar(); } else if ( "BMP".equals(tipoArquivo) || "JPG".equals(tipoArquivo) || "GIF".equals(tipoArquivo) ) { IImagem imagem = AbstractImagem.factory(tipoArquivo, conteudo); return imagem.criar(); } else { throw new Exception ("tipo de arquivo invalido"); } }
6
@Override public String toString() { StringBuffer sBuff = new StringBuffer(); if (octave < 0) { for(int i=0; i< (-1)*octave;i++) { sBuff.append('.'); } } if (swar != -1) { sBuff.append(swarLiterals[swar]); } if (octave > 0) { for(int i=0; i< octave;i++) { sBuff.append('.'); } } return sBuff.toString(); }
5
public boolean validate(byte[] piece_hashes, byte[] piece, int piece_index){ //Make sure we don't get an index out of bounds error if(piece_index != piece_hashes.length) return false; byte[] hashed_piece; MessageDigest create_hash = null; //The MessageDigest will use the SHA algorithm to create the hash of our pieces try { create_hash = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("The Digester has a tummy ache."); e.printStackTrace(); } hashed_piece = create_hash.digest(piece); //Still checking for index out of bounds errors if(piece_hashes.length != hashed_piece.length) return false; for(int i = 0; i<piece_hashes.length;i++) if(piece_hashes[i] != hashed_piece[i]) return false; return true; }
5
public int compareTo(DateTime aThat) { if (this == aThat) return EQUAL; ensureParsed(); aThat.ensureParsed(); ModelUtil.NullsGo nullsGo = ModelUtil.NullsGo.FIRST; int comparison = ModelUtil.comparePossiblyNull(this.fYear, aThat.fYear, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fMonth, aThat.fMonth, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fDay, aThat.fDay, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fHour, aThat.fHour, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fMinute, aThat.fMinute, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fSecond, aThat.fSecond, nullsGo); if (comparison != EQUAL) return comparison; comparison = ModelUtil.comparePossiblyNull(this.fNanosecond, aThat.fNanosecond, nullsGo); if (comparison != EQUAL) return comparison; return EQUAL; }
8
public void paint(Graphics g, int yOffset) { removeDeadFlyUps(); g.setColor(Color.BLACK); int bottomEdge = 15 * flyups.size(); bottomEdge += (permanentFlyUp.equals(""))?0:15; float rgb = (bottomEdge <= (200 + yOffset)) ? 0.0F : 1.0F; g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); g.drawString(permanentFlyUp, 2, 15); int yCoord = 15; if(!permanentFlyUp.equals("")) yCoord += 20; for(FlyUp data:flyups) { float alpha = 1.0F; if((data.timeSinceCreation() >= 2000) && (data.timeSinceCreation() <= 3000)) { alpha = 1.0F - ((data.timeSinceCreation() - 2000.0F)/1000.0F); } // System.out.println("-\t- rgb: " + rgb + ", alpha: " + alpha); g.setColor(new Color(rgb, rgb, rgb, alpha)); g.drawString(data.getMessage(), 2, yCoord); yCoord += 20; } }
6
private Class[] types(int[] dims, Class basetype) { int i = 0; while (dims[i] > -1) { i++; } if (debug) { System.out.println(" rank " + i); } Class[] c = new Class[i]; c[i - 1] = basetype; while (--i > 0) { c[i - 1] = Array.newInstance(c[i], 0).getClass(); } if (debug) { System.out.println("Types " + java.util.Arrays.toString(c)); } return c; }
4
@BeforeClass public static void setUpClass() { }
0
int divideHelper(int a, int b) { if (a > b) return 0; if (a == b) return 1; // shift b to align a and compare with a int diff = bitDiff(a, b); if (a < (b << diff)) return (1 << diff) + divideHelper(a - (b << diff), b); diff--; return (1 << diff) + divideHelper(a - (b << diff), b); }
3
public String getMSISDNString(int position, boolean showAllHex) { byte[] MSISDN = null; String MSISDNString = ""; try { worker.getResponse(worker.select(DatabaseOfEF.DF_TELECOM.getFID())); MSISDN = worker.readRecord(position, worker.getResponse(worker.select(DatabaseOfEF.EF_MSISDN.getFID()))); if (MSISDN[14] != (byte) 0xff) { for (int i = 16; i <= 14 + MSISDN[14]; i++) { String b = Converter.byteToHex(MSISDN[i]); String c = Converter.swapString(b); MSISDNString = MSISDNString.concat(c); } } } catch (Exception ex) { Logger.getLogger(CardManager.class.getName()).log(Level.SEVERE, null, ex); } if (showAllHex) { return Converter.bytesToHex(MSISDN); } else { return MSISDNString; } }
4
private static boolean isConflictWithVenue(long startTime, long endTime, int frequency, long lastDay, long venueId, long exceptApptId, IsLegalExplain explain) { try { List<Appointment> aAppt = Appointment.findByVenue(venueId); for (Appointment iAppt : aAppt) { if (iAppt.id == exceptApptId) continue; if (iAppt .isConflictWith(startTime, endTime, frequency, lastDay)) { if (explain != null) { explain.explain = "this appointment is conflict with appointment " + iAppt.name + " in location"; } return true; } } return false; } catch (Exception e) { e.printStackTrace(); return false; } }
5
private static void quantityOfProducts() { mapOfQuantityProducts = new HashMap<String, Integer>(); for (String entry : scanProducts) { if (mapOfQuantityProducts.containsKey(entry)) { mapOfQuantityProducts.put(entry, (mapOfQuantityProducts.get(entry) + 1)); } else { mapOfQuantityProducts.put(entry, 1); } } }
2
public FlippingPuzzleDialog(final MainWindow mainWindow) { setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); { JPanel panel = new JPanel(); contentPanel.add(panel); { rowsNumberMessage = new JLabel("Rows number"); panel.add(rowsNumberMessage); } { rowsText = new JTextField(); panel.add(rowsText); rowsText.setColumns(10); } rowsNotANumberErrorMessage = new JLabel("* should be a number."); panel.add(rowsNotANumberErrorMessage); rowsNegativeNumberErrorMessage = new JLabel( "* should be a positif value."); rowsNegativeNumberErrorMessage.setVisible(false); panel.add(rowsNegativeNumberErrorMessage); rowsNotANumberErrorMessage.setVisible(false); } JPanel panel = new JPanel(); contentPanel.add(panel); { colsNumberMessage = new JLabel("Cols number"); panel.add(colsNumberMessage); } { colsText = new JTextField(); panel.add(colsText); colsText.setColumns(10); } { colsNotANumberErrorMessage = new JLabel("* should be a number"); colsNotANumberErrorMessage.setVisible(false); panel.add(colsNotANumberErrorMessage); } { colsNegativeNumberErrorMessage = new JLabel( "* should be a positif value."); colsNegativeNumberErrorMessage.setVisible(false); panel.add(colsNegativeNumberErrorMessage); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { int rows = 0; int cols = 0; boolean error = false; rowsNotANumberErrorMessage.setVisible(false); rowsNegativeNumberErrorMessage.setVisible(false); colsNotANumberErrorMessage.setVisible(false); colsNegativeNumberErrorMessage.setVisible(false); try { rows = Integer.parseInt(rowsText.getText()); if (rows <= 0) { error = true; rowsNegativeNumberErrorMessage.setVisible(true); } } catch (NumberFormatException e1) { rowsNotANumberErrorMessage.setVisible(true); error = true; } try { cols = Integer.parseInt(colsText.getText()); if (cols <= 0) { error = true; colsNegativeNumberErrorMessage.setVisible(true); } } catch (NumberFormatException e1) { colsNotANumberErrorMessage.setVisible(true); error = true; } if (!error) { mainWindow.reset(); mainWindow.setFlippingPuzzle(new FlippingPuzzle( rows, cols)); // puzzlePanel.add(new // FlippingPuzzlePanel(MainWindow.this)); mainWindow.getPuzzlePanel().add( new FlippingPuzzlePanel(mainWindow)); mainWindow.getFrame().revalidate(); mainWindow.getFrame().repaint(); FlippingPuzzleDialog.this.dispose(); } } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { FlippingPuzzleDialog.this.dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
5
public static void main(String[] args) { int i, j; for(i=1; i<10; i++) { for(j=2; j<10; j++) { System.out.printf("%d*%d=%2d\t", j,i,i*j); } System.out.println(); } System.out.println();System.out.println(); for(i=0; i<10; i++) { for(j=0; j<10; j++) { System.out.printf("*"); } System.out.println(); } System.out.println();System.out.println(); for(i=0; i<10; i++) { for(j=0; j<i; j++) { System.out.printf("*"); } System.out.println(); } System.out.println();System.out.println(); for(i=0; i<10; i++) { for(j=i; j<10; j++) { System.out.printf("*"); } System.out.println(); } }
8
public static void newFile(String fileContent, String filePath, FileType fileType){ java.io.File file = new java.io.File(filePath + fileType.getType()); try { FileWriter fw = new FileWriter(file); fw.write(fileContent); fw.close(); } catch (IOException e) { log.error("Create file failed."); e.printStackTrace(); } }
1
public Document separateDocument(DocumentView docView) { // Get the List that contains the DocView List<Object> curDocAndDocView = null; for (List<Object> value : this.docAndDocView.values()) { if (value.contains(docView)) { curDocAndDocView = value; } } // Get the Document from this List Document d = null; for (Object o : curDocAndDocView) { if (o instanceof Document) { d = (Document) o; } } return d; }
4
static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) { Class<?> declaredByRaw = declaringClassOf(unknown); // we can't reduce this further if (declaredByRaw == null) { return unknown; } Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw); if (declaredBy instanceof ParameterizedType) { int index = indexOf(declaredByRaw.getTypeParameters(), unknown); return ((ParameterizedType) declaredBy).getActualTypeArguments()[index]; } return unknown; }
5
public static void changeTheme(String name) { GUITHEME[] t = GUITHEME.values(); for (int i = 0; i < t.length; i++) { if (t[i].name().equalsIgnoreCase(name)) theme = t[i]; } }
2