text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) { try { // Print out 10 hashes for(int i = 0; i < 10; i++) System.out.println(PasswordHash.createHash("p\r\nassw0Rd!")); // Test password validation boolean failure = false; System.out.println("Running tests..."); for(int i = 0; i < 100; i++) { String password = ""+i; String hash = createHash(password); String secondHash = createHash(password); if(hash.equals(secondHash)) { System.out.println("FAILURE: TWO HASHES ARE EQUAL!"); failure = true; } String wrongPassword = ""+(i+1); if(validatePassword(wrongPassword, hash)) { System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!"); failure = true; } if(!validatePassword(password, hash)) { System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!"); failure = true; } } if(failure) System.out.println("TESTS FAILED!"); else System.out.println("TESTS PASSED!"); } catch(Exception ex) { System.out.println("ERROR: " + ex); } }
7
private boolean submitScore(boolean next){ //submit_score1 = new String[score.length]; //System.out.println("Submitscore"+db.current_score.getScores().toString()); HashMap<String, Float> submit_score = new HashMap<>(); for (int i = 0; i < score.length; i++) { for (int j = 0; j < score[i].length; j++) { if(score[i][j].isSelected()){ submit_score.put(scoreDesc[i], Float.parseFloat(score[i][j].getText())); //submit_score1[i] = score[i][j].getText(); } } if(!submit_score.containsKey(scoreDesc[i])) { if (next) errormsg.setText("Please enter score for all categories."); else errormsg.setText(""); return false; } } if (db.current_score ==null || !submit_score.equals(db.current_score.getScores())){ //System.out.println("Submitting score..."); try{ db.submitScore(submit_score); } catch(SQLException e){ errormsg.setText("Database error"); e.printStackTrace(); return false; } } //else System.out.println("No score change"); for (int i = 0; i < score.length; i++) { scoregroup[i].clearSelection(); } errormsg.setText(" "); return true; }
9
private String getVersionHistoryHtml(URL templateUrl, int sinceVersion) throws IOException { // Buffer for presentation-ready html. StringBuilder historyBuf = new StringBuilder(); URL url = null; BufferedReader in = null; String line = null; try { // Fetch the template. StringBuilder templateBuf = new StringBuilder(); url = templateUrl; in = new BufferedReader( new InputStreamReader( (InputStream)url.getContent() ) ); while ( (line = in.readLine()) != null ) { templateBuf.append(line).append("\n"); } in.close(); String historyTemplate = templateBuf.toString(); // Fetch the changelog, templating each revision. url = new URL(versionHistoryUrl); in = new BufferedReader( new InputStreamReader( (InputStream)url.getContent() ) ); int releaseVersion = 0; StringBuilder releaseBuf = new StringBuilder(); String releaseDesc = null; while ( (line = in.readLine()) != null ) { releaseVersion = Integer.parseInt( line ); if ( releaseVersion <= sinceVersion ) break; releaseBuf.setLength(0); while ( (line = in.readLine()) != null && !line.equals("") ) { releaseBuf.append("<li>").append(line).append("</li>\n"); } // Must've either hit a blank or done. if (releaseBuf.length() > 0) { String[] placeholders = new String[] { "{version}", "{items}" }; String[] values = new String[] { "v"+releaseVersion, releaseBuf.toString() }; releaseDesc = historyTemplate; for (int i=0; i < placeholders.length; i++) releaseDesc = releaseDesc.replaceAll(Pattern.quote(placeholders[i]), Matcher.quoteReplacement(values[i]) ); historyBuf.append(releaseDesc); } } in.close(); } finally { try {if (in != null) in.close();} catch (IOException e) {} } return historyBuf.toString(); }
9
private String getBaudotChar() { int a=0; if (inChar[5]==true) a=16; if (inChar[4]==true) a=a+8; if (inChar[3]==true) a=a+4; if (inChar[2]==true) a=a+2; if (inChar[1]==true) a++; // Look out for figures or letters shift characters if (a==0) { return ""; } else if (a==27) { lettersMode=false; return ""; } else if (a==31) { lettersMode=true; return ""; } // Only return numbers when in FSK200/500 decode mode //else if (lettersMode==true) return BAUDOT_LETTERS[a]; else return getBAUDOT_NUMBERS(a); }
8
@Override public void fromMessage(Message message) throws JMSException { try { inputStream = ((BlobMessage) message).getInputStream(); } catch (IOException e) { logger.error("Can't get input stream.", e); } }
1
public static void main(String[] args) { List<Integer> ints = new ArrayList<Integer>(); List<Double> doubles = new ArrayList<Double>(); doubles.add(3.05);doubles.add(6.9);doubles.add(8.9); ints.add(3); ints.add(5); ints.add(10); double sum = sum(ints); double doubles1 = sum; System.out.println(doubles1); //Subtyping using Generics Wildcard List<? extends Integer> intList = new ArrayList<Integer>(); List<? extends Number> numList = intList; // OK. List<? extends Integer> is a subtype of List<? extends Number> List<Number> numbers = new ArrayList<Number>(); List<String> stringList = new ArrayList<String>(); stringList.add("Hello"); // printData(stringList); // printData(ints); addIntegers(numbers); // System.out.println(numbers); }
2
public static boolean isOrthonormal(double[][] qt, boolean insufficientRank, double epsilon) { int n = qt.length; int rank = 0; for (int i = 0; i < n; i++) { Vector ei = new DenseVector(qt[i], true); double norm = ei.norm(2); if (Math.abs(1.0 - norm) < epsilon) { rank++; } else if (Math.abs(norm) > epsilon) { return false; // not a rank deficiency, either } for (int j = 0; j <= i; j++) { Vector ej = new DenseVector(qt[j], true); double dot = ei.dot(ej); if (!(Math.abs((i == j && rank > j ? 1.0 : 0.0) - dot) < epsilon)) { return false; } } } return insufficientRank ? rank < n : rank == n; }
8
public static void afficherAide(){ if (p.getEchiquier().getTableau()[p.getCaseCliquee().getI()][p.getCaseCliquee().getJ()] != null){ Vector<Position> dest = p.getEchiquier().destinationPossible(p.getEchiquier().getTableau()[p.getCaseCliquee().getI()][p.getCaseCliquee().getJ()]); for (Position pos : dest){ tabBoutton[pos.getI()][pos.getJ()].setBackground(Color.green); tabBoutton[pos.getI()][pos.getJ()].repaint(); } } else System.out.println("error"); }
2
void drawCard(Graphics g, Card card, int x, int y) { if (card == null) { // Draw a face-down card g.setColor(Color.blue); g.fillRect(x+10, y + 10,65,90); g.setColor(Color.white); g.drawRect(x+10, y + 10, 65,90); } else { // image generation String filename = "media/cards_gif/" + card.getCardToDisplay() + ".gif"; ImageIcon imageIcon = new ImageIcon(filename); Image image = imageIcon.getImage(); Integer height = (int) ( (double) image.getHeight(this)/2.8 ); Integer width = (int) ( (double) image.getWidth(this)/2.8 ) ; g.drawImage(image, x, y, width, height,this); } } // end drawCard()
1
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); ArrayList<Integer> primes = primeNumbers(1000001); while ((line = in.readLine()) != null && line.length() != 0) { int n = Integer.parseInt(line); if (n == 0) break; int curP0 = 0, curP1 = 0; boolean pos = false; for (int i = 0; i < primes.size(); i++) { curP0 = primes.get(i); if (curP0 >= n) break; else if (isPrime[n - curP0]) { pos = true; curP1 = n - curP0; break; } } if (!pos) out.append("Goldbach's conjecture is wrong.\n"); else out.append(n + " = " + curP0 + " + " + curP1 + "\n"); } System.out.print(out); }
7
public int getPlayerNumber(Player p) { if (p == null) throw new IllegalArgumentException("Player can't be null!"); return players.indexOf(p); }
1
public synchronized void put(T msg) { Link<T> next = new Link<T>(msg); if (first == null) { first = next; } else { last.next = next; last = next; } this.notify(); }
1
protected Map<String, Graph> loadGraphsAndPatterns(String filename, String fileDir, Level readLevel) throws IOException { String file = ((fileDir != null) ? fileDir : defaultFileDir) + filename + defaultFileExt; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file)))); StringBuilder builder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { builder.append(line); builder.append('\n'); } ContentHolder<String> input = new ContentHolder<String>(builder.toString()); reader.close(); Map<String, Graph> graphs = new HashMap<String, Graph>(); int i = 0; while(input.get().length() > 0) { Graph g = new SimpleGraph(); TextGraphRepresentation repr; try { repr = (TextGraphRepresentation) new TextGraphRepresentation(g).setUnitName("Greader").setLogLevel( (readLevel != null) ? readLevel : Level.OFF); repr.readRepresentation(input); } catch(IllegalArgumentException e) { g = new GraphPattern(); repr = (TextGraphRepresentation) new TextGraphRepresentation(g).setUnitName("Greader").setLogLevel( (readLevel != null) ? readLevel : Level.OFF); repr.readRepresentation(input); } log.li("new graph / pattern: []", repr.toString()); graphs.put(NAME_GENERAL_GRAPH + "#" + i, g); input.set(input.get().trim()); i++; } return graphs; }
6
public SPIGroup getGroup (int gid) throws SPIException, XmlRpcException { try { Object[] result; result = (Object[])this.execute(GETGROUP, addHeader(new Object[] { gid })); return new SPIGroup(gid, (String)result[0], getIntegerList((Object[])result[1])); } catch (XmlRpcException e) { switch (e.code) { case ERR_GROUP_DOES_NOT_EXIST: throw new GroupDoesNotExistException(); case ERR_GAME_DOES_NOT_EXIST: throw new GameDoesNotExistException(); case ERR_API_KEY_NOT_VALID: throw new APIKeyNotValidException(); case ERR_INVALID_FUNCTION: throw new InvalidFunctionException(); case ERR_UNKNOWN: throw new SPIException(); case ERR_VERSION: throw new InvalidVersionException(); case ERR_INPUT: throw new InvalidInputException(); default: throw e; } } }
8
public List<File> buildFont( String internalName, FileGarbage garbage ) throws IOException { File tempDir = File.createTempFile( "fonts", ".tmp" ); tempDir.delete(); tempDir.mkdirs(); garbage.addFile( tempDir, true ); File binDir = new File( "bin" ); File encFile = new File( "resources/T1-WGL4.enc" ); File inputFile = new File( tempDir, mSourceFile.getName().replace( ' ', '_' ) ); File vplFile = new File( tempDir, internalName + ".vpl" ); File mapFile = new File( tempDir, internalName + ".map" ); File outFile = new File( tempDir, internalName + ".tfm" ); // Copy input files. NativeFiles.copy( mSourceFile, inputFile ); File tempFile = encFile; encFile = new File( tempDir, encFile.getName() ); NativeFiles.copy( tempFile, encFile ); // Generate AFM file. File afmFile = PfToAfm.pfToAfm( inputFile ); // Convert AFM file to TFM file. File binFile = new File( binDir, "afm2tfm" ); List<String> cmd = new ArrayList<String>(); cmd.add( binFile.getAbsolutePath() ); cmd.add( afmFile.getName() ); cmd.add( "-T" ); cmd.add( encFile.getName() ); if( mExtend != 1.0 ) { cmd.add( "-e" ); cmd.add( String.valueOf( mExtend ) ); } if( mSlant != 0.0 ) { cmd.add( "-s" ); cmd.add( String.valueOf( mSlant ) ); } if( mSmallcaps ) { cmd.add( "-V" ); } else { cmd.add( "-v" ); } cmd.add( vplFile.getAbsolutePath() ); cmd.add( outFile.getAbsolutePath() ); String mapString; try { mapString = TranslatorUtil.exec( cmd, binDir, tempDir, true, true ); }catch( InterruptedException ex ) { InterruptedIOException e = new InterruptedIOException(); e.initCause( ex ); throw e; } //Create MAP file. { //System.out.println(mapString); Pattern pat = Pattern.compile("^(\\S++)\\s++(\\S++)\\s*+(\\\".*?\\\")\\s*+\\<(\\S++)"); Matcher mat = pat.matcher(mapString); if(!mat.find()) throw new IOException("Could not read output of afm2tfm command."); PrintWriter out = new PrintWriter( mapFile ); out.format( "%s %s %s <%s <%s\n", internalName, mat.group(2), mat.group(3), mat.group(4), inputFile.getName()); out.close(); //FileUtil.copy(mapFile, new File("/tmp/map.txt")); } // afmFile.delete(); File[] files = tempDir.listFiles(); List<File> ret = new ArrayList<File>(); assert files != null; for( File f : files ) { if( f.isFile() && !f.isHidden() ) { ret.add( f ); } } return ret; }
8
public double getDouble(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } }
2
private final void createSampleArrayCollection() { try { this.audioInputStream.mark(Integer.MAX_VALUE); this.audioInputStream.reset(); int bufferSize = ( (int) this.getNumberOfFrames() ) * this.getFrameSize(); byte[] bytes = new byte[bufferSize]; try { this.audioInputStream.read(bytes); } catch (Exception e) { e.printStackTrace(); } if(this.getBitsPerSample() == 8) { // Ensure the bytes are unsigned... this.ensure8bitUnsigned(bytes); this.samplesContainer = this.get8BitSampleArray(bytes); } else if(this.getBitsPerSample() == 24) { this.samplesContainer = this.get24BitSampleArray(bytes); } else { this.samplesContainer = this.get16BitSampleArray(bytes); } // Find biggest sample. Useful for interpolating the yScaleFactor (ex. drawing a waveform). if (this.sampleMax > this.sampleMin) { this.biggestSample = this.sampleMax; } else { this.biggestSample = Math.abs(((double) this.sampleMin)); } } catch (Exception e) { e.printStackTrace(); } }
5
public void startElement( String uri, String localName, String qName, Attributes attrs ) throws SAXException { if (qName.equals("name") || qName.equals("info")) { buf = new StringBuffer(50); return; } if (qName.equals("hash")) { if (file != null) { HCHash hash = new HCHash( attrs.getValue("length"), attrs.getValue("MD5"), attrs.getValue("SHA1")); file.addHash(hash); } return; } if (qName.equals("file")) { if (archive != null) { file = new HCFile(attrs.getValue("location")); archive.addFile(file); } return; } if (qName.equals("archive")) { if (catalog != null) { archive = new HCArchive(attrs.getValue("id")); catalog.addArchive(archive); } return; } if (qName.equals("catalog")) { catalog = new HCCatalog(attrs.getValue("id")); return; } }
9
public static void executeKey(KEY_COMMAND k) { if (game.paused) { if (k == KEY_COMMAND.PAUSE) { game.resume(); } return; } switch (k) { case LEFT: game.gameBlock.shiftLeft(); break; case RIGHT: game.gameBlock.shiftRight(); break; case ROTATE: game.gameBlock.rotate(); break; case FALL: game.gameBlock.fall(); break; case DROP: game.gameBlock.drop(); break; case HOLD: game.hold(); break; case PAUSE: game.pause(); break; } }
9
private void processSite(final AbstractJobSite site) { try { Document doc = getDocument(site.getUrlWithQuery()); Element elem = site.getElementForNextPage(doc); boolean morePagesToTraverse = site.morePagesToTraverse(elem); //Only a single page listing. Can happen, based on the search terms. if (!morePagesToTraverse) { parseJobEntries(site,doc); } while (morePagesToTraverse) { String nextPage = site.setHrefForNextPage(elem); try { //Process the current document parseJobEntries(site,doc); //Crawl to the next page String query = site.getUrlAddress()+nextPage; doc = getDocument(query); elem = site.getElementForNextPage(doc); morePagesToTraverse = site.morePagesToTraverse(elem); if (morePagesToTraverse == false) { //Reached the last page. Process this parseJobEntries(site,doc); } } catch (IOException e) { Logger.getInstance().logError((e.getMessage() + " for: " + site.getUrlWithQuery())); } Thread.sleep(MSEC_SLEEP); } } catch (IOException e) { Logger.getInstance().logError((e.getMessage() + " for: " + site.getUrlWithQuery())); } catch (InterruptedException e) { Logger.getInstance().logError((e.getMessage() + " for: " + site.getUrlWithQuery())); } }
6
public void generate() { ArrayList<Integer> minePositions = new ArrayList<Integer>(); ArrayList<Integer> r = new ArrayList<Integer>(); for (int i = 0; i < (rows * columns); i++) { r.add(i); } Collections.shuffle(r); minePositions.addAll(r.subList(0, mines)); for (Integer i : minePositions) { map[i] = -1; } for (int i = 0; i < (rows * columns); i++) { if (map[i] == -1) { continue; } map[i] = countSurroundingMines(i); } }
4
public PlayerPanel(Player p) { super(); player = p; playerPnlHash.put(player, this); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent event) { hiliteTerritories(map.getTerritories(player)); } public void mouseExited(MouseEvent event) { unhiliteTerritories(map.getTerritories(player)); } }); setBackground(player.color); nameLbl = new JLabel(player.name); nameLbl.setBorder(BorderFactory.createEmptyBorder(1, 5, 0, 0)); nameLbl.setForeground(Color.BLACK); troopCount.setForeground(Color.BLACK); troopCount.setBorder(EMPTY_BORDER); terrCount.setForeground(Color.BLACK); terrCount.setBorder(EMPTY_BORDER); bonusCount.setForeground(Color.BLACK); bonusCount.setBorder(EMPTY_BORDER); if (cardType != RiskGame.NONE) { cardCount = new JLabel("0 cards"); cardCount.setForeground(Color.BLACK); cardCount.setBorder(EMPTY_BORDER); if (numPlayers <= 10) cardCount.setFont(LABEL_FONT); else cardCount.setFont(SMALL_LABEL_FONT); } if (numPlayers <= 10) { nameLbl.setFont(NAME_FONT); troopCount.setFont(LABEL_FONT); terrCount.setFont(LABEL_FONT); bonusCount.setFont(LABEL_FONT); } else { nameLbl.setFont(SMALL_NAME_FONT); troopCount.setFont(SMALL_LABEL_FONT); terrCount.setFont(SMALL_LABEL_FONT); bonusCount.setFont(SMALL_LABEL_FONT); } setPreferredSize(new Dimension(100, Math.max((int) (500.0 / Math.ceil(numPlayers / 2.0)), 85))); add(nameLbl); add(troopCount); add(terrCount); add(bonusCount); if (cardType != RiskGame.NONE) add(cardCount); }
4
public boolean destruccion(){ marcarBloques(); int i,j,bloquesNuevos,k,r,q; boolean retorno=false; Random generador=new Random(); for(i=0;i<15;i++){ bloquesNuevos=0; for(j=0;j<15;j++){ if(buttonMatrix[i][j].destruir){ retorno=true; for(k=j;k>bloquesNuevos;k--){ buttonMatrix[i][k-1].boton.setBounds(i*30, k*30, 25, 25); buttonMatrix[i][k]=buttonMatrix[i][k-1]; } bloquesNuevos++; } } for(q=0;q<bloquesNuevos;q++){ r=generador.nextInt(99)+1; if(r<=5){ buttonMatrix[i][q]=comodinCreator.crearBloque(); buttonMatrix[i][q].boton.setBounds(i*30, q*30, 25, 25); buttonMatrix[i][q].boton.addActionListener(this); } else{ buttonMatrix[i][q]=colorCreator.crearBloque(); buttonMatrix[i][q].boton.setBounds(i*30, q*30, 25, 25); buttonMatrix[i][q].boton.addActionListener(this); } } } refresh(); if(retorno){return destruccion();} return retorno; }
7
@Override public Method parseMethod() throws IOException { Method m = new Method(); m.setReturnType(parseType()); if (curToken.type == Lexer.Type.NAME) { m.setName(curToken.c); curToken = lexer.getToken(); } else { throw new IOException("missing method name"); } if (curToken.type == Lexer.Type.LEFT_PARENTHESIS) { curToken = lexer.getToken(); m.setArguments(parseArglist()); } else { throw new IOException("missing ( after method name"); } if (curToken.type == Lexer.Type.RIGHT_PARENTHESIS) { curToken = lexer.getToken(); } else { throw new IOException("missing )"); } if (curToken.type == Lexer.Type.LEFT_BRACES) { curToken = lexer.getToken(); m.setBody(parseBody()); } else { throw new IOException("missing {"); } if (curToken.type == Lexer.Type.RIGHT_BRACES) { curToken = lexer.getToken(); } else { throw new IOException("missing }"); } return m; }
5
@SuppressWarnings("nls") @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(mHorizontal ? "Horizontal" : "Vertical"); buffer.append(" Dock Layout [id:"); buffer.append(Integer.toHexString(hashCode())); if (mDividerPosition != -1) { buffer.append(" d:"); buffer.append(mDividerPosition); } buffer.append(" x:"); buffer.append(mX); buffer.append(" y:"); buffer.append(mY); buffer.append(" w:"); buffer.append(mWidth); buffer.append(" h:"); buffer.append(mHeight); if (mParent != null) { buffer.append(" p:"); buffer.append(Integer.toHexString(mParent.hashCode())); } buffer.append(']'); return buffer.toString(); }
3
public void collsionDetect(Particle p){ if(p.loc.x > width || p.loc.x < 0) { p.dir.x = -p.dir.x; } if(p.loc.y > height || p.loc.y < 0){ p.dir.y = -p.dir.y; } }
4
public void skillBuy(int item) { int nn = get99Count(); if (nn > 1) nn = 1; else nn = 0; for (int j = 0; j < skillCapes.length; j++) { if (skillCapes[j] == item || skillCapes[j]+1 == item) { if (c.getItems().freeSlots() > 1) { if (c.getItems().playerHasItem(995,99000)) { if (c.getLevelForXP(c.playerXP[j]) >= 99) { c.getItems().deleteItem(995, c.getItems().getItemSlot(995), 99000); c.getItems().addItem(skillCapes[j] + nn,1); c.getItems().addItem(skillCapes[j] + 2,1); } else { c.sendMessage("You must have 99 in the skill of the cape you're trying to buy."); } } else { c.sendMessage("You need 99k to buy this item."); } } else { c.sendMessage("You must have at least 1 inventory spaces to buy this item."); } } /*if (skillCapes[j][1 + nn] == item) { if (c.getItems().freeSlots() >= 1) { if (c.getItems().playerHasItem(995,99000)) { if (c.getLevelForXP(c.playerXP[j]) >= 99) { c.getItems().deleteItem(995, c.getItems().getItemSlot(995), 99000); c.getItems().addItem(skillCapes[j] + nn,1); c.getItems().addItem(skillCapes[j] + 2,1); } else { c.sendMessage("You must have 99 in the skill of the cape you're trying to buy."); } } else { c.sendMessage("You need 99k to buy this item."); } } else { c.sendMessage("You must have at least 1 inventory spaces to buy this item."); } break; }*/ } c.getItems().resetItems(3823); }
7
ConnectionHandler(SharedTorrent torrent, byte[] id, InetAddress address, boolean force) throws IOException { this.torrent = torrent; this.id = id; this.forceObfuscation = force; this.socket = new ServerSocket(); // Bind to the first available port in the range // [PORT_RANGE_START; PORT_RANGE_END]. for (int port = ConnectionHandler.PORT_RANGE_START; port <= ConnectionHandler.PORT_RANGE_END; port++) { InetSocketAddress tryAddress = new InetSocketAddress(address, port); try { this.socket.bind(tryAddress); this.address = tryAddress; break; } catch (IOException ioe) { // Ignore, try next port logger.info("Could not bind to " + tryAddress + "!"); } } if (!this.socket.isBound()) { throw new IOException("No available port for BitTorrent client!"); } this.listeners = new HashSet<IncomingConnectionListener>(); this.thread = null; }
3
public TuringConvertController(ConvertPane pane, SelectionDrawer drawer, TuringMachine automaton) { super(pane, drawer, automaton); myTuringMachine=automaton; converter = new TuringToGrammarConverter(); // converter.initializeConverter(); pane.getTable().getColumnModel().getColumn(0).setMinWidth(150); pane.getTable().getColumnModel().getColumn(0).setMaxWidth(250); fillMap(); }
0
public static void main (String[] argv) { int i; EntradaMat[] loleido; if (argv.length != 1) { System.err.println("Uso: java ManejadorMatrizXML <archivo>"); System.exit(1); } ManejadorMatrizXML handler = new ManejadorMatrizXML(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse( new File(argv[0]), handler); loleido = handler.getEntradas(); for (i=0; i<loleido.length; i++){ System.out.print("ren: "+loleido[i].getIdxRenglon()); System.out.print("\tcol: "+loleido[i].getIdxColumna()); System.out.println("\tE: "+loleido[i].getContenido()); } } catch (SAXParseException spe) { System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } System.exit(0); }
8
public static void setCursor(String tex, Vector2 hotspot) { CursorLoader.tex = ResourceLoader.getTexture(tex); CursorLoader.hotspot = hotspot; if(tex != null) { Cursor emptyCursor; try { emptyCursor = new Cursor(1, 1, 0, 0, 1, BufferUtils.createIntBuffer(1), null); Mouse.setNativeCursor(emptyCursor); } catch (LWJGLException e) { e.printStackTrace(); } } else { try { Mouse.setNativeCursor(null); } catch (LWJGLException e) { e.printStackTrace(); } } }
3
private void checkAdjacentNodesStart(Node origin) { Node n = null; for (int i = origin.x-1; i <= origin.x+1; i++) { for (int j = origin.y-1; j <= origin.y+1; j++) { if (!(i == origin.x && j == origin.y)) { n = new Node(i, j); int dirr = directionFromAdjacentNode(origin, n); if (dirr == 1) { if (isValidStart(n)) { n.parent = origin; calculateG(n); calculateH(n); calculateF(n); addToOpenList(n); } } } } } }
6
public EntityStatsEditor(String savedStats) { setResizable(false); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Stat Editor"); setBounds(100, 100, 450, 300); getContentPane().setLayout(null); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBounds(0, 0, 434, 237); getContentPane().add(tabbedPane); JPanel vitTab = new JPanel(); tabbedPane.addTab("Vitality", null, vitTab, null); tabbedPane.setEnabledAt(0, true); vitTab.setLayout(null); JLabel lblMaxHp = new JLabel("Max HP"); lblMaxHp.setBounds(10, 11, 86, 14); vitTab.add(lblMaxHp); spinMaxHp = new JSpinner(); spinMaxHp.setModel(new SpinnerNumberModel(new Float(15), new Float(0), null, new Float(1))); lblMaxHp.setLabelFor(spinMaxHp); spinMaxHp.setBounds(106, 8, 70, 20); vitTab.add(spinMaxHp); JLabel lblMaxBuffHp = new JLabel("Max Buff HP"); lblMaxBuffHp.setBounds(10, 36, 86, 14); vitTab.add(lblMaxBuffHp); spinMaxHpBuff = new JSpinner(); spinMaxHpBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); lblMaxBuffHp.setLabelFor(spinMaxHpBuff); spinMaxHpBuff.setBounds(106, 33, 70, 20); vitTab.add(spinMaxHpBuff); JLabel lblMaxBuffTime = new JLabel("Max Buff Time"); lblMaxBuffTime.setBounds(10, 61, 86, 14); vitTab.add(lblMaxBuffTime); spinMaxHpBuffTime = new JSpinner(); spinMaxHpBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); lblMaxBuffTime.setLabelFor(spinMaxHpBuffTime); spinMaxHpBuffTime.setBounds(106, 58, 70, 20); vitTab.add(spinMaxHpBuffTime); JLabel lblHp = new JLabel("HP"); lblHp.setBounds(10, 86, 70, 14); vitTab.add(lblHp); spinHp = new JSpinner(); spinHp.setModel(new SpinnerNumberModel(new Float(15), new Float(0), null, new Float(1))); spinHp.setBounds(106, 83, 70, 20); vitTab.add(spinHp); JLabel lblBuffHp = new JLabel("HP Buff"); lblBuffHp.setBounds(10, 111, 86, 14); vitTab.add(lblBuffHp); spinHpBuff = new JSpinner(); spinHpBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinHpBuff.setBounds(106, 108, 70, 20); vitTab.add(spinHpBuff); JLabel lblHpBuffTime = new JLabel("HP Buff Time"); lblHpBuffTime.setBounds(10, 136, 86, 14); vitTab.add(lblHpBuffTime); spinHpBuffTime = new JSpinner(); spinHpBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinHpBuffTime.setBounds(106, 133, 70, 20); vitTab.add(spinHpBuffTime); JLabel lblAverage = new JLabel("Average"); lblAverage.setBounds(186, 11, 46, 14); vitTab.add(lblAverage); JLabel lblNewLabel = new JLabel("Tallie"); lblNewLabel.setBounds(186, 36, 46, 14); vitTab.add(lblNewLabel); spinHpAvg = new JSpinner(); spinHpAvg.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); spinHpAvg.setBounds(242, 8, 70, 20); vitTab.add(spinHpAvg); spinHpTallie = new JSpinner(); spinHpTallie.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); spinHpTallie.setBounds(242, 33, 70, 20); vitTab.add(spinHpTallie); JPanel vigTab = new JPanel(); tabbedPane.addTab("Vigor", null, vigTab, null); vigTab.setLayout(null); JLabel lblMaxStr = new JLabel("Max STR"); lblMaxStr.setBounds(10, 11, 86, 14); vigTab.add(lblMaxStr); spinMaxVig = new JSpinner(); spinMaxVig.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinMaxVig.setBounds(106, 8, 70, 20); vigTab.add(spinMaxVig); JLabel lblMaxBuffStr = new JLabel("Max Buff STR"); lblMaxBuffStr.setBounds(10, 36, 86, 14); vigTab.add(lblMaxBuffStr); spinMaxVigBuff = new JSpinner(); spinMaxVigBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxVigBuff.setBounds(106, 33, 70, 20); vigTab.add(spinMaxVigBuff); JLabel lblMaxBuffTime_1 = new JLabel("Max Buff Time"); lblMaxBuffTime_1.setBounds(10, 61, 86, 14); vigTab.add(lblMaxBuffTime_1); spinMaxVigBuffTime = new JSpinner(); spinMaxVigBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxVigBuffTime.setBounds(106, 58, 70, 20); vigTab.add(spinMaxVigBuffTime); JLabel lblStr = new JLabel("STR"); lblStr.setBounds(10, 86, 86, 14); vigTab.add(lblStr); spinVig = new JSpinner(); spinVig.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinVig.setBounds(106, 83, 70, 20); vigTab.add(spinVig); JLabel lblStrBuff = new JLabel("STR Buff"); lblStrBuff.setBounds(10, 111, 86, 14); vigTab.add(lblStrBuff); spinVigBuff = new JSpinner(); spinVigBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVigBuff.setBounds(106, 108, 70, 20); vigTab.add(spinVigBuff); JLabel lblStrBuffTime = new JLabel("STR Buff Time"); lblStrBuffTime.setBounds(10, 136, 86, 14); vigTab.add(lblStrBuffTime); spinVigBuffTime = new JSpinner(); spinVigBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVigBuffTime.setBounds(106, 133, 70, 20); vigTab.add(spinVigBuffTime); JLabel lblAverage_1 = new JLabel("Average"); lblAverage_1.setBounds(188, 12, 46, 14); vigTab.add(lblAverage_1); JLabel lblTallie = new JLabel("Tallie"); lblTallie.setBounds(188, 37, 46, 14); vigTab.add(lblTallie); spinVigAvg = new JSpinner(); spinVigAvg.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVigAvg.setBounds(246, 9, 70, 20); vigTab.add(spinVigAvg); spinVigTallie = new JSpinner(); spinVigTallie.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVigTallie.setBounds(246, 34, 70, 20); vigTab.add(spinVigTallie); JPanel essTab = new JPanel(); essTab.setName(""); tabbedPane.addTab("Essence", null, essTab, null); essTab.setLayout(null); JLabel lblMaxEssence = new JLabel("Max Essence"); lblMaxEssence.setBounds(12, 13, 86, 14); essTab.add(lblMaxEssence); JLabel lblMaxBuffEss = new JLabel("Max Buff Ess"); lblMaxBuffEss.setBounds(12, 40, 86, 14); essTab.add(lblMaxBuffEss); JLabel lblMaxBuffTime_2 = new JLabel("Max Buff Time"); lblMaxBuffTime_2.setBounds(12, 67, 86, 14); essTab.add(lblMaxBuffTime_2); JLabel lblEssence = new JLabel("Essence"); lblEssence.setBounds(12, 94, 86, 14); essTab.add(lblEssence); JLabel lblBuffEssence = new JLabel("Essence Buff"); lblBuffEssence.setBounds(12, 121, 86, 14); essTab.add(lblBuffEssence); JLabel lblEssenceBuffTime = new JLabel("Essence Buff Time"); lblEssenceBuffTime.setBounds(12, 148, 86, 14); essTab.add(lblEssenceBuffTime); spinMaxEss = new JSpinner(); spinMaxEss.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinMaxEss.setBounds(110, 11, 70, 20); essTab.add(spinMaxEss); spinMaxEssBuff = new JSpinner(); spinMaxEssBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxEssBuff.setBounds(110, 38, 70, 20); essTab.add(spinMaxEssBuff); spinMaxEssBuffTime = new JSpinner(); spinMaxEssBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxEssBuffTime.setBounds(110, 65, 70, 20); essTab.add(spinMaxEssBuffTime); spinEss = new JSpinner(); spinEss.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinEss.setBounds(110, 92, 70, 20); essTab.add(spinEss); spinEssBuff = new JSpinner(); spinEssBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinEssBuff.setBounds(110, 119, 70, 20); essTab.add(spinEssBuff); spinEssBuffTime = new JSpinner(); spinEssBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinEssBuffTime.setBounds(110, 146, 70, 20); essTab.add(spinEssBuffTime); JLabel lblAverage_2 = new JLabel("Average"); lblAverage_2.setBounds(192, 14, 46, 14); essTab.add(lblAverage_2); JLabel lblTallie_1 = new JLabel("Tallie"); lblTallie_1.setBounds(192, 41, 46, 14); essTab.add(lblTallie_1); spinEssAvg = new JSpinner(); spinEssAvg.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinEssAvg.setBounds(250, 11, 70, 20); essTab.add(spinEssAvg); spinEssTallie = new JSpinner(); spinEssTallie.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinEssTallie.setBounds(250, 38, 70, 20); essTab.add(spinEssTallie); JPanel vivTab = new JPanel(); tabbedPane.addTab("Vivacity", null, vivTab, null); vivTab.setLayout(null); JLabel lblMaxStamina = new JLabel("Max Stamina"); lblMaxStamina.setBounds(12, 13, 86, 14); vivTab.add(lblMaxStamina); JLabel lblMaxBuffStamina = new JLabel("Max Buff Stam"); lblMaxBuffStamina.setBounds(12, 40, 86, 14); vivTab.add(lblMaxBuffStamina); JLabel lblMaxBuffTime_3 = new JLabel("Max Buff Time"); lblMaxBuffTime_3.setBounds(12, 67, 86, 14); vivTab.add(lblMaxBuffTime_3); JLabel lblStamina = new JLabel("Stamina"); lblStamina.setBounds(12, 94, 86, 14); vivTab.add(lblStamina); JLabel lblStaminaBuff = new JLabel("Stamina Buff"); lblStaminaBuff.setBounds(12, 121, 86, 14); vivTab.add(lblStaminaBuff); JLabel lblStaminaBuffTime = new JLabel("Stamina Buff Time"); lblStaminaBuffTime.setBounds(12, 148, 86, 14); vivTab.add(lblStaminaBuffTime); spinMaxViv = new JSpinner(); spinMaxViv.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinMaxViv.setBounds(110, 11, 70, 20); vivTab.add(spinMaxViv); spinMaxVivBuff = new JSpinner(); spinMaxVivBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxVivBuff.setBounds(110, 38, 70, 20); vivTab.add(spinMaxVivBuff); spinMaxVivBuffTime = new JSpinner(); spinMaxVivBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinMaxVivBuffTime.setBounds(110, 65, 70, 20); vivTab.add(spinMaxVivBuffTime); spinViv = new JSpinner(); spinViv.setModel(new SpinnerNumberModel(new Float(30), new Float(0), null, new Float(1))); spinViv.setBounds(110, 92, 70, 20); vivTab.add(spinViv); spinVivBuff = new JSpinner(); spinVivBuff.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVivBuff.setBounds(110, 119, 70, 20); vivTab.add(spinVivBuff); spinVivBuffTime = new JSpinner(); spinVivBuffTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVivBuffTime.setBounds(110, 146, 70, 20); vivTab.add(spinVivBuffTime); JLabel lblActiveCount = new JLabel("Active Count"); lblActiveCount.setBounds(192, 14, 70, 14); vivTab.add(lblActiveCount); spinVivActive = new JSpinner(); spinVivActive.setBounds(274, 11, 70, 20); vivTab.add(spinVivActive); JLabel lblAvgTime = new JLabel("Avg Time"); lblAvgTime.setBounds(192, 41, 70, 14); vivTab.add(lblAvgTime); spinVivTime = new JSpinner(); spinVivTime.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); spinVivTime.setBounds(274, 38, 70, 20); vivTab.add(spinVivTime); { JButton okButton = new JButton("Save"); okButton.setBounds(252, 239, 81, 23); getContentPane().add(okButton); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { stats += "VITALITY;" + spinMaxHp.getValue() + "-" + spinMaxHpBuff.getValue() + "-" + spinMaxHpBuffTime.getValue() + ";" + spinHp.getValue() + "-" + spinHpBuff.getValue() + "-" + spinHpBuffTime.getValue() + ";" + spinHpAvg.getValue() + "-" + spinHpTallie.getValue(); stats += "VIGOR;" + spinMaxVig.getValue() + "-" + spinMaxVigBuff.getValue() + "-" + spinMaxVigBuffTime.getValue() + ";" + spinVig.getValue() + "-" + spinVigBuff.getValue() + "-" + spinVigBuffTime.getValue() + ";" + spinVigAvg.getValue() + "-" + spinVigTallie.getValue(); stats += "ESSENCE;" + spinMaxEss.getValue() + "-" + spinMaxEssBuff.getValue() + "-" + spinMaxEssBuffTime.getValue() + ";" + spinEss.getValue() + "-" + spinEssBuff.getValue() + "-" + spinEssBuffTime.getValue() + ";" + spinEssAvg.getValue() + "-" + spinEssTallie.getValue(); stats += "VIVACITY;" + spinMaxViv.getValue() + "-" + spinMaxVivBuff.getValue() + "-" + spinMaxVivBuffTime.getValue() + ";" + spinViv.getValue() + "-" + spinVivBuff.getValue() + "-" + spinVivBuffTime.getValue() + ";" + spinVivActive.getValue() + "-" + spinVivTime.getValue(); dispose(); } catch(NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "Values must be integers or floats"); } } }); okButton.setActionCommand("OK"); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.setBounds(343, 239, 81, 23); getContentPane().add(cancelButton); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancelButton.setActionCommand("Cancel"); } if(!savedStats.matches("")) loadStats(savedStats); setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
2
public static boolean isAntiarithmetic() { BitSet bs = new BitSet(a.length + 1); for (int i = 0; i < a.length; i++) { bs.clear(); for (int j = i + 1; j < a.length; j++) { bs.set(a[j], true); if ((a[j] + a[i]) % 2 == 0 && bs.get((a[j] + a[i]) / 2)) return false; } } return true; }
4
public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return null; RandomListNode newHead = new RandomListNode(head.label); Map<RandomListNode, RandomListNode> nodeMap = new HashMap<RandomListNode, RandomListNode>(); nodeMap.put(head, newHead); RandomListNode next = head.next; while (next != null) { RandomListNode node = new RandomListNode(next.label); nodeMap.put(next, node); next = next.next; } next = head; while (next != null) { RandomListNode node = nodeMap.get(next); if (next.next != null) node.next = nodeMap.get(next.next); if (next.random != null) node.random = nodeMap.get(next.random); next = next.next; } return newHead; }
5
@RequestMapping(value="/{tripID}/editTravelTrip", method=RequestMethod.POST) public String ediTravelTrip(@PathVariable("tripID") String tripID, @Valid @ModelAttribute("editTravelTrip") TravelTrip editTravelTrip, BindingResult result, Model model){ if (!result.hasErrors()) { travelTripService.update(Integer.parseInt(tripID), editTravelTrip); model.addAttribute("travelTripList", travelTripService.findAll()); return "redirect:/"; } else { //model.addAttribute("travelTripList", travelTripService.findAll()); return "editTravelTrip"; } }
1
public synchronized EquationBTreeNode getChild2() {return child2;}
0
private Object[] readArray() throws EncodingException, NotImplementedException { int handle = readInt(); boolean inline = ((handle & 1) != 0); handle = handle >> 1; if (inline) { String key = readString(); if (key != null && !key.equals("")) throw new NotImplementedException("Associative arrays are not supported"); Object[] ret = new Object[handle]; objectReferences.add(ret); for (int i = 0; i < handle; i++) ret[i] = decode(); return ret; } else { return (Object[])objectReferences.get(handle); } }
4
public static Integer getIntegerValue(String key){ return Integer.valueOf(getStringValue(key)); }
0
@Override public boolean loadAllInstruments(Soundbank soundbank) { boolean success = true; for (Synthesizer s : theSynths) if (!s.loadAllInstruments(soundbank)) success = false; return success; }
2
public void reselect() { if (lastClassName != null) { TreePath lastPath = (hierarchyTree ? hierModel .getPath(lastClassName) : packModel.getPath(lastClassName)); if (lastPath != null) { classTree.setSelectionPath(lastPath); classTree.scrollPathToVisible(lastPath); } } }
3
public static List<Appointment> findByWeek(long uid, long week) throws SQLException { List<Appointment> aAppt = new ArrayList<Appointment>(); long endOfWeek = week + 6 * DateUtil.DAY_LENGTH; // once aAppt.addAll(Appointment.findOnceByDaySpan(uid, week, endOfWeek)); // daily aAppt.addAll(Appointment.findDailyByDaySpan(uid, week, endOfWeek)); // weekly aAppt.addAll(Appointment.findWeeklyByDaySpan(uid, week, endOfWeek)); // monthly aAppt.addAll(Appointment.findMonthlyByDaySpan(uid, week, endOfWeek)); return aAppt; }
0
public SplashScreen(Forme forme){ this.forme=forme; this.setSize(400,387); this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); panel=new JPanel(new BorderLayout()); label=new JLabel(new ImageIcon("Ressources/Images/jeux_taquin.png")); label.setVerticalAlignment(JLabel.CENTER); label.setHorizontalAlignment(JLabel.CENTER); panel.add(label,BorderLayout.NORTH); bar=new JProgressBar(0, 100); bar.setValue(0); bar.setStringPainted(true); panel.add(bar,BorderLayout.CENTER); this.setBackground(Color.black); this.getContentPane().add(panel); this.setLocationRelativeTo(null); this.setAlwaysOnTop(true); this.pack(); this.setVisible(true); Thread thread=new Thread(new Runnable() { @Override public void run() { for(int i=0;i<=100;i++){ bar.setValue(i); try{ Thread.sleep(30); }catch(Exception e){ e.printStackTrace(); } } } }); thread.start(); lancer(); }
2
private boolean camposCompletos (){ if((!field_fec_alta.getText().equals(""))&& (!field_limite_cred.getText().equals(""))&& (!field_dni.getText().equals(""))&& (!field_nombre.getText().equals(""))&& (!field_apellido.getText().equals(""))&& (!field_telefono.getText().equals(""))&& (!field_direccion.getText().equals(""))&& (!field_sueldo.getText().equals(""))&& (!field_fec_cbo_est.getText().equals("")) ){ return true; } else{ return false; } }
9
public static void main(String[] args) { final Logger logger = Logger.getLogger(Money.class.toString()); logger.info("Starting"); Money thisObj = null; try { } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } finally { if (thisObj != null) { // Clean up resource if necessary. E.g., call close() or flush(). } logger.info("Finished."); System.exit(0); } }
2
@Override public FiveCardOmahaWorker build() { if (super.getRounds() <= 0) { throw new IllegalStateException("The number of rounds must be a strictly positive number"); } else if (super.getProfiles() == null || super.getProfiles().size() < 2) { throw new IllegalStateException("There need to be at least 2 players in every simulation."); } else if (super.getUpdateInterval() <= 0 || 100 % super.getUpdateInterval() != 0) { throw new IllegalStateException("Invalid update interval value"); } else if (super.getNotifiable() == null) { throw new IllegalStateException("There needs to be a notifiable for this worker"); } for (PlayerProfile profile : super.getProfiles()) { if (profile == null) { throw new NullPointerException(); } } return new FiveCardOmahaWorker(this); }
8
public void redirectError(Writer w) { if (w == null) { throw new NullPointerException("w"); } stderr = w; }
1
public BlockDistillery(State state) { super(Material.iron); setBlockTextureName("snow"); setCreativeTab(GraphiteMod.tabGraphite); setHardness(2.0f); setResistance(5.0f); setStepSound(Block.soundTypeMetal); this.state = state; switch(state) { case IDLE: setBlockName("distilleryIdle"); break; case BURNING: setBlockName("distilleryBurning"); break; case DISTILLING: setBlockName("distilleryDistilling"); break; } }
3
private void setUp(){ fieldDecode = new JTextField(25); fieldEncode = new JTextField(25); int newHeight = fieldDecode.getPreferredSize().height + 5; int newWidth = fieldDecode.getPreferredSize().height; fieldDecode.setPreferredSize(new Dimension(newWidth, newHeight)); fieldEncode.setPreferredSize(new Dimension(newWidth, newHeight)); buttonDecode = new JButton("Decode"); buttonDecode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String words = fieldDecode.getText(); String binary = Base64.fromBase64(words); fieldEncode.setText(binary); } }); buttonEncode = new JButton("Encode"); buttonEncode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String words = fieldEncode.getText(); String base = Base64.toBase64(words); fieldDecode.setText(base); } }); add(fieldEncode); add(buttonEncode); add(fieldDecode); add(buttonDecode); }
0
protected void paintComponent(Graphics g) { if (isOpaque()) { Dimension size = getSize(); g.setColor(getBackground()); g.fillRect(0, 0, size.width, size.height); } int stepSize = 0; int cDist = 0; int rDist = 0; for (int vectorIndex = 0; vectorIndex < resultVector.size(); vectorIndex++) { double coreDistance = ((DataObject) resultVector.elementAt(vectorIndex)).getCoreDistance(); double reachDistance = ((DataObject) resultVector.elementAt(vectorIndex)).getReachabilityDistance(); if (coreDistance == DataObject.UNDEFINED) cDist = getHeight(); else cDist = (int) (coreDistance * verticalAdjustment); if (reachDistance == DataObject.UNDEFINED) rDist = getHeight(); else rDist = (int) (reachDistance * verticalAdjustment); int x = vectorIndex + stepSize; if (isShowCoreDistances()) { /** * Draw coreDistance */ g.setColor(coreDistanceColor); g.fillRect(x, getHeight() - cDist, widthSlider, cDist); } if (isShowReachabilityDistances()) { int sizer = widthSlider; if (!isShowCoreDistances()) sizer = 0; /** * Draw reachabilityDistance */ g.setColor(reachabilityDistanceColor); g.fillRect(x + sizer, getHeight() - rDist, widthSlider, rDist); } if (isShowCoreDistances() && isShowReachabilityDistances()) { stepSize += (widthSlider * 2); } else stepSize += widthSlider; } }
9
public void setImage(String image) { if (image.indexOf('\\') == -1) { this.image = image; return; } int size = image.length(); StringBuffer buf = new StringBuffer(size); for (int i = 0; i < size; i++) { char c = image.charAt(i); if (c == '\\' && i + 1 < size) { char c1 = image.charAt(i + 1); if (c1 == '\\' || c1 == '"' || c1 == '\'' || c1 == '#' || c1 == '$') { c = c1; i++; } } buf.append(c); } this.image = buf.toString(); }
9
public int getPages(int intRegsPerPag, ArrayList<FilterBean> alFilter, HashMap<String, String> hmOrder) throws Exception { int pages; try { oMysql.conexion(enumTipoConexion); pages = oMysql.getPages("usuario", intRegsPerPag, alFilter, hmOrder); oMysql.desconexion(); return pages; } catch (Exception e) { throw new Exception("UsuarioDao.getPages: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } }
1
private void doDecode() { File file = null; showMessage("uncompressing"); try { int retval = ourChooser.showOpenDialog(null); if (retval != JFileChooser.APPROVE_OPTION) { return; } file = ourChooser.getSelectedFile(); String name = file.getName(); String uname = name; if (name.endsWith(HUFF_SUFFIX)) { uname = name.substring(0,name.length() - HUFF_SUFFIX.length()) + UNHUFF_SUFFIX; } else { uname = name + UNHUFF_SUFFIX; } String newName = JOptionPane.showInputDialog(this, "Name of uncompressed file", uname); if (newName == null) { return; } String path = file.getCanonicalPath(); int pos = path.lastIndexOf(name); newName = path.substring(0, pos) + newName; final File newFile = new File(newName); ProgressMonitorInputStream temp = null; if (myFast){ temp = getMonitorableStream(getFastByteReader(file),"uncompressing bits ..."); } else { temp = getMonitorableStream(file, "uncompressing bits..."); } final ProgressMonitorInputStream stream = temp; final ProgressMonitor progress = stream.getProgressMonitor(); final OutputStream out = new FileOutputStream(newFile); Thread fileReaderThread = new Thread() { public void run() { try { myModel.uncompress(stream, out); } catch (IOException e) { cleanUp(newFile); HuffViewer.this.showError("could not uncompress\n "+e); //e.printStackTrace(); } if (progress.isCanceled()) { cleanUp(newFile); HuffViewer.this.showError("reading cancelled"); } } }; fileReaderThread.start(); } catch (FileNotFoundException e) { showError("could not open " + file.getName()); e.printStackTrace(); } catch (IOException e) { showError("IOException, uncompression halted from viewer"); e.printStackTrace(); } }
8
public Problem validate(final Object instance, final IPAddress annotation, final Object target, final CharSequence address) { if (address == null || address.length() < 1) { if (annotation.required()) { return new Problem(instance, annotation, target, address); } return null; } final String s = address.toString(); final String[] octets = s.split("\\."); if (octets.length != 4) { return new Problem(instance, annotation, target, address); } for (final String o : octets) { if (!ValidationRoutines.isValidOctet(o)) { return new Problem(instance, annotation, target, address); } } return null; }
6
@Override public String getCoordenadas() throws RemoteException { String coordenadas = ""; while (coordenadas.length() != 2) { coordenadas = JOptionPane.showInputDialog(frame, "Digite as coordenadas juntas (ex. XY), " + System.getProperty("line.separator") + "jogadas informadas anteriormente " + System.getProperty("line.separator") + "ser\u00E3o desconsideradas.:"); if ((coordenadas == null) || coordenadas.equals("")) { coordenadas = ""; } else { try { if (Integer.parseInt(coordenadas.charAt(1) + "") > 5 || Integer.parseInt(coordenadas.charAt(0) + "") > 5) { coordenadas = ""; } } catch (Exception e) { // e.printStackTrace(); if (!coordenadas.equalsIgnoreCase("out")) { System.out.println(coordenadas); coordenadas = ""; } else { break; } } } } if (coordenadas.length() == 2) { coordenadas = coordenadas.charAt(1) + "" + coordenadas.charAt(0); } if (out) { return "out"; } return coordenadas; }
9
@Override public void mouseExited(MouseEvent e) { setBorderPainted(false); }
0
public int distanceBetweenRank(Field otherField) { return otherField.rank - this.rank; }
0
private String GenerateOptions(int ir) { String r = new String(); boolean addHit = false; for ( int i = 0; i < hand.size(); i++) { if (this.hand.get(i).isHandPlayable()) { addHit = true; break; } } if ( addHit ) { r += "Hit - 1\n"; iOptions.add(1); } r += "Stand - 2\n"; iOptions.add(2); if ( money >= hand.get(handWillPlay).getBet() && hand.get(handWillPlay).getHand().size() == 2) { r += "Surrender - 3\n"; iOptions.add(3); r += "Double - 4\n"; iOptions.add(4); } if (hand.get(handWillPlay).getHand().size() == 2) { if (hand.get(handWillPlay).getHand().get(0).getFace() == hand.get(handWillPlay).getHand().get(1).getFace() && money >= hand.get(handWillPlay).getBet() * 2) { r += "Split - 5\n"; iOptions.add(5); } } return r; }
8
@Override public void setArrestingOfficer(Area legalArea, MOB mob) { if ((arrestingOfficer != null) && (arrestingOfficer.getStartRoom() != null) && (arrestingOfficer.location() != null) && (legalArea != null) && (arrestingOfficer.getStartRoom().getArea() != arrestingOfficer.location().getArea()) && (!legalArea.inMyMetroArea(arrestingOfficer.location().getArea()))) CMLib.tracking().wanderAway(arrestingOfficer, true, true); if ((mob == null) && (arrestingOfficer != null)) CMLib.tracking().stopTracking(arrestingOfficer); arrestingOfficer = mob; }
8
public static ArrayList<DVD> readTextDatabase(File file) { //------------------------------------- ArrayList<DVD> d = new ArrayList<>(); FileReader fr; BufferedReader br; String line; DVD newDVD; System.out.println("File name and path: " + file.getName() + " " + file); try { fr = new FileReader(file); } catch (FileNotFoundException e) { System.err.println("No DVD Database "); return d; } try { br = new BufferedReader(fr); while ((line = br.readLine()) != null) { newDVD = DVD.createDVD(line); if (newDVD != null) { d.add(newDVD); } } } catch (EOFException eof) { System.out.println("Finished reading file\n"); } catch (IOException e) { System.err.println("Error during read\n" + e.toString()); } try { fr.close(); } catch (IOException e) { System.err.println("File not closed properly\n" + e.toString()); System.exit(1); } return d; }
6
@Override public void onParticipantJoined(IParticipant p) { if (isMyself(p.getUserId())) { if (recvAudio || sendAudio) { connectVoice(); } if (videoFilename != null && videoFilename.length() > 0 && sendVideo) { sendVideo(); } if (recvDeskshare) { connectDeskshare(); } } else { if (p.getStatus().doesHaveStream() && recvVideo) { startReceivingVideo(p.getUserId()); } } }
9
public int MoveInstanceToBestCluster(Instance inst) { clusters.get(m_clusterAssignments.get(m_processed_InstanceID)).DeleteInstance(inst); m_clusterAssignments.set(m_processed_InstanceID, -1); double delta; double deltamax; int clustermax = -1; int tempS = 0; int tempW = 0; if (inst instanceof SparseInstance) { for (int i = 0; i < inst.numValues(); i++) { tempS++; tempW++; } } else { for (int i = 0; i < inst.numAttributes(); i++) { if (!inst.isMissing(i)) { tempS++; tempW++; } } } deltamax = tempS / Math.pow(tempW, m_Repulsion); for (int i = 0; i < clusters.size(); i++) { CLOPECluster tempcluster = clusters.get(i); delta = tempcluster.DeltaAdd(inst, m_Repulsion); // System.out.println("delta " + delta); if (delta > deltamax) { deltamax = delta; clustermax = i; } } if (clustermax == -1) { CLOPECluster newcluster = new CLOPECluster(); clusters.add(newcluster); newcluster.AddInstance(inst); return clusters.size() - 1; } clusters.get(clustermax).AddInstance(inst); return clustermax; }
7
public void setImageIndent (int indent) { checkWidget(); if (indent < 0) return; if (imageIndent == indent) return; imageIndent = indent; if ((parent.getStyle () & SWT.VIRTUAL) != 0) cached = true; }
3
void generateEdges() { // Generate all vertical edges in the maze int index = 0; while (index < this.cells.size() - this.size) { edges.add(new Edge(this.cells.get(index), this.cells.get(index + this.size))); index = index + 1; } // Generate all horizontal edges in the maze for (int ind = 0; ind < this.cells.size(); ind = ind + 1) { if (this.cells.get(ind).x % this.size != 0) { edges.add(new Edge(this.cells.get(ind), this.cells.get(ind + 1))); } } }
3
public SimpleStringProperty localNumberProperty() { return localNumber; }
0
public HashMap cashOutput(int amount) throws Exception { char[] params = Convert.toCharArray(amount); ArrayList<Integer> answer = this.device.send(0x51, 5, params); if (answer.size() == 0) throw new Exception("Пустой ответ"); HashMap<String, Integer> result = new HashMap<String, Integer>(); result.put("result", answer.get(0)); if (answer.get(0) == Status.OK) { if (answer.size() > 1) { result.put("error_code", answer.get(4)); result.put("operator", answer.get(5)); } } return result; }
3
private ArrayList<Product> queryForProducts(String sql) { ArrayList<Product> products = new ArrayList<>(); Connection con = null; try { con = getConnection(); PreparedStatement statement = con.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while(resultSet.next()) { products.add(buildProduct(resultSet)); } } catch (SQLException e) { e.printStackTrace(); } finally { if (con != null) closeConnection(con); } return products; }
3
@Override public void addUser(User user) { PreparedStatement pStmt = null; try { pStmt = conn.prepareStatement("INSERT INTO USER (login, password, name, surname) VALUES (?, ?, ?, ?);"); pStmt.setString(1, user.getLogin()); pStmt.setString(2, getMD5Hash(user.getPassword())); pStmt.setString(3, user.getName()); pStmt.setString(4, user.getSurname()); pStmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { closeResource(pStmt); } }
1
public String read(String transaction, String resource, boolean isReadOnly) { if (isReadOnly) { if (!snapshot.containsKey(transaction)) { throw new IllegalArgumentException( "A read transaction which has no snapshot"); } if (!snapshot.get(transaction).containsKey(resource)) { throw new IllegalArgumentException( "snapshot doesn't contains resource: " + resource + "for transaction: " + transaction); } return snapshot.get(transaction).get(resource); } else { // check if resource is in a write log if (this.writeLog.containsKey(transaction)) { if (writeLog.get(transaction).containsKey(resource)) { // Add to read log if (readLog.containsKey(transaction)) { readLog.get(transaction).add(resource); } else { HashSet<String> tmpSet = new HashSet<String>(); tmpSet.add(resource); readLog.put(transaction, tmpSet); } return writeLog.get(transaction).get(resource); } } // read from database directly if (this.data.get(resource) == null) { System.out.println(resource); throw new RuntimeException("no requested resource in this site"); } // Add to read log if (readLog.containsKey(transaction)) { readLog.get(transaction).add(resource); } else { HashSet<String> tmpSet = new HashSet<String>(); tmpSet.add(resource); readLog.put(transaction, tmpSet); } return this.data.get(resource); } }
8
public String parseLine(String line){ Pattern p=Pattern.compile(":\\w*!\\w*@\\w*.* PRIVMSG #\\w* :"); Matcher m=p.matcher(line); if(m.find()) return line.substring(m.end()); return line; }
1
void createExampleWidgets () { /* Compute the widget style */ int style = getDefaultStyle(); if (dateButton.getSelection ()) style |= SWT.DATE; if (timeButton.getSelection ()) style |= SWT.TIME; if (calendarButton.getSelection ()) style |= SWT.CALENDAR; if (shortButton.getSelection ()) style |= SWT.SHORT; if (mediumButton.getSelection ()) style |= SWT.MEDIUM; if (longButton.getSelection ()) style |= SWT.LONG; if (borderButton.getSelection ()) style |= SWT.BORDER; /* Create the example widgets */ dateTime1 = new DateTime (dateTimeGroup, style); }
7
private double findSplitNominalNumeric(int index) throws Exception { double bestVal = Double.MAX_VALUE, currVal; double[] sumsSquaresPerValue = new double[m_Instances.attribute(index).numValues()], sumsPerValue = new double[m_Instances.attribute(index).numValues()], weightsPerValue = new double[m_Instances.attribute(index).numValues()]; double totalSumSquaresW = 0, totalSumW = 0, totalSumOfWeightsW = 0, totalSumOfWeights = 0, totalSum = 0; double[] sumsSquares = new double[3], sumOfWeights = new double[3]; double[][] bestDist = new double[3][1]; // Compute counts for all the values for (int i = 0; i < m_Instances.numInstances(); i++) { Instance inst = m_Instances.instance(i); if (inst.isMissing(index)) { m_Distribution[2][0] += inst.classValue() * inst.weight(); sumsSquares[2] += inst.classValue() * inst.classValue() * inst.weight(); sumOfWeights[2] += inst.weight(); } else { weightsPerValue[(int)inst.value(index)] += inst.weight(); sumsPerValue[(int)inst.value(index)] += inst.classValue() * inst.weight(); sumsSquaresPerValue[(int)inst.value(index)] += inst.classValue() * inst.classValue() * inst.weight(); } totalSumOfWeights += inst.weight(); totalSum += inst.classValue() * inst.weight(); } // Check if the total weight is zero if (totalSumOfWeights <= 0) { return bestVal; } // Compute sum of counts without missing ones for (int i = 0; i < m_Instances.attribute(index).numValues(); i++) { totalSumOfWeightsW += weightsPerValue[i]; totalSumSquaresW += sumsSquaresPerValue[i]; totalSumW += sumsPerValue[i]; } // Make split counts for each possible split and evaluate for (int i = 0; i < m_Instances.attribute(index).numValues(); i++) { m_Distribution[0][0] = sumsPerValue[i]; sumsSquares[0] = sumsSquaresPerValue[i]; sumOfWeights[0] = weightsPerValue[i]; m_Distribution[1][0] = totalSumW - sumsPerValue[i]; sumsSquares[1] = totalSumSquaresW - sumsSquaresPerValue[i]; sumOfWeights[1] = totalSumOfWeightsW - weightsPerValue[i]; currVal = variance(m_Distribution, sumsSquares, sumOfWeights); if (currVal < bestVal) { bestVal = currVal; m_SplitPoint = (double)i; for (int j = 0; j < 3; j++) { if (sumOfWeights[j] > 0) { bestDist[j][0] = m_Distribution[j][0] / sumOfWeights[j]; } else { bestDist[j][0] = totalSum / totalSumOfWeights; } } } } m_Distribution = bestDist; return bestVal; }
8
public void mousemove(Coord c) { if (dm) { this.c = this.c.add(c.add(doff.inv())); } else { super.mousemove(c); } }
1
private void processMulti(MulticastMessage multiMsg) { String destGroup = multiMsg.getSrcGroup(); ArrayList<String> memberList = groupList.get(destGroup).getMemberList(); MessageKey curKey = new MessageKey(); // If we receive a real multicast message if(!multiMsg.getKind().equals("Ack")) { String localName = multiMsg.getDest(); //System.out.println("Get a multicast message, from " + // multiMsg.getSrc() + " destGroup: " + destGroup + multiMsg); curKey.setDestGroup(multiMsg.getSrcGroup()); curKey.setSrc(multiMsg.getSrc()); curKey.setNum(multiMsg.getNum()); // If it is a new message, add it to holdBackQueue if(!holdBackQueue.containsKey(curKey)) { holdBackQueue.put(curKey, multiMsg); } // Send Ack message to every group member, exclude itself for(String member : memberList) { if(!member.equals(localName)) { MulticastMessage ackMsg = new MulticastMessage(member, "Ack", curKey); ackMsg.setSrc(localName); ackMsg.setTimeStamp(multiMsg.getTimeStamp()); ackMsg.setSeqNum(multiMsg.getSeqNum()); ackMsg.setSrcGroup(((MulticastMessage) multiMsg).getSrcGroup()); ackMsg.setNum(((MulticastMessage) multiMsg).getNum()); //System.out.println("Send Ack message from " + ackMsg.getSrc() + ", to: " + ackMsg.getDest()); MessagePasser.getInstance().checkRuleAndSend(ackMsg); } } } // If we receive an Ack message else { //System.out.println("Get Ack message, from " + multiMsg.getSrc() + " to: " + multiMsg.getDest() + multiMsg); // Update ack record map curKey = (MessageKey) multiMsg.getData(); if(acks.containsKey(curKey)) { acks.get(curKey).add(multiMsg.getSrc()); } else { HashSet<String> tmp = new HashSet<String>(); tmp.add(multiMsg.getSrc()); acks.put(curKey, tmp); } } // If we get enough ack for this message if((acks.get(curKey) != null) && (acks.get(curKey).size() == memberList.size() - 1) && (holdBackQueue.containsKey(curKey))) { //String msgKey = curKey.getSrc() + curKey.getDestGroup(); deliver(curKey); } }
8
private void calculateManhattan() { grid.calculateManhattan(speed); }
0
public double standardError_of_ComplexImaginaryParts() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } double[] re = this.array_as_imaginary_part_of_Complex(); double standardError = Stat.standardError(re); Stat.nFactorOptionS = hold; return standardError; }
2
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: Game.VK_UP = false; break; case KeyEvent.VK_DOWN: Game.VK_DOWN = false; break; case KeyEvent.VK_LEFT: Game.VK_LEFT = false; break; case KeyEvent.VK_RIGHT: Game.VK_RIGHT = false; } }
4
public void update(double time){ for(Particle p:particles) p.tick(time); for(Particle p:bgParticles) p.tick(time); for(Explosion e:explosions) e.tick(time); for(Projectile p:projectiles) p.tick(time); for(Mob m:mobs) m.tick(time); deleteMarkedEntities(); for(Tower t:towers) t.tick(time); double exp = Math.exp(lambda * time); for(int x=0; x<w; x++){ for(int y=0; y<h; y++){ normalKillCounts[y][x] *= exp; splashKillCounts[y][x] *= exp; } } }
8
public void run() { byte[] ack_buffer = new byte[ACK_SIZE]; do { try { ack_buffer = new byte[ACK_SIZE]; DatagramPacket receivePacket = new DatagramPacket( ack_buffer, ack_buffer.length); clientSocket.receive(receivePacket); } catch (Exception e) { } if (Utilities.getPacketNum(ack_buffer) <= last_acknowledged) { continue; } else if (checkForPacket(ack_buffer) == false) { addPacket(ack_buffer); } } while (!end); }
4
public void update(Node lastPlayed){ Resolution.addFact(lastPlayed); int playedNodesIndex = 0; playedNodes = new Node[48]; for(int i = 0; i < allnodes.length; i++){ if(!(allnodes[i].getChar() == 'n')){ playedNodes[playedNodesIndex] = allnodes[i]; playedNodesIndex++; } } int playableIndex = 0; playableNodes = new Node[48]; for(int i = 0; i < playedNodesIndex; i++){ Node[] neighbors = playedNodes[i].getNeighbors(); for(int j = 0; j < neighbors.length; j++){ if ( neighbors[j] == null ) continue; if(!neighbors[j].getValue()){ boolean inlist = false; for(int k = 0; k < playableIndex; k++){ if(playableNodes[k].getId() == neighbors[j].getId()){ inlist = true; k = playableIndex; } } if(!inlist){ playableNodes[playableIndex] = neighbors[j]; playableIndex++; } } } } myGUI.setNodes(playableNodes); myGUI.setPlayedNodes(playedNodes); myGUI.repaint(); }
9
public void setCombatModifiers(int typeID) { switch (typeID) { case 0: weakAgainst = 1; strongAgainst = 3; break; case 1: weakAgainst = 2; strongAgainst = 0; break; case 2: weakAgainst = 3; strongAgainst = 1; break; case 3: weakAgainst = 0; strongAgainst = 2; break; case 4: weakAgainst = 6; strongAgainst = 6; break; case 5: weakAgainst = 6; strongAgainst = 6; break; } }
6
public Move(Board board, Position start, int horizontal , int vertical ){ field = board; this.start=start; this.horizontal=horizontal; this.vertical=vertical; }
0
public static void sendResponse(String output, Long id, Long prdetailsId) { try { post = new HttpPost(prop.getString("PostQuery").trim() + id); post.setHeader("Authorization", "Basic " + new String(encoded)); post.setHeader("Content-Type", "application/json"); post.addHeader("X-Mifos-Platform-TenantId", tenantIdentifier); CSVReader reader = new CSVReader(new StringReader(output)); String[] tokens = reader.readNext(); JSONObject object = new JSONObject(); if (tokens.length > 1) { String mes = tokens[1]; String message = ""; if (mes.equalsIgnoreCase("0")) { message = "success"; }else { String errorid= tokens[1]; String error = tokens[2]; message = "failure : Exception error code is : " + errorid + " , Exception/Error Message is : " + error; } object.put("receiveMessage", message); object.put("receivedStatus", "1"); object.put("prdetailsId", prdetailsId); } //logger.info("The json data sending to BSS System is :"+object.toString()); StringEntity se = new StringEntity(object.toString()); post.setEntity(se); HttpResponse response = httpClient.execute(post); response.getEntity().consumeContent(); if (response.getStatusLine().getStatusCode() != 200) { logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); Thread.sleep(wait); return; } else{ logger.info("record is Updated Successfully in Bss System"); } } catch (IOException e) { logger.error("IOException : " + e.getMessage() + ". verify the BSS system server running or not"); } /*catch (NullPointerException e) { logger.error("NullPointerException : " + e.getMessage() + " is passed and Output from the Oss System Server is : " + output); }*/ catch (InterruptedException e) { logger.error("thread is Interrupted for the : " + e.getMessage()); } catch (Exception e) { logger.error("Exception : " + e.getMessage()); } }
6
public void stopListen(){ run = false; try { socketListen.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
1
private void proveQuery(String content) { try { Evaluator evaluator = new Evaluator(new RobinsonUnificationStrategy(), knowledgeBase); boolean result = evaluator.prove( new ConsoleEvaluationHandler(System.out, console), parser.parsePredicates(content)); if (!result) { System.out.println("false"); } } catch (InfiniteRecursionException ex) { System.out.println("ERROR: Infinite recursion."); } catch (EvaluationException ex) { System.out.println("ERROR: General evaluation error. ['" + ex.getMessage() + "']."); } catch (ParseException ex) { System.out.println("ERROR: The given query is invalid ['" + ex.getMessage() + "']."); } }
4
public static void createIcons(EngineConfiguration config){ EngineConfiguration engine = config; String icon16 = engine.DISPLAY_ICON_16; String icon32 = engine.DISPLAY_ICON_32; if(!FileUtility.doesFileExist(icon16) || !FileUtility.doesFileExist(icon32)){ return; } ByteBuffer[] icons = new ByteBuffer[2]; icons[0] = ImageLoader.getByteBuffer(ImageLoader.getBufferedImage(icon16)); icons[1] = ImageLoader.getByteBuffer(ImageLoader.getBufferedImage(icon32)); Display.setIcon(icons); }
2
public static void main(String[] args) { // insert a bunch of strings String[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMinPQ<String> pq = new IndexMinPQ<String>(strings.length); for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // delete and print each key while (!pq.isEmpty()) { int i = pq.delMin(); System.out.println(i + " " + strings[i]); } System.out.println(); // reinsert the same strings for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // print each key using the iterator for (int i : pq) { System.out.println(i + " " + strings[i]); } while (!pq.isEmpty()) { pq.delMin(); } }
5
public int getStatus() { return Status; }
0
public float get_halffloat(int offset) { int signbit; int mantissa; int exp; float result; if(offset >= 0) if (pb[5] < (offset + 2)) { val = -1; // insufficient payload length return 0; } result = ((pb[offset + 7] & 0x80) != 0) ? (float) -1.0 : (float) 1.0; mantissa = ((((int) pb[offset + 7]) & 0x3) << 8) | (((int) pb[offset + 6]) & 0xff); exp = (pb[offset + 7] & 0x7c) >> 2; //System.out.println("pb[offset+7] pb[offset + 6]: " + pb[offset + 7] + " " + pb[offset +6] // + " exp: " + exp + " mantissa: " + mantissa ); if (exp != 0) { // non-zero exponent // subtracting 1 from exp is required so that left shift by // exp == 31 does not produce negative result. Compensated for in // exponent of scaling factor following if expression result *= ((float) ((1 << HALF_MBITS) + mantissa)) * ((float) ( 1 << exp - 1)); } else { // 0 exponent result *= mantissa; } result *= ((float) 1.0) / (float) (1 << (HALF_EBIAS + HALF_MBITS - 1)); return result; }
4
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
6
public static void drawFullCircle(Graphics g, int x, int y){ //TODO: for (int i = 0; i <= 20; i++){ g.setColor(new Color(Math.abs(i * (127 / 20)) + 127,255,0)); //System.out.println(Math.abs(i * (127 / 20))); // g.fillOval((x + EMPTY_CIRCLE) / 2 + (EMPTY_CIRCLE / 2) - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // (y + EMPTY_CIRCLE) / 2 + (EMPTY_CIRCLE / 2) - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // EMPTY_CIRCLE - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // EMPTY_CIRCLE - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20); g.fillOval(x + EMPTY_CIRCLE / 2 - (20 - i) * FULL_CIRCLE / 40, y + EMPTY_CIRCLE / 2 - (20 - i) * FULL_CIRCLE / 40, (20 - i) * FULL_CIRCLE / 20 ,(20 - i) * FULL_CIRCLE / 20 ); } }
1
/* */ public RIFCSElement getClassObject() /* */ throws RIFCSException /* */ { /* 360 */ NodeList nl = super.getElements(this.objectClass); /* */ /* 362 */ if (nl.getLength() != 1) /* */ { /* 364 */ return null; /* */ } /* */ /* 367 */ if (this.objectClass.equals("collection")) /* */ { /* 369 */ return new Collection(nl.item(0)); /* */ } /* 371 */ if (this.objectClass.equals("party")) /* */ { /* 373 */ return new Party(nl.item(0)); /* */ } /* 375 */ if (this.objectClass.equals("activity")) /* */ { /* 377 */ return new Activity(nl.item(0)); /* */ } /* 379 */ if (this.objectClass.equals("service")) /* */ { /* 381 */ return new Service(nl.item(0)); /* */ } /* */ /* 384 */ return null; /* */ }
5
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); //由context parameter取得JDBC需要的資訊 ServletContext sc = this.getServletConfig().getServletContext(); String dbUrl = sc.getInitParameter("ottzDBurl"); String ottzUser = sc.getInitParameter("ottzUser"); String ottzPassword = sc.getInitParameter("ottzPassword"); String jdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; if("deleteRsiTrain".equals(action)){ String dataKey = request.getParameter("id"); RsiDAO daoFT_delete = null; String sResultDelete =""; try{ daoFT_delete = new RsiDAO(jdbcDriver, dbUrl,ottzUser,ottzPassword); sResultDelete = daoFT_delete.deleteTraining(dataKey); }catch(Exception e){ sResultDelete = "取消刪除: " + e; }finally{ if(daoFT_delete != null) try { daoFT_delete.closeConn(); } catch (SQLException ex) { throw new ServletException("關閉sql connection階段發生例外:<br/> " + ex); } } request.setAttribute("ResultInsert", sResultDelete); request.getRequestDispatcher("/WEB-INF/RsiPages/training/ShowDdTradeResult.jsp").forward(request, response); } }
4
public MainFrame(MainController controller) { super("Chatus"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int confirm = JOptionPane.showOptionDialog(null, "Are You Sure to Close this Application?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (confirm == JOptionPane.YES_OPTION) { SystemFunctions.bye(); System.exit(0); } } }); try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e) { log.error("Can't apply look'n'feel"); } try { setIconImage(ImageIO.read(getClass().getResource("/images/icon16.png"))); } catch (IOException ex) { log.warn("Can't load icon"); } this.controller = controller; initComponents(); }
5
private void constructionGrille () { // creation du JPanel qui contient la grille conteneurGrille = new JPanel(); conteneurGrille.setPreferredSize(new Dimension(420,420)); conteneurGrille.setLayout(new GridBagLayout()); //l'outil pour positionner GridBagConstraints gbc = new GridBagConstraints(); gbc.fill =GridBagConstraints.BOTH; gbc.weightx=1; gbc.weighty=1; //La taille en hauteur et en largeur gbc.gridheight = 1; gbc.gridwidth = 1; //compte les separateurs ajoutés int sepX= 0; // we create and add the boxes cases = new CaseG[9][9]; for(int x=0; x<9; x++){ int sepY= 0; for(int y=0; y<9; y++){ //on definit la position gbc.gridx = y+sepY; gbc.gridy = x+sepX; // la dim gbc.ipady = 40; gbc.ipadx = 40; // on créer la case cases[x][y] =new CaseG(x,y); cases[x][y].addActionListener(caseListener); cases[x][y].addFocusListener(caseFocusListener); conteneurGrille.add(cases[x][y],gbc); //ajouter la colonne de demarcation toutes les 3 cases if(y==2 || y==5){ gbc.ipady = 0; gbc.ipadx = 0; sepY++; gbc.gridx = y+sepY; gbc.gridy = x+sepX; conteneurGrille.add(new Label(), gbc); } } //ajouter la ligne de demarcation toutes les 3 cases if(x==2 || x==5){ gbc.ipady = 0; gbc.ipadx = 0; sepX++; gbc.gridy = x+sepX; conteneurGrille.add(new Label(),gbc); } } // on ajoute la grille au JFrame laGrille.add(conteneurGrille); }
6
public void setWait(){ myKeeper.setWait(); }
0
public World() { }
0
public static void applyFX( DeviceType type, Mobile uses, Target applied, boolean hits ) { final World world = uses.world() ; if (type == null || type.hasProperty(MELEE)) { // // Put in a little 'splash' FX, in the direction of the arc. final float r = uses.radius() ; final Sprite slashFX = SLASH_FX_MODEL.makeSprite() ; slashFX.scale = r * 2 ; world.ephemera.addGhost(uses, r, slashFX, 0.33f) ; } else if (type.hasProperty(RANGED | PHYSICAL)) { // You'll have to create a missile effect, with similar parameters. final ShotFX shot = (ShotFX) SPEAR_FX_MODEL.makeSprite() ; final JointSprite sprite = (JointSprite) uses.sprite() ; uses.viewPosition(sprite.position) ; shot.origin.setTo(sprite.attachPoint("fire")) ; shot.target.setTo(hitPoint(applied, hits)) ; shot.position.setTo(shot.origin).add(shot.target).scale(0.5f) ; final float size = shot.origin.sub(shot.target, null).length() / 2 ; world.ephemera.addGhost(null, size + 1, shot, 1) ; } else if (type.hasProperty(RANGED | ENERGY)) { // Otherwise, create an appropriate 'beam' FX- final ShotFX shot = (ShotFX) LASER_FX_MODEL.makeSprite() ; final JointSprite sprite = (JointSprite) uses.sprite() ; uses.viewPosition(sprite.position) ; shot.origin.setTo(sprite.attachPoint("fire")) ; shot.target.setTo(hitPoint(applied, hits)) ; shot.position.setTo(shot.origin).add(shot.target).scale(0.5f) ; final float size = shot.origin.sub(shot.target, null).length() / 2 ; world.ephemera.addGhost(null, size + 1, shot, 0.66f) ; final Sprite BO = LASER_BURST_MODEL.makeSprite(), BT = LASER_BURST_MODEL.makeSprite() ; BO.position.setTo(shot.origin) ; BT.position.setTo(shot.target) ; //world.ephemera.addGhost(null, 1, BO, 0.66f) ; world.ephemera.addGhost(null, 1, BT, 0.66f) ; } }
4
public Ast.AstVector parse_PredicateList(SpecObject specObject, String property) { int at = m_current; if (!ok()) { return null; } Ast.AstVector node = m_ast.new AstVector(); Ast.AstPredicate pnode = parse_Predicate(specObject, property); if (ok()) { while (true) { node.m_list.add(pnode); if (!peek(TozeTokenizer.TOKEN_SEMICOLON) && !this.atEndOfLine()) { return node; } if (peek(TozeTokenizer.TOKEN_SEMICOLON)) { next(TozeTokenizer.TOKEN_SEMICOLON); } if (peek(TozeTokenizer.TOKEN_EOS)) { return node; } int tat = m_current; pnode = parse_Predicate(specObject, property); if (!ok()) { reset(tat); break; } } if (ok()) { return node; } } return null; }
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImovelDoCorretorId other = (ImovelDoCorretorId) obj; if (corretor == null) { if (other.corretor != null) return false; } else if (!corretor.equals(other.corretor)) return false; if (imovel == null) { if (other.imovel != null) return false; } else if (!imovel.equals(other.imovel)) return false; return true; }
9