text
stringlengths
14
410k
label
int32
0
9
public void SetBus(int bus) { this.bus = bus; }
0
public static Decoder createDecoder(int encoding, CMsgReader reader) { /* if (encoding <= Encodings.encodingMax && createFns[encoding]) return (createFns[encoding])(reader); return 0; */ switch(encoding) { case Encodings.encodingRaw: return new RawDecoder(reader); case Encodings.encodingRRE: return new RREDecoder(reader); case Encodings.encodingHextile: return new HextileDecoder(reader); case Encodings.encodingTight: return new TightDecoder(reader); case Encodings.encodingZRLE: return new ZRLEDecoder(reader); } return null; }
5
public int maxSubArray(int[] A) { int max = 0; int cur = 0; boolean allZero = true; int maxNegtive = Integer.MIN_VALUE; for (int a : A) { cur += a; if (cur > max) { max = cur; } if (cur < 0) { cur = 0; } if (a < 0) { if (maxNegtive < a) { maxNegtive = a; } } else { allZero = false; } } return allZero ? maxNegtive : max; }
6
@Override public void run() { int totalConsumedByThisConsumer=0; try{ while(true) { Integer item =sharedQueue.retreiveItem(); if(item==null) { // nothing to consume. Queue is empty. Too slow producer or producer is dead if (Producer.getNumberOfActiveProducers() <= 0) { break; // no active producers. Let's finish this consumer } }else { // We consumed successfully a item totalConsumedByThisConsumer++; System.out.println("Consumer '" + name + "' consume <<< " + item); } Thread.sleep(rnd.nextInt(50)); } } catch (InterruptedException ex) { System.out.println("Consumer '" + name + "' process killed"); } // Print statistics System.out.println("### Consumer '" + name + "' consumed " + totalConsumedByThisConsumer + " items"); }
4
public static boolean isEqual(BufferedImage newImage, BufferedImage previousImage) { boolean equal = true; if ((newImage != null) && (previousImage != null)) { DataBuffer newDb = newImage.getData().getDataBuffer(); DataBuffer prevDb = previousImage.getData().getDataBuffer(); for (int i = 0; (i < newDb.getSize()) && equal; i++) { if (newDb.getElem(i) != prevDb.getElem(i)) { return false; } } } else { equal = false; } return equal; }
5
private CharacterStorageInventory() { characterList = new LinkedList<Character>(); }
0
protected static String[] parseAsStrings(String[] args) { List<String> all = new LinkedList<String>(); List<String> one = new LinkedList<String>(); for (String arg : args) { one.clear(); for (String a : arg.split(C.separator)) { one.add(a); } all.addAll(one); } String[] result = new String[all.size()]; all.toArray(result); return result; }
2
private ClustersRequest parserRequest(String requestData) throws UnsupportedEncodingException{ // 解析握手信息 ClustersRequest requestInfo = new ClustersRequest(); String[] requestDatas = requestData.split("\r\n"); if(requestDatas.length < 0){ return null; } String line = requestDatas[0]; if(!line.equalsIgnoreCase(ClustersConstants.CLUSTERS)){ return null; } for(int i = 1; i < requestDatas.length; ++i){ // 解析单条请求信息 line = requestDatas[i]; String[] parts = line.split(":", 2); if (parts.length != 2){ log.info("Wrong field format: " + line); return null; } String name = parts[0].toLowerCase(); String value = parts[1].toLowerCase(); if(name.equals("host")){ requestInfo.setHost(value); }else if(name.equals("key")){// 获取随机码 requestInfo.setDigest(getKey(parts[1]));// 设置签名 }else if(name.equals("protocol")){//获取安全控制版本 requestInfo.setProtocol(value);// 设置协议 }else{ log.info("Unexpected header field: " + line); } } return requestInfo; }
7
private static int modifyInt(int rgb, int amount) { int r = rgb & 0xFF0000 >> 16; int g = rgb & 0x00FF00 >> 8; int b = rgb & 0x0000FF; int result = 0; r += amount; g += amount; b += amount; if(r < 0) { r = 0; } else if(r > 255) { r = 255; } if(g < 0) { g = 0; } else if(g > 255) { g = 255; } if(b < 0) { b = 0; } else if(b > 255) { b = 255; } result = result | 0xFF000000; result = result | (r << 16); result = result | (g << 8); result = result | (b); return result; }
6
public static String charToString(char[][] tMap, int player){ String[] board = new String[tMap[0].length]; String pboard; //reset board for(int i=0; i<tMap[0].length; i++) board[i] = ""; if(player == 1){ pboard = "o"; }else{ pboard = "x"; } //Concatenate horizontally //make map into rows for(int j=0; j<tMap[0].length; j++){ for(int i=0; i<tMap.length; i++){ if(tMap[i][j] != '\0') board[j] += tMap[i][j]; } } for(int i=0; i<tMap[0].length; i++){ if(player==1) pboard += board[i]+"o"; else pboard += board[i]+"x"; } return pboard; }
7
public static boolean isWraith (Entity entity) { if (entity instanceof Zombie) { Zombie wraith = (Zombie) entity; LeatherArmorMeta meta; ItemStack stack = new ItemStack(299, 1, (short) - 98789); meta = (LeatherArmorMeta) stack.getItemMeta(); meta.setColor(Color.fromRGB(52, 52, 52)); stack.setItemMeta(meta); if (wraith.getEquipment().getChestplate().equals(stack)) { return true; } } return false; }
2
public void runProgram() { outputLine("Interpreting..."); program.clear(); variables.clear(); try { program = BareBonesInterpreter.InterpretString(input.getText(), variables); } catch (BareBonesSyntaxException e) { outputLine("Syntax Error:"); outputLine(e.getMessage()); outputLine("On Statement " + (e.getLineNumber() + 1)); return; } catch (BareBonesCompilerException e) { outputLine("Compiler Error:"); outputLine(e.getMessage()); outputLine("On Statement " + (e.getLineNumber() + 1)); return; } outputLine("Done"); outputLine("Running..."); try { BareBonesInterpreter.RunProgram(program); } catch (BareBonesRuntimeException e) { outputLine("Runtime Error:"); outputLine(e.getMessage()); outputLine("On Statement " + (e.getLineNumber() + 1)); } catch (InterruptedException e) { outputLine("Program interrupted, exiting"); return; } outputLine("Done"); }
4
public static void buildAssets(String directory) throws IOException { if (!(directory.endsWith("/")||directory.endsWith("\\"))) { //Logger.warning("Assets", "A slash was not added at the end of the asset output directory. Attempting to fix..."); directory = directory + "/"; } Logger.info("Assets", "Building Minecraft assets at " + directory); // Let's start by setting up the stuff we're gonna need Logger.info("Assets", "Setting up folders..."); File assetFolder = new File(directory); try { FileUtils.deleteDirectory(assetFolder); Logger.info("Assets", "Deleting existing assets..."); } catch (IOException e) { // Folder already exists } assetFolder.mkdir(); File assetFolderLegacy = new File(directory + "/legacy"); assetFolderLegacy.mkdir(); // Now let's download the version definition file from Mojang and store it in a temporary file Logger.info("Assets", "Fetching asset definition file..."); File defFile = File.createTempFile("assets", ".json"); URL defWeb = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/legacy.json"); FileUtils.copyURLToFile(defWeb, defFile); Logger.info("Assets", "Saving asset definition file..."); File defFileSaved = new File(directory + "assetDef.json"); FileUtils.copyFile(defFile, defFileSaved); // And now we parse... Logger.info("Assets", "String asset download..."); String defString = FileUtils.readFileToString(defFile); StringReader defReader = new StringReader(defString); JsonReader reader = new JsonReader(defReader); try { reader.beginObject(); reader.nextName(); reader.nextBoolean(); reader.nextName(); reader.beginObject(); boolean newFile = true; while (newFile) { String assetName = reader.nextName(); reader.beginObject(); reader.nextName(); String hash = reader.nextString(); String subhash = hash.substring(0, 2); Logger.info("Assets", "Downloading " + assetName + "..."); URL asset = new URL("http://resources.download.minecraft.net/" + subhash + "/" + hash); File assetDest = new File(directory + "modern/" + subhash + "/" + hash); FileUtils.copyURLToFile(asset, assetDest); assetDest = new File(directory + "legacy/" + assetName); FileUtils.copyURLToFile(asset, assetDest); reader.nextName(); reader.nextInt(); reader.endObject(); JsonToken next = reader.peek(); newFile = next == JsonToken.NAME; } reader.endObject(); } finally { reader.close(); Logger.info("Assets", "Asset download completed"); } Logger.info("Assets", "Deleting tempfiles..."); boolean deleted = defFile.delete(); if (!deleted) { Logger.warning("Assets", "Tempfile " + defFile.getAbsolutePath() + " failed to delete. Scheduling deletion upon termination of Moddle..."); defFile.deleteOnExit(); } }
5
public void setMed_depotLegal(String med_depotLegal) { this.med_depotLegal = med_depotLegal; }
0
public Object newArray(String type, int[] dimensions) throws InterpreterException, NegativeArraySizeException { if (type.length() == dimensions.length + 1) { Class clazz; try { clazz = TypeSignature.getClass(type .substring(dimensions.length)); } catch (ClassNotFoundException ex) { throw new InterpreterException("Class " + ex.getMessage() + " not found"); } return Array.newInstance(clazz, dimensions); } throw new InterpreterException("Creating object array."); }
2
public boolean processFollow(MOB mob, MOB tofollow, boolean quiet) { if(mob==null) return false; final Room R=mob.location(); if(R==null) return false; if(tofollow!=null) { if(tofollow==mob) { return nofollow(mob,true,false); } if(mob.getGroupMembers(new HashSet<MOB>()).contains(tofollow)) { if(!quiet) mob.tell(L("You are already a member of @x1's group!",tofollow.name())); return false; } if(nofollow(mob,false,false)) { final CMMsg msg=CMClass.getMsg(mob,tofollow,null,CMMsg.MSG_FOLLOW,quiet?null:L("<S-NAME> follow(s) <T-NAMESELF>.")); if(R.okMessage(mob,msg)) R.send(mob,msg); else return false; } else return false; } else return nofollow(mob,!quiet,quiet); return true; }
9
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PrincipalWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PrincipalWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PrincipalWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PrincipalWindow.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 PrincipalWindow().setVisible(true); } }); }
6
public void criarGerente(Usuario Gerente) throws SQLException, excecaoGerenteExistente, excecaoGerentePorDepartamento { UsuarioDAO userDAO = new UsuarioDAO(); Usuario GerenteExistente = userDAO.selectGerente(Gerente.getNome(), Gerente.getTipo()); //VERIFICA SE HA ALGUM GERENTE CADASTRADO COM O MESMO NOME if (GerenteExistente == null) { Usuario gerentePorDepartmento = userDAO.selectGerentePorDepartamento(Gerente.getDepartamento().getCodigo(), Gerente.getTipo()); //VERIFICA SE JA EXISTE UM GERENTE CADASTRADO PARA O DEPARTAMENTO SELECIONADO if (gerentePorDepartmento == null) { userDAO.criaUSER(Gerente); } else { throw new excecaoGerentePorDepartamento(); } } else { throw new excecaoGerenteExistente(); } }
2
private void setUpButtonImage(JButton button, String image){ BufferedImage choosePageButtonImage; try{ if(bookLayout == 1){ choosePageButtonImage = ImageIO.read(new File("resources/buttons/"+image)); } else{ choosePageButtonImage = ImageIO.read(new File("resources/buttons" +bookLayout + "/"+image)); } Image scaledButton = choosePageButtonImage.getScaledInstance(110,50,java.awt.Image.SCALE_SMOOTH); button.setIcon(new ImageIcon(scaledButton)); }catch (IOException ex){ } }
2
public DbSchema getSimpleSchema() throws WaarpDatabaseSqlException, IOException { if (type == null) { logger.warn("Structure non prête"); return null; } String schemaName = technicalDescription.getName(); int pos = schemaName.lastIndexOf('.'); if (pos > 0) { schemaName = schemaName.substring(0, pos); } DbSchema schema = new DbSchema(schemaName, technicalDescription.getName(), this); switch (type) { case CSVTYPE: { DbTable table = new DbTable(commonTableName+"_"+CSVNAME, CSVNAME, 0, type); loadDbTable(schema, table, simpleTypes); if (table.datafile == null) { table.datafile = this.refDataFile; } System.out.println("creation ok d'une table "+table.name+ " avec "+table.nbFields()+" champs"); } break; case MULTIPLETYPE: { for (int j = 0; j < multipleTypes.size(); j++) { List<ConstanceField> list = multipleTypes.get(j); DbTable table = new DbTable(commonTableName+"_"+TYPENAME+j, "multiple Rank "+j, j, type); loadDbTable(schema, table, list); if (table.datafile == null) { table.datafile = this.refDataFile; } } System.out.println("creation ok d'un schema "+schema.name+ " avec "+schema.nbTables()+" tables"); } break; case UNIQUETYPE: { DbTable table = new DbTable(commonTableName+"_"+FIXNAME, FIXNAME, 0, type); loadDbTable(schema, table, simpleTypes); if (table.datafile == null) { table.datafile = this.refDataFile; } System.out.println("creation ok d'une table "+table.name+ " avec "+table.nbFields()+" champs"); } break; } return schema; }
9
private static boolean circleCircleResolve(CircleObject a, CircleObject b) { double t=-1; Vector2f aPosition = a.getPosition().copy(); Vector2f bPosition = b.getPosition().copy(); Vector2f aVelocity = a.getVelocity().copy(); Vector2f bVelocity = b.getVelocity().copy(); double distanceSq = aPosition.distanceSquared(bPosition); double radiusSumSq = (a.getRadius() + b.getRadius())*(a.getRadius() + b.getRadius()); //If overlapping if(distanceSq < radiusSumSq) { if(a.isStatic() && b.isStatic()) { //Do Nothing return false; } else if((a.isStatic() && !b.isStatic())) { //System.out.println("resolving "+a.getPosition()+" "+b.getPosition()); Vector2f dist = bPosition.sub(aPosition).normalise(); Vector2f newPos = dist.scale((float) (a.getRadius() + b.getRadius()+1)); b.setPosition(aPosition.add(newPos)); return true; } else if(!a.isStatic() && b.isStatic()) { //System.out.println("resolving "+a.getPosition()+" "+b.getPosition()); Vector2f dist = aPosition.sub(bPosition).normalise(); Vector2f newPos = dist.scale((float) (a.getRadius() + b.getRadius()+1)); a.setPosition(bPosition.add(newPos)); return true; } else { if(a.collisionPriority() >= b.collisionPriority()) { //System.out.println("resolving "+a.getPosition()+" "+b.getPosition()); Vector2f dist = bPosition.sub(aPosition).normalise(); Vector2f newPos = dist.scale((float) (a.getRadius() + b.getRadius()+1)); b.setPosition(aPosition.add(newPos)); return true; } else { //System.out.println("resolving "+a.getPosition()+" "+b.getPosition()); Vector2f dist = aPosition.sub(bPosition).normalise(); Vector2f newPos = dist.scale((float) (a.getRadius() + b.getRadius()+1)); a.setPosition(bPosition.add(newPos)); return true; } } } return false; }
8
public boolean allowParameters(int number) { if ("for".equals(keyword.getKeyword()) && (number == 0 || number == 1)) { return true; } else if ("enum".equals(keyword.getKeyword()) && (number == 1 || number == 2 || number == 3)) { return true; } else if ("set".equals(keyword.getKeyword()) && number == 1) { return true; } return false; }
9
@SuppressWarnings("unchecked") @Override public void mousePressed(MouseEvent e) { if (this.checkModifiers(e)) { this.viewer = (VisualizationViewer<ILayoutVertex, ILayoutEdge>) e .getSource(); this.layout = this.viewer.getModel().getGraphLayout(); final Point2D p = e.getPoint(); GraphElementAccessor<ILayoutVertex, ILayoutEdge> pickSupport = this.viewer .getPickSupport(); if (pickSupport != null) { Graph<ILayoutVertex, ILayoutEdge> graph = this.layout .getGraph(); // set default edge type this.edgeIsDirected = EdgeType.DIRECTED; if (graph instanceof ILayoutGraph) { ILayoutGraph eg = (ILayoutGraph) graph; if (eg.getEdgeType() == EdgeType.UNDIRECTED) { this.edgeIsDirected = EdgeType.UNDIRECTED; } } final ILayoutVertex vertex = pickSupport.getVertex(this.layout, p.getX(), p.getY()); if (vertex != null) { /* edge */ this.startVertex = vertex; this.down = e.getPoint(); this.transformEdgeShape(this.down, this.down); this.viewer.addPostRenderPaintable(this.edgePaintable); if ((e.getModifiers() & MouseEvent.SHIFT_MASK) != 0 && this.layout.getGraph() instanceof UndirectedGraph == false) { this.edgeIsDirected = EdgeType.DIRECTED; } if (this.edgeIsDirected == EdgeType.DIRECTED) { this.transformArrowShape(this.down, e.getPoint()); this.viewer.addPostRenderPaintable(this.arrowPaintable); } } else { /* vertex */ ILayoutVertex newVertex = this.vertexFactory.create(); graph.addVertex(newVertex); Point2D point = this.viewer.getRenderContext() .getMultiLayerTransformer() .inverseTransform(e.getPoint()); this.layout.setLocation(newVertex, point); newVertex.setLocation(point); } } this.viewer.repaint(); } }
8
public void doAction() { for (int i = 0; i < provider.getAvailableShare().length; i++) { try { if (accountmanager.diverShareSell(provider.getAvailableShare()[i].name, playerbotname)) { accountmanager.buyShare(playerbotname, provider.getAvailableShare()[i].name, 5); } } catch (ShareException e) { return; } catch (Exception e) { e.printStackTrace(); } try { if (!accountmanager.diverShareSell( provider.getAvailableShare()[i].name, playerbotname)) { accountmanager.sellShare(playerbotname, provider.getAvailableShare()[i].name, 5); } } catch (Exception e) { } } }
6
private void jButton_DepositActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DepositActionPerformed try { ArrayList selectedIndices = new ArrayList(); for (int i = 0; i < jTable5.getRowCount(); i++) { String id = (String) jTable5.getModel().getValueAt(i, 3); if ((Boolean) jTable5.getModel().getValueAt(i, 5)) { selectedIndices.add(id); } } System.out.println("selectedIndices:" + selectedIndices); if(selectedIndices.isEmpty()){ int selected = JOptionPane.showConfirmDialog(this, "This will deposit all of the tokens in the purse", "Warning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(selected==2) return; } new CashPurseDepositDialog(null, true, details, selectedIndices).setVisible(true); }catch(Exception e){ e.printStackTrace(); } }//GEN-LAST:event_jButton_DepositActionPerformed
5
@Override public SolveStep getStep(Sudoku s) { for (int x=0; x<9;x++){//SCORRO OGNI BLOCCO SudokuBlock sb = s.getBlock(x); Freq[] freq = new Freq[10]; for (int i = 0; i < freq.length; i++) freq[i]= new Freq(); for (int r=0; r<sb.getSize();r++){ for (int c=0; c<sb.getSize();c++){ if (!sb.getCell(r, c).isSolved()){ List<Integer> candidates =sb.getCell(r, c).getCandidates(); for (Integer integer : candidates) { freq[integer.intValue()].add(sb.getCell(r, c)); } } } } for (int i = 1; i < freq.length; i++) { if (freq[i].cells.size()==1){ SolveStep ss = new SolveStep(); ss.setMethod(this); ss.setCell(freq[i].cells.get(0)); ss.setValue(i); return ss; } } } return null; }
8
public static void main(String [] args) { Car car1 = new Car(); Car car2 = new Car(); Car car3 = new Car(); Car car4 = new Car(); Car car5 = new Car(); Car car6 = new Car(); Car car7 = new Car(); Car car8 = new Car(); Car car9 = new Car(); Car car10 = new Car(); Lane firstLane = new Lane(12,1); Lane forwardLane = new Lane(6,1); Lane leftLane = new Lane(6,1); leftLane.createLight(1, 5, 1); forwardLane.createLight(1, 5, 1); leftLane.setParallel(forwardLane); for (int i = 1; i < 30; i++) { if (i == 1) firstLane.putLast(car1); if (i == 2) firstLane.putLast(car2); if (i == 5) firstLane.putLast(car3); if (i == 4) firstLane.putLast(car4); System.out.println(forwardLane + "" + firstLane); System.out.println(leftLane + "\n\n"); firstLane.enterLane(forwardLane,leftLane); forwardLane.step(); leftLane.step(); firstLane.step(); try { Thread.sleep(500); } catch(InterruptedException e) { } } // Skapar ett TrafficSystem // Utfor stegningen, anropar utskriftsmetoder //... }
6
public void fillDeclarables(Collection used) { for (int j = 0; j < methods.length; j++) methods[j].fillDeclarables(used); }
1
@Override public ResultadoAvItem[] getresultadoAvItem(String refeicao, String data) { List<ResultadoAvItem> resultList = new ArrayList<ResultadoAvItem>(); Iterator<List<AvaliacaoItem>> avaliacoes = avItens.values().iterator(); List<AvaliacaoItem> avs = null; while(avaliacoes.hasNext()){ avs = avaliacoes.next(); if(avs != null){ ResultadoAvItem r = new ResultadoAvItem(); r.setItem(avs.get(0).getItem()); r.setData(avs.get(0).getData()); r.setRefeicao(refeicao); r.setDesgostaram(0); r.setGostaram(0); r.setIndiferente(0); for(AvaliacaoItem avi : avs){ if(avi.getRefeicao().equals(refeicao) && avi.getDataFormatoAmericano().equals(data)){ if(avi.getNivelSatisfacao().toString().equals(NivelSatisfacao.GOSTEI.toString())){ r.setGostaram(r.getGostaram() + 1); } else if(avi.getNivelSatisfacao().toString().equals(NivelSatisfacao.DESGOSTEI.toString())){ r.setDesgostaram(r.getDesgostaram() + 1); } else{ r.setIndiferente(r.getIndiferente() + 1); } } } r.setTotalVotos(r.getGostaram() + r.getDesgostaram() + r.getIndiferente()); resultList.add(r); } } return resultList.toArray(new ResultadoAvItem[resultList.size()]); }
7
public void printMergedNodes() { Iterator<Integer> it = mergedNodes.keySet().iterator(); while (it.hasNext()) { int vertex = it.next(); System.out.print(vertex + ":"); LinkedList<Integer> nodes = mergedNodes.get(vertex); if (nodes != null) { System.out.print("["); for (int i : nodes) { System.out.print(i + ","); } System.out.println("]"); } else { System.out.println("null!!"); } } }
3
private void modifyReply(Map<String, Object> jsonrpc2Params) throws Exception { Map<String, Object> params = getParams(jsonrpc2Params, new NullableExtendedParam(Constants.Param.Name.REPLY_ID, false), new NullableExtendedParam(Constants.Param.Name.TEXT, true)); int replyId = (Integer)params.get(Constants.Param.Name.REPLY_ID); String text = (String) params.get(Constants.Param.Name.TEXT); Reply reply = em.find(Reply.class, (Integer) params.get(Constants.Param.Name.REPLY_ID)); if(reply.getAccount().getId() != accountId){ throwJSONRPC2Error(JSONRPC2Error.INVALID_PARAMS, Constants.Errors.ACTION_NOT_ALLOWED); } if(reply == null){ responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.OBJECT_NOT_FOUND); return; } if(text != null){ reply.setText(text); } reply.setTime(getCurrentTime()); persistObjects(reply); responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.SUCCESS); responseParams.put(Constants.Param.Name.REPLY, serialize(reply)); }
3
protected State<TransitionInput> exitCurrentState(State<TransitionInput> newState, State<TransitionInput>... submachineStates) { if(currentState == null) { return null; } State<TransitionInput> previousState = currentState; if(submachine != null) { submachine.exitCurrentState(getFirstState(submachineStates), getRemainingStates(submachineStates)); submachine = null; } if(!currentState.equals(newState) || submachineStates.length == 0) { for(StateMachineEventListener<TransitionInput> listener : eventListeners) { listener.beforeStateExited(currentState, this); } currentState.onExit(); for(StateMachineEventListener<TransitionInput> listener : eventListeners) { listener.afterStateExited(currentState, this); } for(CompositeState<TransitionInput> composite : determineCompositeStatesBeingExited(currentState,newState)) { exitCompositeState(composite); } currentState = null; } return previousState; }
7
private void saveAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAllButtonActionPerformed for (int i = 0; i < tabs.getTabCount(); i++) { SimPanel t = (SimPanel) tabs.getComponentAt(i); if (t.isModified()) { t.save(false); } } try { saveProjectConf(getWork()); } catch (IOException ex) { Main.logger.log(Level.SEVERE, "Error", ex); ex.printStackTrace(System.err); } }//GEN-LAST:event_saveAllButtonActionPerformed
3
public List<T> extractData(ResultSet rs) throws SQLException { List<T> results = (this.rowsExpected > 0 ? new ArrayList<T>(this.rowsExpected) : new ArrayList<T>()); int rowNum = 0; while (rs.next()) { results.add(this.rowMapper.mapRow(rs, rowNum++)); } return results; }
2
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
void readLinesCheck(String vcf, int numTests) { Random random = new Random(20130218); System.out.println("Opening file '" + vcf + "'"); FileIndexChrPos idx = new FileIndexChrPos(vcf); idx.setVerbose(verbose); idx.open(); // Get file size long size = (new File(vcf)).length(); for (int i = 1; i < numTests; i++) { long randPos = random.nextInt((int) size); // Compare methods LineAndPos lineSlow = idx.getLineSlow(randPos); // This method we trust LineAndPos line = idx.getLine(randPos); // This method we test // Check and show differences if (!line.line.equals(lineSlow.line)) { System.err.println("Length: " + lineSlow.line.length() + "\t" + line.line.length()); System.err.println("Lines:\n\t" + lineSlow.line + "\n\t" + line.line); int shown = 0; for (int j = 0; j < line.line.length(); j++) { System.err.print(j + "\t'" + lineSlow.line.charAt(j) + "'\t'" + line.line.charAt(j) + "'"); if (lineSlow.line.charAt(j) != line.line.charAt(j)) { System.err.print("\t<---"); if (shown++ > 20) break; } System.err.println(""); } } Assert.assertEquals(lineSlow.line, line.line); Assert.assertEquals(lineSlow.position, line.position); Gpr.showMark(i, 1); } }
5
public int compareTo(ReviewJournal o) { if (o.score == score) return title.compareTo(o.title); return score > o.score ? -1 : 1; }
2
private void handle(String role, String order) throws Exception { //leader if(role.equals("l1")){ //System.out.println("leader handle"); l1.setOrder(order); l1.action(); }else if(role.equals("l2")){ //System.out.println("leader handle"); l2.setOrder(order); l2.action(); }else if(role.equals("s1")){ //System.out.println("leader handle"); s1.setOrder(order); s1.action(); }else if(role.equals("s2")){ //System.out.println("leader handle"); s2.setOrder(order); s2.action(); }else if(role.equals("s3")){ //System.out.println("leader handle"); s3.setOrder(order); s3.action(); }else if(role.equals("s4")){ //System.out.println("leader handle"); s4.setOrder(order); s4.action(); }else if(role.equals("s5")){ //System.out.println("leader handle"); s5.setOrder(order); s5.action(); }else if(role.equals("s6")){ //System.out.println("leader handle"); s6.setOrder(order); s6.action(); }else if(role.equals("cood")){ //System.out.println("leader handle"); cood.setOrder(order); cood.action(); } else{ System.out.println("Role is incorrect! role="+role); } }
9
public void morrisTraverse(TreeNode root) { while (root != null) { if (root.getLeft() == null) { System.out.println(root.getData()); root = root.getRight(); } else { TreeNode ptr = root.getLeft(); while (ptr.getRight() != null && ptr.getRight() != root) ptr = ptr.getRight(); if (ptr.getRight() == null) { ptr.setRight(root); root = root.getLeft(); } else { ptr.setRight(null); System.out.println(root.getData()); root = root.getRight(); } } } }
5
public static int curiousNumberDenom() { int num = 1; int den = 1; for (int i = 10; i < 100; i++) { for (int j = 10; j < 100; j++) { if (isCurious(i, j)) { num *= j; den *= i; } } } for (int i = 2; i <= num; i++) { while (true) { if (num == 1) { break; } if (num % i == 0 && den % i == 0) { num /= i; den /= i; } else break; } } return den; }
8
@Override public void process(ChatSocket sock, ChatPacket packet) { if (packet.getType() == PacketType.MANIFEST) { ManifestMessage mfst = (ManifestMessage) packet.getPayload(); // For every persistence sequence number locally known... for (int seq : sock.getPersistenceManager().getHeard(mfst.getSrc())) { // If the remote instance hasn't received it.... if (!mfst.getSeqs().contains(seq)) { // Push the message out try { PushMessage msg = new PushMessage(mfst.getSrc(), sock.getPersistenceManager().getPacket( mfst.getSrc(), seq)); sock.sendPacket(sock.wrapPayload(msg)); } catch (IOException e) { Logging.getLogger().warning("Unable to send PushMessage"); } } } // For every persistence sequence number remotely known.. for (int seq : mfst.getSeqs()) { Set<Integer> heard = sock.getPersistenceManager().getHeard(mfst.getSrc()); // If the local instance hasn't received it... if (!heard.contains(seq)) { // Push a manifest out try { sock.sendPacket(sock.wrapPayload(new ManifestMessage(mfst.getSrc(), heard))); return; } catch (IOException e) { Logging.getLogger().warning("Unable to send ManifestMessage"); } } } } }
7
private void method393(int ai[], byte abyte0[], int i, int j, int k, int l, int i1, int j1, int k1) { int l1 = -(l >> 2); l = -(l & 3); for(int i2 = -i1; i2 < 0; i2++) { for(int j2 = l1; j2 < 0; j2++) { if(abyte0[j++] != 0) ai[k++] = i; else k++; if(abyte0[j++] != 0) ai[k++] = i; else k++; if(abyte0[j++] != 0) ai[k++] = i; else k++; if(abyte0[j++] != 0) ai[k++] = i; else k++; } for(int k2 = l; k2 < 0; k2++) if(abyte0[j++] != 0) ai[k++] = i; else k++; k += j1; j += k1; } }
8
@Override public void run() { Start.display("Initialized loop for " + this.getTempAlias()); // Run the loop while it's still open. boolean running = true; while (running) { String message; try { message = (String) input.readObject(); if (CommandFormat.isCommand(message)) { CommandHandler.onCommandReceived(this.identifier, message); } else { Start.display(alias + ": " + message); } } catch (ClassNotFoundException e) { break; } catch (IOException e) { if (socket.isClosed()) { break; } Start.display("Can not read the streams (" + e.toString() + ")."); break; } } // Remove the connection from the handler. Start.display(this.getTempAlias() + " disconnected"); Start.connectionHnd.remove(identifier); disconnect(); }
5
public static void main(String[] args) { Scanner in = new Scanner(System.in); int num1 = Integer.parseInt(in.next()); double num2 = Integer.parseInt(in.next()); if (num2 == 0) { System.out.println("Error: divide by zero!"); System.exit(0); } System.out.println(num1 / num2); }
1
public boolean optimal(int[] bowl, int bowlId, int round) { //System.out.println("Inside Optimal.."); int bowlScore=0; bowlScore = buildDistribution(bowl, bowlId, round); if (maxBowls[round] == 2) { scoresSeen.add(bowlScore); len[round]++; return Math.random()>0.5; } if (maxBowls[round] == 3) { //System.out.println("inside max bowls = 3"); if (bowlsSeen[round] >= 2) { int maxScore = getMaxScore(scoresSeen, start[round], len[round]); scoresSeen.add(bowlScore); len[round]++; //System.out.println("Max Score: "+maxScore); return maxScore <= bowlScore; } else { //System.out.println("Want to pass... "+"true"); scoresSeen.add(bowlScore); len[round]++; return false; } } //System.out.println("n/e value: "+Math.floor((double)(maxBowls[round])/(double)(Math.E))); if (Math.floor((double)(maxBowls[round])/(double)(Math.E)) < bowlsSeen[round]) { //System.out.println("inside general case"); int maxScore = getMaxScore(scoresSeen, start[round], len[round]); scoresSeen.add(bowlScore); len[round]++; //System.out.println("Max Score: "+maxScore); return maxScore <= bowlScore; } else { //System.out.println("else..."); scoresSeen.add(bowlScore); len[round]++; //System.out.println("Want to pass... "+"true"); return false; } }
4
private static String getSelectionString (Object selection) { StringBuilder builder = new StringBuilder(); try { XServiceInfo selectionServiceInfo = As.XServiceInfo (selection); if (selectionServiceInfo.supportsService ("com.sun.star.text.TextRanges")) { XIndexAccess indexAccess = As.XIndexAccess (selection); XTextRange textRange = null; for (int i = 0; i < indexAccess.getCount(); i++) { textRange = As.XTextRange (indexAccess.getByIndex (i)); try { XEnumeration paragraphEnumeration = OfficeUtil.enumerationFor (textRange); while (paragraphEnumeration.hasMoreElements()) { XTextContent textContent = As.XTextContent (paragraphEnumeration.nextElement()); XServiceInfo textContentServiceInfo = As.XServiceInfo (textContent); if (textContentServiceInfo.supportsService ("com.sun.star.text.Paragraph")) { XEnumeration portionEnumeration = OfficeUtil.enumerationFor (textContent); while (portionEnumeration.hasMoreElements()) { Object portion = portionEnumeration.nextElement(); XPropertySet portionProperties = As.XPropertySet (portion); String textPortionType = (String)portionProperties.getPropertyValue ("TextPortionType"); if (textPortionType.equals ("Text")) { XTextRange portionTextRange = As.XTextRange (portion); String content = portionTextRange.getString(); builder.append (content); if (builder.length() > Commands.MAX_DICTIONARY_SEARCH_LENGTH) { return builder.substring (0, Commands.MAX_DICTIONARY_SEARCH_LENGTH); } } } } } } catch (NoSuchElementException e) { // TODO http://www.openoffice.org/issues/show_bug.cgi?id=74054 // Iterating over text sections inside table cells has some issues. } } } } catch (Throwable t) { // Invalid range exceptions can occur due to the lack of synchronisation // with dispose events et al. Probably better simply to ignore the // exception, given the risk of deadlocks in trying to synchronise the // whole affair properly } return builder.toString(); }
9
public void renderEntities(){ for (GameObject gameObject : entityList) { gameObject.render(); } }
1
@Override public void decreaseAmount(ResourceType resource) { switch(resource){ case BRICK: discardView.setResourceDiscardAmount(ResourceType.BRICK, --brickDiscardAmount); updateButtons(brickDiscardAmount,brickMax,resource); break; case ORE: discardView.setResourceDiscardAmount(ResourceType.ORE, --oreDiscardAmount); updateButtons(oreDiscardAmount,oreMax,resource); break; case SHEEP: discardView.setResourceDiscardAmount(ResourceType.SHEEP, --sheepDiscardAmount); updateButtons(sheepDiscardAmount,sheepMax,resource); break; case WHEAT: discardView.setResourceDiscardAmount(ResourceType.WHEAT, --wheatDiscardAmount); updateButtons(wheatDiscardAmount,wheatMax,resource); break; case WOOD: discardView.setResourceDiscardAmount(ResourceType.WOOD, --woodDiscardAmount); updateButtons(woodDiscardAmount,woodMax,resource); break; } totalDiscardSelected--; discardView.setDiscardButtonEnabled(false); updateResourceValues(); discardView.setStateMessage(totalDiscardSelected + "/" + totalResources/2); }
5
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
private static void filterCSV(String filename, LinkedList<String> filters, LinkedList<String> includes) throws IOException { FileReader fr = new FileReader(filename); CsvReader csvIn = new CsvReader(fr, SEPARATOR); csvIn.setSafetySwitch(false); if(csvIn.readHeaders()) { csvIn.readRecord(); System.out.println("'" +filename +"' has " +csvIn.getColumnCount() +" column."); int usedColumn = 0; String[] headers = csvIn.getHeaders(); StringBuffer newHeader = new StringBuffer(); StringBuffer newValues = new StringBuffer(); HashMap<String,String> data = new HashMap<String, String>(); allData.put(filename, data); for(String header : headers) { boolean matches = false; // check if a filter matches the entry for(String filter : filters) { if(header.contains(filter)) { matches = true; // ok, filter matches, but maybe it is on the include list? for(String include : includes) { if(header.contains(include)) { matches = false; break; } } break; } } if(!matches) { usedColumn++; String value = csvIn.get(header); newHeader.append(header); newHeader.append(SEPARATOR_OUT); newValues.append(value); newValues.append(SEPARATOR_OUT); if(data != null) { if(!keys.containsKey(header)) { keys.put(header, true); } data.put(header, value); } } } System.out.println(" -> " +usedColumn +" column remains"); FileWriter fw = new FileWriter(filename +FILENAME_POSTFIX, false); fw.write(newHeader.toString()); fw.write(NEW_LINE); fw.write(newValues.toString()); fw.close(); } else { System.err.println("Can not read header from '" +filename +"'"); } }
9
public String getFormTrackTitle(int formTrackNumber) throws SQLException { List<Track> trackRepTracks = new LinkedList<Track>(); for (Track t : getTracks()) if (t.getFormTrackNumber() == formTrackNumber) trackRepTracks.add(t); if (trackRepTracks.size() == 1) if (trackRepTracks.get(0).getTitle().trim().length() == 0) return "EMPTY_TITLE"; else return trackRepTracks.get(0).getTitle(); StringBuffer title = new StringBuffer(trackRepTracks.get(0).getTitle()); for (Track tck : trackRepTracks.subList(1, trackRepTracks.size())) title.append(" / " + tck.getTitle()); // Check on the track title here if (title.toString().trim().length() == 0) return "EMPTY_TITLE"; return title.toString(); }
6
public static Properties readFile(Log log, File file) { InputStream stream = null; Properties properties = new Properties(); log.info("Reading from config file"); try { if (file == null) { log.warn("No config file given"); } else { stream = new FileInputStream(file); properties.load(stream); } } catch (FileNotFoundException e) { log.error("Config file not found", e); } catch (SecurityException e) { log.error("No read access for config file", e); } catch (IllegalArgumentException e) { log.error("Improper config format", e); } catch (IOException e) { log.error("IO failure while reading config file", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { log.warn("Failed to close stream to config file"); } } } return properties; }
7
public String getSuitAsString() { switch (suit) { case SPADES: return "Spades"; case HEARTS: return "Hearts"; case DIAMONDS: return "Diamonds"; case CLUBS: return "Clubs"; default: return "??"; } }
4
@Override public void deserialize(Buffer buf) { playerId = buf.readInt(); if (playerId < 0) throw new RuntimeException("Forbidden value on playerId = " + playerId + ", it doesn't respect the following condition : playerId < 0"); playerName = buf.readString(); alignmentSide = buf.readByte(); breed = buf.readByte(); if (breed < PlayableBreedEnum.Feca.value() || breed > PlayableBreedEnum.Steamer.value()) throw new RuntimeException("Forbidden value on breed = " + breed + ", it doesn't respect the following condition : breed < PlayableBreedEnum.Feca.value() || breed > PlayableBreedEnum.Steamer.value()"); sex = buf.readBoolean(); isInWorkshop = buf.readBoolean(); worldX = buf.readShort(); if (worldX < -255 || worldX > 255) throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255"); worldY = buf.readShort(); if (worldY < -255 || worldY > 255) throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255"); mapId = buf.readInt(); subAreaId = buf.readShort(); if (subAreaId < 0) throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0"); }
8
@Override public ContextKey createContextPartitionKey(int partition, String context, Class<?> contextType) { return new ContextKey(partition, context, contextType); }
1
public void setPlayerOneWin() { currentState = States.PlayerOneWin; }
0
public void setboss(Player p) { this.boss = p; oldclass = plugin.getHero(p).getHeroClass(); }
0
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int b = in.nextInt(); ArrayList<Integer> result = new ArrayList<Integer>(); int index = 1; while(n-->0){ int ni = in.nextInt(); int possible = 0; for(int i=0;i<ni;i++){ int t = in.nextInt(); if (t<b){ possible = 1; } } if(possible == 1){ result.add(index); } index++; } System.out.println(result.size()); for(int i:result){ System.out.printf("%d ", i); } }
5
public boolean getBoolean(int index) throws JSONException { Object object = get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
6
public void send() { if (!isConnected) { JOptionPane.showMessageDialog(null, "還未連線,不能發送訊息!", "Error", JOptionPane.ERROR_MESSAGE); return; } String message = textField.getText().trim(); if (message == null || message.equals("")) { JOptionPane.showMessageDialog(null, "禁止發廢文!", "Error", JOptionPane.ERROR_MESSAGE); return; } sendMessage(frame.getTitle() + "@" + "ALL" + "@" + message); textField.setText(null); }
3
@Override final public void computeGradient() { // final int last = this.frameidx; // // from last to first layer. // for (int l = this.structure.layers.length - 1; l >= 0; l--) { // if (l == this.structure.inputlayer) continue; final Layer layer = this.structure.layers[l]; // // regular or reversed layer? // if (layer.tag == LayerTag.REGULAR) { this.setFrameIdx(last); for (int t = last; t >= 0; t--) { // if (t < last) { this.copyGradOutput( this.frameidx + 1, this.frameidx, l ); } this.computeLayerGradients(l); // this.decrFrameIdx(); } } else { this.setFrameIdx(0); for (int t = 0; t <= last; t++) { // if (t > 0) { this.copyGradOutput( this.frameidx - 1, this.frameidx, l ); } this.computeLayerGradients(l); // this.incrFrameIdx(); } } } // this.setFrameIdx(last); }
7
public void printOut() { // just a console printout for debugging System.out.println("Task Name: " + taskName); System.out.println("Duration(ms): " + calculateDuration()); if (taskParent != null) { System.out.println("Parent: " + taskParent.getName()); } else { System.out.println("No Parent"); } System.out.println("Depedent Nodes:"); if (dependentNodes.isEmpty()) { System.out.println(" None"); } else { for (Task currentTask : dependentNodes) { System.out.println(" " + currentTask.getName()); } } System.out.println("Children:"); if (children.isEmpty()) { System.out.println(" None"); } else { for (Task currentTask : children) { System.out.println(" " + currentTask.getName()); } } }
5
public boolean guardarCambios(){ File f; f = new File("parametros.conf"); try { FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); pw.write("ruta_excel=>"+this.ruta_excel); pw.close(); bw.close(); JOptionPane.showMessageDialog(null,"Se ha guardado la configuración correctamente."); return true; } catch (IOException e) { JOptionPane.showMessageDialog(null,"No se ha podido guardar la configuración."); return false; } }
1
public static void main(String[] args) { Parcel p = new Parcel(); p.ship("Tasmania"); Parcel q = new Parcel(); // Defining references to inner classes: Contents c = q.contents(); Destination d = q.to("Borneo"); }
0
public boolean foodAhead() { if (direction.equals(Direction.RIGHT)) { return map.getTrailAt(x, (y >= h - 1 ? 0 : y + 1)); } if (direction.equals(Direction.LEFT)) { return map.getTrailAt(x, (y <= 0 ? h - 1 : y - 1)); } if (direction.equals(Direction.UP)) { return map.getTrailAt((x <= 0 ? w - 1 : x - 1), y); } if (direction.equals(Direction.DOWN)) { return map.getTrailAt((x >= w - 1 ? 0 : x + 1), y); } return false; }
8
public FileReadException(String message) { super(message); }
0
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
9
String nextControlWord() throws StorageReaderException { try { String line = file.readLine(); while(line != null && (isCommentString(line) || !isControlWord(line))) { line = file.readLine(); } if(isEndOfBlock(line)) { throw new EndOfBlockException(fileName); } return line; } catch(IOException e) { throw new StorageReaderException(e); } }
5
public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); if (line == null || line.equals("")) return; String[] lines = line.split("\t"); Post post = new Post(lines[0]); String content = lines[1]; List<String> words = util.splitWords(post.getTitle()); if (words != null) { for(String word : words) { record.clear(); record.set(word); offset.clear(); offset.set(key.toString()); // + "|" + post.getLink() context.write(record, offset); } } words = util.splitWords(content); if (words != null) { for(String word : words) { record.clear(); record.set(word); offset.clear(); offset.set(key.toString()); context.write(record, offset); } } }
6
@Override public Iterator<String> iterator() { return cookies.keySet().iterator(); }
0
private void txPesqNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txPesqNomeKeyPressed String nome = txPesqNome.getText(); if(nome.length()>0){ ConsultaController pc = new ConsultaController(); modelo.setNumRows(0); for (Consulta p : pc.listByNome(nome)) { String data = ""; String hora = ""; String linome = ""; try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); hora = sdf.format(p.getHorario()); } catch (Exception ex) { System.out.println("Entrou na excessão Hora: " + ex.getMessage()); hora = ""; } try { SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy"); data = sdfd.format(p.getDataDaConsulta().getTime()); } catch (Exception e) { System.out.println("entrou na excessão data nula: " + e.getMessage()); data = ""; } try { linome = p.getPaciente().getNome(); } catch (Exception e) { System.out.println("entrou na excessão data nula: " + e.getMessage()); } if(!linome.equals(" ")){ System.out.println("Nome:"+linome+":"); modelo.addRow(new Object[]{p.getCodigo(), hora, data, linome, p.getTipoConsulta()}); } } } }//GEN-LAST:event_txPesqNomeKeyPressed
6
public static String gettext(AttributedCharacterIterator s) { StringBuilder tbuf = new StringBuilder(); for(int i = s.getBeginIndex(); i < s.getEndIndex(); i++) tbuf.append(s.setIndex(i)); return(tbuf.toString()); }
1
public Move createMoveFromString(String instruction) { String[] Split = instruction.split(" "); String owner = Split[0]; int ID = Integer.parseInt(Split[1]); Player player = null; if(owner.equals(Character.toString('R'))) player = Player.Rom; else if(owner.equals(Character.toString('C'))) player = Player.Cathargo; Move move = new Move(player, ID); return move; }
2
@Override public Balance addBusinessObject(Balance value) throws EmptyNameException, DuplicateNameException { try { return addBusinessObject(value, value.getUniqueProperties()); } catch (DuplicateNameException ex) { String name = value.getName(); if (YEAR_BALANCE.equals(name) || RESULT_BALANCE.equals(name) || RELATIONS_BALANCE.equals(name)) { System.err.println("Default Balance (" + name + ") already exists!"); return getBusinessObject(name); } else { throw ex; } } }
4
public void mousePressed(MouseEvent paramMouseEvent) { if (TextButton.this.Clickable) { if ((TextButton.this.player != null) && (TextButton.this.sound != null)) { TextButton.this.player.play(TextButton.this.sound); } if (TextButton.this.MousePressedBackgroundColor != null) { TextButton.this.setBackgroundColor(TextButton.this.MousePressedBackgroundColor); TextButton.this.setColor(TextButton.this.MousePressedTextColor); } if (TextButton.this.VerboseEvents) TextButton.this.event(paramMouseEvent); } }
5
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((backFace == null) ? 0 : backFace.hashCode()); result = prime * result + ((bottomFace == null) ? 0 : bottomFace.hashCode()); result = prime * result + ((coord == null) ? 0 : coord.hashCode()); result = prime * result + ((frontFace == null) ? 0 : frontFace.hashCode()); result = prime * result + ((leftFace == null) ? 0 : leftFace.hashCode()); result = prime * result + ((rightFace == null) ? 0 : rightFace.hashCode()); result = prime * result + rubiksCubeSize; result = prime * result + ((topFace == null) ? 0 : topFace.hashCode()); return result; }
7
public static void delete(CommandSender sender, String [] args){ if(sender.hasPermission("battlegrounds.team.delete")){ //If missing parameters if(args.length < 2+1){ sender.sendMessage(ErrorMessage.MissingParameters); sender.sendMessage(ChatColor.YELLOW + usage); } else if(args.length > 2+1+1){ sender.sendMessage(ErrorMessage.TooManyParameters); sender.sendMessage(ChatColor.YELLOW + usage); } else{ String name = args[2]; //If name is too long of too short if(name.length() < ConfigBG.minTeamNameLength || name.length() > ConfigBG.maxTeamNameLength){ sender.sendMessage(ChatColor.RED + "Your team name is too long or too short."); } else if(TeamsManager.getInstance().isTeamExist(name)){ for(String teamPlayers : TeamsManager.getInstance().getTeamByName(name).getMembers()){ try{ Bukkit.getServer().getPlayer(teamPlayers).sendMessage(ChatColor.GOLD + String.format("Team %s has been deleted.", name)); } catch(NullPointerException e){} } TeamsManager.getInstance().deleteTeam(name); sender.sendMessage(ChatColor.GREEN + String.format("Team [%s] delete.", name)); } else{ sender.sendMessage(ChatColor.RED + String.format("Can not delete team [%s].", name)); } } } else{ sender.sendMessage(ErrorMessage.NotAllowed); } }
8
public Node<K> getRoot() { return root; }
0
@Override public boolean isComponent(JsonObject jsonObject) { return jsonObject.get("showdigitalclock") != null && jsonObject.get("showweather") != null && jsonObject.get("type").getAsString().equals("timeofdayclock"); }
2
@Override public boolean doValidation() { if(nameTextField.getText().isEmpty()){ addToValidationMassage("name is empty!"); return false; } if(priceTextField.getText().isEmpty()){ addToValidationMassage("price is empty!"); return false; } if(quantityTextField.getText().isEmpty()){ addToValidationMassage("quantity is empty!"); return false; } return true; }
3
public void run() { while (true) { if (socket.isConnected()) { try { System.out.println("Listening on port " + socket.getPort() + " for incoming messages"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = reader.readLine(); System.out.println("[Client Id = " + socket.toString() + "] Message received: " + msg); if (msg.equals("updateview")) { task.run(); } } catch (IOException e) { System.out.println("I/O error while trying to read messages from server"); return; } } else { Thread.yield(); } } }
4
private float move(float p, int index, Float max, Float min) { float value = 0f; if((min != null && max != null) && allowed[index]) { if(isInRange(p, max, min)) { value = p; } else if(p > max) { value = max; } else { value = min; } } else if(allowed[index]) { value = p; } return value; }
6
public UserInfo setUserInfo(String username, String password, String newPassword, String name, String organization, String position, String phone, String email, String extraInfo)throws XMPPException{ if(newPassword != null && newPassword.length() < 6) throw new XMPPException(new XMPPError(XMPPError.Condition.not_allowed, "userdata.newpassword.incorrect")); if(password != null && "".equals(password.trim())) throw new XMPPException(new XMPPError(XMPPError.Condition.not_allowed, "userdata.password.incorrect")); DHEncoder encoder = new DHEncoder(connection.getKey()); String encodedPassword = password!=null?encoder.encode(password):null; String encodedNewPassword = password!=null?encoder.encode(newPassword):null; UserInfo reg = new UserInfo(encodedPassword, encodedNewPassword, name, organization, position, phone, email, extraInfo); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); UserInfo result = (UserInfo)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } return result; }
8
public Constant newFloat(final float value) { key1.set(value); Constant result = get(key1); if (result == null) { result = new Constant(key1); put(result); } return result; }
1
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return true; final MOB mob=(MOB)affected; if((msg.targetMajor(CMMsg.MASK_MALICIOUS)) &&(((msg.source()==mob)&&(msg.target()!=null)&&(isTruceWith(msg.target().Name()))) ||((msg.target()==mob)&&(isTruceWith(msg.source().Name())))) &&(!msg.sourceMajor(CMMsg.MASK_ALWAYS))) { msg.source().tell(msg.source(),msg.target(),null,L("You have made peace with <T-NAMESELF>.")); msg.source().makePeace(true); if(msg.target() instanceof MOB) ((MOB)msg.target()).makePeace(true); return false; } return super.okMessage(myHost,msg); }
9
public void removeTask(Task task) { if (DEBUG) log("Find the taskWidget that contains the desired task"); TaskWidget target = null; for (TaskWidget tw : taskWidgets) { if (tw.getTask() == task) { target = tw; } } if (target == null) { if (DEBUG) log("Failed to find desired taskWidget"); } else { if (DEBUG) log("Found the desired taskWidget...now just remove it"); taskWidgets.remove(target); centerContent.remove(target); } repaint(); revalidate(); }
6
public void addChatMessage(String s) { if(!s.trim().isEmpty()){ for(Component l : main.getContentPane().getComponents()){ if(l instanceof JLabel && l != name && l != creator && l != players){ l.setLocation(l.getLocation().x, l.getLocation().y - 20); if(l.getLocation().y <= 120){ main.getContentPane().remove(l); } } } JLabel chat = new JLabel("<html><body style='width:770px'><TEXT=#FFF8F0>" + s + "</font>"); chat.setForeground(Color.gray); chat.setBounds(15, 515, 780, 20); chat.setFont(new Font(chat.getFont().getFontName(), Font.TRUETYPE_FONT, 15)); main.add(chat); main.repaint(); } }
7
public void stopSpel(){ //stopt het spel en opent hoofdMenuPanel (als spel nog bezig is, eerst bevestiging via dialog) if(spel.isSpelBezig() && toonStopDialog() == JOptionPane.NO_OPTION) return; try{ spel.resetSpel(); } catch(Exception e){ toonError(e); } openHoofdMenuPanel(); }
3
public void setCityImageLocation(String forceName) { switch (forceName) { case "曹操": cityImageLocation = "/resources/caocaoCityColour.png"; cityImagePressedLocation = "/resources/caocaoCityPressedColour.png"; break; case "刘备": cityImageLocation = "/resources/liubeiCityColour.png"; cityImagePressedLocation = "/resources/liubeiCityPressedColour.png"; break; case "孙权": cityImageLocation = "/resources/sunquanCityColour.png"; cityImagePressedLocation = "/resources/sunquanCityPressedColour.png"; break; case "刘表": cityImageLocation = "/resources/liubiaoCityColour.png"; cityImagePressedLocation = "/resources/liubiaoCityPressedColour.png"; break; default: cityImageLocation = "/resources/caocaoCityColour.png"; cityImagePressedLocation = "/resources/caocaoCityPressedColour.png"; break; } }
4
private Object readDouble() { return readFloat(); }
0
public final void draw(byte i, boolean bool) { anInt4696++; if (i != -49) method2022(null, 101); if (bool) { int width = (Class321.windowWidth > Class92.anInt1524 ? Class321.windowWidth : Class92.anInt1524); int height = (((OpenGlToolkit.anInt7666 ^ 0xffffffff) > (Class348_Sub42_Sub8_Sub2.windowHeight ^ 0xffffffff)) ? Class348_Sub42_Sub8_Sub2.windowHeight : OpenGlToolkit.anInt7666); int i_2_ = rasterToolkit.method966(); int i_3_ = rasterToolkit.method980(); int i_4_ = 0; int i_5_ = width; int i_6_ = width * i_3_ / i_2_; int i_7_ = (height - i_6_) / 2; if (height < i_6_) { i_6_ = height; i_5_ = height * i_2_ / i_3_; i_7_ = 0; i_4_ = (width - i_5_) / 2; } rasterToolkit.method973(i_4_, i_7_, i_5_, i_6_); } }
5
public List<CarrierInfo> findOFDMCarriersWithinRange (double spectrum[],double sampleRate,int binCount,double multiFactor,int startBin,int endBin) { List<CarrierInfo> cList=new ArrayList<CarrierInfo>(); int a; double dPoint=-1.0; for (a=startBin;a<endBin;a++) { if (spectrum[a]>dPoint) dPoint=spectrum[a]; } dPoint=dPoint*multiFactor; for (a=startBin;a<endBin;a++) { // Check the current spectrum value is higher than the last one and the next one // if it is then this is a peak so classify this as a carrier if ((spectrum[a]>spectrum[a-1])&&(spectrum[a]>spectrum[a+1])&&(spectrum[a]>dPoint)) { CarrierInfo cInfo=new CarrierInfo(); cInfo.setBinFFT(a); cInfo.setEnergy(spectrum[a]); // Calculate the actual frequency of the carrier double freq=(double)a*(sampleRate/(double)binCount); cInfo.setFrequencyHZ(freq); // Add this carrier object to the list cList.add(cInfo); } } return cList; }
6
protected void initializeDictionaries() throws MojoFailureException { // Read the dictionary files try { // Load the default dictionary dictionary.addDictionary(getClass().getResourceAsStream("/eap6.dict")); for (File f : dictionaryFiles) dictionary.addDictionary(f); } catch (Exception e) { throw new MojoFailureException("Cannot load dictionaries", e); } // Get the artifacts Set<Artifact> artifacts = project.getArtifacts(); for (Artifact x : artifacts) getLog().debug("Artifact:" + x); // Find artifacts that are not provided, but in the dictionary, // and warn Set<Artifact> artifactsNotProvided = new TreeSet<Artifact>(); // Find artifacts that should be in deployment structure, that is, // all artifacts that have a non-null mapping, and provided artifactsAsModules = new HashMap<Artifact, String>(); reverseMap = new HashMap<String, Artifact>(); for (Artifact a : artifacts) { DictItem item = dictionary.find(a.getGroupId(), a.getArtifactId(), a.getVersion()); if (item != null && item.moduleName != null) { reverseMap.put(item.moduleName, a); if (!a.getScope().equals(Artifact.SCOPE_PROVIDED)) { artifactsNotProvided.add(a); } else { artifactsAsModules.put(a, item.moduleName); } } } for (Artifact a : artifactsNotProvided) { getLog().warn( "EAP6: Artifact " + a + " is not provided, but can be included as an EAP6 module " + dictionary.find(a.getGroupId(), a.getArtifactId(), a.getVersion())); } }
8
@Override public String toString() { String message = ""; // Include name into message message += "Name:\n" + name; // Include done or not if (isDone) { message += " [Done]\n\n"; } else { message += "\n\n"; } // Include description into message if (!description.isEmpty()) { message += "Description:\n" + description + "\n\n"; } // Include start and end into message if ( !getFormattedStart().isEmpty() ) { message += "Starting Time:\n" + getFormattedStart() + "\n\n"; } if ( !getFormattedEnd().isEmpty() ) { message += "Ending Time:\n" + getFormattedEnd() + "\n\n"; } // Include deadline into message if (deadline != NOT_VALID) { message += "Deadline:\n" + getFormattedDeadline() + "\n\n"; } // Include reminder into message if (reminder != NOT_VALID) { message += "Reminder:\n" + getFormattedReminder() + "\n\n"; } // Include label into message String labelName = getLabelName(); if (!labelName.equals(Operations.EMPTY_MESSAGE)) { message += "Label:\n" + labelName + "\n"; } return message + "\n"; }
7
public Trame[] getTrame() { return trame; }
0
public static void back(double curMoney, int last) { if ((totalDis - stations[last].dis) <= (galCapacity * milesPerGal) && curMoney != 0) { if (curMoney < min) min = curMoney; } else { for (int i = last + 1; i < stations.length; i++) { double dis = stations[i].dis - stations[last].dis; double fuelDis = galCapacity - (dis / milesPerGal); if ((noNext(i, last, galCapacity) || stop(galCapacity, dis)) && fuelDis >= 0) back(curMoney + 200 + (galCapacity - fuelDis) * stations[i].gallon, i); } } }
7
private void configureListeners() { /* * Changes to be done in text box on change of seletedDate , * selectedMonth and selectedYear in DatePicker. */ ChangeListener<Object> listener = new ChangeListener<Object>() { @Override public void changed(ObservableValue<? extends Object> arg0, Object arg1, Object arg2) { showDateInTextField(); } }; selectedDateProperty().addListener(listener); selectedMonthProperty().addListener(listener); selectedYearProperty().addListener(listener); showDateInTextField(); properties.localeProperty().addListener(new ChangeListener<Locale>() { @Override public void changed(ObservableValue<? extends Locale> arg0, Locale arg1, Locale arg2) { pickerPopup.refreshDisplayText(); } }); /* Adding listeners for styles. */ getStyleClass().addListener(new ListChangeListener<String>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends String> paramChange) { dateTxtField.getStyleClass().clear(); dateTxtField.getStyleClass().addAll("text-input", "text-field"); for (String clazz : getStyleClass()) { if (!clazz.equals(DEFAULT_STYLE_CLASS)) { dateTxtField.getStyleClass().add(clazz); } } } }); }
5
public List<HipchatUser> getStandupUsers() { List<HipchatUser> remaining_users = new ArrayList<HipchatUser>(); List<String> user_names = getSelectedRoom().getConnectedUsers(); List<HipchatUser> users = new ArrayList<HipchatUser>(); for ( String user_name : user_names ) { HipchatUser user = findUser(user_name.substring(user_name.indexOf("/")+1)); if ( user != null ) users.add(user); } for ( HipchatUser user : users ) { if ( !user.getStatus().equals("offline") && !user.getName().equals(nickname()) && !botData.blacklist.contains( user.getMentionName() ) && !users_early_standup.contains(user.getMentionName()) ) { remaining_users.add(user); } } return remaining_users; }
7
private static String getPostionInBase64Table(char c) { if((c >= 65 && c <= 90))// Gro�buchstabe return c - 65 + ""; else if((c >= 97 && c <= 122))// Kleinbuchstabe return c - 71 + ""; else if((c >= 48 && c <= 57))// Ziffern return c + 4 + ""; else if(c == 43)// Sonderzeichen + return c + 19 + ""; else return c + 16 + ""; }
7
private ArrayList<Vertex<T>> getPath( ArrayList<Tuple<Pair<Vertex<T>>, Double>> vertexPairs, Vertex<T> src, Vertex<T> dest ) { ArrayList<Vertex<T>> path = new ArrayList<Vertex<T>> (); Vertex<T> successor = dest; Pair<Vertex<T>> tempPair = null; // trace the path backwards from the destination to the source by // finding each vertex's minimum cost predecessor in this path. while ( successor != src ) { double minCost = Double.MAX_VALUE; // assume the worst :-( // now find the predecessor on the cheapest path to successor for ( int i = 0; i < vertexPairs.size(); i++ ) { Tuple<Pair<Vertex<T>>, Double> tuple = vertexPairs.get( i ); Pair<Vertex<T>> pair = tuple.getFirstElement(); // got another candidate vertex tuple, see if this one // has a cheaper cost than another other path to successor // seen so far if ( pair.getSecondElement().equals( successor ) ) { // it is possible there are multiple "cheapest" paths // to successor; want to avoid adding duplicates if ( !path.contains( successor ) ) { path.add( successor ); } double cost = tuple.getSecondElement(); if ( cost < minCost ) { minCost = cost; // new lowest cost path to successor tempPair = pair; } // remove it so we never need to look at it again // assumes the caller isn't going to need this list // intact! vertexPairs.remove( i ); } } // the predecessor for successor becomes the new successor, // as we move backward in the path from destination to source successor = tempPair.getFirstElement(); } path.add( src ); // vertices added in reverse order, fix that Collections.reverse( path ); return path; }
5