text
stringlengths
14
410k
label
int32
0
9
public void run() { NdefParser parser = new NdefParser(true); Reader reader = new ACR122Reader(true); byte[] result = null; byte[] message = null; while (!Thread.interrupted() && message == null) { try { if (reader.waitForDeviceReady(500)) { Connection con = reader.getConnection(); if(con != null) { result = con.receiveData(); parser.parse(result); message = parser.getPayload(); // System.out.println("Byte Message : " + NfcUtils.byteArrayToHexString(message)); // System.out.println("Localization : " + new String(parser.getLocale())); // System.out.println("Only Message : " + new String(message)); Handler(new String(message)); } } } catch(ParserException pe) { pe.printStackTrace(); } catch(ReaderException e) { e.printStackTrace(); } catch(ConnectionException ce) { ce.printStackTrace(); } catch(UnsupportedDeviceException usde) { usde.printStackTrace(); } try { reader.disconnect(); } catch(ReaderException e) { e.printStackTrace(); } } }
9
private DatabaseElement testButtonClick(ActionEvent evt, boolean showSuccessInfomationDialog) { DriverInfo selectedItem = (DriverInfo) driverComboBox.getSelectedItem(); String name = textName.getText(); String url = textUrl.getText(); String username = textUsername.getText(); String password = textPassword.getText(); String schema = textSchema.getText(); if (StringUtil.isEmpty(name)) { JOptionPane.showMessageDialog(this, "请输入 name.", "提示", JOptionPane.INFORMATION_MESSAGE); return null; } if (StringUtil.isEmpty(url)) { JOptionPane.showMessageDialog(this, "请输入 URL.", "提示", JOptionPane.INFORMATION_MESSAGE); return null; } if (StringUtil.isEmpty(username)) { JOptionPane.showMessageDialog(this, "请输入 Username.", "提示", JOptionPane.INFORMATION_MESSAGE); return null; } // if (StringUtil.isEmpty(password)) { // JOptionPane.showMessageDialog(this, "请输入 Password.", "提示", JOptionPane.INFORMATION_MESSAGE); // return null; // } Connection conn = null; try { DatabaseElement dbItem = new DatabaseElement(name, selectedItem.getDriverClass(), url, username, password, schema); conn = dbItem.connect(); if (conn != null) { if (showSuccessInfomationDialog) { JOptionPane.showMessageDialog(this, "连接成功.", "错误", JOptionPane.INFORMATION_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "连接失败.", "错误", JOptionPane.INFORMATION_MESSAGE); } return dbItem; } catch (ClassNotFoundException cfe) { JOptionPane.showMessageDialog(this, "找不到你选择的 JDBC Driver 类.", "错误", JOptionPane.ERROR_MESSAGE); } catch (SQLException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } finally { try { if(conn!=null){ conn.close(); } } catch (SQLException e) { } } return null; }
9
public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Format available"); } inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Instance available"); } input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - End of instance batch"); } batchFinished(); b_FirstInputFinished = true; break; default: System.err.println(this.getClass().getName() + "::firstInstanceProduced() - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Unknown source object type"); } }
8
public HTTPRequest(Vector<String> headerData, String postData, String clientIP) { this.clientIP = clientIP; Iterator<String> it = headerData.iterator(); String[] spaceSplit = it.next().split(" "); type = spaceSplit[0]; path = spaceSplit[1]; while ( it.hasNext() ) { String thisHeader[] = it.next().split(": "); headers.put(thisHeader[0], thisHeader[1]); } host = headers.get("Host").split(":")[0]; if ( type.equals("GET") ) { String[] querysplit = path.split("\\?"); path = querysplit[0]; if ( querysplit.length == 2 ) { String[] args = querysplit[1].split("&"); for ( int i = 0; i < args.length; i++ ) { String[] thisValue = args[i].split("="); if ( thisValue.length == 2 ) this.queryData.put(thisValue[0], thisValue[1]); } } } else if ( type.equals("POST") ) { String[] separatePostData = postData.split("&"); for ( int i = 0; i < separatePostData.length; i++ ) { String[] thisValue = separatePostData[i].split("="); if ( thisValue.length == 2 ) this.queryData.put(thisValue[0], thisValue[1]); } } }
8
@Override public void calculateFitness(List<Individual> population) throws Exception{ for(int i = 0; i < population.size(); i++){ try{ population.get(i).fitness(); }catch (Exception e){ int fitnessFactor = 0; MaxOnePheno pheno = (MaxOnePheno) population.get(i).phenotype(); int[] phenoArray = pheno.pheno; //Blow up targetString and compare each bit if(targetArray != null && targetArray.length != phenoArray.length){ throw new Exception("Phenotype and bit string not of equal length!"); } for(int j = 0; j < phenoArray.length; j++){ if(targetArray != null && phenoArray[j] == targetArray[j]){ fitnessFactor++; }else if(phenoArray[j] == '1') fitnessFactor++; }population.get(i).setFitness((double) fitnessFactor/ (double) phenoArray.length); } } }
8
private void delete(int row) { if (!MyFactory.getResourceService().hasRight(MyFactory.getCurrentUser(), Resource.USER_MNG)) { return; } User selectedRow = result == null ? null : result.get(row); if (selectedRow != null) { int result = JOptionPane.showConfirmDialog(null, "确定要删除" + selectedRow.getName() + "?"); if (result == JOptionPane.YES_OPTION) { boolean flag = MyFactory.getUserService().delete(selectedRow.getId()); if (flag) { JOptionPane.showMessageDialog(null, "删除成功"); refresh(); } else { JOptionPane.showMessageDialog(null, "删除失败,请重试"); } } } }
5
private byte[] encrypt(EncryptableObject o, Key key) throws Exception{ String Algrithem; if(key instanceof PublicKey){Algrithem = "RSA";} else{Algrithem = "AES";} ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray()); Cipher cipher = Cipher.getInstance(Algrithem); cipher.init(Cipher.ENCRYPT_MODE, key); ByteArrayOutputStream out = new ByteArrayOutputStream(); CipherOutputStream ciph = new CipherOutputStream(out, cipher); byte[] buf = new byte[2048]; int read; while((read=i.read(buf))!=-1){//reading data ciph.write(buf,0,read); //writing encrypted data ciph.flush(); } out.close(); ciph.close(); i.close(); return out.toByteArray(); }
2
public int createAssembly() throws IOException { logger = Log.getLogger(); logger.debug("Packing ..."); removeOldAssemblies(targetLocation); String loaderName = J2JSCompiler.compiler.getTargetPlatform().toLowerCase(); Writer writer; if ("javascript".equals(loaderName)) { writer = new FileWriter(targetLocation); pipeFileToStream(writer, "javascript/loaders/" + loaderName + ".js"); } else { targetLocation.mkdirs(); writer = new JunkWriter(targetLocation); } writer.write("// Assembly generated by j2js " + Utils.getVersion() + " on " + Utils.currentTimeStamp() + "\n"); pipeFileToStream(writer, "javascript/runtime.js"); writer.write("j2js.assemblyVersion = 'j2js Assembly " + targetLocation.getName() + "@" + Utils.currentTimeStamp() + "';\n"); writer.write("j2js.userData = {};\n"); int classCount = 0; for (ClassUnit fileUnit : project.getClasses()) { if (!fileUnit.isTainted()) continue; writer.write("j2js."); writer.write(DECLARECLASS); writer.write("(\"" + fileUnit.getSignature() + "\""); writer.write(", " + fileUnit.getSignature().getId()); writer.write(");\n"); classCount++; } project.currentGeneratedMethods = 0; if (J2JSCompiler.compiler.getSingleEntryPoint() != null) { Signature signature = project.getSignature(J2JSCompiler.compiler.getSingleEntryPoint()); ClassUnit clazz = project.getClassUnit(signature.className()); clazz.write(0, writer); } else { ClassUnit object = project.getJavaLangObject(); object.write(0, writer); for (ClassUnit cu : project.getClasses()) { // TODO Interface: Generate them nicely. if (cu.isInterface) { cu.write(0, writer); } } // for (ClassUnit cu : project.getClasses()) { // if (cu.isInterface && cu.getInterfaces().size() != 0) { // cu.write(0, writer); // } // } } if (getProject().getOrCreateClassUnit("java.lang.String").isTainted()) { writer.write("String.prototype.clazz = j2js.forName('java.lang.String');\n"); } writer.write("j2js.onLoad('" + entryPointClassName + "#main(java.lang.String[])void');\n"); // String resourcePath = J2JSCompiler.compiler.resourcePath; // if (resourcePath != null) { // resolveResources(new File(J2JSCompiler.compiler.getBaseDir(), resourcePath), writer); // } writer.close(); if ("web".equals(loaderName)) { Writer loader = new FileWriter(new File(targetLocation, "/0.js")); loader.write("var j2js = {assemblySize:"); loader.write(Integer.toString(((JunkWriter) writer).getSize())); loader.write("};\n"); pipeFileToStream(loader, "javascript/loaders/" + loaderName + ".js"); loader.close(); } return project.currentGeneratedMethods; }
8
public List<String> search(String number) { Queue<String> tempQueue = new ArrayDeque<>(); List<String> words = new LinkedList<>(); tempQueue.add(""); for (int i = 0; i < number.length(); i++) { String key = keyPad.get(number.charAt(i)); for (int qLength = tempQueue.size(); qLength > 0; qLength--) { String prefix = tempQueue.remove(); for (int j = 0; j < key.length(); j++) { String str = prefix + key.charAt(j); if (searchDictionary(str)) { words.add(str); } else { tempQueue.add(str); } } } } return words; }
4
public TokenManager(int cantidadDeTokensDeLookahead, FileReader archivo) throws FileNotFoundException, InvalidCantidadDeTokensDeLookaheadException { //Aquí seteamos el archivo a ser leído setScanner(new LexerJsonML(archivo)); //Contendra los tokens en un buffer setBufferTokens(new LinkedList()); //Definimos y validamos la cantidad de tokens de pre-análisis disponibles mediante un buffer de tokens setTamanhoDeBuffer(cantidadDeTokensDeLookahead); // Al buffer añadimos la cantidad de tokens especificados por el parámetro cantidadDeTokensDeLookahead //Ya que el valor minimo de nuestro buffer es de 1, quiere decir que en el buffer como minimo tendra siempre un elemento for (int i = 0; i < getTamanhoDeBuffer(); i++) { //El token consumido, anhadimos al buffer. getBufferTokens().addLast(getScanner().getToken()); //Si es EOF quiere decir que el token que acabe de consumir es un EOF, salimos del for y dejamos de rellenar el buffer. if (getScanner().isEOF()) { break; } } }
2
public ArrayList<Yhdistelma> yliviivattavat(){ Yhdistelma y = new Yhdistelma(kasi); ArrayList<Yhdistelma> yhdistelmat = y.getYhdistelmat(); // Kaikki kädestä saatavat yhdistelmät ArrayList<Yhdistelma> toReturn = new ArrayList<Yhdistelma>(); // Palautettavat yhdistelmät for(int i=0; i<jatsiyhdistelmat.size(); i++){ // Käydään kaikki jatsiyhdistelmät läpi for(int j=0; j<yhdistelmat.size(); j++){ // Käydään kaikki kädestä saatavat yhdistelmät läpi if(jatsiyhdistelmat.get(i)==yhdistelmat.get(j).getNimi()){ // Jos kädestä on mahdollista saada ko. yhdistelmä, ei lisätä palautettaviin continue; } if(j==yhdistelmat.size()-1){ // Ollaan päästy loppuun, eli kädestä ei ole mahdollista saada ko. yhdistelmää. Lisätään palautettaviin toReturn.add(new Yhdistelma(kasi.getNopat(), 0, jatsiyhdistelmat.get(i))); } } } for(int i=0; i<toReturn.size(); i++){ try{ vihko.getPisteet(toReturn.get(i).getNimi()); // Kokeillaan, onko vihkoon jo asetettu yhdistelmälle pisteet toReturn.remove(i); // On asetettu, joten poistetaan palautettavista i--; } catch(NoPointsException e){ // Yhdistelmälle ei ole vielä asetettu pisteitä, joten ei tehdä mitään } } return toReturn; }
6
@Override public void mouseEntered(MouseEvent e) { }
0
public int setup(String arg, ImagePlus imp) { int i; ImageStatistics stats; stats=imp.getStatistics(); if (IJ.versionLessThan("1.31l")){ IJ.error("Needs ImageJ 1.31l or newer."); return DONE; } if (stats.histogram[0]+stats.histogram[255]!=stats.pixelCount){ IJ.error("8-bit binary image (0 and 255) required."); return DONE; } if (arg.equals("about")) {showAbout(); return DONE;} showDialog("A"); //show 3x3 kernel //value[4]=0; for (i=0; i<9;i++) kernA+=Integer.toString(value[i])+" "; GenericDialog gd = new GenericDialog("Binary Thick", IJ.getInstance()); gd.addMessage("Binary Thick v1.0"); gd.addMessage("Kernel configuration"); gd.addMessage(" 1 2 3"); gd.addMessage(" 4 5 6"); gd.addMessage(" 7 8 9"); gd.addMessage(""); gd.addMessage("0=empty, 1=set, 2=don't care"); gd.addStringField ("Kernel_A", kernA,14); String [] roption={"none", "rotate 90", "rotate 45", "rotate 180", "mirror", "flip" }; gd.addChoice("Rotations", roption, roption[0]); gd.addNumericField ("Iterations (-1=all)", 1, 0); gd.addCheckbox("White foreground",false); gd.showDialog(); if (gd.wasCanceled()) return DONE; kernA=gd.getNextString(); selectedOption=gd.getNextChoice(); iterations = (int) gd.getNextNumber(); doIwhite = gd.getNextBoolean (); return DOES_8G+DOES_STACKS; }
5
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); int nCase = 1; while ((line = in.readLine()) != null && line.length() != 0) { int times = Integer.parseInt(line.trim()); if (times == 0) break; out.append("Case " + nCase++ + ":\n"); int a[] = new int[times]; for (int i = 0; i < times; i++) a[i] = Integer.parseInt(in.readLine().trim()); int nQueries = Integer.parseInt(in.readLine().trim()); for (int i = 0; i < nQueries; i++) { int q = Integer.parseInt(in.readLine().trim()); int dif = Integer.MAX_VALUE, sum = 0; for (int j = 0; j < a.length; j++) for (int k = j + 1; k < a.length; k++) if (Math.abs(a[j] + a[k] - q) < dif) { dif = Math.abs(a[j] + a[k] - q); sum = a[j] + a[k]; } out.append("Closest sum to " + q + " is " + sum + ".\n"); } } System.out.print(out); }
8
public void visitArrayRefExpr(final ArrayRefExpr expr) { if (expr.array == from) { expr.array = (Expr) to; ((Expr) to).setParent(expr); } else if (expr.index == from) { expr.index = (Expr) to; ((Expr) to).setParent(expr); } else { expr.visitChildren(this); } }
2
private static void setUpHeightmap() { try { // Load the heightmap-image from its resource file //TODO: ggf. heightmaps austauschen // BufferedImage heightmapImage = ImageIO.read(new File("res/images/heightmap.bmp")); BufferedImage heightmapImage = ImageIO.read(new File("saved.png")); // Initialise the data array, which holds the heights of the heightmap-vertices, with the correct dimensions data = new float[heightmapImage.getWidth()][heightmapImage.getHeight()]; // Lazily initialise the convenience class for extracting the separate red, green, blue, or alpha channels // an int in the default RGB color model and default sRGB colourspace. Color colour; // Iterate over the pixels in the image on the x-axis for (int z = 0; z < data.length; z++) { // Iterate over the pixels in the image on the y-axis for (int x = 0; x < data[z].length; x++) { // Retrieve the colour at the current x-location and y-location in the image colour = new Color(heightmapImage.getRGB(z, x)); // Store the value of the red channel as the height of a heightmap-vertex in 'data'. The choice for // the red channel is arbitrary, since the heightmap-image itself only has white, gray, and black. data[z][x] = colour.getRed(); } } // Create an input stream for the 'lookup texture', a texture that will used by the fragment shader to // determine which colour matches which height on the heightmap FileInputStream heightmapLookupInputStream = new FileInputStream("res/images/heightmap_lookup.png"); // Create a class that will give us information about the image file (width and height) and give us the // texture data in an OpenGL-friendly manner PNGDecoder decoder = new PNGDecoder(heightmapLookupInputStream); // Create a ByteBuffer in which to store the contents of the texture. Its size is the width multiplied by // the height and 4, which stands for the amount of bytes a float is in Java. ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight()); // 'Decode' the texture and store its data in the buffer we just created decoder.decode(buffer, decoder.getWidth() * 4, PNGDecoder.Format.RGBA); // Make the contents of the ByteBuffer readable to OpenGL (and unreadable to us) buffer.flip(); // Close the input stream for the heightmap 'lookup texture' heightmapLookupInputStream.close(); // Generate a texture handle for the 'lookup texture' lookupTexture = glGenTextures(); glBindTexture(GL_TEXTURE_2D, lookupTexture); // Hand the texture data to OpenGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } catch (IOException e) { e.printStackTrace(); } // Use the GL_NEAREST texture filter so that the sampled texel (texture pixel) is not smoothed out. Usually // using GL_NEAREST will make the textured shape appear pixelated, but in this case using the alternative, // GL_LINEAR, will make the sharp transitions between height-colours ugly. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Generate a display list handle for the display list that will store the heightmap vertex data heightmapDisplayList = glGenLists(1); // TODO: Add alternative VBO rendering for pseudo-compatibility with version 3 and higher. glNewList(heightmapDisplayList, GL_COMPILE); // Scale back the display list so that its proportions are acceptable. glScalef(0.2f, 0.06f, 0.2f); // Iterate over the 'strips' of heightmap data. for (int z = 0; z < data.length - 1; z++) { // Render a triangle strip for each 'strip'. glBegin(GL_TRIANGLE_STRIP); for (int x = 0; x < data[z].length; x++) { // Take a vertex from the current strip glVertex3f(x, data[z][x], z); // Take a vertex from the next strip glVertex3f(x, data[z + 1][x], z + 1); } glEnd(); } glEndList(); }
5
public static String dayOfWeekToText(int i) { if (i == Calendar.SUNDAY) return "Sunday"; else if (i == Calendar.MONDAY) return "Monday"; else if (i == Calendar.TUESDAY) return "Tuesday"; else if (i == Calendar.WEDNESDAY) return "Wednesday"; else if (i == Calendar.THURSDAY) return "Thursday"; else if (i == Calendar.FRIDAY) return "Friday"; else if (i == Calendar.SATURDAY) return "Saturday"; return null; }
7
public String Actualizar() { // some validations may be done here... if (usuario.equals("")) { mensaje = ""; mensaje2 = "Nombre obligatorio"; return "ActualizarUsuario?faces-redirect=true"; } else { if (clave.equals("")) { mensaje = ""; mensaje2 = "clave obligatorio"; return "ActualizarUsuario?faces-redirect=true"; } else { if (email.equals("")) { mensaje = ""; mensaje2 = "email obligatorio"; return "ActualizarUsuario?faces-redirect=true"; } else { if (nick.equals("")) { mensaje = ""; mensaje2 = "Usuario obligatorio"; return "ActualizarUsuario?faces-redirect=true"; } else { if (privacidad.equals("")) { mensaje = ""; mensaje2 = "privacidad obligatorio"; return "ActualizarUsuario?faces-redirect=true"; } else { if (clave.equals("")) { mensaje = ""; mensaje2 = "clave obligatoria"; return "ActualizarUsuario?faces-redirect=true"; } else { boolean Actualizado = false; mensaje = ""; mensaje2 = "Actualizado"; Usuario user = new Usuario(); UsuarioDAO Actusuario = new UsuarioDAO(); user.setIdUsuario(id); user.setNombre(nombreapellido); user.setUsuario(nick); user.setPassword(clave); user.setEmail(email); user.setDireccion(direccion); user.setFacebook(facebook); user.setTwittter(twitter); user.setGoogle(google); user.setPrivacidad(privacidad); Actualizado = Actusuario.ActualizarUsuario(user); if (Actualizado) { return "principal?faces-redirect=true"; } else { mensaje2 = "no se logro actualizar el usuario"; return "ActualizarUsuario?faces-redirect=true"; } } } } } } } }
7
public BigDecimal getValue(int row, int clums, int sheetat) { BigDecimal value = new BigDecimal(0); String s = null; try { hSheet = hWorkbook.getSheetAt(sheetat); hRow = hSheet.getRow(row - 1); hCell = hRow.getCell(clums - 1); hCell.setCellType(Cell.CELL_TYPE_STRING); s = hCell.getStringCellValue(); value = new BigDecimal(s).setScale(2, BigDecimal.ROUND_HALF_UP); } catch (Exception e) { value = new BigDecimal(0); } return value; }
1
public static OreVein[] loadConf( List lst ){ OreVein[] ret = new OreVein[lst.size()]; for(int i=0;i<lst.size();i++){ MemoryConfiguration nd = new MemoryConfiguration(); nd.createSection( "sec", (Map<String,Object>) lst.get(i) ); ret[i] = new OreVein(); ret[i].mat = new MVMaterial( nd.getString("sec.block","0") ); ret[i].seed = nd.getInt("sec.seed", 6516); ret[i].density = nd.getDouble("sec.density", 1); ret[i].maxSpan = nd.getDouble("sec.thickness", 5); ret[i].densBonus = nd.getDouble("sec.densityBonus", 0); ret[i].areaHeight = nd.getDouble("sec.heightAvg", 32); ret[i].areaSpan = nd.getDouble("sec.heightVar", 20); ret[i].heighRel = nd.getBoolean("sec.heighRel", false); ret[i].heightLength = nd.getDouble("sec.heightLength", 80); ret[i].densLength = nd.getDouble("sec.densLength", 80); ret[i].exclusive = nd.getBoolean("sec.exclusive", false); ret[i].addMode = nd.getString("sec.mode", "").equals("add"); if( nd.contains("sec.biomes") ){ //System.out.println("LOADING BIOMES LIST"+nd.getProperty("biomes")+": "+nd.getStringList("biomes", null)+"; "+nd.getString("biomes")); ret[i].biomes = convertStringList( nd.getStringList("sec.biomes") );} else ret[i].biomes = null; if( nd.contains("sec.exclude_biomes") ){ //System.out.println("LOADING BIOMES LIST"+nd.getProperty("biomes")+": "+nd.getStringList("biomes", null)+"; "+nd.getString("biomes")); ret[i].noBiomes = convertStringList( nd.getStringList("sec.exclude_biomes") );} else ret[i].noBiomes = null; if(MineralVein.plugin.debug){ System.out.println( "LOADED ORE: "+ret[i].mat.id ); } } return ret; }
4
public boolean playerIsAllowed(String name) { boolean bool = false; if (portCommand.containsKey(name)) { int cid = portCommand.get(name); try { Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String queryCmd = "SELECT num_uses, cooldown FROM commands WHERE c_id = " + cid; ResultSet rsCmd = statement.executeQuery(queryCmd); if (rsCmd.next()) { int cmd_num = (rsCmd.getInt("num_uses") < 0) ? Integer.MAX_VALUE : rsCmd.getInt("num_uses"); long cooldown = (rsCmd.getLong("cooldown") > 0) ? rsCmd.getLong("cooldown") : 0L; String queryPlayer = "SELECT uses, last_use FROM command_uses WHERE c_id = " + cid + " AND player = '" + name + "'"; ResultSet rsPlayer = statement.executeQuery(queryPlayer); int uses = 0; long now = System.currentTimeMillis(); long last = 0; if (rsPlayer.next()) { uses = rsPlayer.getInt("uses"); last = rsPlayer.getLong("last_use") + (cooldown * 1000L); } if (uses < cmd_num && last < now) { bool = true; } } rsCmd.close(); statement.close(); } catch (SQLException e) { plugin.debug("Could not check for command! " + e); } } return bool; }
8
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public ThanatosPhantom(int room) { super(new SoulStrike(), new Bash(), 90.0*room, 40.0*room, 0*room, 2.0*room, 80.0*room, 80.0*room, "Thanatos Phantom"); } // End DVC
0
@Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof SevenSegmentDisplay)) return false; SevenSegmentDisplay other = (SevenSegmentDisplay)obj; return other.top == this.top && other.middle == this.middle && other.bottom == this.bottom && other.upperLeft == this.upperLeft && other.upperRight == this.upperRight && other.lowerRight == this.lowerRight && other.lowerLeft == this.lowerLeft; }
8
public void setVille(String ville) { this.ville = ville; }
0
public int adjacentLivesCount(int xIndex, int yIndex) { int total = 0; if(areInBounds(xIndex-1,yIndex-1)) total+=1; if(areInBounds(xIndex-1,yIndex)) total+=1; if(areInBounds(xIndex-1,yIndex+1)) total+=1; if(areInBounds(xIndex,yIndex-1)) total+=1; if(areInBounds(xIndex,yIndex+1)) total+=1; if(areInBounds(xIndex+1,yIndex-1)) total+=1; if(areInBounds(xIndex+1,yIndex)) total+=1; if(areInBounds(xIndex+1,yIndex+1)) total+=1; return total; }
8
@Override public void keyPressed(KeyEvent e) { // Verifica si se oprime la tecla P para pausar o reanudar el juego if (e.getKeyCode() == KeyEvent.VK_P) { //Se cambia el estado de la variable pausa dependiendo de su //valor actual y desaparece el letrero de desaparece pausa = !pausa; } if (e.getKeyCode() == KeyEvent.VK_I) { //Se cambia el estado de la variable pausa dependiendo de su //valor actual y desaparece el letrero de desaparece info = !info; pausa = !pausa; } if (e.getKeyCode() == KeyEvent.VK_G) { //tecla para grabar el juego if (!info) { try { grabaArchivo(); } catch(IOException f) { System.out.println(""); } } } if (e.getKeyCode() == KeyEvent.VK_C) { // tecla para cargar el juego anterior try { leeArchivo(); } catch(IOException f) { System.out.println(""); } } //Se cambia la dirección del bueno con base en la tecla oprimida if (e.getKeyCode() == KeyEvent.VK_LEFT) { direccion = 1; } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { direccion = 2; } }
9
public BigDecimal getValue1(int row, int clums, int sheetat) { BigDecimal value = new BigDecimal(0); String s = null; try { XSSFSheet xSheet = xWorkbook.getSheetAt(sheetat); XSSFRow xRow = xSheet.getRow(row - 1); XSSFCell xCell = xRow.getCell(clums - 1); xCell.setCellType(Cell.CELL_TYPE_STRING); s = xCell.getStringCellValue(); value = new BigDecimal(s).setScale(2, BigDecimal.ROUND_HALF_UP); } catch (Exception e) { value = new BigDecimal(0); } return value; }
1
private Position getField(int xPos, int yPos) { int rectSize = myBoard.getRectSize (); int x, y; if ( myBoard.getPerspective () == WHITE ) { x = ( xPos / rectSize ) + 1; y = ( yPos / rectSize ) + 1; } else { x = AMOUNT_OF_CELLS - ( xPos / rectSize ); y = AMOUNT_OF_CELLS - ( yPos / rectSize ); } if ( x > AMOUNT_OF_CELLS || x < 1 || y > AMOUNT_OF_CELLS || y < 1 || xPos < 1 ) { // position is not on the GameField!! return null; } else { return ( new Position (x, y) ); } }
6
public static final int getPresidence( char c){ switch( c ){ case '+': return 0; case '-': return 1; case '*': return 2; case '/': return 3; case '^': return 4; default: return 100; //bad coding practice } }
5
public void invokeMain(String sClass, String[] args) throws Throwable { Class<?> clazz = loadClass(sClass); logInfo(LogArea.CONFIG, "Launch: %s.main(); Loader: %s", sClass, clazz.getClassLoader()); Method method = clazz.getMethod("main", new Class<?>[] { String[].class }); boolean bValidModifiers = false; boolean bValidVoid = false; if (method != null) { method.setAccessible(true); // Disable IllegalAccessException int nModifiers = method.getModifiers(); // main() must be "public static" bValidModifiers = Modifier.isPublic(nModifiers) && Modifier.isStatic(nModifiers); Class<?> clazzRet = method.getReturnType(); // main() must be "void" bValidVoid = (clazzRet == void.class); } if (method == null || !bValidModifiers || !bValidVoid) { throw new NoSuchMethodException( "The main() method in class \"" + sClass + "\" not found."); } // Invoke method. // Crazy cast "(Object)args" because param is: "Object... args" try { method.invoke(null, (Object)args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } // invokeMain()
9
private void addRangeData(Range r) { Docuverse docuverse = r.refersTo(); Integer begin = (Integer) r.begins(); Integer end = (Integer) r.ends(); String xpath = null; if (docuverse != null) { docuverseMap.get(docuverse).add(r); } if (begin == null) { begin = -1; /* To be indexed */ } Set<Range> beginSet = rangeBeginLocationMap.get(begin); if (beginSet == null) { beginSet = new HashSet<Range>(); rangeBeginLocationMap.put(begin, beginSet); } beginSet.add(r); if (end == null) { end = -1; /* To be indexed */ } Set<Range> endSet = rangeEndLocationMap.get(end); if (endSet == null) { endSet = new HashSet<Range>(); rangeEndLocationMap.put(end, endSet); } endSet.add(r); if (r instanceof XPathRange) { xpath = ((XPathRange)r).hasXPathContext(); if (xpath == null) { xpath = ""; } Set<Range> xpathSet = rangeXPathPointerMap.get(xpath); if (xpathSet == null) { xpathSet = new HashSet<Range>(); rangeXPathPointerMap.put(xpath, xpathSet); } xpathSet.add(r); } }
8
@SuppressWarnings("unchecked") public static <T extends Number> ArrayList<ArrayList<T>> mulSparseMatrixWithArrayMatrix(SparseMatrix a, ArrayList<ArrayList<Double>> b, Class<T> type) { try { ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>(); if (a == null || b == null) { throw new NullPointerException(); } ArrayList<ArrayList<Integer>> rowIndexes = getClone(a.getRowIndexes(), Integer.class); ArrayList<Double> values = VectorOpUtils.getClone(a.getValues(), Double.class); Collections.fill(values, 0.0); int rows = a.getSize(); int cols = b.get(0).size(); Logger.getLogger(MatrixOpUtils.class.getSimpleName()).info("sorted indexes"); for (int i = 0; i < rows; i++) { ArrayList<Integer> row = rowIndexes.get(i); if (row != null) { ArrayList<T> rowToAdd = new ArrayList<>(); for (int col = 0; col < cols; col++) { T elem = ElementOpUtils.getNeutralSumElem(type); elem = ElementOpUtils.sum(elem, ElementOpUtils.mul((T) a.getElement(i, i), (T) b.get(i).get(col), type), type); for (Integer k : row) { elem = ElementOpUtils.sum(elem, ElementOpUtils.mul((T) a.getElement(i, k), (T) b.get(k).get(col), type), type); } rowToAdd.add(elem); } result.add(rowToAdd); } } return result; } catch (NullPointerException e) { Logger.getGlobal().log(Level.SEVERE, "cannot multiply null matrixes"); e.printStackTrace(); return null; } catch (IndexOutOfBoundsException e) { Logger.getGlobal().log(Level.SEVERE, "check your indexes when multiplying matrixes"); e.printStackTrace(); return null; } }
8
public List<Component> getAllProcessorsOfType(int processorType) { List<Component> outputData = new ArrayList<Component>(); try { // Query DB, gather results into output list ResultSet res = DAO.getAllProcessorsOfType(processorType); while (res.next()) { Component newCmp = new Component(); newCmp.setId(res.getInt("processorTypeID")); newCmp.setBrand(Build.processorTypes[res.getInt("processorBrandID")]); newCmp.setName(res.getString("processorDescription")); newCmp.setCategory(Build.buildStates[0]); newCmp.setPrice(res.getInt("processorPrice")); outputData.add(newCmp); } //clean up database resources res.close(); DAO.closeStatement(); } catch(SQLException ex) { DataAccessLayer.handleSqlExceptions(ex); } return outputData; }
2
@Override public TestResult test(Object input, String... args) { if( !InputType.isPrimitiveType(input) ){ throw new IllegalArgumentException("Parameter 'input' ONLY support primitive type."); } final String regex = args[0]; final String inputS = String.valueOf(input); Pattern pattern = Pattern.compile(regex); boolean passed = pattern.matcher(inputS).matches(); String message = passed ? null : messageT; return new TestResult(passed, message); }
2
private static final byte[] encodeInteger(Integer integer) { int num_digits = 1; int int_val = integer.intValue(); while((int_val /= 10) > 0) ++num_digits; int_val = integer.intValue(); byte[] bencoded_integer = new byte[num_digits+2]; bencoded_integer[0] = (byte)'i'; bencoded_integer[bencoded_integer.length - 1] = (byte)'e'; for(int i = num_digits; i > 0; i--) { bencoded_integer[i] = (byte)((int_val % 10)+48); int_val /= 10; } return bencoded_integer; }
2
public static void setSelectedX(int x) { if (Main.selectedId != -1 && !Main.getSelected().locked) { RSInterface rsi = Main.getInterface(); if (rsi != null) { if (rsi.children != null) { rsi.childX.set(getSelectedIndex(), x); } } } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof DiningCarriage)) return false; DiningCarriage other = (DiningCarriage) obj; if (tableCount != other.tableCount) return false; return true; }
4
@Override public boolean keyDown(int keycode) { switch (keycode) { case Keys.UP: moving.add(Dir.North); return true; case Keys.DOWN: moving.add(Dir.South); return true; case Keys.RIGHT: moving.add(Dir.East); return true; case Keys.LEFT: moving.add(Dir.West); return true; case Keys.Z: A = true; return true; case Keys.X: B = true; return true; case Keys.ENTER: start = true; return true; case Keys.SHIFT_RIGHT: select = true; return true; } return false; }
8
private boolean jj_3_79() { if (jj_scan_token(YES)) return true; return false; }
1
private void Initialize(int x, int y) { // X and Y coordinate of track passed from game.java this.x = x; this.y = y; }
0
public static WeekOfMonthEnum fromValue(String v) { for (WeekOfMonthEnum c: WeekOfMonthEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
@Override public void actionPerformed(ActionEvent e) { final JButton rafraichir = (JButton) e.getSource(); new Thread(new Runnable(){ public void run() { try { Main.service.rafraichirListeLignes(); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
1
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
@Override public boolean check() { System.out.println(this.getClass().getSimpleName()); if (isLowerExists() == false) { return false; } if (isLowerEqualsCurrent() == false) { return false; } if (isUpperExists() == false) { return false; } if (shoulSwitchUpperRight()) { if (isExecuteNotClick()) { return true; } getUpper(1).click(); getUpperRight().click(); return true; } if (shouldSwitchUpperLeft()) { if (isExecuteNotClick()) { return true; } getUpper(1).click(); getUpperLeft().click(); return true; } if (shouldSwitchUpper()) { if (isExecuteNotClick()) { return true; } getUpper(1).click(); getUpper(2).click(); return true; } return false; }
9
public Model method540() { Model models[] = new Model[5]; int j = 0; for (int k = 0; k < 5; k++) { if (anIntArray661[k] != -1) { models[j++] = Model.getModel(anIntArray661[k]); } } Model model = new Model(j, models); for (int l = 0; l < 6; l++) { if (anIntArray659[l] == 0) { break; } model.swapColors(anIntArray659[l], anIntArray660[l]); } return model; }
4
public void setIpaddress(String ipaddress) { this.ipaddress = ipaddress; }
0
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String type = request.getParameter("type"); HttpRequest req = Enum.valueOf(HttpRequest.class, type.trim()); System.out.println("importantaffair " + req); String url = "2.0/index.jsp"; System.out.println(session.getAttribute("user")); if(session.getAttribute("user") != null && session.getAttribute("user").equals("admin")){ switch (req) { case addworldnode: IprocessHttpRequest iRequest = new WorldController(); System.out.println("addworldnode process"); iRequest.process(request); url = request.getHeader("Referer"); response.sendRedirect(url); break; default: break; } }else { response.sendRedirect(url); } }
3
public ClientCli(Config config, Shell shell) { this.config = config; this.shell = shell; try { socket = new Socket(config.getString("proxy.host"), config.getInt("proxy.tcp.port")); directory = config.getString("download.dir"); input = socket.getInputStream(); objectInput = new ObjectInputStream(input); output = socket.getOutputStream(); objectOutput = new ObjectOutputStream(output); objectOutput.flush(); } catch(SocketException se) { try { shell.writeLine("Could not find server."); exitWithoutConnection(); } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
4
public AbstractPlay get(int number) { return super.get(number); }
0
public Vector<String> getSessionId(){ Vector<String> resString = new Vector<String>(); CSVFileManager csvMgr = new CSVFileManager(); try { SimpleMatchParser parser = new SimpleMatchParser(TokenType.parse(csvMgr .readFile("res/SessionID.txt").getCSVObject())); List<Token> result = parser.parse(answer); System.out.println("------------ SessionID "+ result.get(0).content.split("=")[1].split("\\.")[0] +" ---------------"); resString.add(result.get(0).content.split("=")[1].split("\\.")[0]); String strName =""; for (Token tkn : result){ if (tkn.type.name.contains("Name")){ strName = tkn.content; } } System.out.println("------------ Hallo " + strName + " ---------------"); } catch (Exception e){ resString.add( e.getMessage() ); } return resString; }
3
@Override public void mousePressed(MouseEvent e) { if (!e.isConsumed() && isEnabled() && isRubberbandTrigger(e) && !e.isPopupTrigger()) { start(e.getPoint()); e.consume(); } }
4
public synchronized boolean remover(int i) { try { new AreaConhecimentoDAO().remover(list.get(i)); list = new AreaConhecimentoDAO().listar(""); preencherTabela(); } catch (Exception e) { return false; } return true; }
1
static Double M(Double[] prices, Integer[] volumes, Integer capacity) { Double[] sol, mySol; Double myFinalSol; sol = new Double[prices.length]; mySol = new Double[prices.length]; if (capacity == 0) { return 0.0; } for (int i = 0; i < prices.length; ++i) { if (capacity >= volumes[i]) { sol[i] = M(prices, volumes, capacity - volumes[i]); } else { sol[i] = 0.0; } } Double a; Double b; for (int i = 0; i < prices.length; ++i) { if (capacity >= volumes[i]) { mySol[i] = sol[i] + prices[i]; } else { mySol[i] = 0.0; } } myFinalSol = mySol[0]; for (int i = 1; i < prices.length; ++i) { if (mySol[i] > myFinalSol) { myFinalSol = mySol[i]; } } return myFinalSol; }
7
@Override public double getFalsePositiveRate(String classValue) throws IllegalArgumentException { if( classValue == null) throw new IllegalArgumentException("Error: null class value"); if( this.valueToIndex.get(classValue) == null) throw new IllegalArgumentException("Error: state = " + classValue + " didn't found"); if( this.performances.size() == 0) return Double.NaN; if( this.FPRate == null) { this.FPRate = new double[this.indexToValue.size()]; for(int i = 0; i < this.FPRate.length; ++i) this.FPRate[i] = 0.0; Iterator<PType> iterPerf = this.performances.iterator(); while(iterPerf.hasNext()) { PType perf = iterPerf.next(); for(int i = 0; i < this.FPRate.length; ++i) this.FPRate[i] += perf.getFalsePositiveRate(this.indexToValue(i)); } for(int i = 0; i < this.FPRate.length; ++i) this.FPRate[i] /= this.performances.size(); } return this.FPRate[this.valueToIndex.get(classValue)]; }
8
public void close() { closed = true; try { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); if (socket != null) socket.close(); } catch (IOException _ex) { System.out.println("Error closing stream"); } isWriter = false; synchronized (this) { notify(); } buffer = null; }
4
public AutoCompletion(final JComboBox comboBox) { this.comboBox = comboBox; model = comboBox.getModel(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!selecting) { highlightCompletedText(0); } } }); comboBox.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("editor")) { configureEditor((ComboBoxEditor) e.getNewValue()); } if (e.getPropertyName().equals("model")) { model = (ComboBoxModel) e.getNewValue(); } } }); editorKeyListener = new KeyAdapter() { public void keyPressed(KeyEvent e) { if (comboBox.isDisplayable()) { comboBox.setPopupVisible(true); } hitBackspace = false; switch (e.getKeyCode()) { // determine if the pressed key is backspace (needed by the remove method) case KeyEvent.VK_BACK_SPACE: hitBackspace = true; hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd(); break; // ignore delete key case KeyEvent.VK_DELETE: e.consume(); comboBox.getToolkit().beep(); break; } } }; // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5"); // Highlight whole text when gaining focus editorFocusListener = new FocusAdapter() { public void focusGained(FocusEvent e) { highlightCompletedText(0); } public void focusLost(FocusEvent e) { // Workaround for Bug 5100422 - Hide Popup on focus loss if (hidePopupOnFocusLoss) { comboBox.setPopupVisible(false); } } }; configureEditor(comboBox.getEditor()); // Handle initially selected object Object selected = comboBox.getSelectedItem(); if (selected != null) { setText(selected.toString()); } highlightCompletedText(0); }
8
public static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { boolean lastWasWhite = false; boolean reachedNonWhite = false; int len = string.length(); int c; for (int i = 0; i < len; i+= Character.charCount(c)) { c = string.codePointAt(i); if (isWhitespace(c)) { if ((stripLeading && !reachedNonWhite) || lastWasWhite) continue; accum.append(' '); lastWasWhite = true; } else { accum.appendCodePoint(c); lastWasWhite = false; reachedNonWhite = true; } } }
5
public void flushBase64() throws java.io.IOException { if (position > 0) { if (encode) { out.write(encode3to4(b4, buffer, position, options)); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full } // end flush
2
public Table AddTable(Table table) { if (ColSize()!=table.ColSize()) return null; // order sensitive for (int i=0; i<AttributeNames.size(); i++) { if (!table.GetAttributeName(i).equalsIgnoreCase(AttributeNames.get(i))) return null; } for (int i=0; i<table.RowSize();i++) { Insert(table.GetRow(i)); } return this; }
4
private String executeTask(String taskId) { // Prepare a request object. Request requestObject = new Request(tokenTS, taskId); // Prepare a request message. String request; try { // Attempt to serialize the request object into a string. request = serialize(requestObject); } catch (Exception e) { // If an error occurs, return it as a message. return "An error occured during serialization: " + e.getMessage(); } // Try at most 3 times to perform the execution. for (int i = 1; i <= 2; i++) { // Transmit the request. outS.transmit(request); // Prepare a Receiver for the reply. Receiver<String> inS = outS.getReceiver(); // Get a reply. String reply = inS.receive(); // Do different actions depending of the contents of the reply. switch (reply.toLowerCase()) { case "success": return "The task has been successfully executed."; case "failure": return "The task can't be executed."; case "role-mismatch": return "You don't have the permission to execute this task."; case "token-expired": // The token has expired and must be renewed. renewToken(); // Then try again. continue; default: // Reply not recognized, return as error. return "Errort: " + reply; } } return "Error: Unable to execute task."; }
6
protected void closeall(){ JInternalFrame [] x = desktop.getAllFrames(); for(int i=0 ; i<x.length ; i++){ x[i].setVisible(false); } }
1
public static BigIntStringChecksum fromString(String bics) { boolean returnIsNegative = false; BigIntStringChecksum ret = null; if (bics == null) { createThrow("Input cannot be null", bics); } if (startsWithPrefix(bics)) { String noprefix = bics.substring(PREFIX_BIGINT_DASH_CHECKSUM.length()); String noprefixnosign = noprefix; if (noprefixnosign.startsWith("-")) { returnIsNegative = true; noprefixnosign = noprefixnosign.substring(1); } String[] split = noprefixnosign.split("-"); if (split.length <= 1) { createThrow("Missing checksum section", bics); } else { String asHex = ""; if (returnIsNegative) { asHex = "-"; } for (int i = 0, n = split.length - 1; i < n; i++) { asHex += split[i]; } String computedMd5sum = computeMd5ChecksumLimit6(asHex); String givenMd5sum = split[split.length - 1]; if (computedMd5sum.equalsIgnoreCase(givenMd5sum)) { ret = new BigIntStringChecksum(asHex, computedMd5sum); } else { createThrow("Mismatch checksum given='" + givenMd5sum + "' computed='" + computedMd5sum + "'", bics); } } } else { createThrow("Input must start with '" + PREFIX_BIGINT_DASH_CHECKSUM + "'", bics); } // The call to .asBigInteger() should never throw an exception at this point. // But, if it is going to throw an exception, it is better to do it now rather than later: ret.asBigInteger(); return ret; }
7
public static double binomialPDF(double p, int n, int k) { if (k < 0 || n < 0) throw new IllegalArgumentException("\nn and k must be greater than or equal to zero"); if (k > n) throw new IllegalArgumentException("\nk is greater than n"); return Math.floor(0.5D + Math.exp(Stat.logFactorial(n) - Stat.logFactorial(k) - Stat.logFactorial(n - k))) * Math.pow(p, k) * Math.pow(1.0D - p, n - k); }
3
public static int[][] mixed(int length, int width) { int[][] r = new int[length][width]; for (int i = 0; i < length / 2; i++) { for (int j = 0; j < width; j++) { r[i][j] = (i + j) % 2; } } for (int i = length / 2; i < length; i++) { for (int j = 0; j < width; j++) { r[i][j] = j % 2; } } r[length / 4][width / 2] = 1; r[length * 3 / 4 + 1][width / 2+1] = 1; return r; }
4
protected void saveToken(HttpServletRequest request) { HttpSession session = request.getSession(); String token = generateToken(request); if (token != null) { session.setAttribute(ApplictionResources.getTransactionTokenKey(), token); request.setAttribute(ApplictionResources.getTransactionTokenKey(), token); } }
1
public void checkCollision() throws Exception{ Rectangle rCharacter = new Rectangle(WIDTH/2-32+12, HEIGHT/2-32+24, 64-24, 64+6); boolean check = true; for (int i=0;i<stoneList.size();i++) { Stone stone = (Stone) stoneList.get(i); Rectangle rStone = stone.getNextRectangle(); if (rStone.intersects(rCharacter)) { check = false; break; } } if(check == true){ moveAllComponents(); } }
3
public void setCheatingAllowed(boolean _cheating) { this.cheatsAllowed = _cheating; }
0
@Override public boolean isForwarding() { if (a == null || !a.isAlive()) return false; if (b == null || !b.isAlive()) return false; if (target == null || target.isClosed()) return false; return isActive(); }
6
public void stop() { if (stopped()) { return; } player = null; outputLine.drain(); }
1
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
public String consumeIdentifier() throws ParseException { for (int i = 0; i < currentToken.length(); i++) { final char c = currentToken.charAt(i); if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || (c == '_') || (c == '.')) { // OK } else { throw parseException("Expected identifier."); } } final String result = currentToken; nextToken(); return result; }
9
@Override public void processNode(Node node) { String namespace = node.getNamespaceURI(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", namespace); logger.debug("Searching for environments."); try { NodeList environmentNodes = Utilities.selectNodes(node, "./c:environment", namespaces); for(int i = 0; i < environmentNodes.getLength(); ++i) { Node environmentNode = environmentNodes.item(i); Environment env = new Environment(environmentNode); this.environments.put(env.getName(), env); logger.debug("Found environment '" + env.getName() + "' at: " + env.getRawEndpoint()); } } catch(Exception e) { logger.error("Unable to decode service methods.", e); } logger.info("Found " + this.environments.size() + " environments."); }
2
public void setShape(Shape shape) { this.shape = shape; }
0
@Override public void superSample(int[] input, int[] output) { int offs = this.offset; final int h = this.height; final int w = this.width; final int st = this.stride; final int[] buf1 = this.buffer1; final int[] buf2 = this.buffer2; final int count = this.dim * this.dim; final SliceIntArray src = new SliceIntArray(buf1, 0); final SliceIntArray dst = new SliceIntArray(buf2, 0); final int step = this.dim >> 1; final int stStep = st * step; final int count4 = count >> 2; for (int y=0; y<h; y+=step) { for (int x=0; x<w; x+=step) { int iOffs = offs; int n = 0; // Fill buf from input for (int j=0; j<step; j++) { for (int i=0; i<step; i+=4) { final int idx = iOffs + x + i; buf1[n] = input[idx]; buf1[n+1] = input[idx+1]; buf1[n+2] = input[idx+2]; buf1[n+3] = input[idx+3]; n += 4; } iOffs += st; } src.index = 0; dst.index = 0; src.length = count4; this.fdct.forward(src, dst); // Unpack and clear DCT high frequency bands for (int i=0; i<count; i++) buf1[i] = 0; for (int i=0; i<count4; i++) buf1[this.scan[i]] = buf2[i]; src.index = 0; dst.index = 0; src.length = count; this.idct.inverse(src, dst); int oOffs = (offs<<2) + (x<<1); n = 0; // Fill output at x,y from buf(dim x dim) for (int j=0; j<this.dim; j++) { for (int i=0; i<this.dim; i++, n++) { final int val = buf2[n]; output[oOffs+i] = (val >= 255) ? 255 : val & ~(val>>31); } oOffs += (st<<1); } } offs += stStep; } }
9
private int read1(char[] cbuf, int off, int len) throws IOException { if( nextChar >= nChars ) { /* If the requested length is at least as large as the buffer, and if there is no mark/reset activity, and if line feeds are not being skipped, do not bother to copy the characters into the local buffer. In this way buffered streams will cascade harmlessly. */ if( len >= cb.length && markedChar <= UNMARKED && !skipLF ) return in.read(cbuf, off, len); fill(); } if( nextChar >= nChars ) return -1; if( skipLF ) { skipLF = false; if( cb[nextChar] == '\n' ) { nextChar++; if( nextChar >= nChars ) fill(); if( nextChar >= nChars ) return -1; } } int n = Math.min(len, nChars - nextChar); System.arraycopy(cb, nextChar, cbuf, off, n); nextChar += n; return n; }
9
public void open() { Display display = Display.getDefault(); createContents(); shlCrisisList.open(); shlCrisisList.layout(); while (!shlCrisisList.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } }
2
public NeuronPair getNeuronPair(TYPE n1,TYPE n2){ NeuronPair np = null; for(NeuronPair pair : pairs.keySet()){ if((pair.getN1()==n1 && pair.getN2()==n2) || (pair.getN1()==n2 && pair.getN2()==n1)) np = pair; } return np; }
5
public int sendfd ( FileDescriptor passFd ) throws IOException { if ( this.streamClosed ) { throw new AFUNIXSocketException("This OutputStream has already been closed."); } try { int res = NativeUnixSocket.passFd(getFD(), passFd); if ( res == -1 ) { throw new IOException("Unspecific error while writing"); } return res; } catch ( IOException e ) { throw (IOException) new IOException(e.getMessage() + " at " + AFUNIXSocketImpl.this.toString()).initCause(e); } }
3
public Date getDate() { try { Calendar c = Calendar.getInstance(timeZone); if ((mode & DATE) != 0) { String s = dateField.getText(); c.set(Calendar.YEAR, Integer.parseInt(s.substring(0, 4))); c.set(Calendar.MONTH, Integer.parseInt(s.substring(5, 7))-1 +Calendar.JANUARY); c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(8, 10))); } else c.setTime(new Date(0)); if ((mode & TIME) != 0) { String s = timeField.getText(); c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s.substring(0, 2))); c.set(Calendar.MINUTE, Integer.parseInt(s.substring(3, 5))); } else { c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); } c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } catch (Exception e) { return null; } }
3
public Boolean checkForEqualityStudents(){ if (logger.isDebugEnabled()){ logger.debug("Called checking for equality"); } if (elemGr != null) { for (int i = 0; i < groups.size(); i++) { if (elemGr.equals(groups.get(i).getFakulty()) || elemGr.equals(groups.get(i).getNumber())){ groupNumber = groups.get(i).getNumber(); currentfakulty = groups.get(i).getFakulty(); } } } try { if (tb.getModel().getRowCount()== client.getShow(currentfakulty, groupNumber).size()){ return true; }else { return false; } }catch (ClientException e) { logger.error("Error while cheking for equality.Something wrong with client data",e); JOptionPane.showMessageDialog(frame, "Something wrong with client data while checking for equality" ); }catch(ServerException e){ logger.error("Error while cheking for equality.Somethinf wrong with client data",e); JOptionPane.showMessageDialog(frame, "Something wrong with client data while checking for equality" ); } return null; }
8
public static int maximalRectangle(char[][] matrix) { if (null == matrix || 0 == matrix.length) return 0; for (int i = 1; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if ('1' == matrix[i][j]) { matrix[i][j] = (char) (matrix[i][j] + matrix[i - 1][j] - '0'); } } } int max = 0; int[] height = new int[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { height[j] = matrix[i][j] - '0'; } int ret = largestRectangleArea(height); if (ret > max) max = ret; } return max; }
8
public void setPlayerRoles(){ // alternate who launches the ball if((roundCount % 2) == 1){ p1.setRole(ATTACK); p2.setRole(DEFEND); } else{ p1.setRole(DEFEND); p2.setRole(ATTACK); } }
1
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Route route = (Route) o; if (Double.compare(route.coeffDate, coeffDate) != 0) return false; if (Double.compare(route.coeffSeats, coeffSeats) != 0) return false; if (id != route.id) return false; if (name != null ? !name.equals(route.name) : route.name != null) return false; return true; }
8
public void restore( Map<Class<? extends IUser>, List<Map<String, Object>>> usersAccountsDescription) { if (usersAccountsDescription == null) { } if (usersAccountsDescription.isEmpty()) { } for (Class<? extends IUser> key : usersAccountsDescription.keySet()) { for (Map<String, Object> currentAccountDescription : usersAccountsDescription .get(key)) { this.addUser(restoreUser(key, currentAccountDescription)); } } }
6
protected double goldenSectionSearch(HashMap heldOutMap,double a,double b,double c,double tau,int typeCount){ assert(c>b&&b>a); double d=0; if(c-b>b-a){ d=b+resphi*(c-b); }else{ d=b-resphi*(b-a); } if(Math.abs(c-a)<tau*(Math.abs(b)+Math.abs(d))){ return (c+a)/2.0; } double prob=getLogModelProbFromMap(heldOutMap,d,typeCount); double prevProb=getLogModelProbFromMap(heldOutMap,b,typeCount); assert(prob!=prevProb); if(prob>prevProb){ if(c-b>b-a) return goldenSectionSearch(heldOutMap,b,d,c,tau,typeCount); else return goldenSectionSearch(heldOutMap,a,d,b,tau,typeCount); }else{ if(c-b>b-a) return goldenSectionSearch(heldOutMap,a,b,d,tau,typeCount); else return goldenSectionSearch(heldOutMap,d,b,c,tau,typeCount); } }
6
public Hashtable <String, Integer> getGroupByName(String groupName){ return this.groups.get(groupName); }
0
public PolicyProposalResult evaluateDeepSearch_innerMethod( TransferredFile policyFileToTransfer, TransferredFile dbSQLDumpFileToTransfer, Context initialContext, long gid2, float maxRisk) { logger.writeLog(Level.ALL,"Method evaluateDeepSearch_innerMethod, gid:"+gid+", thread number:"+Thread.currentThread().getId()); logger.writeLog(Level.ALL,("DBA_utils-Instance #"+this.toString())); this.gid = gid2; DataHandler dbDumpFileDataHandler; try { dbDumpFileDataHandler = convertZipFile(dbSQLDumpFileToTransfer, dbSQLDumpFileToTransfer.getFileName()); } catch (ZipException e2) { e2.printStackTrace(); // return "-1, Error: The given file is not a Zip file"; return null; } catch (FileNotFoundException e2) { e2.printStackTrace(); // return "-2, Error: Impossible to find the specified file"; return null; } catch (IOException e2) { e2.printStackTrace(); // return "-3, I/O Error"; return null; } Context initContext = null; /* * if initialContext == null * we expect the execution to be hosted in * an application server */ if (initialContext == null) { try { initContext = new InitialContext(); } catch (NamingException e1) { e1.printStackTrace(); } } else { // we are not in an application server context! initContext = initialContext; } if (initContext == null) { // return "-4, Error: Null context"; return null; } MySQLQueryFactory mySQLFactory = null; try { mySQLFactory = setupAndApplyDBDump(initContext, dbDumpFileDataHandler.getInputStream()); } catch (IOException e) { e.printStackTrace(); // return "-5, Problem with input DB dump"; return null; } if (mySQLFactory == null) { // return "-5, Problem with input DB dump"; return null; } PolicyProposalResult result = deepSearchEvaluator(policyFileToTransfer, "", "", true, gid, maxRisk); // results are automatically saved by DeepSearch class return result; }
8
public boolean Jion(OptimusArray a1, OptimusArray a2, OptimusArray a3, OptimusShape start, OptimusShape off,OptimusCalculator c) throws WrongArgumentException { OptimusZone z1 = ci.openZone(a1.getZid()); DataChunk chunk = new DataChunk(z1.getSize().getShape(), z1.getPstep().getShape()); do{ int id = chunk.getChunkNum(); PID p = new PID(id); try { Partition p1 = new Partition(a1.getZid(),a1.getId(),p,new RID(0)); Partition p2 = new Partition(a1.getZid(),a2.getId(),p,new RID(0)); Partition p3 = new Partition(a1.getZid(),a3.getId(),p,new RID(0)); Host h = ci.getReplicateHost(p1, new RID( 0 )); OptimusCalculatorProtocol cp = (OptimusCalculatorProtocol) h.getCalculateProtocol(); BooleanWritable b = cp.JoinArray(p1, p2, p3, c); if( b.get() ) { System.out.println("CalCulate OK"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }while(chunk.nextChunk()); return true; }
3
public int exprHashCode() { int v = 17; for (int i = 0; i < dimensions.length; i++) { v ^= dimensions[i].hashCode(); } return v; }
1
@EventHandler(priority = EventPriority.NORMAL) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); if(block.getState() instanceof Sign) { Sign sign = (Sign) block.getState(); int line = CustomFunction.isURLSign(sign); if(line == -1) return; else { Player player = event.getPlayer(); if(CustomFunction.hasPermission(player, "signurls.break")) { Material inhand = event.getPlayer().getItemInHand().getType(); if(!(inhand == Material.GOLDEN_CARROT)) { player.sendMessage(SignURLs.PREFIX + "You need to use a Golden Carrot to destroy [SignURLs] Signs."); event.setCancelled(true); } } else event.setCancelled(true); } } }
4
@Before public void setUp() { }
0
public synchronized Users getUsers(String userKey) { Users users = null; if (userKey == null || userKey.isEmpty()) return users; try { String url = this.urlManager.getUsers(Constants.APP_KEY, userKey); JSONObject jo = getJson(Methods.GET, url, null); if (!jo.has("error")) { users = new Users(jo.getString("id"), jo.getString("name"), jo.getString("mail"), jo.getString("access"), jo.getString("login"), jo.getString("created"), jo.getBoolean("enabled"), null, null ); JSONObject plan_JO = jo.getJSONObject("plan"); Plan plan = new Plan(plan_JO.getString("id"), plan_JO.getInt("concurrency"), plan_JO.getInt("engines"), plan_JO.getBoolean("isMetered"), plan_JO.getInt("threadsPerEngine"), plan_JO.getInt("threadsPerMediumEngine")); users.setPlan(plan); JSONArray locations = this.getLocations(userKey); users.setLocations(locations); } } catch (JSONException e) { BmLog.error("Error getting users: " + e); } catch (Throwable e) { BmLog.error("Error getting users: " + e); } return users; }
5
@Override public List<T> findByIdAndDeskripsi(String id, String des) throws HibernateException { DetachedCriteria crit = DetachedCriteria.forClass(getDomainClass()); String id_table = "id"; String des_table = "deskripsi"; String id_field = "id"; String des_field = "deskripsi"; for (Field field: getDomainClass().getDeclaredFields()){ Column col; if ((col = field.getAnnotation(Column.class)) != null){ if (col.name().contains("id_")) { id_table = col.name().trim(); id_field = field.getName().trim(); //System.out.println(col.name() + "\t" + col.table()); } else if (col.name().contains("kode_")) { id_field = col.name().trim(); id_field = field.getName().trim(); //System.out.println(col.name()); } if (col.name().contains("deskripsi")){ des_field = col.name(); des_field = field.getName().trim(); //System.out.println(col.name()); } else if (col.name().contains("nama_")){ des_field = col.name(); des_field = field.getName().trim(); //System.out.println(col.name()); } else if (col.name().contains("descript")){ des_field = col.name(); des_field = field.getName().trim(); //System.out.println(col.name()); } } } crit.add(Restrictions.and(Restrictions.like(id_field, id), Restrictions.like(des_field, des))); crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return getHibernateTemplate().findByCriteria(crit); }
7
public Database() { // TODO Auto-generated constructor stub }
0
void passThroughAllBits() { try { Socket destinationHost = new Socket(host, port); byte[] buf = new byte[1024]; boolean didNothing = true; while(!this.sock.isClosed() && !destinationHost.isClosed()) { didNothing = true; if (sock.getInputStream().available() > 0) { int b = sock.getInputStream().read(buf); destinationHost.getOutputStream().write(buf, 0, b); didNothing = false; } if (destinationHost.getInputStream().available() > 0) { int b = destinationHost.getInputStream().read(buf); sock.getOutputStream().write(buf, 0, b); didNothing = false; } if (didNothing) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } } } this.sock.close(); destinationHost.close(); } catch (UnknownHostException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } }
8
public Symbol insert(String name) throws RedeclarationError { // scan local list for a redeclaration of symbol with same name //System.out.println("DEBUG: symTable for inner symTable" + symTable.toString()); for(Symbol s: this.symTable){ if(s.name().equals(name)){ throw new RedeclarationError(s); } } // else it hasn't been declared. so make a new symbol and add it to // the local list Symbol tempSym = new Symbol(name); this.symTable.add(tempSym); return tempSym; }
2
public void calculateScore() { double basePoints = 750.0; double multiplier = 1.0; if(last_difficulty.equals("Easy")) { multiplier = 1.0; } else if(last_difficulty.equals("Medium")) { multiplier = 1.5; } else if(last_difficulty.equals("Hard")) { multiplier = 2.0; } else if(last_difficulty.equals("Evil")) { multiplier = 4.0; } if(last_size.equals("9x9")) { basePoints = 750.0; } else if(last_size.equals("16x16")) { basePoints = 1000.0; } current_score = (float) ((((480 / current_time) * basePoints) * multiplier) - (number_of_hints * 5.0)); updateHighScore(); }
6
@Override public RoleSchool addRoleSchool(String json, long id) { RoleSchool role = null; if (json.contains("Teacher")) { role = trans.fromJson(json, Teacher.class); } if (json.contains("Student")) { role = trans.fromJson(json, Student.class); } if (json.contains("AssistentTeacher")) { role = trans.fromJson(json, AssistentTeacher.class); } em.getTransaction().begin(); Person person = em.find(Person.class, id); if (person != null && role != null) { person.addRole(role); } em.getTransaction().commit(); return role; }
5
private static int range(int low, int high, int nUpper){ int max = 0; for(int i=low;i<high;i++){ StringBuilder sb = new StringBuilder(); Set<Character> digits = new HashSet<Character>(); for(int n=1;n<nUpper;n++){ int temp = i*n; sb.append(temp); for(char c : Integer.toString(temp).toCharArray()){ if (c!='0') digits.add(c); } } if (digits.size()==9 && sb.length()==9){ System.out.println(i); int ss = Integer.parseInt(sb.toString()); if(ss > max) max = ss; } } return max; }
7