text
stringlengths
14
410k
label
int32
0
9
private void initCumulative() { cumulative = new int[frequencies.length + 1]; int sum = 0; for (int i = 0; i < frequencies.length; i++) { sum = checkedAdd(frequencies[i], sum); cumulative[i + 1] = sum; } if (sum != total) throw new AssertionError(); }
2
public static final String crypt(String salt, String original) { while(salt.length() < 2) salt += "A"; StringBuffer buffer = new StringBuffer(" "); char charZero = salt.charAt(0); char charOne = salt.charAt(1); buffer.setCharAt(0, charZero); buffer.setCharAt(1, charOne); int Eswap0 = con_salt[(int)charZero]; int Eswap1 = con_salt[(int)charOne] << 4; byte key[] = new byte[8]; for(int i = 0; i < key.length; i ++) key[i] = (byte)0; for(int i = 0; i < key.length && i < original.length(); i ++) { int iChar = (int)original.charAt(i); key[i] = (byte)(iChar << 1); } int schedule[] = des_set_key(key); int out[] = body(schedule, Eswap0, Eswap1); byte b[] = new byte[9]; intToFourBytes(out[0], b, 0); intToFourBytes(out[1], b, 4); b[8] = 0; for(int i = 2, y = 0, u = 0x80; i < 13; i ++) { for(int j = 0, c = 0; j < 6; j ++) { c <<= 1; if(((int)b[y] & u) != 0) c |= 1; u >>>= 1; if(u == 0) { y++; u = 0x80; } buffer.setCharAt(i, (char)cov_2char[c]); } } return(buffer.toString()); }
8
public static void main(String args[]) { try { final String str_sysORTable = "1.3.6.1.2.1.1.9"; final String str_sysOREntry = "1.3.6.1.2.1.1.9.1"; final String str_sysORIndex = "1.3.6.1.2.1.1.9.1.1"; final String str_sysORID = "1.3.6.1.2.1.1.9.1.2"; final String str_sysORDescr = "1.3.6.1.2.1.1.9.1.3"; final String str_sysORUpTime = "1.3.6.1.2.1.1.9.1.4"; final ManagedInstance sysORID = new ManagedInstance(str_sysORID); final ManagedInstance sysORDescr = new ManagedInstance(str_sysORDescr); final ManagedInstance sysORUpTime = new ManagedInstance(str_sysORUpTime); final Hashtable columns = new Hashtable(); columns.put("sysORIndex", new Integer(1)); columns.put("sysORID", new Integer(2)); columns.put("sysORDescr", new Integer(3)); columns.put("sysORUpTime", new Integer(4)); Arguments a = new Arguments("SnmpGet"); a.parse(args); SnmpManager manager = a.generateManager(); Table managedObject = new Table(manager); System.out.println("Retrieve a table as a HashTable"); VarbindList vbl = new VarbindList(); vbl.addVarbind(sysORID.createVarbind()); vbl.addVarbind(sysORDescr.createVarbind()); vbl.addVarbind(sysORUpTime.createVarbind()); Hashtable h = managedObject.coreGetTable(new Hashtable(), vbl); Enumeration h_cells = h.elements(); while (h_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)h_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve a table as a Vector"); Vector v = managedObject.coreGetTable(new Vector(), vbl); Enumeration v_cells = v.elements(); while (v_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)v_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve a column as HashTable"); h = managedObject.coreGetColumn(new Hashtable(), str_sysORID); h_cells = h.elements(); while (h_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)h_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve a column as Vector"); v = managedObject.coreGetColumn(new Vector(), str_sysORID); v_cells = v.elements(); while (v_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)v_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve a row as HashTable"); h = managedObject.coreGetRow(new Hashtable(), vbl, "1"); h_cells = h.elements(); while (h_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)h_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve a row as Vector"); v = managedObject.coreGetRow(new Vector(), vbl, "1"); v_cells = v.elements(); while (v_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)v_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve the next row as HashTable"); h = managedObject.coreGetNextRow(new Hashtable(), vbl, "1"); h_cells = h.elements(); while (h_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)h_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } System.out.println("Retrieve the next row as Vector"); v = managedObject.coreGetNextRow(new Vector(), vbl, "1"); v_cells = v.elements(); while (v_cells.hasMoreElements()) { ManagedInstance mi = (ManagedInstance)v_cells.nextElement(); System.out.println("Name: " + mi.name + " value: " + mi.value); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
9
public String boolStrVal() { if (null == isTrue) { return "null"; } if (isTrue) { return "true"; } else { return "false"; } }
2
private Palos parsePalo(String s) { if(s.endsWith("d")){ return Palos.diamantes; }else if(s.endsWith("h")){ return Palos.corazones; }else if(s.endsWith("c")){ return Palos.treboles; }else if(s.endsWith("s")){ return Palos.picas; } return null; }
4
@Override public void draw(Object obj, Component comp, Graphics2D g2) { Image finalImage; if (isConnected) { finalImage = this.conectedTexture.connectedImage((ConectedTexture) obj); } else { finalImage = this.image; } int width = finalImage.getWidth(null); int height = finalImage.getHeight(null); int size = Math.max(width, height); // Scale to shrink or enlarge the image to fit the size 1x1 cell. g2.scale(1.0 / size, 1.0 / size); g2.clip(new Rectangle(-width / 2, -height / 2, width, height)); g2.drawImage(finalImage, -width / 2, -height / 2, null); }
1
public static boolean isInputDown(GameContainer container, List<Integer> input) { for (Integer key : input) { if (container.getInput().isKeyDown(key)) { return true; } } return false; }
2
public void setCast2(String[] src) { charCast2 = new Image[src.length]; for (int i = 0; i < src.length; i++) { try { charCast2[i] = new Image(src[i]); } catch (SlickException e) { System.out.println(e); } } }
2
public final GalaxyXPreprocessorParser.parameter_return parameter() throws RecognitionException { GalaxyXPreprocessorParser.parameter_return retval = new GalaxyXPreprocessorParser.parameter_return(); retval.start = input.LT(1); int parameter_StartIndex = input.index(); Object root_0 = null; Token IDENTIFIER69=null; GalaxyXPreprocessorParser.type_return type68 = null; Object IDENTIFIER69_tree=null; try { if ( state.backtracking>0 && alreadyParsedRule(input, 8) ) { return retval; } // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXPreprocessorParser.g:79:2: ( type IDENTIFIER ) // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXPreprocessorParser.g:79:4: type IDENTIFIER { root_0 = (Object)adaptor.nil(); pushFollow(FOLLOW_type_in_parameter402); type68=type(); state._fsp--; if (state.failed) return retval; if ( state.backtracking==0 ) adaptor.addChild(root_0, type68.getTree()); IDENTIFIER69=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_parameter404); if (state.failed) return retval; if ( state.backtracking==0 ) { IDENTIFIER69_tree = (Object)adaptor.create(IDENTIFIER69); adaptor.addChild(root_0, IDENTIFIER69_tree); } } retval.stop = input.LT(-1); if ( state.backtracking==0 ) { retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { if ( state.backtracking>0 ) { memoize(input, 8, parameter_StartIndex); } } return retval; }
9
public void MakeAllPackets() { while (packetsCreated < totalNumberOfPackets) { //add created packet to packet created queue packetCreated.add(CreatePacket()); } }
1
@Override public void init() { // グリッド初期化 _grid = new short[ GRID_Y ][ GRID_X ]; _gridColor = new short[ GRID_Y ][ GRID_X ]; // ファイルパスルート String filePathRoot = new File( "" ).getAbsolutePath(); // 背景読み込み ImageIcon bgIcon = new ImageIcon( filePathRoot + "/res/image/bg.png" ); _bgImg = bgIcon.getImage(); // 背景ブロック読み込み ImageIcon bgBlockIcon = new ImageIcon( filePathRoot + "/res/image/bgBlock.png" ); _bgBlockImg = bgBlockIcon.getImage(); // 背景ブロック座標設定 for ( int i = 0, y = 0; i < 16; i++, y += 24 ) { for ( int j = 0, x = 24; j < 10; j++, x += 24 ) { List< Integer > pos = new ArrayList<Integer>(); pos.add( x ); pos.add( y ); _bgBlockPos.add( pos ); } } // ブロック画像読み込み ImageIcon blockIcon = new ImageIcon( filePathRoot + "/res/image/block.png" ); _blockImg = blockIcon.getImage(); // 壁ブロック座標設定 for ( int i = 0, y = 0; i < 17; i++, y+= 24 ) { for ( int j = 0, x = 0; j < 12; j++, x += 24 ) { // 最終行以外は両端のみ if ( j > 0 && j < 11 && i < 16 ) { continue; } List< Integer > pos = new ArrayList<Integer>(); pos.add( x ); pos.add( y ); _wallBlockPos.add( pos ); } } // Press Enter画像読み込み ImageIcon pressEnterIcon = new ImageIcon( filePathRoot + "/res/image/press.png" ); _pressEnterImg = pressEnterIcon.getImage(); _pressEnterStart = System.currentTimeMillis(); _pressEnterPos.add( ( _displayWidth - _pressEnterImg.getWidth( null ) ) >> 1 ); _pressEnterPos.add( ( _displayHeight - _pressEnterImg.getHeight( null ) ) >> 1 ); // Ready画像読み込み ImageIcon readyIcon = new ImageIcon( filePathRoot + "/res/image/ready.png" ); _readyImg = readyIcon.getImage(); // GO!!!画像読み込み ImageIcon goIcon = new ImageIcon( filePathRoot + "/res/image/go.png" ); _goImg = goIcon.getImage(); // BGM読み込み _bgm = new Sound( filePathRoot + "/res/sound/bgm/Galaxy_loop.wav", true ); // SE読み込み _fixSe = new Sound( filePathRoot + "/res/sound/se/kachi.wav" ); _deleteSe = new Sound( filePathRoot + "/res/sound/se/delete.wav" ); }
7
public void omitLessFreq() { if (name == null) return; // Illegal int threshold = n_words[0] / LESS_FREQ_RATIO; if (threshold < MINIMUM_FREQ) threshold = MINIMUM_FREQ; Set<String> keys = freq.keySet(); int roman = 0; for(Iterator<String> i = keys.iterator(); i.hasNext(); ){ String key = i.next(); int count = freq.get(key); if (count <= threshold) { n_words[key.length()-1] -= count; i.remove(); } else { if (key.matches("^[A-Za-z]$")) { roman += count; } } } // roman check if (roman < n_words[0] / 3) { Set<String> keys2 = freq.keySet(); for(Iterator<String> i = keys2.iterator(); i.hasNext(); ){ String key = i.next(); if (key.matches(".*[A-Za-z].*")) { n_words[key.length()-1] -= freq.get(key); i.remove(); } } } }
8
public void setQuantidade(int quantidade) throws ErroValidacaoException{ if(quantidade < 0){ throw new ErroValidacaoException("A quantidade não pode ser menor que 0"); }else { this.quantidade = quantidade; } }
1
public boolean equals (Object other) { if ( ! (other instanceof MavenVersion)) return false; MavenVersion that = (MavenVersion) other; return this.major == that.major && this.minor == that.minor && this.incremental == that.incremental && this.qualifier.equals(that.qualifier); }
4
public static Strategy getStrategy(String strategyName) { if("average".equals(strategyName)) { return new AverageStrategy(); } else if("vacancyRate".equals(strategyName)) { return new VacancyRateStrategy(); } else { return new DefaultStrategy(); } }
2
public void getFriendshipWindmillGraph(mxAnalysisGraph aGraph, int numBranches, int branchSize) { if (numBranches < 2 || branchSize < 2) { throw new IllegalArgumentException(); } mxGraph graph = aGraph.getGraph(); Object parent = graph.getDefaultParent(); int numVertices = numBranches * branchSize + 1; Object[] vertices = new Object[numVertices]; int vertexCount = 0; for (int i = 0; i < numBranches; i++) { for (int j = 0; j < branchSize; j++) { vertices[vertexCount] = graph.insertVertex(parent, null, new Integer(vertexCount).toString(), 0, 0, 25, 25); vertexCount++; } } vertices[numVertices - 1] = graph.insertVertex(parent, null, new Integer(numVertices - 1).toString(), 0, 0, 25, 25); //make the connections for (int i = 0; i < numBranches; i++) { Object oldVertex = vertices[numVertices - 1]; for (int j = 0; j < branchSize; j++) { Object currVertex = vertices[i * (branchSize) + j]; graph.insertEdge(parent, null, getNewEdgeValue(aGraph), oldVertex, currVertex); oldVertex = currVertex; } Object currVertex = vertices[numVertices - 1]; graph.insertEdge(parent, null, getNewEdgeValue(aGraph), oldVertex, currVertex); } };
6
public static Uiswt getInstance() { if (uniqueInstance == null) { synchronized (Uiswt.class) { if (uniqueInstance == null) { uniqueInstance = new Uiswt(); } } } return uniqueInstance; }
2
public TabStripper(String args[]) { // Get input from the console String startingPath = ConsoleTools.getNonEmptyInput("Enter starting path: "); int numOfTabs = ConsoleTools.getIntInput("Enter the number of tabs to strip: "); String[] fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: "); while (fileExtensions.length <= 0) { fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: "); } System.out.println(""); // Setup the Crawler DirectoryCrawler crawler = new DirectoryCrawler(); crawler.setFileHandler(new TabStripperFileContentsHandler(numOfTabs, FileTools.LINE_ENDING_UNIX)); crawler.setFileFilter(new FileExtensionFilter(fileExtensions)); // Do the Crawl System.out.println("STARTING..."); crawler.crawl(startingPath); System.out.println("DONE"); // java -classpath com.organic.maynard.jar com.organic.maynard.TabStripper }
1
@Override public void setPrerequisites(String prerequisites) { if(prerequisites == null || prerequisites.isEmpty()) { this.prerequisites = "none"; } this.prerequisites = prerequisites; }
2
public static boolean isInside(Positioned a, Positioned b, boolean notOnTheEdge) { if (notOnTheEdge) { if (occupySameSpace(a, b)) return true; if (isInsideInSameHorizontalSpace(a, b)) return true; if (isInsideInSameVerticalSpace(a, b)) return true; } return pointInside(a, b.leftBorder(), b.topBorder(), notOnTheEdge) || pointInside(a, b.rightBorder(), b.topBorder(), notOnTheEdge) || pointInside(a, b.leftBorder(), b.bottomBorder(), notOnTheEdge) || pointInside(a, b.rightBorder(), b.bottomBorder(), notOnTheEdge); }
7
public LinkedList<Semester> uniformCostSearch() { LinkedList<Semester> optimalSemesterList = new LinkedList<Semester>(); if ( directoryOfClasses == null ) { System.err.println( "Error: directoryOfClasses does not exist"); System.exit(1); } // instantiate the root semester, which contains any courses previously // taken, considered as one semester Semester sem = new Semester(0, -1, 0, 2014, null, null, rootInheritedCourses, 0.0, 0.0); // set the root to active activeSemester = sem; // maintain explored? Set<Semester> explored = new HashSet<Semester>(); // add the root to the frontier frontier.push( sem ); // track current depth currentDepth = 0; // nodes explored int nodeCount = 1; // keep track of time long startTime = System.nanoTime(); List<Semester> childSem = new ArrayList<Semester>(); while (true) { // failure condition. optimal not found and nothing to observe if (frontier.isEmpty()) { optimalSemesterList = null; //returning failure System.out.println( "Unable to find a valid schedule."); break; } // we have reached a goal state. return a linked list of semester // objects for output and user feedback if (succeedsGoalTest(activeSemester)) { optimalSemesterList.addFirst(activeSemester); //backtrack up to the root to get the schedules for each semester //along the path from the root to the goal semester System.out.println( "Semester Found"); optimalSemesterList = activeSemester.getFinal(); for( int x = 0; x < optimalSemesterList.size(); x++ ) { System.out.println( optimalSemesterList.get(x)); } System.out.println( " Nodes explored: "+nodeCount); System.out.println( " Time taken: "+(( System.nanoTime() - startTime ) / 1000000000 )+"s"); break; } // if we're not at a goal state if (activeSemester.getDepth() <= numCourses ) { childSem = activeSemester.addChild(); Collections.sort( childSem ); // reverse the ordering of the pqueue and stack for( int i=childSem.size()-1; i>=0; i-- ) { frontier.push( childSem.get(i)); } nodeCount++; activeSemester = frontier.pop(); } } return optimalSemesterList; }
7
public void playRound() { // Reset our players piles (hand and won pile) -- necessary if this is // not the first game played with these Players. for (int i = 0; i < players.length; i++) players[i].resetPiles(); // Create the game piles this.createGamePiles(); // Increment our dealer. dealerIndex = (dealerIndex + 1) % PLAYER_COUNT; // Shuffle and deal cards this.deck.shuffle(); this.dealCards(); // Mark the start of a new round this.roundStats = this.gameStats.createNewRound(); this.roundStats.setRoundStart(); // Manage bidding and game type declaration. this.initiateBidding(); if(this.declarerIndex == -1) { this.roundStats.log("Every Player chose not to make an initial bid this Round. It has been ended prematurely."); this.roundStats.setRoundEnd(); return; } this.setGameType(); // Play the 10 tricks of a game of skat. for (int i = 0; i < 10; i++) { // Log our header for our trick. this.roundStats.log("Trick " + (i + 1) + ": ", this.indentationLevel); // Play the trick and determine who won. this.indentationLevel++; this.playTrick(); this.winTrick(); this.indentationLevel--; // If it's a null game, if declarer wins a trick, it's game over for them. if(this.gameType.getGameType() == GameTypeOptions.GameType.Null) if(firstToPlayIndex == declarerIndex) { this.roundStats.log("Declarer won a trick in a null game. It's an early game over.", this.indentationLevel); break; } } // Now that the tricks have been played, check if the declarer achieved schwarz or schneider. // If it's a null game, reset our multiplier. if(this.gameType.getGameType() == GameTypeOptions.GameType.Null) multiplier=1; else { // Check if schneider was achieved if(this.countCardPoints(this.declarerIndex) >= 90) { multiplier++; this.roundStats.log("Schneider was achieved in a non-null game!", this.indentationLevel); } // Check if schwarz was achieved if(this.players[this.declarerIndex].getTricksWonPile().getNumCards() == 30) { multiplier++; this.roundStats.log("Schwarz was achieved in a non-null game!", this.indentationLevel); } } // Once 10 tricks have been played, count card points, determine whether // or not the declarer won, update game scores. this.assignGamePoints(); // Mark the end of a round this.roundStats.setRoundEnd(); }
8
public double hiddenBias(int index) { if(index < 0 || index >= n) throw new RuntimeException("given n=" + n + ", illegal value for index: " + index); return _hiddenBias[index]; }
2
@Override public void check(final FolderConfig folderConfig) { // folderConfig.getSongs().clear(); String artistString = null; String user = null; try { final long artistId = getApi().resolve(folderConfig.getArtistUrl()); final HttpResponse artistResponse = getApi().get(new Request(String.format(Constants.ARTIST_TRACK_URL, artistId, Constants.CLIENT_ID))); artistString = EntityUtils.toString(artistResponse.getEntity()); final HttpResponse userResponse = getApi().get(new Request(String.format(Constants.ARTIST_URL, artistId, Constants.CLIENT_ID))); user = EntityUtils.toString(userResponse.getEntity()); } catch (final Exception e) { e.printStackTrace(); } final JSONObject userObj = new JSONObject(user); final String artist = userObj.getString("username"); folderConfig.setArtist(artist); System.out.println("Songs that need to sync from user: " + artist); final JSONArray array = new JSONArray(artistString); for (int i = 0; i < array.length(); i++) { final JSONObject obj = array.getJSONObject(i); checkSong(obj.getString("permalink_url"), folderConfig); } }
2
public boolean hasTarget() { if (rangeHandler.getPlacablesInRange().isEmpty()) { return false; } return true; }
1
public static void main(String[] args) throws Exception { long time = System.currentTimeMillis(); // Loading configuration first try (FileInputStream fis = new FileInputStream(CONFIG_PATH)) { logger.info("Loading configuration"); System.getProperties().load(fis); } catch (Throwable t) { logger.error("Unable to load configurations", t); System.exit(-1); } try { String protocol = System.getProperty("http-protocol", DEFAULT_PROTOCOL); String scheme = System.getProperty("org.apache.coyote.http11.SCHEME", DEFAULT_SCHEME); // Creating the web connector service // use the static NodeService if configured. WebConnectorService service = new WebConnectorService(protocol, scheme, new CLNodeService()); // configure the web connector service // Setting the address (host:port) int port = DEFAULT_HTTP_PORT; String portStr = System.getProperty("org.apache.tomcat.util.net.PORT"); if (portStr != null) { try { port = Integer.valueOf(portStr); } catch (Throwable t) { logger.error(t.getMessage(), t); System.setProperty("org.apache.tomcat.util.net.PORT", "" + DEFAULT_HTTP_PORT); } } else { System.setProperty("org.apache.tomcat.util.net.PORT", "" + DEFAULT_HTTP_PORT); } String hostname = System.getProperty("org.apache.tomcat.util.net.ADDRESS"); if (hostname == null) { hostname = "0.0.0.0"; System.setProperty("org.apache.tomcat.util.net.ADDRESS", hostname); } // Setting the address service.setAddress(new InetSocketAddress(hostname, port)); // TODO finish configuration setup // Starting the web connector service service.start(); services.add(service); // Add the static node somewhere and otherwise add the MCM one. // Adding node web connector service protocol = System.getProperty("http-protocol", DEFAULT_MCM_PROTOCOL); scheme = System.getProperty("org.jboss.cluster.proxy.http11.SCHEME", DEFAULT_SCHEME); // Creating the web connector service WebConnectorService nodeService = new WebConnectorService(protocol, scheme, new MCMNodeService()); // configure the web connector service // Setting the address (host:port) int mcmPort = DEFAULT_MCM_PORT; String mcmPortStr = System.getProperty("org.jboss.cluster.proxy.net.PORT"); if (mcmPortStr != null) { try { mcmPort = Integer.valueOf(mcmPortStr); } catch (Throwable t) { logger.error(t.getMessage(), t); System.setProperty("org.jboss.cluster.proxy.net.PORT", "" + DEFAULT_MCM_PORT); } } else { System.setProperty("org.jboss.cluster.proxy.net.PORT", "" + DEFAULT_MCM_PORT); } // Retrieve the MCMP hostname String mcmHostname = System.getProperty("org.jboss.cluster.proxy.net.ADDRESS"); if (mcmHostname == null) { mcmHostname = "0.0.0.0"; System.setProperty("org.jboss.cluster.proxy.net.ADDRESS", mcmHostname); } nodeService.setAddress(new InetSocketAddress(mcmHostname, mcmPort)); // TODO finish configuration setup // Starting the web connector service nodeService.start(); services.add(nodeService); } catch (Throwable e) { logger.error("creating protocol handler error", e); e.printStackTrace(); System.exit(-1); } threads.add(new Thread(new CLI(System.out))); time = System.currentTimeMillis() - time; logger.info("JBoss Mod Cluster Proxy started in " + time + "ms"); // Add shutdown hook addShutdownHook(); // Start all threads startThreads(); }
8
@Override public void update(Observable o, Object arg) { Integer mode = (Integer) arg; switch (mode) { case ApplicationState.MESSAGES_UPDATED: Messages m = (Messages) o; DefaultTableModel tableModel = (DefaultTableModel) jTable2.getModel(); tableModel.setRowCount(0); for (Message message : m.getAll()) { String[] row = {message.getSender().getUsername(), message.getText(), sdf.format(message.getDate())}; tableModel.addRow(row); } // scroll down JViewport viewport = (JViewport) jTable2.getParent(); Rectangle rect = jTable2.getCellRect(jTable2.getRowCount() - 1, 0, true); viewport.scrollRectToVisible(rect); break; case ApplicationState.USERS_UPDATED: Users u = (Users) o; DefaultListModel model = (DefaultListModel) usersList.getModel(); model.clear(); for (User user : u.getAll()) { model.addElement(user.getUsername()); } break; } }
4
private int minimax(NeutronBoard nb, int depth) { NeutronBoard n_copy; int best_value=-3000; if (nb.whoToMove()==NeutronBoard.BLACK) { best_value=3000; } if ((depth==0) || (nb.isGameOver()!=NeutronBoard.NOPLAYER)) { return NeutronUtil.evaluation(nb); } for (String AMove : nb.uniqueMoves()) { n_copy=new NeutronBoard(nb); try { n_copy.makeMove(AMove); } catch (IllegalMoveException e) { e.printStackTrace(); throw new RuntimeException("(033) This should never happen."); } if (nb.whoToMove()==NeutronBoard.WHITE) { // The max player best_value=Math.max(best_value,minimax(n_copy,depth-1)); } else { // The min-player best_value=Math.min(best_value,minimax(n_copy,depth-1)); } } return best_value; }
6
public String getLinkID() { return LinkID; }
0
public void setEntradasCollection(Collection<Entradas> entradasCollection) { this.entradasCollection = entradasCollection; }
0
@Override public EnvironnementAbs run(EnvironnementAbs env) { EnvironnementWator univert = (EnvironnementWator)env; ArrayList<AgentSwatorAbs> voisins = univert.voisins(pos_x, pos_y); boolean depalcementPossible = voisins.contains(null); cycleReproduction++; int x = pos_x,y = pos_y; if (depalcementPossible){ univert = move(univert); } if (cycleReproduction >= univert.tempsReproductionPoisson && depalcementPossible){ univert.grille[x][y] = new Poisson(String.valueOf(SMAWator.size()), x, y); cycleReproduction=-1; } return univert; }
3
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); controller.populateMovies(); this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } catch (IOException ex) { Logger.getLogger(mainPanel.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed
1
@EventHandler(priority = EventPriority.HIGH) public void InteractAggroMob(EntityTargetEvent event){ final EntityTargetEvent realEvent = (EntityTargetEvent) event; if(realEvent.getTarget() instanceof Player){ String TargetName = ((Player) realEvent.getTarget()).getName(); Player TargetedPlayer = Bukkit.getPlayer(TargetName); if(!TargetedPlayer.hasPermission("NodeWhitelist.Whitelisted")){ if(!whitelistWaive.isWaived(TargetedPlayer)){ if(!Config.GetBoolean("NoneWhitelisted.Restraints.Interact")){ event.setCancelled(true); } } } } }
4
public ManifestType createManifestType() { return new ManifestType(); }
0
* @param genFormatList the genFormat argument substitution sequence * * @throws UnknownHostException if cyc server host not found on the network * @throws IOException if a data communication error occurs * @throws CycApiException if the api request results in a cyc server error */ @Deprecated public void assertGenFormat(CycFort relation, String genFormatString, CycList genFormatList) throws UnknownHostException, IOException, CycApiException { // (#$genFormat <relation> <genFormatString> <genFormatList>) CycList sentence = new CycList(); sentence.add(getKnownConstantByGuid("beed06de-9c29-11b1-9dad-c379636f7270")); sentence.add(relation); sentence.add(genFormatString); if (genFormatList.size() == 0) { sentence.add(CycObjectFactory.nil); } else { sentence.add(genFormatList); } assertGaf(sentence, // #$EnglishParaphraseMt makeELMt(getKnownConstantByGuid("bda16220-9c29-11b1-9dad-c379636f7270"))); }
1
public void manageEconomy(final User user) { if (user == null) return; try { // Manage account final BankAccount acc = Economy.getInstance().getAccount(user); if (acc == null) return; // Check for welfare double welfare = acc.hasWelfare() ? Economy.getWelfareAmount() : 0.0D; // Calculate everything together double payday = acc.getPayday() + welfare; double taxes = acc.getCreditTax() + acc.getVehicleTax() + acc.getPropertyTax() + acc.getStateTax(); acc.updateBalance(acc.getBalance() + payday); acc.updateBalance(acc.getBalance() - taxes); } catch(Exception e) { e.printStackTrace(); } }
4
private void shoot() { boolean cur = GUI.whosTurn; if (this.p == GUI.getPlayer(cur)) { //ei voi ampua omalle alueelle return; } int result; /*yritys optimoida allaolevaa metodin osiota. ei toimi vielä*/ // result = GUI.getPlayer(cur).shoot(GUI.getPlayer(!cur), x, y); // if (GUI.getPlayer(!cur).getFleet().isEmpty()) { // result = -3; // GUI.win = true; // GUI.setWhosTurn(); // } else if (result == -1) { // if (!GUI.pvp) { // GUI.setWhosTurn(); // } // } if (GUI.whosTurn) { result = GUI.getPlayer1().shoot(GUI.getPlayer2(), x, y); if (GUI.getPlayer2().getFleet().isEmpty()) { result = -3; GUI.win = true; GUI.setWhosTurn(); } else if (result == -1) { if (!GUI.pvp) { GUI.setWhosTurn(); } } } else { result = GUI.getPlayer2().shoot(GUI.getPlayer1(), x, y); if (GUI.getPlayer1().getFleet().isEmpty()) { result = -3; GUI.win = true; GUI.setWhosTurn(); } if (result == -1) { if (!GUI.pvp) { GUI.setWhosTurn(); } } } GUI.infoState(result); updateColour(state); GUI.g1.updateAll(); GUI.g2.updateAll(); }
8
public boolean maskContainsRelativePoint(Point relativep, int maskindex) { // In case mask is not used (mask == null), always returns true if (getMask() == null) return true; // Checks if the maskindex was a valid number if (maskindex >= getMask().getImageNumber()) maskindex = getMask().getImageNumber() - 1; // Checks whether the point is within the mask and returns false if // it isn't if (!HelpMath.pointIsInRange(relativep, 0, getMask().getWidth(), 0, getMask().getHeight())) return false; if (maskindex >= 0) { int c = this.mask.getSubImage(maskindex).getRGB(relativep.x, relativep.y); return c == maskcolor; } // If maskindex was negative has to check each subimage else { for (int i = 0; i < getMask().getImageNumber(); i++) { int c = getMask().getSubImage(i).getRGB(relativep.x, relativep.y); if (c == maskcolor) return true; } return false; } }
6
public void handleDeath() { for (Iterator<NPC> i = NPC.iterator(); i.hasNext();) if (i.next().getDeath()) i.remove(); for (Iterator<Bullet> i = BulletAlly.iterator(); i.hasNext();) if (i.next().getDeath()) i.remove(); for (Iterator<Bullet> i = BulletNPC.iterator(); i.hasNext();) if (i.next().getDeath()) i.remove(); if (player.getDeath()) {SceneManager.Switch(new SceneGameOver());} }
7
private static char lookChar() { // return next character from input if (buffer == null || pos > buffer.length()) fillBuffer(); if (buffer == null) return EOF; else if (pos == buffer.length()) return '\n'; else return buffer.charAt(pos); }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractComponent other = (AbstractComponent) obj; if (identifier == null) { if (other.identifier != null) return false; } else if (!identifier.equals(other.identifier)) return false; return true; }
6
public PopupMenu(JPopupMenu menu){ this.menu = menu; }
0
public NetworkListener(int port) { this.port = port; }
0
public void actionPerformed(ActionEvent e) { if(forest ==1 && oldMan ==0){ boyY = boyY + velY; } if(forest ==1 && oldMan ==1){ GameFile.iLocY = GameFile.iLocY + velY; } }
4
public boolean inSameRankAs(Field otherField) { return this.distanceBetweenRank(otherField) == 0; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node other = (Node) obj; if (col == null) { if (other.col != null) return false; } else if (!col.equals(other.col)) return false; if (row == null) { if (other.row != null) return false; } else if (!row.equals(other.row)) return false; return true; }
9
private void cmbSearchItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbSearchItemStateChanged // TODO add your handling code here: String studentID = ""; String examID = ""; if (cmbExamID.getSelectedItem() != null) { examID = cmbExamID.getSelectedItem().toString(); if (cmbSearch.getSelectedItem() != null) { studentID = cmbSearch.getSelectedItem().toString(); if (!studentID.equals("No such student")) { try { ResultSet rst = marksController.retrieveSingleStudentMarks(examID, cmbSearch.getSelectedItem().toString()); if (rst.next()) { txtStudentID.setText(rst.getString("studentID")); txtMarks.setText(rst.getString("marks")); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } } } }//GEN-LAST:event_cmbSearchItemStateChanged
5
public Set<String> findSet(String woe_id,String group_id) { SearchParameters search_parameters = new SearchParameters(); search_parameters.setWoeId(woe_id); Set<String> user_set = findUserSet(woe_id); Set<String> result = new HashSet<String>(); PhotoList photo_list = null; System.out.println("total user:" + user_set.size()); int user_count = 0; String str = ""; int same_str = 0; for (String owner_id : user_set) { search_parameters.setUserId(owner_id); try { photo_list = photo_interface.search(search_parameters, 250, 1); int pages = photo_list.getPages(); for (int i = 1; i <= pages; i++) { photo_list = photo_interface.search(search_parameters, 250, i); for (Object o : photo_list) { Photo photo = (Photo) o; String photo_id = photo.getId(); Element photoElement = apiPhotosGetInfo(photo_id); String location = parseLocation(photoElement); System.out.println("location:" + location); if (str.equals(owner_id + "," + location)) same_str++; if (same_str >= 30) { same_str = 0; continue; } str = owner_id + "," + location; result.add(str); System.out.println("collected count:" + result.size()); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FlickrException e) { // TODO Auto-generated catch block e.printStackTrace(); } user_count++; System.out.println("done user:" + user_count); } return result; }
8
public String commonPrefix(PGridPath path) { if (path == null) { throw new NullPointerException(); } int index = 1; String oPath = path.toString(); while (path_.regionMatches(0, oPath, 0, index)) { index++; } index--; return path_.substring(0, index); }
2
public static String[] getKeyandValue(String line) { String[] words = Tools.readWords(line); if (words.length==0 || words[0].charAt(0)==commentChar) { return new String[] {"",""}; } String key, value=""; if (words[0].contains("=")) { String[] subwords = words[0].split("=",2); key = subwords[0]; if (subwords.length>1) { value = subwords[1]; } else if (words.length>1) { value = words[1]; } } else { key = words[0]; if (words.length>1) { if (words[1].equals("=") && words.length>2) { value = words[2]; } else { if (words[1].charAt(0)=='=') { value = words[1].substring(1); } } } } key = key.toUpperCase(); return new String[] {key, value}; } //getKeyandValue
9
public PolyCubicSplineFast(Object xArrays, Object fOfX){ this.fOfX = Fmath.copyObject(fOfX); this.xArrays = Fmath.copyObject(xArrays); // Calculate fOfX array dimension number Object internalArrays = Fmath.copyObject(fOfX); this.nDimensions = 1; while(!((internalArrays = Array.get(internalArrays, 0)) instanceof Double))this.nDimensions++; // Repack xArrays as 2 dimensional array if entered a single dimensioned array for a simple cubic spline if(this.xArrays instanceof double[] && this.nDimensions == 1){ double[][] xArraysTemp = new double[1][]; xArraysTemp[0] = (double[])this.xArrays; this.xArrays = (Object)xArraysTemp; } else{ if(!(this.xArrays instanceof double[][]))throw new IllegalArgumentException("xArrays should be a two dimensional array of doubles"); } // x -arrays and their limits this.xArray = (double[][])this.xArrays; // Select interpolation method switch(this.nDimensions){ case 0: throw new IllegalArgumentException("data array must have at least one dimension"); case 1: // If fOfX is one dimensional perform simple cubic spline CubicSplineFast cs = new CubicSplineFast(this.xArray[0], (double[])this.fOfX); this.method = (Object)cs; break; case 2: // If fOfX is two dimensional perform bicubic spline BiCubicSplineFast bcs = new BiCubicSplineFast(this.xArray[0], this.xArray[1], (double[][])this.fOfX); this.method = (Object)bcs; break; default: // If fOfX is greater than four dimensional, recursively call PolyCubicSplineFast // with, as arguments, the n1 fOfX sub-arrays, each of (number of dimensions - 1) dimensions, // where n1 is the number of x1 variables. Object obj = fOfX; this.dimOne = Array.getLength(obj); this.csArray = new double [dimOne]; double[][] newXarrays= new double[this.nDimensions-1][]; for(int i=0; i<this.nDimensions-1; i++){ newXarrays[i] = xArray[i+1]; } this.pcs = new PolyCubicSplineFast[dimOne]; for(int i=0; i<dimOne; i++){ Object objT = (Object)Array.get(obj, i); this.pcs[i] = new PolyCubicSplineFast(newXarrays, objT); } } }
9
public Piece selectMonRoi(int tour) { Piece monRoi = null; for(int i = 0; i < 8; i++){ for(int j = 0; j < 8; j++){ if(this.E.getTableau()[i][j]!=null) if(this.E.getTableau()[i][j].getClass().getName() == "pieces.Roi") if((this.E.getTableau()[i][j].getCouleur() == "blanc") && ((tour%2 != 0)) || (this.E.getTableau()[i][j].getCouleur() == "noir") && ((tour%2 == 0))) monRoi = this.E.getTableau()[i][j]; } } return monRoi; }
8
public void countNeuralValues(){ int i=0; int j=0; int k=0; for(i=0;i<incomeLayoutNeuronCount;i++){ incomeLayout.get(i).countOutcomeValue(); } for(i=0;i<hideLayoutNeuronCount;i++){ for(j=0;j<incomeLayoutNeuronCount;j++){ sendSignalFromTo(incomeLayout.get(j),hideLayouts.get(0).get(i)); } hideLayouts.get(0).get(i).countOutcomeValue(); } for(i=1; i<hideLayoutsCount; i++){ for(j=0; j<hideLayoutNeuronCount; j++){ for(k=0; k<hideLayoutNeuronCount; k++){ sendSignalFromTo(hideLayouts.get(i-1).get(k),hideLayouts.get(i).get(j)); } hideLayouts.get(i).get(j).countOutcomeValue(); } } //for(i=0; i<outcomeLayoutNeuronCount; i++){ // for(j=0; j<hideLayoutNeuronCount; j++){ // sendSignalFromTo(hideLayouts.get(hideLayoutsCount-1).get(j),outcomeLayout.get(i)); // } // outcomeLayout.get(i).countOutcomeValue(); //} for(i=0;i<hideLayoutNeuronCount;i++){ sendSignalFromTo(hideLayouts.get(hideLayoutsCount-1).get(i),outNeuron); } }
7
public void handle(SingleUserCrawlingEvent event) { long uid = event.getOriginalSourceUid(); if (uid > 0) { try { weibo4j.model.User user = SinaWeibo.getInstance().getUser(uid); if (user != SinaWeibo.USER_NOT_FOUND) { com.julu.weibouser.model.User juluUser = com.julu.weibouser.model.User.compose(user, event.getCrawlingTarget()); List<UserFollowersCrawlingEvent> subsequentEvents = UserFollowersCrawlingEventFactory. create(juluUser.getOriginalSourceUid(), juluUser.getFollowersCount()); StandalonePusher<UserFollowersCrawlingEvent, UserFollowersCrawlingEventQueue> pusher = EventSystem.getPusher(EventType.FIND_USER_FOLLOWERS); for (UserFollowersCrawlingEvent userFollowersCrawlingEvent : subsequentEvents) { try { pusher.push(userFollowersCrawlingEvent); } catch (EventProcessingException e) { consoleLogger.logError("Cannot push user followers finding event into queue " + userFollowersCrawlingEvent, e); } } if (!Integration.hasProcessed(event.getCrawlingTarget(), juluUser.getOriginalSourceUid())) { try { juluUser.setUid(IdService.getUniqueId()); ProcessingSystem.getInstance().push(Arrays.asList(juluUser)); } catch (IOException e) { consoleLogger.logError("Cannot serialization user instance " + juluUser, e); } catch (EventProcessingException e) { //TODO here will involve retrying process; consoleLogger.logError("Cannot push user processing event into queue " + juluUser, e); } } } else { //TODO here will involve some company policy, to be implement later } } catch (IntegrationException e) { //TODO here will involve retrying process, to be implement later } } }
8
public static int queryGetInt(HttpRequest req, String key, int def) { int ret = def; String val = null; if(req.method().equals("GET")) val = req.queryParam(key); else if(req.method().equals("POST")) val = req.postParam(key); if(val != null) try { ret = Integer.parseInt(val); } catch(NumberFormatException e) { log.debug(e.toString(), e); } return ret; }
4
@Override public Map convertMap(pplgg.Map myMap) { Tile[][] newMap = new Tile[myMap.getWidth()][myMap.getHeight()]; List<Tile> keys = new ArrayList<Tile>(); for (int x = 0; x < myMap.getWidth(); x++) { for (int y = 0; y < myMap.getHeight(); y++) { int type = myMap.getTerrain(x, y); if (type == 0) { newMap[x][y] = new Tile(type, false, x, y); } else if(type == 5){ Tile t = new Tile(type, false, x, y); newMap[x][y] = t; keys.add(t); } else { newMap[x][y] = new Tile(type, true, x, y); } } } return new Map(newMap, keys); }
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Feature)) { return false; } Feature other = (Feature) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
private DPTXlator createTranslator(final int objIndex, final int pid) throws KNXException, InterruptedException { final int ot = getObjectType(objIndex, true); int pdt = -1; Property p = (Property) properties.get(new PropertyKey(ot, pid)); // if no property found, lookup global pid if (p == null && pid < 50) p = (Property) properties.get(new PropertyKey(pid)); if (p != null) { if (p.dpt != null) try { final DPTXlator t = TranslatorTypes.createTranslator(0, p.dpt); t.setAppendUnit(false); return t; } catch (final KNXException e) { logger.warn("fallback to default translator for PID " + pid + ", no translator for DPT " + p.dpt, e); } pdt = p.pdt; } // if we didn't get pdt from definitions, query property description, // in local dev.mgmt, no pdt description is available if (pdt == -1 && !local) pdt = pa.getDescription(objIndex, pid, 0)[3] & 0x3f; if (PropertyTypes.hasTranslator(pdt)) { final DPTXlator t = PropertyTypes.createTranslator(pdt); t.setAppendUnit(false); return t; } final KNXException e = new KNXException( "no translator available for PID " + pid + ", " + getObjectTypeName(ot)); logger.warn("translator missing for PID " + pid + ", PDT " + pdt, e); throw e; }
8
@Override public void setName(String name) { this.name = name; }
0
public final static double roundBidAsk(double number, double tick, boolean bid) { // get rid of trailing 00..001s and 99..99s double raw = Math.round((number) * scale); long recpTick = Math.round(1 / tick); // get back to basis, tricky with the tick size due to floating issues raw /= scale * 1 / recpTick; // round to direction raw = bid ? Math.floor(raw) : Math.ceil(raw); return raw / recpTick; }
1
void setReverb(JSSample sample) { /* * Only third sample of multisample sounds has reverb parameters set. * For now, only positional and directional sounds are reverberated. */ int soundType = sample.getSoundType(); int dataType = sample.getDataType(); // QUESTION: Should reverb be applied to background sounds? if ( (soundType == AudioDevice3D.CONE_SOUND) || (soundType == AudioDevice3D.POINT_SOUND) ) { if (debugFlag) debugPrintln("setReverb called with type, on = " + auralParams.reverbType + ", " + auralParams.reverbFlag); if (sample == null) return; JSPositionalSample posSample = (JSPositionalSample)sample; if (posSample.channel == null) return; /********** // NOTE: no support for reverb channel yet... int reverbIndex = posSample.getReverbIndex(); **********/ if (dataType == JSSample.STREAMING_AUDIO_DATA) { JSStream stream = (JSStream)posSample.channel; stream.setSampleReverb(auralParams.reverbType, auralParams.reverbFlag); } else if (dataType == JSSample.BUFFERED_AUDIO_DATA) { JSClip clip = (JSClip)posSample.channel; clip.setSampleReverb(auralParams.reverbType, auralParams.reverbFlag); } /********** // TODO: else if (dataType == JSSample.STREAMING_MIDI_DATA || dataType == JSSample.BUFFERED_MIDI_DATA) { JSMidi.setSampleReverb(reverbIndex, auralParams.reverbType, auralParams.reverbFlag); } **********/ else { if (internalErrors) debugPrintln( "JavaSoundMixer: Internal Error setReverb " + "dataType " + dataType + " invalid"); } } }
8
static void optimize(final File f, final File d, final Remapper remapper) throws IOException { if (f.isDirectory()) { File[] files = f.listFiles(); for (int i = 0; i < files.length; ++i) { optimize(files[i], d, remapper); } } else if (f.getName().endsWith(".class")) { ConstantPool cp = new ConstantPool(); ClassReader cr = new ClassReader(new FileInputStream(f)); ClassWriter cw = new ClassWriter(0); ClassConstantsCollector ccc = new ClassConstantsCollector(cw, cp); ClassOptimizer co = new ClassOptimizer(ccc, remapper); cr.accept(co, ClassReader.SKIP_DEBUG); Set<Constant> constants = new TreeSet<Constant>( new ConstantComparator()); constants.addAll(cp.values()); cr = new ClassReader(cw.toByteArray()); cw = new ClassWriter(0); Iterator<Constant> i = constants.iterator(); while (i.hasNext()) { Constant c = i.next(); c.write(cw); } cr.accept(cw, ClassReader.SKIP_DEBUG); if (MAPPING.get(cr.getClassName() + "/remove") != null) { return; } String n = remapper.mapType(cr.getClassName()); File g = new File(d, n + ".class"); if (!g.exists() || g.lastModified() < f.lastModified()) { if (!g.getParentFile().exists() && !g.getParentFile().mkdirs()) { throw new IOException("Cannot create directory " + g.getParentFile()); } OutputStream os = new FileOutputStream(g); try { os.write(cw.toByteArray()); } finally { os.close(); } } } }
9
public static void makeReports(List<Book> bookL){ StringBuilder data=new StringBuilder(); for(Book b:bookL){ if (b.getQuantity() == 0){ data.append(b.toReport()); data.append("\n"); } } try { FileOutputStream file=new FileOutputStream(new File("report.txt")); file.write(data.toString().getBytes()); file.flush(); file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
4
public void startElement( String namespaceURI, String simpleName, String qualifiedName, Attributes attributes) throws SAXException { short currentTag = 0; String element = simpleName; if ("".equals(simpleName)) { element = qualifiedName; } if (element.equalsIgnoreCase(UUID_STATE_TAG_STR)) { currentTag = UUID_STATE_TAG; } else if (element.equalsIgnoreCase(NODE_TAG_STR)) { currentTag = NODE_TAG; } //Process attributes if (attributes != null) { switch (currentTag) { case 1 : processBodyTag(attributes); break; case 2 : processNodeTag(attributes); break; default : break; } } }
6
public boolean storeImageFreqsToDb(String imageFileName, long[][] bins, long pixels) { StopWatch sw = new StopWatch(); sw.start(); StringBuilder sql = new StringBuilder("INSERT INTO frequencies (id_image, r_value, g_value, b_value, frequency, frequency_perc) VALUES (?, ?, ?, ?, ?, ?)"); PreparedStatement ps = null; try { ps = mySqlConfig.getConnection().prepareStatement(sql.toString()); for (int i = 0; i < bins.length; i++) { for (int j = 0; j < 256; j++) { ps.setInt(1, 1); if (i == 0) {//setting R values ps.setLong(2, j); ps.setNull(3, java.sql.Types.NULL); ps.setNull(4, java.sql.Types.NULL); } else if (i == 1) {// G values ps.setNull(2, java.sql.Types.NULL); ps.setLong(3, j); ps.setNull(4, java.sql.Types.NULL); } else if (i == 2) {// B values ps.setNull(2, java.sql.Types.NULL); ps.setNull(3, java.sql.Types.NULL); ps.setLong(4, j); } ps.setLong(5, bins[i][j]); double freq_perc = ((double) bins[0][j]) / pixels; ps.setDouble(6, freq_perc); ps.addBatch(); } } ps.executeBatch(); } catch (SQLException ex) { System.err.println(ex.getMessage()); } finally { if (ps != null) { try { ps.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } sw.stop(); System.out.println("Inserting to DB took:" + sw.getTime() + " ms"); return true; }
8
public static ArrayList<Subcategorias> sqlSelectDos(Categorias cat){ ArrayList<Subcategorias> subcat = new ArrayList(); if(!BD.getInstance().sqlSelect("SELECT sc.nombre, sc.idsubcategorias FROM subcategorias sc INNER JOIN cat_subcat_tit_attr_descr pr ON pr.subcategorias_id = sc.idsubcategorias INNER JOIN categorias ca ON ca.idcategorias = pr.categorias_id WHERE ca.idcategorias = '"+cat.getId()+"' GROUP BY sc.nombre")){ return subcat; } while(BD.getInstance().sqlFetch()){ subcat.add(new Subcategorias(BD.getInstance().getInt("idsubcategorias") ,BD.getInstance().getString("nombre") )); } return subcat; }
2
private void CommandQuickPlay( boolean priority, boolean toStream, boolean toLoop, String sourcename, FilenameURL filenameURL, float x, float y, float z, int attModel, float distORroll, boolean temporary ) { if( soundLibrary != null ) { if( filenameURL.getFilename().matches( SoundSystemConfig.EXTENSION_MIDI ) && !SoundSystemConfig.midiCodec() ) { soundLibrary.loadMidi( toLoop, sourcename, filenameURL ); } else { soundLibrary.quickPlay( priority, toStream, toLoop, sourcename, filenameURL, x, y, z, attModel, distORroll, temporary ); } } else errorMessage( "Variable 'soundLibrary' null in method 'CommandQuickPlay'", 0 ); }
3
void hash(){ if(hashed) return; MAC macsha1=getHMACSHA1(); if(salt==null){ Random random=Session.random; synchronized(random){ salt=new byte[macsha1.getBlockSize()]; random.fill(salt, 0, salt.length); } } try{ synchronized(macsha1){ macsha1.init(salt); byte[] foo=Util.str2byte(host); macsha1.update(foo, 0, foo.length); hash=new byte[macsha1.getBlockSize()]; macsha1.doFinal(hash, 0); } } catch(Exception e){ } host=HASH_MAGIC+Util.byte2str(Util.toBase64(salt, 0, salt.length))+ HASH_DELIM+Util.byte2str(Util.toBase64(hash, 0, hash.length)); hashed=true; }
3
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ZobrazDetailFiltraForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ZobrazDetailFiltraForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ZobrazDetailFiltraForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ZobrazDetailFiltraForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ZobrazDetailFiltraForm dialog = new ZobrazDetailFiltraForm(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
protected void startGame() { notifyNewGame(); discardCards(); shuffle(); community.clear(); doAntes(); doBlinds(); dealCard(players.get((dealer + 1) % numplayers), false); dealCard(players.get((dealer + 1) % numplayers), false); dealCard(players.get((dealer + 1) % numplayers), false); dealCard(players.get((dealer + 1) % numplayers), false); for (int i = 0; i < 5; i++) { community.add(deck.deal()); } doneFlop = false; doneTurn = false; doneRiver = false; waitForBets(); if (countPlayers(true, true, false) > 1) { doneFlop = true; doBettingRound(); } if (countPlayers(true, true, false) > 1) { doneTurn = true; doBettingRound(); } if (countPlayers(true, true, false) > 1) { doneRiver = true; doBettingRound(); } if (countPlayers(true, true, false) > 1) { doShowDown(); } else { doWinner(); } for (Player player : players) { if (player.getCash() <= 0) { player.setOut(); } } notifyEndGame(); doDealerAdvance(); }
7
public static Criteria parseCriteria( Ptg[] criteria ) { DB dblist = DB.parseList( criteria ); if( dblist == null ) { return null; } Criteria crit = new Criteria( dblist.getNCols(), dblist.getNRows() ); crit.colHeaders = dblist.colHeaders; crit.rows = dblist.rows; if( log.isDebugEnabled() ) { log.debug( "\nCriteria:" ); for( int i = 0; i < crit.getNCols(); i++ ) { log.debug( "\t" + crit.getCol( i ) ); } for( int j = 0; j < crit.getNCols(); j++ ) { for( int i = 0; i < crit.getNRows(); i++ ) { log.debug( "\t" + crit.getCell( i, j ) ); } } } return crit; }
5
public void checkTableStructure(TableRegistration table) { // TODO Update table structure StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ") .append(table.getName()) .append(" LIMIT 1"); try { ResultSetMetaData meta = connection.prepareStatement(query.toString()).executeQuery().getMetaData(); Collection<FieldRegistration> fields = table.getFields(); // <field,alreadyexisting?> Map<String,String> redo = new LinkedHashMap<String,String>(); for (FieldRegistration f : fields){ boolean found = false; String deftype = SQLiteUtil.getSQLiteTypeFromClass(f.getType()); for (int i = 1; i <= meta.getColumnCount(); i++){ if (f.getName().equalsIgnoreCase(meta.getColumnName(i))){ found = true; break; } } if (!found){ redo.put(f.getName(),false + ";" + deftype); } } for (String s : redo.keySet()){ StringBuilder q = new StringBuilder(); String[] results = redo.get(s).split(";"); q.append("ALTER TABLE ").append(table.getName()).append(" "); q.append("ADD COLUMN ").append(s).append(" ").append(results[1]); connection.prepareStatement(q.toString()).executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } }
6
public void DVD() { pcIncrease(); if ((getXF().get().equals("00") || getXF().get().equals("10")) && (getRF().get().equals("00") || getRF().get().equals("10"))) { if (SelectRegister().get().equals("00000000000000000000")||SelectRegister().get().equals("10000000000000000000")){ //cc(3)set to 1 getCC().setBit(3, "1"); } else { getALU().OP1.set(SelectRegister().get());//OP1 take ry //String RFcopy = RF.get(); getRF().set(getXF().get()); getALU().OP2.set(SelectRegister().get());//OP2 take rx getALU().divide();//Op2/OP1 //RF.set(RFcopy); SelectRegister().set(getALU().RES.get()); pause(MIDDLE); SelectNextRegister().set(getALU().RES1.get()); pause(MIDDLE); } } }
6
private ArrayList<AnchorPiece> getAnchorPieces(Board board) { ArrayList<AnchorPiece> anchors = new ArrayList<AnchorPiece>(); ArrayList<Piece> opposingPieces = getOpposingNeighbors(board); for(Piece p : opposingPieces) { int x = this.getX(), y = this.getY(); int dirX = p.getX() - this.getX(); int dirY = p.getY() - this.getY(); Piece step = new Piece(p.getColor()); while(step != null && step.getColor() == p.getColor() && board.placeInRange(x, y)) { x += dirX; y += dirY; step = board.getPiece(x, y); } if(step != null && step.getColor() == this.color) { AnchorPiece anchor = new AnchorPiece(this); anchor.setAnchor(step); anchors.add(anchor); } } return anchors; }
6
private void placeButtons() { createButton(0 + startPointXCoordinate, 40 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.LEFT); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_W.png", 40, 40)); createButton(0 + startPointXCoordinate, 0 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.LEFTUP); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_NW.png", 40, 40)); createButton(40 + startPointXCoordinate, 0 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.UP); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_N.png", 40, 40)); createButton(80 + startPointXCoordinate, 0 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.RIGHTUP); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_NE.png", 40, 40)); createButton(80 + startPointXCoordinate, 40 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.RIGHT); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_E.png", 40, 40)); createButton(80 + startPointXCoordinate, 80 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.RIGHTDOWN); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_SE.png", 40, 40)); createButton(40 + startPointXCoordinate, 80 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.DOWN); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_S.png", 40, 40)); createButton(0 + startPointXCoordinate, 80 + startPointYCoordinate, 40, 40, new Runnable() { public void run() { MoveAction moveAction = objectTron .moveAction(Movement.LEFTDOWN); doAction(moveAction); repaint(); } }).setImage(loadImage("view/assets/arrow_SW.png", 40, 40)); createButton(0 + startPointXCoordinate, 120 + startPointYCoordinate, 120, 40, new Runnable() { public void run() { if (objectTron.getActivePlayer().getInventory().size() > 0) { askForItemToUse(); repaint(); } else { showError(getClass().getSimpleName(), "The inventory of the player is empty!"); } } }).setText("Use item"); createButton(0 + startPointXCoordinate, 160 + startPointYCoordinate, 120, 40, new Runnable() { public void run() { if (objectTron.getFirstItemOnPosition(objectTron .getActivePlayer().getPosition()) != null) { PickUpAction pickUpAction = objectTron .pickUpAction(objectTron .getFirstItemOnPosition(objectTron .getActivePlayer() .getPosition())); doAction(pickUpAction); repaint(); } else { showError(getClass().getSimpleName(), "There is no item on the current player's position!"); } } }).setText("Pick up item"); createButton(0 + startPointXCoordinate, 200 + startPointYCoordinate, 120, 80, new Runnable() { public void run() { doAction(new EndTurnAction()); repaint(); } }).setText("End Turn"); actionsLeft = new JLabel("Turns left: " + objectTron.getActivePlayer().getRemainingActions()); actionsLeft.setLocation(0 + startPointXCoordinate, 280 + startPointYCoordinate); actionsLeft.setSize(120, 20); actionsLeft.setHorizontalAlignment(JLabel.CENTER); panel.add(actionsLeft); playersInventory = new JLabel("Inventory"); playersInventory.setLocation(0 + startPointXCoordinate, 320 + startPointYCoordinate); playersInventory.setSize(120, 20); playersInventory.setHorizontalAlignment(JLabel.CENTER); panel.add(playersInventory); }
2
public void makeReactions(final SquirmChemistry chemistry, int n_x, int n_y, SquirmCellSlot cell_grid[][]) { // collect the unbonded neighbours of this cell (up to 8) final Vector<SquirmCell> neighbours = new Vector<SquirmCell>(); int tx, ty; SquirmCellSlot slot; SquirmCell cell; for (int i = 0; i < 8; i++) { tx = x + EIGHT_x[i]; ty = y + EIGHT_y[i]; if (tx >= 0 && tx < n_x && ty >= 0 && ty < n_y) { slot = cell_grid[tx][ty]; // does this cell slot contain a cell? if (!slot.queryEmpty()) { cell = slot.getOccupant(); // is this cell unbonded with us? if (!bonds.contains(cell)) { neighbours.addElement(cell); } } } } // see if this situation causes a reaction in the current chemistry chemistry.react(cell_grid, this, neighbours); }
7
@Override public void actionPerformed(ActionEvent e) { int numPages = pages.size(); String pageNumMessage; if(numPages > 1){ pageNumMessage = numPages + " pages."; } else{ pageNumMessage = numPages + " page."; } String allWords = ""; for(int i = 0; i < pages.size(); i++){ JTextPane currentPage = pages.get(i) ; String currentPageText = currentPage.getText(); allWords = allWords + " " + currentPageText; } String[] pageWords = allWords.split("\\W+"); int numWords = pageWords.length-1; String popUpMessage; popUpMessage = "No words typed on " + pageNumMessage; if(numWords == 1){ popUpMessage = "Only 1 word on " + pageNumMessage; } else if(numWords > 1){ popUpMessage = numWords + " words on " + pageNumMessage; } String imgLocation = "images/" + "wordCount" + ".png"; URL imageURL = EditText.class.getResource(imgLocation); if (imageURL != null) { //image found ImageIcon icon = new ImageIcon(imageURL, "WordCount"); JOptionPane.showMessageDialog( new JFrame(),popUpMessage,"Word Count",JOptionPane.PLAIN_MESSAGE,icon); } else{ JOptionPane.showInternalMessageDialog( new JFrame(),popUpMessage,"Word Count",JOptionPane.PLAIN_MESSAGE); } }
5
private boolean inPoly(FastVector ob, double x, double y) { int count = 0; double vecx, vecy; double change; double x1, y1, x2, y2; for (int noa = 1; noa < ob.size() - 2; noa += 2) { y1 = ((Double)ob.elementAt(noa+1)).doubleValue(); y2 = ((Double)ob.elementAt(noa+3)).doubleValue(); if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) { //then continue tests. vecy = y2 - y1; if (vecy == 0) { //then lines are parallel stop tests for this line } else { x1 = ((Double)ob.elementAt(noa)).doubleValue(); x2 = ((Double)ob.elementAt(noa+2)).doubleValue(); vecx = x2 - x1; change = (y - y1) / vecy; if (vecx * change + x1 >= x) { //then add to count as an intersected line count++; } } } } if ((count % 2) == 1) { //then lies inside polygon //System.out.println("in"); return true; } else { //System.out.println("out"); return false; } //System.out.println("WHAT?!?!?!?!!?!??!?!"); //return false; }
8
public ArrayList viewServiceDesc() { ArrayList temp = new ArrayList(); Query q = em.createQuery("SELECT t from ServiceEntity t"); for (Object o : q.getResultList()) { ServiceEntity p = (ServiceEntity) o; temp.add(p.getDescription()); } return temp; }
1
public static int[] findMinMax(int[] arr) { if( arr == null ){ throw new IllegalArgumentException("Can't find max/min in NULL array"); } if( arr.length == 0 ){ throw new IllegalArgumentException("Can't find max/min in EMPTY array"); } if( arr.length < 2 ){ return new int[]{ arr[0], arr[0] }; } int offset = 1; int min = arr[0]; int max = arr[0]; // array length is even if( (arr.length & 1) != 1 ){ min = Math.min(arr[0], arr[1]); max = (min == arr[0] ? arr[1] : arr[0]); ++offset; } int minTemp; int maxTemp; for( int i = offset; i < arr.length; i+=2 ){ if( arr[i] < arr[i+1] ){ minTemp = arr[i]; maxTemp = arr[i+1]; } else { minTemp = arr[i+1]; maxTemp = arr[i]; } if( minTemp < min ){ min = minTemp; } if( maxTemp > max ){ max = maxTemp; } } return new int[]{min, max}; }
9
public void startClient() { udpSocket = new UDPSocket(udpPort); MainClient.clientExecutionService.execute(udpSocket); try { socket = new Socket(host, tcpPort); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host + "."); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: " + host + ".\n" + "Please try again later!"); ioNotFound = true; shutdown(); // propper shutdown of the ExecutorService MainClient.clientExecutionService.shutdown(); // Disable new tasks from being submitted } // just build if the connection to the server is ok. if (ioNotFound == false) { String incommingMessage; ClientCommandListener commandListener = new ClientCommandListener(socket, udpPort, this); MainClient.clientExecutionService.execute(commandListener); try { while((incommingMessage = in.readLine()) != null) { // server shut down if (incommingMessage.equals("shutdownServer")) { System.out.println("Sorry, the Server just went offline, you have been logged out automatically. " + "Please press ENTER to shut down your Client and try to start it again later!"); shutdown(); ClientCommandListener.shutdown(); } else { System.out.println(incommingMessage); } } } catch (IOException e) { // empty- just is thrown when ending client } } }
6
private static void enqueueCacheEntry(String name, String version, String packCacheLocation, String minecraftVersion, List<String> installationQueue) { //Get entry location String entryPath = getCacheEntryPath(name, version, packCacheLocation); if (entryPath != null) { //Load entry config JSONObject entryConfig; try { entryConfig = Util.readJSONFile(entryPath + "/entry.json"); } catch (IOException ex) { Logger.warning("Instances.enqueueCacheEntry", "Could not load config for cache entry!"); return; } //Check Minecraft version if (!entryConfig.get("minecraftversion").equals(minecraftVersion)) { Logger.warning("Instances.enqueueCacheEntry", "Entry is not compatible with this version of Minecraft!"); return; } //Add to queue installationQueue.add(name + "-" + version); //Enqueue dependencies if (entryConfig.get("dependencies") != null) { for (Object obj : (JSONArray)entryConfig.get("dependencies")) { JSONObject dependencyObj = (JSONObject)obj; if (!installationQueue.contains(dependencyObj.get("name").toString() + "-" + dependencyObj.get("version").toString())) { Logger.info("Instances.getInstallationQueue", "Enqueueing '" + dependencyObj.get("name").toString() + "'..."); enqueueCacheEntry(dependencyObj.get("name").toString(), dependencyObj.get("version").toString(), packCacheLocation, minecraftVersion, installationQueue); } } } } else { Logger.warning("Instances.enqueueCacheEntry", "Cache entry not found!"); } }
6
private static void writePairs( Document dom, MVD mvd, Element parent, String encoding ) throws Exception { Element pParent = dom.createElement( "pairs" ); HashMap<Pair,Integer> parents = new HashMap<Pair,Integer>(); HashMap<Pair,LinkedList<Element>> orphans = new HashMap<Pair,LinkedList<Element>>(); int id = 1; for ( int i=0;i<mvd.pairs.size();i++ ) { Pair p = mvd.pairs.get( i ); Element pElement = dom.createElement( "pair" ); if ( p.children != null ) { pElement.setAttribute("id", Integer.toString(id) ); parents.put( p, new Integer(id++) ); // check if any orphans belong to this parent LinkedList<Element> llp = orphans.get( p ); if ( llp != null ) { Integer pId = parents.get( p ); for ( int j=0;j<llp.size();j++ ) { Element child = llp.get( j ); child.setAttribute( "parent", pId.toString() ); } orphans.remove( p ); } } else if ( p.parent != null ) { Integer pId = parents.get( p.parent ); if ( pId != null ) pElement.setAttribute( "parent", pId.toString() ); else { LinkedList<Element> children = orphans.get( p.parent ); if ( children == null ) { children = new LinkedList<Element>(); children.add( pElement ); orphans.put( p.parent, children ); } else children.add( pElement ); } } if ( p.versions.nextSetBit(0)==0 ) pElement.setAttribute("hint", Boolean.toString(true) ); pElement.setAttribute( "versions", serialiseVersion(p.versions) ); if ( p.parent == null ) { String contents = new String(p.getData(),encoding); pElement.setTextContent( contents ); } pParent.appendChild( pElement ); } // attach pairs node to its parent node parent.appendChild( pParent ); }
9
public static String encodeURIComponent(String s) { StringBuilder o = new StringBuilder(); for (char ch : s.toCharArray()) { if (isUnsafe(ch)) { o.append('%'); o.append(toHex(ch / 16)); o.append(toHex(ch % 16)); } else o.append(ch); } return o.toString().replace(" ","%20"); }
2
public void keyReleased(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_LEFT) { leftPressed = false; } else if (code == KeyEvent.VK_RIGHT) { rightPressed = false; } else if (code == KeyEvent.VK_UP) { upPressed = false; if (onGround) jumping = false; if (jumpHold) jumpHold = false; } }
5
private List<String> getListOfStyles() { List<String> styles = new ArrayList<String>(); try { String baseURL = Options.getInstance().getProperty("cloudURL"); URI rURI = new URI("http", null, baseURL, 80, "/styles/", null, null); URL url = rURI.toURL(); //URL url = new URL(baseURL+"/styles/"); InputStream response = url.openStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); // dbf.setCoalescing(true); // dbf.setExpandEntityReferences(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document readXML = db.parse(response); NodeList childNodes = readXML.getElementsByTagName("style"); Debug.print("Loading Styles from online: "+ childNodes.getLength()); for(int x = 0; x < childNodes.getLength(); x++ ) { Node child = childNodes.item(x); // generate the style list Debug.print("Style: " + child.getTextContent()); if(child.getTextContent() != null) { styles.add(child.getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } return styles; }
3
public boolean isChunkFullyGenerated(int x, int z) { // if all adjacent // chunks exist, it // should be a safe // enough bet that // this one is fully // generated return !(!doesChunkExist(x, z) || !doesChunkExist(x + 1, z) || !doesChunkExist(x - 1, z) || !doesChunkExist(x, z + 1) || !doesChunkExist( x, z - 1)); }
4
public void setCarPositions(ArrayList<CarPosition> carPositions) { allCars2.clear(); for (CarPosition carPosition : carPositions) { CarInfo carInfoOld = null; for (CarInfo car : allCars) { if (car.color != null && car.color.equals(carPosition.color)) { carInfoOld = car; } } CarInfo newCarInfo = obtainCarInfo(carPosition.name, carPosition.color, carInfoOld, carPosition); allCars2.add(newCarInfo); if (carInfoOld != null) { recycledCarInfos.add(carInfoOld); } } ArrayList<CarInfo> t = allCars; allCars = allCars2; allCars2 = t; if (turboTicksLeft > 0) { turboTicksLeft--; if (turboTicksLeft == 0) { System.out.println("set turbo factor to 1 because no more turboTicks left"); turboFactor = 1; } } if (turboCautionTicksLeft > 0) { turboCautionTicksLeft--; } }
8
public double[] getTemperatures(double[] var1, int var2, int var3, int var4, int var5) { if(var1 == null || var1.length < var4 * var5) { var1 = new double[var4 * var5]; } var1 = this.field_4194_e.func_4112_a(var1, (double)var2, (double)var3, var4, var5, 0.02500000037252903D, 0.02500000037252903D, 0.25D); this.field_4196_c = this.field_4192_g.func_4112_a(this.field_4196_c, (double)var2, (double)var3, var4, var5, 0.25D, 0.25D, 0.5882352941176471D); int var6 = 0; for(int var7 = 0; var7 < var4; ++var7) { for(int var8 = 0; var8 < var5; ++var8) { double var9 = this.field_4196_c[var6] * 1.1D + 0.5D; double var11 = 0.01D; double var13 = 1.0D - var11; double var15 = (var1[var6] * 0.15D + 0.7D) * var13 + var9 * var11; var15 = 1.0D - (1.0D - var15) * (1.0D - var15); if(var15 < 0.0D) { var15 = 0.0D; } if(var15 > 1.0D) { var15 = 1.0D; } var1[var6] = var15; ++var6; } } return var1; }
6
public void saveXml(String xmlFileName){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = factory.newDocumentBuilder(); DOMImplementation domImplementation = db.getDOMImplementation(); Document doc = domImplementation.createDocument(null, "XML_File", null); buildTree(doc, doc.getDocumentElement()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); Properties transfProps = new Properties(); transfProps.put("method", "xml"); transfProps.put("indent", "yes"); transformer.setOutputProperties(transfProps); DOMSource source = new DOMSource(doc); OutputStream out = new FileOutputStream(new File(xmlFileName)); StreamResult result = new StreamResult(out); transformer.transform(source, result); try { out.close(); } catch (Exception ex) {} } catch (Exception ex) { System.err.println("XML error\n"+ex.toString()); } }
2
@Override public boolean hasNext() { if (mNextValid) { return true; } while (mIterator.hasNext()) { Object obj = mIterator.next(); if (obj == null) { if (!mOmitNulls) { mNext = null; mNextValid = true; return true; } } else if (mContentClass.isInstance(obj)) { mNext = mContentClass.cast(obj); mNextValid = true; return true; } } return false; }
5
public static void deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { if (!file.delete()) { log.warn("Unable to delete directory file " + file); } } } } } boolean exist = path.exists(); boolean deleted = path.delete(); if (exist && !deleted) { log.warn("Unable to delete directory " + path); } log.info("Folder {} was deleted successfully.", path.getAbsolutePath()); }
7
public PreferenceString getCreateModDatesFormat() { if (useDocumentSettings()) { return this.createModDatesFormat; } else { return Preferences.getPreferenceString(Preferences.CREATE_MOD_DATES_FORMAT); } }
1
public boolean contains(Mark m) { if((m.top() || m.vmiddle()) && m.left()) { return m.y < (m.x / 2 + radius / 2); } else if(m.bottom() && (m.left() || m.middle())) { return (Math.pow(m.x, 2) + Math.pow(m.y, 2)) < Math.pow(radius, 2); } else if(m.bottom() && m.right()) { return m.x < radius && m.y > -radius; } return false; }
9
static boolean unpackZipTo(Path zipfile, Path destDirectory) throws IOException { boolean ret = true; byte[] bytebuffer = new byte[BUFFERSIZE]; ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile())); ZipEntry zipentry; while ((zipentry = zipinputstream.getNextEntry()) != null) { Path newFile = destDirectory.resolve(zipentry.getName()); if (!Files.exists(newFile.getParent(), LinkOption.NOFOLLOW_LINKS)) { Files.createDirectories(newFile.getParent()); } if (!Files.isDirectory(newFile, LinkOption.NOFOLLOW_LINKS)) { FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile()); int bytes; while ((bytes = zipinputstream.read(bytebuffer)) > -1) { fileoutputstream.write(bytebuffer, 0, bytes); } fileoutputstream.close(); } zipinputstream.closeEntry(); } zipinputstream.close(); return ret; }
4
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SessionRequestContent req = new SessionRequestContent(request); ActionCommand command = CommandFactory.defineCommand(req); String page = command.execute(req); req.insertAttributes(request); if (page != null) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page); dispatcher.forward(request, response); } else { page = ConfigurationManager.getProperty("path.page.index"); response.sendRedirect(request.getContextPath() + page); } }
1
public void sendServerMessage (String message) { for (Map.Entry<String, Socket> user : activeSockets.entrySet()) { Socket socket = user.getValue(); try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("*** [SERVER] " + message); } catch (IOException e) { } } }
2
private void sing(String singname) { System.out.println("唱歌:" + singname); }
0
public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); char[] str = s.toCharArray(); int n = 1 << s.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb = new StringBuilder(); for (int j = 0; j < s.length(); j++) { if (((i >> j) & 1 )== 1) { sb.append(str[j]); } } System.out.println(sb.toString()); } }
3
private void parseDayDetails(int i) { int firstOccurance = 0; for (int j=i-1; j>=0; j--) { if (parts[j].equals("next") || parts[j].equals("following") ) { isCommandDetails[j] = false; } else { firstOccurance = j+1; break; } } if ((firstOccurance > 0) && getConnectorWords().contains(parts[firstOccurance-1])) { isCommandDetails[firstOccurance-1] = false; if ((firstOccurance>1) && getConnectorWords().contains(parts[firstOccurance-2])) { isCommandDetails[firstOccurance-2] = false; } if ((firstOccurance>2) && getConnectorWords().contains(parts[firstOccurance-3])) { isCommandDetails[firstOccurance-3] = false; } } isCommandDetails[i] = false; }
9