text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); BigDecimal a, b; String[] w; do { line = in.readLine(); if (line == null || line.length() == 0) break; int times = Integer.parseInt(line); for (int i = 0; i < times; i++) { line = " " + in.readLine().replaceAll(" ", " ") + " "; line = line.replaceAll(" \\.", "0.").replaceAll(" -\\.", "-0.") .replaceAll("\\. ", ".0").replaceAll(" ", " "); w = line.trim().split(" "); a = new BigDecimal(w[0]); b = new BigDecimal(w[1]); String ans = a.add(b).toPlainString(); char[] sum = ans.toCharArray(); int index = sum.length - 1; for (; index >= 1; index--) if (sum[index] == '0' && sum[index - 1] == '.') break; else if (sum[index] != '0') break; out.append(ans.substring(0, index + 1) + "\n"); } } while (line != null && line.length() != 0); System.out.print(out); }
9
public void msgMenu() { System.out.println("0.Sair"); System.out.println("1. Criar uma nova conta"); System.out.println("2. Depositar na conta"); System.out.println("3. Sacar da conta"); System.out.println("4. Consultar o saldo"); System.out.println("5. Cadastrar cliente"); System.out.println("6. Listar clientes"); System.out.println("7. Ordenar contas por numero"); System.out.println("8. mostrar contas correntes com saldo acima de um determinado valor"); }
0
@DELETE @Path("delete/personne/{id}") public String deleteById(@PathParam("id") String arg0) { System.out.println("bien appelé "); EntityManager manager = SingletonManager.getManager(); EntityTransaction t = manager.getTransaction(); t.begin(); String res = "nok"; try { Personne p = manager.find(Personne.class,Long.parseLong(arg0)); System.out.println("**********************************************"); System.out.println("personne to delete ="+p.getNom()); //retire la personne dans les evenements ou il a participé. for (Evenement e : p.getListEvent()) { e.getParticipants().remove(p); System.out.println("remove ev_id: "+e.getId()); } System.out.println("deleting commentaire c......"); for(Commentaire c: p.getListCom()) { c.getEvenement().getListComEv().remove(c); System.out.println("remove com_id: "+c.getId()+" value = "+c.getValue()); manager.remove(c); } //supprime les evenements ou la personne est conducteur System.out.println("deleting event from driver"); for (Evenement e : p.getListEvCond()) { System.out.println("**deleting personne from event"); for(Personne p1: e.getParticipants()) { //suppression de la participation d'un participant à l'evenement p1.getListEvCond().remove(e); p1.getListEvent().remove(e); System.out.println("remove participant: "+p1.getId()); //e.getParticipants().remove(p1); //suppression des commentaires Iterator listCom = p1.getListCom().iterator(); while(listCom.hasNext() ) { Commentaire c = (Commentaire) listCom.next(); if(c.getEvenement() == e) { System.out.println("commentaire trouvé"); //c.getEvenement().getistComEv().remove(c); listCom.remove();//retire le commentaire courant de la liste de com //p1.getListCom().remove(c); manager.remove(c); } } } System.out.println("**deleting commentaire from event"); Iterator<Commentaire> iterListComEv = e.getListComEv().iterator(); while(iterListComEv.hasNext()) { Commentaire c = iterListComEv.next(); c.getPersonne().getListCom().remove(c); iterListComEv.remove(); manager.remove(c); } manager.remove(e);//supprime l'evenement si la personne est conducteur } if(p.getVoiture() != null) { manager.remove(p.getVoiture()); } manager.remove(p); System.out.println("*******finish deleteById"); res = "ok"; } catch(Exception e){ System.out.println("echec "+e.toString()); }finally{ t.commit(); } return res; }
9
@Override public void drawCell(Outline outline, Graphics gc, Rectangle bounds, Row row, Column column, boolean selected, boolean active) { if (row != null) { StdImage image = getIcon(row, column, selected, active); if (image != null) { int x = bounds.x; int y = bounds.y; if (mHAlignment != SwingConstants.LEFT) { int hDelta = bounds.width - image.getWidth(); if (mHAlignment == SwingConstants.CENTER) { hDelta /= 2; } x += hDelta; } if (mVAlignment != SwingConstants.TOP) { int vDelta = bounds.height - image.getHeight(); if (mVAlignment == SwingConstants.CENTER) { vDelta /= 2; } y += vDelta; } gc.drawImage(image, x, y, null); } } }
6
public JPanel getPWResetBtnChangesMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.pwResetBtnPanel; }
1
public Token determineToken(String st) { Token tok = new Token(); tok.setValue(st); if (st.equals("(")) { tok.setType(Token.TokenType.L_PAREN); } else if (st.equals(")")) { tok.setType(Token.TokenType.R_PAREN); } else if (Character.isDigit(st.charAt(0))) { tok.setType(Token.TokenType.NUMBER); } else if (specialSymbol.contains(st)) { tok.setType(Token.TokenType.SYMBOL); } else { tok.setType(Token.TokenType.WORD); } return tok; }
4
public FrameAddArraysData getDataWindow(){ return dataWindow; }
0
public static <T> T getTrackObjectAt(World world, int x, int y, int z, Class<T> type) { TileEntity tile = world.getTileEntity(x, y, z); if (tile == null) return null; if (type.isInstance(tile)) return (T) tile; if (tile instanceof ITrackTile) { ITrackInstance track = ((ITrackTile) tile).getTrackInstance(); if (type.isInstance(track)) return (T) track; } return null; }
4
public void signOut() throws SocketTimeoutException { try { clientSocket.Escribir("SALIR\n"); serverAnswer = clientSocket.Leer(); } catch (IOException e) { throw new SocketTimeoutException(); } System.out.println(serverAnswer); }
1
public void setRecursiveNotDirty() { super.setRecursiveNotDirty(); this.isAltitudeModeDirty = false; if(this.location!=null && this.location.isDirty()) { this.location.setRecursiveNotDirty(); } if(this.orientation!=null && this.orientation.isDirty()) { this.orientation.setRecursiveNotDirty(); } if(this.scale!=null && this.scale.isDirty()) { this.scale.setRecursiveNotDirty(); } if(this.link!=null && this.link.isDirty()) { this.link.setRecursiveNotDirty(); } }
8
public BufferedImage thresholdTransform(BufferedImage image,double threshold, int grayValue){ if(image == null){ return null; } int width = image.getWidth(); int height = image.getHeight(); //calculate color as RGB integer int color = (grayValue << 16) | (grayValue << 8) | grayValue; BufferedImage result = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY); for(int h=0;h<height;h++){ for(int w=0;w<width;w++){ int pixel = image.getRGB(w,h) & 0xff; if(pixel >= threshold){ //set to background color result.setRGB(w,h,color); }else{ result.setRGB(w,h,0); //splash 1.5 pixels if(w>1 && w<width-1 && h>1 && h<height-1){ result.setRGB(w-1,h,0); result.setRGB(w,h-1,0); result.setRGB(w+1,h,0); result.setRGB(w,h+1,0); result.setRGB(w-1,h-1,0); result.setRGB(w-1,h+1,0); result.setRGB(w+1,h-1,0); result.setRGB(w+1,h+1,0); result.setRGB(w+2,h,0); result.setRGB(w-2,h,0); result.setRGB(w,h-2,0); result.setRGB(w,h+2,0); } } } } return result; }
8
@Override public void onStop() { try { String user = Base64.encode(Environment.getDisplayName()); String timerun = Base64.encode(Long.toString((System.currentTimeMillis() - startTime))); String profits = Base64.encode(Integer.toString(profit)); String killed = Base64.encode(Integer.toString(killCount)); //ready String visagesc = Base64.encode(Integer.toString(visageCount)); final URL url = new URL( "http://tswiftkbdsignatures.net76.net/submitdata.php?user=" + user + "&timerun=" + timerun + "&profit=" + profits + "&killed=" + killed + "&visages=" + visagesc); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); final BufferedReader rd = new BufferedReader( //can you have it print URL ? new InputStreamReader(con.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.toLowerCase().contains("success")) { log.info("Successfully updated signature."); } else if (line.toLowerCase().contains("missing") || line.toLowerCase().contains("fak'd")) { log.info("Something fucked up, couldn't update."); } } rd.close(); //lastSent = System.currentTimeMillis(); System.out.println(url); } catch (Exception e) { e.printStackTrace(); } }
5
@Override public void execute() { Map<String, Ban> bans = plugin.getController().getBans(); Player receiver = getReceiver(); // prepare values HashMap<String, String> values = new HashMap<String, String>(2); values.put("{amount}", String.valueOf(bans.size())); // put output together StringBuilder builder = new StringBuilder(); builder.append(TerminalUtil.createHeadline("TimeBan info")).append("\n"); builder.append(MessagesUtil.formatMessage("info_ban_amount", values)).append("\n"); if (bans.size() > 0) { Date unbanTime = plugin.getController().getUpcomingBan().getUntil().getTime(); values.put("{unban}", unbanTime.toString()); builder.append(MessagesUtil.formatMessage("info_next_unban", values)); } String output = builder.toString(); if (receiver == null) { TerminalUtil.printToConsole(output); } else { TerminalUtil.printToPlayer(receiver, output); } }
2
@Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (surname != null ? surname.hashCode() : 0); result = 31 * result + (createDate != null ? createDate.hashCode() : 0); result = 31 * result + (deleted ? 1 : 0); return result; }
6
public MyCoastLines() { String[][] coastLineArray = getCoastLineArray(); utmPoints = new MyUTMPoint[coastLineArray.length][]; for(int i = 0; i < coastLineArray.length; i++) { utmPoints[i] = new MyUTMPoint[coastLineArray[i].length]; for(int j = 0; j < utmPoints[i].length ; j++) { if(coastLineArray[i][j] != null && !coastLineArray[i][j].contains(">")) { String[] lineArray = coastLineArray[i][j].split("\\s"); utmPoints[i][j] = toUTMPoint(Double.parseDouble(lineArray[1]), Double.parseDouble(lineArray[0])); } } } }
4
public ConsoleListener(TotalPermissions p) { plugin = p; }
0
public String getSaleid() { return this.saleid; }
0
public static String getClean(String sport) { if(sport!=null) { List<Sport> sports = getAllSport(); for(Sport sp : sports) { if(sp.name!=null && sp.name.compareTo(sport)==0) return sp.getCleanName(); } } return null; }
4
public void saveConfig() { if (config == null || configFile == null) return; try { config.save(configFile); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Could not save data to " + configFile, ex); } }
3
public static void main( String[] args ) throws java.io.FileNotFoundException, IOException { try{ String testFile; if( args.length != 0 ){ testFile = args[0]; } else{ testFile = "klein-programs\\tests02-parser\\08-print.kln"; } SemanticAnalyzer analyzer; Scanner test = new Scanner( testFile ); TableDrivenParser tdp = new TableDrivenParser( test ); tdp.parseProgram(); SemanticAction programNode = tdp.getProgramNode(); analyzer = new SemanticAnalyzer( programNode ); for( String defName: analyzer.getSymbolTable().getTable().keySet() ) { System.out.println( defName + ": " + analyzer.getSymbolTable().getTable().get( defName ).toString() ); } analyzer.analyzeTree( ); CodeGenerator.generateTMCode( testFile, programNode ); } catch(Exception e){ System.out.println( e ); } }
3
public List findByAuther(Object auther) { return findByProperty(AUTHER, auther); }
0
private void statementDecl() { next(); // To check for all of the types // if we've got modifiers, always do it... // Other conditions: ident + [] or ident + ident if (_token == TK_IDENT && (_defining || _nexttoken == TK_BRACKETS || _nexttoken == TK_IDENT)) { // if ((_defining || _token == TK_IDENT) && (_nexttoken == TK_IDENT || _nexttoken == TK_OPENBRACKET)) { String str = _string; lex(); if (_token == TK_BRACKETS) { lex(); defTypeString(str); defArray(); } else if (_token == TK_IDENT) { defTypeString(str); } } expression(); }
6
private Nodo seleccion() { ArrayList<Nodo> lis; Nodo tem = new Nodo("if", Nodo.tipoToken.PalabraReservada); if (aux.getTipo()==Nodo.tipoToken.ParentesisIzquierdo) { aux=(Tokens2)tok.next(); } else { error("Se esperaba ("); } Nodo temR = new Nodo("Condición", null); Nodo res=expresion(); if(res==null){ error("No se encontró expresión"); }else{ if(!res.getTipoDato().equals("bool")){ error("Expresión incompatible"); } } temR.addNodo(res); tem.addNodo(temR); if (aux.getTipo()==Nodo.tipoToken.ParentesisDerecho) { aux=(Tokens2)tok.next(); } else { error(" Se esperaba )"); } lis = this.listaSentencias(1); Nodo tem2 = new Nodo("Lista_Sentencias_true", null); Iterator nex = lis.iterator(); while (nex.hasNext()) { tem2.addNodo((Nodo) nex.next()); } tem.addNodo(tem2); if (aux.getToken().equals("else")) { aux=(Tokens2)tok.next(); lis.clear(); lis = listaSentencias(1); tem2 = new Nodo("Lista_Sentencias_else", null); nex = lis.iterator(); while (nex.hasNext()) { tem2.addNodo((Nodo) nex.next()); } tem.addNodo(tem2); } if (aux.getToken().equals("fi")) { aux=(Tokens2)tok.next(); } else { error(" Se esperaba fi"); } return tem; }
8
public void setIcon() { this.setIcon(this.imgIcon); }
0
@Override public void run() { if (binary) { // Sanity check if (lineFilter != null) throw new RuntimeException("Cannot apply line filter to binary output."); runBinGobbler(); } else { runLineGobbler(); } }
2
public void update () { String path = null; try { path = new File(LaunchFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getCanonicalPath(); path = URLDecoder.decode(path, "UTF-8"); Logger.logDebug("Launcher Install path: " + path);//we need this to make sure that the app behaves correctly when updating } catch (IOException e) { Logger.logError("Couldn't get path to current launcher jar/exe", e); } String temporaryUpdatePath = OSUtils.getCacheStorageLocation() + File.separator + "updatetemp" + "/" + path.substring(path.lastIndexOf(File.separator) + 1); String extension = path.substring(path.lastIndexOf('.') + 1); extension = "exe".equalsIgnoreCase(extension) ? extension : "jar"; try { URL updateURL = new URL(!useBeta ? DownloadUtils.getCreeperhostLink(downloadAddress + "." + extension) : betaAddress.replace("${ext}", extension).replace("${jenkins}", Integer.toString(betaJenk)).replace("${version}", betaStr)); File temporaryUpdate = new File(temporaryUpdatePath); temporaryUpdate.getParentFile().mkdir(); DownloadUtils.downloadToFile(updateURL, temporaryUpdate);//TODO hash check this !!!! if(useBeta && betaHash != null){ String sha = DownloadUtils.fileSHA(temporaryUpdate); if(betaHash.contains(sha)) SelfUpdate.runUpdate(path, temporaryUpdate.getCanonicalPath()); else { Logger.logDebug("TempPath" + temporaryUpdatePath); throw new IOException("Update Download failed hash check please try again! -- fileSha " + sha); } }else{ SelfUpdate.runUpdate(path, temporaryUpdatePath); } } catch (Exception e) { Logger.logError("Error while updating launcher", e); } }
7
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Couleur other = (Couleur) obj; if (this.id != other.id) { return false; } if ((this.libelle == null) ? (other.libelle != null) : !this.libelle.equals(other.libelle)) { return false; } return true; }
5
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (taskId >= 0) { return true; } // Begin hitting the server with glorious data taskId = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && taskId > 0) { plugin.getServer().getScheduler().cancelTask(taskId); taskId = -1; } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } }, 0, PING_INTERVAL * 1200); return true; } }
5
private void createCScore() throws YouFailException{ //C: (4*examScore + 13.2) of all wESubjects and oESubject //13.2 int tempScore = 0; for(Subject thisWESubject:wESubjects){ tempScore += 4 * thisWESubject.abinote; tempScore += thisWESubject.semesters[3].mark; thisWESubject.semesters[3].usedState = Semester.UsedState.mandatory; if(tempScore>=25) failer.add1ToCounter(); cScore += tempScore; tempScore = 0; } tempScore += 4 * oESubject.abinote; tempScore += oESubject.semesters[3].mark; oESubject.semesters[3].usedState = Semester.UsedState.mandatory; if(tempScore>=25) failer.add1ToCounter(); cScore += tempScore; if(!failer.checkPoints(cScore, 'c')) throw new YouFailException(); if(!failer.checkCounter('c')) throw new YouFailException(); }
5
public String toString() { if (m_Instances == null) { return "Bayesian logistic regression: No model built yet."; } StringBuffer buf = new StringBuffer(); String text = ""; switch (HyperparameterSelection) { case 1: text = "Norm-Based Hyperparameter Selection: "; break; case 2: text = "Cross-Validation Based Hyperparameter Selection: "; break; case 3: text = "Specified Hyperparameter: "; break; } buf.append(text).append(HyperparameterValue).append("\n\n"); buf.append("Regression Coefficients\n"); buf.append("=========================\n\n"); for (int j = 0; j < m_Instances.numAttributes(); j++) { if (j != ClassIndex) { if (BetaVector[j] != 0.0) { buf.append(m_Instances.attribute(j).name()).append(" : ") .append(BetaVector[j]).append("\n"); } } } buf.append("===========================\n\n"); buf.append("Likelihood: " + m_PriorUpdate.getLoglikelihood() + "\n\n"); buf.append("Penalty: " + m_PriorUpdate.getPenalty() + "\n\n"); buf.append("Regularized Log Posterior: " + m_PriorUpdate.getLogPosterior() + "\n"); buf.append("===========================\n\n"); return buf.toString(); }
7
private void activarServiciosDeProveedor(LinkedList<Servicio> servicio) { //Como estamos usando Singleton, entonces los cambios que se hagan aquí se conservarán: VtnAgrega_oModificaProveedor vtnModificaProveedor = VtnAgrega_oModificaProveedor.getInstanciaVtnAgregaoModificaProveedor(); for (Servicio serv : servicio) { /*Para cada uno de los servicios del proveedor, activamos su correspondiente CheckBox y escribimos su costo en su textField*/ if (serv.getServNombre().equals("Banquetera")) { vtnModificaProveedor.getCbBanqueteraEvento().setSelected(true); vtnModificaProveedor.getTxtBanqueterEvento().setText(Float.toString(serv.getCosto())); vtnModificaProveedor.getTxtBanqueterEvento().setEditable(true); } if (serv.getServNombre().equals("Iluminacion")) { vtnModificaProveedor.getCbLucesEvento().setSelected(true); vtnModificaProveedor.getTxtLucesEvento().setText(Float.toString(serv.getCosto())); vtnModificaProveedor.getTxtLucesEvento().setEditable(true); } if (serv.getServNombre().equals("Carpa")) { vtnModificaProveedor.getCbCarpaEvento().setSelected(true); vtnModificaProveedor.getTxtCarpaEvento().setText(Float.toString(serv.getCosto())); vtnModificaProveedor.getTxtCarpaEvento().setEditable(true); } if (serv.getServNombre().equals("Lugar")) { vtnModificaProveedor.getCbLugarEvento().setSelected(true); vtnModificaProveedor.getTxtLugarEvento().setText(Float.toString(serv.getCosto())); vtnModificaProveedor.getTxtLugarEvento().setEditable(true); } if (serv.getServNombre().equals("Musica")) { vtnModificaProveedor.getCbMusicaEvento().setSelected(true); vtnModificaProveedor.getTxtMusicaEvento().setText(Float.toString(serv.getCosto())); vtnModificaProveedor.getTxtMusicaEvento().setEditable(true); } } }
6
public void resetData(double[] x, double[] y){ this.nPoints = this.nPointsOriginal; if(x.length!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length"); if(this.nPoints!=x.length)throw new IllegalArgumentException("Original array length not matched by new array length"); for(int i=0; i<this.nPoints; i++){ this.x[i]=x[i]; this.y[i]=y[i]; } this.orderPoints(); this.checkForIdenticalPoints(); }
3
public static void main(String[] args) throws Exception { String str = "hello world wolcome nihao hehe"; char[] buffer = new char[str.length()]; str.getChars(0, str.length(), buffer, 0); FileWriter f = new FileWriter("FileWriteOutFile.txt"); for(int i=0; i < buffer.length;i ++) { f.write(buffer[i]); } f.close(); }
1
public FactoryOfPlaysForCpuForPiece (Position position, Player cpu,int largestCapture){ loadPlays(position,cpu,largestCapture); }
0
public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Integer> m=new ArrayList<Integer>(); Scanner in=new Scanner(System.in); int sum=0; int n=in.nextInt(); long mint=in.nextLong(); for(int i=0;i<mint;i++){ m.add(in.nextInt()); } //for n rooms <-- problem area long multi[][]=new long[n][100]; for(int i=0;i<n;i++){ int noofbottle =in.nextInt(); for(int j=0;j<noofbottle;j++){ //System.out.println(i+" "+j); multi[i][j]=in.nextLong(); } Arrays.sort(multi[i]); } //checking for(int i=0;i<n;i++){ for(int j=0;j<8;j++){ System.out.print(multi[i][j]); } System.out.println(" "); }//checking ended //processing Iterator<Integer> itr=m.iterator(); while(itr.hasNext()){ int temp=itr.next(); sum+=multi[temp][99]; System.out.println(multi[temp][99]); multi[itr.next()][99]=(Long) null; Arrays.sort(multi[temp]); } System.out.println(sum+" "+m); }
6
public void paintComponent (Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); x1 = (int)(CONSTANT_A*X_DIM);//determining the location to draw the outline of the calendar y1 = (int)(CONSTANT_B*Y_DIM); boxWidth = (int)(CONSTANT_C*X_DIM);//determining the dimensions of the box int boxHeight = (int)(CONSTANT_D*Y_DIM); g.setFont(TITLE_FONT); int extra = (currentMonth.getName()).length()-5;//calculate number of letters more than "March" int constant = (int) (boxWidth/10.0); int x_value = x1+(constant*4); g.drawString(currentMonth.getName()+", "+currentYear.getNumber(), x_value-(5*extra),(int)(y1/1.5));//attempt to centre g.drawImage(forwardArrow,boxWidth+x1-40,(int)(y1/3.0),null);//x values: 30-70, y values: 15-45 g.drawImage(backwardArrow,x1,(int)(y1/3.0),null);//x values: 774-814 g.drawRect(x1,y1,boxWidth, boxHeight);//line for date double h = 75.0/600; int y2 = (int)(h*Y_DIM);//position of the line g.drawLine(x1, y2,x1+boxWidth, y2); each_x = (int) (boxWidth/7.0); each_y = (int)((boxHeight-(y2-y1))/6.0); int var = x1; g.setFont(BOLD_FONT); g.drawString("Sunday",centre(var, var+=each_x,"Sunday"),(int)(y1*1.25)); g.drawString("Monday",centre(var, var+=each_x,"Monday"),(int)(y1*1.25)); g.drawString("Tuesday",centre(var, var+=each_x, "Tuesday"),(int)(y1*1.25)); g.drawString("Wednesday",centre(var, var+=each_x, "Wednesday"),(int)(y1*1.25)); g.drawString("Thursday",centre(var, var+=each_x, "Thursday"),(int)(y1*1.25)); g.drawString("Friday",centre(var, var+=each_x, "Friday"),(int)(y1*1.25)); g.drawString("Saturday",centre(var, var+=each_x, "Saturday"),(int)(y1*1.25)); int variable_x = x1; int variable_y = y2; for (int j = 0;j<6;j++)//nested loop to add boxes, loop to go through weeks in a month { variable_x = x1; for (int i = 0;i<7;i++)//loop to go through days in a week { int boxNumber = (j*7)+(i+1);//square number is the index number in the arraylist plus 1 Box tempBox = boxes.get(boxNumber-1); tempBox.setTopLeft(variable_x, variable_y); variable_x+=each_x; tempBox.setOthers(each_x, each_y); } variable_y+=each_y; } g.setFont(NORMAL_FONT); int num = currentMonth.getFirstDay(); if (num ==0) num=7; for (int i = 1;i<=currentMonth.getDaysInMonth();i++) { Box tempBox = boxes.get(i+num-1); Day currentDay = currentMonth.getDays().get(i-1); tempBox.setDayStored(currentDay); tempBox.setMonthStored(currentMonth); tempBox.setYearStored(currentYear); int [] topLeft = tempBox.getTopLeft(); g=drawBox(tempBox,g,false); g.drawString (currentDay.getNum()+"",topLeft[0]+10, topLeft[1]+20); boxes.set(i+num-1, tempBox); } Month previousMonth = currentYear.getMonths().get((CalendarFunctions.previousMonth(currentMonth.getNum())-1)); int k = previousMonth.getDaysInMonth()-num; for (int i = 0;i<num;i++) { Box tempBox = boxes.get(i); Day currentDay = previousMonth.getDays().get(k); k++; tempBox.setDayStored(currentDay); tempBox.setMonthStored(previousMonth); tempBox.setYearStored(currentYear); int [] topLeft = tempBox.getTopLeft(); g=drawBox(tempBox,g, false); g.setColor(light); g.drawString(currentDay.getNum()+"", topLeft[0]+10, topLeft[1]+20); boxes.set(i, tempBox); } Month nextMonth = currentYear.getMonths().get((CalendarFunctions.nextMonth(currentMonth.getNum())-1)); int r = 1; for (int i = currentMonth.getDaysInMonth()+num;i<boxes.size();i++) { Box tempBox = boxes.get(i); Day currentDay = nextMonth.getDays().get(r-1); r++; tempBox.setDayStored(currentDay); tempBox.setMonthStored(nextMonth); tempBox.setYearStored(currentYear); int [] topLeft = tempBox.getTopLeft(); g=drawBox(tempBox,g,false); g.setColor(light); g.drawString(currentDay.getNum()+"", topLeft[0]+10, topLeft[1]+20); boxes.set(i, tempBox); } for (int i = 0;i<boxes.size();i++) { Box tempBox = boxes.get(i); Day tempDay = tempBox.getDayStored(); Day cursorDay = cursor.getDayStored(); Month cursorMonth = cursor.getMonthStored(); Month boxMonth = tempBox.getMonthStored(); if (cursorDay.getNum()==tempDay.getNum()&&cursorMonth.getName().equals(boxMonth.getName()) ) g=drawBox(tempBox,g,true); } g.setColor(Color.black); //for (int x = x1+each_x;x<x1+boxWidth;x+=each_x) //if (x1+boxWidth-x>(int)(0.9*each_x)) //g.drawLine(x,y1, x,boxHeight+y1); //for (int y = y2;y<=y1+boxHeight;y+=each_y) //if (y1+boxHeight-y>(int)(0.9*each_y))//if the box created is greater than atleast 90% of the normal size //g.drawLine(x1, y, x1+boxWidth, y); //System.out.println(x*X_DIM); //System.out.println(y*Y_DIM); //g.drawRect(20,60,900,600);//draw the outline of the calender }
9
public void deleteService(String id) { long tempid = Long.parseLong(id); Query q = em.createQuery("SELECT t from ServiceEntity t"); for (Object o : q.getResultList()) { ServiceEntity p = (ServiceEntity) o; if (p.getId() == tempid) { p.setRooms(null); em.merge(p); em.flush(); em.remove(p); em.flush(); break; } } }
2
public static List<Point> getPointsOnLine (LineEquation line) { List<Point> ps = new ArrayList<Point>(); // x = ay + b if (line.isX()) { double y1 = line.getStart().y; double y2 = line.getEnd().y; if (line.getStart().y > line.getEnd().y) { y1 = line.getEnd().y; y2 = line.getStart().y ; } double x = line.getStart().x; for (double j = y1; j <= y2; j++) { Point point = new Point((int) x, (int) j); ps.add(point); } } // y = ax + b else { double x1 = line.getStart().x; double x2 = line.getEnd().x; double a = line.getA(); double b = line.getB(); for (double j = x1; j <= x2; j++) { double y = a * j + b; Point point = new Point((int) j, (int) y); ps.add(point); } } return ps; }
4
@Override public synchronized void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection for (ConnectThread ct : connectionAttempts.values()) ct.cancel(); connectionAttempts.clear(); // Cancel any thread currently running a connection for (ConnectedThread ct : remoteConnections.values()) ct.cancel(); remoteConnections.clear(); setState(STATE_LISTEN); // Start the thread to listen on a BluetoothServerSocket if (mSecureBluetoothServer == null) { mSecureBluetoothServer = new BluetoothServer(Rfcomm.this, true, timeout); mSecureBluetoothServer.addListener(this); mSecureBluetoothServer.start(); } if (mInsecureBluetoothServer == null) { mInsecureBluetoothServer = new BluetoothServer(Rfcomm.this, false, timeout); mSecureBluetoothServer.addListener(this); mInsecureBluetoothServer.start(); } }
5
@Override public void run() { while (true) { if (pool != null) { writer.println(System.currentTimeMillis() + "," + waitingJobs.size() + "," + runningJobs.size() + "," + pool.inUseVMCount() + "," + pool.availableVMCount()); writer.flush(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } }
3
public void debugPrint(){ System.out.println("Sentences:"); Iterator<String[]> it = sentences.iterator(); while(it.hasNext()){ String[] sentence = it.next(); for(int i = 0; i < sentence.length; i++){ System.out.print(sentence[i]); System.out.print(" "); } System.out.println(); } }
2
public void permutations(int[] num){ if(list.size() == length){ result.add(new ArrayList<Integer>(list)); return; } for(int i = 0; i< length;i++){ if(flag[i]) continue; if(i > 0 && num[i] == num[i-1] && !flag[i-1]) continue; flag[i] = true; list.add(num[i]); permutations(num); //roll back flag[i] = false; list.remove(list.size()-1); } }
6
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { String stringValue = tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus); this.tree = tree; this.hasFocus = hasFocus; setText(stringValue); if(sel) setForeground(getTextSelectionColor()); else { if (value instanceof SingleTreeNode) setForeground(Color.black); else if (value instanceof ComparatorTreeNode) setForeground(((ComparatorTreeNode) value).getColor()); } setComponentOrientation(tree.getComponentOrientation()); selected = sel; return this; }
3
public boolean leave() { return false; }
0
void initInputFrame(final ClassWriter cw, final int access, final Type[] args, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int i = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) { inputLocals[i++] = OBJECT | cw.addType(cw.thisName); } else { inputLocals[i++] = UNINITIALIZED_THIS; } } for (int j = 0; j < args.length; ++j) { int t = type(cw, args[j].getDescriptor()); inputLocals[i++] = t; if (t == LONG || t == DOUBLE) { inputLocals[i++] = TOP; } } while (i < maxLocals) { inputLocals[i++] = TOP; } }
6
public static long kadane(long[] comp) { long sum = 0, max = 0; int startRow = 0; for (int i = 0; i < m.length; i++) { sum += comp[i]; if (sum != 0) { sum = 0; startRow = i + 1; } else if (max < i - startRow + 1) max = i - startRow + 1; max = Math.max(max, comp[i] == 0 ? 1 : 0); } return max; }
4
@SuppressWarnings("deprecation") @EventHandler public void onPlayerInteractBlock(PlayerInteractEvent event) { if(event.getPlayer().hasPermission("skeptermod.useitem.godsword") || (event.getPlayer().isOp())) { if(event.getPlayer().getItemInHand().getTypeId() == Material.IRON_SWORD.getId() && event.getPlayer().getItemInHand().getEnchantmentLevel(Enchantment.DAMAGE_ALL) == 16960) { if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){ event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 200).getLocation()); event.getPlayer().setFireTicks(0); if(event.getPlayer().getHealth() < 20); event.getPlayer().setHealth(20); }} }else{ } }
7
public void scaleDown(){ switch (polygonPaint) { case 0: line.ScaleDown(); repaint(); break; case 1: curv.ScaleDown(); repaint(); break; case 2: triangle.ScaleDown(); repaint(); break; case 3: rectangle.ScaleDown(); repaint(); break; case 4: cu.ScaleDown(); repaint(); break; case 5: elipse.ScaleDown(); repaint(); break; case 6: arc.ScaleDown(); repaint(); break; } repaint(); }
7
public void visit_arraylength(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
public boolean equals(Object o) { if (!(o instanceof CompressedGameBoard)) return false; CompressedGameBoard b = (CompressedGameBoard) o; return b.fst2c == fst2c && b.snd2c == snd2c && b.trd2c == trd2c && b.lst2c == lst2c && b.flags == flags; }
5
protected void addFollowerDependent(PhysicalAgent P, PairList<PhysicalAgent,String> list, String parent) { if(P==null) return; if(list.contains(P)) return; if((P instanceof MOB) &&((!((MOB)P).isMonster())||(((MOB)P).isPossessing()))) return; CMLib.catalog().updateCatalogIntegrity(P); final String myCode=""+(list.size()-1); list.add(P,CMClass.classID(P)+"#"+myCode+parent); if(P instanceof Rideable) { final Rideable R=(Rideable)P; for(int r=0;r<R.numRiders();r++) addFollowerDependent(R.fetchRider(r),list,"@"+myCode+"R"); } if(P instanceof Container) { final Container C=(Container)P; final List<Item> contents=C.getDeepContents(); for(int c=0;c<contents.size();c++) addFollowerDependent(contents.get(c),list,"@"+myCode+"C"); } }
9
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public void copie(HDD dirSource, HDD dirDest) { // on copie chaque fichier de source dans dest // s'il existe dans dest, on teste la date de modification de fichier // afin de copier uniquement les fichiers mofifiés String nomficSRC; String nomficDST; File folder=new File(dirSource.getPath()); File[] files = folder.listFiles(); if(files==null) { parentFen.zoneTexte.append("ERREUR DE LECTURE : "+folder.getPath()+"\r\n"); return; } for (final File fileEntry : folder.listFiles()) { // impossible de remplacer dans une chaine avec des backslash donc on passe en / nomficSRC=fileEntry.getPath().replaceAll("\\\\", "/"); nomficDST=nomficSRC.replaceAll("^"+this.pathSRC0.replaceAll("\\\\", "/"),this.pathDST0.replaceAll("\\\\", "/")); // Fichier à Skipper ? if(src.myInArray(fileEntry.getPath(),src.getExclude())) // gestion des exclusions { parentFen.zoneTexte.append("SKIP : "+nomficSRC+"\r\n"); continue; } // si c'est un dossier if(fileEntry.isDirectory()) { // on poursuit dans l'arborescence this.copie(new HDD(nomficSRC,parentFen,"SOURCE"),new HDD(nomficDST,parentFen,"DESTINATION")); } // si c'est un fichier else { cptPourcent++; parentFen.lblInfo.setText((Math.round((cptPourcent*100)/nbfilesSRC))+"% "+nomficSRC+"\r"); // %tage // Le fichier source existe en dest File fileTmp=new File(nomficDST); if(fileTmp.exists()) { // On compare les dates de modification long dateSrc=fileEntry.lastModified(); long dateDst=fileTmp.lastModified(); // Fichier source modifié -> on copie if(dateSrc>dateDst) { //echo "\nSource modifiée donc copie : $nomficSRC\n"; copyStats(new File(nomficSRC),new File(nomficDST)); } // Le fichier de destination a une date différente -> on copie aussi else if(dateSrc<dateDst) { //echo "\nFichier de destination avec date différente donc copie : $nomficDST\n"; copyStats(new File(nomficSRC),new File(nomficDST)); } // Donc si date identique, pas de copie } // Le fichier source n'existe pas en dest else { // création récursive des dossiers de destination String tmp1=fileTmp.getParent(); File tmp2=new File(tmp1); if(!tmp2.isDirectory()) {tmp2.mkdirs();} // Copie du fichier copyStats(new File(nomficSRC),new File(nomficDST)); } } // else de if(is_dir($nomficSRC)) } // while() } // public void copie(...)
8
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("JSESSIONID")) { } cookie.setMaxAge(0); response.addCookie(cookie); } } HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } response.sendRedirect("offline.jsp"); }
4
private OpenResult openKey(String key, Integer accessType) { if (METHOD_OPEN_KEY == null) { METHOD_OPEN_KEY = getMethod(mRoot.getClass(), "WindowsRegOpenKey", int.class, byte[].class, int.class); } try { return new OpenResult((int[]) METHOD_OPEN_KEY.invoke(mRoot, new Object[] { mRootKey, toCstr(key), accessType })); } catch (Exception exception) { Log.error(exception); return new OpenResult(); } }
2
protected void carregaTabelaTelefones(List<Telefone> lista){ this.modeloTabelaTelefone = new DefaultTableModel(); this.modeloTabelaTelefone.addColumn("DDD"); this.modeloTabelaTelefone.addColumn("Numero"); for(Telefone t : lista){ Vector v = new Vector(); v.add(0,t.getDdd()); v.add(1,t.getNumero()); this.modeloTabelaTelefone.addRow(v); } this.tblTelefones.setModel(modeloTabelaTelefone); this.tblTelefones.repaint(); }
1
public PrimitiveUndoableCommentChange(Node node, int oldState, int newState) { this.node = node; this.oldState = oldState; this.newState = newState; }
0
public Node removeDup(Node head) { if (head == null) { return null; } Node p = head; while (p.next != null) { Node q = p; while (q.next != null) { if (p.data == q.next.data) { deleteNextNode(q); } q = q.next; } p = p.next; } return head; }
4
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed /** It can happen that the field is already filled in. So, there are 3 options: * 1.- Empty * 2.- Absolute Path * 3.- Relative path to the genfit_sas home: jgui_examples/curve.dat */ SelectFileJDialog select = new SelectFileJDialog(null, true); select.setEvent(GenfitEventType.SCATERING_FILE_SELECTED); select.genfitEvent.addListener(this); if (this.jTextFieldScatteringCurveFile.getText() != null){ /** This is case 2 **/ if (new File(this.jTextFieldScatteringCurveFile.getText()).exists()){ select.setSelectedFile(new File(this.jTextFieldScatteringCurveFile.getText())); } else{ try { String genfitFolderAbsolutePath = GenfitPropertiesReader.getGenfitFolderAbsolutePath(); /** This is case 3 **/ if (new File(genfitFolderAbsolutePath + "/" + this.jTextFieldScatteringCurveFile.getText()).exists()){ select.setSelectedFile(new File(genfitFolderAbsolutePath + "/" + this.jTextFieldScatteringCurveFile.getText())); } else{ /** Case 1 **/ select.setSelectedFile(new File(genfitFolderAbsolutePath)); } } catch (FileNotFoundException ex) { Logger.getLogger(SingleExperimentJDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SingleExperimentJDialog.class.getName()).log(Level.SEVERE, null, ex); } } } else{ try { String genfitFolderAbsolutePath = GenfitPropertiesReader.getGenfitFolderAbsolutePath(); select.setSelectedFile(new File(genfitFolderAbsolutePath)); } catch (FileNotFoundException ex) { Logger.getLogger(SingleExperimentJDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SingleExperimentJDialog.class.getName()).log(Level.SEVERE, null, ex); } } select.setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed
7
@Override public BufferedImage getObject(String name, Map<String, String> data) { // If a cache of this object already exists, return it if (cache.containsKey(name)) { return cache.get(name); } // Load the image if there is no cache of it BufferedImage loadedImage = FileManager.loadImage(data.get("fileLocation")); // Put it in our cache cache.put(name, loadedImage); return loadedImage; }
1
void initLabyrinthe(){ ArrayList<Arete> liste; int j; boolean flag; sommets.add(aretes.get(0).s1); for(int i=1;i<DIM*DIM;i++){ liste = selectAretes(); j=0; flag = false; while (!flag){ if (!sommets.contains(liste.get(j).s1)){ sommets.add(liste.get(j).s1); flag = true; } else if (!sommets.contains(liste.get(j).s2)){ sommets.add(liste.get(j).s2); flag = true; } else j++; } ouvertures.add(liste.get(j)); aretes.remove(liste.get(j)); } sortieAleatoire(); }
4
public static void getRatios(Unsigned m, Unsigned n, Unsigned t, File fout, Unsigned xOver) { BigInt.setRandSeed(1231538606138l); int pairs = m.intValue(); double[] ratios = new double[t.intValue()]; for(int j = 1; j <= t.intValue(); j++) { // generate m pairs of BigInts of length n*t int len = n.intValue() * j; BigInt[][] bigints = new BigInt[pairs][2]; for(int i = 0; i < pairs; i++) { bigints[i][0] = new BigInt(len); bigints[i][1] = new BigInt(len); } // storage for execution times long[] koTimes = new long[pairs]; long start = 0; // to record start time for(int i = 0; i < pairs; i++) { System.out.print("BigIntMul.getRatios(): computing pair " + (i + 1)); System.out.print(" of " + pairs + " with " + len + " digits.\n"); // multiple using koMul start = System.currentTimeMillis(); StudentCode.koMulOpt(bigints[i][0], bigints[i][1]); // record exe time koTimes[i] = System.currentTimeMillis() - start; } // sort array in ascending order Arrays.sort(koTimes); // store ratio = runtime / n^(lg_3) if(len >= xOver.intValue()) ratios[j - 1] = ((double)koTimes[pairs - 1] / Math.pow(len, lgPwr_)); else ratios[j - 1] = 0; } // print runtimes to output file try { BufferedWriter sOut = new BufferedWriter(new FileWriter(fout)); for(int j = (xOver.intValue()/n.intValue()) - 1; j < t.intValue(); j++) { // print in columns "integer-size ratio" sOut.write(((j + 1) * n.intValue()) + "\t" + ratios[j] + "\n"); } // record max and average ratios and print the sorted ratios in the file Arrays.sort(ratios); // sort ratio array sOut.write ("Ignoring ratios before cross over point: "+(xOver.intValue()/n.intValue())+"\n"); sOut.write ("Sorted ratios are: "); for(int i = (xOver.intValue()/n.intValue()) - 1; i < t.intValue(); i++){ sOut.write(ratios[i]+", "); } sOut.write("\n"); sOut.write("Maximum ratio is: " + ratios[t.intValue() - 1] + "\n"); sOut.write("Average ratio is: " + Arithmetic.average(ratios,(xOver.intValue()/n.intValue()) - 1)); sOut.close(); System.err.println("BigIntMul.getRatios() results printed to " + fout.getPath()); } catch (Exception e) {//Catch exception if any System.err.println("ERROR. BigInt.getRatios() IO error " + e.getMessage()); } // record ratios for later use! max_ratio_ = ratios[t.intValue() - 1]; avg_ratio_ = Arithmetic.average(ratios,(xOver.intValue()/n.intValue()) - 1); }
7
public WaitingForOpponentDialog(Game game) { this.game = game; this.setLayout(new BorderLayout()); this.setModal(false); this.setLocationRelativeTo(this.game.window.board); this.setUndecorated(true); this.setAlwaysOnTop(true); this.setModal(true); this.label.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); this.cancelButton.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); this.cancelButton.addActionListener(this); this.add(this.label, BorderLayout.CENTER); this.add(this.cancelButton, BorderLayout.PAGE_END); this.pack(); this.setVisible(true); }
0
public boolean renderPistonExtension(Block par1Block, int par2, int par3, int par4, boolean par5) { int var6 = this.blockAccess.getBlockMetadata(par2, par3, par4); int var7 = BlockPistonExtension.getDirectionMeta(var6); float var8 = par1Block.getBlockBrightness(this.blockAccess, par2, par3, par4); float var9 = par5 ? 1.0F : 0.5F; double var10 = par5 ? 16.0D : 8.0D; switch (var7) { case 0: this.uvRotateEast = 3; this.uvRotateWest = 3; this.uvRotateSouth = 3; this.uvRotateNorth = 3; par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.25F, 1.0F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodUD((double)((float)par2 + 0.375F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.25F), (double)((float)par3 + 0.25F + var9), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.625F), var8 * 0.8F, var10); this.renderPistonRodUD((double)((float)par2 + 0.625F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.25F), (double)((float)par3 + 0.25F + var9), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.375F), var8 * 0.8F, var10); this.renderPistonRodUD((double)((float)par2 + 0.375F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.25F), (double)((float)par3 + 0.25F + var9), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.625F), var8 * 0.6F, var10); this.renderPistonRodUD((double)((float)par2 + 0.625F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.25F), (double)((float)par3 + 0.25F + var9), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.375F), var8 * 0.6F, var10); break; case 1: par1Block.setBlockBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodUD((double)((float)par2 + 0.375F), (double)((float)par2 + 0.625F), (double)((float)par3 - 0.25F + 1.0F - var9), (double)((float)par3 - 0.25F + 1.0F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.625F), var8 * 0.8F, var10); this.renderPistonRodUD((double)((float)par2 + 0.625F), (double)((float)par2 + 0.375F), (double)((float)par3 - 0.25F + 1.0F - var9), (double)((float)par3 - 0.25F + 1.0F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.375F), var8 * 0.8F, var10); this.renderPistonRodUD((double)((float)par2 + 0.375F), (double)((float)par2 + 0.375F), (double)((float)par3 - 0.25F + 1.0F - var9), (double)((float)par3 - 0.25F + 1.0F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.625F), var8 * 0.6F, var10); this.renderPistonRodUD((double)((float)par2 + 0.625F), (double)((float)par2 + 0.625F), (double)((float)par3 - 0.25F + 1.0F - var9), (double)((float)par3 - 0.25F + 1.0F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.375F), var8 * 0.6F, var10); break; case 2: this.uvRotateSouth = 1; this.uvRotateNorth = 2; par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.25F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodSN((double)((float)par2 + 0.375F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.25F), (double)((float)par4 + 0.25F + var9), var8 * 0.6F, var10); this.renderPistonRodSN((double)((float)par2 + 0.625F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.25F), (double)((float)par4 + 0.25F + var9), var8 * 0.6F, var10); this.renderPistonRodSN((double)((float)par2 + 0.375F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.25F), (double)((float)par4 + 0.25F + var9), var8 * 0.5F, var10); this.renderPistonRodSN((double)((float)par2 + 0.625F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.25F), (double)((float)par4 + 0.25F + var9), var8, var10); break; case 3: this.uvRotateSouth = 2; this.uvRotateNorth = 1; this.uvRotateTop = 3; this.uvRotateBottom = 3; par1Block.setBlockBounds(0.0F, 0.0F, 0.75F, 1.0F, 1.0F, 1.0F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodSN((double)((float)par2 + 0.375F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par4 - 0.25F + 1.0F - var9), (double)((float)par4 - 0.25F + 1.0F), var8 * 0.6F, var10); this.renderPistonRodSN((double)((float)par2 + 0.625F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par4 - 0.25F + 1.0F - var9), (double)((float)par4 - 0.25F + 1.0F), var8 * 0.6F, var10); this.renderPistonRodSN((double)((float)par2 + 0.375F), (double)((float)par2 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.375F), (double)((float)par4 - 0.25F + 1.0F - var9), (double)((float)par4 - 0.25F + 1.0F), var8 * 0.5F, var10); this.renderPistonRodSN((double)((float)par2 + 0.625F), (double)((float)par2 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.625F), (double)((float)par4 - 0.25F + 1.0F - var9), (double)((float)par4 - 0.25F + 1.0F), var8, var10); break; case 4: this.uvRotateEast = 1; this.uvRotateWest = 2; this.uvRotateTop = 2; this.uvRotateBottom = 1; par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 0.25F, 1.0F, 1.0F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodEW((double)((float)par2 + 0.25F), (double)((float)par2 + 0.25F + var9), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.375F), var8 * 0.5F, var10); this.renderPistonRodEW((double)((float)par2 + 0.25F), (double)((float)par2 + 0.25F + var9), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.625F), var8, var10); this.renderPistonRodEW((double)((float)par2 + 0.25F), (double)((float)par2 + 0.25F + var9), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.375F), var8 * 0.6F, var10); this.renderPistonRodEW((double)((float)par2 + 0.25F), (double)((float)par2 + 0.25F + var9), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.625F), var8 * 0.6F, var10); break; case 5: this.uvRotateEast = 2; this.uvRotateWest = 1; this.uvRotateTop = 1; this.uvRotateBottom = 2; par1Block.setBlockBounds(0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); this.renderStandardBlock(par1Block, par2, par3, par4); this.renderPistonRodEW((double)((float)par2 - 0.25F + 1.0F - var9), (double)((float)par2 - 0.25F + 1.0F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.375F), var8 * 0.5F, var10); this.renderPistonRodEW((double)((float)par2 - 0.25F + 1.0F - var9), (double)((float)par2 - 0.25F + 1.0F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.625F), var8, var10); this.renderPistonRodEW((double)((float)par2 - 0.25F + 1.0F - var9), (double)((float)par2 - 0.25F + 1.0F), (double)((float)par3 + 0.375F), (double)((float)par3 + 0.625F), (double)((float)par4 + 0.375F), (double)((float)par4 + 0.375F), var8 * 0.6F, var10); this.renderPistonRodEW((double)((float)par2 - 0.25F + 1.0F - var9), (double)((float)par2 - 0.25F + 1.0F), (double)((float)par3 + 0.625F), (double)((float)par3 + 0.375F), (double)((float)par4 + 0.625F), (double)((float)par4 + 0.625F), var8 * 0.6F, var10); } this.uvRotateEast = 0; this.uvRotateWest = 0; this.uvRotateSouth = 0; this.uvRotateNorth = 0; this.uvRotateTop = 0; this.uvRotateBottom = 0; par1Block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); return true; }
8
private static EnumOS getOs() { String s = System.getProperty("os.name").toLowerCase(); if (s.contains("win")) { return EnumOS.windows; } if (s.contains("mac")) { return EnumOS.macos; } if (s.contains("solaris")) { return EnumOS.solaris; } if (s.contains("sunos")) { return EnumOS.solaris; } if (s.contains("linux")) { return EnumOS.linux; } if (s.contains("unix")) { return EnumOS.linux; } else { return EnumOS.unknown; } }
6
public AstarSP(EdgeWeightedDigraph G, int s, int t) { for (DirectedEdge e : G.edges()) { if (e.weight() < 0) throw new IllegalArgumentException("edge " + e + " has negative weight"); } distTo = new double[G.V()]; edgeTo = new DirectedEdge[G.V()]; x = G.getX(); y = G.getY(); for (int v = 0; v < G.V(); v++) distTo[v] = Double.POSITIVE_INFINITY; distTo[s] = 0.0; // relax vertices in order of distance from s pq = new IndexMinPQ<Double>(G.V()); pq.insert(s, distTo[s] + h(s, t)); while (!pq.isEmpty()) { int v = pq.delMin(); if (v == t) break; for (DirectedEdge e : G.adj(v)) relax(e, t); } // check optimality conditions //assert check(G, s); }
6
public Vector getRayIntersection(Edge ray) { double closestDistance = Double.MAX_VALUE; Vector closest = null; double distance; List<Vector> intersections; Polygon polygon = new Polygon(new Vector(0, 0), new Vector(Tile.SIZE, 0), new Vector(Tile.SIZE, Tile.SIZE), new Vector(0, Tile.SIZE)); for(int i = 0; i < sizeX; i++) { for(int j = 0; j < sizeY; j++) { if(getTile(i, j).visible) { polygon.translate(new Vector(i * Tile.SIZE, j * Tile.SIZE)); intersections = polygon.getRayCollisions(ray); if(intersections != null) { for(Vector vector : intersections) { distance = ray.start.getDistance(vector); if(distance < closestDistance) { closestDistance = distance; closest = vector; } } } polygon.translate(new Vector(-i * Tile.SIZE, -j * Tile.SIZE)); } } } return closest; }
6
@Override public void run(){ while(true){ if (messageQueue.size() > 0){ pullStack(); } } }
2
private TextLayout zoomTextLayout(TextLayout layout) { TextLayout zoomed = new TextLayout(Display.getCurrent()); zoomed.setText(layout.getText()); int zoomWidth = -1; if (layout.getWidth() != -1) zoomWidth = ((int) (layout.getWidth() * zoom)); if (zoomWidth < -1 || zoomWidth == 0) return null; zoomed.setFont(zoomFont(layout.getFont())); zoomed.setAlignment(layout.getAlignment()); zoomed.setAscent(layout.getAscent()); zoomed.setDescent(layout.getDescent()); zoomed.setOrientation(layout.getOrientation()); zoomed.setSegments(layout.getSegments()); zoomed.setSpacing(layout.getSpacing()); zoomed.setTabs(layout.getTabs()); zoomed.setWidth(zoomWidth); int length = layout.getText().length(); if (length > 0) { int start = 0, offset = 1; TextStyle style = null, lastStyle = layout.getStyle(0); for (; offset <= length; offset++) { if (offset != length && (style = layout.getStyle(offset)) == lastStyle) continue; int end = offset - 1; if (lastStyle != null) { TextStyle zoomedStyle = new TextStyle( zoomFont(lastStyle.font), lastStyle.foreground, lastStyle.background); zoomedStyle.metrics = lastStyle.metrics; zoomedStyle.rise = lastStyle.rise; zoomedStyle.strikeout = lastStyle.strikeout; zoomedStyle.underline = lastStyle.underline; zoomed.setStyle(zoomedStyle, start, end); } lastStyle = style; start = offset; } } return zoomed; }
8
@Override public void keyTyped(KeyEvent e) { if ((e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0) { return; } char c = e.getKeyChar(); if (c == KeyEvent.VK_BACK_SPACE) { return; } // TODO: This statement used to check \\v and \\t as well, but it was causing VK_ENTER and // VK_TAB not to be accepted // as completing the menu which resulted in a painting exception. VK_TAB and VK_ENTER are // standard for completing // an autocompletion menu, see Eclipse and Scintilla/CodeBlocks. if (c == KeyEvent.VK_ENTER || c == KeyEvent.VK_TAB || c == KeyEvent.VK_SPACE) { apply(c); e.consume(); dispose(); return; } setSelectedText(String.valueOf(c)); e.consume(); reset(); }
5
public void laheta(Palaute p) throws DAOPoikkeus { try { PalauteDAO dao = new PalauteDAO(); dao.tallennaPalaute(p); } catch (DAOPoikkeus e) { } }
1
public static File selectFileFromDialog(Component parent, String startPath, boolean showAllFiles) { if (startPath == null || parent == null) { throw new IllegalArgumentException("The arguments may not be null."); } LookAndFeel originalLookAndFeel = UIManager.getLookAndFeel(); setLookAndFeelToNimbus(); File startFile = new File(startPath); JFileChooser dialog = new JFileChooser(startFile); if (startFile.isFile()) { dialog.setSelectedFile(startFile); } if (!showAllFiles) { dialog.setFileFilter(new FileFilter() { @Override public boolean accept(File file) { return file != null && (file.isDirectory() || file.getAbsolutePath().matches(".*\\.csv")); } @Override public String getDescription() { return "*.csv"; } }); } dialog.setMultiSelectionEnabled(false); dialog.setMinimumSize(MINIMUM_SIZE); dialog.setPreferredSize(PREFERRED_SIZE); dialog.showOpenDialog(parent); File file = dialog.getSelectedFile(); setLookAndFeel(originalLookAndFeel); return file; }
6
@Override public Connection getConnection() throws DatabaseManagerException { DataSource dataSource = getDbSource(); if(dataSource == null) { throw new DatabaseManagerException("<connection> No Datasource. Cannot get a connection."); } try { return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseManagerException(e.getMessage()); } }
2
@Override protected Void doInBackground() throws Exception { List<ScriptInfo> locals = new ArrayList<ScriptInfo>(); ScriptClassLoader.loadLocal(locals, new File(Configuration.COMPILED_DIR)); for (ScriptInfo si : locals) { firePropertyChange("script", null, si); } final List<ScriptInfo> definitions = new ArrayList<ScriptInfo>(); final List<String[]> jars = SDN.getData(); final List<byte[]> scriptList = SDN.getScriptByteList(); if (jars != null) { for (int i = 0; i < scriptList.size(); i++) { try { final File file = File.createTempFile("script" + i, "jar"); final OutputStream out = new FileOutputStream(file); out.write(scriptList.get(i)); out.close(); ScriptClassLoader.load(definitions, file); if (definitions.size() > 0) { firePropertyChange("script", null, definitions.get(definitions.size() - 1)); } } catch (final Exception ignored) { ignored.printStackTrace(); } } } firePropertyChange("finished", null, null); return null; }
5
public String getDriver() { if ( this.driver == null ) return ""; return driver; }
1
private void calculateG(AStarNode checkNode) { int parentX = checkNode.getParent().getxCoord(); int parentY = checkNode.getParent().getyCoord(); int xCoord = checkNode.getxCoord(); int yCoord = checkNode.getyCoord(); if ((yCoord - 1 == parentY && xCoord == parentX) || (yCoord + 1 == parentY && xCoord == parentX) || (xCoord - 1 == parentX && yCoord == parentY) || (xCoord + 1 == parentX && yCoord == parentY)) { checkNode.setG(10); } else { checkNode.setG(14); } }
8
private void assertShallowTraceMatches(final Task<?> task, final Trace trace) { assertEquals(task.getName(), trace.getName()); assertEquals(ResultType.fromTask(task), trace.getResultType()); assertEquals(task.getShallowTrace().getStartNanos(), trace.getStartNanos()); // If the task has not been started then we expect the endNanos to be null. // If the task has started but has not been finished then endNanos is set // to the time that the trace was taken. If the task was finished then the // task end time and trace end time should match. if (trace.getResultType().equals(ResultType.UNFINISHED)) { if (trace.getStartNanos() == null) { assertNull(trace.getEndNanos()); } else { // Trace will have the end time set to the time the trace was taken assertTrue(trace.getEndNanos() <= System.nanoTime()); // We assume that the end time will always be at least one nanosecond // greater than the start time. assertTrue(trace.getEndNanos() > trace.getStartNanos()); } } else { assertEquals(task.getShallowTrace().getEndNanos(), trace.getEndNanos()); } switch (ResultType.fromTask(task)) { case SUCCESS: Object value = task.get(); assertEquals(value == null ? null : value.toString(), trace.getValue()); break; case ERROR: assertTrue(trace.getValue().contains(task.getError().toString())); break; case UNFINISHED: assertNull(trace.getValue()); break; case EARLY_FINISH: assertNull(trace.getValue()); break; } }
8
public String toString() { StringBuilder sb = new StringBuilder(); for (Card card : this) { sb.append(card.toString()); } return sb.toString(); }
1
public void setTicketStatus(String ticketStatus) { this.ticketStatus = ticketStatus; }
0
@Override public boolean onCommand(CommandSender cs, Command cmd, String s, String[] args) { if (cmd.getName().equalsIgnoreCase("ircmessage")) { if (!cs.hasPermission("royalirc.ircmessage")) { RUtils.dispNoPerms(cs); return true; } if (args.length < 3) { cs.sendMessage(cmd.getDescription()); return false; } String server = args[0]; String user = args[1]; String message = StringUtils.join(args, " ", 2, args.length); RoyalIRCBot bot = plugin.bh.getBotByServer(server); if (bot == null) { cs.sendMessage(ChatColor.RED + "No such server!"); return true; } final User u = bot.getBackend().getUserChannelDao().getUser(user); if (!plugin.bh.userInChannels(u)) { cs.sendMessage(ChatColor.RED + "That user is not in the channel!"); return true; } if (u.getNick().equalsIgnoreCase(bot.getBackend().getNick())) { cs.sendMessage(ChatColor.RED + "You can't message the bot!"); return true; } String send = Config.btuMessage; send = send.replace("{name}", cs.getName()); send = send.replace("{message}", message); if (Config.parseMinecraftColors) message = ChatColor.translateAlternateColorCodes('&', message); if (Config.allowColors) message = RUtils.minecraftColorstoIRCColors(message); else message = ChatColor.stripColor(message); u.send().message(send); String confirm = Config.btuConfirm; confirm = confirm.replace("{name}", cs.getName()); confirm = confirm.replace("{message}", message); confirm = confirm.replace("{recipient}", u.getNick()); confirm = confirm.replace("{server}", u.getServer()); cs.sendMessage(confirm); return true; } return false; }
8
@Override public IMatrix add(IMatrix other) { //ako nisu jednake dimenzije, vrati iznimku if (this.getColsCount() != other.getColsCount() || this.getRowsCount() != other.getRowsCount()) { throw new IncompatibleOperandException( "Matrices have not same dimensions."); } for (int row = 0; row < this.getRowsCount(); row++) { for (int col = 0; col < this.getColsCount(); col++) { this.set(row, col, this.get(row, col)+other.get(row, col)); } } return this; }
4
public void getResultDP(int[][] mat) { int n = mat.length; int k = 1 << n; int[][] f = new int[n + 1][1 << n]; for (int i = 0; i < n; ++i) { for (int b = 0; b < (1 << n); ++b) { for (int j = 0; j < n; ++j) { int kk = (b >> j); kk = kk & 1; if (((b >> j) & 1) == 0) { f[i + 1][b | (1 << j)] = Math.max(f[i + 1][b | (1 << j)], f[i][b] + mat[i][j]); } } } } System.out.println("ans = " + f[n][(1 << n) - 1]); }
4
@Override public void update(int delta) { super.update(delta); setMoving(false); if (Engine.isInputDown(Controls.MOVE_UP) && getCollidingEntity(Globals.DIRECTION_UP) == null) { moveY(true); } else if (Engine.isInputDown(Controls.MOVE_DOWN) && getCollidingEntity(Globals.DIRECTION_DOWN) == null) { moveY(false); } if (Engine.isInputDown(Controls.MOVE_LEFT) && getCollidingEntity(Globals.DIRECTION_LEFT) == null) { moveX(true); } else if (Engine.isInputDown(Controls.MOVE_RIGHT) && getCollidingEntity(Globals.DIRECTION_RIGHT) == null) { moveX(false); } }
8
public static String getNameFromId(int figureId) { String figureName = null; switch (figureId) { case Figure.FIGURE_ID_I: figureName = "FigureI"; break; case Figure.FIGURE_ID_T: figureName = "FigureT"; break; case Figure.FIGURE_ID_O: figureName = "FigureO"; break; case Figure.FIGURE_ID_L: figureName = "FigureL"; break; case Figure.FIGURE_ID_J: figureName = "FigureJ"; break; case Figure.FIGURE_ID_S: figureName = "FigureS"; break; case Figure.FIGURE_ID_Z: figureName = "FigureZ"; break; default: figureName = null; break; } return figureName; }
7
@Override public boolean _equals(DbData other) { List<DbRow> rows1 = this.getRow(); List<DbRow> rows2 = other.getRow(); if (rows1.size() != rows2.size()) { return false; } for (int i = 0, len = rows1.size(); i < len; ++i) { if (!rows1.get(i).equals(rows2.get(i))) { return false; } } return true; }
3
public void pan(int direction) { GCThread.increaseGCFlag(5); switch(direction) { case 1: double newUpperLeftY = upperLeftY+(utmHeight*0.1); if(newUpperLeftY >= 6412239) newUpperLeftY = 6412239; zoom(upperLeftX, newUpperLeftY, utmWidth, utmHeight, false, 0, 0, 0, 0); break; case 2: double newUpperLeftY1 = (upperLeftY-(utmHeight*0.1)); if(newUpperLeftY1-utmHeight+1000 <= 6032816) newUpperLeftY1 = upperLeftY; zoom(upperLeftX, newUpperLeftY1, utmWidth, utmHeight, false, 0, 0, 0, 0); break; case 3: double newUpperLeftX = upperLeftX-(utmWidth*0.1); if(newUpperLeftX <= 434168) newUpperLeftX = 434168; zoom(newUpperLeftX, upperLeftY, utmWidth, utmHeight, false, 0, 0, 0, 0); break; case 4: double newUpperLeftX1 = upperLeftX+(utmWidth*0.1); if(newUpperLeftX1+utmWidth >= 918958) newUpperLeftX1 = 918958-utmWidth; zoom(newUpperLeftX1, upperLeftY, utmWidth, utmHeight, false, 0, 0, 0, 0); break; } }
8
public User[] loadUsers(ChatChannel channel){ User[] users = null; try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:" + DBName; Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement(); String sqlStatement = "SELECT * FROM userchatrelations, users, userChannelRelationshipTypes " + "WHERE userchatrelations.channelID = " + channel.getChannelID() + " " + "AND userchatrelations.userid = users.uid " + "AND userChannelRelationshipTypes.ucrtID = (SELECT ucrtid FROM userChannelRelationshipTypes WHERE rtype='online')"; ResultSet rs = statement.executeQuery(sqlStatement); ArrayList<User> alstUsers = new ArrayList<>(); while(rs.next()){ User user = new User(rs.getString("juser"), null); user.setID(rs.getInt("uid")); user.setValidLogin(true); user.setNick(rs.getString("jnick")); user.setLevel(rs.getInt("level")); user.setCurrentExp(rs.getInt("currentExp")); user.setrCoins(rs.getInt("rcoins")); user.setvCoins(rs.getInt("vcoins")); user.setPoints(rs.getInt("points")); user.setLastLogin(rs.getTimestamp("jlastloggin")); alstUsers.add(user); } users = alstUsers.toArray(new User[0]); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } return users; }
2
public String getOwnerName(){ return human.getName(); }
0
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(myHost instanceof MOB)) return super.okMessage(myHost,msg); final MOB myChar=(MOB)myHost; if(!super.okMessage(myChar, msg)) return false; if((msg.amITarget(myChar)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.sourceMinor()==CMMsg.TYP_FIRE)) { final int recovery=myChar.charStats().getClassLevel(this); msg.setValue(msg.value()-recovery); } else if((msg.amITarget(myChar)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.sourceMinor()==CMMsg.TYP_COLD)) { final int recovery=msg.value(); msg.setValue(msg.value()+recovery); } return true; }
8
public void onAnswerSideChanged(AnswerSide answerSide) { if (answerSide == null) { removeSelection(); return; } switch (answerSide) { case LEFT: selectSingleScorePanel(AnswerSide.LEFT); break; case RIGHT: selectSingleScorePanel(AnswerSide.RIGHT); break; } }
3
private static int getRemoteVersion() { URL url = null; try { url = new URL(SERVER_URL + "version.txt"); } catch (MalformedURLException e2) { e2.printStackTrace(); } try { URLConnection urlConnection = url.openConnection(); urlConnection.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); byte buffer[] = new byte[1000]; int numRead = urlStream.read(buffer); String content = new String(buffer, 0, numRead); while ((numRead != -1) && (content.length() < 1024)) { numRead = urlStream.read(buffer); if (numRead != -1) { String newContent = new String(buffer, 0, numRead); content += newContent; } } content = content.trim(); System.out.println("Remote version is " + content + "."); return Integer.valueOf(content); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e1) { e1.printStackTrace(); } return -1; }
6
private Constructor filterConstructorsUnsafe(Constructor[] constructors, Class[] parameterTypes) { outside2: for(Constructor c : constructors) { if(parameterTypes != null) { Class[] p = c.getParameterTypes(); if(p.length != parameterTypes.length) { continue; } for(int i = 0; i < p.length; i++) { if((parameterTypes[i] != null) && !p[i].equals(parameterTypes[i])) { continue outside2; } } } return c; } return null; }
6
public void print(final String txt) { log(txt); }
0
@Override public void mouseDragged(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. if (e.getSource().equals(EditingPane)) { long hereIAm = System.currentTimeMillis(); bg.setStroke(new BasicStroke(thickness.getValue(),BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND)); if (doodles[kind]==null) { bg.setColor(colors[kind]); } else { bg.setPaint(doodles[kind]); } if (hereIAm-timeNoSee<100) { bg.drawLine(x, y, e.getX(), e.getY()); //FillLine(x,y,e.getX(),e.getY(),thickness.getValue(),(byte)kind); synchronized (bufferedStrokes) { bufferedStrokes.add(new BrushStroke(x,y,e.getX(),e.getY(),thickness.getValue(),kind)); buffering.setValue(0); max = bufferedStrokes.size(); count = 0; buffering.setForeground(Color.red); } //bg.fillArc(x-2, y-2, 4,4, 0, 360); //bg.fillArc(e.getX()-2, e.getY()-2, 4,4, 0, 360); EditingPane.getGraphics().drawImage(bi, 0, 0, rootPane); } x = e.getX(); y = e.getY(); timeNoSee = hereIAm; } if (e.getSource().equals(jScrollPane1)) { EditingPane.getGraphics().drawImage(bi, 0, 0, rootPane); } }
4
public Tileset getTileset() { return tileset; }
0
@Override public void render() { glEnable(GL_BLEND); if (texture != null) { RenderAssistant.bindTexture(texture); if (!stackTexture) RenderAssistant.renderRect(x, y, width, height); else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); RenderAssistant.renderRect(x, y, width, height, 0, 0, width / (float) texW, height / (float) texH); } } glDisable(GL_BLEND); int tx = FontAssistant.getFont(font).getWidth(title); int mx = width / 2 - tx / 2; glColor3f(color.x, color.y, color.z); RenderAssistant.renderText(x + ((width > -1 && center) ? mx : 0), y + ((height > -1) ? height / 4f : 0), title, font); }
5
public void scalarDivide(double Denominator) { for (Entry<Integer, Double> entry : this.getVector().entrySet()) { entry.setValue(entry.getValue()/Denominator); } }
1
@RequestMapping("/comprar/{producto}") public ModelAndView comprar(@PathVariable String producto) { Stock stock = Stock.getInstance(); Integer availableStock = stock.obtenerStockDisponible(producto); ModelMap model = new ModelMap(); model.put("producto", producto); model.put("stock", availableStock); return new ModelAndView("comprarProducto", model); }
0
private void getUserInformation(){ if(userId!=null){ try { ResultSet userInfo = dataBaseConnector.getUserInformation(userId); userInfo.next(); scores = userInfo.getInt("scores"); money = userInfo.getInt("money"); currentTank = userInfo.getInt("tank"); userInfo = dataBaseConnector.getUserTanks(userId); while(userInfo.next()){ garage.addTank( userInfo.getInt("id_tank"), userInfo.getInt("tank"), userInfo.getInt("armor"), userInfo.getInt("engine"), userInfo.getInt("first_weapon"), userInfo.getInt("second_weapon") ); } userInfo = dataBaseConnector.getUserArmor(userId); while(userInfo.next()){ garage.addArmor(userInfo.getInt("armor")); } userInfo = dataBaseConnector.getUserEngine(userId); while(userInfo.next()){ garage.addEngine(userInfo.getInt("engine")); } userInfo = dataBaseConnector.getUserFirstWeapon(userId); while(userInfo.next()){ garage.addFirstWeapon(userInfo.getInt("first_weapon")); } userInfo = dataBaseConnector.getUserSecondWeapon(userId); while(userInfo.next()){ garage.addSecondWeapon(userInfo.getInt("second_weapon")); } } catch (Exception e) { e.printStackTrace(); close(); } } }
7
public MapEditor() { //set frame properties setTitle("Map Editor"); setSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); setBackground(Color.gray); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Close when closed.For reals. //set the content of the frame try{ File file=new File("purdue-map.jpg"); Image image = (Image)ImageIO.read(file); _map = new MapScene(image); }catch(Exception e){ System.out.println(e.getMessage()); } _zoomPane = new ZoomPane(_map); _textarea=new JTextArea("Welcome to Map Editor!", 20, 20); _textarea.setEditable(false); _text=new JScrollPane(); _text.getViewport().add(_textarea); //add components to frame getContentPane().setLayout(new BorderLayout()); getContentPane().add(_text,BorderLayout.WEST); getContentPane().add(_zoomPane,BorderLayout.CENTER); getContentPane().add(_zoomPane.getJSlider(),BorderLayout.SOUTH); //add actionlistener to the menuitems save.addActionListener(this); saveas.addActionListener(this); openfile.addActionListener(this); newfile.addActionListener(this); fileinfo.addActionListener(this); insertloc.addActionListener(this); deleteloc.addActionListener(this); insertpath.addActionListener(this); deletepath.addActionListener(this); location.addActionListener(this); find.addActionListener(this); directions.addActionListener(this); readme.addActionListener(this); //add menuitems to menus file.add(newfile); file.add(openfile); file.add(save); file.add(saveas); file.add(fileinfo); mode.add(insertloc); mode.add(deleteloc); mode.add(insertpath); mode.add(deletepath); mode.add(location); function.add(find); function.add(directions); help.add(readme); editor.add(file); editor.add(mode); editor.add(function); editor.add(help); //set menu bar of the frame setJMenuBar(editor); //MouseAdapter & MouseMotionAdapter for _zoomPane MouseAdapter listener = new MouseAdapter() { public void mousePressed(MouseEvent e) { Point point = _zoomPane.toViewCoordinates(e.getPoint()); if(point.getX()>_map.getWidth() || point.getY()>_map.getHeight()){ return; } _map.mousePressed(point); } public void mouseClicked(MouseEvent e){ //System.out.println("mouseclicked"); int times=e.getClickCount(); Point point = _zoomPane.toViewCoordinates(e.getPoint()); if(point.getX()>_map.getWidth() || point.getY()>_map.getHeight()){ return; } if(times==1){ _map.mouseSingleClicked(point); } if(times==2){ _map.mouseDoubleClicked(point); } } }; MouseMotionAdapter motionListener = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Point point = _zoomPane.toViewCoordinates(e.getPoint()); if(point.getX()>_map.getWidth() || point.getY()>_map.getHeight()){ return; } _map.mouseDragged(point); } }; //add MouseAdapter & MouseMotionAdapter to _zoomPane _zoomPane.getZoomPanel().addMouseListener(listener); _zoomPane.getZoomPanel().addMouseMotionListener(motionListener); }
9