text
stringlengths
14
410k
label
int32
0
9
public void Play() { if (!left && !right) snapToX(); if (!up && !down) snapToY(); moveRight(right); moveLeft(left); moveDown(down); moveUp(up); for(int a = 0; a < totalBullets; a++){ bullet[a].Play(); } }
5
private boolean processProduction(Production production, Grammar grammar, FirstSets firstSets) { if (production.isEpsilonMove()) { return false; } boolean result = false; int index = 0; for (final Symbol symbol : production.getRight()) { final Set<Symbol> follow = sets.get(symbol); final Set<Symbol> first = firstSets.getFirstSet( production.getRight(), index + 1); if ((first.remove(grammar.getEpsilon()) || (index == production.getRight().size() - 1)) && follow.addAll(sets.get(production.getLeft()))) { result = true; } if (follow.addAll(first)) { result = true; } index++; } return result; }
6
public void execute( JobExecutionContext context ) throws JobExecutionException { invocation++; }
0
public boolean esDigito(int num) { boolean retorno; switch(num) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': retorno=true; break; default: retorno=false; break; } return retorno; }
9
public void newTitle(String title) { final int length = title.length(); if (length == 0) { title = "NO_TITLE"; newTitle(title); return; } if (_first) _first = false; else newLine(); StringBuilder line = new StringBuilder(); int i; for (i = 0 ; i < _titleMargin ; i++) line.append(' '); line.append(_cross); for (i = 0 ; i < length + 2 ; i++) line.append(_horizontal); line.append(_cross); doReport(line.toString()); newLine(); StringBuilder line2 = new StringBuilder(); for (i = 0 ; i < _titleMargin ; i++) line2.append(' '); line2.append(_vertical); line2.append(' '); line2.append(title); line2.append(' '); line2.append(_vertical); doReport(line2.toString()); newLine(); doReport(line.toString()); _isTitle = false; }
5
public String and(String field, int min, int max) { String newField = "", number = ""; System.out.println(field.substring(0, 3)); if(field.substring(0, 3).equals("AND")) { newField = ","; field = field.substring(3); for(int i = 1; i <= field.length(); i++) { if(isNumber(field.substring(i - 1, i))) { newField = newField + field.substring(i - 1, i); number = number + field.substring(i - 1, i); } else { if(field.substring(i - 1, i).equals("A") && field.substring(i - 1).length() > 3) { if(field.substring(i - 1, i + 2).equals("AND")) { newField = newField + ","; number = ""; i = i + 2; } else { newField = "~invalid~"; } } else if(field.substring(i - 1, i).equals(" ")) { // ignore space } else { newField = "~invalid~"; break; } } } } else { newField = "~invalid~"; } return newField; }
7
@Test public void multipleBoxTest() { BoundingBox bigBox = new BoundingBox(-100.0d, 100.0d, -100.0d, 100.0d); List<BoundingBox> boxes = new ArrayList<BoundingBox>(); for (int i=0; i<10000; i++) { boxes.add(BoundingBox.containing(bigBox.randomPoint(), bigBox.randomPoint())); } for (int i=0; i<boxes.size();i++) { BoundingBox first = boxes.get(i); assertTrue(bigBox.contains(first)); assertTrue(first.isContainedBy(bigBox)); assertFalse(bigBox.isOutside(first)); assertFalse(first.isOutside(bigBox)); assertFalse(bigBox.intersects(first)); assertFalse(first.intersects(bigBox)); for (int j=i+1; j< boxes.size(); j++) { BoundingBox second = boxes.get(j); if (second.contains(first)) { assertTrue(first.isContainedBy(second)); assertFalse(first.contains(second)); assertFalse(second.isOutside(first)); assertFalse(first.isOutside(second)); assertFalse(second.intersects(first)); assertFalse(first.intersects(second)); } else if (first.contains(second)) { assertTrue(second.isContainedBy(first)); assertFalse(second.contains(first)); assertFalse(second.isOutside(first)); assertFalse(first.isOutside(second)); assertFalse(second.intersects(first)); assertFalse(first.intersects(second)); } else if (first.isOutside(second)) { assertTrue(second.isOutside(first)); assertFalse(first.contains(second)); assertFalse(first.isContainedBy(second)); assertFalse(second.contains(first)); assertFalse(second.isContainedBy(first)); assertFalse(second.intersects(first)); assertFalse(first.intersects(second)); } else if (first.intersects(second)) { assertTrue(second.intersects(first)); assertFalse(first.contains(second)); assertFalse(first.isContainedBy(second)); assertFalse(second.contains(first)); assertFalse(second.isContainedBy(first)); assertFalse(second.isOutside(first)); assertFalse(first.isOutside(second)); } } } }
7
public static Type wrapTypeAndReplaceTypeVariables(final Type type, final TypeMap typeMap) { if (isParameterizedType(type)) { final ParameterizedType parameterizedType = getAsParameterizedType(type); final Type[] wrappedArguments = wrapTypeParameters(parameterizedType.getActualTypeArguments(), typeMap); final Class<?> asClass = getAsClass(type); return new WrappedParameterizedType(asClass, wrappedArguments); } else if (isWildcard(type)) { final WildcardType wildcardType = (WildcardType) type; final Type[] wrappedUpperBounds = wrapTypeParameters(wildcardType.getUpperBounds(), typeMap); final Type[] wrappedLowerBounds = wrapTypeParameters(wildcardType.getLowerBounds(), typeMap); return new WrappedWildcardType(wrappedUpperBounds, wrappedLowerBounds); } else if (isGenericArrayType(type)) { final GenericArrayType genericArrayType = (GenericArrayType) type; final Type wrappedType = wrapTypeAndReplaceTypeVariables(genericArrayType.getGenericComponentType(), typeMap); return new WrappedGenericArrayType(wrappedType); } else if (isTypeVariable(type)) { final Type actualType = typeMap.getActualType((TypeVariable<?>) type); if (actualType != null) { return actualType; } } return type; }
7
public CheckResultMessage checkJ01(int day) { return checkReport.checkJ01(day); }
0
public void close(ResultSet rs, PreparedStatement ps, Connection conn) { if (rs != null) { try { rs.close(); rs = null; } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); ps = null; } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); conn = null; } catch (SQLException e) { e.printStackTrace(); } } }
6
public void setIntArray(int[] intArray){ this.intArray = intArray; }
0
public void actionPerformed (ActionEvent event) { String eventName=event.getActionCommand(); // OK if (eventName.equals("OK")) { // Transfer the trigger this to the main program TtheApp.setListTriggers(triggerList); changedTriggers=true; dispose(); } // Cancel else if (eventName.equals("Cancel")) { changedTriggers=false; dispose(); } // Delete a trigger else if (eventName.equals("Delete the selected Trigger")) { deleteTrigger(); } // Edit a trigger else if (eventName.equals("Edit the selected Trigger")) { // Find the name of the selected Trigger String selectedTriggerName=(String) triggerComboList.getSelectedItem(); // Get the list index of this trigger int index=getTriggerIndex(selectedTriggerName); // Check if anything has been selected if (index==-1) { JOptionPane.showMessageDialog(null,"Please select the Trigger you wish to edit.","Rivet", JOptionPane.ERROR_MESSAGE); return; } TriggerModifyAddEdit triggerMod=new TriggerModifyAddEdit(this,triggerList.get(index)); // Has a trigger changed ? if (triggerMod.isChangedTriggers()==true) { // Remove the old trigger triggerList.remove(index); // Add the edited trigger triggerList.add(triggerMod.exposeTrigger()); // Ensure the object knows that changes have been made changesMade(); } } // Add a trigger else if (eventName.equals("Add a new Trigger")) { TriggerModifyAddEdit triggerMod=new TriggerModifyAddEdit(this,null); // Has a trigger changed ? if (triggerMod.isChangedTriggers()==true) { triggerList.add(triggerMod.exposeTrigger()); // Ensure the object knows that changes have been made changesMade(); } } }
8
static public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[17]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 5; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } } } } for (int i = 0; i < 17; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
8
public void setNombre(String nombre) { this.nombre = nombre; }
0
private boolean check() { if (N == 0) { if (first != null) return false; } else if (N == 1) { if (first == null) return false; if (first.next != null) return false; } else { if (first.next == null) return false; } // check internal consistency of instance variable N int numberOfNodes = 0; for (Node x = first; x != null; x = x.next) { numberOfNodes++; } if (numberOfNodes != N) return false; return true; }
8
public int[] getInts(int par1, int par2, int par3, int par4) { int ai[] = IntCache.getIntCache(par3 * par4); for (int i = 0; i < par4; i++) { for (int j = 0; j < par3; j++) { initChunkSeed(par1 + j, par2 + i); ai[j + i * par3] = nextInt(10) != 0 ? 0 : 1; } } if (par1 > -par3 && par1 <= 0 && par2 > -par4 && par2 <= 0) { ai[-par1 + -par2 * par3] = 1; } return ai; }
7
public void set(long pos, long val) { if (start == end && start == pos) { minVal = maxVal = val; sumVal = val; } else { long mid = (start + end) / 2; if (pos <= mid) left.set(pos, val); else right.set(pos, val); minVal = Math.min(left.minVal, right.minVal); maxVal = Math.max(left.maxVal, right.maxVal); sumVal = left.sumVal + right.sumVal; } }
3
private void Escalao_ComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Escalao_ComboBox3ActionPerformed // atualizar Torneio_ComboBox Torneio_ComboBox.removeAllItems(); Collection <Competicao> competicoes = a.getDAOCompeticao().values(); if (competicoes != null) { String escalao = "class Escalao." + Escalao_ComboBox3.getSelectedItem().toString(); for(Competicao competicao: competicoes) { if (competicao instanceof Torneio && competicao.getEscalao().getClass().toString().equals(escalao)) Torneio_ComboBox.addItem(competicao.getNome()); } } }//GEN-LAST:event_Escalao_ComboBox3ActionPerformed
4
public static void main(String[] args) { System.out.println("Tervetuloa etsimään polkuja. Haluatko syöttää " + "karttatiedoston nimen (1) vai antaa kartan koon koordinaatteina (jokin muu numero)? "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Kartta kartta; String xAlku; String yAlku; String xLoppu; String yLoppu; try { String arvo = br.readLine(); if ("1".equals(arvo)) { System.out.println("Anna suoritushakemiston juuressa sijaitsevan " + "kuvatiedoston nimi tiedostopäätteineen: "); kartta = new Kartta<Noodi>(br.readLine()); } else { System.out.println("Anna kartan x-koordinaattien määrä: "); String x = br.readLine(); System.out.println("Anna kartan y-koordinaattien määrä: "); String y = br.readLine(); //Lisätään annettuihin koordinaattimääriin yksi koska kartan //indeksit alkavat nollasta kartta = new Kartta<Noodi>(Integer.parseInt(x)+1, Integer.parseInt(y)+1); } System.out.println("Anna aloituspisteen x-koordinaatti: "); xAlku = br.readLine(); System.out.println("Anna aloituspisteen y-koordinaatti: "); yAlku = br.readLine(); System.out.println("Anna lopetuspisteen x-koordinaatti: "); xLoppu = br.readLine(); System.out.println("Anna lopetuspisteen y-koordinaatti: "); yLoppu = br.readLine(); //Loppupisteistä vähennetään yksi koska oikeasti indeksit alkavat nollasta. Pino polku = kartta.etsiPolku(Integer.parseInt(xAlku), Integer.parseInt(yAlku), Integer.parseInt(xLoppu), Integer.parseInt(yLoppu), ""); if (polku.size() == -1) { System.out.println("Polkua ei löytynyt!"); } else { System.out.println("Läpikuljettujen noodien määrä:" + polku.size()); while(!polku.onkoTyhja()){ Noodi noodi = polku.poista(); System.out.print("(" + noodi.getxPositio() + ", " + noodi.getyPositio() + ") -> "); } } } catch (IOException ioe) { System.out.println("IO-virhe vastauksen tulkinnassa"); System.exit(1); } catch (IllegalArgumentException iae){ System.out.println("Annoit koordinaatin joka ei ole kartalla!"); } catch (Exception ex){ throw ex; } }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Utente other = (Utente) obj; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; return true; }
6
private void doPublicStuff(Patient patient) { LinkedBlockingDeque<Patient> q = doc_queues.get(HospitalPart.PUBLIC); q.add(patient); log("enter " + "Public" + " Q", clock, patient, "Public", doc_queues .get(HospitalPart.PUBLIC).size()); if (q.size() > max.getMaxQ()) { max.setMaxQ(q.size()); max.setHp(HospitalPart.PUBLIC); } handlePublicQueue(); }
1
public void setChildren() { if (main == null) { return; } if (main.hasChildren()) { children = new LinkedList<RSInterface>(); layers = new LinkedList<RSInterface>(); for (int index = 0; index < main.children.size(); index++) { RSInterface child = RSInterface.getInterface(main.children.get(index)); if (child.hasChildren()) { layers.add(child); } children.add(child); } } }
4
public void populateTable() { NPC_DATA.removeAllElements(); NPC[] allNPCs = NPCs.getLoaded(new Filter<NPC>() { final int Radius = 20; @Override public boolean accept(NPC npc) { return (double)Calculations.distanceTo(npc) <= Radius && !npc.getName().equals("null"); } }); for (NPC npc : allNPCs) { final Object[] data = {npc.getName(), npc.getLevel(), npc.getId()}; final Vector<Object> dataVector = new Vector<>(Arrays.asList(data)); NPC_DATA.add(dataVector); } TABLE.repaint(); SCROLL_PANE.revalidate(); }
2
public MOB victimHere(Room room, MOB mob) { if(room==null) return null; if(mob==null) return null; for(int i=0;i<room.numInhabitants();i++) { final MOB M=room.fetchInhabitant(i); if((M!=null) &&(M!=mob) &&(!CMLib.flags().isEvil(M)) &&(mob.mayIFight(M)) &&(M.phyStats().level()<(mob.phyStats().level()+5))) return M; } return null; }
8
private void begin () { long t__send, dt; double rate; _t_send = System.currentTimeMillis(); while (++times <= Utils.MAX) { broadcast("TEST", String.format("%d", System.currentTimeMillis())); if (times % Utils.STEP == 0) { t__send = System.currentTimeMillis(); dt = t__send - _t_send; if (dt > 0) rate = (double) (Utils.STEP * 1000) / (double) dt; else rate = 0.0; Utils.out(pid, String.format("[SEND] %06d\trate %10.1f m/s", times, rate)); _t_send = t__send; } } }
3
public boolean locationWithinActor(double x, double y) { if(enabled) { // disabled actors cannot be targeted (TODO: is this good???) PhysicsComponent pc = (PhysicsComponent)getComponent("PhysicsComponent"); //HitboxComponent hc = (HitboxComponent)getComponent("HitboxComponent"); if(pc != null) { Rectangle hb = pc.getHitbox(); if(x > hb.getX() && x < hb.getX() + hb.getWidth() && y > hb.getY() && y < hb.getY() + hb.getHeight()) { return true; } } // TODO: add proper hitboxes perhaps maybe /* if(lc != null && hc != null) { double relativeX = x - lc.getX(); double relativeY = y - lc.getY(); return hc.locationInsideHitbox(relativeX, relativeY); } */ } return false; }
6
public void breakmethod () { while (true) { System.out.println("Input an integer"); n = input.nextInt(); if (n == 0) { break; } System.out.println("You entered " + n); } }
2
protected void process_term (int linger_) { assert (!pending); // If the termination of the pipe happens before the term command is // delivered there's nothing much to do. We can proceed with the // stadard termination immediately. if (pipe == null) { proceed_with_term (); return; } pending = true; // If there's finite linger value, delay the termination. // If linger is infinite (negative) we don't even have to set // the timer. if (linger_ > 0) { assert (!has_linger_timer); io_object.add_timer (linger_, linger_timer_id); has_linger_timer = true; } // Start pipe termination process. Delay the termination till all messages // are processed in case the linger time is non-zero. pipe.terminate (linger_ != 0); // TODO: Should this go into pipe_t::terminate ? // In case there's no engine and there's only delimiter in the // pipe it wouldn't be ever read. Thus we check for it explicitly. pipe.check_read (); }
2
public static int[] findLIS(int[] A) { int n = A.length; int[] M = new int[n]; int[] P = new int[n]; M[0] = 0; P[0] = -1; int L = 1; for (int i = 1; i < n; ++i) { int j = search(M, A, i, L); if (j == -1) P[i] = -1; else P[i] = M[j]; if (j == L - 1 || A[i] < A[M[j + 1]]) { M[j + 1] = i; if (j + 2 > L) L = j + 2; } } int[] LIS = new int[L]; n = L - 1; int p = M[n]; while (n >= 0) { LIS[n] = A[p]; p = P[p]; n--; } return LIS; }
6
@Override public File touch(String fileName) { //System.out.println("touch"); try { File f = new File(directory, fileName); f.createNewFile(); FileOutputStream os = new FileOutputStream(f); //os.write("Generated by Bulka".getBytes()); os.close(); //System.out.println(f.getAbsolutePath()); return f; } catch (IOException e) { handleException(e); } return null; }
1
@Override public String toString() { if (filterConfig == null) { return ("filtroAutenticacion()"); } StringBuffer sb = new StringBuffer("filtroAutenticacion("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); }
1
@Override public Record removeRecord(Account from, Record record) { PreparedStatement pStmt = null; Record rec = null; Integer result; rec = getRecord(record.getId()); if(rec != null){ try { pStmt = conn.prepareStatement("DELETE FROM RECORD WHERE id = ? AND id_account = ?;"); pStmt.setInt(1, record.getId()); pStmt.setInt(2, from.getId()); result = pStmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { closeResource(pStmt); } } return rec; }
2
public boolean szabalyose(){ if(aktualispoz1+2==hovaakar1 || aktualispoz1-2==hovaakar1) if(aktualispoz2+1==hovaakar2 || aktualispoz2-1==hovaakar2) return true; else {logger.info("A lépés nem huszár lépés!");return false;} else if(aktualispoz2+2==hovaakar2 || aktualispoz2-2==hovaakar2) if(aktualispoz1+1==hovaakar1 || aktualispoz1-1==hovaakar1) return true; else {logger.info("A lépés nem huszár lépés!"); return false;} logger.info("A lépés nem huszár lépés!"); return false; }
8
final public CycVariable variable(boolean requireEOF) throws ParseException { CycVariable val = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SIMPLE_VARIABLE: val = simpleVariable(false); break; case META_VARIABLE: val = metaVariable(false); break; default: jj_la1[30] = jj_gen; jj_consume_token(-1); throw new ParseException(); } eof(requireEOF); {if (true) return val;} throw new Error("Missing return statement in function"); }
4
@SuppressWarnings(value = "unchecked") public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: intField = (java.lang.Integer) value$; break; case 1: floatField = (java.lang.Float) value$; break; case 2: stringField = (java.lang.CharSequence) value$; break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } }
3
private JPanel createTimePanel() { JPanel newPanel = new JPanel(); newPanel.setLayout(new FlowLayout()); SpinnerDateModel dateModel = new SpinnerDateModel(); timeSpinner = new JSpinner(dateModel); if( timeFormat == null ) timeFormat = DateFormat.getTimeInstance( DateFormat.SHORT ); updateTextFieldFormat(); newPanel.add(new JLabel( "Time:" ) ); newPanel.add(timeSpinner); newPanel.setBackground(Color.WHITE); return newPanel; }
1
public Object[] update(final int i, final int j) { int gridValue = seaGrid[i + 1][j + 1]; Logger.debug("gridValue:" + gridValue); // You hit that before if (gridValue < 0 || gridValue == AbstractFleedModel.MISS) { return new Object[]{AGAIN, null}; } if (gridValue > 0 && gridValue < NUMBER_OF_SHIPS + 1) { Ship ship = ships[gridValue - 1]; // No need to wast bombs ;) if (ship.isDestroyed()) { return new Object[]{AGAIN, null}; } //boom beng: ship.hit(); if (ship.isDestroyed()) { shipsDestroyed++; for (int m = 0, ix = ship.getStartI(), jy = ship.getStartJ(); m < ship.getSize(); m++) { seaGrid[ix][jy] = Math.abs(gridValue); ix += (ship.getDir() == 0) ? 1 : 0; jy += (ship.getDir() != 0) ? 1 : 0; } listener.onTotalUpdate(this); return new Object[]{DESTROYED, ship}; } else { seaGrid[i + 1][j + 1] = -gridValue; listener.onPartialUpdate(this, i, j, AbstractFleedModel.HIT); return new Object[]{HIT, null}; } } seaGrid[i + 1][j + 1] = AbstractFleedModel.MISS; listener.onPartialUpdate(this, i, j, AbstractFleedModel.MISS); return new Object[]{MISS, null}; }
9
protected void processSpecialTag(boolean allowCDATA) throws Exception { String str = XMLUtil.read(this.reader, '&'); char ch = str.charAt(0); if (ch == '&') { XMLUtil.errorUnexpectedEntity(reader.getSystemID(), reader.getLineNr(), str); } switch (ch) { case '[': if (allowCDATA) { this.processCDATA(); } else { XMLUtil.errorUnexpectedCDATA(reader.getSystemID(), reader.getLineNr()); } return; case 'D': this.processDocType(); return; case '-': XMLUtil.skipComment(this.reader); return; } }
5
protected void updateAsMobile() { final Target target = this.targetFor(null) ; float idealHeight = DEFAULT_FLY_HEIGHT ; if (! health.conscious()) idealHeight = 0 ; else if (target == null) idealHeight = flyHeight ; else if (target instanceof Tile) idealHeight = DEFAULT_FLY_HEIGHT ; else if (Spacing.distance(target, this) < health.sightRange()) { idealHeight = target.position(null).z + (target.height() / 2f) - 0.5f ; } final float MFI = 1f / (2 * PlayLoop.UPDATES_PER_SECOND) ; flyHeight = Visit.clamp(idealHeight, flyHeight - MFI, flyHeight + MFI) ; super.updateAsMobile() ; }
4
public void doWork() throws IOException, NoSuchAlgorithmException{ Iterator<MetaConnection> itor = connections.iterator(); while(itor.hasNext()){ //Stand connection loop... MetaConnection mc = itor.next(); if(mc.getConnectionState() == ConnectionState.closed){ itor.remove(); System.out.println("ENDED: "+mc); }else if(mc.getConnectionState() == ConnectionState.uninitialized){ mc.blindInitialize(meta); }else if(mc.getConnectionState() == ConnectionState.connected){ //push requests. status = "Peer's found. Searching for meta data"; mc.setAmChoking(false); mc.setAmInterested(true); mc.doWork(this); // if(mc.supportsMetaMetaRequest()){ // if(mc.getActiveRequests().length<2){//pretty slow but w/e // // int i = meta.getOpenPiece(); // if(i!=-1){ // mc.sendMetaMetaRequest(i); // } //// System.out.println("Asking for piece! "+i+" from "+mc); // } // } } } DHTtracker.doWork(); List<MetaConnection> cms = DHTtracker.connections(); if(cms!=null){ connections.addAll(cms); } if(connections.size()==0){ DHTtracker.setAggrsive(); } if(meta.isComplete()){ //do something? if(meta.shaMatch(hashInfo)){ complete =true; } } }
8
private void removeDefeaterImpl() throws TheoryNormalizerException { List<Rule> rulesToAdd = new ArrayList<Rule>(); Set<String> rulesToDelete = new TreeSet<String>(); Map<String, List<Rule>> oldNewRuleMapping = new Hashtable<String, List<Rule>>(); List<Rule> newRules; List<Rule> newRuleMapping = null; try { for (Rule rule : factsAndRules.values()) { newRuleMapping = null; switch (rule.getRuleType()) { case STRICT: newRules = removeDefeater_transformRule(rule); rulesToAdd.addAll(newRules); rulesToDelete.add(rule.getLabel()); newRuleMapping = newRules; break; case DEFEASIBLE: if (rule.getHeadLiterals().size() > 1) throw new TheoryException(ErrorMessage.THEORY_NOT_IN_REGULAR_FORM_MULTIPLE_HEADS_RULE,new Object[]{rule.getLabel()}); // Messages.getErrorMessage(ErrorMessage.THEORY_NOT_IN_REGULAR_FORM_MULTIPLE_HEADS)); newRules = removeDefeater_transformRule(rule); rulesToDelete.add(rule.getLabel()); rulesToAdd.addAll(newRules); newRuleMapping = newRules; break; case DEFEATER: Rule r = removeDefeater_transformDefeater(rule); rulesToAdd.add(r); rulesToDelete.add(rule.getLabel()); break; default: } if (newRuleMapping != null) oldNewRuleMapping.put(rule.getLabel(), newRuleMapping); } theory.updateTheory(rulesToAdd, rulesToDelete, oldNewRuleMapping); } catch (TheoryException e) { throw new TheoryNormalizerException(getClass(), ErrorMessage.TRANSFORMATION_DEFEATER_REMOVAL_ERROR, "Defeater removal exception!", e); } }
7
public ListNode reverseKGroup(ListNode head, int k) { if (head == null || head.next == null) { return head; } ListNode pre = new ListNode(0); pre.next = head; head = pre; ListNode cur = pre.next; while (cur != null) { int counter = k; while (cur != null && counter > 1) { cur = cur.next; counter--; } if (cur != null) { cur = pre.next; counter = k; while (counter > 1) { ListNode temp = cur.next; cur.next = temp.next; temp.next = pre.next; pre.next = temp; counter--; } pre = cur; cur = pre.next; } } return head.next; }
7
public static String insertInSpecialPosition(String s, String s1, int position) { if(s.isEmpty()) { return s1; } else { StringBuilder sb = new StringBuilder(); sb.append(s.substring(0,position)); sb.append(s1); if(s.length()>position) { sb.append(s.substring(position)); } return sb.toString(); } }
2
private void serialiseResponse() { byte[] responseHeader = new byte[2]; byte[] responsePayload; // set the bits for the first byte responseHeader[0] = 0; responseHeader[1] = 0; if (FIN) responseHeader[0] = (byte) (responseHeader[0] | (byte) (1 << 7) ); if (RSV1) responseHeader[0] = (byte) (responseHeader[0] | (byte) (1 << 6) ); if (RSV2) responseHeader[0] = (byte) (responseHeader[0] | (byte) (1 << 5) ); if (RSV3) responseHeader[0] = (byte) (responseHeader[0] | (byte) (1 << 4) ); responseHeader[0] = (byte) (responseHeader[0] | (byte) (opcode) ); System.out.println("First byte of response. " + responseHeader[0]); // set the payload length if (payloadSize <= 125) { responseHeader[1] = (byte) payloadSize; responsePayload = new byte[0]; } else if (payloadSize <= 65535) { responseHeader[1] = (byte) 126; responsePayload = new byte[2]; responsePayload[0] = (byte) (payloadSize >> 8); responsePayload[1] = (byte) (payloadSize & 255); } else // TODO handle payloads over 65535 bytes { responsePayload = new byte[0]; } response = new byte[(int) (2 + responsePayload.length + message.length)]; for (int i=0; i<2; i++) { response[i] = responseHeader[i]; } // append int i; for (i=0; i<responsePayload.length; i++) { response[2+i] = responsePayload[i]; } int payloadStart = 2 + responsePayload.length; for (i=0; i<message.length; i++) { response[payloadStart + i] = message[i]; } }
9
public void setSource(boolean isSource) { this.isSource = isSource; }
0
public int genShader(int shaderType,String source) { int shader = 0; try { shader = GL20.glCreateShader(shaderType); if(shader == 0) return 0; GL20.glShaderSource(shader, source); GL20.glCompileShader(shader); if (GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) throw new RuntimeException("Error creating shader: "); Work = true; return shader; } catch(Exception exc) { System.err.println(GL20.glGetShaderInfoLog(shader,GL20.glGetShaderi(shader,GL20.GL_INFO_LOG_LENGTH))); System.err.println(source); GL20.glDeleteShader(shader); } return shader; }
3
void makeIgnoreList(File dir) throws IOException { excludeFiles.clear(); final File ignoreFilesFile = new File(dir, EXCLUDE_FILES_FILENAME); if (!ignoreFilesFile.exists()) { return; } try (BufferedReader is = new BufferedReader(new FileReader(ignoreFilesFile))) { String line; while ((line = is.readLine()) != null) { if (line.length() == 0 || line.startsWith("#")) { continue; } excludeFiles.add(line); } } }
4
Object[] choose(double P[], double D[][], double F[][], int Rank[], int n) { double sP[] = new double[P.length]; double sum = 0; int counter = 0; int Selected[] = new int[n]; double S1[][] = new double[n][D[0].length]; double F1[][] = new double[n][F[0].length]; int R1[] = new int[n]; for (int i = 0; i < P.length; i++) { sP[i] = (sum += P[i]); } while (counter < n) { double U; int R = -1; boolean multipleOccurrences = false; do { multipleOccurrences = false; // Draw random number U between 0 and 1 using a uniform distribution U = random(); //generator.nextDouble(); // Combine labelled U with trapezoidal probability for (int i = 0; i < P.length; i++) { if (U < sP[i]) { R = i; break; } } for (int i = 0; i < counter; i++) { if (Selected[i] == R) { multipleOccurrences = true; break; } } } while (multipleOccurrences == true); Selected[counter] = R; for (int j = 0; j < D[0].length; j++) { S1[counter][j] = D[R][j]; } for (int j = 0; j < F[0].length; j++) { F1[counter][j] = F[R][j]; } R1[counter] = Rank[R]; counter++; } return new Object[]{S1, F1, R1}; }
9
public static void main(String[] arg){ String s = arg[0].toUpperCase(); //public char charAt(int index), index of the character will be returned char grade = s.charAt(0); switch(grade){ case 'H': System.out.println("Your score is between 85-100."); break; case 'D': System.out.println("Your score is between 75-84."); break; case 'C': System.out.println("Your score is between 65-74."); break; case 'P': System.out.println("Your score is between 50-64."); break; case 'F': System.out.println("Your score is between 0-49."); break; default: break; } }
5
private void initializeSingleSource(Vertex start) { for (int i = 0; i < vertices.getSize(); i++) { vertices.get(i).setColor(VertexColor.WHITE); vertices.get(i).setDistance(Integer.MAX_VALUE); vertices.get(i).setPath(null); } int indexOfStart = vertices.indexOf(start); vertices.get(indexOfStart).setDistance(0); vertices.get(indexOfStart).setColor(VertexColor.GRAY); }
1
public static void main(String[] args) { String config = null; if (args.length != 0) { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-c".equals(arg) && args.length > i) { config = args[i+1]; } } } SQLRunner.setOkToExit(true); SQLRunnerGUI prog = new SQLRunnerGUI(new DefaultConfigurationManager()); if (config != null) { prog.setConfig(config); } }
5
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed //Botão salvar/adicionar Endereco e = new Endereco(); e.setEstado(txEstado.getText()); e.setCidade(txCidade.getText()); e.setBairro(txBairro.getText()); e.setRua(txRua.getText()); e.setComplemento(txComplemento.getText()); e.setNumero (Integer.parseInt(txNumero.getText())); e.setCodigo(codigoEndereco); EnderecoController ec = new EnderecoController(); e.setCodigo(ec.salvar(e)); Funcionario f = new Funcionario(); f.setEndereco(e); if (!(txCodigo.getText().equals("")) || (txCodigo.getText().equals(null))) { f.setCodigo(Integer.parseInt(txCodigo.getText())); } f.setNome(txNome.getText()); f.setIdade(Integer.parseInt(txIdade.getText())); if (rbFeminino.isSelected()) { f.setSexo("Feminino"); } else if (rbMasculino.isSelected()) { f.setSexo("Masculino"); } try { String data = txDataNascimento.getText(); f.setDataNascimento(new SimpleDateFormat("dd/MM/yyyy").parse(data)); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao converter a data: " + ex); } f.setRg(txRg.getText()); f.setCpf(txCpf.getText()); f.setTelefone(txTelefone.getText()); f.setCargo(txCargo.getText()); f.setSalario(Double.parseDouble(txSalario.getText())); f.setLogin(txLogin.getText()); f.setSenha(txSenha.getText()); FuncionarioController fc = new FuncionarioController(); if (f.getCodigo() == 0) { int id = fc.salvar(f); if (id > 0) { modelo.addRow(new Object[]{id, f.getNome(), f.getCpf(), f.getCargo()}); JOptionPane.showMessageDialog(null, "Usuário cadastrado com sucesso."); } } else { int id = fc.salvar(f); if (id > 0) { modelo.removeRow(linhaSelecionada); modelo.addRow(new Object[]{id, f.getNome(), f.getCpf(), f.getCargo()}); JOptionPane.showMessageDialog(null, "Usuário atualizado com sucesso."); } } dispose(); }//GEN-LAST:event_btSalvarActionPerformed
8
final private static String trimZeroes(String output) { String copyOfOutput = output; if (copyOfOutput.contains(".")) { while (copyOfOutput.substring(copyOfOutput.length() - 1, copyOfOutput.length()).equals("0")) { if (copyOfOutput.length() > 1) { copyOfOutput = copyOfOutput.substring(0, copyOfOutput.length() - 1); } else { break; } } if (copyOfOutput.substring(copyOfOutput.length() - 1, copyOfOutput.length()).equals(".")) { copyOfOutput = copyOfOutput.substring(0, copyOfOutput.length() - 1); } } return copyOfOutput; }
4
public static void checkIntParam(SessionRequestContent request, Criteria criteria, String reqName, String critName){ String param = (String) request.getParameter(reqName); if (param != null && !param.isEmpty()) { Integer currParam = Integer.decode(param); if (currParam > 0) { criteria.addParam(critName, currParam); } } }
3
public void majInformations() { if(_informations == null || _informations.isEmpty()) { _informations = new ArrayList<>(); _informations.add("Aucune information"); } JLabel label; JPanel panelGrid = new JPanel(new GridLayout(_informations.size(), 1)); boolean pair = true; for (String info : _informations) { label = new JLabel(info); label.setOpaque(true); if(pair = !pair) label.setBackground(COULEUR_PANEL1); else label.setBackground(COULEUR_PANEL2); label.setForeground(Color.white); panelGrid.add(label); } add(new JScrollPane(panelGrid), BorderLayout.CENTER); this.validate(); }
4
@Override public void handleHttpRequest(final HttpRequest request, final HttpResponse response, final HttpControl control) throws Exception { String authHeader = request.header("Authorization"); if (authHeader == null) { needAuthentication(response); } else { if (authHeader.startsWith(BASIC_PREFIX)) { String decoded = new String(Base64.decode(authHeader.substring(BASIC_PREFIX.length()))); final String[] pair = decoded.split(":", 2); if (pair.length == 2) { final String username = pair[0]; final String password = pair[1]; PasswordAuthenticator.ResultCallback callback = new PasswordAuthenticator.ResultCallback() { @Override public void success() { request.data(USERNAME, username); control.nextHandler(); } @Override public void failure() { needAuthentication(response); } }; authenticator.authenticate(request, username, password, callback, control); } else { needAuthentication(response); } } } }
3
public List<User> divideFirstUser(List<User> userList, int index) { List finalList = new ArrayList(); for (int i = 0; i < userList.size(); i++) { User user = (User) userList.get(i); List firstUserList = null; if (i == index) { firstUserList = new ArrayList(); } List postList = user.getUserPost(); List toAddPostList = new ArrayList(); for (int j = 0; j < postList.size(); j++) { if (j % 2 == 0 && i == index) { firstUserList.add((Posts) postList.get(j)); } else if (j % 2 != 0) { toAddPostList.add((Posts) postList.get(j)); } } if (i == 0) { User firstUser = new User(); firstUser.setType(UserType.A); firstUser.setId(user.getId()); firstUser.setUserPost(firstUserList); finalList.add(0, firstUser); } User users = new User(); users.setType(UserType.B); users.setId(user.getId()); users.setUserPost(toAddPostList); finalList.add(users); } return finalList; }
7
@Override public void run() { BmTestManager bmTestManager = BmTestManager.getInstance(); FileServer fileServer = FileServer.getFileServer(); String projectPath = null; if (fileServer.getScriptName() != null) { projectPath = fileServer.getBaseDir() + "/" + fileServer.getScriptName(); } else if (!JMeter.isNonGUI()) { projectPath = GuiPackage.getInstance().getTestPlanFile(); } try { String filename = new File(projectPath).getName(); BlazemeterApi.getInstance().uploadJmx(bmTestManager.getUserKey(), bmTestManager.getTestInfo().getId(), filename, projectPath); } catch (NullPointerException npe) { BmLog.error("JMX was not uploaded to server: test-plan is needed to be saved first "); } catch (Exception ex) { BmLog.error(ex); } }
4
private void initialize(JComponent component) { component.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { notifyInputAction("Keyboard_Any_Down", new AlertObject(e.getWhen())); String keyName = KeyboardMappings.getKeyName(e.getKeyCode()); ButtonState downKey = new ButtonState(DEVICE, keyName, e.getWhen(), inDev); notifyInputAction(downKey.getFullName() + "_KeyDown", new AlertObject(e.getWhen())); //Legacy Support if (!myDownKeys.contains(downKey)){ if(myDownKeys.size() > 1) { recursiveCombination(myDownKeys, e.getWhen(), downKey); } myDownKeys.add(downKey); } else notifyInputAction(downKey.getFullName() + "_LongPress",new AlertObject(e.getWhen())); ArrayList<ButtonState> buttonArray = (ArrayList<ButtonState>) myDownKeys.clone(); if(buttonArray.size() > 1) recursivePermutation("", buttonArray, buttonArray.size(), e.getWhen()); } @Override public void keyReleased(KeyEvent e) { notifyInputAction("Keyboard_Any_Up", new AlertObject(e.getWhen())); String keyName = KeyboardMappings.getKeyName(e.getKeyCode()); ButtonState temp = new ButtonState(DEVICE, keyName, e.getWhen(), inDev); int keyIndex; if( (keyIndex = myDownKeys.indexOf(temp)) != -1 ) { long timeDifference = temp.getTime() - myDownKeys.remove(keyIndex).getTime(); notifyInputAction(temp.getFullName() + "_Up", new AlertObject(e.getWhen())); notifyInputAction(temp.getFullName() + "_KeyUp", new AlertObject(e.getWhen())); //Legacy Support if (timeDifference < Integer.parseInt(myInput.getSetting("ShortClickTimeThreshold")) ) { notifyInputAction(temp.getFullName() + "_ShortClick", new AlertObject(e.getWhen())); } if (timeDifference >= Integer.parseInt(myInput.getSetting("LongClickTimeThreshold"))) { notifyInputAction(temp.getFullName() + "_LongClick", new AlertObject(e.getWhen())); } if (lastClickKey.equals(keyName) && e.getWhen() - lastClickTime < Integer.parseInt(myInput.getSetting("DoubleClickTimeThreshold"))) { notifyInputAction(temp.getFullName() + "_DoubleClick", new AlertObject(e.getWhen())); } lastClickTime = e.getWhen(); lastClickKey = keyName; } } @Override public void keyTyped(KeyEvent e) { } }); }
8
public VirtualDateNode(Property property, PropertyTree parent) { super(property, parent); }
0
private void notifyOverseers(String key, OperatorCommand opcmd) { //get list of players PluginManager pm = plugin.getServer().getPluginManager(); Set<Permissible> notifiedPlayers = new HashSet<Permissible>(); Set<Permissible> approvers = pm.getPermissionSubscriptions("SudoOp.Approve"); Set<Permissible> deniers = pm.getPermissionSubscriptions("SudoOp.Deny"); notifiedPlayers.addAll(approvers); notifiedPlayers.addAll(deniers); //add command sending player notifiedPlayers.add(opcmd.getSender()); int numPlayersNotified = 0; for(Permissible p: notifiedPlayers){ if(p instanceof CommandSender){ CommandSender s = (CommandSender) p; if (!(s.equals(opcmd.getSender()))) { numPlayersNotified++; String message = opcmd.getSender().getName() + " wants to use: " +"\n\"/" + opcmd.getCommand()+"\""; if (s.hasPermission("SudoOp.Approve")) message = message + "\n" + "Send \"/SudoApprove " + opcmd.getSender().getName()+ " " + key + "\" to approve."; if (s.hasPermission("SudoOp.Deny")) message = message + "\n" + "Send \"/SudoDeny " + opcmd.getSender().getName() + " " + key + "\" to deny."; s.sendMessage(message); }else if(s.hasPermission("SudoOp.Cancel")){ String message = "Command requested: "+opcmd.getCommand() +"\nSend \"/SudoCancel "+key+"\" to cancel."; s.sendMessage(message); } } } if(numPlayersNotified == 0) opcmd.getSender().sendMessage("No one is available right now to approve your request," + "\nit will remain open for 5 minutes."); }
7
private void initBackgroundMenu(Color bg) { this.backgroundMenu = new JPanel(); this.backgroundMenu.setBackground(bg); this.backgroundMenu.setLayout(new VerticalLayout(5, VerticalLayout.LEFT)); // image Path initialValue = this.skin.getBackground(); ImageField imgField = new ImageField(initialValue, bg, strImgFieldTitle, false) { private final long serialVersionUID = 1L; @Override public void onFileChosen(File file) { try { if (file != null) { GeneralChangesMenu.this.skin.setBackground(file.toPath()); updatePathField(GeneralChangesMenu.this.skin.getBackground(), false); } else { GeneralChangesMenu.this.skin.setBackground(null); updatePathField(GeneralChangesMenu.this.skin.getBackground(), true); } } catch (IOException e) { Main.showProblemMessage(e.getMessage()); } } }; imgField.setImageFileFilter(Constants.DEFAULT_BACKGROUND_TYPE); this.backgroundMenu.add(imgField); }
2
@Override public boolean parseArg(String[] values) { int w = Integer.parseInt(values[0]); int h = Integer.parseInt(values[1]); if(w>0 && h>0) { Properties.Client.WINDOW_WIDTH = w; Properties.Client.WINDOW_HEIGHT = h; return true; } return false; }
2
private String getName(final ZipEntry ze) { String name = ze.getName(); if (isClassEntry(ze)) { if (inRepresentation != BYTECODE && outRepresentation == BYTECODE) { name = name.substring(0, name.length() - 4); // .class.xml to // .class } else if (inRepresentation == BYTECODE && outRepresentation != BYTECODE) { name += ".xml"; // .class to .class.xml } // } else if( CODE2ASM.equals( command)) { // name = name.substring( 0, name.length()-6).concat( ".asm"); } return name; }
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already snatching the wind.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> chant(s) for <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("The wind snatcher surrounds <S-NAME>.")); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) for the wind snatcher, but nothing happens.")); // return whether it worked return success; }
8
void setBlock(int x, int y, int z, byte[][] chunk, Material material) { if (chunk[y >> 4] == null) chunk[y >> 4] = new byte[16 * 16 * 16]; if (!(y <= 256 && y >= 0 && x <= 16 && x >= 0 && z <= 16 && z >= 0)) return; try { chunk[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = (byte) material.getId(); } catch (Exception e) { // do nothing } }
8
public static void MakeFramesVisible(Boolean state) { for(int i =0;i<callFrameList.size();i++) callFrameList.get(i).setVisible(state); }
1
private void sampleTopics(InstanceList docs, boolean init) { // resample topics int ndMax = -1; int[] wordCounts = (init) ? new int[W] : null; for (int d=0; d<D; d++) { FeatureSequence fs = (FeatureSequence) docs.get(d).getData(); int nd = fs.getLength(); if (init) { z[d] = new int[nd]; if (nd > ndMax) ndMax = nd; } for (int i=0; i<nd; i++) { int w = fs.getIndexAtPosition(i); int oldTopic = z[d][i]; if (!init) { wordScore.decrementCounts(w, oldTopic, !init); topicScore.decrementCounts(oldTopic, d); } // build a distribution over topics double dist[] = new double[T]; double distSum = 0.0; for (int j=0; j<T; j++) { double score = getScore(w, j, d); dist[j] = score; distSum += score; } int newTopic = rng.nextDiscrete(dist, distSum); z[d][i] = newTopic; wordScore.incrementCounts(w, newTopic, !init); topicScore.incrementCounts(newTopic, d); if (init) wordCounts[w]++; } } if (init) { wordScore.initializeHists(wordCounts); topicScore.initializeHists(ndMax); } }
9
private static boolean isWindowInScreenBounds(Point location, Point size) { Point myLocation = new Point(location); if (!isLocationInScreenBounds(myLocation)) { return false; } myLocation.translate(size.x - 1, 0); if (!isLocationInScreenBounds(myLocation)) { return false; } myLocation.translate(0, size.y - 1); if (!isLocationInScreenBounds(myLocation)) { return false; } myLocation.translate(-(size.x - 1), 0); if (!isLocationInScreenBounds(myLocation)) { return false; } return true; }
4
public void mainFlow() throws IOException { StringBuilder headersb = new StringBuilder(); headerWrite(Mode.Co, nameArray, headersb); resp.getWriter().println( "<!-- mainflow_start: " + (System.currentTimeMillis() - time) + "-->"); // 出力キャッシュが揃っていなければメインの処理をする if (flush == null || sideCount == null || flush.isEmpty()) { StringBuilder sb1 = new StringBuilder(); // 出力優先度の高いStringBuilder StringBuilder sb2 = new StringBuilder(); // 出力優先度の低いStringBuilder /* メインの処理ここから */ Record rc = new Record(); record[1] = rc.getRecord(nameArray[1], shift, force); if (nameArray[2].isEmpty()) { setContent(); /* シングル処理 */ singleOut(sb1, sb2); sideCount = record[1][0].length; /* シングル処理終了 */ } else { /* ダブル処理 */ record[2] = rc.getRecord(nameArray[2], shift, force); setContent(); doubleSearch(sb1, sb2); resp.getWriter().println( "<!-- doubleend: " + ((System.currentTimeMillis() - time) * -1) + "-->"); if (!ipFlag && (maxCount[0] != 0 || maxCount[1] != 0)) // 検索結果が1件以上あれば検索履歴に書き込む new Past().putPastAndRank(nameArray, maxCount, sb1); resp.getWriter().println( "<!-- putpastend: " + ((System.currentTimeMillis() - time) * -1) + "-->"); sideCount = maxCount[0] + maxCount[1]; /* ダブル処理終了 */ } /* シングル・ダブル共通処理 */ flush = new String(sb1) + new String(sb2); cache.put(nameArray[1] + "," + nameArray[2], flush); cache.put(nameArray[1] + "," + nameArray[2] + ",count", sideCount); /* 共通処理終了 */ } StringBuilder sb0 = new StringBuilder(); // sideOutput用 new Past().sideOutput(sb0, sideCount, nameArray); // サイドメニューはキャッシュに含めないので逐次書き出す resp.getWriter().println( "<!-- sideoutend: " + ((System.currentTimeMillis() - time) * -1) + "-->"); resp.getWriter() .println(new String(headersb) + flush + new String(sb0)); }
7
private static boolean test6_1() throws FileNotFoundException { String input = "new\n" + "pick up key\n" + "lock cell door\n" + "lock cell door with key\n" + "open door\n" + "open cell door\n" + "go through door\n" + "unlock cell door\n" + "wait\n" + "unlock cell door with key\n" + "open door\n" + "go through cell door\n" + "quit\n" + "yes\n"; HashMap<Integer, String> output = new HashMap<Integer, String>(); boolean passed = true; try { in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); out = new PrintStream("testing.txt"); System.setOut(out); Game.main(null); } catch (ExitException se) { } catch (Exception e) { System.setOut(stdout); System.out.println("Error: "); e.printStackTrace(); passed = false; } finally { System.setOut(stdout); @SuppressWarnings("resource") Scanner sc = new Scanner(new File("testing.txt")); ArrayList<String> testOutput = new ArrayList<String>(); while (sc.hasNextLine()) { testOutput.add(sc.nextLine()); } output.put(testOutput.size() - 36, ">> You need to use a key to lock this cell door."); output.put(testOutput.size() - 34, ">> You lock the cell door."); output.put(testOutput.size() - 32, ">> The door is locked."); output.put(testOutput.size() - 30, ">> The door is locked."); output.put(testOutput.size() - 28, ">> The cell door is locked."); output.put(testOutput.size() - 26, ">> You need to use a key to unlock the cell door."); output.put(testOutput.size() - 22, ">> You unlock the cell door."); output.put(testOutput.size() - 20, ">> The door swings open."); output.put(testOutput.size() - 18, ">> You walk through the cell door."); output.put( testOutput.size() - 17, "A lone torch flickers next to you, and the hallway stretches off to darkness to the north and south."); output.put(testOutput.size() - 16, "In the wall next to you is a cell door."); if (passed) { for (Map.Entry<Integer, String> entry : output.entrySet()) { if (!testOutput.get(entry.getKey()) .equals(entry.getValue())) { passed = false; System.out.println("test6 failed: Line " + entry.getKey()); System.out.println("\tExpected: " + entry.getValue()); System.out.println("\tReceived: " + testOutput.get(entry.getKey())); } } if (passed) { return true; } } else { System.out.println("test6 failed: error"); } } return false; }
7
final int[][] method3047(int i, int i_0_) { anInt9141++; int[][] is = ((Class348_Sub40) this).aClass322_7033.method2557(-119, i); if (((Class322) ((Class348_Sub40) this).aClass322_7033).aBoolean4035) { int[][] is_1_ = this.method3039((byte) 120, (aBoolean9147 ? -i + Class299_Sub2.anInt6325 : i), 0); int[] is_2_ = is_1_[0]; int[] is_3_ = is_1_[1]; int[] is_4_ = is_1_[2]; int[] is_5_ = is[0]; int[] is_6_ = is[1]; int[] is_7_ = is[2]; if (aBoolean9140) { for (int i_8_ = 0; i_8_ < Class348_Sub40_Sub6.anInt9139; i_8_++) { is_5_[i_8_] = is_2_[Class239_Sub22.anInt6076 + -i_8_]; is_6_[i_8_] = is_3_[Class239_Sub22.anInt6076 - i_8_]; is_7_[i_8_] = is_4_[-i_8_ + Class239_Sub22.anInt6076]; } } else { for (int i_9_ = 0; ((Class348_Sub40_Sub6.anInt9139 ^ 0xffffffff) < (i_9_ ^ 0xffffffff)); i_9_++) { is_5_[i_9_] = is_2_[i_9_]; is_6_[i_9_] = is_3_[i_9_]; is_7_[i_9_] = is_4_[i_9_]; } } } if (i_0_ != -1564599039) method3065(-40, true, 93); return is; }
6
public List<String> fullJustify(String[] words, int L) { List<String> list = new ArrayList<String>(); int sta=0; int length =0; for(int i=0 ; i < words.length && words[i] != "";i++){ length += words[i].length() + 1; // System.out.println(length); if(length-1 >L ){ line(Arrays.copyOfRange(words, sta, i),length-2 - words[i].length(),L ,list); sta = i; i--; length =0; } } if(sta < words.length){ String str =""; length = 0; for(int i=sta; i< words.length && words[i] != "";i++){ str += words[i] + " "; length += words[i].length()+1; } for(int i=0; i< L - length;i++) str += " "; list.add(str.substring(0,L)); } return list; }
7
private Color getValueAsColor(String value, Color defaultColor) { try { if(value.startsWith("#")) { return Color.decode(value.substring(1)); } else { Field f = Color.class.getField(value); return (Color) f.get(null); } } catch (Exception e) { e.printStackTrace(); } return defaultColor; }
2
private Component[] getChildren(Container target, boolean useMinimumSize) { ArrayList<Component> children = new ArrayList<>(); for (Component child : target.getComponents()) { PrecisionLayoutData data = mConstraints.get(child); if (!data.shouldExclude()) { children.add(child); data.computeSize(child, DEFAULT, DEFAULT, useMinimumSize); } } return children.toArray(new Component[children.size()]); }
2
public JSONObject updateRANKTag(int USER_ID,int QUESTION_ID,int ANSWER_ID, int RANK, int increased) { try { Class.forName(JDBC_DRIVER); conn=DriverManager.getConnection(DB_URL,USER,PASS); stmt=conn.createStatement(); json=new JSONObject(); String SQL="update ANSWERS set RANK ='"+RANK+"'where ANSWER_ID='"+ANSWER_ID+"'"; //int result=stmt.executeUpdate(SQL); LocationBasedHandler object=new LocationBasedHandler(); object.A_Vote(ANSWER_ID+"",USER_ID+"", increased); object=null; //if(result>0) //{ json.put(SUCCESS, 1); json.put(MESSAGE, "Insertion Successful"); SQL="Select * from ANSWERS where QUESTION_ID="+QUESTION_ID; rs=stmt.executeQuery(SQL); if(rs.isBeforeFirst()) { JSONArray Answers=new JSONArray(); JSONObject answer; while(rs.next()) { answer=new JSONObject(); answer.put("ANSWER", rs.getString("ANSWER")); answer.put("ANSWER_ID", rs.getString("ANSWER_ID")); answer.put("RANK", rs.getInt("RANK")); Answers.add(answer); } json.put("ANSWERS", Answers); } //} rs.close(); stmt.close(); //Calling Mahesh Method Parser parseobject=new Parser(); parseobject.modifyRank(increased, ANSWER_ID, USER_ID, Constants.PATH); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } //json.put(SUCCESS, 0); //json.put(MESSAGE, "Sorry, couldn't Process Request"); return(json); }
6
private int getClickedRoom(int cursorX, int cursorY){ for(Room room : this.map.getRooms()){ if (cursorX > room.getPositionX() && cursorX < room.getPositionX() + room.getWidth() && cursorY > room.getPositionY() && cursorY < room.getPositionY() + room.getHeight()){ return map.getRooms().indexOf(room); } } return -1; }
5
private void stop() { if (server == null) return; readyToGo = false; if (taskID != -1) server.getScheduler().cancelTask(taskID); server = null; // go ahead and unload any chunks we still have loaded while(!storedChunks.isEmpty()) { CoordXZ coord = storedChunks.remove(0); if (!originalChunks.contains(coord)) world.unloadChunkRequest(coord.x, coord.z); } }
4
public void setPosicionJugador2(int x,int y){ if(x>=0&&x<8&&y<8&&y>0){ switch (pd.mapa_jugador2[x][y]) { case "SM": case "PA": case "AZ": System.out.print("POSICION OCUPADA"); System.out.println("OTRA CORDENADA"); System.out.println("cordenada en x"); x=sc.nextInt(); System.out.println("coordenada en y "); setPosicionJugador1(x, y); case "": pd.mapa_jugador2[x][y]=codigo; break; } } System.out.println("Las coordenadas estan fuera de limite"); }
8
private static void shade(short[] imageColorArray, int[] imageShadeArray) { int i = 512; int j = 512; int k = 0; for (int m = 0; m < j; m++) { for (int n = 0; n < i; k++) { if (imageShadeArray[k] != 0) { float f1; if (n == 0) { f1 = imageColorArray[(k + 1)] - imageColorArray[k]; } else if (n == i - 1) { f1 = imageColorArray[k] - imageColorArray[(k - 1)]; } else { f1 = (imageColorArray[(k + 1)] - imageColorArray[(k - 1)]) * 2; } float f2; if (m == 0) { f2 = imageColorArray[(k + i)] - imageColorArray[k]; } else if (m == j - 1) { f2 = imageColorArray[k] - imageColorArray[(k - i)]; } else { f2 = (imageColorArray[(k + i)] - imageColorArray[(k - i)]) * 2; } float f3 = f1 + f2; if (f3 > 10.0F) { f3 = 10.0F; } if (f3 < -10.0F) { f3 = -10.0F; } f3 = (float) (f3 + (imageColorArray[k] - 64) / 7.0D); imageShadeArray[k] = Color.shade(imageShadeArray[k], (int) (f3 * 8.0F)); } n++; } } }
9
public void collisionWall() { if(snake.isSnakeUp()) { if(snake.getSnakeY()<20) { finishGame(); }else{ snake.setSnakeY(snake.getSnakeY() - 15); } }else if(snake.isSnakeDown()) { if(snake.getSnakeY()>335) { finishGame(); }else { snake.setSnakeY(snake.getSnakeY() + 15); } }else if(snake.isSnakeLeft()) { if(snake.getSnakeX()<20) { finishGame(); }else { snake.setSnakeX(snake.getSnakeX() - 15); } }else if(snake.isSnakeRight()) { if(snake.getSnakeX()>370) { finishGame(); }else { snake.setSnakeX(snake.getSnakeX() + 15); } } }
8
public int getTileSize() { return tileSize; }
0
public LinkedList<Kokus> initialisationPaquetKokus(){ LinkedList<Kokus> llk = new LinkedList<Kokus>(); for(Kokus k : this.hashKokus){ // 12 cartes kokus de 1 unité if(k.getNbkoku()==1){ for(int i=0; i<12; i++){ llk.add(k); } } // 8 cartes kokus de 2 unités if(k.getNbkoku()==2){ for(int i=0; i<8; i++){ llk.add(k); } } // 4 cartes kokus de 3 unités if(k.getNbkoku()==3){ for(int i=0; i<4; i++){ llk.add(k); } } } Collections.shuffle(llk); return llk; }
7
public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner s = new Scanner(System.in); double salary = s.nextDouble(); double newSalary = 0; double earned = 0; int percentage = 0; if(salary >= 0 && salary <= 400){ percentage = 15; }else if(salary > 400 && salary <= 800){ percentage = 12; }else if(salary > 800 && salary <= 1200){ percentage = 10; }else if(salary > 1200 && salary <= 2000){ percentage = 7; }else if(salary > 2000){ percentage = 4; } newSalary = salary * (1.0 + percentage/100.0); earned = newSalary - salary; System.out.printf("Novo salario: %.2f\n", newSalary); System.out.printf("Reajuste ganho: %.2f\n", earned); System.out.printf("Em percentual: %d %%\n", percentage); }
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (hashCode() == o.hashCode()) return true; Comet comet = (Comet) o; if (tailColor != comet.tailColor) return false; if (mineralResources != null ? !mineralResources.equals(comet.mineralResources) : comet.mineralResources != null) return false; return true; }
7
private void myListMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_myListMousePressed // TODO add your handling code here: if( evt.getButton() == MouseEvent.BUTTON2 ) { myList.clearSelection(); Rectangle r = myList.getCellBounds( 0, usernames.size()-1 ); if( r!=null && r.contains(evt.getPoint()) ) { int index = myList.locationToIndex(evt.getPoint()); myList.setSelectedIndex(index); }; } }//GEN-LAST:event_myListMousePressed
3
public void addFrame(Frame frame) { if (frame == null) { System.err.println("oh no! frame is null"); } String[] idRefParts; for (FrameElement fe : frame.getFrameElements()) { for (String feID : fe.getIdrefs()) { idRefParts = feID.split(":"); if (!containsNode(idRefParts[0])) return; } } for (String targetID : frame.getTargetIDs()) { if (!containsNode(targetID)) return; } getFrames().add(frame); }
6
public static BufferedImage makeColorTransparent(BufferedImage ref, Color color) { BufferedImage dimg = new BufferedImage(ref.getWidth(), ref.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = dimg.createGraphics(); g.setComposite(AlphaComposite.Src); g.drawImage(ref, null, 0, 0); g.dispose(); for (int i = 0; i < dimg.getHeight(); i++) { for (int j = 0; j < dimg.getWidth(); j++) { if (dimg.getRGB(j, i) == color.getRGB()) { dimg.setRGB(j, i, 0x8F1C1C); } } } return dimg; }
3
public AnnotationVisitor visitParameterAnnotation( final int parameter, final String desc, final boolean visible) { buf.setLength(0); buf.append(tab2).append('@'); appendDescriptor(FIELD_DESCRIPTOR, desc); buf.append('('); text.add(buf.toString()); TraceAnnotationVisitor tav = createTraceAnnotationVisitor(); text.add(tav.getText()); text.add(visible ? ") // parameter " : ") // invisible, parameter "); text.add(new Integer(parameter)); text.add("\n"); if (mv != null) { tav.av = mv.visitParameterAnnotation(parameter, desc, visible); } return tav; }
2
@Override public void updateView() { Model model = controller.getModel(); Object col[] = new Object[3]; movieHash.clear(); int c = tModel.getRowCount(); for (int i = c - 1; i >= 0; i--) { tModel.removeRow(i); movieTable.revalidate(); } if (model.getMovies().getMovieList().isEmpty()) { System.out.println("movie list is empty"); col[0] = ""; col[1] = ""; col[2] = ""; tModel.addRow(col); } for (Movie m : model.getMovies().getMovieList()) { col[0] = m.getTitle(); col[1] = m.getFormat(); col[2] = m.getSize(); movieHash.put(m.getTitle(), m); tModel.addRow(col); } movieTable.setModel(tModel); movieTable.getColumnModel().getColumn(0).setPreferredWidth(400); movieTable.getColumnModel().getColumn(1).setPreferredWidth(60); }
3
@SuppressWarnings({"unchecked","rawtypes"}) public Object copyTransferrableProperties(AdministeredComponent target, AdministeredComponent source) { try { Iterator<String> propertyIterator = PropertyUtils.describe( target ).keySet().iterator(); Map sourceValuesMap = PropertyUtils.describe( source ); while ( propertyIterator.hasNext() ) { String property = propertyIterator.next(); Object value = sourceValuesMap.get( property ); if ( PropertyUtils.isWriteable( target, property ) && Hibernate.isInitialized( value ) && !(isCADSREntity( value )) && !(value instanceof Collection)) { PropertyUtils.setProperty( target, property, value ); } } return target; } catch (Exception ex){ log.error( "Error while copying properties: "+ ex.getMessage() ); } return target; }
6
private boolean processInternCommand(MapleClient c, MessageCallback mc, String[] splitted) { DefinitionInternCommandPair definitionCommandPair = interncommands.get(splitted[0]); if (definitionCommandPair != null) { try { definitionCommandPair.getCommand().execute(c, mc, splitted); } catch (IllegalCommandSyntaxException ex) { mc.dropMessage(ex.getMessage()); dropHelpForInternDefinition(mc, definitionCommandPair.getDefinition()); } catch (NumberFormatException nfe) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForInternDefinition(mc, definitionCommandPair.getDefinition()); } catch (ArrayIndexOutOfBoundsException ex) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForInternDefinition(mc, definitionCommandPair.getDefinition()); } catch (NullPointerException exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } catch (Exception exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } return true; } else { processDonatorCommand(c, mc, splitted); } return true; }
6
private void tablaUsuariosDelSistemaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaUsuariosDelSistemaMouseClicked // TODO add your handling code here: String opcionHabilitar = "Habilitar"; String nombreUsuario = String.valueOf(tablaUsuariosDelSistema.getValueAt(tablaUsuariosDelSistema.getSelectedRow(), 0)); String estado = String.valueOf(tablaUsuariosDelSistema.getValueAt(tablaUsuariosDelSistema.getSelectedRow(), 2)); if (estado.equals("Habilitado")) { opcionHabilitar = "Deshabilitar"; } Object[] opciones = {"Cancelar", "Editar", opcionHabilitar}; final ControladorUsuarios controladorUsuarios = new ControladorUsuarios(); final Usuarios usuarioSelecionado = controladorUsuarios.obtenerUsuario(nombreUsuario); if (nombreUsuario.equals("admin") || nombreUsuario.equals(JTextFieldnombreDeUsuario.getText())) { JOptionPane.showMessageDialog(this, "No se puede editarse a si mismo o el usuario administrador del sistema", "Mensaje del sistema", JOptionPane.WARNING_MESSAGE); } else { int opcionElegida = JOptionPane.showOptionDialog(this, "Por favor elija una opción", "Editar cliente", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, null); switch (opcionElegida) { case 1: final JDialog dialogoEditar = new JDialog(this); dialogoEditar.setTitle("Editar usuario"); dialogoEditar.setSize(400, 310); dialogoEditar.setResizable(false); JPanel panelDialogo = new JPanel(); panelDialogo.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; JLabel editarTextoPrincipalDialogo = new JLabel("Editar clientes"); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.insets = new Insets(15, 10, 40, 0); c.ipadx = 0; Font textoGrande = new Font("Arial", 1, 18); editarTextoPrincipalDialogo.setFont(textoGrande); panelDialogo.add(editarTextoPrincipalDialogo, c); c.insets = new Insets(0, 5, 10, 0); c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.ipadx = 0; JLabel editarNombreClienteDialogo = new JLabel("Login:"); panelDialogo.add(editarNombreClienteDialogo, c); final JTextField valorEditarNombreClienteDialogo = new JTextField(); c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); valorEditarNombreClienteDialogo.setText(usuarioSelecionado.getLogin()); panelDialogo.add(valorEditarNombreClienteDialogo, c); c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); JLabel editarPasswordClienteDialogo = new JLabel("Contraseña:"); panelDialogo.add(editarPasswordClienteDialogo, c); final JTextField valoreditarPasswordClienteDialogo = new JTextField(); c.gridx = 1; c.gridy = 2; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); panelDialogo.add(valoreditarPasswordClienteDialogo, c); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.ipadx = 0; c.insets = new Insets(0, 5, 10, 0); JLabel mensajeEditarPassword = new JLabel("Si no desea editar la contraseña deje este espacio en blanco:"); panelDialogo.add(mensajeEditarPassword, c); c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.ipadx = 0; c.insets = new Insets(0, 15, 10, 15); JButton botonGuardarClienteDialogo = new JButton("Guardar"); panelDialogo.add(botonGuardarClienteDialogo, c); c.gridx = 1; c.gridy = 4; c.gridwidth = 1; c.insets = new Insets(0, 15, 10, 15); c.ipadx = 0; JButton botonCerrarClienteDialogo = new JButton("Cancelar"); panelDialogo.add(botonCerrarClienteDialogo, c); botonCerrarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialogoEditar.dispose(); } }); botonGuardarClienteDialogo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String nombreUsuario = valorEditarNombreClienteDialogo.getText(); usuarioSelecionado.setLogin(nombreUsuario); if (!valoreditarPasswordClienteDialogo.getText().equals("")) { usuarioSelecionado.setPassword(valoreditarPasswordClienteDialogo.getText()); } controladorUsuarios.modificarUsuario(usuarioSelecionado.getUser_id(), usuarioSelecionado.getLogin(), usuarioSelecionado.getPassword()); JOptionPane.showMessageDialog(dialogoEditar, "Se ha modificado el usuario con éxito", "Mensaje del sistema", JOptionPane.INFORMATION_MESSAGE); generarTablaUsuarios(); dialogoEditar.dispose(); } }); dialogoEditar.add(panelDialogo); dialogoEditar.setVisible(true); break; case 2: if (estado.equals("Habilitado")) { usuarioSelecionado.setStatus('i'); } else { usuarioSelecionado.setStatus('e'); } controladorUsuarios.modificarEstadoUsuario(usuarioSelecionado); JOptionPane.showMessageDialog(this, "Se ha cambiado el estado del usuario", "Mensaje del sistema", JOptionPane.INFORMATION_MESSAGE); generarTablaUsuarios(); break; default: break; } } // TODO add your handling code here: }
7
public void setjButtonPrevious(JButton jButtonPrevious) { this.jButtonPrevious = jButtonPrevious; }
0
@Override public void atualizarAVItem(AvaliacaoItem avItem, int idUser, String refeicao, String data, String item) { if(avItem.getData() != null){ if( avItens.get(avItem.getDataFormatoAmericano()+avItem.getRefeicao()+avItem.getItem()) != null){ List<AvaliacaoItem> avaliacoes = avItens.get(avItem.getDataFormatoAmericano()+avItem.getRefeicao()+avItem.getItem()); for( AvaliacaoItem avI : avaliacoes){ if(avI.getData().equals(data) && avI.getIdUsuario() == idUser && avI.getRefeicao().equals(refeicao) && avI.getItem().equals(item)){ avI = avItem; break; } } } } }
7
public String getStringToPop() { return myStringToPop; }
0
public void setComments(String comments) { this.comments = comments; }
0
public static void main(String[] args) { // Working with Strings System.out.println("String letter 10 11 12 $%<!"); // Working with Intergers System.out.println(50); System.out.println(30000); System.out.println(5 + 5 - 2 * 4 / 2); // Working with Doubles System.out.println(1.2); System.out.println(1.75); System.out.println(2.5 + 1.2); System.out.println(7.5E3); }
0
public void checkExit(final int status) { if (!allowExit) { System.err.println("exit " + status); throw new SecurityException("Tried to exit (status=" + status + ")"); } }
1
public static void test() throws Exception { // ######################################################################################### System.out.println("Testing packet serialization:"); /** * Foreach packet class, create an instance, serialize it and * unserialize it. Packet class and a random sequence number must be * correct in addition to some specific data */ int i = 0; while (true) { // Packet send Packet packetSend = Packet.getPacketById((byte) i); if (packetSend == null) { break; } // Fill package packetSend.setSequenceNumber((int) (Math.random() * 100)); packetSend.setSender((Inet4Address)InetAddress.getByName("128.128.128.128")); // Packet specific data if (packetSend instanceof KeepAlivePacket) { ((KeepAlivePacket) packetSend).setData(KeepAlivePacket.PONG); } else if (packetSend instanceof DataPacket) { byte[] b = { 0, 1, 2, 3, 4, 5, 0, 42 }; ((DataPacket) packetSend).setData(b); } /* Can be ignored: packetSend instanceof CTSPacket */ else if (packetSend instanceof RTSPacket) { ((RTSPacket) packetSend).setAddress((Inet4Address)InetAddress.getByName("localhost")); ((RTSPacket) packetSend).setSizeToSend(32); } else if (packetSend instanceof ConfigPacket) { ((ConfigPacket) packetSend).setKey(ConfigPacket.Setting.FIX_LAMBDA); ((ConfigPacket) packetSend).setValue(ConfigPacket.FALSE); } else if (packetSend instanceof StatsPacket) { ((StatsPacket) packetSend).setLambda(64); ((StatsPacket) packetSend).setQueueSize(32); } // serialization byte[] b = packetSend.serialize(); // dump packet System.out.println("Packet " + packetSend.getClass() + ": " + bytesToHex(b)); // Packet receive Packet packetReceive = Packet.getPacket(b); // Test if received packet equals send packet if (b.equals(packetReceive.serialize())) { throw new Exception("ERROR: Packet received: " + bytesToHex(packetReceive.serialize())); } i++; } // ######################################################################################### }
8