text
stringlengths
14
410k
label
int32
0
9
public void setInitialResizePoint(Point initialResizePoint) { this.initialResizePoint = initialResizePoint; }
0
private ArrayList<String> createPrintables() { ArrayList<String> printables = new ArrayList<String>(); // Title printables.add("Graph: " + numNodes + " nodes"); String separationLine = ""; for (int i = 0; i <= 2 * numNodes; i++) separationLine += "-"; printables.add(separationLine); // Matrix for (int i = 1; i <= numNodes; i++) { String line = "["; for (int j = 1; j <= numNodes; j++) { if (j != numNodes) { String result = (buttons[i][j].isSelected()) ? "1" : "0"; line += result + ","; } else { String result = (buttons[i][j].isSelected()) ? "1" : "0"; line += result + "]"; } } printables.add(line); } printables.add(separationLine); // auto printables.add("Automorphism: " + pairSize + "x" + numPairs); printables.add(separationLine); for (int i = 1; i <= numPairs; i++) { String line = "["; for (int j = 1; j <= pairSize; j++) { if (j != pairSize) line += auts[i][j].getText() + ","; else line += auts[i][j].getText() + "]"; } printables.add(line); } printables.add(separationLine); return printables; }
9
private void deviceListComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_deviceListComboBoxItemStateChanged //this gets triggered whenever the list of items is changed, like when refreshing //don't do anything then if (!refreshing && evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) { setDevice(); } }//GEN-LAST:event_deviceListComboBoxItemStateChanged
2
private boolean isTrueSNP(VariantCandidate v) { if (v.val("max.qual.minor") >= 58.341 && v.val("max.qual.major") >= 46.184 && v.val("total.depth") < 47.256) { return true; } else if(v.val("max.qual.minor") <= 58.933 || v.val("max.qual.major") < 48.921 || v.val("total.depth") >= 63.330) { return false; } else { return false; } }
6
@SuppressWarnings("unused") @Pointcut("execution(public String demo.spring.aop..*(..))") //public 戻りString demoサブ階層 doが含まれるメソッド名 private void anyPublicOperation() {}
0
public void destroy() { if (frames == null) return; for (ZFrame f : frames) { f.destroy(); } frames.clear(); frames = null; }
2
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((brandName == null) ? 0 : brandName.hashCode()); result = prime * result + ((originalPrice == null) ? 0 : originalPrice.hashCode()); result = prime * result + ((percentOff == null) ? 0 : percentOff.hashCode()); result = prime * result + ((price == null) ? 0 : price.hashCode()); result = prime * result + ((productId == null) ? 0 : productId.hashCode()); result = prime * result + ((productName == null) ? 0 : productName.hashCode()); result = prime * result + ((productUrl == null) ? 0 : productUrl.hashCode()); result = prime * result + ((styleId == null) ? 0 : styleId.hashCode()); result = prime * result + ((thumbnailImageUrl == null) ? 0 : thumbnailImageUrl.hashCode()); return result; }
9
public MOB determineMonster(MOB caster, int level) { final MOB newMOB=CMClass.getMOB("GenMOB"); newMOB.basePhyStats().setAbility(7); newMOB.basePhyStats().setLevel(level); newMOB.basePhyStats().setRejuv(PhyStats.NO_REJUV); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); final int choice=CMLib.dice().roll(1,9,-1); switch(choice) { case 0: newMOB.setName(L("a dog")); newMOB.setDisplayText(L("a dog is sniffing around here")); newMOB.setDescription(L("She looks like a nice loyal companion.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'F'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Dog")); break; case 1: newMOB.setName(L("a turtle")); newMOB.setDisplayText(L("a turtle is crawling around here")); newMOB.setDescription(L("Not very fast, but pretty cute.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'F'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Turtle")); break; case 2: newMOB.setName(L("a cat")); newMOB.setDisplayText(L("a cat is prowling around here")); newMOB.setDescription(L("She looks busy ignoring you.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'F'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Cat")); break; case 3: newMOB.setName(L("a bat")); newMOB.setDisplayText(L("a bat is flying around here")); newMOB.setDescription(L("The darn thing just won`t stay still!")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Bat")); break; case 4: newMOB.setName(L("a rat")); newMOB.setDisplayText(L("a rat scurries nearby")); newMOB.setDescription(L("Such a cute, furry little guy!")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Rodent")); break; case 5: newMOB.setName(L("a snake")); newMOB.setDisplayText(L("a snake is slithering around")); newMOB.setDescription(L("..red on yellow..., how did that go again?")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Snake")); break; case 6: newMOB.setName(L("an owl")); newMOB.setDisplayText(L("an owl is flying around here")); newMOB.setDescription(L("He looks wise beyond his years.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Owl")); break; case 7: newMOB.setName(L("a rabbit")); newMOB.setDisplayText(L("a cute little rabbit is watching you")); newMOB.setDescription(L("Don`t blink, or she may twitch her nose.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'F'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Rabbit")); break; case 8: newMOB.setName(L("a raven")); newMOB.setDisplayText(L("a raven is pearched nearby")); newMOB.setDescription(L("You think he`s watching you.")); newMOB.baseCharStats().setStat(CharStats.STAT_GENDER,'M'); newMOB.baseCharStats().setMyRace(CMClass.getRace("Raven")); break; } newMOB.recoverPhyStats(); newMOB.recoverCharStats(); newMOB.basePhyStats().setArmor(CMLib.leveler().getLevelMOBArmor(newMOB)); newMOB.basePhyStats().setAttackAdjustment(CMLib.leveler().getLevelAttack(newMOB)); newMOB.basePhyStats().setDamage(CMLib.leveler().getLevelMOBDamage(newMOB)); newMOB.basePhyStats().setSpeed(CMLib.leveler().getLevelMOBSpeed(newMOB)); newMOB.baseCharStats().getMyRace().startRacing(newMOB,false); newMOB.addNonUninvokableEffect(CMClass.getAbility("Prop_ModExperience")); CMLib.factions().setAlignment(newMOB,Faction.Align.GOOD); newMOB.setStartRoom(null); newMOB.recoverCharStats(); newMOB.recoverPhyStats(); newMOB.recoverMaxState(); newMOB.resetToMaxState(); final Ability A=CMClass.getAbility("Prop_Familiar"); A.setMiscText(""+choice); newMOB.addNonUninvokableEffect(A); newMOB.text(); newMOB.bringToLife(caster.location(),true); CMLib.beanCounter().clearZeroMoney(newMOB,null); newMOB.location().showOthers(newMOB,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> appears!")); caster.location().recoverRoomStats(); return(newMOB); }
9
public void setFunCedula(long funCedula) { this.funCedula = funCedula; }
0
public int size()//Accessor method { return manyItems; }
0
@Override public void fire() { InviteMessage msg = new InviteMessage(); refreshCounter--; if(refreshCounter <= 0) { ((Antenna) this.node).resetNeighborhood(); msg.requireSubscription = true; refreshCounter = refreshRate; // reset the counter } this.node.broadcast(msg); double time = dist.nextSample(); if(time <=0) { Tools.fatalError("Invalid offset time for inviteInterval: " + time + " is <= 0."); } this.startRelative(time, this.node); }
2
public ArrayList<Meeting> getAllMeetingsFromDatabase(){ ArrayList<Meeting> meetings = new ArrayList<>(); ArrayList<HashMap<String, String>> meetings_raw = mySQLQuery.getAllRows("Meeting"); for(HashMap<String, String> meeting_raw : meetings_raw){ int meetingID = Integer.parseInt(meeting_raw.get("meetingID")); String startTime = meeting_raw.get("startTime").substring(0, meeting_raw.get("startTime").length()-2).replace(' ', 'T'); String endTime = meeting_raw.get("endTime").substring(0, meeting_raw.get("endTime").length()-2).replace(' ', 'T'); String description = meeting_raw.get("description") == null ? "" : meeting_raw.get("description"); String place = meeting_raw.get("place") == null ? "" : meeting_raw.get("place"); int room = meeting_raw.get("room") == null ? -1 : Integer.parseInt(meeting_raw.get("room")); int minCapacity = meeting_raw.get("minCapacity") == null ? -1 : Integer.parseInt(meeting_raw.get("minCapacity")); String creator = meeting_raw.get("creator"); String lastUpdated = meeting_raw.get("lastUpdated") == null ? null : meeting_raw.get("lastUpdated").substring(0, meeting_raw.get("lastUpdated").length()-2).replace(' ', 'T'); meetings.add(new Meeting(meetingID, startTime, endTime, description, place, room, minCapacity, creator, lastUpdated)); } return meetings; }
6
public static void main(String[] args) { System.out.println("Enter number of dice to toss"); Scanner s = new Scanner(System.in); int diceCount = s.nextInt(); SevenTally t = new SevenTally(diceCount); int experiments = 1000000; // int experiments = 1; int wins = 0; for(int j = 0; j < experiments; j++) if(t.experiment()) wins++; System.out.println((double)wins/experiments); //t.experiment(); }
2
private BaseDO makeObjectPersistent(final BaseDO baseDO) { return getEntityManager().merge(baseDO); }
0
public void cargarComboCargo(){ Usuario u = new Usuario(); ArrayList<String> listado = u.listarCargos(); if(listado !=null){ for (int i = 0; i < listado.size(); i++) { Cargo.addItem(listado.get(i)); } } }
2
public void wallOut() { if (mySpringies.getKey(JGEngine.KeyDown) & BoardSetup.wall_margin > 0) { for (Wall w : myBoardSetup.getWalls()) { w.remove(); } BoardSetup.changeMargin(-1* WALLCHANGE); myBoardSetup.setWalls(myEnvForces.getWallMags(), myEnvForces.getWallMags()); mySpringies.clearKey(JGEngine.KeyDown); } }
2
private boolean bit() throws JSONException { boolean value; try { value = this.bitreader.bit(); if (probe) { log(value ? 1 : 0); } return value; } catch (Throwable e) { throw new JSONException(e); } }
3
public int getY() { return y; }
0
public boolean canFall(){ // Parcours les coordonnées du jeu for(int x=0; x <= coordonneJeu.getNombreColonne()-1; x++) for(int y=0; y <= coordonneJeu.getNombreRangee()-1; y++) // Si un Tetrominoe est présent vérifie la position du desous if(!tetrominoes.get(tetrominoes.size()-1).IsEmpty(x, y)) try{ if(!coordonneJeu.IsEmpty(x, y+1) && tetrominoes.get(tetrominoes.size()-1).getEmplacement().IsEmpty(x, y+1) ){ updateFallingEndBlocks(); return false; } }catch(Exception e){ updateFallingEndBlocks(); return false; } return true; }
6
public Nodo<E> mostrarElementoAzar(){ //muestra solamente int posicionAzar = (int )(Math.random() * talla); Nodo datoEscogido = cabeza; for (int cont = 0; cont < posicionAzar; cont++) { datoEscogido = datoEscogido.siguiente; } Nodo <E> tmp2 = datoEscogido; return tmp2; }
1
public void render(Graphics2D g) { g.setColor(new Color(0,0,0,125)); g.fillOval(colBox.x-5, colBox.y, colBox.width+5, colBox.height+5); if (dir == 2) { g.drawImage(animRight.getCurrentImage(), (int) x, (int) y, width, height, null); } else if (dir == 1) { g.drawImage(animUp.getCurrentImage(), (int) x, (int) y, width, height, null); } else if (dir == 3) { g.drawImage(animLeft.getCurrentImage(), (int) x, (int) y, width, height, null); } else if (dir == 0) { g.drawImage(animDown.getCurrentImage(), (int) x, (int) y, width, height, null); } g.drawLine((int) x2 - 3, (int) y2, (int) x2 + 3, (int) y2); g.drawLine((int) x2, (int) y2 - 3, (int) x2, (int) y2 + 3); }
4
private void jButton1MouseMouseClicked(MouseEvent event) { ChooseFrame cf = new ChooseFrame(); cf.setDefaultCloseOperation(ChooseFrame.EXIT_ON_CLOSE); cf.setTitle("ChooseOpration"); cf.getContentPane().setPreferredSize(cf.getSize()); cf.pack(); cf.setLocationRelativeTo(null); cf.setVisible(true); this.dispose(); }
0
public void cambiarPosicionJugado2(){ for(int x=0;x<8;x++){ for(int y=0;y<8;y++){ if(pd.mapa_jugador2[x][y].equals(codigo)) pd.mapa_jugador2[x][y]=""; } } int x=rd.nextInt(0)+7; int y=rd.nextInt(0)+7; cambiarPosicionJugado2(); }
3
public static Boolean[] getCaseFancyMap(String strToMap) { Boolean[] map = new Boolean[strToMap.length()]; for (int i = 0; i < strToMap.length(); i++) { if (Character.isUpperCase(strToMap.charAt(i))) { map[i] = true; } else if (Character.isLowerCase(strToMap.charAt(i))) { map[i] = false; } } return map; }
3
public LinkedHashMap<Integer, Persona> leerPersonaJAXB(String rutaFichero) { rutaFichero = rutaFichero + ".xml"; LinkedHashMap<Integer, Persona> personas = new LinkedHashMap<>(); try { JAXBContext jaxbContext = JAXBContext.newInstance(MapPersona.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); MapPersona mp = (MapPersona) jaxbUnmarshaller.unmarshal(new File(rutaFichero)); for (Persona p : mp.getMapPersona().values()) { personas.put(p.getId(), p); } } catch (JAXBException ex) { //Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error en leerPersonaJAXB"); } return personas; }
2
public void filter(byte[] samples, int offset, int length) { for (int i=offset; i<offset+length; i+=2) { // update the sample short oldSample = getSample(samples, i); short newSample = (short)(oldSample + decay * delayBuffer[delayBufferPos]); setSample(samples, i, newSample); // update the delay buffer delayBuffer[delayBufferPos] = newSample; delayBufferPos++; if (delayBufferPos == delayBuffer.length) { delayBufferPos = 0; } } }
2
@Override public void renderControl(Graphics2D g) { if(this.isEnable()) { // create control bitmap BufferedImage Control = new BufferedImage(this.getSize().getWidth(), this.getSize().getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) Control.getGraphics(); // Anti Alias g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); // Fill the background if(this.getBackgroundColor() != null) { g2d.setColor(this.getBackgroundColor()); g2d.fillRect(0,0, this.getSize().getWidth(), this.getSize().getHeight()); } // Draw the text if(this.getText() != null && this.getForegroundColor() != null) { g2d.setColor(this.getForegroundColor()); g2d.setFont(this.getFont()); g2d.drawString(this.getText(), 0, this.getSize().getHeight() / 2); } // Draw the Control g.drawImage(Control, this.getLocation().getX(), this.getLocation().getY(), this.getSize().getWidth(), this.getSize().getHeight(), null); } }
4
private void field_localidadFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_field_localidadFocusLost boolean es_componente=false; // voy a preguntar si la componente que me saco el foco es algun campo del panel de datos de asientos int i=0; Component[] components = panel_datos.getComponents(); while ((!es_componente)&&(i<components.length)){ if (components[i]==evt.getOppositeComponent()){ es_componente=true; } i++; } if((es_componente)&&(field_codigo.isEditable())){ String id_sfi=field_localidad.getText(); if(!id_sfi.equals("")){ String descripcion =get_tipo_localidad(id_sfi); if (!descripcion.equals("")){ lab_localidad.setText(descripcion); } else{ field_localidad.requestFocus(); this.generarAyuda_Localidades(); } } else{ this.mostrar_Msj_Error("El campo Localidad esta vacio, debe ingresar un valor"); field_localidad.requestFocus(); } } else{ this.ocultar_Msj(); } }//GEN-LAST:event_field_localidadFocusLost
7
public boolean conflict(ValueIndexPair in) { return index1 == in.index1 || index1 == in.index2 || index2 == in.index1 || index2 == in.index2; }
3
private int walkthrough() { int result = 0; for (Position whiteKingPos : Position.getAllPositions()) { for (Position blackKingPos : Position.getAllPositions()) { if (whiteKingPos == blackKingPos) { continue; } for (Position blackRookPos : Position.getAllPositions()) { if (blackRookPos == blackKingPos || blackRookPos == whiteKingPos) { continue; } Situation situation = new Situation(); situation.addPiece(whiteKing, whiteKingPos); situation.addPiece(blackKing, blackKingPos); situation.addPiece(blackRook, blackRookPos); if (evaluate(situation, blackPlayer)) { result++; } if (evaluate(situation, whitePlayer)) { result++; } } } } return result; }
8
public static boolean hasAlpha(final Image image) { // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; return bimage.getColorModel().hasAlpha(); } // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { } // Get the image's color model ColorModel cm = pg.getColorModel(); return cm.hasAlpha(); }
2
@Test public void sequentialFigurePlacement() { FiguresPlacement figuresPlacement = new BishopsPlacement(); Set<String> boards = figuresPlacement.placeFigureOnBoard(BISHOP.getFigure(), EMPTY_BOARD_SIZE_6); assertThat("board is different", boards.contains("b.....\n" + "......\n" + "......\n" + "......\n" + "......\n" + "......\n"), is(true)); assertTrue("all elements are not present on each board", boards.stream() .allMatch(board -> !board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(BISHOP.getFigureAsString()) && leftOnlyFigures(board).length() == 1 && boards.size() == 36 )); }
6
@SuppressWarnings({ "rawtypes", "unchecked" }) protected int testCompareTo(Comparable o1, Comparable o2) { int res = 0; Map<String, Object> fields1 = getMineAndParentFields( ForCompareTo.class, o1); Map<String, Object> fields2 = getMineAndParentFields( ForCompareTo.class, o2); if (!isEmpty(fields1) && fields2.size() >= fields1.size()) { for (String key : fields1.keySet()) { Object v1 = fields1.get(key); Object v2 = fields2.get(key); if (v1 != null) { if (v2 != null) { if (v1 instanceof Comparable && v2 instanceof Comparable) { res = ((Comparable) v1).compareTo((Comparable) v2); } else { throw new IllegalArgumentException( safeFormat( "both arguments must be Comparables: (%s vs. %s)", v1.getClass(), v2.getClass())); } } else { res = 1; } } else { if (v2 != null) { res = -1; } else { // res = 0; } } if (res != 0) { break; } } } else { res = o1.compareTo(o2); } return res; }
9
public BeeperStack(int x, int y, int beepers) { super(x, y); if (beepers < 1 && beepers != Display.INFINITY) { Debug.printWarning("Invalid amount of beepers: " + beepers + "... Setting to 1..."); beepers = 1; } numBeepers = beepers; }
2
public boolean isActive(int id) { if (!plugin.getConfig().getBoolean("registration.activation")) return true; Connection conn = plugin.getDbCtrl().getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { String sql = String.format("SELECT `active` FROM `%s` WHERE `id` = ?", plugin.getDbCtrl().getTable(Table.ACCOUNT)); ps = conn.prepareStatement(sql); ps.setInt(1, id); rs = ps.executeQuery(); if (!rs.next()) return false; return rs.getBoolean("active"); } catch (SQLException e) { xAuthLog.severe("Failed to check active status of account: " + id, e); return false; } finally { plugin.getDbCtrl().close(conn, ps, rs); } }
3
public void close() { loggedIn = false; if (out != null) { // And attempt to logout, but don't care if we fail try { int id = invoke("loginService", "logout", new Object[] { authToken }); join(id); } catch (IOException e) { // Ignored } } super.close(); }
2
public DefaultSurfaceModel getModel() { return model; }
0
public Sound(byte[] samples) { this.samples = samples; }
0
public Train firstComeTrain(Double humpTime){ double minTime = humpTime; int trackNo=-1; //最先來火車的火車軌道 int i=0; for(ReceivingTrack rt : receivingTrack){ if(rt.isEmpty==false && rt.existTrain.currentTime<minTime){ //track有火車且最先來 minTime = rt.existTrain.currentTime; trackNo = i; //設定最先來的火車軌道是第幾個 } i++; } if(trackNo != -1){ //軌道有火車 Train tmp = receivingTrack[trackNo].existTrain; receivingTrack[trackNo].isEmpty = true; //讓那個track可以在接車 receivingTrack[trackNo].existTrain = null; //讓那個軌道存在的train回歸null tmp.receivingTrackNo = "R" + String.valueOf(trackNo+1); //要加1的原因是因為track命名是從R1開始 if(humpTime!=Double.MAX_VALUE) //因為只有第一次拉的時候,hump time為極大值 tmp.currentTime = humpTime; tmp.currentTime += Constants.HUMP_INTERVAL; //被hump拉出去的現在時間即為Sheet No.2 inbound_train_info的starting time of humping job finishTrain.add(tmp); return tmp; } else return null; }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!PositionType.class.isAssignableFrom(obj.getClass())) return false; PositionType other = (PositionType) obj; return row == other.getRow() && col == other.getCol(); }
4
public void run() { if(this.resultFilePath == null || this.resultFilePath == ""){ this.resultFilePath = createFileName(); } search(this.resultFilePath); }
2
@Override public void teardownTest(JavaSamplerContext context) { super.teardownTest(context); try { if (table != null) { table.flushCommits(); table.close(); table = null ; } } catch (IOException e) { System.out.println("teardown error"); } }
2
public void loadConfigFiles() { try { board.loadConfigFiles(); board.calcAdjacencies(); loadPlayers(); loadCards(); board.setPlayers(players); //called here after the cards are loaded notes.setUpNotes(cards); accuse.setUpComboBoxes(cards); suggest.setUpComboBoxes(cards); } catch(BadConfigFormatException e) { System.out.println(e.getMessage()); } }
1
public ArithmeticEncoder(BitOutputStream out) { super(); if (out == null) throw new NullPointerException(); output = out; underflow = 0; }
1
private void getSelectedDownloads() { toDownload = new ArrayList<>(); ArrayList<Object> selections; for (int i = 0, l = table.getRowCount(); i < l; i++) { selections = table.isSelected(i); if ((boolean) selections.get(0)) { toDownload.add(new Resource(i, lectures.get(i))); //System.out.println(lectures.get(i)); } if ((boolean) selections.get(1)) { toDownload.add(new Resource(i, txt.get(i))); //System.out.println(txt.get(i)); } if ((boolean) selections.get(2)) { toDownload.add(new Resource(i, srt.get(i))); //System.out.println(srt.get(i)); } if ((boolean) selections.get(3) && pdf.get(i) != null) { toDownload.add(new Resource(i, pdf.get(i))); //System.out.println(pdf.get(i)); } if ((boolean) selections.get(4) && ppt.get(i) != null) { toDownload.add(new Resource(i, ppt.get(i))); //System.out.println(ppt.get(i)); } } }
8
public int[] getArrayForNumberOfBreakpoints() throws IOException { FileInputStream fileInputStream = new FileInputStream(pathToFile); DataInputStream in = new DataInputStream(fileInputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; String[] splitted = new String[10000]; while ((strLine = br.readLine()) != null) { splitted = strLine.split(" "); } in.close(); int count = 0; for (int i = 0; i < splitted.length; i++) { count++; } int[] splittedInt = new int[count]; for (int i = 0; i < count; i++) { splittedInt[i] = Integer.valueOf(splitted[i]); } return splittedInt; }
3
public int getNumberOfSamples() { if (vcfFileIterator == null) return 0; VcfHeader vh = vcfFileIterator.getVcfHeader(); if (vh == null) return 0; return vh.getNumberOfSamples(); }
2
public boolean isFlipD() { switch (tileFlip) { case D: case HD: case VD: case HVD: return true; default: return false; } }
4
String typeOf(String st) throws Exception { //handle define, the word after it is a procedure //to ensure that everything after define is still procedure if (reservedWords.contains(st)) { return "RESERVED WORD"; } else if (Character.isDigit(st.charAt(0))) { return "DIGIT"; } else if (specialSymbol.contains(st)) { return "PROCEDURE"; } else { return "IDENTIFIER"; } //add here if you want to check procedure example: member?, null? }
3
@Cacheable(cacheName = "findAllBlogCache") public List<Blog> getBlogs() { return this.blogModelDao.findAll(); }
0
public int getX() { return x; }
0
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){ try { Object o1 = session.getAttribute("UserID"); Object o2 = session.getAttribute("UserRights"); boolean bRedirect = false; if ( o1 == null || o2 == null ) { bRedirect = true; } if ( ! bRedirect ) { if ( (o1.toString()).equals("")) { bRedirect = true; } else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; } } if ( bRedirect ) { response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI())); return "sendRedirect"; } } catch(Exception e){}; return ""; }
7
public Draw(int a, int b, int c, boolean v) { int[] p = new int[] { a + 1, b + 1, c + 1 }; if (v) { boolean asc, desc; for (int i = 0; i <= 2; i++) { asc = desc = true; for (int j = 0; j <= 1; j++) if (p[(i + j + 1) % 3] > p[(i + j) % 3]) desc = false; else if (p[(i + j + 1) % 3] < p[(i + j) % 3]) asc = false; if (asc || desc) { this.a = p[i]; this.b = p[(i + 1) % 3]; this.c = p[(i + 2) % 3]; break; } } } else { Arrays.sort(p); this.a = p[0]; this.b = p[1]; this.c = p[2]; } }
7
public static void subpermute(List<List<Integer>> res, List<Integer> l, int[] num) { if (0 == num.length) { List<Integer> t = new ArrayList<Integer>(l); res.add(t); return; } else { for (int i = 0; i < num.length; i++) { if (i > 0 && num[i] == num[i - 1]) continue; l.add(num[i]); int[] tmp = new int[num.length - 1]; int delta = 0; for (int j = 0; j < num.length; j++) { if (j != i) { tmp[j - delta] = num[j]; } else { delta = 1; } } subpermute(res, l, tmp); l.remove(l.size() - 1); } } }
6
public void doLoad(List<String> codes, List<String> years, List<String> publishers) throws XMPPException { StringCollection reg = new StringCollection(); reg.setType(IQ.Type.GET); reg.setTo(connection.getServiceName()); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); StringCollection result = (StringCollection)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); //1 min // Stop queuing results // collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } codes.addAll(result.getStrings()); result = (StringCollection)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); //1 min // Stop queuing results // collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } years.addAll(result.getStrings()); result = (StringCollection)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); //1 min // Stop queuing results // collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } publishers.addAll(result.getStrings()); PropertiesCollection result1 = (PropertiesCollection)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); //1 min // Stop queuing results collector.cancel(); if (result1 == null) { throw new XMPPException("No response from server."); } else if (result1.getType() == IQ.Type.ERROR) { throw new XMPPException(result1.getError()); } for (Property prop : result1.getProperties()){ ZnConfiguration.put(prop.getName(), prop.getValue()); } }
9
private void refreshRemoteUsersList(){ for(Object clients:userOnLineL){ InterClient client=(InterClient) clients; try { client.refreshClient(); } catch (RemoteException ex) { Logger.getLogger(ServeurLegede.class.getName()).log(Level.SEVERE, null, ex); } } }
2
public static String toText(byte [] bytes) { StringWriter sw = new StringWriter(); int length = bytes.length; if(length > 0) { for(int i = 0; i < length; i++) { byte b = bytes [i]; if(b > 64 && b < 91 || b > 96 && b < 123) sw.write((char)b); } } return(sw.toString()); }
6
@Override public <T extends OAuthResponse> T execute(Request request, Class<T> responseClass) { String responseBody = null; URLConnection c = null; int responseCode = 0; try { URL url = new URL(request.getLocationUri()); c = url.openConnection(); responseCode = -1; if (c instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) c; if (request.getHeaders() != null) { for (Map.Entry<String, String> header : request .getHeaders().entrySet()) { httpURLConnection.addRequestProperty(header.getKey(), header.getValue()); } } String requestMethod = request.getRequestType(); if (!OAuthKit.isEmpty(requestMethod)) { httpURLConnection.setRequestMethod(requestMethod); if (requestMethod.equals(OAuth.HttpMethod.POST)) { httpURLConnection.setDoOutput(true); OutputStream ost = httpURLConnection.getOutputStream(); PrintWriter pw = new PrintWriter(ost); pw.print(OAuthKit.format(request.getBodyNameValuePair() .entrySet(), "UTF-8")); pw.flush(); pw.close(); } } else { httpURLConnection.setRequestMethod(OAuth.HttpMethod.GET); } httpURLConnection.connect(); InputStream inputStream; responseCode = httpURLConnection.getResponseCode(); if (responseCode == 400 || responseCode == 401) { inputStream = httpURLConnection.getErrorStream(); } else { inputStream = httpURLConnection.getInputStream(); } responseBody = OAuthKit.saveStreamAsString(inputStream); } } catch (IOException e) { throw new OAuthException(e); } return OAuthKit.createCustomResponse(responseBody, c.getContentType(), null, responseCode, responseClass); }
8
protected void generateWorld() { if(!Game.Online) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int tile = r.nextInt(Tile.dirtId); tiles[y][x] = Tile.createTile(tile, x, y, this); } } } }
3
private void performTask(){ long start = System.nanoTime(); switch(this.action){ case HASHFUNCTIONS: performHashFunctionTests(); break; case HYPERLOGLOG: performHyperLogLog(); break; case SIMILARITIES: performSimilarities(); break; case SLIDINGWINDOW: performSlidingWindow(); break; case FREQUENTWORDS: performFrequentWords(); break; case MICE: performMice(); break; case ICEBERGS: performIcebergs(); break; default: break; } long end = System.nanoTime(); if(this.jCheckBox1.isSelected()) this.jTextField1.setText(Double.toString((end-start)/1000000000.) + " s"); }
8
public IVPBoolean ivpNotEqualTo(IVPValue num, Context c, HashMap map, DataFactory factory) { IVPBoolean result = factory.createIVPBoolean(); map.put(result.getUniqueID(), result); boolean resultBoolean = false; if(getValueType().equals(IVPValue.INTEGER_TYPE) && num.getValueType().equals(IVPValue.INTEGER_TYPE)){ resultBoolean = c.getInt(getUniqueID()) != c.getInt(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE) && num.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) != c.getDouble(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) != c.getInt(num.getUniqueID()); }else{ resultBoolean = c.getInt(getUniqueID()) != c.getDouble(num.getUniqueID()); } } } c.addBoolean(result.getUniqueID(), resultBoolean); return result; }
5
public void hit(int damage) { if(dead || flinching) return; health -= damage; if(health < 0) health = 0; if(health == 0) dead = true; flinching = true; flinchTimer = System.nanoTime(); }
4
public int getHp(int npc) { switch (npc) { case 2627: return 10; case 2630: return 20; case 2631: return 40; case 2741: return 80; case 2743: return 150; case 2745: return 2500; } return 100; }
6
public static void main( String[] args ) throws IOException { String myFile = "/home/abu/Desktop/1.txt"; FileReader myFileReader = new FileReader( myFile ); BufferedReader myFileBuffer = new BufferedReader( myFileReader ); String text = myFileBuffer.readLine(); while ( text != null ) { System.out.println( text ); text = myFileBuffer.readLine();// read the next line } myFileReader.close(); }
1
public boolean addUser(String username, String password) { boolean succes = false; try { crs = qb.selectFrom("users").where("username", "=", username).executeQuery(); if(crs.next()) { succes = false; } else { String[] fields = {"username", "password"}; String[] values = {username, password}; qb.insertInto("users", fields).values(values).execute(); succes = true; } } catch (SQLException e) { e.printStackTrace(); } finally { try { crs.close(); } catch (SQLException e) { e.printStackTrace(); } } return succes; }
3
public HipPacket handleClose(byte[] src, byte[] dst, HipPacket close, HipSadb sadb, SignatureAlgo sigAlgo, HostIdentityTag hit) { SaEntry __entry = null; HMACParameter __hmacParam = null; HipPacket __closeAck = null; SignatureParameter __sigParameter = null; byte[] __signature = null; byte[] __hmac = null; byte[] __opaque = new byte[4]; EchoRequestSigParameter __echoRequest = null; EchoResponseSigParameter __echoResponse = (EchoResponseSigParameter) HipParameterFactoryImpl .createHipParameter(EchoResponseSigParameter.TYPE_ECHO_SIG_RESPONSE); byte[] __hitR = null; byte[] __hitI = null; if (close == null) return null; __echoRequest = (EchoRequestSigParameter) close .getParameter(EchoRequestSigParameter.TYPE_ECHO_SIG_REQUEST); if (__echoRequest == null) return null; __echoRequest.getOpaque(__opaque); __echoResponse.setOpaque(__opaque); __hitR = new byte[HostIdentityTag.TAGLENGTH]; __hitI = new byte[HostIdentityTag.TAGLENGTH]; close.getSourceHit(__hitI); close.getDestinationHit(__hitR); if (!hit.equals(__hitR)) return null; __entry = sadb.find(new HostIdentityTag(__hitI)); if (__entry == null) return null; // process based on destination ip instead if (!HipPacket.verifyHMAC(close, __entry.getPeerHostID(), new HMACSHA1Digest(__entry.getAuthKeyIn()))) { System.out.println("HMAC VERIFICATION FAILED"); return null; } if (!HipPacket.verifySignature(close, sigAlgo, __entry .getPeerPublicKey())) return null; IPPacket __packet = null; if (close.getIPVersion() == IPPacket.IP_VERSION4) { __packet = new IPPacket(DEFAULT_IPV4_LENGTH); // SET IP VERSION FIRST __packet.setIPVersion(IPPacket.IP_VERSION4); __packet.setIPHeaderLength(DEFAULT_IPV4_LENGTH / 4); __packet.setTTL(DEFAULT_TTL); __packet.setProtocol(HipPacket.HIP_PROTO); __packet.setSource(dst); __packet.setDestination(src); } else { // TODO: IPv6 ... } __closeAck = HipPacketFactoryImpl.getFactory().createCloseAckPacket( __packet, __hitI, __hitR, __echoResponse); __hmacParam = (HMACParameter) HipParameterFactoryImpl .createHipParameter(HMACParameter.TYPE_HMAC); __closeAck.setParameter(__hmacParam); __hmac = HipPacket.computeHMAC(__closeAck, __entry.getLocalHostID(), new HMACSHA1Digest(__entry.getAuthKeyOut())); __hmacParam.setHMAC(__hmac); __closeAck.setParameter(__hmacParam, true); __sigParameter = (SignatureParameter) HipParameterFactoryImpl .createHipParameter(SignatureParameter.TYPE_SIGNATURE); __closeAck.setParameter(__sigParameter); __signature = HipPacket.computeSignature(__closeAck, sigAlgo, __entry .getLocalPrivateKey()); __sigParameter.setSignature(__signature); __sigParameter.setSigAlgo((byte) __entry.getSignatureAlgo()); __closeAck.setParameter(__sigParameter, true); __closeAck.setHIPChecksum(); __entry.setState(HipState.CLOSED); __entry.setTimer(System.currentTimeMillis()); __entry.setRetransmitCounter(0); return __closeAck; }
7
public StudentInfoEditor(StudentsListTab window, Student student) { this.window = window; this.student = student; this.setTitle(student.getFirstName() + " " + student.getLastName()); this.tabs = new JTabbedPane(); this.avoidingTable = makeTable(student); this.scrollbar = new JScrollPane(this.avoidingTable); /* * Separation Tab */ JPanel buttonsPane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton newStudentButton = new JButton("New"); newStudentButton.setActionCommand("New Student"); newStudentButton.addActionListener(this); buttonsPane.add(newStudentButton); JButton delStudentButton = new JButton("Delete"); delStudentButton.setActionCommand("Delete Student"); delStudentButton.addActionListener(this); buttonsPane.add(delStudentButton); JPanel separationPanel = new JPanel(new BorderLayout()); separationPanel.add(scrollbar, BorderLayout.CENTER); separationPanel.add(buttonsPane, BorderLayout.PAGE_END); /* * Information Editing Tab contents */ /* * Name and student ID text fields for setting those of a student. */ JPanel studentIDSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel studentIDLabel = new JLabel("Student ID: "); this.studentIDField = new JTextField(Integer.toString(student.getStudentID())); this.studentIDField.setColumns(5); studentIDSetter.add(studentIDLabel); studentIDSetter.add(studentIDField); JPanel firstNameSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel firstNameLabel = new JLabel("First: "); this.firstNameField = new JTextField(student.getFirstName()); this.firstNameField.setColumns(8); firstNameSetter.add(firstNameLabel); firstNameSetter.add(firstNameField); JPanel lastNameSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel lastNameLabel = new JLabel("Last: "); this.lastNameField = new JTextField(student.getLastName()); this.lastNameField.setColumns(8); lastNameSetter.add(lastNameLabel); lastNameSetter.add(lastNameField); /* * Box to force assigned seating */ JPanel assignedSeatSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel assignedSeatLabel = new JLabel("Assigned Seat"); this.assignedSeatField = new JTextField(); for (int i = 0; i < 3; i++) { for (int j = 0; j < this.window.currentClass.getQuadrants().get(i).getSize(); j++) { Desk desk = this.window.currentClass.getQuadrants().get(i).getDesk(j); if (desk.isEditable() == false && desk.getOccupyingStudent().equals(student)) { switch (i) { case 0: this.assignedSeatField = new JTextField(Integer.toString(j+1)); break; case 1: this.assignedSeatField = new JTextField(Integer.toString(j+11)); break; case 2: this.assignedSeatField = new JTextField(Integer.toString(j+23)); break; } } } } this.assignedSeatField.setColumns(2); assignedSeatSetter.add(assignedSeatLabel); assignedSeatSetter.add(assignedSeatField); /* * Box to set the race of a student. */ JPanel raceSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel raceNameLabel = new JLabel("Race: "); this.raceSelection = new JComboBox<String>(new String[] { "White", "Asian", "AfricanAmerican", "Latino", "PacificIslander", "Other"}); this.raceSelection.setSelectedItem(student.getRace().toString()); raceSetter.add(raceNameLabel); raceSetter.add(raceSelection); /* * Box to set the Gender of a student */ JPanel genderSetter = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel genderLabel = new JLabel("Gender: "); this.genderSelection = new JComboBox<String>(new String[] { "Male", "Female", "Other" }); this.genderSelection.setSelectedItem(student.getGender().toString()); genderSetter.add(genderLabel); genderSetter.add(genderSelection); /* * Bottom button pane with save/cancel buttons */ JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton saveChanges = new JButton("Save"); saveChanges.addActionListener(this); saveChanges.setActionCommand("Save"); JButton cancelChanges = new JButton("Cancel"); cancelChanges.addActionListener(this); cancelChanges.setActionCommand("Cancel"); buttonPane.add(saveChanges); buttonPane.add(cancelChanges); JPanel comboboxPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); comboboxPane.add(genderSetter); JPanel informationPanel = new JPanel(); informationPanel.setLayout(new GridLayout(5, 2)); informationPanel.add(studentIDSetter); informationPanel.add(assignedSeatSetter); informationPanel.add(firstNameSetter); informationPanel.add(lastNameSetter); informationPanel.add(genderSetter); informationPanel.add(raceSetter); informationPanel.add(new JPanel()); informationPanel.add(buttonPane); tabs.addTab("Information", null, informationPanel);; tabs.addTab("Separation", null, separationPanel); this.add(tabs, BorderLayout.CENTER); this.setResizable(false); this.setSize(400, 320); this.setLocationRelativeTo(null); this.setVisible(true); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }
7
public static void test_2(){ try{ System.out.println("\n\nTestCase-2\n\n"); TestNetwork n=new TestNetwork(4,4,2); Paxos p=new Paxos(n); p.runPaxos(); n.change_DPmode(-1,1); for(int i=0;i<10;i++) //Block the channel of all processes n.block_channel(i, 1); Thread.sleep(500); for(int i=0;i<4;i++) //Release all Proposers n.block_channel(i,0); Thread.sleep(1000); for(int i=4;i<8;i++) //Release all Acceptors n.block_channel(i,0); Thread.sleep(1000); n.block_channel(9,0); //Release one of the learner's channel Thread.sleep(1000); n.block_channel(8,0); //Lets release the next learner's channel Thread.sleep(5000); n.terminate_run(); Thread.sleep(2000); System.out.println("\n\nTERMINATED PAXOS RUN-2"); n.printTrace(); } catch(Exception e){} }
4
@Override public void unInvoke() { if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; if(canBeUninvoked()) { if(!mob.amDead()) { if((invoker!=null)&&(invoker.location()==mob.location())&&(!invoker.amDead())) invoker.tell(invoker,mob,null,L("You are no longer distracting <T-NAMESELF>.")); if((mob.location()!=null)&&(!mob.amDead())) mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> no longer so distracted.")); } } super.unInvoke(); }
8
public static final String trim4Html(Object obj) { String str; return obj != null && (str = obj.toString().trim()).length() > 0 ? str : "&nbsp;"; }
2
public void setProperty(String property, int value) { switch (property) { case "resolution": setResolution(value); break; case "tolerance": setTolerance(value/100d); break; case "blurRadius": setBlurRadius(value); break; case "temperature": setTemperature(value/100d); break; case "brightness": setBrightness(value/100d); break; case "saturation": setSaturation(value/100d); break; case "difference": setDifference(value/100d); break; case "modelSnap": setModelSnap(value/100d); break; case "patchSize": setPatchSize(value/100d); break; default: throw new IllegalArgumentException(); } }
9
private void Ok() { if(loginTextField.getText().length() == 0) { JOptionPane.showMessageDialog(rf, "Enter login"); return; } if(loginTextField.getText().length() < 4) { JOptionPane.showMessageDialog(rf, "Login is to short, it should be longer then 3 characters"); return; } if(passTextField.getText().length() == 0) { JOptionPane.showMessageDialog(rf, "Enter password"); return; } if(passTextField.getText().length() < 5) { JOptionPane.showMessageDialog(rf, "Password is to short, it should be longer then 6 characters"); return; } if(passConfTextField.getText().length() == 0) { JOptionPane.showMessageDialog(rf, "Confirm password"); return; } if(!passConfTextField.getText().equals(passTextField.getText())) { JOptionPane.showMessageDialog(rf, "Passwords do not match"); return; } try { if(!link.Registrate(loginTextField.getText(), passTextField.getText())) { JOptionPane.showMessageDialog(rf, "Login is already used"); return; } else { JOptionPane.showMessageDialog(rf, "Registration completed successful"); frame.setVisible(true); rf.dispose(); } } catch (RemoteException e1) { JOptionPane.showMessageDialog(rf, "No connection with server"); rf.dispose(); lf.setVisible(true); } }
8
private WarMachine platziereWarMachine(WarMachine newWarMachine) { boolean invalidInput = true; String input = null; Koordinate platzKoordinate = null; Ausrichtung platzAusrichtung = null; while (invalidInput) { try { input = client.getPlayerInput(); } catch (Exception e) { e.printStackTrace(); } String[] argumente = input.split(","); if (argumente.length < 3) { ausgabe.printFalscheEingabe(); continue; } platzKoordinate = eingabe.string2Koord(argumente[0].toString() + "," + argumente[1].toString()); platzAusrichtung = eingabe.string2Ausrichtung(argumente[2]); if (!eingabe.validAusrichtung(platzAusrichtung)) { ausgabe.printFalscheEingabe(); continue; } try { spielfeld.place(newWarMachine, platzKoordinate, platzAusrichtung); invalidInput = false; } catch (Exception e) { ausgabe.printFalscheEingabe(); System.out.println("Exception: " + e); invalidInput = true; } } // while invalid Input return newWarMachine; }
5
public String getThreeOfAKind() { String stt = "0"; //search for groups of 3 neighbouring cards that have the same rank if (cards[0].getRank() == cards[1].getRank() && cards[1].getRank() == cards[2].getRank()) { stt = Character.toString (cards[0].getCharCard()) + cards[3].getCharCard() + cards[4].getCharCard(); return stt; } if (cards[1].getRank() == cards[2].getRank() && cards[2].getRank() == cards[3].getRank()) { stt = Character.toString(cards[1].getCharCard()) + cards[0].getCharCard() + cards[4].getCharCard(); return stt; } if (cards[2].getRank() == cards[3].getRank() && cards[3].getRank() == cards[4].getRank()) { stt = Character.toString(cards[2].getCharCard()) + cards[0].getCharCard() + cards[1].getCharCard(); return stt; } return stt; }
6
public List<IrcClient> getAllClients(){ return AllClients; }
0
public void setCurrentCells(boolean[] currentCells) { this.currentCells = currentCells; }
0
public boolean[] getCurrentCells() { return currentCells; }
0
public int firstMissingPositive(int[] A) { for (int i = 0; i < A.length; i++) { while(A[i] != i+1){ if(A[i] <= 0 || A[i] > A.length || A[i] == A[A[i]-1]) break; int tmp = A[i]; A[i] = A[tmp-1]; A[tmp-1] = tmp; } } for (int i = 0; i < A.length; i++) { if (A[i] != i + 1) return i + 1; } return A.length + 1; }
7
@Override public CellSpace newSubCellSpace( int i ) { // We need to describe the corners of the two cubes on the lo-hi // diagonal. There are 13 new points to create. // T top / B bottom // L left / R right // F front / B back if( C == null ) { double cx = lo.x + ( hi.x - lo.x ) / 2; double cy = lo.y + ( hi.y - lo.y ) / 2; double cz = lo.z + ( hi.z - lo.z ) / 2; C = new Anchor( cx, cy, cz ); } Anchor BLF1 = lo; Anchor TRB2 = hi; switch( i ) { case 0: return new OctreeCellSpace( BLF1, C ); case 1: Anchor BRF1 = new Anchor( C.x, lo.y, lo.z ); Anchor BRF2 = new Anchor( hi.x, C.y, C.z ); return new OctreeCellSpace( BRF1, BRF2 ); case 2: Anchor TRF1 = new Anchor( C.x, C.y, lo.z ); Anchor TRF2 = new Anchor( hi.x, hi.y, C.z ); return new OctreeCellSpace( TRF1, TRF2 ); case 3: Anchor TLF1 = new Anchor( lo.x, C.y, lo.z ); Anchor TLF2 = new Anchor( C.x, hi.y, C.z ); return new OctreeCellSpace( TLF1, TLF2 ); case 4: Anchor BLB1 = new Anchor( lo.x, lo.y, C.z ); Anchor BLB2 = new Anchor( C.x, C.y, hi.z ); return new OctreeCellSpace( BLB1, BLB2 ); case 5: Anchor BRB1 = new Anchor( C.x, lo.y, C.z ); Anchor BRB2 = new Anchor( hi.x, C.y, hi.z ); return new OctreeCellSpace( BRB1, BRB2 ); case 6: return new OctreeCellSpace( C, TRB2 ); case 7: Anchor TLB1 = new Anchor( lo.x, C.y, C.z ); Anchor TLB2 = new Anchor( C.x, hi.y, hi.z ); return new OctreeCellSpace( TLB1, TLB2 ); default: throw new RuntimeException( "invalid subcell space index '"+i+"' for oct tree" ); } }
9
@Override public String readFromBomberman() throws IOException { Scanner scan = new Scanner(System.in); System.out.print("Please input your command: "); String command = scan.nextLine(); clientSideWriter.append(command).append("\n").flush(); return serverSideReader.readLine(); }
0
private boolean isAdjacent(int currentIndex, int newIndex, RoomCell.DoorDirection directionOut, RoomCell.DoorDirection directionIn) { // If your new cell is a walkway and you're not in a room, return true if (cells.get(newIndex).isWalkway() && !cells.get(currentIndex).isRoom()) return true; // If the current cell is a room, and not a doorway, then there are no adjacencies else if (cells.get(currentIndex).isRoom() && !cells.get(currentIndex).isDoorway()) return false; // If you're in a doorway, and the door is facing the direction required to get out as specified by the call, it's adjacent. else if (cells.get(currentIndex).isDoorway() && ((RoomCell) cells.get(currentIndex)).getDoorDirection() == directionOut) return true; // If you're on a walkway and trying to get into a door, and it's facing the correct way to go in, it's adjacent else if (!cells.get(currentIndex).isDoorway() && ((RoomCell) cells.get(newIndex)).getDoorDirection() == directionIn) return true; // Otherwise, it's not adjacent. return false; }
8
private void getPheno() { if(Character.isUpperCase(allel1)){pheno = allel1;} if(Character.isUpperCase(allel2)){pheno = allel2;} if(Character.isLowerCase(allel1)&&Character.isLowerCase(allel2)){pheno = allel1;} }
4
public synchronized final void saveToCache () { if (getCache() == null) return; // absolutely required field if (getTitle()==null) return; //1. Compose this one and childrefs Element e = getSpecificDataXML(); if (e==null) return; // element is corrupt and should not be cached e.setAttribute("title", getTitle()); e.setAttribute("url", url.toString()); for (AbstractPage child: childPages) if (child != null) { Element childElement = new Element("childref"); childElement.setAttribute("class",child.getClass().getSimpleName()); childElement.setAttribute("url",child.url.toString()); e.addContent(childElement); } getCache().addElementWithReplacement(e); }
5
private int sum(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; }
1
private void notifyListeners() { if(!listeners.isEmpty()) for(Listener listener : listeners) listener.update(); }
2
@Test public void testConnection6() throws Throwable { final LoopHandle loop = new LoopHandle(); if (!UDPHandleTest.isIPv6Enabled(loop)) { return; } final AtomicInteger serverSendCount = new AtomicInteger(0); final AtomicInteger clientSendCount = new AtomicInteger(0); final AtomicInteger serverRecvCount = new AtomicInteger(0); final AtomicInteger clientRecvCount = new AtomicInteger(0); final AtomicBoolean serverDone = new AtomicBoolean(false); final AtomicBoolean clientDone = new AtomicBoolean(false); final TCPHandle server = new TCPHandle(loop); final TCPHandle peer = new TCPHandle(loop); final TCPHandle client = new TCPHandle(loop); final Logger serverLoggingCallback = new Logger("s: "); final Logger clientLoggingCallback = new Logger("c: "); final Random random = new Random(); server.setConnectionCallback(new StreamConnectionCallback() { @Override public void onConnection(int status, Exception error) throws Exception { serverLoggingCallback.log(status, error); server.accept(peer); peer.readStart(); System.out.println("s: " + server.getSocketName() + " connected to " + peer.getPeerName()); peer.write("message " + serverSendCount.getAndIncrement() + " from server"); server.close(); // not expecting any more connections } }); peer.setReadCallback(new StreamReadCallback() { @Override public void onRead(final ByteBuffer data) throws Exception { serverRecvCount.incrementAndGet(); if (data == null) { peer.close(); } else { final Object[] args = {data}; serverLoggingCallback.log(args); if (serverRecvCount.get() == TIMES) { peer.close(); } else { peer.write("message " + serverSendCount.getAndIncrement() + " from server"); } } } }); peer.setCloseCallback(new StreamCloseCallback() { @Override public void onClose() throws Exception { // close serverDone.set(true); } }); client.setReadCallback(new StreamReadCallback() { @Override public void onRead(final ByteBuffer data) throws Exception { clientRecvCount.incrementAndGet(); if (data == null) { client.close(); } else { final Object[] args = {data}; clientLoggingCallback.log(args); if (clientRecvCount.get() == TIMES) { client.close(); } else { client.write("message " + clientSendCount.getAndIncrement() + " from client"); } } } }); client.setConnectCallback(new StreamConnectCallback() { @Override public void onConnect(int status, Exception error) throws Exception { clientLoggingCallback.log(status, error); System.out.println("c: " + client.getSocketName() + " connected to " + client.getPeerName()); client.readStart(); client.write("message " + clientSendCount.getAndIncrement() + " from client"); } }); client.setCloseCallback(new StreamCloseCallback() { @Override public void onClose() throws Exception { // close clientDone.set(true); } }); server.bind6(ADDRESS6, PORT6); server.listen(1); Thread.sleep((long) (random.nextDouble() * 100)); client.connect6(ADDRESS6, PORT6); while (!serverDone.get() || !clientDone.get()) { loop.run(); } Assert.assertEquals(serverSendCount.get(), TIMES); Assert.assertEquals(clientSendCount.get(), TIMES); Assert.assertEquals(serverRecvCount.get(), TIMES); Assert.assertEquals(clientRecvCount.get(), TIMES); }
7
public List<Deal> ListerDeals() { PrestataireDeServiceDAO psdao = new PrestataireDeServiceDAO(); try { String sql = "SELECT * FROM Deal "; ResultSet rs = crud.exeRead(sql); List<Deal> liste = new ArrayList<Deal>(); while (rs.next()) { Deal d = new Deal(); d.setIdDeal(rs.getInt("idDeal")); d.setLibelle(rs.getString("libelle")); d.setCategorie(rs.getString("categorie")); d.setTypeDeal(rs.getString("typeDeal")); d.setDateDebut(rs.getString("dateDebut")); d.setDateFin(rs.getString("dateFin")); d.setImage(rs.getString("image")); d.setPrixInitial(rs.getDouble("prixInitial")); d.setPrixPromotionnel(rs.getDouble("prixPromotionnel")); d.setQuantite(rs.getInt("quantite")); d.setStatut(rs.getInt("statut")); d.setPrestataireDeService(psdao.ChercherPrestataireDeService(rs.getInt("idUser"))); liste.add(d); } return liste; } catch (SQLException ex) { Logger.getLogger(DealDAO.class.getName()).log(Level.SEVERE, null, ex); return null; } }
2
@Test public void testDeleteAcademy() { System.out.println("deleteAcademy"); String nameId = "CPH"; int ispresent = amock.getAcademysAsJson().contains(nameId) ? 1 : 0; BusinessAcademy a = amock.deleteAcademy(nameId); if (ispresent == 1 && a.getName().equals(nameId)) { assertTrue(true); } assertFalse(false); }
3
@Override public void run() { String responseData = null; HttpClient httpClient = new HttpClient(); int statusCode = -1; try { statusCode = httpClient.executeMethod(mHttpMedthod); if (statusCode != HttpStatus.SC_OK) { System.err.println("HttpMethod failed: " + mHttpMedthod.getStatusLine()); } responseData = mHttpMedthod.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); if (mAsyncHandler != null) { mAsyncHandler.onThrowable(e, mCookie); } return; } catch (IOException e) { e.printStackTrace(); if (mAsyncHandler != null) { mAsyncHandler.onThrowable(e, mCookie); } return; } finally { mHttpMedthod.releaseConnection(); httpClient = null; } if (mAsyncHandler != null) { mAsyncHandler.onCompleted(statusCode, responseData, mCookie); } }
6
public void run(){ try ( /*ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept();*/ PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); ) { System.out.println("Connected"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromClient, fromServer; fromServer="hello"; in.ready(); System.out.println("So far so good"); out.println(fromServer); while ((fromClient = in.readLine()) != null) { System.out.println("Client: " + fromClient); if (fromClient.equals("\\shutdown")){ break; } fromServer = stdIn.readLine(); if (fromServer!=null){ System.out.println("Client: " + fromServer); out.println(fromServer); out.flush(); } if(fromServer.equals("\\shutdown")){ break; } } System.out.println("Did you get anything"); } catch(IOException e) { System.out.println(e.getMessage()); } }
5
public boolean matchesAddress(String address, int port) { if(address == null) return (clientAddress == null && port == clientPort); return (address.equals(clientAddress) && port == clientPort); }
3
public U fold(U u, Queue<T> ts, Function2<T, U, U> function) { // The recursive implementation will overflow the stack for // any data set of real size, your job is to implement a // non-recursive solution // return fold(function.apply(ts.poll(), u), ts, function); while(true) { if(u == null || ts == null || function == null) throw new IllegalArgumentException(); if (ts.isEmpty()) { return u; } u = function.apply(ts.poll(), u); } //return null; }
5
public static void main(String[] args) { int port; if (args.length < 1) { port = 6727; } else { port = Integer.parseInt(args[0]); } try { serverSocket = new ServerSocket(port); } catch (IOException ex) { Logger.getLogger(ClipboardShare_Server.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); while (true) { try { Socket currentConnection = serverSocket.accept(); new WelcomeThread(currentConnection).start(); } catch (IOException e) { System.err.println(e.getMessage()); break; } } }
4
protected static float complexToFloat(int complex) { return (complex&(COMPLEX_MANTISSA_MASK << COMPLEX_MANTISSA_SHIFT)) * RADIX_MULTS[(complex>>COMPLEX_RADIX_SHIFT) & COMPLEX_RADIX_MASK]; }
0
public Set<AndroidMethod> getSources() { return sources; }
0
public String toString() { StringBuilder sb = new StringBuilder(); for (Card card : cards) { sb.append(card.toString()); } return sb.toString(); }
1
public EqualDivisionNormalDistributedDemandGenerator( int numberOfForerunPeriods, int offSet) { if (numberOfForerunPeriods < 0 || offSet < 0) throw new IllegalArgumentException(); this.forerun = numberOfForerunPeriods; this.offSet = offSet; }
2
@Override public void mouseClicked(MouseEvent click) { for (int j = 0; j < components.getLength(); j++) { Componente component = components.get(j); if (component.contains(click.getPoint())) { if (SwingUtilities.isLeftMouseButton(click)) { if (component.isIn()) { boolean value = component.changeDigitalValue(); listener.actionPerformed(new ActionEvent(this, SET_INOUT, component.getReference() + "#" + value)); } } if (SwingUtilities.isRightMouseButton(click)) { deleteComponent(j); } } } }
5
private static void writeTableAssignmentByTable(String fileName) { EasyWriter tableByTable = new EasyWriter(fileName + "_byTable.txt"); // "table_assignment_by_table.txt"); if (tableByTable.bad()) { System.err.println("Error creating " + fileName + "_byTable.txt\n"); } for (int i = 0; i < DiningRoom.size(); i++) { Table thisTable = new Table((Table) DiningRoom.get(i)); // if ( i > 6 ) // tableByTable.print("[" + (i+3) + "] " ); // else tableByTable.print("[" + (i + 1) + "] "); tableByTable.print(((Table) DiningRoom.get(i)).getTableName() + "\n"); tableByTable.print("------------------------------\n"); tableByTable.print("\n"); for (int j = 0; j < ((Table) DiningRoom.get(i)).getIDList().size(); j++) { Student thisKid = (Student) Students .get(getIndexOfStu((String) thisTable.getIDList() .get(j))); tableByTable.print(thisKid.getfName() + " " + thisKid.getlName() + "\n"); } tableByTable.print("\n\n\n\n"); } tableByTable.close(); }
3
private String currentCategory() { if (places[currentPlayer] == 0) return "Pop"; if (places[currentPlayer] == 4) return "Pop"; if (places[currentPlayer] == 8) return "Pop"; if (places[currentPlayer] == 1) return "Science"; if (places[currentPlayer] == 5) return "Science"; if (places[currentPlayer] == 9) return "Science"; if (places[currentPlayer] == 2) return "Sports"; if (places[currentPlayer] == 6) return "Sports"; if (places[currentPlayer] == 10) return "Sports"; return "Rock"; }
9