text
stringlengths
14
410k
label
int32
0
9
private void testAbstractMethods(ByteMatcher matcher) { // test methods from abstract superclass assertEquals("length is one", 1, matcher.length()); assertEquals("matcher for position 0 is this", matcher, matcher.getMatcherForPosition(0)); try { matcher.getMatcherForPosition(-1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.getMatcherForPosition(1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} assertEquals("reversed is identical", matcher, matcher.reverse()); assertEquals("subsequence of 0 is identical", matcher, matcher.subsequence(0)); try { matcher.subsequence(-1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.subsequence(1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} assertEquals("subsequence of 0,1 is identical", matcher, matcher.subsequence(0,1)); try { matcher.subsequence(-1, 1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.subsequence(0, 2); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} int count = 0; for (ByteMatcher itself : matcher) { count++; assertEquals("Iterating returns same matcher", matcher, itself); } assertEquals("Count of iterated matchers is one", 1, count); Iterator<ByteMatcher> it = matcher.iterator(); try { it.remove(); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expectedIgnore) {} it = matcher.iterator(); try { assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); it.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expectedIgnore) {} }
9
public int insert(ModelCRLV crlv) throws ClassNotFoundException, SQLException{ int result; con = abrirBanco(con); String sql = "insert into crlv" + "(via, cod_renavam, rntrc, exercicio, nome, cpf_cnpj, placa," + "uf_placa, placa_ant, uf_placa_ant, chassi, especie_tipo, combustivel," + "marca, modelo, ano_fab, ano_mod, cap, pot, cil, categoria, cor, premio_tarifario," + "iof, premio_total, data_pagamento, observacoes, local, data)" + "values" + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement stm = con.prepareStatement(sql); stm.setInt(1, crlv.getVia()); stm.setString(2, crlv.getCodRenavam()); stm.setString(3, crlv.getRntrc()); stm.setString(4, crlv.getExercicio()); stm.setString(5, crlv.getNome()); stm.setString(6, crlv.getCpfCnpj()); stm.setString(7, crlv.getPlaca()); stm.setString(8, crlv.getUfPlaca()); stm.setString(9, crlv.getPlacaAnt()); stm.setString(10, crlv.getUfPlacaAnt()); stm.setString(11, crlv.getChassi()); stm.setString(12, crlv.getEspecieTipo()); stm.setString(13, crlv.getCombustivel()); stm.setString(14, crlv.getMarca()); stm.setString(15, crlv.getModelo()); stm.setInt(16, crlv.getAnoFab()); stm.setInt(17, crlv.getAnoMod()); stm.setString(18, crlv.getCap()); stm.setString(19, crlv.getPot()); stm.setString(20, crlv.getCil()); stm.setString(21, crlv.getCategoria()); stm.setString(22, crlv.getCor()); stm.setString(23, crlv.getPremioTarifario()); stm.setString(24, crlv.getIof()); stm.setString(25, crlv.getPremioTotal()); stm.setString(26, crlv.getDataPag()); stm.setString(27, crlv.getObservacoes()); stm.setString(28, crlv.getLocal()); stm.setString(29, crlv.getData()); result = stm.executeUpdate(); int idCrlv = 0; ResultSet rs = selectIpva(crlv); if(rs.next()) idCrlv = rs.getInt("id_crlv"); sql = "insert into ipva " + "(cota_unica, venc_cota_unica, faixa_ipva, parcelamento_cotas," + "venc_primeira_cota, venc_segunda_cota, venc_terceira_cota, crlv_id_crlv) " + "values " + "(?,?,?,?,?,?,?,?)"; stm = con.prepareStatement(sql); stm.setString(1, crlv.getIpva().getCotaUnica()); stm.setString(2, crlv.getIpva().getVencCotaUnica()); stm.setString(3, crlv.getIpva().getFaixaIpva()); stm.setString(4, crlv.getIpva().getParcelamentoCotas()); stm.setString(5, crlv.getIpva().getVencPrimeiraCota()); stm.setString(6, crlv.getIpva().getVencSegundaCota()); stm.setString(7, crlv.getIpva().getVencTerceiraCota()); stm.setInt(8, idCrlv); // System.out.println(idCrlv); result = stm.executeUpdate(); fecharBanco(con); return result; }
1
void maxSlidingWindow(int A[], int n, int w, int B[]) { LinkedList<Integer> Q = new LinkedList<Integer>(); for (int i = 0; i < w; i++) { while (!Q.isEmpty() && A[i] >= A[Q.getLast()]) Q.removeLast(); Q.addLast(i); } for (int i = w; i < n; i++) { B[i-w] = A[Q.getFirst()]; while (!Q.isEmpty() && A[i] >= A[Q.getLast()]) Q.removeLast(); while (!Q.isEmpty() && Q.getFirst() <= i-w) Q.removeFirst(); Q.addLast(i); } B[n-w] = A[Q.getFirst()]; }
8
@Override public Object getValueAt(int rowIndex, int columnIndex) { KundeDTO kunde = kundeList.get(rowIndex); Object value = null; switch (columnIndex) { case 0: value = kunde.getKundeId(); break; case 1: value = kunde.getFirmaNavn(); break; case 2: value = kunde.getKontaktNavn(); break; case 3: value = kunde.getTelefonNr(); break; case 4: value = kunde.getStatus(); break; } return value; }
5
public void doStatsOnList(ArrayList<Float> data) { ArrayList<Float> medianFinder = new ArrayList<Float>(); for (float dataPoint : data) { if (dataPoint != dataPoint) continue; n++; sum += dataPoint; sumOfSquares += dataPoint * dataPoint; medianFinder.add(dataPoint); } mean = sum / n; if (medianFinder.size() < 1) return; Collections.sort(medianFinder); median = ((medianFinder.get((int) (n / 2)) + medianFinder .get((int) ((n - 1) / 2))) / 2); min = medianFinder.get(0); max = medianFinder.get(medianFinder.size() - 1); // mode = findMode(medianFinder); standardDeviation = (float) Math.sqrt((sumOfSquares - sum * sum / n) / n); range = max - min; dataQuality = (float) n / data.size(); float lowThird = (mean - percentile * standardDeviation); emin = lowThird < min ? min : lowThird; float highThird = (mean + percentile * standardDeviation); emax = highThird > max ? max : highThird; // round our numbers to 4 sig fig BigDecimal bd = new BigDecimal(emin); bd = bd.round(new MathContext(4)); emin = bd.floatValue(); bd = new BigDecimal(emax); bd = bd.round(new MathContext(4)); emax = bd.floatValue(); }
5
private void hookListener(final ColumnViewer viewer) { Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.MouseDown: handleMouseDown(event); break; case SWT.KeyDown: handleKeyDown(event); break; case SWT.Selection: handleSelection(event); break; case SWT.FocusIn: handleFocusIn(event); break; } } }; viewer.getControl().addListener(SWT.MouseDown, listener); viewer.getControl().addListener(SWT.KeyDown, listener); viewer.getControl().addListener(SWT.Selection, listener); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if( event.selection.isEmpty() ) { setFocusCell(null); } } }); viewer.getControl().addListener(SWT.FocusIn, listener); viewer.getControl().getAccessible().addAccessibleListener( new AccessibleAdapter() { public void getName(AccessibleEvent event) { ViewerCell cell = getFocusCell(); if (cell == null) return; ViewerRow row = cell.getViewerRow(); if (row == null) return; ViewerColumn viewPart = viewer.getViewerColumn(cell .getColumnIndex()); if (viewPart == null) return; CellLabelProvider labelProvider = viewPart .getLabelProvider(); if (labelProvider == null) return; labelProvider.update(cell); event.result = cell.getText(); } }); }
9
public void getSysRunDate() { date = gregorianCalendar.getTime(); sysRunTime = (date.toString()).split(" "); }
0
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { if (!(sender instanceof Player)) { return true; } Player player = (Player)sender; if (HyperPVP.getSpectators().contains(player.getName())) { player.teleport(HyperPVP.getMap().getSpawn()); //sender.sendMessage(ChatColor.RED + "You aren't playing a game!"); return true; } if (!HyperPVP.isCycling()) { HyperPVP.getSession(player).leaveGame(true); } TagAPI.refreshPlayer(player); //HyperTag.changePlayer(player); } catch (Exception e) { e.printStackTrace(); } return true; }
4
public synchronized void finishEntropyProcessing(int num_msgs, int otherID, Socket sock) { // Write nextWrite; // Write committedWrite; entropy_size = num_msgs; while(entropy_writes.size() != entropy_size) { try { wait(); } catch(InterruptedException e) {} } for(int i = 1; i<=num_msgs; i++) { Write nextWrite = entropy_writes.get(i); if(nextWrite.isCommitted()) { if(!(nextWrite.getUpdateCmd()).equals(Constants.commit_existing)) { committedWrites.log(nextWrite); } else { System.out.println("W: " + nextWrite); //committedWrite = committedWrites.removeWrite(nextWrite.getAcceptStamp(), nextWrite.getServerId()); Write committedWrite = uncommittedWrites.removeWrite(nextWrite.getAcceptStamp(), nextWrite.getServerId()); committedWrite.setAcceptStamp(nextWrite.getAcceptStamp()); committedWrite.setCSN(nextWrite.getCSN()); committedWrite.setSID(nextWrite.getServerId()); committedWrite.setCommitted(true); committedWrites.log(committedWrite); } largestCSN = Math.max(nextWrite.getCSN(), largestCSN); } else { if(isPrimary) { largestCSN = Math.max(System.currentTimeMillis(), largestCSN+1); nextWrite.setCommitted(true); nextWrite.setCSN(largestCSN); committedWrites.log(nextWrite); } else { uncommittedWrites.log(nextWrite); } } if(!retired_list.containsEntry(nextWrite.getServerId())) { if(versionVector.containsEntry(nextWrite.getServerId())) versionVector.changeifMax(nextWrite.getServerId(), nextWrite.getAcceptStamp()); else versionVector.addEntry(nextWrite.getServerId(), nextWrite.getAcceptStamp()); } } entropy_writes.clear(); entropy_size = Integer.MAX_VALUE; setFreeForEntropy(true); rePopulatePlaylist(); sendUpdatesReceivedAck(sock); }
8
public int getPoints() { return points; }
0
public CombatScreen(TurnBasedGame _game, Battle battle, CombatEntity player, CombatEntity monster, MapScreen parent) { this.game = _game; this.battle = battle; this.player = player; this.monster = monster; this.mapScreen = parent; rng = new Random(); battle.addBattleEndListener(new BattleEndListener() { @Override public void onBattleEnd(BattleEndCondition cond) { if(cond == BattleEndCondition.WIN || cond == BattleEndCondition.FLEE) game.setScreen(mapScreen); } }); battle.addBattleTurnListener(new BattleTurnListener() { @Override public void onTurn(Turn t, int amount){ if(combatLog != null) { String text = "error"; switch(t.getAction()) { case ATTACK: text = t.getSourceEntity().getName() + " attacks " + t.getTargetEntity().getName() + " for " + amount; AngryAudio.hit(); break; case HEAL: text = t.getSourceEntity().getName() + " heals self for " + amount; break; case FIRE: text = t.getSourceEntity().getName() + " casts fire on " + t.getTargetEntity().getName() + " for " + amount; break; case ICE: text = t.getSourceEntity().getName() + " casts ice on " + t.getTargetEntity().getName() + " for " + amount; break; case DEFEND: text = t.getSourceEntity().getName() + " defends itself against the next attack!"; break; default: text = "error2"; break; } String currText = combatLog.getText().toString(); int containsMultiline = currText.lastIndexOf('\n'); int idx = (containsMultiline > -1) ? containsMultiline : 0; text = currText.substring(idx) + '\n' + text; combatLog.setText(text); //infolog.setText("Enemy Health: "+player.getHealth()+"/"+player.getTotalHealth()+" | "+monster.getHealth()+"/"+monster.getTotalHealth()+"Player Health:"); } } }); }
9
static String getMessageName(StringBuilder sb, Class<?> type, boolean includeScope) { // Crosstown does not support complex generated names since they won't // translate to // dotNet if (includeScope) { String scope = null; if (ExternallyNamespaced.class.isAssignableFrom(type)) { // Use dotNet Namespaces try { scope = ((ExternallyNamespaced) type.newInstance()) .getExternalNamespace(); } catch (Exception e) { _log.error( "Unable to obtain namespace for " + type + ". ExternallyNamespaced classes must have a default constructor.", e); } } else { // Use Java Packages scope = type.getPackage().getName(); } if (scope != null && !scope.isEmpty()) { sb.append(scope); sb.append(":"); } } sb.append(type.getSimpleName()); return sb.toString(); }
6
public void actionPerformed(ActionEvent e) { if(e.getSource() == trainSelector) { redraw(); } else if(e.getSource() == engine) { int currTrain = Integer.parseInt((String) trainSelector.getSelectedItem()); if(trainModelWrapper.isInFailure(currTrain)) { trainModelWrapper.resolveFailure(currTrain); brake.setEnabled(true); signal.setEnabled(true); eBrake.setEnabled(true); } else { trainModelWrapper.causeFailure(Failure.ENGINE, currTrain); brake.setEnabled(false); signal.setEnabled(false); eBrake.setEnabled(false); } redraw(); } else if(e.getSource() == brake) { int currTrain = Integer.parseInt((String) trainSelector.getSelectedItem()); if(trainModelWrapper.isInFailure(currTrain)) { trainModelWrapper.resolveFailure(currTrain); engine.setEnabled(true); signal.setEnabled(true); eBrake.setEnabled(true); } else { trainModelWrapper.causeFailure(Failure.BRAKE, currTrain); engine.setEnabled(false); signal.setEnabled(false); eBrake.setEnabled(false); } redraw(); } else if(e.getSource() == signal) { int currTrain = Integer.parseInt((String) trainSelector.getSelectedItem()); if(trainModelWrapper.isInFailure(currTrain)) { trainModelWrapper.resolveFailure(currTrain); engine.setEnabled(true); brake.setEnabled(true); eBrake.setEnabled(true); } else { trainModelWrapper.causeFailure(Failure.SIGNAL, currTrain); engine.setEnabled(false); brake.setEnabled(false); eBrake.setEnabled(false); } redraw(); } else if(e.getSource() == eBrake) { int currTrain = Integer.parseInt((String) trainSelector.getSelectedItem()); if(trainModelWrapper.eBrakePulled(currTrain)) { trainModelWrapper.endEBrake(currTrain); System.out.println("E-Brake TURNING OFF GUI"); engine.setEnabled(true); brake.setEnabled(true); signal.setEnabled(true); } else { trainModelWrapper.pullEBrake(currTrain); engine.setEnabled(false); brake.setEnabled(false); signal.setEnabled(false); } redraw(); } }
9
private int compareHandsLo(String hand1, String hand2) { if (hand1.equals("0")) { return hand2.equals("0") ? 0 : 2; } else if (hand2.equals("0")) { return 1; } for (int i = 0; i < 5; i++) { if (Card.getRank(hand1.charAt(i)) > Card.getRank(hand2.charAt(i))) { return 2; } else if (Card.getRank(hand2.charAt(i)) > Card.getRank(hand1.charAt(i))) { return 1; } } return 0; }
6
public static void main(String[] args) throws Exception { String env = null; if (args != null && args.length > 0) { env = args[0]; } if (! "dev".equals(env)) if (! "prod".equals(env)) { System.out.println("Usage: $0 (dev|prod)\n"); System.exit(1); } // Topology config Config conf = new Config(); // Load parameters and add them to the Config Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml"); conf.putAll(configMap); log.info(JSONValue.toJSONString((conf))); // Set topology loglevel to DEBUG conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug")); // Create Topology builder TopologyBuilder builder = new TopologyBuilder(); // if there are not special reasons, start with parallelism hint of 1 // and multiple tasks. By that, you can scale dynamically later on. int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint"); int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks"); // Create Stream from RabbitMQ messages // bind new queue with name of the topology // to the main plan9 exchange (from properties config) // consuming only CBT-related events by using the rounting key 'cbt.#' String badgeName = RecordBreakerBadgeTopology.class.getSimpleName(); String rabbitQueueName = badgeName; // use topology class name as name for the queue String rabbitExchangeName = JsonPath.read(conf, "$.deck36_storm.RecordBreakerBolt.rabbitmq.exchange"); String rabbitRoutingKey = JsonPath.read(conf, "$.deck36_storm.RecordBreakerBolt.rabbitmq.routing_key"); // Get JSON deserialization scheme Scheme rabbitScheme = new SimpleJSONScheme(); // Setup a Declarator to configure exchange/queue/routing key RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey); // Create Configuration for the Spout ConnectionConfig connectionConfig = new ConnectionConfig( (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat")); ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig) .queue(rabbitQueueName) .prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")) .requeueOnFail() .build(); // add global parameters to topology config - the RabbitMQSpout will read them from there conf.putAll(spoutConfig.asMap()); // For production, set the spout pending value to the same value as the RabbitMQ pre-fetch // see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md if ("prod".equals(env)) { conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")); } // Add RabbitMQ spout to topology builder.setSpout("incoming", new RabbitMQSpout(rabbitScheme, rabbitDeclarator), parallelism_hint) .setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks")); // construct command to invoke the external bolt implementation ArrayList<String> command = new ArrayList(15); // Add main execution program (php, hhvm, zend, ..) and parameters command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params")); // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.) command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params")); // create command to execute the RecordBreakerBolt ArrayList<String> recordBreakerBoltCommand = new ArrayList<String>(command); // Add main route to be invoked and its parameters recordBreakerBoltCommand.add((String) JsonPath.read(conf, "$.deck36_storm.RecordBreakerBolt.main")); List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.RecordBreakerBolt.params"); if (boltParams != null) recordBreakerBoltCommand.addAll(boltParams); // create command to execute the RecordMasterBolt ArrayList<String> recordMasterBoltCommand = new ArrayList<String>(command); // Add main route to be invoked and its parameters recordMasterBoltCommand.add((String) JsonPath.read(conf, "$.deck36_storm.RecordMasterBolt.main")); boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.RecordMasterBolt.params"); if (boltParams != null) recordMasterBoltCommand.addAll(boltParams); // Log the final commands log.info("Command to start bolt for RecordBreaker badge: " + Arrays.toString(recordBreakerBoltCommand.toArray())); log.info("Command to start bolt for RecordMaster badge: " + Arrays.toString(recordMasterBoltCommand.toArray())); // Add constructed external bolt command to topology using MultilangAdapterBolt // The RecordBreaker reads the incoming messages from the game application, i.e. the "incoming" spout builder.setBolt("record_breaker", new MultilangAdapterBolt(recordBreakerBoltCommand, "badge"), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("incoming"); // The RecordMaster reads the badge messages generated by the RecordBreakerBolt builder.setBolt("record_master", new MultilangAdapterBolt(recordMasterBoltCommand, "badge"), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("record_breaker"); // the RabbitMQ router bolt can read messages from both, RecordBreakerBolt and RecordMasterBolt, // and forward those messages to the broker builder.setBolt("rabbitmq_router", new Plan9RabbitMQRouterBolt( (String) JsonPath.read(conf, "$.deck36_storm.RecordBreakerBolt.rabbitmq.target_exchange"), "RecordBreakerMaster" // RabbitMQ routing key ), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("record_breaker") .shuffleGrouping("record_master"); builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("rabbitmq_router"); if ("dev".equals(env)) { LocalCluster cluster = new LocalCluster(); cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology()); Thread.sleep(2000000); } if ("prod".equals(env)) { StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology()); } }
9
public void testKeepLastNDeletionPolicy() throws IOException { final int N = 5; for(int pass=0;pass<2;pass++) { boolean useCompoundFile = (pass % 2) != 0; Directory dir = new RAMDirectory(); KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N); for(int j=0;j<N+1;j++) { IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, policy, IndexWriter.MaxFieldLength.UNLIMITED); writer.setMaxBufferedDocs(10); writer.setUseCompoundFile(useCompoundFile); for(int i=0;i<17;i++) { addDoc(writer); } writer.optimize(); writer.close(); } assertTrue(policy.numDelete > 0); assertEquals(N+1, policy.numOnInit); assertEquals(N+1, policy.numOnCommit); // Simplistic check: just verify only the past N segments_N's still // exist, and, I can open a reader on each: dir.deleteFile(IndexFileNames.SEGMENTS_GEN); long gen = SegmentInfos.getCurrentSegmentGeneration(dir); for(int i=0;i<N+1;i++) { try { IndexReader reader = IndexReader.open(dir, true); reader.close(); if (i == N) { fail("should have failed on commits prior to last " + N); } } catch (IOException e) { if (i != N) { throw e; } } if (i < N) { dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen)); } gen--; } dir.close(); } }
8
@Override public void addCallback(IJeTTEventCallback callback) { // Create adapters // Create an adapter for each type of callback here CallbackAdapter<?>[] adapters = new CallbackAdapter[] { new EventCallbackAdapter(callback), new ResultCallbackAdapter(callback), }; // Add all for(CallbackAdapter<?> adapter : adapters) for(MethodParamBinding binding : adapter.getMethods()) this.callbackBindings.get(binding.message).add( new Binding(binding.method, callback)); }
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Contact)) { return false; } Contact other = (Contact) object; if ((this.contactID == null && other.contactID != null) || (this.contactID != null && !this.contactID.equals(other.contactID))) { return false; } return true; }
5
public double getAltura() { return altura; }
0
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Cidade)) { return false; } Cidade other = (Cidade) object; if ((this.codcidade == null && other.codcidade != null) || (this.codcidade != null && !this.codcidade.equals(other.codcidade))) { return false; } return true; }
5
@Override public void actionPerformed(GUIComponent source) { if (source == newGameButton) { Game.linkedGet().newGame(); this.deactivate(); Game.linkedGet().resumePlay(); } else if (source == quitButton) { Game.linkedGet().quit(); this.deactivate(); Game.linkedGet().resumePlay(); } }
2
@Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return listReclamation.get(rowIndex).getIdReclamation(); case 1: return listReclamation.get(rowIndex).getDateReclamation(); case 2: return listReclamation.get(rowIndex).getSujet_reclamation(); case 3: return listReclamation.get(rowIndex).getContenuReclamation(); default: return null; } }
4
private synchronized String getSelection() { while (selection == null) { try { this.wait(); } catch (InterruptedException e) { throw (new RuntimeException(e)); //Seriously when is it ever correct to actually handle this error } } return selection; }
2
private static <AnyType extends Comparable<? super AnyType>> void percDown( AnyType [ ] a, int i, int n ) { int child; AnyType tmp; for( tmp = a[ i ]; leftChild( i ) < n; i = child ) { child = leftChild( i ); if( child != n - 1 && a[ child ].compareTo( a[ child + 1 ] ) < 0 ) child++; if( tmp.compareTo( a[ child ] ) < 0 ) a[ i ] = a[ child ]; else break; } a[ i ] = tmp; }
5
private void getStringFiles(File[] valuesFolder) { for (File valuesVersion : valuesFolder) { System.out.println("Parsing xml from " + valuesVersion.getName() + "\n"); String columnName = valuesVersion.getName().substring( "values".length()); if (ConstantMethods.isEmptyString(columnName)) { columnName = "default"; } else { columnName = columnName.substring(1); } int column = findIndexOfLanguage(columnName); if (valuesVersion.isDirectory()) { File stringsDotXml = new File(valuesVersion, "strings.xml"); Document document = Utils.getXmlFromFile(stringsDotXml); NodeList nodes = document.getElementsByTagName("string"); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); String key = "" + item.getAttributes().getNamedItem("name"); int row = getIndexFromKey(key); ArrayList<String> values = keysValueMap.get(key); String value = item.getTextContent(); if (value == null) value = ""; values.add(value); } } } }
5
public Object getConfig(int i, String name) { String str = ""; int in = 0; long lng = 0; double dbl = 0; boolean bln = false; try { Transaction trans=new JDBCTransaction(createConnection()); Connection connection = ((JDBCTransaction)trans).getConnection(); Statement stmt=connection.createStatement(); String query = SQL_CONFIG_GET + "'" + name + "')"; ResultSet result = stmt.executeQuery(query); if(result.next()) { switch(i) { case(SQL_BLN):{ bln = result.getBoolean("value"); return bln; } case(SQL_INT):{ in = result.getInt("value"); return in; } case(SQL_DBL):{ dbl = result.getDouble("value"); return dbl; } case(SQL_LNG):{ lng = result.getLong("value"); return lng; } case(SQL_STR):{ str = result.getString("value"); return str; } } } else { eng.LOG.printError("MySQL Error loading config: name = " + name + " type = " + i, null); return null; } } catch (DatabaseException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; }
8
public E get(int id) { try { selectId.setInt(1, id); ResultSet rs = selectId.executeQuery(); while(rs.next()){ return build(rs); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
2
@Override public void mouseDown(Point mousePoint, boolean shiftDown, boolean ctrlDown) { // if ctrl is down deselect all selected objects if (!ctrlDown) { for (Object go : model.list()) { ((GraphicalObject) go).setSelected(false); } } GraphicalObject obj = model.findSelectedGraphicalObject(mousePoint); if (obj != null) obj.setSelected(true); //is hot point selected if (!ctrlDown && model.getSelectedObjects().size() == 1) { int hpIndex = model.findSelectedHotPoint(obj, mousePoint); if (hpIndex != -1) obj.setHotPointSelected(hpIndex, true); } }
6
public void addPageHeader(List<String> whereTo, String head) { whereTo.add("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"); whereTo.add("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" >\n"); whereTo.add("<head>\n"); whereTo.add("<meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\" />\n"); whereTo.add("<meta name=\"author\" content=\"Bastiaan Schuiling Konings\" />\n"); whereTo.add("<meta name=\"keywords\" content=\"coffeesaint admin\" />\n"); whereTo.add("<meta name=\"description\" content=\"CoffeeSaint remote configuration panel\" /\n"); whereTo.add(" <title>CoffeeSaint admin</title>\n"); whereTo.add(" <script type=\"text/javascript\"></script>\n"); whereTo.add("<link href=\"/design.css\" rel=\"stylesheet\" media=\"screen\">\n"); if (head != null && head.equals("") == false) whereTo.add(head); whereTo.add("</head>\n"); whereTo.add("<body id=\"css-coffeesaint\" BGCOLOR=\"#ffffff\">\n"); whereTo.add(" <div id=\"coffee\"><img src=\"/images/coffee.png\" /></div>\n"); whereTo.add(" <div id=\"container\">\n"); whereTo.add(" <div id=\"column_navigation\">\n"); whereTo.add(" <div id=\"navigation\">\n"); whereTo.add(" <strong>Nagios</strong><br />\n"); whereTo.add(" <a href=\"/cgi-bin/performance-data.cgi\">Performance data</a><br />\n"); whereTo.add(" <a href=\"/latency-graph.html\">Latency graph</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/list-all.cgi\">List of hosts/services</a><br />\n"); boolean file = false; for(NagiosDataSource nds : config.getNagiosDataSources()) { if (nds.getType() == NagiosDataSourceType.FILE) { file = true; break; } } if (file) whereTo.add(" <a href=\"/cgi-bin/nagios_status.cgi\">Problems overview</a><br />\n"); else whereTo.add(" <a href=\"/applet.html\">Problems overview</a><br />\n"); whereTo.add(" <br /><strong>Logging</strong><br />\n"); whereTo.add(" <a href=\"/cgi-bin/statistics.cgi\">CoffeeSaint statistics</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/log.cgi\">List of connecting hosts</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/list-log.cgi\">Show log</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/jvm_stats.cgi\">JVM statistics</a><br />\n"); whereTo.add(" <br /><strong>Configuration</strong><br />\n"); whereTo.add(" <a href=\"/cgi-bin/config-menu.cgi\">Configure CoffeeSaint</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/reload-config.cgi\">Reload configuration</a><br />\n"); whereTo.add(" <a href=\"/cgi-bin/select_configfile.cgi\">Select configuration file</a><br />\n"); if (config.getConfigFilename() == null) whereTo.add("No configuration-file selected, save disabled<br />\n"); else { String line = "<A HREF=\"/cgi-bin/write-config.cgi\">Write config to " + config.getConfigFilename() + "</A>"; if (configNotWrittenToDisk == true) line += " (changes pending!)"; line += "<br />\n"; whereTo.add(line); } whereTo.add(" <br /><strong>Actions</strong><br />\n"); if (config.getRunGui()) whereTo.add("<A HREF=\"/cgi-bin/force_reload.cgi\">Force reload</A><br />\n"); else whereTo.add("Force reload disabled, not running GUI<br />\n"); String sample = config.getProblemSound(); if (sample != null) whereTo.add("<A HREF=\"/cgi-bin/test-sound.cgi\">Test sound (" + sample + ")</A><br />\n"); else whereTo.add("No sound selected<br />\n"); whereTo.add(" <br /><strong>Links</strong><br />\n"); whereTo.add(" <a href=\"/links.html\">Links relevant to this program</a><br />\n"); whereTo.add(" <br />\n"); whereTo.add(" <br />\n"); whereTo.add(" <a href=\"http://www.vanheusden.com\" target=\"_blank\"><img src=\"/images/footer01.png\" border=\"0\" /></a>\n"); whereTo.add(" </div>\n"); whereTo.add(" </div>\n"); whereTo.add(" <div id=\"column_main\">\n"); whereTo.add(" <img src=\"/images/title01.png\" />\n"); whereTo.add(" <font size=\"5\">" + CoffeeSaint.getVersionNr() + "</font>\n"); whereTo.add(" <div id=\"main\">\n"); }
9
public final void handlePlace(PlayerInteractEvent event, BlockAPI plugin) { Player player = event.getPlayer(); ItemStack item = event.getItem(); Block block = event.getClickedBlock().getRelative(event.getBlockFace()); BlockState state = block.getState(); if ((!block.isEmpty()) && (!block.isLiquid())) { return; } if (player.getGameMode() != GameMode.CREATIVE) { item = BlockAPI.setCustomBlockAmount(event.getItem(), BlockAPI.getCustomBlockAmount(event.getItem()) - 1); player.setItemInHand(item); } block.setType(Material.getMaterial(getMaterialName().toUpperCase())); block.setMetadata(getIdentifier(), new FixedMetadataValue(plugin, Integer.valueOf(0))); BlockPlaceEvent event2 = new BlockPlaceEvent(block, state, event.getClickedBlock(), item, player, true); plugin.getServer().getPluginManager().callEvent(event2); place(event2); if (!event2.isCancelled()) addLocation(block.getLocation()); }
4
private void btn_generate_tokenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_generate_tokenActionPerformed // TODO add your handling code here: String cadToken = this.val_token.getText(); if (cadToken.length() > 0) { while (modelTable.getRowCount() > 0) { modelTable.removeRow(0); } Lectura to = new Lectura(cadToken); // Lectura to = new Lectura(cadLectura); // while (to.getHaveLectura()) { // to.getLectura(); // } // for (int j = 0; j < to.ListLectura.size(); j++) { // Token token = (Token) to.ListLectura.get(j); // modelTable.addRow(new Object[]{j + 1, token.getValor(), token.getDescripcion()}); // } } else { JOptionPane.showMessageDialog(this.rootPane, "Ingresa una cadena", "Información", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_btn_generate_tokenActionPerformed
2
@Override public void mouseReleased(MouseEvent e) { if (this.isMovingToolBar) this.isMovingToolBar = false; if (this.isDrawing) this.isDrawing = false; if (this.isSelecting) { this.isSelecting = false; } System.out.println("mouseReleased: "+e.getX()+","+e.getY()); }
3
public void setCaso(TCaso node) { if(this._caso_ != null) { this._caso_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._caso_ = node; }
3
public static void deleteWorlds() { if (!containsLoadedWorlds()) { if (ChristmasCrashers.isDebugModeEnabled()) System.out.println("Cancelling DeleteWorldsTask - there are no loaded worlds."); return; } ArrayList<World> worldsToDelete = new ArrayList<World>(); for (World w : worlds) if (w != null) worldsToDelete.add(w); new Thread(new DeleteWorldsTask((World[]) worldsToDelete.toArray())).start(); for (World w : worldsToDelete) worlds[w.getID()] = null; }
5
public Object getValue() { return this.value; }
0
private FriendsStatusListener makeFriendsStatusListener() { return new FriendsStatusListener() { @Override public void statusChange(Long friendId, SkypeStatus newStatus) { System.out.println(" !! Status msg receiv: userID:"+friendId+" newStatus:"+newStatus.name()); switch (newStatus) { case OFFLINE : { Friend friend = findListEntryById(friendId); if(friend != null) { friend.setStatus(newStatus); friendsList.setModel(friendslistModel); ChatWindow win = getActivChatWindow(friendId); if(win != null) { win.setOnOffStyle(false); } } } break; case ONLINE : { Friend friend = findListEntryById(friendId); if(friend != null) { friend.setStatus(newStatus); friendsList.setModel(friendslistModel); friendsList.repaint(); // listModel.addElement(entry); ChatWindow win = getActivChatWindow(friendId); if(win != null) { win.setOnOffStyle(true); } } } break; default: break; } } }; }
6
public ReportServer() { try { server = new Server(); Network.register(server.getKryo()); server.start(); server.bind(Network.PORT, Network.PORT); database = new ReportDB(); server.addListener(new Listener() { @Override public void received(Connection con, Object o) { if(o instanceof LoginRequest) { LoginRequest req = (LoginRequest) o; LoginResponse res = new LoginResponse(); if(database.validateUser(req.getUsername(), req.getPassword())) { res.setAccepted(true); } con.sendTCP(res); } else if (o instanceof ReportRequest) { ReportRequest req = (ReportRequest) o; Report r = database.buildReport(req.getReportid()); ReportResponse res = new ReportResponse(); res.setReport(r); con.sendTCP(res); } } }); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Network error, try restarting the application."); e.printStackTrace(); } }
4
private boolean execMakeCollaborativeProfiles(VectorMap queryParam, StringBuffer respBody, DBAccess dbAccess) { int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt"); String clientName = (String) queryParam.getVal(clntIdx); int threasholdIdx = queryParam.qpIndexOfKeyNoCase("th"); if (threasholdIdx == -1) { WebServer.win.log.error("-The parameter th is missing: "); return false; } String thStr = (String) queryParam.getVal(threasholdIdx); int op = 0; boolean avtualDist = true; if (thStr.startsWith("<")) { avtualDist = false; op = 1; } else if (thStr.startsWith(">")) { op = 2; } else { WebServer.win.log.error("-The parameter th is starts neither with < nor > "); return false; } float threashold = Float.parseFloat(thStr.substring(1)); boolean success = true; try { PCommunityDBAccess pdbAccess = new PCommunityDBAccess(dbAccess); pdbAccess.deleteUserAccociations(clientName, DBAccess.RELATION_BINARY_SIMILARITY); pdbAccess.generateBinarySimilarities(dbAccess, clientName, op, threashold); final int userSize = 1000; int offset = 0; int i = 0; int threadNum = Integer.parseInt(PersServer.pref.getPref("thread_num")); ///threadNum = 1; Statement stmt = dbAccess.getConnection().createStatement(); String sql = "DELETE FROM " + DBAccess.CFPROFILE_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "'"; stmt.execute(sql); sql = "DELETE FROM " + DBAccess.CFFEATURE_STATISTICS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "'"; stmt.execute(sql); sql = "DELETE FROM " + DBAccess.CFFTRASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "'"; stmt.execute(sql); threadNum = 1; ExecutorService threadExecutor = Executors.newFixedThreadPool(threadNum); do { i = 0; sql = "SELECT " + DBAccess.USER_TABLE_FIELD_USER + " FROM " + DBAccess.USER_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' LIMIT " + userSize + " OFFSET " + offset; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String user = rs.getString(1); //WebServer.win.log.debug("-Creating collaborative profile for user " + user ); threadExecutor.execute(new CollaborativeProfileBuilderThread(dbAccess, user, clientName, avtualDist)); i++; } offset += userSize; } while (i == userSize); threadExecutor.shutdown(); while (threadExecutor.isTerminated() == false) { try { Thread.sleep(5000); } catch (InterruptedException ex) { } } stmt.close(); return success; } catch (SQLException ex) { success = false; WebServer.win.log.debug("-Problem executing query: " + ex); } //String query1 = "SELECT uf_feature AS up_feature, uf_numdefvalue AS up_numvalue FROM up_features WHERE uf_feature NOT IN " + " ( SELECT up_feature FROM user_profiles WHERE up_user = '" + userName + "' AND FK_psclient = '" + clientName + "') AND FK_psclient = '" + clientName + "'"; //String query2 = "SELECT up_feature, up_numvalue AS up_numvalue FROM user_profiles WHERE up_user = '" + userName + "' AND up_feature in " + "(SELECT up_feature FROM user_profiles WHERE FK_psclient='" + clientName + "' ) AND FK_psclient='" + clientName + "'"; //String sql = " ( " + query1 + " ) UNION ( " + query2 + " ) " + condition; return success; }
8
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
9
public Process getNextProcess(Integer processor) { Process currentProcess = runningProcesses.get(processor); if(currentProcess != null && preemption == false) { return currentProcess; } if(waitingProcesses.size() == 0) { return null; } Integer shortestProcess = 0; Integer shortestTime = waitingProcesses.get(0).getTimeRemaining(); for(Integer i = 0; i < waitingProcesses.size(); ++i) { Process process = waitingProcesses.get(i); if(process.getTimeRemaining() < shortestTime) { shortestTime = process.getTimeRemaining(); shortestProcess = i; } } if(currentProcess != null && preemption) { if(shortestTime < currentProcess.getTimeRemaining()) { addProcess(currentProcess); runningProcesses.set(processor, null); } else { return currentProcess; } } return waitingProcesses.remove((int) shortestProcess); }
8
public List<Message> getAllChildrenMessages(int parentId) { List<Message> list = new LinkedList<>(); Connection connection = ConnectionManager.getConnection(); if (connection == null) { logger.log(Level.SEVERE, "Couln't establish a connection to database"); return list; } try { PreparedStatement ps = connection.prepareStatement(SELECT_BY_PARENT_ID_QUERY); ps.setInt(1, parentId); ResultSet rs = ps.executeQuery(); while (rs.next()) { Message message = new Message( rs.getInt(ID_COLUMN_NAME), rs.getString(TEXT_COLUMN_NAME), rs.getString(AUTHOR_COLUMN_NAME), rs.getTimestamp(DATE_COLUMN_NAME), rs.getInt(PARENT_ID_COLUMN_NAME) ); list.add(message); } } catch (SQLException ex) { logger.log(Level.SEVERE, null, ex); return list; } return list; }
3
private void downloadCover (String coverName){ File f=new File(downloadPath+File.separator+coverName); InputStream is = null; try { is = new URL("http://beta.grooveshark.com/static/amazonart/"+coverName).openStream(); } catch (MalformedURLException e1) { showMessage(("Cover Download Failed")); e1.printStackTrace(); } catch (IOException e1) { showMessage(("Cover Download Failed")); e1.printStackTrace(); } OutputStream out = null; try { out = new FileOutputStream(f); } catch (FileNotFoundException e) { showMessage(("Cover Download Failed")); e.printStackTrace(); } byte buf[]=new byte[1024]; int len; try { while((len=is.read(buf))>0){ out.write(buf,0,len); } } catch (IOException e) { showMessage(("Cover Download Failed")); e.printStackTrace(); } try { out.close(); } catch (IOException e) { showMessage(("Cover Download Failed")); e.printStackTrace(); } try { is.close(); } catch (IOException e) { e.printStackTrace(); } showMessage(("Cover Downloaded")); }
7
public Library addNative(OperatingSystem operatingSystem, String name) { if ((operatingSystem == null) || (!operatingSystem.isSupported())) throw new IllegalArgumentException("Cannot add native for unsupported OS"); if ((name == null) || (name.length() == 0)) throw new IllegalArgumentException("Cannot add native for null or empty name"); if (this.natives == null) this.natives = new EnumMap(OperatingSystem.class); this.natives.put(operatingSystem, name); return this; }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StageDirection other = (StageDirection) obj; if (direction == null) { if (other.direction != null) return false; } else if (!direction.equals(other.direction)) return false; return true; }
6
public int longestConsecutive(int[] num){ Map<Integer,Integer> mapStart = new HashMap<Integer,Integer>(); Map<Integer,Integer> mapEnd = new HashMap<Integer,Integer>(); int maxLength = 0; for(int i = 0 ;i < num.length;i++){ if(mapStart.containsKey(num[i])) continue; int low = num[i]; int up = num[i]; if(mapStart.containsKey(num[i]-1)) low = mapStart.get(num[i]-1); if(mapEnd.containsKey(num[i]+1)) up = mapEnd.get(num[i]+1); maxLength = Math.max(maxLength ,(up- low)+1); mapEnd.put(num[i],up); mapStart.put(num[i],low); mapEnd.put(low,up); mapStart.put(up,low); } return maxLength; }
4
public boolean parseStr(String str){ Pattern pattern = Pattern.compile("[,;]"); String[] strs = pattern.split(str); x1=Integer.valueOf(strs[0]); y1=Integer.valueOf(strs[1]); x2=Integer.valueOf(strs[2]); y2=Integer.valueOf(strs[3]); if(cb.getX()<=x1||x1<0||cb.getX()<=x2||x2<0||cb.getY()<=y1||y1<0||cb.getY()<=y2||y2<0){ return false; } cm1 = cb.getChessManByXY(x1,y1); cm2 = cb.getChessManByXY(x2,y2); return true; }
8
public int sumNumbers(TreeNode root) { int result = 0 ; if(root == null) return result; String s =""; saveNumber(s,root); return total; }
1
public static int getIndexOfPS(Stock u, ArrayList<Stock> stocks) { int counter = 0; for(Stock e:stocks) { if(e.getTickername().equalsIgnoreCase(u.getTickername())) { return counter; } counter++; } return -1; }
2
private String nextQuotedValue(char quote) throws IOException { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. char[] buffer = this.buffer; StringBuilder builder = new StringBuilder(); while (true) { int p = pos; int l = limit; /* the index of the first character not yet appended to the builder. */ int start = p; while (p < l) { int c = buffer[p++]; if (c == quote) { pos = p; builder.append(buffer, start, p - start - 1); return builder.toString(); } else if (c == '\\') { pos = p; builder.append(buffer, start, p - start - 1); builder.append(readEscapeCharacter()); p = pos; l = limit; start = p; } else if (c == '\n') { lineNumber++; lineStart = p; } } builder.append(buffer, start, p - start); pos = p; if (!fillBuffer(1)) { throw syntaxError("Unterminated string"); } } }
6
@Override public double[][] solve(double[] T_0, int n, double k, double u, double dt, double dx) { double[][] ans = new double[n][]; int m = T_0.length; ans[0] = T_0; for (int layer = 1; layer < 2; layer++) { double[] T = ans[layer - 1]; double[] curLayer = new double[m]; for (int i = 1; i < m - 1; i++) curLayer[i] = T[i] + dt * (k * (T[i + 1] - 2 * T[i] + T[i - 1]) / dx / dx - u * (T[i] - T[i - 1]) / dx); curLayer[0 ] = T[0 ]; curLayer[m - 1] = T[m - 1]; ans[layer] = curLayer; } for (int layer = 2; layer < n; layer++) { double[] T = ans[layer - 1]; double[] TT = ans[layer - 2]; double[] curLayer = new double[m]; for (int i = 1; i < m - 1; i++) curLayer[i] = TT[i] + 2 * dt * (k * (T[i + 1] - 2 * T[i] + T[i - 1]) / dx / dx - u * (T[i + 1] - T[i - 1]) / dx / 2); curLayer[0 ] = T[0 ]; curLayer[m - 1] = T[m - 1]; ans[layer] = curLayer; } /* dt k (T[i + 1, n] - 2T[i, n] + T[i - 1, n]) dt u (T[i, n] - T[i - 1, n]) T[i, n + 1] = T[i, n - 1] + 2 ——————————————————————————————————————————— - 2 ———————————————————————————— dx * dx dx */ return ans; }
4
@SuppressWarnings("unchecked") public void tabulateSurvey(Survey s) throws IOException{ //Takes a Survey given by the user and shows all response results for the Survey. Survey surv = s; ArrayList<ArrayList<Response>> resp = new ArrayList<ArrayList<Response>>(); final File dir = new File("responses"); if (!dir.exists()){ // files folder does not exist Out.getDisp().renderLine("Folder \"responses\" not found. Please take the Survey first to create this folder and populate it with responses."); return; }else{ // files folder does exist for(final File fileEntry : dir.listFiles()){ String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf(".") + 1, fileEntry.getName().length()); //Take the extension of each file if (ext.equals("resp")){ //If the extension is .resp, check for the right survey String surveyName = fileEntry.getName().substring(0,fileEntry.getName().indexOf("_")); //Take the Survey/Test name in the response file if (surveyName.equals(surv.getName())){ //If it is the right survey, add to the list of files //Deserialization try { FileInputStream fileIn = new FileInputStream("responses/" + fileEntry.getName()); ObjectInputStream read = new ObjectInputStream(fileIn); resp.add((ArrayList<Response>) read.readObject()); read.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { Out.getDisp().renderLine("Response not found."); c.printStackTrace(); return; }//try catch }//if (surveyName.equals(surv.getName())) }//if (ext.equals("resp")) }//for(final File fileEntry : dir.listFiles()) }//else if (resp.size() == 0){ Out.getDisp().renderLine("No responses found for this Survey."); }else{ surv.tabulate(resp); //Tabulate the ArrayList of ArrayList of Responses } }
7
public boolean containsValue( Object value ) { final int num = mBuckets.length; if( value != null ) { for( int i = 0; i < num; i++ ) { Node<V> entry = mBuckets[i]; while( entry != null ) { if( value.equals( entry.mValue ) ) { return true; } entry = entry.mNext; } } } else { for( int i = 0; i < num; i++ ) { Node<V> entry = mBuckets[i]; while( entry != null ) { if( entry.mValue == null ) { return true; } entry = entry.mNext; } } } return false; }
7
public List<RoomEvent> getRoomEventList() { return roomEventList; }
0
public GeneralConfigurationPanel() { super(); setLayout(new BorderLayout()); contents = new GeneralData(); PropertySet ps = new PropertySet(); final TextProperty tpName = new TextProperty("Game name", null); final FileProperty fpMenuBackgroundImage = new FileProperty( "Menu background image (800 \u00d7 600)", null); final FileProperty fpBackgroundMusic = new FileProperty( "Background music", null); final FileProperty fpTitleImage = new FileProperty( "Title image (800 \u00d7 100)", null); final FileProperty fpHelpImage = new FileProperty( "Help image (800 \u00d7 600)", null); final FileProperty fpBaseImage = new FileProperty( "Home base (96 \u00d7 96)", null); final FileProperty fpButtonImage = new FileProperty( "Button up image (48 \u00d7 48, divided in thirds)", null); final FileProperty fpButtonHover = new FileProperty( "Button hover image", null); final FileProperty fpButtonPressed = new FileProperty( "Button pressed image", null); final FileProperty fpButtonClick = new FileProperty( "Button click sound", null); final FileProperty fpButtonTweenInSound = new FileProperty( "Button fly-in sound", null); ps.add(tpName); ps.add(fpTitleImage); ps.add(fpBackgroundMusic); ps.add(null); ps.add(fpMenuBackgroundImage); ps.add(fpHelpImage); ps.add(null); ps.add(fpBaseImage); ps.add(null); ps.add(fpButtonImage); ps.add(fpButtonHover); ps.add(fpButtonPressed); ps.add(null); ps.add(fpButtonClick); ps.add(fpButtonTweenInSound); FileProperty[] images = { fpButtonImage, fpButtonHover, fpBaseImage, fpButtonPressed, fpTitleImage, fpHelpImage, fpMenuBackgroundImage }; for (FileProperty imageProperty : images) { imageProperty.setFilter(ffImage); } fpBackgroundMusic.setFilter(ffSoundOgg); fpButtonClick.setFilter(ffSoundWav); fpButtonTweenInSound.setFilter(ffSoundWav); tpName.setDescription("Appears in the window title."); fpMenuBackgroundImage .setDescription("The background image for the main menu."); fpBackgroundMusic .setDescription("Will start when the title first enters and loop until quit."); fpButtonImage .setDescription("This will be the image for all buttons. It should be optimized for nine-slice scaling."); fpButtonHover .setDescription("This image will be displayed when the user's mouse pointer is over a button."); fpBaseImage .setDescription("This is the base that the enemies are approaching and the player must defend."); fpButtonPressed .setDescription("This image will be displayed when the user is pressing a button."); fpButtonClick .setDescription("The sound made when a button is clicked."); fpTitleImage .setDescription("The image for the title text only (not background, etc.)."); fpButtonTweenInSound .setDescription("The sound that plays when each main menu button enters the screen."); fpHelpImage .setDescription("The image for the help pane. This should contain the background and all text."); ChangeListener cl = new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { if (!isUpdating()) { contents.name = tpName.getValue(); contents.menuBackgroundImage = fpMenuBackgroundImage .getValue(); contents.backgroundMusic = fpBackgroundMusic.getValue(); contents.base = fpBaseImage.getValue(); contents.buttonImage = fpButtonImage.getValue(); contents.buttonImageHover = fpButtonHover.getValue(); contents.buttonImagePressed = fpButtonPressed.getValue(); contents.buttonClickSound = fpButtonClick.getValue(); contents.titleImage = fpTitleImage.getValue(); contents.buttonTweenInSound = fpButtonTweenInSound .getValue(); contents.helpImage = fpHelpImage.getValue(); } } }; for (AbstractProperty<?> p : ps) { if (p != null) { p.addChangeListener(cl); } } add(new PropertyPanel(ps, true, false), BorderLayout.CENTER); rUpdate = new Runnable() { @Override public void run() { tpName.setValue(contents.name); fpBaseImage.setValue(contents.base); fpMenuBackgroundImage.setValue(contents.menuBackgroundImage); fpBackgroundMusic.setValue(contents.backgroundMusic); fpButtonImage.setValue(contents.buttonImage); fpButtonHover.setValue(contents.buttonImageHover); fpButtonPressed.setValue(contents.buttonImagePressed); fpButtonClick.setValue(contents.buttonClickSound); fpTitleImage.setValue(contents.titleImage); fpButtonTweenInSound.setValue(contents.buttonTweenInSound); fpHelpImage.setValue(contents.helpImage); } }; }
5
public void start() throws BITalinoException { int bit = 1; for (int channel : analogChannels) bit = bit | 1 << (2 + channel); try { socket.write(bit); } catch (Exception e) { throw new BITalinoException(BITalinoErrorTypes.BT_DEVICE_NOT_CONNECTED); } }
2
public void saveYMLFile(String fileName) { if (!FileConfigs.containsKey(fileName)) { FileConfigs.put(fileName, new YamlConfiguration()); } try { FileConfigs.get(fileName).save(Files.get(fileName)); } catch (IOException e) {e.printStackTrace(); } }
2
public String toString() { String str = paintNo+"|"+manu+"|"; for(String man : manus) { str = str + man + ","; } str = str.substring(0, str.length()-1); for(String num : numbers) { str = str + num + ","; } str = str.substring(0, str.length()-1); return str; }
2
public PlanMinuten(JSONObject object, Object min) throws FatalError { super("Minuten"); if (min != null && min instanceof Integer) { count = (Integer) min; } else { throw new ConfigError("Minuten"); } if (count < 0) { Output.println("Config: Minuten is set to 0.", 0); count = 0; } }
3
public void keyTyped(KeyEvent e) { debug("keyTyped("+e+")"); char c=e.getKeyChar(); if(((c>='0')&&(c<='9'))||((c>='A')&&(c<='F'))||((c>='a')&&(c<='f'))) { char[] str=new char[2]; String n="00"+Integer.toHexString((int)he.buff[he.cursor]); if(n.length()>2) n=n.substring(n.length()-2); str[1-cursor]=n.charAt(1-cursor); str[cursor]=e.getKeyChar(); he.buff[he.cursor]=(byte)Integer.parseInt(new String(str),16); if(cursor!=1) cursor=1; else if(he.cursor!=(he.buff.length-1)){ he.cursor++; cursor=0;} he.actualizaCursor(); } }
9
private static void convertRGBtoHSL(final int r, final int g, final int b, final float[] hsl) { final float varR = (r / 255f); final float varG = (g / 255f); final float varB = (b / 255f); float varMin; float varMax; float delMax; if (varR > varG) { varMin = varG; varMax = varR; } else { varMin = varR; varMax = varG; } if (varB > varMax) { varMax = varB; } if (varB < varMin) { varMin = varB; } delMax = varMax - varMin; float hue; float saturation; float lightness; lightness = (varMax + varMin) / 2f; if (delMax - 0.01f <= 0.0f) { hue = 0; saturation = 0; } else { if (lightness < 0.5f) { saturation = delMax / (varMax + varMin); } else { saturation = delMax / (2 - varMax - varMin); } final float delRed = (((varMax - varR) / 6f) + (delMax / 2f)) / delMax; final float delGreen = (((varMax - varG) / 6f) + (delMax / 2f)) / delMax; final float delBlue = (((varMax - varB) / 6f) + (delMax / 2f)) / delMax; if (MathUtils.floatEquals(varR, varMax)) { hue = delBlue - delGreen; } else if (MathUtils.floatEquals(varG, varMax)) { hue = (1 / 3f) + delRed - delBlue; } else { hue = (2 / 3f) + delGreen - delRed; } if (hue < 0) { hue += 1; } if (hue > 1) { hue -= 1; } } hsl[0] = hue; hsl[1] = saturation; hsl[2] = lightness; }
9
public boolean login(String inUsername){ String sql = "select username " + "from Users " + "where username LIKE ?"; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, inUsername); ResultSet rs = ps.executeQuery(); while(rs.next()) { String username = rs.getString("username"); if( username.equalsIgnoreCase(inUsername)){ return true; } } } catch (SQLException e) { e.printStackTrace(); } finally { try { if(ps != null) ps.close(); } catch(SQLException e2) { e2.printStackTrace(); } } return false; }
5
public void die(){ alive = false; respawnX = x; respawnY = y; respawnColX = colOffsetX; respawnColY = colOffsetY; respawnWidth = width; respawnHeight = height; respawnTexture = texture; if(loot.size() > 0){ setBounds(x + colOffsetX + width/2 - 16, y + colOffsetY + height/2 - 16,32,32); setCollisionBox(6, 0, 20, 32); setTexture("res/items/bag.png"); }else{ visible = false; solid = false; } respawnTimer = Game.SECONDS + respawnTime; Game.PLAYER.addExp(exp); }
1
public static String getLocalHostName() throws SocketException, UnknownHostException { try { final String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName(); if (isFQDN(canonicalHostName)) { return canonicalHostName; } else { return InetAddress.getLocalHost().getHostName(); } } catch (UnknownHostException e) { NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaces().nextElement(); if (networkInterface == null) throw e; InetAddress ipAddress = networkInterface.getInetAddresses().nextElement(); if (ipAddress == null) throw e; return ipAddress.getHostAddress(); } }
4
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try { //metodo de impresion anterior por JTable /**try { MessageFormat headerFormat = new MessageFormat(jLabel1.getText()); MessageFormat footerFormat = new MessageFormat("- Página {0} -"); jTable1.print(PrintMode.FIT_WIDTH, headerFormat, footerFormat); } catch (PrinterException ex) { } **/ r_con.Connection(); JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(r_con.Consultar(consulta_Vigente)); //localizo el reporte JasperReport report = JasperCompileManager.compileReport("src/Reportes/"+nombre_reporte); //cargo los datos JasperPrint print = JasperFillManager.fillReport(report, new HashMap(), resultSetDataSource); //vector con las impresoras del modulo de la base de datos Vector<Vector<String>>v = r_con.getContenidoTabla("SELECT * FROM impresoras WHERE imp_id_modulo = "+id_modulo_imp); //total impresoras disponibles PrintService [] impresoras = PrintServiceLookup.lookupPrintServices(null, null); //vector con las impresoras del modulo como objeto impresora (PrintService) Vector<PrintService>impresoras_modulo = new Vector(); //objeto impresora en el que se imprime PrintService impresora = null; if (v.size()>0){ String nombre_imp; //caso en que sea una unica impresora por modulo //if(v.size()==1){ //nombre_imp=v.elementAt(0).firstElement(); //AttributeSet aset = new HashAttributeSet(); //aset.add(new PrinterName(nombre_imp, null)); //impresoras = PrintServiceLookup.lookupPrintServices(null, aset); //impresora = impresoras[0]; //} //caso en que haya mas de una impresora por modulo if (v.size()>=1){ //localizo con el simple nombre de la base de dato, el objeto impresora y los cargo for (int i = 0; i < v.size(); i++) { nombre_imp=v.elementAt(i).firstElement(); AttributeSet aset = new HashAttributeSet(); aset.add(new PrinterName(nombre_imp, null)); impresoras = PrintServiceLookup.lookupPrintServices(null, aset); impresora = impresoras[0]; impresoras_modulo.add(impresora); } //paso las impresoras del modulo a un arreglo para poder mostrarlo en el Dialog PrintService [] listado_impresoras = new PrintService[impresoras_modulo.size()]; for (int i = 0; i < impresoras_modulo.size(); i++) { listado_impresoras[i]=impresoras_modulo.elementAt(i); } //muestro el listado de impresoras como objeto y se la asigno a la impresora a imprimir impresora = (PrintService) JOptionPane.showInputDialog(null, "Seleccione una impresora asignada a este módulo:", "Imprimir Reporte", JOptionPane.QUESTION_MESSAGE, null, listado_impresoras, listado_impresoras[0]); } //mando a imprimir el reporte en la impresora if (impresora != null){ JRPrintServiceExporter jrprintServiceExporter = new JRPrintServiceExporter(); jrprintServiceExporter.setParameter(JRExporterParameter.JASPER_PRINT, print ); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, impresora ); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.TRUE); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE); jrprintServiceExporter.exportReport(); } } else{ JOptionPane.showMessageDialog(null, "No hay Impresoras asignadas a este Modulo, " + "\npóngase en contacto con el Administrador de Impresoras.","Atención",JOptionPane.WARNING_MESSAGE); } r_con.cierraConexion(); } catch (JRException ex) { Logger.getLogger(GUI_Listado.class.getName()).log(Level.SEVERE, null, ex); r_con.cierraConexion(); } }//GEN-LAST:event_jButton2ActionPerformed
6
public Double relativePrime(Double x) { ArrayList<Double> primes = new ArrayList<Double>(); Double relativePrime = BigInteger.probablePrime(9, new Random()).doubleValue(); while (relativePrime<x) { if (BigInteger.valueOf(x.longValue()).gcd(BigInteger.valueOf(relativePrime.longValue())).intValue() == 1) { relativePrime = Math.pow(relativePrime, Math.floor((Math.random()*2)+1)); if (relativePrime < x) { return relativePrime; } } relativePrime = BigInteger.probablePrime(9, new Random()).doubleValue(); } return relativePrime; }
3
@Override public void finishPopulate() { }
0
public void deleteObject(ChunkyObject chunkyObject) { if (isLoaded()) { query(QueryGen.deleteAllOwnership(chunkyObject)); query(QueryGen.deleteAllPermissions(chunkyObject)); query(QueryGen.deleteObject(chunkyObject)); if (chunkyObject instanceof ChunkyGroup) removeGroup((ChunkyGroup)chunkyObject); } }
2
public void receiveMsg(){ try { InputStream is = socket.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); Object newObj = ois.readObject(); if (newObj instanceof ClientModel) { // Always perform add when ClientModel receive to update client information ClientModel client = (ClientModel) newObj; // remove old object if(!server.clientList.isEmpty()){ ArrayList<ClientModel> deleteList = new ArrayList<ClientModel>(); for(ClientModel cm : server.clientList){ // distinguish clients by port number if(cm.port == client.port){ // server.clientList.remove(cm); deleteList.add(cm); } } server.clientList.removeAll(deleteList); } server.clientList.add(client); System.out.println("Client information is stored in server"); System.out.println(client.toString()); } else if (newObj instanceof String) { String filename = (String) newObj; System.out.println("Start to find file: "+filename); ArrayList<ClientModel> targets = server.find(filename); if(targets.isEmpty()||targets==null){ System.out.println("No result found: "+filename); } // Send the result back OutputStream os = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(targets); oos.close(); os.close(); } ois.close(); is.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
9
@Override public void addToEnd(String value) throws AlreadyExist { if (!exists(value)) { super.addToEnd(value); } else { throw new AlreadyExist("Alredy exist in List"); } }
1
public String process(String wikiText) { String[] linesArray = arrayOfBloks(wikiText); String HalfBaked = ""; for (String line : linesArray) { // For each bloke of text: // if it free text Wrap with P tag. // Otherwise append it as is. if (Util.isNormalText(line) == true) { String[] a = Util.splitByNewLineSign(line); line = ArrayUtils.join(a, "<br/>\n"); HalfBaked += "<p>" + line + "</p>\n"; } else { HalfBaked += line + '\n'; } } return jobManager(HalfBaked); }
2
public void printProblem() { System.out.println("Number of meetings: " + this.NumMeetings); System.out.println("Number of employees: " + this.NumEmployees); System.out.println("Number of time slots: " + this.NumTimeSlots); System.out.println("Meetings each employee must attend:"); for(Integer e : this.EmployeeMeetingMap.keySet()) { ArrayList<Integer> meetings = this.EmployeeMeetingMap.get(e); System.out.print(e + ":"); for(Integer m: meetings) { System.out.print(" " + m); } System.out.println(); } System.out.println("Travel time between meetings: "); System.out.print(" "); for(Integer i = 1; i <= this.NumMeetings; i++) { System.out.print(i + " "); } System.out.println(); for(Integer i = 0; i < this.NumMeetings; i++) { System.out.print((i + 1) + ": "); for(Integer j = 0; j < this.NumMeetings; j++) { System.out.print(this.TravelTimes.get(i).get(j) + " "); } System.out.println(); } }
5
public GuideUserAction predict(DependencyStructure gold, ParserConfiguration configuration) throws MaltChainedException { StackConfig config = (StackConfig)configuration; Stack<DependencyNode> stack = config.getStack(); if (!swapArrayActive) { createSwapArray(gold); swapArrayActive = true; } GuideUserAction action = null; if (stack.size() < 2) { action = updateActionContainers(NonProjective.SHIFT, null); } else { DependencyNode left = stack.get(stack.size()-2); int leftIndex = left.getIndex(); int rightIndex = stack.get(stack.size()-1).getIndex(); if (swapArray.get(leftIndex) > swapArray.get(rightIndex)) { action = updateActionContainers(NonProjective.SWAP, null); } else if (!left.isRoot() && gold.getTokenNode(leftIndex).getHead().getIndex() == rightIndex && nodeComplete(gold, config.getDependencyGraph(), leftIndex)) { action = updateActionContainers(NonProjective.LEFTARC, gold.getTokenNode(leftIndex).getHeadEdge().getLabelSet()); } else if (gold.getTokenNode(rightIndex).getHead().getIndex() == leftIndex && nodeComplete(gold, config.getDependencyGraph(), rightIndex)) { action = updateActionContainers(NonProjective.RIGHTARC, gold.getTokenNode(rightIndex).getHeadEdge().getLabelSet()); } else { action = updateActionContainers(NonProjective.SHIFT, null); } } return action; }
8
public IrcListenerThread(AprilonIrc plugin, IrcClient hostclient) { this.Parent = plugin; this.HostClient = hostclient; this.HostReader = hostclient.getReader(); thread = new Thread(this); }
0
public static void validateHotel(Hotel hotel) throws TechnicalException { if (hotel == null) { throw new TechnicalException(MSG_ERR_NULL_ENTITY); } if ( ! isStringValid(hotel.getName(), NAME_SIZE)) { throw new TechnicalException(NAME_ERROR_MSG); } if ( ! isStringValid(hotel.getPicture(), PICTURE_SIZE)) { throw new TechnicalException(PICTURE_ERROR_MSG); } if ( ! isSelectedElem(hotel.getCity().getIdCity())) { throw new TechnicalException(SELECT_CITY_ERROR_MSG); } if ( ! isSelectedElem(hotel.getStars()) || ! isValidStars(hotel.getStars())) { throw new TechnicalException(SELECT_STARS_ERROR_MSG); } }
6
@Basic @Column(name = "description") public String getDescription() { return description; }
0
public static void main(String args[]) { SynchronizedSrc target = new SynchronizedSrc(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } //System.out.println("Main Thread"); }
1
@Override public V get(K key) throws InvalidKeyException, InvalidPositionException, BoundaryViolationException, EmptyTreeException { checkKey(key); Position<Entry<K, V>> currentP = treeSearch(key, root()); actionP = currentP; if (isInternal(currentP)) return value(currentP); return null; }
1
public RGBColor pathShade(ShadeRec rec, int depth) { RGBColor L=new RGBColor(RGBColor.black); int lightnum=rec.w.ls.size(); Light cur; for(int i=0;i<lightnum;i++){ cur=rec.w.ls.get(i); if(cur instanceof AreaLight){ AreaLight arealight=(AreaLight)cur; boolean shadowed=false; arealight.randsam(); Vector3D w=arealight.direction(rec); Ray shadowray=new Ray(rec.local_hit_point,w); Normal n=rec.normal; double dot=w.dot(n); Normal r=n.multiply(2.0*dot).add(new Normal(w.minus())); double dotr=r.dot(rec.r.d.minus()); double ksr=Math.pow(dotr, shininess); shadowed=arealight.shadowed(shadowray, rec); if(!shadowed){ if(dot>0.0) L.plusEqual( diffuse.get().multiply(cur.radiance(rec).multiply(dot*arealight.G(rec)))); if(dotr>0.0) L.plusEqual(specular.get().multiply(cur.radiance(rec).multiply(dot*ksr*arealight.G(rec)))); } } } double prob =random.nextDouble(); double faktor=1.0; if(depth>0) if(prob<0.5) return L; else{ faktor=0.5; } Vector3D n=sample(rec,rec.r.d.minus()); Vector3D wo=rec.r.d; double ndotwo = rec.normal.dot(wo.minus()); Vector3D r = wo.add(new Vector3D(rec.normal.multiply(2.0* ndotwo))); // double phong_lobe = Math.pow(n.dot(r), shininess); // double pdfs = phong_lobe * (rec.normal.dot(n)); //double pdfs = (rec.normal.dot(n)); // System.out.println(n); double pdfd = (rec.normal.dot(n)); if(pdfd>0.001) { // for rays going bak into objekt{ prob=random.nextDouble(); if(prob<0.5) L.plusEqual(diffuse.get().multiply(rec.w.tracer.trace_ray(new Ray(rec.local_hit_point,n.hat()), depth+1,false)).multiply(pdfd/(faktor*0.5)) ); else L.plusEqual(specular.get().multiply(rec.w.tracer.trace_ray(new Ray(rec.local_hit_point,r), depth+1,false)).multiply(1/(0.5*faktor))); } return L; }
9
@Override public boolean execute(final CommandSender sender, final String[] split) { if (sender instanceof Player) { if (MonsterIRC.getHandleManager().getPermissionsHandler() != null) { if (!MonsterIRC.getHandleManager().getPermissionsHandler() .hasCommandPerms((Player) sender, this)) { sender.sendMessage("[IRC] You don't have permission to preform that command."); return true; } } else { sender.sendMessage("[IRC] PEX not detected, unable to run any IRC commands."); return true; } } if (split.length < 3) { sender.sendMessage("[IRC] Please specify a channel to leave!"); return false; } if (split[2] == null) { sender.sendMessage("[IRC] Please specify a channel to leave!"); return false; } for (final IRCChannel c : Variables.channels) { if (c.getChannel().equalsIgnoreCase(split[2])) { MonsterIRC.getHandleManager().getIRCHandler().part(c); return true; } } sender.sendMessage("[IRC] Could not part from that channel!"); return true; }
7
@Override public void validate(ProcessingEnvironment procEnv, RoundEnvironment roundEnv, TypeElement annotationType, AnnotationMirror annotation, ExecutableElement e) { AnnotationValue expectedReturnType = AnnotationProcessingUtils .getAnnotationElementValue(procEnv, annotation, "expectedReturnType"); AnnotationValue strictValue = AnnotationProcessingUtils .getAnnotationElementValue(procEnv, annotation, "strict"); Boolean strict = (Boolean) strictValue.getValue(); if (!matches(procEnv, strict, e.getReturnType(), (TypeMirror) expectedReturnType.getValue())) { procEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, (String) AnnotationProcessingUtils .getAnnotationElementValue(procEnv, annotation, "errorMessage").getValue(), e, annotation, expectedReturnType); } }
1
public static Double parseTimestamp(String data) { String[] lines = data.split("\n"); for (String line : lines) { String[] parts = line.split(":", 2); if (parts[0].equals("t")) { return Double.parseDouble( parts[1].replace(",",".") ); } } return null; }
2
public void func() { System.out.println(this + ".func() : " + data); }
0
public Collection<Label> getLabels() { try { if (labels.size() == 0) execute(); } catch (SQLException e) { e.printStackTrace(); } return labels.values(); }
2
public int dividir(int a, int b) throws MiExcepcion{ if (a==5){ throw new MiExcepcion("No vale el número 5"); } if (b==0){ throw new MiExcepcion("Oh por DIOS!?!? ¿qué hiciste?"); } return a / b; }
2
public boolean qualifies(MOB mob, Room R) { if((mob==affected)||(mob==null)) return false; if(mob.fetchEffect(ID())!=null) return false; if(mob.isMonster()) { if(matchPlayersFollowersOnly) { final MOB folM=mob.amUltimatelyFollowing(); return (folM!=null)&& (!folM.isMonster()); } return (!matchPlayersOnly); } if((!CMSecurity.isAllowed(mob,R,CMSecurity.SecFlag.CMDMOBS)) &&(!CMSecurity.isAllowed(mob,R,CMSecurity.SecFlag.CMDROOMS)) &&(!CMLib.flags().isUnattackable(mob))) return true; return false; }
9
public String getPermutation(int n, int k) { // Start typing your Java solution below // DO NOT write main() function if (k > factorial(n) || k <= 0 || n <= 0) { return new String(); } StringBuilder sb = new StringBuilder(); ArrayList<Integer> num = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { num.add(i); } System.out.println("size" + num.size()); int[] factor = new int[n];// store factorial result to speed up for (int i = 0; i <= n - 1; i++) { factor[i] = factorial(i); } // determine the permutation digit by digit for (int i = 0; i < n; i++) { int f = factor[n - i - 1]; int j = 0; while (j * f < k) { j++; } j--; k -= j * f; sb.append(String.valueOf(num.get(j))); num.remove(j); } return sb.toString(); }
7
private void nombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombreActionPerformed nombre.setText(cliente.getNombre()); }//GEN-LAST:event_nombreActionPerformed
0
public Object copyColorData() { // Note: This is a fudge. The data about defaultColor, // groutingColor, and alwaysDrawGrouting is added to the // last row of the grid. If alwaysDrawGrouting is true, // this is recorded by adding an extra empty space to // that row. Color[][] copy = new Color[rows][columns]; // Replace the last row with a longer row. if (alwaysDrawGrouting) copy[rows-1] = new Color[columns+3]; else copy[rows-1] = new Color[columns+2]; for (int r = 0; r < rows; r++) for (int c = 0; c < columns; c++) copy[r][c] = grid[r][c]; copy[rows-1][columns] = defaultColor; copy[rows-1][columns+1] = groutingColor; return copy; }
3
public boolean validateUserName(String userName) throws IllegalAccessError, SocketTimeoutException { boolean answer = false; try { clientSocket.Escribir("USUARIO " + userName + '\n'); serverAnswer = clientSocket.Leer(); } catch (IOException e) { throw new SocketTimeoutException(); } if(serverAnswer != null) { if(serverAnswer.contains("OK")) { answer = true; } else if(serverAnswer.contains("599 ERR")) { throw new IllegalAccessError(); } System.out.println(serverAnswer); } return answer; }
4
public void paint(Graphics g) { if(mElementDimension == null) { mElementDimension = new Dimension(); FontMetrics fm = g.getFontMetrics(mFonts[0]); mElementDimension.width = fm.charWidth('_')+1; mElementDimension.height = fm.getHeight()+1; } Stack<AffineTransform> transforms = new Stack<AffineTransform>(); Graphics2D g2D = (Graphics2D) g; // Background elements drawing // Text drawing // Setup text model g2D.translate(0, mElementDimension.height); for(int x = 0; x < mElementCount.width; x++) for(int y = 0; y < mElementCount.height; y++) { if(mElements[y][x].mValue != 0) { transforms.push(g2D.getTransform()); g2D.translate(x * mElementDimension.width, y * mElementDimension.height); g2D.setFont(mFonts[(mElements[y][x].mFlags & 3)]); g2D.setColor(mElements[y][x].mBackColor); g2D.fillRect(0, -mElementDimension.height+1, mElementDimension.width, mElementDimension.height); g2D.setColor(mElements[y][x].mColor); if((mElements[y][x].mFlags & StyleFlipped) > 0) { g2D.translate(mElementDimension.width, 0); g2D.scale(-1, 1); } if((mElements[y][x].mFlags & StyleInverted) > 0) { g2D.scale(1, -1); g2D.translate(0, mElementDimension.height-5); } if((mElements[y][x].mFlags & StyleUnderlined) > 0) g2D.drawLine(0, 0, mElementDimension.width, 0); g2D.drawString("" + mElements[y][x].mValue, 0, 0); g2D.setTransform(transforms.pop()); } } if(mCaretState && mCaretVisible) { transforms.push(g2D.getTransform()); g2D.translate(mElementCursorPosition.x * mElementDimension.width, mElementCursorPosition.y * mElementDimension.height); g2D.drawString("_", 0, 0); g2D.setTransform(transforms.pop()); } // Overhead elements }
9
@Test public void treeMapRetrievesIndexes() { Random r = new Random(); for (int i = 0; i < 1000; i++) { MyInteger m = new MyInteger(r.nextInt(10000)); if (!tree.contains(m)) treeHeap.insert(m); } Object[] array = treeHeap.getArray(); boolean test = true; for (int i = 0; i < treeHeap.size(); i++) { if (tree.get((MyInteger)array[i]) != i) test = false; } assertTrue(test); }
4
public static Rectangle2D getBounds(CellView[] views) { if (views != null && views.length > 0) { Rectangle2D r = (views[0] != null) ? views[0].getBounds() : null; Rectangle2D ret = (r != null) ? (Rectangle2D) r.clone() : null; for (int i = 1; i < views.length; i++) { r = (views[i] != null) ? views[i].getBounds() : null; if (r != null) { if (ret == null) ret = (r != null) ? (Rectangle2D) r.clone() : null; else Rectangle2D.union(ret, r, ret); } } return ret; } return null; }
9
private void about() { JOptionPane .showMessageDialog( this, "Mit Hilfe von diesem Programm k\u00F6nnen Sie Ihre Kontakte verwalten.\n" + "Es besitzt Aktionen zum Erstellen, L\u00F6schen und Editieren\n" + "Ihrer Kontakte und hat Felder wie Vorname, Nachname und eMail."); }
0
public CLC() { commandMap = new HashMap<String, Action>(); abbrMap = new HashMap<Character, Action>(); optionMap = new HashMap<String, Action>(); contextMap = new HashMap<String, CLC>(); defaultAction = unknownCommandAction; rootAction = defaultRootAction; }
0
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); QuizService quizService = new QuizService(); int quizId = Integer.parseInt(request.getParameter("quizId")); Quiz quiz = null; //deleteQuiz case if(request.getParameter("deleteQuiz")!=null){ quizService.deleteEntity(quizId); session.setAttribute("notifyM", "Quiz successfully deleted"); // update quizes list Collection<Quiz> quizes = quizService.getEntityList(); session.setAttribute("quizes", quizes); response.sendRedirect("protected/admin/editQuizes.jsp"); return; } // addQuestion case if (request.getParameter("addQuestion") != null) { quiz = quizService.getEntityById(quizId); session.setAttribute("quizType", quiz.getType()); request.setAttribute("quizId", quizId); request.getRequestDispatcher("protected/admin/addQuestion.jsp") .forward(request, response); return; } // editQuestion case if (request.getParameter("editQuestion") != null) { int questionId = Integer.parseInt(request .getParameter("editQuestion")); QuestionService questionService = new QuestionService(); Question question = questionService.getEntityById(questionId); request.setAttribute("question", question); // redirect to edit question request.getRequestDispatcher("protected/admin/editQuestion.jsp") .forward(request, response); return; // delete question case } else if (request.getParameter("deleteQuestion") != null) { int questionId = Integer.parseInt(request .getParameter("deleteQuestion")); QuestionService questionService = new QuestionService(); questionService.deleteEntity(questionId); // get the updated quiz, without the deleted question quiz = quizService.getEntityById(quizId); session.setAttribute("notifyM", "Question successfully deleted"); session.setAttribute("quiz", quiz); // update quizes list Collection<Quiz> quizes = quizService.getEntityList(); session.setAttribute("quizes", quizes); response.sendRedirect("protected/admin/editQuiz.jsp"); return; } // update quiz case String qName = request.getParameter("quizName"); boolean ordered; int type = 0; try { ordered = Boolean.parseBoolean(request .getParameterValues("ordered")[0]); } catch (Exception e) { Logger.getLogger(EditQuizServlet.class).debug(e.getMessage()); ordered = false; } int timeLimit = Integer.parseInt(request.getParameter("timeLimit")); if (request.getParameter("type") != null) type = Integer.parseInt(request.getParameter("type")); String comments = request.getParameter("comments"); try { Quiz q = new Quiz(); q.setId(quizId); q.setName(qName); q.setOrdered(ordered); q.setTimeLimit(timeLimit); q.setType(type); q.setModifiedDate(new Timestamp(new Date().getTime())); q.setComments(comments); quizService.updateEntity(q); } catch (WordContainsException e) { Logger.getLogger(EditQuizServlet.class).debug(e.getMessage()); e.printStackTrace(); session.setAttribute("errorM", "Could not update quiz. \n A Quiz with name " + qName + " already exits"); response.sendRedirect("protected/admin/editQuiz.jsp"); return; } // refresh the quizes list after update of a quiz session.setAttribute("quizes", quizService.getEntityList()); session.setAttribute("notifyM", "Quiz successfully updated"); response.sendRedirect("protected/admin/editQuizes.jsp"); }
7
@Override public void actionPerformed(GuiButton button) { if(button.id == 0) holder.closeWindow(this); else if(button.id == 1) { try { Entity e = ((GuiEditor)holder).getMap().getEntityList().getEntityWithUUID(entity); R2DFileManager manager = new R2DFileManager(textField.text,null); Map.saveEntityFull(e, manager.getCollection(), true); manager.write(); e.setPrefabPath(textField.text); holder.closeWindow(this); }catch(Exception e) { throw new Remote2DException(e); } } }
3
void notifyConnected () { if (INFO) { SocketChannel socketChannel = tcp.socketChannel; if (socketChannel != null) { Socket socket = tcp.socketChannel.socket(); if (socket != null) { InetSocketAddress remoteSocketAddress = (InetSocketAddress)socket.getRemoteSocketAddress(); if (remoteSocketAddress != null) info("kryonet", this + " connected: " + remoteSocketAddress.getAddress()); } } } Listener[] listeners = this.listeners; for (int i = 0, n = listeners.length; i < n; i++) listeners[i].connected(this); }
5
private void calcMode(ArrayList<Double> values) { int maxCount = 0; /* Tallies each value to determine the max count */ for (int i = 0; i < values.size(); i++) { int count = 0; // count resets to 0 for (int j = 0; j < values.size(); j++) { if (values.get(j).equals(values.get(i))) { count++; if (count > maxCount) { maxCount = count; } } } } mode.clear(); // empties mode for re-use /* Adds a mode to the list if it qualifies */ for (int i = 0; i < values.size(); i++) { int count = 0; for (int j = 0; j < values.size(); j++) { if (values.get(j).equals(values.get(i))) { count++; if (count == maxCount && !mode.contains(values.get(i))) { mode.add(values.get(i)); } } } } }
9
public static boolean inCWars() { int x = Players.getLocal().getLocation().getX(); int y = Players.getLocal().getLocation().getY(); return (y >= 3072 && y < 3135 && x > 2368 && x < 2431); }
3
public final DccFileTransfer dccSendFile(File file, String nick, int timeout) { DccFileTransfer transfer = new DccFileTransfer(this, _dccManager, file, nick, timeout); transfer.doSend(true); return transfer; }
0