method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
b1f790d3-e395-47c8-b6e3-13c634b367dc
3
public void saveCustomConfig() { // Return if the configs are null. if (config == null || trueFile == null) { plugin.getLogger().log(Level.SEVERE, "Could not save config to " + trueFile + " due to nulls."); return; } // Attempt to save the files. try { config.save(trueFile); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Could not save config to " + trueFile, ex); } }
1ca369a4-5100-46bd-8f67-59f6bd0314e3
4
public void move(int enemyx, int enemyy){ if(getxCoord() < enemyx+30){ setxCoord(getxCoord() + speed); } if(getxCoord() > enemyx+30){ setxCoord(getxCoord() - speed); } if(getyCoord() < enemyy+80){ setyCoord(getyCoord() + speed); } if(getyCoord() > enemyy+80){ setyCoord(getyCoord() - speed); } }
492aaaea-8895-4e60-8d9b-16d68c8bd4a9
6
public static void createItemAll(int itemID, int itemX, int itemY, int itemAmount, int itemController) { for (Player p : server.playerHandler.players){ if(p != null) { client person = (client)p; if((person.playerName != null || person.playerName != "null") && !(person.playerId == itemController)) { // misc.println("distance to create "+person.distanceToPoint(itemX, itemY)); if (person.distanceToPoint(itemX, itemY) <= 60) { person.createGroundItem(itemID, itemX, itemY, itemAmount); } } } } }
678aa5eb-06e9-40bf-a5fa-a03fd879336f
8
public int find_split(Context cx, Scriptable scope, String target, String separator, Scriptable reObj, int[] ip, int[] matchlen, boolean[] matched, String[][] parensp) { int i = ip[0]; int length = target.length(); int result; int version = cx.getLanguageVersion(); NativeRegExp re = (NativeRegExp) reObj; again: while (true) { // imitating C label /* JS1.2 deviated from Perl by never matching at end of string. */ int ipsave = ip[0]; // reuse ip to save object creation ip[0] = i; Object ret = re.executeRegExp(cx, scope, this, target, ip, NativeRegExp.TEST); if (ret != Boolean.TRUE) { // Mismatch: ensure our caller advances i past end of string. ip[0] = ipsave; matchlen[0] = 1; matched[0] = false; return length; } i = ip[0]; ip[0] = ipsave; matched[0] = true; SubString sep = this.lastMatch; matchlen[0] = sep.length; if (matchlen[0] == 0) { /* * Empty string match: never split on an empty * match at the start of a find_split cycle. Same * rule as for an empty global match in * match_or_replace. */ if (i == ip[0]) { /* * "Bump-along" to avoid sticking at an empty * match, but don't bump past end of string -- * our caller must do that by adding * sep->length to our return value. */ if (i == length) { if (version == Context.VERSION_1_2) { matchlen[0] = 1; result = i; } else result = -1; break; } i++; continue again; // imitating C goto } } // PR_ASSERT((size_t)i >= sep->length); result = i - matchlen[0]; break; } int size = (parens == null) ? 0 : parens.length; parensp[0] = new String[size]; for (int num = 0; num < size; num++) { SubString parsub = getParenSubString(num); parensp[0][num] = parsub.toString(); } return result; }
a16a822b-7dc8-4d0c-abae-afffcf8e9248
5
public void editMakler() { //Menü zum selektieren des Maklers Menu maklerSelectionMenu = new MaklerSelectionMenu("Makler editieren", service.getAllMakler()); int id = maklerSelectionMenu.show(); //Falls nicht "zurück" gewählt, Makler bearbeiten if(id != MaklerSelectionMenu.BACK) { //Makler laden Makler m = service.getMaklerById(id); System.out.println("Makler "+m.getName()+" wird bearbeitet. Leere Felder bleiben unverändert."); //Neue Daten abfragen String new_name = FormUtil.readString("Name ("+m.getName()+")"); String new_address = FormUtil.readString("Adresse ("+m.getAdresse()+")"); String new_login = FormUtil.readString("Login ("+m.getLogin()+")"); String new_password = FormUtil.readString("Passwort ("+m.getPasswort()+")"); //Neue Daten setzen if(!new_name.equals("")) m.setName(new_name); if(!new_address.equals("")) m.setAdresse(new_address); if(!new_login.equals("")) m.setLogin(new_login); if(!new_password.equals("")) m.setPasswort(new_password); service.updateMakler(m); } }
0f7da36b-5e51-42f1-89c4-9369131bf7f2
0
@Override public String getColumnName(int column) { return colNames[column]; }
cbc19429-bb44-417e-ae3a-0f2611c526c3
1
@Override public int getAttributeCount() { if (attributes != null) { return attributes.size(); } return 0; }
750adf32-bb8d-4a83-943f-12f6b0b66fdb
0
public void setDireccion(String direccion) { this.direccion = direccion; }
c7e953eb-87ee-493c-9319-14d49c424000
9
protected ArrayList<Placement> densityMapping(Field[][] map, int c) { shootDensity.clear(); for (int y = 0; y < map.length; ++y) { for (int x = 0; x < map[y].length - shipValue + 1; ++x) { int tmp = 0; for (int z = 0; z < shipValue; ++z) { //tmp = tmp + map[x + z][y].getOppShotTrend(); int tmp2 = map[x + z][y].getOppShotTrend(); if (tmp2 > tmp) { tmp = tmp2; } } Placement temp = new Placement(new Position(x, y), false, tmp); shootDensity.add(temp); } } for (int y = 0; y < map.length - shipValue; ++y) { for (int x = 0; x < map[y].length; ++x) { int tmp = 0; for (int z = 0; z < shipValue; ++z) { //tmp = tmp + map[x][y + z].getOppShotTrend(); int tmp2 = map[x][y + z].getOppShotTrend(); if (tmp2 > tmp) { tmp = tmp2; } } Placement temp = new Placement(new Position(x, y), true, tmp); shootDensity.add(temp); } } if (c > 5) { Collections.sort(shootDensity); } else { Collections.shuffle(shootDensity); } return shootDensity; }
5734d10a-5370-4003-97f8-9f7c1d101980
7
public static CalendarHMS jauD2dtf(final String scale, int ndp, double d1, double d2 ) throws JSOFAIllegalParameter, JSOFAInternalError { boolean leap; int iy1, im1, id1, iy2, im2, id2, ihmsf1[] = new int[4]; double a1, b1, fd, dat0, dat12, dat24, dleap; /* The two-part JD. */ a1 = d1; b1 = d2; /* Provisional calendar date. */ Calendar cal = jauJd2cal(a1, b1); iy1 = cal.iy; im1 = cal.im; id1 = cal.id; fd = cal.fd; /* Is this a leap second day? */ leap = false; if ( scale.equalsIgnoreCase("UTC") ) { /* TAI-UTC at 0h today. */ dat0 = jauDat(iy1, im1, id1, 0.0 ); /* TAI-UTC at 12h today (to detect drift). */ dat12 = jauDat(iy1, im1, id1, 0.5); /* TAI-UTC at 0h tomorrow (to detect jumps). */ cal = jauJd2cal(a1+1.5, b1-fd); iy2 = cal.iy; im2 = cal.im; id2 = cal.id; dat24 = jauDat(iy2, im2, id2, 0.0); /* Any sudden change in TAI-UTC (seconds). */ dleap = dat24 - (2.0*dat12 - dat0); /* If leap second day, scale the fraction of a day into SI. */ leap = (dleap != 0.0); if (leap) fd += fd * dleap/DAYSEC; } jauD2tf ( ndp, fd, ihmsf1 ); /* Has the (rounded) time gone past 24h? */ if ( ihmsf1[0] > 23 ) { /* Yes. We probably need tomorrow's calendar date. */ cal = jauJd2cal(a1+1.5, b1-fd); iy2 = cal.iy; im2 = cal.im; id2 = cal.id; /* Is today a leap second day? */ if ( ! leap ) { /* No. Use 0h tomorrow. */ iy1 = iy2; im1 = im2; id1 = id2; ihmsf1[0] = 0; ihmsf1[1] = 0; ihmsf1[2] = 0; } else { /* Yes. Are we past the leap second itself? */ if ( ihmsf1[2] > 0 ) { /* Yes. Use tomorrow but allow for the leap second. */ iy1 = iy2; im1 = im2; id1 = id2; ihmsf1[0] = 0; ihmsf1[1] = 0; ihmsf1[2] = 0; } else { /* No. Use 23 59 60... today. */ ihmsf1[0] = 23; ihmsf1[1] = 59; ihmsf1[2] = 60; } /* If rounding to 10s or coarser always go up to new day. */ if ( ndp < 0 && ihmsf1[2] == 60 ) { iy1 = iy2; im1 = im2; id1 = id2; ihmsf1[0] = 0; ihmsf1[1] = 0; ihmsf1[2] = 0; } } } /* Results. */ return new CalendarHMS(iy1, im1, id1, ihmsf1); }
4196be7c-2ee2-4861-978c-767c8a05ac05
5
public boolean metodoCompare(Pessoa u ){ if (this.end.equals(u.getEnd()) && this.nome.equals(u.getNome()) && this.login.equals(u.getLogin()) && this.senha.equals(u.getSenha()) &&(this.id.equals(getId()))){ return true; } return false; }
c6a09156-614d-4829-b89b-2d143022987e
9
@Override public void clearSky() { if(!skyedYet) return; final Room skyGridRoom=rawDoors()[Directions.UP]; if(skyGridRoom!=null) { if(((skyGridRoom.roomID()==null)||(skyGridRoom.roomID().length()==0)) &&((skyGridRoom instanceof EndlessSky)||(skyGridRoom instanceof EndlessThinSky))) { ((GridLocale)skyGridRoom).clearGrid(null); rawDoors()[Directions.UP]=null; setRawExit(Directions.UP,null); for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room thatSky=skyGridRoom.rawDoors()[d]; final int opDir=Directions.getOpDirectionCode(d); if((thatSky!=null)&&(thatSky.rawDoors()[opDir]==skyGridRoom)) { thatSky.rawDoors()[opDir]=null; thatSky.setRawExit(opDir, null); } skyGridRoom.rawDoors()[d]=null; skyGridRoom.setRawExit(d,null); } CMLib.map().emptyRoom(skyGridRoom,null,true); skyGridRoom.destroy(); skyedYet=false; } } }
923fd49f-09ea-457a-a06d-0dd27fb2ec26
1
public boolean addClient(String x) { try { LoadBalancer.registerNewClient(x); } catch (IOException e) { System.err.println("Had an error connecting to " + x.split("::")[0] + ": " + e.getMessage()); System.err.println("Will continue to try to connect..."); LolDataServer.log.warning("Had an error connecting to " + x.split("::")[0] + ": " + e.getMessage()); LolDataServer.log.warning("Will continue to try to connect..."); return false; } return true; }
04b6db3a-0b87-4b8c-bb5c-fb2c2252eb74
0
@AfterClass public static void tearDownClass() { }
2db40925-afa0-4384-8920-3133cf213d6d
8
static final public void ClassExtendsDeclaration() throws ParseException { jj_consume_token(CLASS); Identifier(); jj_consume_token(EXTENDS); Identifier(); jj_consume_token(LBRACE); label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case BOOLEAN: case INTEGER: case IDENTIFIER: ; break; default: jj_la1[4] = jj_gen; break label_4; } VarDeclaration(); } label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PUBLIC: ; break; default: jj_la1[5] = jj_gen; break label_5; } MethodDeclaration(); } jj_consume_token(RBRACE); }
7fd31461-7e68-4cfe-9c5e-b34c2bd08610
9
protected void guessDeviceType(UserAgentInfo uaInfo) { if (compiledDeviceRegMap == null || deviceMap == null) { return; } String type = uaInfo.getType(); if (type == null || type.isEmpty()) { return; } if (type.equals("Other") || type.equals("Library") || type.equals("Useragent Anonymizer")) { uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_OTHER)); } else if (type.equals("Mobile Browser") || type.equals("Wap Browser")) { uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_SMARTPHONE)); } else { uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_DESKTOP)); } }
3a57d57d-01b5-4306-90da-14d401ca0390
5
public static boolean isPermutation(String s1, String s2){ /*Firstly, compare their length*/ if(s1.length()!=s2.length()) return false; /*Then use bitmap to do the counting * Assume char has a range of 0 to 255*/ int map[] =new int[256]; int length=s1.length(); for(int i=0;i<length;i++){ map[s1.charAt(i)]++; } for(int i=0;i<length;i++){ map[s2.charAt(i)]--; } /*Check whether they are all zeros*/ for (int i=0;i<256;i++){ if(map[i]!=0) return false; } return true; }
26bcc389-3dc8-4686-9865-cf7d7887d45d
1
public void twoBodyCollision(Entity e1, Entity e2){ double m1 = e1.mass; double m2 = e2.mass; double v1x = e1.vx; double v1y = e1.vy; double v2x = e2.vx; double v2y = e2.vy; double x1 = e1.x; double y1 = e1.y; double x2 = e2.x; double y2 = e2.y; double size1 = e1.size; double size2 = e2.size; double theta = Math.toDegrees(Math.atan2(v2y - v1y, v2x - v1x)); double separation = Math.sqrt(sqr(x2 - x1) + sqr(y2 - y1)); if(sqr(v1x) + sqr(v1y) >= sqr(v2x) + sqr(v2y)){ e1.x = x1 + 2.0*cos((int)theta)*((size1+size2)/2 - separation); e1.y = y1 + 2.0*sin((int)theta)*((size1+size2)/2 - separation); }else{ e2.x = x2 -= 2.0*cos((int)theta)*((size1+size2)/2 - separation); e2.y = y2 -= 2.0*sin((int)theta)*((size1+size2)/2 - separation); } e1.vx = (2*v2x*m2 + v1x*(m1 - m2))/(m1 + m2); e1.vy = (2*v2y*m2 + v1y*(m1 - m2))/(m1 + m2); e2.vx = (v2x*(m2 - m1) + 2*m1*v1x)/(m1 + m2); e2.vy = (v2y*(m2 - m1) + 2*m1*v1y)/(m1 + m2); }//end two body collision
13ef440b-7e3c-43ba-9ff0-07785fdfe6f7
9
@Override public boolean isValid(Location from, Location to) { int fromCount = game.getCount(from); int toCount = game.getCount(to); Color fromColor = game.getColor(from); Color toColor = game.getColor(to); Color playerInTurn = game.getPlayerInTurn(); if(from == to){ return false; } if ( fromColor != playerInTurn ){ //Can't move opponent's piece //Notify Observers for( GameObserver gO : this.game.getObservers() ){ gO.setStatus("Invalid Move: Can not move opponent's piece. " + this.game.getPlayerInTurn().toString() + " has " + this.game.getNumberOfMovesLeft() + " moves left..."); } // return false; } if ( fromCount == 0 ){ //Can't move piece if no pieces //Notify Observers for( GameObserver gO : this.game.getObservers() ){ gO.setStatus("Invalid Move: Can not move from an empty location. " + this.game.getPlayerInTurn().toString() + " has " + this.game.getNumberOfMovesLeft() + " moves left..."); } // return false; } if ( toCount > 0 ){ //toSquare is not empty if (toColor != playerInTurn && toColor != Color.NONE){ //If to square is occupied by the opponent //Notify Observers for( GameObserver gO : this.game.getObservers() ){ gO.setStatus("Invalid Move: Can not move to an occupied location. " + this.game.getPlayerInTurn().toString() + " has " + this.game.getNumberOfMovesLeft() + " moves left..."); } // return false; } } return true; }
04995442-253a-496d-9419-082f74fa3586
8
public static void renderEntities(Graphics g, Global global){ Verse currentVerse = global.getCurrent().getCurrentVerse(); for (int i=0; i<currentVerse.getVerseEntities().size(); i++){ Entity ent = currentVerse.getVerseEntities().get(i); if (ent!=null){ if (ent.getEntityImg()!=null){ if (ent.getEntityImg().getImage()!=null){ ent.getEntityImg().getImage().draw(ent.getEntityPos().getX(),ent.getEntityPos().getY()); } } } } Level currentLevel = global.getCurrent().getCurrentLevel(); for (int i=0; i<currentLevel.getLevelEntities().size(); i++){ Entity ent = currentLevel.getLevelEntities().get(i); if (ent!=null){ if (ent.getEntityImg()!=null){ if (ent.getEntityImg().getImage()!=null){ ent.getEntityImg().getImage().draw(ent.getEntityPos().getX(),ent.getEntityPos().getY()); } } } } }
61008cc8-4055-4d9d-82c9-163f41928f77
7
public Archive findStartMatchArchive( String consolFun, long startTime, long resolution ) throws IOException { long arcStep, diff; int fallBackIndex = 0; int arcIndex = -1; long minDiff = Long.MAX_VALUE; long fallBackDiff = Long.MAX_VALUE; for ( int i = 0; i < archives.length; i++ ) { if ( archives[i].getConsolFun().equals(consolFun) ) { arcStep = archives[i].getArcStep(); diff = Math.abs( resolution - arcStep ); // Now compare start time, see if this archive encompasses the requested interval if ( startTime >= archives[i].getStartTime() ) { if ( diff == 0 ) // Best possible match either way return archives[i]; else if ( diff < minDiff ) { minDiff = diff; arcIndex = i; } } else if ( diff < fallBackDiff ) { fallBackDiff = diff; fallBackIndex = i; } } } return ( arcIndex >= 0 ? archives[arcIndex] : archives[fallBackIndex] ); }
f89b46f8-3523-4ab8-9c35-b99ab10da2ba
9
void createHMlut(int [] kernel, int [] lut){ int i, j, match, toMatch; for(i=0;i<512;i++) lut[i]=1; toMatch=0; for(j=0;j<9;j++){ if (kernel[j]!=2) toMatch++; } //System.out.println("Debug: to match: "+toMatch); //make lut for(i=0;i<512;i++){ match=0; for(j=0;j<9;j++){ if (kernel[j]!=2){ if ((((i & (int)Math.pow(2,j))!=0)?1:0) == kernel[j]) match++; } } if (match!=toMatch){ lut[i]=0; } } }
08da16d7-c76f-4b68-8c4a-fa9c07e1f277
5
public static void main(String[] args) { Reader in = new Reader(); int i,dg[],n; int tc = in.nextInt(); while (0 < tc--) { n = in.nextInt(); in.restStringLine(); ArrayList<Integer> list = new ArrayList<Integer>(); for (int j = 1; j <=n; j++) { list.add(in.readLine().split(" ").length); } StringBuilder sb = new StringBuilder(); int min = Collections.min(list); for (int j = 0; j < list.size(); j++) { // if(j!=0) System.out.print(" "); if(list.get(j)==min) sb.append((j+1)+" "); } System.out.println(sb.substring(0,sb.length()-1)); if(tc!=0) in.readLine(); }//End of While }
666f493e-9671-455f-947c-ef08764511ac
6
public void updateFiles () { if (FD!=null) return; File dir=new File(DirField.getText()); if (!dir.isDirectory()) return; CurrentDir=DirField.getText(); if (PatternField.getText().equals("")) PatternField.setText("*"); try { Files.clear(); Dirs.clear(); FileList l=new FileList(DirField.getText(), PatternField.getText(),false); l.setCase(Global.getParameter("filedialog.usecaps",false)); l.search(); l.sort(); Enumeration e=l.files(); while (e.hasMoreElements()) { File f=(File)e.nextElement(); Files.addElement(FileName.filename(f.getCanonicalPath())); } Dirs.addElement(".."); e=l.dirs(); while (e.hasMoreElements()) { File f=(File)e.nextElement(); Dirs.addElement(FileName.filename(f.getCanonicalPath())); } } catch (Exception e) {} Dirs.updateDisplay(); Files.updateDisplay(); Files.requestFocus(); }
9c91f79e-c032-4e07-9e86-0073450215a3
3
public State getMovingDirectionState(Point destination) { Point position = new Point(super.getIntX(), super.getIntY()); if(Point.insideAngle(Point.DOWN_LEFT, Point.DOWN_RIGHT, position, destination)) { // Move up return State.MOVE_UP; } else if(Point.insideAngle(Point.DOWN_RIGHT, Point.UP_RIGHT, position, destination)) { // Move right return State.MOVE_RIGHT; } else if(Point.insideAngle(Point.UP_RIGHT, Point.UP_LEFT, position, destination)) { // Move down return State.MOVE_DOWN; } else { // Move left return State.MOVE_LEFT; } }
21e56732-a0ee-4d05-96e1-01d529dd4d83
3
public DataSource assemble(ServletConfig config) throws ServletException { String dataSourceName = "jdbc/blabber"; DataSource dataSource = null; System.out.println("Data Source Parameter " + dataSourceName); Context envContext = null; try { Context context = new InitialContext(); System.out.println("initial context " + context.getNameInNamespace()); envContext = (Context) context.lookup("java:/comp/env"); System.out.println("envcontext " + envContext); listContext(envContext, ""); } catch (Exception et) { throw new ServletException("Can't get contexts " + et); } try { dataSource = (DataSource)envContext.lookup(dataSourceName); if (dataSource == null) throw new ServletException(dataSourceName + " is an unknown data-source."); } catch (NamingException e) { throw new ServletException("Cant find datasource name " +dataSourceName+" Error "+ e); } CreateSchema(dataSource); return dataSource; }
8823b662-ecdc-404f-a567-63613d60a145
9
@Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (claimNumber != null ? claimNumber.hashCode() : 0); result = 31 * result + (claimantFirstName != null ? claimantFirstName.hashCode() : 0); result = 31 * result + (claimantLastName != null ? claimantLastName.hashCode() : 0); result = 31 * result + (claimStatus != null ? claimStatus.hashCode() : 0); result = 31 * result + (lossDate != null ? lossDate.hashCode() : 0); result = 31 * result + (lossInfo != null ? lossInfo.hashCode() : 0); result = 31 * result + (assignedAdjusterID != null ? assignedAdjusterID.hashCode() : 0); result = 31 * result + (vehicles != null ? vehicles.hashCode() : 0); return result; }
043a4342-4cbd-43dd-8aa0-85bb96ca8634
1
public String getOrgaEinheitBezeichnung(){ OrgaEinheit orgaEinheit = dbZugriff.getOrgaEinheitZuidOrgaEinheit(this.idOrgaEinheit); if(orgaEinheit!=null)return orgaEinheit.getOrgaEinheitBez(); else return "Keine Organisationseinheit"; }
98b28d46-8ce6-43c6-84d2-edee2f8736da
5
public static Personne authenticate(String username, String password) { try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "margo", "margo"); if (con == null) System.out.println("con classe ko "); else System.out.println("con classe ok "); Statement statement = con.createStatement(); if (statement == null) System.out.println("statement classe ko "); else System.out.println("statement classe ok "); //System.out.println("test1 : " + SaisieNom.getText()); ResultSet rs = statement.executeQuery("select p.NOM,p.PRENOM,p.TYPEPERSONNE,p.ADRESSE,p.SITUATION,p.MDP,p.IDPERS,p.MAIL,p.LOGIN from PERSONNE p WHERE p.LOGIN='"+username+"'"); //ResultSet rs = statement.executeQuery("select * from \"classe\" where nom='"+SaisieNom.getText()+"'" ); //ResultSet rs = statement.executeQuery("SELECT table_name FROM user_tables" ); rs.next(); int role = rs.getInt(3); String nom = rs.getString(1); String prenom = rs.getString(2); String adresse = rs.getString(4); String situation = rs.getString(5); String mdp = rs.getString(6); int id = rs.getInt(7); String mail = rs.getString(8); String login = rs.getString(9); if(rs.wasNull()) return null; rs.close(); statement.close(); con.close(); if(password.equals(mdp)){ Personne user = new Personne(id,login,nom,prenom,situation,adresse,mail,role); return user; }else{ return null; } } catch (SQLException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } return null; }
423b1698-0dae-472f-968f-fcfce490b147
2
public static ArrayList<String> merge(String[] a, String[] b) { ArrayList<String> sentence = new ArrayList<String>(); for (String s: a) sentence.add(s); for (String s: b) sentence.add(s); return sentence; }
6e4f23af-66eb-402a-a96f-bc183e19c893
2
public void draw(Graphics graphics) { int y = 1000 / 3; int i = 1; graphics.drawImage(sprite.getImage(image), 0, 0, null); for (String menuItem : menuItems) { if (i == selectedItem) { graphics.setColor(Color.red); graphics.fillRect(310, y + (i * 37) + 5 , 15, 2); } i++; } }
f188ae5b-b515-4681-9b42-f8cf0bf6a541
5
private void updateLists(double x) { if (n == 1) { X[1] = x; } else if (n > 1 && n <= maxlag) { for (int j = 1; j <= n-1; j++) { W[j] = W[j] + ((double)(n - 1) / n) * (x - x_bar) * (X[n-j] - x_bar); } X[n] = x; } else { for (int j = 1; j <= maxlag; j++) { W[j] = W[j] + ((double)(n - 1) / n) * (x - x_bar) * (X[((n - j) % maxlag)+1] - x_bar); } X[(n % maxlag)+1] = x; } }
27206c21-e3b2-4efe-b3be-47feb192b043
2
void compareCdfUp(double p, int k, int n, double result) { double prob = Binomial.get().cdfUp(p, k, n); double abs = Math.abs(prob - result); double diff = abs / Math.min(prob, result); if ((abs > 1E-300) && (diff > 0.00000000001)) throw new RuntimeException("Relative difference:" + diff + "\t\t" + prob + " != " + result); }
c9a500c5-d23f-4b7f-9d5f-c62c9c158add
2
public MenuItem getLlItemItem() { if (llItem == null) { llItem = new MenuItem("Show Lekkerland Menu"); llItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { new ReceiptListPanel(); } catch (Exception ex) { ex.printStackTrace(); } } }); } return llItem; }
8f2a309d-77ce-450e-b232-8febbcba268f
0
public static int tilesToPixels(int numTiles) { // no real reason to use shifting here. // it's slighty faster, but doesn't add up to much // on modern processors. return numTiles << TILE_SIZE_BITS; // use this if the tile size isn't a power of 2: //return numTiles * TILE_SIZE; }
d24b84fc-55b9-4b14-a2ae-94698ae9a6e2
3
String EncodeCurrentStatus() { String code = ""; for(int i = 0; i < sudokuSize; i++) { for(int k = 0; k < sudokuSize; k++) { if(cells[i][k].valueState != waitingValue) code += i + "," + k + "," + cells[i][k].current + "," + cells[i][k].valueState + "," + instantiator[i][k] + "&"; } } return code.substring(0, code.length() - 1); }
438ecf07-1de8-4d3c-933e-e36283cddcc6
5
public void persistir() { FileOutputStream fos = null; ObjectOutputStream stream = null; try { fos = new FileOutputStream("arquivo.bin"); stream = new ObjectOutputStream(fos); stream.writeObject(persistencia); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
16e66891-dae2-42ce-9c33-6dff50b27d06
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SequenceImpl<?> other = (SequenceImpl<?>)obj; if (size != other.size) return false; if (!Arrays.equals(values, other.values)) return false; return true; }
0d1a6891-a6e7-4c7d-9270-ddeb40bbf303
6
public static void ledprocess(String filepath, String result, String sn){ String finalresult = ""; int errorcode=0;// print error code in the final output file; int errornum = 8; File outputfile = new File(filepath); if ((result.equals("P"))||(result.equals("p"))||(result.equals("pass"))||(result.equals("PASS"))){ finalresult = "PASS"; } else { finalresult="FAILED"; errorcode = 0; } try { BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile, true));// append the content to the end instead of overwriting the prior contents. bw.write("LED_RGB_Result="+finalresult+"\r\n"); System.out.println("LED_RGB_Result="+finalresult); if (finalresult.equals("FAILED")){ NumberFormat nf = NumberFormat.getIntegerInstance(); nf.setMinimumIntegerDigits(2); bw.write("Error_Code="+nf.format(errornum)+nf.format(errorcode)+"\r\n"); System.out.println("Error_Code="+nf.format(errornum)+nf.format(errorcode)); } bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
4360d71a-4f4b-42a4-98a4-7aa403fdddbe
5
private void calculateBestFitLine() { int count = timestamps.length, validCount = 0; double ts = 0.0, vs = 0.0; for(int i = 0; i < count; i++) { if(!Double.isNaN(values[i])) { ts += timestamps[i]; vs += values[i]; validCount++; } } if(validCount <= 1) { // just one not-NaN point b0 = b1 = Double.NaN; return; } ts /= validCount; vs /= validCount; double s1 = 0, s2 = 0; for(int i = 0; i < count; i++) { if(!Double.isNaN(values[i])) { double dt = timestamps[i] - ts; double dv = values[i] - vs; s1 += dt * dv; s2 += dt * dt; } } b1 = s1 / s2; b0 = vs - b1 * ts; }
a44fd661-1eac-4d7f-83b5-64d5651b8b03
7
public void loadConfig() { configYaml = new YamlConfiguration(); try { configYaml.load(configFile); } catch (Exception e) { e.printStackTrace(); } if (configYaml.getString("config-version") != plugin.getDescription().getVersion()) { if (configYaml.getString("config-version") == null) { if (!configYaml.contains("default-rows")) configYaml.set("default-rows", Integer.valueOf(4)); if (configYaml.contains("right_click")) configYaml.set("right_click", null); if (configYaml.contains("shift_right_click")) configYaml.set("shift_right_click", null); if (!configYaml.contains("economy.enabled")) { configYaml.set("economy.enabled", Boolean.valueOf(configYaml.getBoolean("economy", false))); configYaml.set("economy.values.small", Integer.valueOf(1)); configYaml.set("economy.values.medium", Integer.valueOf(10)); configYaml.set("economy.values.big", Integer.valueOf(50)); configYaml.set("economy.items.small.type", Integer.valueOf(371)); configYaml.set("economy.items.small.amount", Integer.valueOf(1)); configYaml.set("economy.items.medium.type", Integer.valueOf(266)); configYaml.set("economy.items.medium.amount", Integer.valueOf(10)); configYaml.set("economy.items.large.type", Integer.valueOf(41)); configYaml.set("economy.items.large.amount", Integer.valueOf(50)); } } configYaml.set("config-version", plugin.getDescription().getVersion()); saveConfig(); } }
1d5925d2-fddf-4187-9914-00d13e9cabe5
9
private Object handleSubm(Object tos, String id, String ref) { if (tos instanceof Header && ref != null && ((Header)tos).getSubmitterRef() == null) { ((Header)tos).setSubmitterRef(ref); return new Object(); // placeholder } else if (tos instanceof Header && ref == null && ((Header)tos).getSubmitter() == null) { Submitter submitter = new Submitter(); ((Header)tos).setSubmitter(submitter); return submitter; } else if (tos instanceof Gedcom && ((Gedcom)tos).getSubmitter() == null) { Submitter submitter = new Submitter(); if (id != null) { submitter.setId(id); } ((Gedcom)tos).setSubmitter(submitter); return submitter; } return null; }
d20a2476-2fa8-4e12-87e4-acaf4424bbc5
9
public void portalEffect(Player p){ int n = -1; int lb = 0; int ub = 3; String head; String textBlock; ArrayList<String> strList = new ArrayList<String>(); head = "Outworld Portal"; strList.add("0: Decline"); if((p.inventory.contains(Card.gauntlet) || p.inventory.contains(Card.gauntletii)) && !spectralImmune(p)){ textBlock = "A voice from the gauntlet is speaking to you in a language you've never heard, yet somehow you understand. You don't know why but you have to draw a Spectral Card."; ub = 0; }else{ textBlock = "Here you may draw a card of your choice. Light Cards tend to be utility-oriented equipment or healing effects, and some of them only benefit lower HP avatars or Hallows. Augur Cards are passed face-down to another player to gain insight into their identity. Dark Cards tend to be offensive equipment or risky damaging effects, and some only help Fiends."; strList.add("1: Draw Light Card"); strList.add("2: Draw Augur Card"); strList.add("3: Draw Dark Card"); } p.displayRender(head, textBlock, strList); drawEvent(p, pturn); do{ n = playerInput(p); }while(n < lb || n > ub); switch(n){ case 0 : declinedAreaEffects(p, Area.PORTAL); break; case 1 : drawLightCard(p); break; case 2 : drawAugurCard(p); break; case 3 : drawDarkCard(p); break; default : break; }; }
3639a786-2993-46ce-8021-3edf829fd978
8
private eIDTokenLoadingWindow(final String providerName, final BiConsumer<PbxUser, CertificateData> consumer) { super("Validating your Citizen Card - Protbox"); this.setIconImage(Constants.getAsset("box.png")); this.setLayout(null); info = new JLabel(); setInfoWithLooking(); info.setFont(Constants.FONT); info.setBounds(20, 20, 250, 30); add(info); cancel = new JLabel(new ImageIcon(Constants.getAsset("cancel.png"))); cancel.setLayout(null); cancel.setBounds(250, 15, 122, 39); cancel.setBackground(Color.black); cancel.addMouseListener((OnMouseClick) e -> { if (JOptionPane.showConfirmDialog( eIDTokenLoadingWindow.this, "You need to authenticate yourself in order to use this application!\n" + "Are you sure you want to cancel and quit the application?\n\n", "Confirm quit application", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { dispose(); System.exit(2); } }); add(cancel); this.setSize(370, 73); this.setUndecorated(true); this.getContentPane().setBackground(Color.white); this.setBackground(Color.white); this.setResizable(false); getRootPane().setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100))); Utils.setComponentLocationOnCenter(this); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setVisible(true); // tests every 3 seconds if card was added final Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { setInfoWithLooking(); try { Provider p = Security.getProvider(providerName); KeyStore ks = KeyStore.getInstance("PKCS11", p); String alias = Protbox.pkcs11Providers.get(providerName); if (Constants.verbose) { logger.info("eID Token was found!"); } t.cancel(); setInfoWithLoading(); try { ks.load(null, null); Certificate cert = ks.getCertificate(alias); Certificate[] chain = ks.getCertificateChain(alias); if (ks.isKeyEntry(alias)) { PrivateKey privateKey = (PrivateKey) ks.getKey(alias, null); X509Certificate c = new X509CertImpl(cert.getEncoded()); // generates a new key-pair to use in folder sharing requests and responses KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); byte[] encodedPublicKey = pair.getPublic().getEncoded(); // obtains signature to use in key requests Signature sig1 = Signature.getInstance(c.getSigAlgName()); sig1.initSign(privateKey); sig1.update(encodedPublicKey); byte[] signatureBytes = sig1.sign(); // gets user name and cc number TokenParser parser = TokenParser.parse(c); if (Constants.verbose) { logger.info("Token parser results: {} {}", parser.getUserName(), parser.getSerialNumber()); } // returns certificate, generated pair and signature bytes PbxUser user = new PbxUser( chain, // certificate chain c, // X509 certificate parser.getSerialNumber(), // user cc number parser.getUserName() // user name ); CertificateData data = new CertificateData(encodedPublicKey, signatureBytes, pair.getPrivate()); setInfoWithUser(user); Thread.sleep(2000); consumer.accept(user, data); t.cancel(); dispose(); } } catch (CertificateException | KeyStoreException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "You must insert you digital authentication certificate code in order to use this application!\n" + "Please run the application again and insert you digital authentication certificate code!", "Invalid Digital Signature Code!", JOptionPane.ERROR_MESSAGE); System.exit(2); } catch (GeneralSecurityException | IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); System.exit(2); } } catch (Exception ex) { ex.printStackTrace(); if (Constants.verbose) { logger.info("Card was NOT found... Trying again in 3 seconds."); } } } }, 0, 3000); }
59c228ba-82d8-41df-b4c2-a772bcb7cc1e
0
public void setWeight(String weight) { this.weight = weight; setDirty(); }
a81bb9ef-6cb6-45dd-b8c2-a25fca2e8f14
6
public static ServerType getServerType(byte t) { switch (t) { case 'D': case 'd': return DEDICATED; case 'L': case 'l': return NON_DEDICATED; case 'P': case 'p': return TELEVISION; default: throw new IllegalArgumentException(); } }
41958d36-c515-41da-950a-7f0a6726fbd4
4
public void createAccount(String strAccountName, String strUserName, Boolean autoPassword, int autoPassLen, Boolean autoPassAllSpecials, String autoPassSpecials, String strPassword, Boolean seperatorTab, FkActionEventListener delegate) { StringBuilder sb = new StringBuilder(256); sb.append(strAccountName); sb.append(ENTER_KEY); sb.append(PAUSE_CODE); sb.append(strUserName); sb.append(ENTER_KEY); sb.append(PAUSE_CODE); if( autoPassword ) { sb.append('2'); //Select automatic password sb.append(PAUSE_CODE); sb.append(autoPassLen); sb.append(ENTER_KEY); if( autoPassAllSpecials ) { sb.append('1'); //Allow all characters } else { if( autoPassSpecials.length() > 0 ) { sb.append('2'); //Allow only characters specified below sb.append(PAUSE_CODE); sb.append(autoPassSpecials); sb.append(ENTER_KEY); } else { sb.append('3'); // Allow no special characters } } } else { //Manual entered password sb.append('1'); // Select manual password sb.append(PAUSE_CODE); sb.append(strPassword); sb.append(ENTER_KEY); } sb.append(PAUSE_CODE); //Tab/Enter sep if( seperatorTab ) { sb.append('1'); //Select tab seperator } else { sb.append('2'); //Select enter seperator } String seq = sb.toString(); System.out.println("Seq ["+seq.replace(PAUSE_CODE, 'ø').replace(ENTER_KEY, 'å')+"]"); NewAccountTask newTask = new NewAccountTask(seq, delegate, strAccountName); new Thread(newTask).start(); }
087bdb44-832d-4b19-bc38-a2441365b893
0
public String getIsNull() { return isNull; }
b087240e-9b9b-4f96-ac9b-40025daffb0d
1
public AnalysisData createAnalysisData() { final AnalysisData analysisData = new AnalysisData(); analysisData.name = getName(); analysisData.duration = getDuration(); analysisData.properties = getProperties(); final List<String> callNames = getCallNames(); analysisData.rows = new AnalysisData.Row[callNames.size()]; int i = 0; for (final String callName : callNames) { analysisData.rows[i] = new AnalysisData.Row(); analysisData.rows[i].name = callName; analysisData.rows[i].count = getCount(callName); analysisData.rows[i].countErrors = getCountErrors(callName); analysisData.rows[i].countFailures = getCountFailures(callName); analysisData.rows[i].min = getMinimum(callName); analysisData.rows[i].max = getMaximum(callName); analysisData.rows[i].avg = getAverage(callName); i++; } return analysisData; }
cf9970d9-b690-4fc4-87be-5170ae0c1483
8
private void setAnchorPointForRectangularShape(byte i, float x, float y, float w, float h) { switch (i) { case RectangleComponent.UPPER_LEFT: anchorPoint.setLocation(x + w, y + h); break; case RectangleComponent.UPPER_RIGHT: anchorPoint.setLocation(x, y + h); break; case RectangleComponent.LOWER_RIGHT: anchorPoint.setLocation(x, y); break; case RectangleComponent.LOWER_LEFT: anchorPoint.setLocation(x + w, y); break; case RectangleComponent.TOP: anchorPoint.setLocation(x, y + h); break; case RectangleComponent.RIGHT: anchorPoint.setLocation(x, y); break; case RectangleComponent.BOTTOM: anchorPoint.setLocation(x, y); break; case RectangleComponent.LEFT: anchorPoint.setLocation(x + w, y); break; } }
0730fea4-f1d8-4a63-ac57-6d73d7aa9565
6
public void readFile() throws FileNotFoundException { if (fileName != null) { File file = new File(fileName); Scanner scanner; try { scanner = new Scanner(file); String line; if (scanner.hasNextLine()) { scanner.nextLine(); } String currClass = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); String[] str = line.split(";"); if (str.length == 1) { currClass = str[0]; } else { name = str[1].trim(); riderID = Integer.parseInt(str[0]); add(); race.addClass(riderID, currClass); for (int i = 2; i < str.length; i++) { String attribute = str[i].trim(); race.addAttribute(riderID, attribute); } } } } catch (FileNotFoundException e) { printErrorText(); throw new FileNotFoundException(); } } }
ac149a76-bde4-4188-b547-b98c7a8e5ce8
8
@Override public String execute() throws Exception { User user = this.service.getCurrentUser(); if (user == null) return SUCCESS; List<Map<String, Object>> notifications = this.service.checkNotification(user.getUid()); if (notifications == null) return SUCCESS; StringBuilder sb = new StringBuilder(); for (Map<String, Object> map : notifications) { switch (Integer.parseInt(map.get("type").toString())) { // type: 1=invitation, 2=invitation_reply, 3=newbie, 4=join_club_apply_reply, 5=join_club_apply case 1 : // like /*<div class="invitation-item"> $1 wants to join $2 - $3 <a href="acceptInvitation?from=$4&to=$5&where=$6">accept</a> <a href="refuseInvitation?from=$4&to=$5&where=$6">refuse</a> </div>*/ sb.append("<div class=\"invitation-item\">"); sb.append(map.get("sender").toString()); sb.append(" wants to join ");sb.append(map.get("club").toString()); sb.append(" - ");sb.append(map.get("date").toString()); sb.append("<a href=\"acceptInvitation?from=");sb.append(map.get("from").toString()); sb.append("&to=");sb.append(map.get("to").toString()); sb.append("&where=");sb.append(map.get("where").toString()); sb.append("\">accept</a>"); sb.append("<a href=\"refuseInvitation?from=");sb.append(map.get("from").toString()); sb.append("&to=");sb.append(map.get("to").toString()); sb.append("&where=");sb.append(map.get("where").toString()); sb.append("\">refuse</a>"); break; case 2 : /*<div class="invitation-reply-item"> $1 has $2 your invitation to join $3 - $4 <a href="muteNotification?type=invitation-reply&sender=$5&receiver=$6&cid=$7&date=$4"> got it</a> </div>*/ sb.append("<div class=\"invitation-reply-item\">"); sb.append(map.get("newbie").toString()); sb.append(" has "); sb.append(map.get("status").toString()); sb.append(" your invitation to join ");sb.append(map.get("club").toString()); sb.append(" - ");sb.append(map.get("date").toString()); sb.append("<a href=\"muteNotification?type=invitation-reply"); sb.append("&sender=");sb.append(map.get("sender").toString()); sb.append("&receiver=");sb.append(map.get("receiver").toString()); sb.append("&cid=");sb.append(map.get("cid").toString()); sb.append("&date=");sb.append(map.get("date").toString()); sb.append("\">gotcha</a>"); break; case 3 : /*<div class="newbie-notice-item"> a new member $1 has just joined your club $2 - $3 <a href="muteNotification?type=newbie-notice&sender=$4&receiver=$5&cid=$6">got it</a> </div>*/ sb.append("<div class=\"newbie-notice-item\">"); sb.append("a new member ");sb.append(map.get("newbie").toString()); sb.append(" has just joined your club ");sb.append(map.get("club").toString()); sb.append(" - ");sb.append(map.get("date").toString()); sb.append("<a href=\"muteNotification?type=newbie-notice&sender="); sb.append(map.get("sender").toString()); sb.append("&receiver=");sb.append(map.get("receiver").toString()); sb.append("&cid=");sb.append(map.get("cid").toString()); sb.append("\">got it</a>"); break; case 4 : /*<div class="join-club-apply-reply-item"> $leader has $status your apply to join $club - $date <a href="muteNotification?type=join-club-reply&sender=$sender&receiver=$receiver&cid=$cid"> I see</a> </div>*/ sb.append("<div class=\"join-club-apply-reply-item\">"); sb.append(map.get("leader").toString()); sb.append(" has ");sb.append(map.get("status").toString()); sb.append(" your apply to join ");sb.append(map.get("club").toString()); sb.append(" - ");sb.append(map.get("date").toString()); sb.append("<a href=\"muteNotification?type=join-club-reply"); sb.append("&sender=");sb.append(map.get("sender").toString()); sb.append("&receiver=");sb.append(map.get("receiver").toString()); sb.append("&cid=");sb.append(map.get("cid").toString()); sb.append("\">I see</a></div>"); break; case 5 : /*<div class="join-club-apply-item"> $applicant wants to join your club $club - $date <a href="responseJoinClubApply?action=approve&sender=$sender&receiver=$receiver&cid=$cid"> <span class="approve">approve</span></a> <a href="responseJoinClubApply?action=reject&sender=$sender&receiver=$receiver&cid=$cid"> <span class="reject">negative</span></a> </div>*/ sb.append("<div class=\"join-club-apply-item\">"); sb.append(map.get("applicant").toString()); sb.append(" wants to join your club ");sb.append(map.get("club").toString()); sb.append(" - ");sb.append(map.get("date").toString()); sb.append(" <a href=\"responseJoinClubApply?action=approve"); sb.append("&sender=");sb.append(map.get("sender").toString()); sb.append("&receiver=");sb.append(map.get("receiver").toString()); sb.append("&cid=");sb.append(map.get("cid").toString()); sb.append("\"><span class=\"reject\">negative</span></a></div>"); break; } } notification = sb.toString(); System.out.println(notification); return SUCCESS; // parse to JSON /*if (notifications == null) System.out.println("Notifications null"); else { JSONArray jsonArr = new JSONArray(); for (Map<String, Object> map : notifications) { JSONObject jsonObj = new JSONObject(); for (Map.Entry<String, Object> entry : map.entrySet()) { jsonObj.put(entry.getKey(), entry.getValue()); } jsonArr.add(jsonObj); } System.out.print("it's jsonArr:" + jsonArr.toString()); notification = jsonArr.toString(); }*/ }
8bf82447-cd35-485d-b4ac-06d2277809a2
6
public String saveXML(boolean withDialog) { String fileName = ""; FileWriter fstream = null; File tempFile = null; if (withDialog == true) { fileName = getSavedFileName(); if (fileName == null) { return null; } try { fstream = new FileWriter(fileName); } catch (IOException e1) { ErrorMessage .show("Eroare cand a fost deschis stream-ul de scriere"); e1.printStackTrace(); return null; } } else { try { tempFile = File.createTempFile("temp", ".xml"); fileName = tempFile.getAbsolutePath(); fstream = new FileWriter(tempFile); } catch (IOException e) { ErrorMessage .show("Eroare cand a fost deschis stream-ul de scriere"); e.printStackTrace(); } } boolean result = writeToFile(fstream); if (withDialog) { if (result == true) { JOptionPane.showMessageDialog(null, "Modificarile au fost salvate cu succes!"); } else { JOptionPane .showMessageDialog(null, "A fost o eroare in timpul salvarii. Va rog sa incercati din nou!"); } } return fileName; }
877f8777-61c6-4f9d-a073-8681bba3899b
3
private boolean move(int nX, int nY) { //Check if valid if (!isValidPosition(nX, nY)) { return false; } pX = nX; pY = nY; setVisited(pX, pY); if(hasWumpus(pX,pY)) { score -= 1000; gameOver = true; } if (hasPit(pX,pY)) { score -= 1000; isInPit = true; } return true; }
ff4b2f0a-25c4-4199-9afe-89eeb4cc99c0
5
public String try_user_name() throws Exception { System.out.println("userName is " + userName); Connection conn = null; ResultSet rs = null; Statement stmt = null; if (userName.length() > 20) return "overflow"; if (userName.length() < 7) return "usernameShort"; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, psw); if (!conn.isClosed()) System.out.println("Success connecting to the Database!"); else System.out.println("Fail connecting to the Database!"); stmt = conn.createStatement(); rs = stmt.executeQuery("select * from member where user_name = '" + userName + "'"); if (!rs.next()) { return SUCCESS; } else { return "exist"; } } catch (Exception e) { System.out.print("connection error!"); e.printStackTrace(); return ERROR; } }
30313d9b-1dbb-492e-9a32-91f6b2bed348
2
HashMap<Variant, String> readEnsemblFile(String fileName) { String lines[] = Gpr.readFile(fileName).split("\n"); if (lines.length <= 0) throw new RuntimeException("Cannot open file '" + fileName + "' (or it's empty)."); HashMap<Variant, String> seqChanges = new HashMap<Variant, String>(); for (String line : lines) { Variant seqChange = str2seqChange(line); seqChanges.put(seqChange, line); } return seqChanges; }
215cd94f-8d49-4ac6-9617-afef55534b8f
6
public static Double calculateAndSomething(ArrayList<String> container) { double answer = 0; ArrayList<Double> values = new ArrayList<Double>(); for (int i = 0; i < container.size(); i++) { values.add(Double.valueOf(container.get(i))); } answer = values.get(0); System.out.println(answer); Random generator = new Random(); for (int i = 1; i < values.size(); i++) { int randomOp = generator.nextInt(4); String op = MathGame.operations[randomOp]; if(op.equals("+")) { answer += values.get(i); } else if(op.equals("-")) { answer -= values.get(i); } else if(op.equals("*")) { answer *= values.get(i); } else if(op.equals("/")) { answer /= values.get(i); } else { System.err.println("Bad operation"); } System.out.println(op + " " + values.get(i)); } return answer; }
01ca2253-2cc2-45a0-80bc-51a76a6b4748
2
public void add( Double addVal ) { //Add value as last node, to maintain balance, completeness of tree _heap.add( addVal ); _size++; int addValPos = _heap.size() - 1; int parentPos; while( addValPos > 0 ) { //potentially swap until reach root //pinpoint parent parentPos = (addValPos-1) / 2; if ( addVal < _heap.get(parentPos) ) {//addVal < parent swap( addValPos, parentPos ); addValPos = parentPos; } else break; } } //O(logn)
917c1f65-8ce5-4d09-97c8-be934f1abeae
1
public void setIndent(boolean bIndent) { this.bIndent = bIndent; newLine = bIndent ? "\n" : ""; }
09ebe172-4c51-4c89-8e77-e6a9f00ac458
2
public static void main(String... args) throws InterruptedException { GWCAConnection gwcaConnection = null; try { LOG.info("Executing \"Java GWCAConstants\" (version {})", Version.getVersion()); //TODO: Fill in the PID here gwcaConnection = new NamedPipeGWCAConnection(new File("\\\\.\\pipe\\GWCA_" + 3100)); gwcaConnection.open(); GWCAOperations op = new GWCAOperations(gwcaConnection); GuildWarsInstance gwInstance = new GuildWarsInstance(op); //TODO: START code your program below this point LOG.debug("getMyMaxHp(): {{},{}}", gwInstance.getPlayer().getMyMaxHp()[0], gwInstance.getPlayer().getMyMaxHp()[1]); LOG.debug("getTitleAsura(): {}", gwInstance.getHeroPanel().getTitlesTab().getTitleAsura()); LOG.debug("getBuildNumber(): {}", gwInstance.getRemainingCommands().getBuildNumber()); gwInstance.getRemainingCommands().setMaxZoom(4000); LOG.debug("getPing(): {}", gwInstance.getRemainingCommands().getBuildNumber()); //TODO: END code your program below this point LOG.info("The \"Java GWCAConstants\" finished executing"); } catch (Throwable throwable) { LOG.error("Initializing the \"Java GWCAConstants\" failed because: ", throwable); } finally { try { gwcaConnection.close(); } catch (IOException ex) { LOG.error("IO closing", ex); } } }
5d85e592-be8e-4e0c-9026-f57fbc95b779
1
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(args[0])); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append('\n'); line = br.readLine(); } String everything = sb.toString(); count(everything.toLowerCase().trim().replaceAll(" +", "")); }
adc056f7-5408-4f84-8622-46117f80b48e
0
public AppTest( String testName ) { super( testName ); }
b9dd6f57-1dcf-4bad-bdad-adf874eabb19
5
@Override protected byte[] generatePayload() throws MQTTException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (topicFilters.length <= 0 || QoSs.length <= 0) throw new MQTTException( "The SUBSCRIBE message must contain at least one topic filter and QoS pair"); if (topicFilters.length != QoSs.length) throw new MQTTException( "The SUBSCRIBE message should have the same number of topic filters and QoS"); for (int i = 0; i < topicFilters.length; i++) { if (MQTTHelper.isUTF8(topicFilters[i].getBytes("UTF-8"))) throw new MQTTException("Invalid topic filter encoding: " + topicFilters[i]); out.write(MQTTHelper.MSB(topicFilters[i].length())); out.write(MQTTHelper.LSB(topicFilters[i].length())); out.write(topicFilters[i].getBytes()); out.write(QoSs[i]); } return out.toByteArray(); }
b1c5c5e1-37dc-4824-bb49-cf728d223226
4
public HookingJar(String folderNameIn, String fileNameIn){ folderName = folderNameIn; fileName = fileNameIn; if (debug) { filePath = ROOT_FOLDER + "\\" + folderName + "\\Testing\\" + fileName + ".jar"; } else { filePath = ROOT_FOLDER + "\\" + folderName + "\\" + fileName + ".jar"; } try{ if (debug) { Files.createDirectories(Paths.get(ROOT_FOLDER + "\\" + folderName + "\\Testing\\")); } else { Files.createDirectories(Paths.get(ROOT_FOLDER + "\\" + folderName + "\\")); } Files.createFile(Paths.get(filePath)); }catch(Exception e){ if (!Files.exists(Paths.get(filePath))) System.out.println("Path does not exist, creation failed."); } }
a42c5e38-94d9-48d5-b954-24d3ec2d4510
3
public JButton getDialogButton(String buttonName){ if(buttonName.equals("ok")){ return okButton; } else if(buttonName.equals("cancel")){ return cancelButton; } else if(buttonName.equals("close")){ return closeButton; } return null; }
65ad1683-8732-4105-92c4-608c6fe3f2bd
7
public static boolean isData(String[] ccCode){ String[] tCodes = ccCode; int tblestart = 0; int tbleend = 0; Boolean b=false; Connection con = DBase.dbConnection(); PreparedStatement pst; try{ String query = "Select Count(CountryCode) FROM AED"; pst = con.prepareStatement(query); ResultSet rs = pst.executeQuery(); if(!rs.next()){ tblestart =0; } else do{ tblestart = rs.getInt(1); System.out.println(tblestart); }while(rs.next()); rs.close(); pst.close(); String query2 = "Select Count(CountryCode) From ZAR"; pst = con.prepareStatement(query2); ResultSet rs1 = pst.executeQuery(); if(!rs1.next()){ tbleend =0; } else do{ tbleend = rs1.getInt(1); System.out.println(tbleend); }while(rs1.next()); rs1.close(); pst.close(); con.close(); }catch(SQLException e){System.err.println(e + "?");} if (tbleend ==0){ b=true; } else if (tbleend ==90){ b = false; } return b; }
52b47c01-c3b2-4969-8ee6-515d2387b5d0
3
public Error getError() { if(isOk()) return error; try { JAXBContext context = JAXBContext.newInstance(Error.class); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader xml = new StringReader(content); if(!content.isEmpty()) error = (Error)unmarshaller.unmarshal(new StreamSource(xml)); } catch(JAXBException e) { e.printStackTrace(); } return error; }
5b5620e2-d08f-4293-b7f7-e3681f818692
6
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(ViewResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { // new ViewResults().setVisible(true); } }); }
06975582-4fa9-498c-b126-73fa8678ee47
4
@Override public boolean ausfuehren(ServerKontext kontext, Spieler spieler, Befehlszeile befehlszeile) { Raum aktuellerRaum = kontext.getAktuellenRaumZu(spieler); Item kuchen = aktuellerRaum.getNaechstesItem(); int energie = spieler.getLebensEnergie(); if(kuchen.isKuchen()) { energie += SpielKonstanten.KUCHEN_ENERGIE_GEWINN; aktuellerRaum.loescheItem(); kontext.schreibeAnSpieler(spieler, TextVerwalter.kuchenVomBodenGegessenText(energie)); if(aktuellerRaum.getNaechstesItem() != Item.Keins) { kontext.schreibeAnSpieler(spieler, TextVerwalter.IMMERNOCHKUCHENTEXT); } } if(kuchen.isGiftkuchen()) { energie -= SpielKonstanten.GIFTKUCHEN_ENERGIE_VERLUST; aktuellerRaum.loescheItem(); if(energie > 0) { kontext.schreibeAnSpieler(spieler, TextVerwalter.giftkuchenVomBodenGegessenText(energie)); } else { spieler.die(); kontext.schreibeAnSpieler(spieler, TextVerwalter.KUCHENTODTEXT); } } spieler.setLebensEnergie(energie); return true; }
c784c9d9-fefe-41a6-9428-930952a3653b
6
public BooleanOperator getIntegerToBooleanOperator(String string) { char[] chars = string.toCharArray(); for(char c : chars) { if(c == '<') return BooleanOperator.LESS_THAN; else if(c == '>') return BooleanOperator.MORE_THAN; else if(c == '=') return BooleanOperator.EQUAL_TOO; else if(c == '&') return BooleanOperator.AND; else if(c == '^') return BooleanOperator.OR; } return BooleanOperator.EQUAL_TOO; }
95f551a2-35fe-4780-9ca5-a0f13e945576
7
public static void main(String[] args) { if (args.length == 0) { usage(); return; } if (args.length > 2) { reportError("too many command-line arguments"); usage(); System.exit(1); } try { Reader input; input = new FileReader(new File(args[0])); PrintWriter output; if (args.length == 2) { output = new PrintWriter(new File(args[1])); } else { output = new PrintWriter(System.out); } Controller cntrl = new Controller(output); InputParser src = new InputParser(input, cntrl); src.process(); if (cntrl.endnoteStoreLength() > 0) { cntrl.setEndnoteMode(); for (int i = 0; i < cntrl.endnoteStoreLength(); i += 1) { cntrl.refNumSetter(i); InputParser endnote = new InputParser(cntrl.endnoteString(i), cntrl); endnote.process(); } } cntrl.setNormalMode(); cntrl.close(); output.close(); } catch (IOException e) { reportError(e.getMessage()); System.exit(1); return; } System.exit(getTotalErrors() == 0 ? 0 : 1); }
49706b65-a84c-4b50-b9db-ce900c18df4f
4
public static String getCookieValue(HttpServletRequest request,String cookieName) { Assert.notNull(request); Assert.hasText(cookieName); Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length >0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(cookieName)) { return cookie.getValue(); } } } return null; }
70dfadd1-51db-4466-b733-23af9560aed0
6
static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
42a2013f-702c-42d4-b5aa-e1927c9c8edd
1
public void setId(int id) throws ParkingException { if (id < 0) { throw new ParkingException("Parking id is under zero"); } this.id = id; }
dfc8752e-56ed-4b77-aae6-d41f455f3c57
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
410308fc-7620-4d5f-9371-ab30ad871feb
6
private String findSepLineInFile() { String[] lines = new String[0]; try { lines = FileHelper.readFileAsUtf8StringArray( selectedFile ); } catch( final Exception e ) { return DEFAULT_SEPARATOR_LINE; } Arrays.sort( lines ); String candidate = DEFAULT_SEPARATOR_LINE; int candidateCount = 0; String currentBest = candidate; int currentBestCount = candidateCount; for( String line : lines ) { line = line.trim(); if( line.isEmpty() ) { continue; } if( line.equals( candidate ) ) { candidateCount += line.length(); continue; } if( candidateCount > currentBestCount ) { currentBest = candidate; currentBestCount = candidateCount; } if( line.matches( "[-=xX.]+" ) ) { candidate = line; candidateCount = line.length(); } } return currentBest; }
49d5cec8-f86a-47c8-a75e-f483bdc820c4
6
public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("Cut")) { if (tf != null) { tf.cut(); } else { ta.cut(); } } if (actionEvent.getActionCommand().equals("Copy")) { if (tf != null) { tf.copy(); } else { ta.copy(); } } if (actionEvent.getActionCommand().equals("Paste")) { if (tf != null) { tf.paste(); } else { ta.paste(); } } }
c5a2d2fa-9cd8-492c-9491-ce1b5cfdff67
6
@SuppressWarnings({ "rawtypes", "unchecked" }) /* * This creates a request message from the omnilink.jar library. * This function needs to be cleaned up. */ public RequestMessage createRequestMessage(Map o) { Class commandClass = commandMap.get(o.get("command")); try { Constructor constr = commandClass.getConstructor(Map.class); return (RequestMessage) constr.newInstance((Map) o.get("params")); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.getCause(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
7fa3b5d3-baed-4291-a2d9-3313615843c8
9
boolean removeIfExists(Key key, T obj) { Object s = index.get(key); if (s instanceof Relation) { Relation rel = (Relation)s; Storage storage = getStorage(); int oid = storage.getOid(obj); int l = 0, n = rel.size(), r = n; while (l < r) { int m = (l + r) >>> 1; if (storage.getOid(rel.getRaw(m)) < oid) { l = m + 1; } else { r = m; } } if (r < n && storage.getOid(rel.getRaw(r)) == oid) { rel.remove(r); if (rel.size() == 0) { index.remove(key, rel); rel.deallocate(); } nElems -= 1; modify(); return true; } } else if (s instanceof IPersistentSet) { IPersistentSet ps = (IPersistentSet)s; if (ps.remove(obj)) { if (ps.size() == 0) { index.remove(key, ps); ps.deallocate(); } nElems -= 1; modify(); return true; } } return false; }
430b3cc1-76a5-47a5-8b08-51f3d7dab272
1
public static void main(String[] args) { String a=""; String palabra=JOptionPane.showInputDialog(null,"Ingrese uns frase : "); String []frase=palabra.split(" "); for(int i=frase.length-1;i>=0;i--) { a=a+frase[i]+" "; } JOptionPane.showMessageDialog(null, a); }
3c5c7a7d-955c-4916-af7b-389822f8b4e5
0
public void actionPerformed(ActionEvent arg0) { Component apane = environment.tabbed.getSelectedComponent(); JComponent c=(JComponent)environment.getActive(); SaveGraphUtility.saveGraph(apane, c,"PNG files", "png"); }
7880babd-fa60-4eae-bb1b-a094c28d7ae9
7
public static void DoBullyBotTurn(PlanetWars pw) { Planet source = null; double sourceScore = Double.MIN_VALUE; //Select my strongest planet to send ships from for (Planet myPlanet : pw.MyPlanets()) { if (myPlanet.NumShips() <= 1) continue; double score = (double) myPlanet.NumShips(); if (score > sourceScore) { sourceScore = score; source = myPlanet; } } Planet dest = null; double destScore = Double.MAX_VALUE; //Select weakest destination planet for (Planet notMyPlanet : pw.NotMyPlanets()) { double score = (double) (notMyPlanet.NumShips()); if (score < destScore) { destScore = score; dest = notMyPlanet; } } if (source != null && dest != null) { pw.IssueOrder(source, dest); } }
f8affff6-8584-4874-bbc3-ce207ca9b7f2
1
public static void main(String... args) { final SimpleFetcher simpleFetcher = new SimpleFetcher(); new Thread(new Runnable() { @Override public void run() { simpleFetcher.fetch(new TestCallBack()); } }).start(); logger.info("do something in main thread ..."); logger.info("do something in main thread ,,,"); logger.info("do something in main thread ///"); try { Thread.sleep(3000); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } }
525f0b36-6e9e-4560-a2c2-13565a75d861
1
public void registerEntityType(EntityType type) { log(Level.INFO, "Registering entity type %d", type.id); entityTypes.put(type.id, type); type.init(this); if (type.spawner != null) { registerEntityType(type.spawner); } }
da608ef1-0d8e-4b6f-aa48-e2a50781d35a
6
public static void kickPlayer(Player player, String playerName, String kickPlayerName, String reason) { ArrayList<Player> kickPlayers = AdminEyeUtils .requestPlayers(kickPlayerName); if (kickPlayers == null && kickPlayerName != null) { StefsAPI.MessageHandler.buildMessage().addSender(playerName) .setMessage("error.playerNotFound", AdminEye.messages) .changeVariable("playername", kickPlayerName).build(); return; } String finalReason = AdminEye.messages.getFile().getString( "normal.kickreason"); String kickedPlayers = ""; finalReason = finalReason + (reason == null ? AdminEye.messages.getFile().getString( "normal.noReasonGiven") + "%N." : reason + "%N."); for (Player kickPlayer : kickPlayers) { kickPlayer.kickPlayer(StefsAPI.MessageHandler .replaceColours(StefsAPI.MessageHandler .replacePrefixes(finalReason))); kickedPlayers += "%A" + kickPlayer.getName() + "%N, "; } kickedPlayers = (kickPlayerName.equals("*") ? kickedPlayers = AdminEye.config .getFile().getString("chat.everyone") + "%N, " : kickedPlayers); AdminEye.broadcastAdminEyeMessage( playerName, "kicked", "kick", "playernames", kickedPlayers, "reason", (reason == null ? AdminEye.messages.getFile().getString( "normal.noReasonGiven") : reason.replaceAll("&u", " "))); }
30620372-8bcb-4da4-ae50-39045cdc88ed
2
public void drawRange(Graphics g, boolean nearTrack){ if (focused){ //Turret Range g.setColor(new Color(0, 0, 0, 120)); g.fillOval(locX-(range/2), locY-(range/2), range+size, range+size); if (nearTrack){ g.setColor(new Color(6, 65, 105, 120)); } else{ g.setColor(new Color(178, 34, 34, 120)); } g.fillOval(locX-(range/2)+2, locY-(range/2)+2, range+size-4, range+size-4); } }
23f24284-f1a4-4769-8941-e4c15495b245
5
protected static Point getLowestPoint(Point[] points) { if (points.length < 1) { return null; } Point lowest = points[0]; for (Point temp : points) { if(temp.y < lowest.y || (temp.y == lowest.y && temp.x < lowest.x)) { lowest = temp; } } return lowest; }
78e4b0b6-c96b-4342-b536-9a5d60cd2b17
1
protected void readScaleFactorSelection() { for (int i = 0; i < num_subbands; ++i) ((SubbandLayer2)subbands[i]).read_scalefactor_selection(stream, crc); }
b59c52f9-833e-4393-a2d1-690d202fe095
0
public Date getCheckinDate() { return checkinDate; }
86e17d89-4db9-4b41-bc08-62e0cffcd47c
4
public static void removeFine(int fineId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("DELETE FROM Fines WHERE fine_id = ?"); stmnt.setInt(1, fineId); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); } catch(SQLException e){ System.out.println("Remove fail: " + e); } }
cddfbc38-8559-4c17-ab74-dfb5fe65f78f
1
public static BufferedImage loadImage(String s){ BufferedImage image = null; try { image = ImageIO.read(Images.class.getClass().getResourceAsStream(s)); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to load " + s + ". Shutting down system."); System.exit(0); } return image; }
8577553b-459a-4a3e-b040-392bd94ade2e
9
protected void computeRect(Raster[] sources, WritableRaster dest, Rectangle destRect) { Raster source = sources[0]; Rectangle srcRect = source.getBounds(); int formatTag = MediaLibAccessor.findCompatibleTag(sources, dest); MediaLibAccessor srcAccessor = new MediaLibAccessor(source, srcRect, formatTag); MediaLibAccessor dstAccessor = new MediaLibAccessor(dest, destRect, formatTag); // Get the scale factors in double precision double mlibScaleX = (double)scaleXRationalNum / (double)scaleXRationalDenom; double mlibScaleY = (double)scaleYRationalNum / (double)scaleYRationalDenom; // Translation to be specified to Medialib. Note that we have to // specify an additional translation since all images are 0 based // in Medialib. Note that scale and translation scalars have // rational representations. // Calculate intermediate values using rational arithmetic. long tempDenomX = scaleXRationalDenom * transXRationalDenom; long tempDenomY = scaleYRationalDenom * transYRationalDenom; long tempNumerX = (srcRect.x * scaleXRationalNum * transXRationalDenom) + (transXRationalNum * scaleXRationalDenom) - (destRect.x * tempDenomX); long tempNumerY = (srcRect.y * scaleYRationalNum * transYRationalDenom) + (transYRationalNum * scaleYRationalDenom) - (destRect.y * tempDenomY); double tx = (double)tempNumerX/(double)tempDenomX; double ty = (double)tempNumerY/(double)tempDenomY; mediaLibImage srcML[], dstML[]; switch (dstAccessor.getDataType()) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_INT: srcML = srcAccessor.getMediaLibImages(); dstML = dstAccessor.getMediaLibImages(); for (int i = 0 ; i < dstML.length; i++) { Image.ZoomTranslate(dstML[i], srcML[i], mlibScaleX, mlibScaleY, tx, ty, Constants.MLIB_BILINEAR, Constants.MLIB_EDGE_DST_NO_WRITE); MlibUtils.clampImage(dstML[i], getColorModel()); } break; case DataBuffer.TYPE_FLOAT: case DataBuffer.TYPE_DOUBLE: srcML = srcAccessor.getMediaLibImages(); dstML = dstAccessor.getMediaLibImages(); for (int i = 0 ; i < dstML.length; i++) { Image.ZoomTranslate_Fp(dstML[i], srcML[i], mlibScaleX, mlibScaleY, tx, ty, Constants.MLIB_BILINEAR, Constants.MLIB_EDGE_DST_NO_WRITE); } break; default: String className = this.getClass().getName(); throw new RuntimeException(JaiI18N.getString("Generic2")); } if (dstAccessor.isDataCopy()) { dstAccessor.clampDataArrays(); dstAccessor.copyDataToRaster(); } }
5dec03e4-44b5-4684-9af1-81500bc86c1b
8
public static void drawBoard(){ String[][] result = new String[8][8]; //make the tiles white or black boolean white = true; for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ if (white){ result[i][j] = " |"; white = false; }else{ result[i][j] = "##|"; white = true; } } white = !(white); } // draw the pieces in the right locations for (int y = 0; y < 8; y++){ for (int x = 0; x < 8; x++){ if ( gameboard.board[x][y] != null){ result[x][y] = gameboard.board[x][y].drawPiece() + "|"; } } } //print out the whole board System.out.println("_________________________"); for (int y = 0; y < 8; y++){ System.out.print("|"); for (int x = 0; x < 8; x++){ System.out.print(result[x][y]); } System.out.print(" " + (8-y)); System.out.println(); } System.out.println("\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'"); System.out.println(" a b c d e f g h"); }
2a495713-a23d-458c-a77f-69352f5be3cf
4
public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 // for (String key : map.keySet()) { // System.out.println(key + "--->" + map.get(key)); // } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; }
07b009c2-c7e7-47be-abb9-014fe80556c1
2
protected DisplayPiece rotatePiece() { DisplayPiece piece = null; Point[] temp = new Point[body.length]; //switch x,y y,x for (int i = 0; i < body.length; i++) { temp[i] = new Point(); temp[i].x = body[i].y; temp[i].y = body[i].x; } piece = new DisplayPiece(label, color, temp); piece.setPieceDims(); for (int i = 0; i < piece.body.length; i++) { temp[i].x = (piece.width - 1) - piece.body[i].x; temp[i].y = piece.body[i].y; } piece = new DisplayPiece(label, color, temp); return(piece); }
d3b68788-ff19-4395-b802-56ee474913bb
3
private boolean endRequest(Request request) { if (!this.requestTransactionLiving(request)) return false; transactionEntity tempT = this.transInfo.get(request.transaction); for (Site site : tempT.visitedSites) { if (!site.isRunning()) continue; //Commit to each visited running site site.exeRequest(new Request(null, request.transaction, RequestType.COMMIT, null)); //remove from visiting transaction set of the site this.visitingTrans.get(site).remove(tempT.name); } tempT.status = tranStatus.Commited; tempT.visitedSites = Collections.unmodifiableSet(tempT.visitedSites); System.out .println("transaction [" + tempT.name + "] have success comitted"); return true; }
7c128c28-a5c8-4787-af2b-5ddaf8ad48c3
8
public boolean collidesEntity(int x, int y) { for (Entity e: entites) { if ((e != (Entity)p) && (e.getPos_x() == x) && (e.getPos_y() == y) && (!e.isPushable())) { p.setHealth(p.getHealth()-e.getAttack()); e.setHealth(e.getHealth()-p.getAttack()); System.out.println("ATK, ENEMY HP " + e.getHealth()); if (e.isDead) { if (e.getType() == EntityType.MONSTER) { killedMonsters++; } Item drop = e.getDrop(); drop.setPos(x, y); addItem(drop); entites.remove(e); p.setExp(p.getExp() + e.getEarnsExp()); if (killedMonsters == Game.NUM_MONSTERS) { allDead = true; } } return true; } } return collidesWall(x, y); }
14fdb5fb-006f-45ba-920e-c308892285f1
8
public List<String> allUsers() { PreparedStatement stmt = null; Connection conn = null; ResultSet rs = null; List<String> users = new ArrayList<String>(); try { conn = DbConnection.getConnection(); stmt = conn.prepareStatement(ALL_USERS_STMT); rs = stmt.executeQuery(); while (rs.next()) { users.add(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); } rs.close(); rs = null; stmt.close(); stmt = null; conn.close(); conn = null; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { ; } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { ; } stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { ; } conn = null; } } return users; }
8f2de1ce-7d6c-48f8-bd74-7cd2cec00bb0
1
@Override public void remove(Component component) { if (mList != null) { mList.remove(component); } }
fd84d592-fea5-4f85-a3df-5d1be4083190
7
private static boolean compareBoolean(Node node, Argument left, Argument right) { if (left.isNull()) return right.isNull(); if (left.isBoolean()) { return right.isBoolean() && left.asBoolean() == right.asBoolean(); } if (left.isString() || left.isObject()) { return (right.isString() || right.isObject()) && left.asObject().equals(right.asObject()); } return compareNumeric(node, left, right) == 0; }