text
stringlengths
14
410k
label
int32
0
9
public void setLastName(String lastName) { this.lastName = lastName; }
0
public void doDamage(Enemy e) { //isSplitting added for debug purposes if (Math.random()<0.1 || isSplitting()) { setSplit(false); Enemy newEnemy; try { newEnemy = e.getClass().newInstance(); newEnemy.setActionListener(listener); e.getRoad().enter(newEnemy); newEnemy.setHP(e.getHP()/2); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } } else e.lowerHP(power); }
4
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("ar") || cmd.getName().equalsIgnoreCase("antirelog") || cmd.getName().equalsIgnoreCase("arl")) { if (args.length == 1) { if (args[0].equalsIgnoreCase("t") || args[0].equalsIgnoreCase("time")) { if (playerCheck(sender)) { getRemainingTime(player); } } else { unknownCommand(sender); } } else { unknownCommand(sender); } } return true; }
8
public String getRosterNames() { if ((trip == null) || (trip.getRosterCount() == 0)) { return "<?>"; } String r =""; for (int i = 0; i < trip.getRosterCount(); i++) { if (i > 0) r = r + ", "; r = r + trip.getRosterName(i); } return r; }
4
public void selectPosition(int position, char playerToken) { // Select the position switch (position){ case 1: this.setPosition(0,0, playerToken); break; case 2: this.setPosition(0,1, playerToken); break; case 3: this.setPosition(0,2, playerToken); break; case 4: this.setPosition(1,0, playerToken); break; case 5: this.setPosition(1,1, playerToken); break; case 6: this.setPosition(1,2, playerToken); break; case 7: this.setPosition(2,0, playerToken); break; case 8: this.setPosition(2,1, playerToken); break; case 9: this.setPosition(2,2, playerToken); break; default: error("Error: TicTacToeBoard.selectPosition()\nPosition selected out of range 1 - 9."); System.out.println("Position selected: " + position + "\n"); break; } // end switch }
9
@Override public Object getValue() { Name n = getName(); try { Ptg[] p = n.getCellRangePtgs(); if( p.length == 0 ) { return new String( "#NAME?" ); } if( (p.length == 1) || !(parent_rec instanceof Array) ) { // usual case return p[0].getValue(); } // multiple values; create an array String retarry = ""; for( Ptg aP : p ) { retarry = retarry + aP.getValue() + ","; } retarry = "{" + retarry.substring( 0, retarry.length() - 1 ) + "}"; PtgArray pa = new PtgArray(); pa.setVal( retarry ); return pa; } catch( Exception e ) { } ; // String s = n.getName(); //return n; return new String( "#NAME?" ); }
5
public void archiveResponse(Data data) { synchronized (this) { // aus den Daten das byte-Array anfordern. In dem Array sind die Informationen, // ob die Infoanfrage geklappt hat, gespeichert byte[] requestInfoResponse = data.getUnscaledArray("daten").getByteArray(); InputStream in = new ByteArrayInputStream(requestInfoResponse); //deserialisieren Deserializer deserializer = SerializingFactory.createDeserializer(in); // Das erste byte bestimmt, ob die Anfrage geklappt hat. 0 = nein; 1 = ja try { final byte requestSuccessfulFlag = deserializer.readByte(); if (requestSuccessfulFlag == 0) { _requestSuccessful = false; } else { _requestSuccessful = true; } if (_requestSuccessful == true) { // Die Infoanfrage konnte bearbeitet werden // Das Antwortobjekt erzeugen // Der erste Wert ist ein int, er bestimmt wieviele Objekte serialisiert wurde final int numberOfData = deserializer.readInt(); for (int nr = 0; nr < numberOfData; nr++) { //Folgende Werte werden eingelesen // 1) intervalStart (long) // 2) intervalEnd (long) // 3) timingType (byte) // 4) isDataGap (byte) // 5) directAccess (byte) // 6) volumeId (int) // 7) Zeiger auf ArchiveDataSpecification Eintrag (int) final long intervalStart = deserializer.readLong(); final long intervalEnd = deserializer.readLong(); final byte byteTimingType = deserializer.readByte(); final TimingType timingType; if (byteTimingType == 1) { timingType = TimingType.DATA_TIME; } else if (byteTimingType == 2) { timingType = TimingType.ARCHIVE_TIME; } else { timingType = TimingType.DATA_INDEX; } final byte byteDataGap = deserializer.readByte(); final boolean dataGap; if (byteDataGap == 0) { dataGap = false; } else { dataGap = true; } final byte byteDirectAccess = deserializer.readByte(); final boolean directAccess; if (byteDirectAccess == 0) { directAccess = false; } else { directAccess = true; } final int volumeId = deserializer.readInt(); // Die ArchiveDataSpec werden nicht übertragen, sondern nur ein Index auf welche ArchiveDataSpec // sich diese antwort bezieht, somit kann aus der Liste der ArchiveDataSpecs der richtige // ausgewählt werden. final int pointerArchiveDataSpec = deserializer.readInt(); // Es wurden alle Infos eingelesen um ein ArchiveInformationResult Objekt zu erzeugen ArchiveInformationResult archiveInformationResult = new ArchiveInfoResult(intervalStart, intervalEnd, timingType, dataGap, directAccess, volumeId, _specs.get(pointerArchiveDataSpec)); // Ergebnisliste _archiveInformationResults.add(archiveInformationResult); } // for } else { // Die Anfrage hat nicht funktioniert, den Fehler auslesen _errorMessage = deserializer.readString(); } } catch (IOException e) { e.printStackTrace(); } _lock = false; this.notifyAll(); } }
8
@Override public void setPathShape( PathShape shape ) { if( shape == null ) { throw new IllegalArgumentException( "shape must not be null" ); } this.path = shape; }
1
public void start() { init(); RenderUtil.initGraphics(); window.setIcon(); if(isRunning) return; run(); }
1
public static void main(final String[] args) { /* Just go up to a million for testing sake */ int max = 1000000; int exponentMax = 100; List<Integer> list = new ArrayList<Integer>(); List<Integer> otherList = new ArrayList<Integer>(); for (int i = 3; i < max; i += 2) { otherList.add(i); System.out.println(i + "/" + max); for (int e = 1; e < exponentMax; e++) { int possiblePrime = i - twiceSquare(e); if (possiblePrime < 0) { break; } if (Utils.isPrime(possiblePrime) && (possiblePrime + twiceSquare(e) == i)) { // System.out.println(i + " = " + possiblePrime + " + 2x" + e + "^2"); list.add(i); continue; } else { if (!list.contains(i)) { // System.out.println(i + " DOES NOT EQUAL " + possiblePrime + " + 2x" + e + "^2"); //break mainForLoop; } } } } if (list.removeAll(otherList)) ; uptime(); }
7
public void update() { if (health <= 0) { dead = true; if (Player.target == this) Player.target = null; deathTimer(); return; } if (!frozen) { anim++; if (anim % 100 == 0) { move = random.nextInt(5); // Comment to freeze movement anim = random.nextInt(50); // Comment to freeze movement } } else { move = 4; freezeTime++; if (freezeTime == freezeCap) { frozen = false; } } xa = 0; ya = 0; checkMove(distance); if (xa != 0 || ya != 0) { move(xa, ya); } if (hit) { healthTimer(); } }
8
public static void runResultView(){ frames.runResultView(); frames.getResultView().setVisible(true); }
0
public void remover(InstituicaoCooperadora instituicaocooperadora) throws Exception { String sql = "DELETE FROM instituicaocooperadora WHERE id = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setLong(1, instituicaocooperadora.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } }
1
@Override public boolean equals(Object object){ if(this.x == ((DCoord)object).x && this.y == ((DCoord)object).y) return true; else return false; }
2
public int getPlayCount(int player_id) { PreparedStatement pst = null; ResultSet rs = null; try { pst = conn.prepareStatement("SELECT times_played FROM ffa_leaderboards WHERE player_id=?"); pst.setInt(1, player_id); rs = pst.executeQuery(); while (rs.next()) { return rs.getInt("times_played"); } } catch (SQLException ex) { } finally { if (pst != null) { try { pst.close(); } catch (SQLException ex) { } } if (rs != null) { try { rs.close(); } catch (SQLException ex) { } } } return 0; }
6
@Override protected void onPrivateMessage(String sender, String login, String hostname, String message) { if (!message.startsWith("USERCOLOR") && !message.startsWith("EMOTESET") && !message.startsWith("SPECIALUSER") && !message.startsWith("HISTORYEND") && !message.startsWith("CLEARCHAT") && !message.startsWith("Your color")) LOGGER_D.debug("RB PM: " + sender + " " + message); Matcher m = banNoticePattern.matcher(message); if (m.matches()) { String channel = "#" + m.group(1); BotManager.getInstance().log("SB: Detected ban in " + channel + ". Parting.."); BotManager.getInstance().removeChannel(channel); } m = toNoticePattern.matcher(message); if (m.matches()) { String channel = "#" + m.group(1); BotManager.getInstance().log("SB: Detected timeout in " + channel + ". Parting.."); BotManager.getInstance().removeChannel(channel); } }
8
public int max(int hori, int verti, int dia) { if (hori >= verti && hori >= dia && hori >= 0) { return hori; } else if (verti >= hori && verti >= dia && verti >= 0) { return verti; } else if (dia >= hori && dia >= verti && dia >= 0) { return dia; } else { return 0; } }
9
Fraction findFrction(double x) { boolean negative = false; if (x < 0) { negative = true; x = -x; } double max = 1d; double tmp = x; while ((long) tmp != tmp) { // still has decimal part max *= 10; tmp = x * max; } // denominator minimization via iterative division algorithm long i = (long) tmp, j = (long) max; while (i > 0 && j > 0) { if (i >= j) i %= j; else j %= i; } long factor = Math.max(i, j); return new Fraction((negative ? -1 : 1) * (int) (tmp / factor), (int) (max / factor)); }
6
private void checkRandom(){ int min=100,max=0,total=0; for(int i = 0; i <10000; ++i){ int x = (int) (Math.random()*100); if(min>x) min = x; if(max<x) max = x; total+=x; } System.out.println("Min: "+ min +"Mean: " + (total/10000) +" Max: "+ max + " Total: " + total); }
3
public void readFromXMLPartialByClass(XMLStreamReader in, Class<?> theClass) throws XMLStreamException { int n = in.getAttributeCount(); setId(in.getAttributeValue(null, ID_ATTRIBUTE)); for (int i = 0; i < n; i++) { String name = in.getAttributeLocalName(i); if (name.equals(ID_ATTRIBUTE) || name.equals(PARTIAL_ATTRIBUTE)) continue; try { Introspector intro = new Introspector(theClass, name); intro.setter(this, in.getAttributeValue(i)); } catch (IllegalArgumentException e) { logger.warning("Could not set field " + name + ": " + e.toString()); } } while (in.nextTag() != XMLStreamConstants.END_ELEMENT); }
6
public void Solve() { ArrayList<Long> pentagonals = new ArrayList<Long>(); for (int n = 1; n < _max; n++) { long pentagonal = n * (3 * n - 1) / 2; if (pentagonal < 0) { throw new RuntimeException("Overflow for n=" + n); } pentagonals.add(pentagonal); } long d = Long.MAX_VALUE; for (int i = 0; i < pentagonals.size(); i++) { for (int j = i + 1; j < pentagonals.size(); j++) { long sum = pentagonals.get(i) + pentagonals.get(j); if (0 <= Collections.binarySearch(pentagonals, sum)) { long difference = pentagonals.get(j) - pentagonals.get(i); if (0 <= Collections.binarySearch(pentagonals, difference)) { System.out.println("i=" + i + ", j=" + j + ", Pi=" + pentagonals.get(i) + ", Pj=" + pentagonals.get(j)); if (difference < d) { d = difference; System.out.println("Difference=" + d); } } } } } System.out.print("Result=" + d); }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PlayerDescription other = (PlayerDescription) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
7
public void sort(double[] pq) { int N = pq.length; // Create heap structure for (int k = N/2; k >= 1; k--) { sink(pq, k, N); } // Move largest item to end of unsorted section of the array while (N > 1) { Helper.exch(pq, 1-1, --N); sink(pq, 1, N); } }
2
int insertKeyRehash(int val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
private void genererTerrain() { // génération de la grille d'effets (flammes) for (int hauteur = 1; hauteur < grilleJeu.length - 1; hauteur++) { for (int largeur = 1; largeur < grilleJeu[0].length - 1; largeur++) { effets[hauteur][largeur] = 0; } } // generation du millieu du plateau for (int hauteur = 1; hauteur < grilleJeu.length - 1; hauteur++) { for (int largeur = 1; largeur < grilleJeu[0].length - 1; largeur++) { if (Math.random() * 100 > ratio) { grilleJeu[hauteur][largeur] = new Chemin(getImage( imageChemin, 255, 255, 255), largeur, hauteur); } else { grilleJeu[hauteur][largeur] = new Mur_Destructible( getImage(imageMurDestructible, 255, 255, 255), largeur, hauteur); } } } // Generation du tour indéstructible for (int hauteur = 0; hauteur < grilleJeu.length; hauteur++) { grilleJeu[hauteur][0] = new Mur_Indestructible(getImage( imageMurIndestructible, 255, 255, 255), 0, hauteur); grilleJeu[hauteur][14] = new Mur_Indestructible(getImage( imageMurIndestructible, 255, 255, 255), 14, hauteur); } for (int largeur = 0; largeur < grilleJeu[0].length; largeur++) { grilleJeu[0][largeur] = new Mur_Indestructible(getImage( imageMurIndestructible, 255, 255, 255), largeur, 0); grilleJeu[12][largeur] = new Mur_Indestructible(getImage( imageMurIndestructible, 255, 255, 255), largeur, 12); } // Generation des cases indéstructibles au millieu du terrain for (int hauteur = 2; hauteur < grilleJeu.length - 1; hauteur += 2) { for (int largeur = 2; largeur < grilleJeu[0].length - 1; largeur += 2) { grilleJeu[hauteur][largeur] = new Mur_Indestructible(getImage( imageMurIndestructible, 255, 255, 255), largeur, hauteur); } } // Generation du depart des joueurs grilleJeu[1][2] = new Chemin(getImage(imageChemin, 255, 255, 255), 2, 1); grilleJeu[2][1] = new Chemin(getImage(imageChemin, 255, 255, 255), 1, 2); grilleJeu[1][1] = new Chemin(getImage(imageChemin, 255, 255, 255), 1, 1); grilleJeu[11][13] = new Chemin(getImage(imageChemin, 255, 255, 255), 13, 11);/* # */ grilleJeu[11][12] = new Chemin(getImage(imageChemin, 255, 255, 255), 11, 12);/* ## */ grilleJeu[10][13] = new Chemin(getImage(imageChemin, 255, 255, 255), 13, 10); grilleJeu[1][13] = new Chemin(getImage(imageChemin, 255, 255, 255), 13, 1);/* ## */ grilleJeu[1][12] = new Chemin(getImage(imageChemin, 255, 255, 255), 12, 1);/* # */ grilleJeu[2][13] = new Chemin(getImage(imageChemin, 255, 255, 255), 13, 2); grilleJeu[11][1] = new Chemin(getImage(imageChemin, 255, 255, 255), 1, 11);/* # */ grilleJeu[11][2] = new Chemin(getImage(imageChemin, 255, 255, 255), 2, 11);/* ## */ grilleJeu[10][1] = new Chemin(getImage(imageChemin, 255, 255, 255), 1, 10); }
9
public double getCost() { return this.cost; }
0
public int translateEscapeSequence(int[] buffer) { try { if (buffer[0] == LSB) { switch (buffer[1]) { case A: return TerminalIO.UP; case B: return TerminalIO.DOWN; case C: return TerminalIO.RIGHT; case D: return TerminalIO.LEFT; default: break; } } } catch (ArrayIndexOutOfBoundsException e) { return TerminalIO.BYTEMISSING; } return TerminalIO.UNRECOGNIZED; }// translateEscapeSequence
6
public static void multiRun() { System.out.println("alpha: "+alpha); int[] numLocs = {10000};//{1000,2000,5000,10000}; double[] detect = {0.01};//{0.005,0.01,0.02,0.05}; long[] duration = {EpiSimUtil.dayToSeconds(100)};//{EpiSimUtil.dayToSeconds(3),EpiSimUtil.dayToSeconds(7),EpiSimUtil.dayToSeconds(10),EpiSimUtil.dayToSeconds(14)}; int[] numMons = {2000,1000}; for (int numLocsIndex=0; numLocsIndex<numLocs.length; numLocsIndex++) { for (int detectIndex=0; detectIndex<detect.length; detectIndex++) { for (int durationIndex=0; durationIndex<duration.length; durationIndex++) { for (int monIndex=0; monIndex<numMons.length; monIndex++) { MonBuildClose policy = new MonBuildClose(numMons[monIndex], detect[detectIndex],duration[durationIndex],EpiSimUtil.getLocsHighPop(numLocs[numLocsIndex])); // new MonBuildClose(numMons[monIndex], detect[detectIndex],duration[durationIndex],EpiSimUtil.getLocsHighPop(numLocs[numLocsIndex]),new HarmonicAvgLabels()); ArrayList<Policy> policies = new ArrayList<Policy>(); policies.add(policy); DendroReSim sim = new DendroReSim(policies); policy.setMySim(sim); policy.printParams(); int prevNumInf = Integer.MAX_VALUE; int curNumInf = sim.infections.size(); // next two lines for closing populous locations initially int numInitClose = 10; policy.closeLocations(EpiSimUtil.getLocsHighPop(numInitClose).keySet().iterator(), 0); while (sim.curTime < EpiSimUtil.dayToSeconds(100) && curNumInf / prevNumInf < 2) {//sim.infections.size() < 56569) { policy.refreshMonLocs(); sim.stepSim(); prevNumInf = curNumInf; curNumInf = sim.infections.size(); if (policy.numMonitors != 0) policy.numMonitorDays += policy.numMonitors; policy.printCumStats(sim); policy.printMonStats(); policy.printWeightStats(); // System.out.println("Day "+EpiSimUtil.secondsToDays(sim.curTime)+"\tnumNonZero\t"+numNonZero); numNonZero = 0; } } } } } }
7
private double[][] createEmptyValueGrid(GeoParams geoParams, Operator operator) { double delta_y = Math.abs(geoParams.geoBoundNW.latitude - geoParams.geoBoundSE.latitude); double delta_x; if (geoParams.geoBoundNW.longitude > geoParams.geoBoundSE.longitude) { //We've wrapped around from 180 to -180, delta_x = 360-(geoParams.geoBoundNW.longitude+geoParams.geoBoundSE.longitude); } else { delta_x = Math.abs(geoParams.geoBoundNW.longitude - geoParams.geoBoundSE.longitude); } int x_width = (int) Math.round(delta_x/geoParams.geoResolutionX); int y_width = (int) Math.round(delta_y/geoParams.geoResolutionY); double[][] valueGrid = new double[x_width][y_width]; if (operator.equals(Operator.MAX)) { for (int i=0; i<x_width; i++) { Arrays.fill(valueGrid[i], Integer.MIN_VALUE); } } if (operator.equals(Operator.MIN)) { for (int i=0; i<x_width; i++) { Arrays.fill(valueGrid[i], Integer.MAX_VALUE); } } return valueGrid; }
5
private double getAxisVal(int loc) { switch(loc){ case 0: case 7: return -1; case 1: case 6: return -.5; case 2: case 5: return .5; case 3: case 4: return 2; default: return 0; } }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final VtDataAck other = (VtDataAck) obj; if (acceptedOctetCount == null) { if (other.acceptedOctetCount != null) return false; } else if (!acceptedOctetCount.equals(other.acceptedOctetCount)) return false; if (allNewDataAccepted == null) { if (other.allNewDataAccepted != null) return false; } else if (!allNewDataAccepted.equals(other.allNewDataAccepted)) return false; return true; }
9
public void updateScores(int result) { if (result == 0) { scores.incrementTie(); } if (result == -1) { scores.incrementLoss(); } if (result == 1) { scores.incrementWin(); } }
3
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) { setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedById__typeInfo)) { setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) { setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Field__typeInfo)) { setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, NewValue__typeInfo)) { setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, OldValue__typeInfo)) { setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Site__typeInfo)) { setSite((com.sforce.soap.enterprise.sobject.Site)__typeMapper.readObject(__in, Site__typeInfo, com.sforce.soap.enterprise.sobject.Site.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, SiteId__typeInfo)) { setSiteId(__typeMapper.readString(__in, SiteId__typeInfo, java.lang.String.class)); } }
9
public final void silence_statement_list(SS_scriptset scriptset) throws RecognitionException { try { // SayScript.g:513:48: ( ( silence_statement[scriptset] )+ ) // SayScript.g:513:50: ( silence_statement[scriptset] )+ { // SayScript.g:513:50: ( silence_statement[scriptset] )+ int cnt42=0; loop42: while (true) { int alt42=2; int LA42_0 = input.LA(1); if ( (LA42_0==WHITE) ) { int LA42_2 = input.LA(2); if ( (LA42_2==ID) ) { alt42=1; } } else if ( (LA42_0==ID) ) { alt42=1; } switch (alt42) { case 1 : // SayScript.g:513:50: silence_statement[scriptset] { pushFollow(FOLLOW_silence_statement_in_silence_statement_list2963); silence_statement(scriptset); state._fsp--; } break; default : if ( cnt42 >= 1 ) break loop42; EarlyExitException eee = new EarlyExitException(42, input); throw eee; } cnt42++; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } }
7
public static Set<Month> getMonthBySeason(Season season) { Set<Month> months = new HashSet<Month>(); switch (season) { case SUMMER: { months.add(Month.JUN); months.add(Month.JUL); months.add(Month.AUG); break; } case AUTUMN: { months.add(Month.SEPT); months.add(Month.OCT); months.add(Month.NOV); break; } case WINTER: { months.add(Month.DEC); months.add(Month.JAN); months.add(Month.FEB); break; } case SPING: { months.add(Month.MAR); months.add(Month.APR); months.add(Month.MAY); break; } } return months; }
4
public void guardarArchivoOrigen() { byte c[]; try { clsEnKardex[] arreglo1; arreglo1=lista.toArray(arreglo); FileOutputStream file=new FileOutputStream("kardex.txt"); String n="~"; c=n.getBytes(); file.write(c); arreglo1=lista.toArray(arreglo1); for(int i=0;i<lista.size();i++) { String cadena="idka:"+arreglo1[i].getIntidkard()+"*idpr:"+arreglo1[i].getIntidpord()+"*fech:"+arreglo1[i].getFecha()+"*saen:"+arreglo1[i].getSaldoantentrada()+"*sasa:"+arreglo1[i].getSaldoantsalida()+"*~"; c=cadena.getBytes(); file.write(c); } file.close(); } catch(FileNotFoundException e) { System.out.println("Se creara un nuevo registro debido a que el anterior no existe o esta ilegible."); crearArchivoOrigen(); } catch(IOException e) { System.out.println("No se pudo crear el archivo de articulos, saliendo"); System.exit(0); } }
3
@Override public void addPatient(Patient patient)throws Exception { // Get JDBC Connection Connection conn= JDBCManager.getConnection(); PreparedStatement stmt=null; String sql="INSERT INTO Patient "+ "(HealthRecordNumber,FirstName,LastName,Gender,Age) VALUES "+ "(?,?,?,?,?)"; try { stmt=conn.prepareStatement(sql); //Extract patient informations and set to Prepared Statement stmt.setInt(1, patient.getHealthRecNo()); stmt.setString(2, patient.getFirstName()); stmt.setString(3, patient.getLastName()); stmt.setString(4, patient.getGender()); stmt.setInt(5, patient.getAge()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } finally { // Closing the connections if(stmt!=null){ stmt.close(); } if(conn!=null){ conn.close(); } } }
3
public void getTwitterTimeline() { try { Twitter twitter = new TwitterFactory().getInstance(); try { RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; accessToken = new AccessToken("36063580-4ct4i8XBLnT1i7CcoLEPSyx0JofWXLWvA9XsuJraa", "HwC4qx8u0gLDcXlIUOEuw54JFYAsB0LKSVDmV4xy6KF2H"); twitter.setOAuthAccessToken(accessToken); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set. " + ie.getMessage()); System.exit(-1); } } List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing home timeline."); for (Status status : statuses) { System.out.println(status.getUser().getName() + ":" + status.getText()); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }
9
final public BigDecimal Primary() throws ParseException { Token t ; BigDecimal d ; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NUMBER: t = jj_consume_token(NUMBER); {if (true) return new BigDecimal( t.image ) ;} break; case OPEN_PAR: jj_consume_token(OPEN_PAR); d = Expression(); jj_consume_token(CLOSE_PAR); {if (true) return d ;} break; case MINUS: jj_consume_token(MINUS); d = Primary(); {if (true) return d.negate() ;} break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); }
7
public void visitCheckExpr(final CheckExpr expr) { if (expr instanceof ZeroCheckExpr) { visitZeroCheckExpr((ZeroCheckExpr) expr); } else if (expr instanceof RCExpr) { visitRCExpr((RCExpr) expr); } else if (expr instanceof UCExpr) { visitUCExpr((UCExpr) expr); } }
3
public static ArrayList<File> GetAllFiles(String src, String ext, boolean recurse) { ArrayList<File> ret_files = new ArrayList<File>(); File[] files = new File(src).listFiles(); for (File f : files) { if (f.isDirectory()) { if (recurse) ret_files.addAll(GetAllFiles(f.getPath(), ext, recurse)); } else { if (ext == null || f.toString().endsWith(ext)) ret_files.add(f); } } return ret_files; }
5
public void generateParenthesisDFS(int left, int right, String s) { if(right < left) return; if(left == 0 && right == 0){ res.add(s); } if(left > 0){ generateParenthesisDFS(left - 1, right, s + "("); } if(right > 0){ generateParenthesisDFS(left, right - 1, s + ")"); } }
5
public void damage(int amt) { if(state == STATE_IDLE) state = STATE_CHASE; health -= amt; if(health > 0) AudioUtil.playAudio(hitNoise, transform.getPosition().sub(Transform.getCamera().getPos()).length()); }
2
public static void main(String... args) { Scanner s = new Scanner("Hello my love"); String token; do { token = s.findInLine(""); System.out.print(token + " "); } while (token != null); }
1
public Hand(Deck d) { ArrayList<Card> Import = new ArrayList<Card>(); for (int x = 0; x < 5; x++) { Import.add(d.drawFromDeck()); } CardsInHand = Import; }
1
public static String[] getTokensUsingDelim( String instr, String token ) { if( instr.indexOf( token ) < 0 ) { String[] ret = new String[1]; ret[0] = instr; return ret; } CompatibleVector output = new CompatibleVector(); new StringBuffer(); int lastpos = 0; int offset = 0; int toklen = token.length(); int pos = instr.indexOf( token ); // pos--; while( pos > -1 ) { if( lastpos > 0 )// if the line starts with a token { offset = lastpos + toklen; } else { offset = 0; } String st = instr.substring( offset, pos ); output.add( st ); lastpos = pos; pos = instr.indexOf( token, lastpos + 1 ); } if( lastpos < instr.length() ) { String st = instr.substring( lastpos + toklen ); output.add( st ); } String[] retval = new String[output.size()]; for( int i = 0; i < output.size(); i++ ) { retval[i] = (String) output.get( i ); } return retval; }
5
private void drawNumbers(Graphics2D g2d) { for (int i=0; i<width; i++) { for (int j=0; j<height; j++) { if (numbers[i][j] >= 0) { if (black [i][j] == null || !black[i][j]) { g2d.setColor(Color.black); } else { g2d.setColor(Color.white); } g2d.drawString("" + numbers[i][j], i*SIZE + SIZE/2 - FONTSIZE/3, j*SIZE + SIZE/2 + FONTSIZE/2 - 1); } } } }
5
public String findAlgorithm(Cube cube, TileColor c1, TileColor c2) { int rotation = 4 - (c1.getInt() < 3 ? c1.getInt() - 1 : c1.getInt() - 2); String top = ""; for (int k = 0; k < 4; k++) { for (int i = 1; i < F2L.length; i++) { String alg = F2L[i]; Cube cubeClone = cube.clone(); for (int j = 0; j < rotation; j++) alg = Cube.rotateAlgorithm(alg); cubeClone.doAlgorithm(alg); if (isCorrect(cubeClone, c1, c2)) { cube.doAlgorithm(alg); return top + alg; } } top += "U,"; cube.turn(Turn.U); } return ""; }
5
public void setDataRegistrazione(Date dataRegistrazione) { this.dataRegistrazione = dataRegistrazione; }
0
public static void main(String[] args) { // args[0] = -d is for debug, -r is for running if (args.length == 0 || args[0].equals("-r")) { runState = runStates.RUN; } else if (args[0].equals("-d")) { runState = runStates.DEBUG; } switch (runState) { case DEBUG: log("Running in DEBUG mode."); gen = new Random(0); break; case RUN: log("Running in RUN mode."); gen = new Random(); break; case TEST: log("Running in TEST mode."); break; default: log("Running in RUN mode."); gen = new Random(); break; } GameManager gm = new LGameManager(); lp = new Letterpress(gm); red = new GreedyPlayer(); blue = new WeightedGreedyPlayer(); lp.assignPlayer(red); lp.assignPlayer(blue); gm.run(); }
6
public void run() { if(this.sampleSize==-1) { this.TGA(); } else { String arr[] = this.outputFilename.split("\\.(?=[^\\.]+$)"); double n = this.sampleSize; double sum = 0; double sum2 = 0; double prom = 0; double var = 0; double v; Genotipo best = null; Genotipo worst = null; Genotipo g; for(int i=1; i<=this.sampleSize; i++) { this.outputFilename = String.format("%s_%d.%s", arr[0], i, arr[1]); g = this.TGA(); v = g.getFitnessValue(); sum += v; sum2 += v*v; if(i==1) { best = g; worst = g; } if(comp.compare(g, best) < 0) { best = g; } if(comp.compare(g, worst) > 0) { worst = g; } } //calculamos prom = sum/n; var = 1/(n-1)*(sum2 - n*prom*prom); //imprimimos PrintWriter pw; try { pw = new PrintWriter( new File( String.format("%s_%s.%s", arr[0], "stat", arr[1]))); pw.println("TGA - eliTist Genetic Algorithm"); pw.printf("\"Funcion\", %s\n", "\"" +func.toString() +"\""); pw.printf("\"Promedio\", %f\n", prom); pw.printf("\"Varianza\", %f\n", var); pw.printf("\"Desv.Est\", %f\n", Math.sqrt(var)); pw.printf("\"Mejor Fitness\", %f\n", best.getFitnessValue()); pw.printf("\"Mejor Genoma\", %s\n", func.getFenotipo(best)); pw.printf("\"Peor Fitness\", %f\n", worst.getFitnessValue()); pw.printf("\"Peor Genoma\", %s\n", func.getFenotipo(worst)); pw.close(); } catch(Exception e) { System.err.println("Hubo un error al abrir el " + "archivo de salida de estadisticas"); System.exit(1); } } }
6
public static void setCellStyleFlags(mxIGraphModel model, Object[] cells, String key, int flag, Boolean value) { if (cells != null && cells.length > 0) { model.beginUpdate(); try { for (int i = 0; i < cells.length; i++) { if (cells[i] != null) { String style = setStyleFlag(model.getStyle(cells[i]), key, flag, value); model.setStyle(cells[i], style); } } } finally { model.endUpdate(); } } }
4
public static int posteX(int travee,int orientation){ int centreX = centrePositionX(travee) ; switch(orientation){ case Orientation.NORD : centreX -= 25 ; break ; case Orientation.EST : break ; case Orientation.SUD : centreX -= 25 ; break ; case Orientation.OUEST : centreX -= 20 ; break ; } return centreX ; }
4
public int getWidth() { return width; }
0
public void playGame(Agent player1, Agent player2) { GameAction p1move, p2move; GameAction[] history = new GameAction[roundsPerGame*2]; player1.matchScore = 0; player2.matchScore = 0; for(int i = 0; i < roundsPerGame; i++) { p1move = player1.getNextMove(i, history, false); p2move = player2.getNextMove(i, history, true); history[2*i] = p1move; history[2*i+1] = p2move; if(p1move == GameAction.COOPERATE && p2move == GameAction.COOPERATE) { //System.out.println("Both cooperated"); player1.giveScore(mutualCooperationScore); player2.giveScore(mutualCooperationScore); } else if(p1move == GameAction.COOPERATE && p2move == GameAction.DEFECT) { player1.giveScore(loseScore); player2.giveScore(winScore); } else if(p1move == GameAction.DEFECT && p2move == GameAction.COOPERATE) { player1.giveScore(winScore); player2.giveScore(loseScore); } else if(p1move == GameAction.DEFECT && p2move == GameAction.DEFECT) { player1.giveScore(mutualDefectionScore); player2.giveScore(mutualDefectionScore); } } }
9
public static Complex log(final Complex value) { if (value == null) throw new NullPointerException("The value is not properly specified."); if (isNaN(value) || isInfinite(value)) return Complex.NaN; if (isOrigin(value)) return Complex.Infinity; double real = Math.abs(value.getModulus() - 1.0) < 0.1 ? Math.log1p(value.getModulus() - 1.0) : Math.log(value.getModulus()); return Complex.Cartesian(real, value.getArgument()); }
5
private boolean validateValues(String column, String value) throws MobbedException { String type = typeMap.get(column.toLowerCase()); try { if (type.equalsIgnoreCase("uuid")) UUID.fromString(value); else if (type.equalsIgnoreCase("integer")) Integer.parseInt(value); else if (type.equalsIgnoreCase("bigint")) Long.parseLong(value); else if (type.equalsIgnoreCase("timestamp without time zone")) Timestamp.valueOf(value); } catch (Exception ex) { throw new MobbedException("Invalid type, column: " + column + " value: " + value); } return true; }
5
public static void main(String[] args) { Tank t1 = new Tank(); Tank t2 = new Tank(); t1.level = 9; t2.level = 47; System.out.println("1: t1.level: " + t1.level + ", t2.level: " + t2.level); t1 = t2; System.out.println("2: t1.level: " + t1.level + ", t2.level: " + t2.level); t1.level = 27; System.out.println("3: t1.level: " + t1.level + ", t2.level: " + t2.level); }
0
@Override public List<Map<String, ?>> Listar_hist_fecha(String FE_MODIF, String idtra) { List<Map<String, ?>> lista = new ArrayList<Map<String, ?>>(); try { this.cnn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE); String sql = "SELECT * FROM RHVD_MOD_TRABAJADOR \n" + "WHERE ID_TRABAJADOR='" + idtra + "' AND\n" + " fe_modif= '" + FE_MODIF + "'\n" + " and rownum=1"; ResultSet rs = this.cnn.query(sql); if (rs.next()) { Map<String, Object> rec = new HashMap<String, Object>(); for (int i = 1; i < 75; i++) { if (rs.getString(i) == null) { rec.put("col" + i, "SIN DATOS"); } else { rec.put("col" + i, rs.getString(i)); } } lista.add(rec); } rs.close(); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException("ERROR"); } finally { try { this.cnn.close(); } catch (Exception e) { } } return lista; }
9
private void chooseBrainActionPerformed(java.awt.event.ActionEvent evt) throws Exception { AntBrain b = new AntBrain(chooseBrain.getSelectedFile().getName()); brains.add(b); numBrainsLabel.setText("Number of Brains(2 Minimum): " + brains.size()); }
0
private int laskeMiinat(int x, int y){ int miinoja = 0; int yla = y - 1; int ala = y + 1; int vasen = x - 1; int oikea = x + 1; if (onKartallaJaMiina(vasen, yla)) { miinoja++; } if (onKartallaJaMiina(x, yla)) { miinoja++; } if (onKartallaJaMiina(oikea, yla)) { miinoja++; } if (onKartallaJaMiina(vasen, y)) { miinoja++; } if (onKartallaJaMiina(oikea, y)) { miinoja++; } if (onKartallaJaMiina(vasen, ala)) { miinoja++; } if (onKartallaJaMiina(x, ala)) { miinoja++; } if (onKartallaJaMiina(oikea, ala)) { miinoja++; } return miinoja; }
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto, asLevel)) return false; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> speak(s) and gesture(s) to <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> seem(s) too hideous to look at!")); maliciousAffect(mob,target,asLevel,0,-1); } } else return beneficialVisualFizzle(mob,target,L("<S-NAME> incant(s) harshly to <T-NAMESELF>, but nothing more happens.")); // return whether it worked return success; }
8
static final void method1230(int i) { anInt1517++; FileOnDisk fileondisk = null; try { Class241 class241 = Class240.aSignLink2946.method3631(true, "2", (byte) 126); while (class241.anInt2953 == 0) Class262_Sub22.method3208(1L, false); if ((class241.anInt2953 ^ 0xffffffff) == -2) { fileondisk = (FileOnDisk) class241.anObject2956; byte[] bs = new byte[(int) fileondisk.method1101(0)]; int i_1_; for (int i_2_ = 0; i_2_ < bs.length; i_2_ += i_1_) { i_1_ = fileondisk.method1103((byte) -115, bs.length - i_2_, bs, i_2_); if (i_1_ == -1) { throw new IOException("EOF"); } } CacheNode_Sub14_Sub2.method2353((byte) -42, new BufferedStream(bs)); } } catch (Exception exception) { /* empty */ } if (i > 117) { do { try { if (fileondisk == null) { break; } fileondisk.method1098(true); } catch (Exception exception) { break; } break; } while (false); } }
9
@Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { Person person = listPerson.get(rowIndex); switch (columnIndex) { case 0: person.setId(Integer.parseInt((String) aValue)); break; case 1: person.setFirstName((String) aValue); break; case 2: person.setLastName((String) aValue); break; case 3: person.setAge(Integer.parseInt((String) aValue)); break; case 4: if(person.getAddressList().size()==0){ Address address = new Address(); address.setAdress((String) aValue); address.setPerson(person); person.getAddressList().add(address); } else{ person.getAddressList().get(0).setAdress((String) aValue); } break; case 5: if(person.getPhoneList().size()==0){ Phone phone = new Phone(); phone.setPhone((String) aValue); phone.setPerson(person); person.getPhoneList().add(phone); } else{ person.getPhoneList().get(0).setPhone((String) aValue); } break; default: break; } FromDAO.update(person); }
8
public void show(){ game.getContentPane().removeAll(); menuWrapper.removeAll(); menuPanel.removeAll(); this.prepareSpecificMenu(); this.menuWrapper.add(this.menuPanel); game.add(this.menuWrapper, BorderLayout.CENTER); game.setVisible(true); }
0
public void update(){ up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W]; down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S]; left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A]; right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D]; sprint = keys[KeyEvent.VK_SHIFT]; for(int i=0; i< keys.length; i++){ if(keys[i] == true){ //System.out.println("KEY: " + i); } } }
6
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((((ClanItem)this).clanID().length()>0) &&(CMLib.flags().isGettable(this)) &&(msg.target()==this) &&(owner() instanceof Room)) { final Clan C=CMLib.clans().getClan(clanID()); if((C!=null)&&(C.getDonation().length()>0)) { final Room R=CMLib.map().getRoom(C.getDonation()); if(R==owner()) { CMLib.flags().setGettable(this,false); text(); } } } return super.okMessage(myHost,msg); }
7
public boolean almostEquals(Object obj){ if (this == obj) return true; if (getClass() != obj.getClass()) return false; Fraction other = (Fraction) obj; if (bottom == null) { if (other.bottom != null) return false; } else if (!bottom.equals(other.bottom)) return false; if (top == null) { if (other.top != null) return false; } else if (!top.equals(other.top)) return false; return true; }
8
public final KeyStroke getAccelerator() { Object value = getValue(ACCELERATOR_KEY); return value instanceof KeyStroke ? (KeyStroke) value : null; }
1
public static int scoreForCards( ArrayList<Card> cards ) { int totalScore = 0; for ( Card aCard : cards ) { switch ( aCard.value() ) { case 1: totalScore += 11; break; case 3: totalScore += 10; break; case 10: // S totalScore += 2; break; case 11: // C totalScore += 3; break; case 12: // R totalScore += 4; break; // Ejem Ejem... Sobra? xD default: break; //(bis) } } return totalScore; }
6
public void pysaytaLiike() { this.xSuunta = 0; }
0
public String getCurrentLoanIndex() { Statement stmt = null; int max = 0; try { stmt = con.createStatement(); ResultSet results = stmt.executeQuery("Select * from Loan"); while (results.next()) { String strnum = results.getString("ID"); int intnum = Integer.parseInt(strnum); if (intnum > max) { max = intnum; } } return Integer.toString(max + 1); } catch (SQLException e) { e.printStackTrace(); return null; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
5
private int getClosestMatch(){ int lowestMatchFactorIndex = 0; double lowestMatchFactor = 99999999; for (int i = 0; i < this.log.size(); i++){ if (getMatchFactor(i) < lowestMatchFactor) lowestMatchFactorIndex = i; } return lowestMatchFactorIndex; }
2
private void init(char[][] array) { int size = GameConfiguration.gameConfiguration_SIZE; this.label = new JLabel[size][size]; this.grid.setLayout(new GridLayout(size,size)); this.infos.setLayout(new GridLayout(1,1)); BorderLayout layout = new BorderLayout(); this.setLayout(layout); for (int i=0; i<size; i++) { for (int j=0; j<size; j++) { label[i][j] = new JLabel(Character.toString(array[i][j]),JLabel.CENTER); label[i][j].setBorder(GridView.BLACKLINE); label[i][j].setFont(new Font("Arial",Font.BOLD,15)); label[i][j].setForeground(Color.WHITE); label[i][j].setOpaque(false); label[i][j].setName(String.valueOf(j)+String.valueOf(i)); label[i][j].setBorder(GridView.BLACKLINE); this.grid.add((label[i][j])); } } this.add(this.grid,BorderLayout.CENTER); if(this.action) this.infos.add(new JLabel("Click on the left grid to make a guess",JLabel.CENTER)); else this.infos.add(new JLabel("State of your fleet",JLabel.CENTER)); this.add(this.infos,BorderLayout.SOUTH); }
3
void move() { switch(dir) { case U: y -= Y_SPEED; break; case D: y += Y_SPEED; break; case L: x -= X_SPEED; break; case R: x += Y_SPEED; break; case LU: x -= X_SPEED; y -= Y_SPEED; break; case RU: x += X_SPEED; y -= Y_SPEED; break; case LD: x -= X_SPEED; y += Y_SPEED; break; case RD: x += X_SPEED; y += Y_SPEED; break; default: } }
8
public static void processFlower(Client c) { final int[] coords = new int[2]; coords[0] = c.absX; coords[1] = c.absY; Server.objectHandler.createAnObject(c, -1, coords[0], coords[1]); Server.objectHandler.createAnObject(c, c.randomFlower(), coords[0], coords[1]); c.canWalk = true; if (Region.getClipping(c.getX() - 1, c.getY(), c.heightLevel, -1, 0)) { c.getPA().walkTo(-1, 0); } else if (Region.getClipping(c.getX() + 1, c.getY(), c.heightLevel, 1, 0)) { c.getPA().walkTo(1, 0); } else if (Region.getClipping(c.getX(), c.getY() - 1, c.heightLevel, 0, -1)) { c.getPA().walkTo(0, -1); } else if (Region.getClipping(c.getX(), c.getY() + 1, c.heightLevel, 0, 1)) { c.getPA().walkTo(0, 1); } c.turnPlayerTo(coords[0] + 1, coords[1]); c.sendMessage("You plant a flower!"); CycleEventHandler.getSingleton().addEvent(c, new CycleEvent() { @Override public void execute(CycleEventContainer container) { for (int j = 0; j < Server.playerHandler.players.length; j++) { if (Server.playerHandler.players[j] != null) { Client c = (Client)Server.playerHandler.players[j]; Server.objectHandler.createAnObject(c, -1, coords[0], coords[1]); container.stop(); } } } @Override public void stop() { } }, 100); }
6
@Override public void piirra(Graphics graphics) { graphics.setColor(vari); for (KentallaOlija osa : osat){ osa.piirra(graphics); } if (suojakilpi){ int halkaisija = (int)getSuojakilvenHalkaisija(); graphics.drawOval((int)(this.getX() - halkaisija/2), (int)(this.getY() - halkaisija/2), halkaisija, halkaisija); } piirraKilpienergia(graphics); piirraElinvoima(graphics); }
2
public void updateFK(String table, String nameColumn, int valueColumn, String nameID, int valueID) { try { con = DriverManager.getConnection(url, user, password); String stm = null; stm = "UPDATE " + table + " SET " + nameColumn + " = '" + valueColumn + "' WHERE " + nameID + " = " + valueID; pst = con.prepareStatement(stm); // execute statement me pst.executeUpdate(); } catch (SQLException ex) { Logger lgr = Logger.getLogger(UpdateMethod.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(UpdateMethod.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } }
4
public static InputSource getFromHTTPS(String adresse){ //String result = ""; URL url = null; System.out.println("downloading..."); try{ disableCertificateValidation(); url = new URL(adresse.replace(" ", "%20")); HttpsURLConnection client = (HttpsURLConnection) url.openConnection(); client.setRequestProperty("User-Agent", "Xenos"); client.setRequestProperty("Accept-Encoding", "gzip, deflate"); client.setRequestProperty("Accept", "application/xml"); client.setRequestMethod("GET"); //String line; //BufferedReader rd = new BufferedReader( new InputStreamReader(client.getInputStream())); return new InputSource(client.getURL().openStream()); //while ((line = rd.readLine()) != null){ // result += line; //} } catch (Exception e){ e.printStackTrace(); //TODO: ignore 500 errors return null; } //System.out.println("downloaded"); }
1
protected void onRemoveNoExternalMessages(String channel, String sourceNick, String sourceLogin, String sourceHostname) {}
0
static int[] merge(int[] a, int[] b) { if (a == null) throw new NullPointerException("a is null"); if (b == null) throw new NullPointerException("b is null"); int[] result = new int[a.length + b.length]; // Precondition assert result.length == a.length + b.length : "length mismatch"; for (int i = 0; i < a.length; i++) result[i] = a[i]; for (int i = 0; i < b.length; i++) result[a.length + i - 1] = b[i]; // Postcondition assert containsAll(result, a, b) : "value missing from array"; return result; }
4
public void getMovesFromWord ( Word word, int x, int y, Vector<Move> moves, boolean isUpDownCheck ) { for ( int i = 0 ; i < word.length ( ) ; i++ ) { final int xNew = x - ( isUpDownCheck ? 0 : i ) ; final int yNew = y - ( isUpDownCheck ? i : 0 ) ; if ( xNew >= 0 && yNew >= 0 && xNew < Player.board.boardWidth && yNew < Player.board.boardHeight ) { this.getMovesFromWordPositional ( word, xNew, yNew, moves, isUpDownCheck, x, y ) ; } } }
7
private void compute_pcm_samples0(Obuffer buffer) { final float[] vp = actual_v; //int inc = v_inc; final float[] tmpOut = _tmpOut; int dvp =0; // fat chance of having this loop unroll for( int i=0; i<32; i++) { float pcm_sample; final float[] dp = d16[i]; pcm_sample = (float)(((vp[0 + dvp] * dp[0]) + (vp[15 + dvp] * dp[1]) + (vp[14 + dvp] * dp[2]) + (vp[13 + dvp] * dp[3]) + (vp[12 + dvp] * dp[4]) + (vp[11 + dvp] * dp[5]) + (vp[10 + dvp] * dp[6]) + (vp[9 + dvp] * dp[7]) + (vp[8 + dvp] * dp[8]) + (vp[7 + dvp] * dp[9]) + (vp[6 + dvp] * dp[10]) + (vp[5 + dvp] * dp[11]) + (vp[4 + dvp] * dp[12]) + (vp[3 + dvp] * dp[13]) + (vp[2 + dvp] * dp[14]) + (vp[1 + dvp] * dp[15]) ) * scalefactor); tmpOut[i] = pcm_sample; dvp += 16; } // for }
1
public boolean inside(Bullet b){ if(b.getX()>x && b.getX()<x+WIDTH && b.getY()>y && b.getY()<y+HEIGHT ){ return true; } return false; }
4
private void method130(int arg0, int id, int rotation, int arg3, int y, int objectType, int plane, int x, int arg8) { SceneObject object = null; for (SceneObject sceneObject = (SceneObject) aClass19_1179.getFront(); sceneObject != null; sceneObject = (SceneObject) aClass19_1179.getNext()) { if (sceneObject.anInt1295 != plane || sceneObject.anInt1297 != x || sceneObject.anInt1298 != y || sceneObject.anInt1296 != arg3) { continue; } object = sceneObject; break; } if (object == null) { object = new SceneObject(); object.anInt1295 = plane; object.anInt1296 = arg3; object.anInt1297 = x; object.anInt1298 = y; method89(object); aClass19_1179.insertBack(object); } System.out.println(id + "," + x + "," + y); object.anInt1291 = id; object.anInt1293 = objectType; object.anInt1292 = rotation; object.anInt1302 = arg8; object.anInt1294 = arg0; }
6
public static void main(String[] args) { InetAddress addr = null; try { addr = InetAddress.getByName(DEFAULT_HOST); } catch (UnknownHostException e) { e.printStackTrace(); } int port = DEFAULT_PORT; if (args.length > 0) { try { port = Integer.parseInt(args[0]); if (port < 0 || port >= 65535) { LOGGER.log(Level.SEVERE, "port must between 0 ~ 65535"); return; } } catch (NumberFormatException e) { //use default port } } Socket socket = null; try { socket = new Socket(addr, port); LOGGER.log(Level.INFO, "connected to addr: " + addr + ", tcp: " + socket); Thread readThread = new ReadThread(socket.getInputStream()); readThread.start(); Thread writeThread = new WriteThread(socket.getOutputStream()); writeThread.start(); //wait for input and output complete try { readThread.join(); writeThread.join(); LOGGER.log(Level.INFO, "IO finished, closing tcp..."); socket.close(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { LOGGER.log(Level.SEVERE, "Connection to " + addr + ":" + port + " failed."); // e.printStackTrace(); } finally { try { if (null != socket) socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
9
private static File syncAssets(File assetDir, String indexName) throws JsonSyntaxException, JsonIOException, IOException { Logger.logInfo("Syncing Assets:"); File objects = new File(assetDir, "objects"); AssetIndex index = JsonFactory.loadAssetIndex(new File(assetDir, "indexes/{INDEX}.json".replace("{INDEX}", indexName))); if (!index.virtual) return assetDir; File targetDir = new File(assetDir, "virtual/" + indexName); Set<File> old = FileUtils.listFiles(targetDir); for (Entry<String, Asset> e : index.objects.entrySet()) { Asset asset = e.getValue(); File local = new File(targetDir, e.getKey()); File object = new File(objects, asset.hash.substring(0, 2) + "/" + asset.hash); old.remove(local); if (local.exists() && !DownloadUtils.fileSHA(local).equals(asset.hash)) { Logger.logInfo(" Changed: " + e.getKey()); FileUtils.copyFile(object, local, true); } else if (!local.exists()) { Logger.logInfo(" Added: " + e.getKey()); FileUtils.copyFile(object, local); } } for (File f : old) { String name = f.getAbsolutePath().replace(targetDir.getAbsolutePath(), ""); Logger.logInfo(" Removed: " + name.substring(1)); f.delete(); } return targetDir; }
6
public boolean check_for_zombies() { check(); boolean change=false; Iterator<Entry<String, FileState>> it = m.entrySet().iterator(); while (it.hasNext()) { Entry<String,FileState> pair = it.next(); FileState fs=pair.getValue(); String repo_filename=pair.getKey(); File f = new File(fs.local_filename); //OpenBox.log(0, "Zombie checking "+repo_filename + " " +fs.local_filename + " " +fs); if (!fs.deleted && !f.exists()) { OpenBox.log(0, "ZOMBIE: "+ fs.local_filename); fs.earliest_deleted_time=(new Date()).getTime()-OpenBox.poll_delay; fs.deleted=true; change=true; } if (fs.deleted && f.exists()) { if (fs.earliest_deleted_time<f.lastModified()) { OpenBox.log(0, "Ressurecting a zombie file that should be dead!" + repo_filename); //keep the file! fs.last_modified=f.lastModified(); fs.deleted=false; //if we keep this file we should make sure its parent folders are undeleted File repo_root=new File(repo_path); File parent = f.getParentFile(); try { while(!parent.getCanonicalPath().equals(repo_root.getCanonicalPath())) { String repo_parent_filename=parent.getCanonicalPath().replace(repo_path, ""); if (m.containsKey(repo_parent_filename)) { m.get(repo_parent_filename).deleted=false; } parent=parent.getParentFile(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { //remove the file! OpenBox.log(0, "Removing a zombie file that should be dead!" + repo_filename); f.delete(); } } } check(); return change; }
9
public int getAge() { return age; }
0
protected byte[] computeSHAdigest(final byte[] value) { try { return MessageDigest.getInstance("SHA").digest(value); } catch (Exception e) { throw new UnsupportedOperationException(e.toString()); } }
1
public boolean attack(Spinner self, Spinner target) { if (!newSp.contains(target) || !newSp.contains(self)) { return false; //crappy way of handling concurrency issues } float targetEnergy = target.getEnergy(); float selfEnergy = self.getEnergy(); float energyWager = Math.min(self.getEnergy(), target.getEnergy()); boolean allTargetEnergy = selfEnergy >= targetEnergy; self.setEnergy(selfEnergy + energyWager); target.setEnergy(targetEnergy - energyWager); self.setEnergy(self.getEnergy() * (1f - attackEnergyScale)); globalProperties.addEnergy(attackEnergyScale * self.getEnergy()); if (allTargetEnergy) { newSp.remove(target); return true; } else { return false; } }
3
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frmViewCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmViewCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmViewCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmViewCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmViewCliente().setVisible(true); } }); }
6
public void setHTML(URL url) { // Lazy Instantiation if (!isInitialized()) { initialize(); } try { this.viewer.setPage(url); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); } }
2
public AntAttack() { }
0
private Version mapFrameworkPackageVersion(Version pv) { if (pv.getMajor() != 1) return null; Version version; switch (pv.getMinor()) { case 7: version = new Version(5, 0, 0); break; case 6: version = new Version(4, 3, 0); break; case 5: version = new Version(4, 2, 0); break; case 4: version = new Version(4, 1, 0); break; case 3: version = new Version(4, 0, 0); break; case 2: version = new Version(3, 0, 0); break; case 1: version = new Version(2, 0, 0); break; case 0: version = new Version(1, 0, 0); break; default: version = null; break; } return version; }
9
public boolean onCommand(Player player, String[] args) { File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); if(player.hasPermission(getPermission())){ if(args.length < 2){ String notEnoughArgs = Language.getString("Language.Error.Not_enough_args"); UtilSendMessage.sendMessage(player, notEnoughArgs); return true; } if(args.length > 1){ String arenaName = args[1]; if(ArenaManager.getArenaManager().getArenaByName(arenaName) != null){ if(args[0].equalsIgnoreCase("lives") || args[0].equalsIgnoreCase("points")){ Type type = Type.valueOf(args[0].toUpperCase()); Arena arena = ArenaManager.getArenaManager().getArenaByName(arenaName); arena.setType(type); arena.saveConfig(); String succes = Language.getString("Language.Setup.Type").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, succes); return true; }else{ String badArg = Language.getString("Language.Error.Bad_args"); UtilSendMessage.sendMessage(player, badArg); return true; } }else{ String doesntExist = Language.getString("Language.Error.Arena_does_not_exist").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, doesntExist); return true; } } }else{ String notPerm = Language.getString("Language.Error.Not_permission"); UtilSendMessage.sendMessage(player, notPerm); return true; } return true; }
6
public String getPrettyErrors() { String errors = null; if (hasErrors()) { for (String errorMsg : getErrors()) { errors = errors + errorMsg; } } else { errors = "Unknown"; } return errors; }
2
private EntryElement getEntryElement(final ZipOutputStream zos) { if (outRepresentation == SINGLE_XML) { return new SingleDocElement(zos); } return new ZipEntryElement(zos); }
1
private static void paintTextEffect(Graphics2D g, String s, Color c, int size, double tx, double ty, boolean isShadow) { prepareGraphics(g); final float opacity = 0.8f; // Effect "darkness". final Composite oldComposite = g.getComposite(); final Color oldColor = g.getColor(); // Use a alpha blend smaller than 1 to prevent the effect from becoming // too dark when multiple paints occur on top of each other. float preAlpha = 0.4f; if (oldComposite instanceof AlphaComposite && ((AlphaComposite) oldComposite).getRule() == AlphaComposite.SRC_OVER) { preAlpha = Math.min(((AlphaComposite) oldComposite).getAlpha(), preAlpha); } g.setColor(c); g.translate(tx, ty); // If the effect is a shadow it looks better to stop painting a bit to // early... (shadow will look softer). int maxSize = isShadow ? size - 1 : size; for (int i = -size; i <= maxSize; i++) { for (int j = -size; j <= maxSize; j++) { double distance = i * i + j * j; float alpha = opacity; if (distance > 0.0d) { alpha = (float) (1.0f / ((distance * size) * opacity)); } alpha *= preAlpha; if (alpha > 1.0f) { alpha = 1.0f; } g.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, alpha)); g.drawString(s, i + size, j + size); } } // Restore graphics g.translate(-tx, -ty); g.setComposite(oldComposite); g.setColor(oldColor); g.drawString(s, 0, 0); }
7
public static void countSort (int[] array, int k) { int[] count = new int[k]; int size = array.length; for (int i = 0; i < size; i++) { count[array[i]]++; } for (int i = k - 1; i >= 0; i--) { while (count[i]-- > 0) { array[--size] = i; } } }
3