text
stringlengths
14
410k
label
int32
0
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ChangeOfState other = (ChangeOfState) obj; if (newState == null) { if (other.newState != null) return false; } else if (!newState.equals(other.newState)) return false; if (statusFlags == null) { if (other.statusFlags != null) return false; } else if (!statusFlags.equals(other.statusFlags)) return false; return true; }
9
private void ladeFressakte(File aktdatei) { if (!aktdatei.exists() || aktdatei.isDirectory()) { System.err.println("Geschichtsdatei existiert nicht oder ist Ordner"); return; } try { BufferedReader reader = new BufferedReader(new FileReader(aktdatei)); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(" "); if (parts.length != 3) { System.err.println("Geschichts-Zeile ist ungültig und wird übersprungen: " + line); continue; } addFressakt(parts[0], parts[2]); } reader.close(); } catch (IOException e) { System.err.println("Konnte Fischdatei nicht laden"); e.printStackTrace(); } }
5
public void clusterDocument(Document doc) throws Exception{ Transaction tx = graphDb.beginTx(); try { ArrayList<Sentence> sentencesList = doc.getSentences(); // these tables will be used to calculate the similarity between the new document and existing cluster Hashtable<String, Double> documentSimilairtyTableForWords = new Hashtable<String, Double>(); Hashtable<String, Double> documentSimilairtyTableForEdges = new Hashtable<String, Double>(); double documentMagnitude = 0.0; double edgesMagnitude = 0.0; int numberOfEgdesOfDocument = 0; // //Loop for each sentence of the document for (int sentenceIndex = 0; sentenceIndex < sentencesList.size(); sentenceIndex++) { Sentence currentSentence = sentencesList.get(sentenceIndex); ArrayList<Word> currentSentenceWords = currentSentence.getWords(); //Loop for the words of the current sentence Word previousWord = null; Word currentWord = null; Node previousNodeInTheGraph = null; Node currentNodeInGraph = null; for (int wordIndex = 0; wordIndex < currentSentenceWords.size(); wordIndex++) { currentWord = currentSentenceWords.get(wordIndex); currentNodeInGraph = nodeIndex.get(Neo4jNode.WORD_PROPERTY, currentWord.getContent()).getSingle(); double wordValueForTheDocument = calculateWordValue(doc, currentWord); documentMagnitude += Math.pow(wordValueForTheDocument, 2); // start handling the word if(currentNodeInGraph != null){ // currentWord exists in the graph updateDocumentImportanceTable(documentSimilairtyTableForWords, currentNodeInGraph, wordValueForTheDocument); }else{ // currentWord is a new word currentNodeInGraph = createNewWord(currentWord); } // done handling the nodes // start handling the edges if((previousNodeInTheGraph != null) && (currentNodeInGraph != null)){ numberOfEgdesOfDocument++; edgesMagnitude++; String edgeID = previousWord.getContent()+"_"+currentWord.getContent(); Relationship edge = edgesIndex.get("edge", edgeID).getSingle(); if(edge != null){ //edge exists updateEdgesDocumentImportanceTable(documentSimilairtyTableForEdges, edge, 1); }else{ // create new edge createNewEdge(previousNodeInTheGraph, currentNodeInGraph, edgeID); } } // done handling the edges previousNodeInTheGraph = currentNodeInGraph; previousWord = currentWord; }// end loop for words of the current sentence }// end loop of sentence of the document // Evaluate the document to the matched clusters String closestCluster = getClosestCluster(doc, documentMagnitude, numberOfEgdesOfDocument ,documentSimilairtyTableForWords, documentSimilairtyTableForEdges); if(closestCluster.equalsIgnoreCase("")){ //create new cluster closestCluster = String.valueOf(clusterCounter); Neo4jCluster c = new Neo4jCluster(closestCluster); c.incrementMagnitude(documentMagnitude); c.incrementEdgesMagnitude(edgesMagnitude); this.clustersList.put(c.getId(), c); c.addDcoument(doc.getId()); this.clusterCounter++; updateTheGraph(doc); }else{ Neo4jCluster c = this.clustersList.get(closestCluster); c.incrementMagnitude(documentMagnitude); c.incrementEdgesMagnitude(edgesMagnitude); c.addDcoument(doc.getId()); updateTheGraph(doc); } tx.success(); } finally { tx.finish(); } }
7
public String makingReservation(String type){ Random rand=new Random(); String resr=""; if(type.equals("W")){ for(int i=0;i<wSeats.length;i++) { if(wSeats[i].equals("NA")){ if(i/3==0){ resr="A"+i+(rand.nextInt(899)+100); wSeats[i]=resr; } else{ resr="D"+(i-3)+(rand.nextInt(899)+100); wSeats[i]=resr; } break; } } } if(type.equals("A")){ for(int i=0;i<wSeats.length;i++) { if(wSeats[i].equals("NA")){ if(i/3==0){ resr="A"+i+(rand.nextInt(899)+100); aSeats[i]=resr; } else{ resr="D"+(i-3)+(rand.nextInt(899)+100); aSeats[i]=resr; } break; } } } return resr; }
8
private void button_remove_blue_listMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button_remove_blue_listMousePressed if(frame_index_selected!=-1) { if(current_frame==null) { Element new_frame = hitboxes_doc.createElement("Frame"); new_frame.setAttribute("number", ""+(frame_index_selected+1)); if(current_move==null) { Element new_move = hitboxes_doc.createElement("Move"); new_move.setAttribute("name", ""+list_moves.getSelectedValue()); hitboxes_doc.getFirstChild().appendChild(new_move); current_move=new_move; } current_move.appendChild(new_frame); current_frame=new_frame; } for(Node hitboxes_node=current_frame.getFirstChild();hitboxes_node!=null;hitboxes_node=hitboxes_node.getNextSibling())//Hitbox loop { if(hitboxes_node.getNodeName().equals("Hitboxes")) { if(((Element)hitboxes_node).getAttribute("variable").equals("blue")) { current_frame.removeChild(hitboxes_node); } } } frame_index_selected=-1; updateHitboxes(current_frame); } else { JOptionPane.showMessageDialog(null, "Select a frame first.", "Be careful", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_button_remove_blue_listMousePressed
6
public void removeFocus(){ if(tmpFocus==null && focus==character) return; tmpFocus = null; focus = character; focusing = false; moving = true; if(wasCharacterFacingLeft!=null) if (wasCharacterFacingLeft != character.getDirection()){ character.changeDirection(); wasCharacterFacingLeft = null; } }
4
private static void binarySearchFirst(int[] a, int i) { // TODO Auto-generated method stub int start = 0; int mid = 0 ; int end = a.length; while(start<end){ mid = ((start + end)/2); System.out.println(mid); if (a[mid] == i){ end = mid; } else if(a[mid] < i){ start = mid + 1; } else if(a[mid] > i) end = mid -1 ; if (start==end){ mid = start; } System.out.println("Start " + start); System.out.println("end " +end); } if(a.length > mid && a[mid] == i){ System.out.println("find " + mid); return ; } else{ System.out.println("Not Found"); } }
7
public int countMatches(String dataFile){ if(localconditions == null) { localconditions = new String[0]; } MatchData M = new MatchData(dataFile); Match m; int c = 0; Set<Integer> players = new HashSet<Integer>(); while((m = M.getNext()) != null) { if(m.getDuration() > 0 && m.winner != -2) { if(localConditionsMet(m,-1,-1)) { c++; for(int i : m.playerIds) { players.add(i); } } } } System.out.println(players.size() + " players in " + c + " matches"); M.close(); return c; }
6
public int[] readAllInts() { String[] fields = readAllStrings(); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; }
1
public MainMenuPanel(MainPanel mainPanel){ super(MainMenuPanel.ID,mainPanel); this.background = new Sprite("others/backMenu.png"); this.playSprite = new Sprite("others/menuButton.png"); this.exitSprite = new Sprite("others/menuButton.png"); this.mainPanel = mainPanel; this.setLayout(null); this.playButton = new JButton(){ public void paintComponent(Graphics g){ Point p1 = MainMenuPanel.this.getLocationOnScreen(); Point p2 = MouseInfo.getPointerInfo().getLocation(); Point p = new Point(p2.x-p1.x-240,p2.y-p1.y-300); if (this.contains(p)){ MainMenuPanel.this.playSprite.clip(300, 0, 300, 100); } else { MainMenuPanel.this.playSprite.clip(0, 0, 300, 100); } } }; this.playButton.setBounds(240,300,300,100); this.playButton.setBorderPainted(false); this.playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { MainMenuPanel.this.mainPanel.setPanel(GamePanel.ID); } }); this.exitButton = new JButton(){ public void paintComponent(Graphics g){ Point p1 = MainMenuPanel.this.getLocationOnScreen(); Point p2 = MouseInfo.getPointerInfo().getLocation(); Point p = new Point(p2.x-p1.x-240,p2.y-p1.y-420); if (this.contains(p)){ MainMenuPanel.this.exitSprite.clip(300, 0, 300, 100); } else { MainMenuPanel.this.exitSprite.clip(0, 0, 300, 100); } } }; this.exitButton.setBounds(240,420,300,100); this.exitButton.setBorderPainted(false); this.exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); this.add(this.playButton); this.add(this.exitButton); }
2
public void handle(String token) { StringTokenizer st = new StringTokenizer(token, " "); String action = st.nextToken(); List<String> params = new ArrayList<String>(); while (st.hasMoreTokens()) params.add(st.nextToken()); // Individual handling if (action.equals("g")) group(params.get(0)); else if (action.equals("v")) vertex(Double.parseDouble(params.get(0)), Double.parseDouble(params.get(1)), Double.parseDouble(params.get(2))); else if (action.equals("f")) { int[] vertices = new int[3]; int[] textures = new int[3]; for (int i = 0; i < 3; i++) { String[] arr = params.get(i).split("/"); vertices[i] = Integer.parseInt(arr[0]); textures[i] = arr.length > 1 && !arr[1].trim().equals("") ? Integer.parseInt(arr[1]) : -1; } face(vertices[0], vertices[1], vertices[2]); // FIXME Add texture support } }
7
public static final TypeBinding wellKnownType(Scope scope, int id) { switch (id) { case TypeIds.T_boolean: return TypeBinding.BOOLEAN; case TypeIds.T_byte: return TypeBinding.BYTE; case TypeIds.T_char: return TypeBinding.CHAR; case TypeIds.T_short: return TypeBinding.SHORT; case TypeIds.T_double: return TypeBinding.DOUBLE; case TypeIds.T_float: return TypeBinding.FLOAT; case TypeIds.T_int: return TypeBinding.INT; case TypeIds.T_long: return TypeBinding.LONG; // case TypeIds.T_JavaLangObject: // return scope.getJavaLangObject(); // case TypeIds.T_JavaLangString: // return scope.getJavaLangString(); default: return null; } }
8
@Override public AbstractPlay get(int number) { return bestPlays.get(number); }
0
private void runSingleFile(String[] args) { ConfigurationForStdOut configuration = ConfigurationForStdOut.parse(args); configuration.setProperties(properties); if (configuration.isInvalid()) exitStatus = 1; if (configuration.showHelp()) { System.out.println(configuration.getHelpText()); } else { stdOutInstrumenter.run(configuration); } }
2
private void reflectClassWrapper(Map<Type, Set<GeneTrait>> genePool, String className, int parameterCount, List<String> parameterTypes, int parametersSet) throws ClassNotFoundException { // This wrapper takes care of running reflectClass() for all possible combinations of parameter types on classes that are parameterized (Java generics) if (parametersSet < parameterCount) { // Recurse! for (BreedingClassSetup classSetup : Settings.getSettings().getClasses()) { if (!rawTypesClassMap.containsKey(classSetup.className)) { // Raw types are not supported by Java generics, so skip those if (parameterTypes.size() >= parametersSet + 1) { parameterTypes.remove(parametersSet); } parameterTypes.add(parametersSet, classSetup.className); reflectClassWrapper(genePool, className, parameterCount, parameterTypes, parametersSet + 1); } } } else { Class<?> clazz = rawTypesClassMap.get(className); if (clazz == null) { clazz = Class.forName(className); } Type classType = Type.getType(className + ((parameterCount == 0) ? "" : ("<" + Tools.implode(parameterTypes, ",") + ">"))); reflectClass(genePool, clazz, className, classType, parameterTypes); } }
7
synchronized void runProjectiles() { java.util.List<Projectile> remove = new LinkedList<Projectile>(); for (Projectile p : projectiles) { if (p.time >= 50) remove.add(p); else if(gameIsMultiPlayer() && p.hasCollision(otherPlayer)) { otherPlayer.loseHealth(); remove.add(p); } p.run(); } for (Projectile p : remove) { projectiles.remove(p); } }
5
private void loadConfig() throws InvalidConfigurationException { mAllGroups.clear(); mAutoGroups.clear(); FileConfiguration config = getConfig(); mNoisy = config.getBoolean("output_to_console", false); mInterval = config.getInt("ticks_between_run", 1200); if(mInterval <= 0) throw new InvalidConfigurationException("ticks_between_run must be greater than 0"); for(String key : config.getKeys(false)) { if(!config.isConfigurationSection(key)) continue; GroupSettings group = new GroupSettings(); group.load(config.getConfigurationSection(key)); if (group.isChunkOnly()) mChunkGroups.add(group); else { mAllGroups.add(group); if(group.shouldAutorun()) mAutoGroups.add(group); } getLogger().info(String.format("Loaded group %s: AutoRun: %s", group.getName(), group.shouldAutorun())); } if(config.isList("worlds")) { List<String> worlds = config.getStringList("worlds"); mWorlds = new HashSet<String>(worlds.size()); for(String world : worlds) mWorlds.add(world.toLowerCase()); } else mWorlds = new HashSet<String>(); mWorldsBlacklist = config.getBoolean("worlds_is_blacklist", true); mResetTicksLived = config.getBoolean("vehicle_reset_ticks_lived", false); }
7
public String toStringFile() { StringBuilder string = new StringBuilder(); HashMap<NodeVariable, Integer> nodevariable_agent = new HashMap<NodeVariable, Integer>(); HashMap<NodeFunction, Integer> nodefunction_agent = new HashMap<NodeFunction, Integer>(); Iterator<NodeVariable> itnv; Iterator<NodeFunction> itnf; FunctionEvaluator fe; // AGENTS Iterator<Agent> ita = this.agents.iterator(); while (ita.hasNext()) { Agent agent = ita.next(); string.append("AGENT ").append(agent.id()).append("\n"); itnv = agent.getVariables().iterator(); while (itnv.hasNext()) { NodeVariable nodeVariable = itnv.next(); nodevariable_agent.put(nodeVariable, agent.id()); } itnf = agent.getFunctions().iterator(); while (itnf.hasNext()) { NodeFunction nodeFunction = itnf.next(); nodefunction_agent.put(nodeFunction, agent.id()); } } // VARIABLES itnv = this.factorgraph.getNodevariables().iterator(); while (itnv.hasNext()) { NodeVariable nodeVariable = itnv.next(); string.append("VARIABLE ").append(nodeVariable.id()).append(" ").append(nodevariable_agent.get(nodeVariable)).append(" ").append(nodeVariable.size()).append("\n"); } // FUNCTIONS itnf = this.factorgraph.getNodefunctions().iterator(); while (itnf.hasNext()) { NodeFunction nodeFunction = itnf.next(); //string.append("CONSTRAINT ").append(nodeFunction.id()).append(" ").append(nodefunction_agent.get(nodeFunction)).append(" "); // constraint?! string.append(nodeFunction.getTypeOfFe()).append(nodeFunction.id()).append(" ").append(nodefunction_agent.get(nodeFunction)).append(" "); // variables id fe = nodeFunction.getFunction(); for (int i = 0; i < fe.parametersNumber(); i++) { string.append(fe.getParameter(i).id() + " "); } string.append("\n"); // variables values and function cost string.append(fe.toStringForFile()); } return string.toString(); }
6
public void draw() { Graphics g = getFrame().getBufferStrategy().getDrawGraphics(); g.setColor(new Color(240, 240, 240)); g.fillRect(0, 0, getWidth(), getHeight()); for (int i = 0; i < grid.getUI().getTowers().size(); i++) { if (grid.getUI().getTowers().get(i).clicked()) { if (getMouse().getY() > 0 && getMouse().getY() < getHeight()) { if (getMouse().getX() > 0 && getMouse().getX() < getWidth()) { int px = (int) (getMouse().getX() / grid.sideLength()); int py = (int) (getMouse().getY() / grid.sideLength()); g.setColor(new Color(119, 230, 127)); if (grid.canBePlaced(px, py)) if (!grid.getUI().on(getMouse())) g.fillRect(px * grid.sideLength() + 3, py * grid.sideLength() + 3, grid.sideLength() - 5, grid.sideLength() - 5); } } } } grid.draw(g); exitButton.draw(g); play.draw(g); }
8
private static boolean isUsefulProduction(Production production, Set set) { ProductionChecker pc = new ProductionChecker(); String rhs = production.getRHS(); for (int k = 0; k < rhs.length(); k++) { char ch = rhs.charAt(k); if (!ProductionChecker.isTerminal(ch) && !isInUsefulVariableSet(ch, set)) { return false; } } return true; }
3
private CompilerToken processFloat(String token, final String state) throws LexicalException { // state: real, realexponent, realexponentzero final String[] parts = token.split("\\."); final String NEW_EXPONENT = "e1"; final String NEW_DECIMAL = ".0e"; validateInteger(parts[0].split("e")[0]); // Validate the integer parts of the number if (token.indexOf(".") > 0) { validateInteger(parts[1].split("e")[0]); } if (state.equals("realexponent") || state.equals("realexponentzero")) { final String[] exponentParts = token.split("e"); validateInteger(exponentParts[1]); } if (token.indexOf(".") > 0) { if (token.indexOf("e") > 0) { } else { token += NEW_EXPONENT; } } else { if (token.indexOf("e") > 0) { final String[] tokenParts = token.split("e"); token = tokenParts[0] + NEW_DECIMAL + tokenParts[1]; } else { throw new LexicalException("Real number created without . or e. This doesn't seem physically possible!"); } } return new CompilerToken("real", token); }
6
public BotManager(final int num, long time, final URI uri, final int numMsg) { //this.r = new Random(Thread.currentThread().getId() + Config.MACHINE_SEED); //this.top = r.nextInt(Config.MAX_TOP); //this.left = r.nextInt(Config.MAX_LEFT); this.top = 0; //0 is just a hardcoded value so that I can see bots popping on the screen and disappear later on this.left = Config.MACHINE_SEED + num; // connect cc = new LogBot(this, num, time, uri, WebSocketDraft.DRAFT76); cc.connect(); this.botid = num; // send task doUpdatePosAndSend = new TimerTask() { @Override public void run() { updatePos(); cc.send(getStrFromPos()); numMsgSent ++; // log every LOG_FREQ msg if(numMsgSent % Config.LOG_FREQ == (Config.LOG_FREQ-1)) { cc.changeTrackedPositionAndLog(getTop(), getLeft()); } // flush every FLUSH_FREQ msg if(numMsgSent % Config.FLUSH_FREQ == (Config.FLUSH_FREQ-1)) { cc.flushLog(); } if(numMsgSent >= numMsg) { // I'm done sending all msg timer.cancel(); ctimer = new Timer(); ctimer.schedule(doClose, num*Config.SLEEP_CLOSE); } } }; // close task doClose = new TimerTask() { @Override public void run() { try { cc.close(); ctimer.cancel(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; } //end of botmanager constructor
4
public void updateEvent() { if (id != null) { PreparedStatement st = null; String q = "UPDATE events SET name = ?, location = ?, start_date = ?, end_date = ? WHERE id = ?"; try { java.sql.Date sd = null; java.sql.Date ed = null; if (this.startDate != null) { sd = new java.sql.Date(StringUtil.stringToDate(startDate).getTime()); } if (this.endDate != null) { ed = new java.sql.Date(StringUtil.stringToDate(endDate).getTime()); } conn = dbconn.getConnection(); st = conn.prepareStatement(q); st.setString(1, this.name); st.setString(2, this.location); st.setDate(3, sd); st.setDate(4, ed); st.setInt(5, this.id.intValue()); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); st.close(); } catch (SQLException e) { System.out.println("Unable to close connection"); } } } else { System.out.println("Unable to update event because id is null"); } }
5
public void rule_mapred() throws Exception { fs.delete(path, true); JobConf job = new JobConf(getConf(), WordCount.class); job.setJarByClass(WordCount.class); job.setJobName("Rule Based Classifier"); job.set("attr_num", String.valueOf(attr_num)); job.set("attr_value", attr_value); job.set("rule_no", String.valueOf(rule_no)); for(int i1=0;i1<=rule_no;i1++) { job.set("length"+i1, String.valueOf(rule[i1].length)); job.set("class_name"+i1, rule[i1].class_name); for(int i2=0;i2<rule[i1].length;i2++) { job.set("rule_num"+i1+i2, String.valueOf(rule[i1].num[i2])); job.set("rule_value"+i1+i2, rule[i1].val[i2]); } } FileInputFormat.setInputPaths(job, new Path(input)); FileOutputFormat.setOutputPath(job, new Path(output)); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); RunningJob job1 = JobClient.runJob(job); Counters c = job1.getCounters(); p1 = (int)c.getCounter(Counter.P1); n1 = (int)c.getCounter(Counter.N1); if(p0 == 0 && n0 == 0 && rule[rule_no].class_name.equals("p")) { n0 = 2761; p0 = 2571; } else if(p0 == 0 && n0 == 0 && rule[rule_no].class_name.equals("e")) { p0 = 2761; n0 = 2571; } if (p1 == 0 | n1 > 0) gain = 0; else { newGain = log2((double) p1 / (double) (p1 + n1)); oldGain = log2((double) p0 / (double) (p0 + n0)); gain = p1 * (newGain - oldGain); } System.out.println(gain); }
9
private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } }
1
public void run() { try { while (true) { TimeUnit.MILLISECONDS.sleep(100); System.out.println(Thread.currentThread() + " " + this); } } catch (InterruptedException e) { System.out.println("Interrupted"); } }
2
public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); }
3
public void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { menu.show(e.getComponent(), e.getX(), e.getY()); } }
1
private boolean isNumberVector() { if(x == Float.NEGATIVE_INFINITY || y == Float.NEGATIVE_INFINITY || x == Float.POSITIVE_INFINITY || y == Float.POSITIVE_INFINITY || x == Float.NaN || y == Float.NaN) { return false; } return true; }
6
void add() { String apiKey; BufferedReader bufferRead; ArrayList<Pushbullet> devices; Pushbullet device; String s; int option; int i = 0; String alias; UI.clearError(); try { System.out.print("Introduce la \"API_KEY\" del usuario: "); bufferRead = new BufferedReader(new InputStreamReader(System.in)); apiKey = bufferRead.readLine(); devices = PushbulletAPI.getDevices(apiKey); if (devices.size() == 0) { UI.setError("No se han encontrado dispositivos."); } else { UI.printHeader(); System.out.println(devices.size() + " dispositivos disponibles:"); System.out.println(""); for (i = 0; i < devices.size(); i++) { device = devices.get(i); System.out.println((i + 1) + ") " + device.getModel() + " Iden: " + device.getIden()); } System.out.println(""); System.out.print("Elige un dispositivo: "); bufferRead = new BufferedReader( new InputStreamReader(System.in)); s = bufferRead.readLine(); System.out.println(""); System.out.print("Introduce un alias para el dispositivo: "); bufferRead = new BufferedReader( new InputStreamReader(System.in)); alias = bufferRead.readLine(); option = Integer.parseInt(s); devices.get(option - 1).setApiKey(apiKey); devices.get(option - 1).setAlias(alias); services.add(devices.get(option - 1)); } } catch (IOException e) { e.printStackTrace(); } }
3
@EventHandler public void onPlayerQuit(PlayerQuitEvent e) { IrcClient client = Parent.Manager.getCurrentClient(); for(String s : client.getMcEcho_ActiveChannels()) { try{ client.PrivMsg(s, IrcColor.formatMCMessage(ChatManagerUtils.ParseDisplayName(e.getPlayer())) + IrcColor.NORMAL.getIRCColor() + " has left.", false); } catch(Exception ex){ } } }
2
static int afficheMenu() { int choix = 0; System.out.println(); System.out.println("1 : Déplacer le porte-avion"); System.out.println("2 : Faire décoller un avion"); System.out.println("3 : Faire attérir l'avion");// affiché si decoller System.out.println("4 : Ne rien faire"); System.out.println("5 : Quitter"); while ((choix != 1) && (choix != 2) && (choix != 3) && (choix != 4) && (choix != 5)) { try { choix = clavier.nextInt(); } catch (InputMismatchException e) { System.out.println("Veuillez saisir un chiffre :"); clavier.nextLine(); } } return choix; }
6
public void stop() { if (player != null) { player.close(); player = null; } }
1
public int validity() { int specifiedAttributes = 0; if (name != null) specifiedAttributes++; if (quality!= null) specifiedAttributes++; if (source != null) specifiedAttributes++; if (codec != null) specifiedAttributes++; if (releaseDate != null) specifiedAttributes++; if (seasonAndEpisode != null) specifiedAttributes++; return (specifiedAttributes*100/NEEDED_ATTRIBUTES); }
6
public int Checkhit(){ int i; for(i = 0 ;i < button_count ;i++){ if(xpos >= buttons[i].getX() && xpos <= buttons[i].getX()+buttonPress.getWidth()){ if(ypos >= buttons[i].getY() && ypos <= buttons[i].getY()+buttonPress.getWidth()){ return i; } } } return 3; }
5
public String findRandom() { // string to return results with String result = ""; // randomiser for finding a random number Random random = new Random(); // a random entry can only be found if there exists a tree if(treeSize>0) { // this number represents the number of traversals to be executed int downs = random.nextInt(treeSize); // this number determin es whether or not to traverse left or right int direction = downs%2; Node newNode = rootNode; // if the number of traversals are more than 0 enter the statment // otherwise return the data contained in the root node if(downs > 0) { // iterate through the tree until a leaf is reached or the specified // traversals have been traversed for(int i = 0 ; i < downs ; i ++) { // this produces a value of either 0 or 1. to specify left or right direction = random.nextInt(treeSize)%2; if(direction == 0) { if(newNode.hasRight()) newNode = newNode.getRight(); else { if(newNode.hasLeft()) newNode = newNode.getLeft(); else { result = newNode.getData().toString(); break; } } } else { if(newNode.hasLeft()) newNode = newNode.getLeft(); else { if(newNode.hasRight()) newNode = newNode.getRight(); else { result = newNode.getData().toString(); break; } } } } } else result = newNode.getData().toString(); } // return the result if one was found return result; }
8
public float readFloat(String tag){ float f =0; if(!data.containsKey(tag)){ System.out.println("The tag "+ tag + " did not exist."); return f; } double d = (double)data.get(tag); f = (float)d; return f; }
1
public static void writeProducts(String src){ XMLInputFactory xmlif = XMLInputFactory.newInstance(); try { XMLEventReader xmlr = xmlif.createXMLEventReader(new FileInputStream(new File(src))); while (xmlr.hasNext()) { XMLEvent e = xmlr.nextEvent(); if (e.isStartDocument()){ System.out.println("Start StAX parsing"); } else if (e.isStartElement()) { System.out.println("\n"+e.asStartElement().getName().getLocalPart()+": "); @SuppressWarnings("rawtypes") Iterator i = e.asStartElement().getAttributes(); while (i.hasNext()){ System.out.print("att: "+i.next().toString()+"; "); } i = e.asStartElement().getNamespaces(); while (i.hasNext()){ System.out.print("ns: "+i.next().toString()+"; "); } } else if(e.isCharacters()) { System.out.print(e.asCharacters().getData().trim()); } else if (e.isEndDocument()){ System.out.println("Parsing ended"); } } } catch (FileNotFoundException ffe) { ffe.printStackTrace(); } catch (XMLStreamException xmlse) { xmlse.printStackTrace(); } }
9
public void setCursor (int n) { for (int i = 0;i<boxes.size();i++) { Box b = boxes.get(i); Day d = b.getDayStored(); if (currentMonth.getNum()==b.getMonthStored().getNum()&&n==d.getNum()) cursor = new Box (b); } repaint(); }
3
private static boolean typesHaveTheSameParameter(final Type thisArgument, final Type thatArgument, final TypeMap typeMap) { if (thisArgument.equals(thatArgument)) { return true; } if (isWildcard(thisArgument)) { if (isWildcard(thatArgument)) { return wildcardsAreAssignable((WildcardType) thisArgument, (WildcardType) thatArgument, typeMap); } else { return isAssignableFromWildcard((WildcardType) thisArgument, thatArgument, typeMap); } } else if (isTypeVariable(thatArgument)) { final TypeVariable<?> thatTypeVariable = (TypeVariable<?>) thatArgument; final Type thatResolvedType = typeMap.getActualType(thatTypeVariable); return typesHaveTheSameParameter(thisArgument, thatResolvedType, typeMap); } // This only happens with Java 7. // In Java 6 you will always get two GenericArrayTypes, and the match will happen on an earlier equals. else if (isClass(thisArgument) && isGenericArrayType(thatArgument)) { final Class<?> arrayClassFromGenericArray = getArrayClassFromGenericArray((GenericArrayType) thatArgument); return thisArgument.equals(arrayClassFromGenericArray); } return false; }
9
@Override public EntityInfo getFileMetaData(String path) throws PathNotFoundException { if (path.contains(hiddenPrefix)) throw new PathNotFoundException(path); if (hardlinks) { //Get hard link paths String[] hardlinks = getHardLinks(path); if (hardlinks.length > 0) { EntityInfo info = innerFs.getFileMetaData(hardlinks[0]); FileInfo fileInfo = (FileInfo)info; FileInfo target = new FileInfo(path, fileInfo.getFileSize()); target.setCreationTime(fileInfo.getCreationTime()); target.setLastAccessTime(fileInfo.getLastAccessTime()); target.setLastModificationTime(fileInfo.getLastModificationTime()); return target; } } if (symlinks) { if (attributeFs.pathExists(getSymLinkPath(path))) { String dest = ""; try { dest = FileSystemUtils.readWholeText(attributeFs, getSymLinkPath(path)); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (AccessDeniedException e) { e.printStackTrace(); } catch (NotAFileException e) { e.printStackTrace(); } return new SymbolicLinkInfo(path, dest); } } return innerFs.getFileMetaData(path); }
8
public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE); Thread t = new Thread(r); t.start(); } }
1
public static synchronized boolean wavereplay() { if (Signlink.savereq != null) { return false; } else { Signlink.savebuf = null; Signlink.waveplay = true; Signlink.savereq = "sound" + Signlink.wavepos + ".wav"; return true; } }
1
public ZombieFrame(JPanel... contents) { super("ZombieHouse"); // Request keyboard focus for the frame. setFocusable(true); requestFocusInWindow(); requestFocus(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setUndecorated(true); setResizable(false); setBackground(Color.BLACK); // The content pane. An optional JPanel may be passed into the // constructor. It creates an empty pane with a black background if // one isn't provided. pane = getContentPane(); pane.setBackground(Color.BLACK); pane.setFocusable(false); pane.setVisible(true); if (contents.length > 0) { pane.add(contents[0]); } keys = new ZombieKeyBinds((JComponent) pane); // Get the graphics device information. GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice graphics = environment.getDefaultScreenDevice(); pack(); // Go full screen, if supported. if (graphics.isFullScreenSupported()) { try { graphics.setFullScreenWindow(this); // Having gone full screen, retrieve the display size. // size = Toolkit.getDefaultToolkit().getScreenSize(); // This double-switching of setVisible is to fix a bug with // full-screen-exclusive mode on OS X. Versions 10.8 and later // don't send keyboard events properly without it. if (System.getProperty("os.name").contains("OS X")) { setVisible(false); } } catch (HeadlessException ex) { System.err.println("Error: primary display not set or found. " + "Your experience of life may be suboptimal."); ex.printStackTrace(); } } else { // If full-screen-exclusive mode isn't supported, switch to // maximized window mode. System.err.println("Full-screen-exclusive mode not supported."); setExtendedState(Frame.MAXIMIZED_BOTH); } setVisible(true); }
4
public void mouseExited(MouseEvent e){ }
0
public void addResultSet(List<Map<String, Object>> resultSet) { if (rowData.size() <= 0) { setResultSet(resultSet); } else { if (resultSet != null && resultSet.size() > 0) { if (resultSet.get(0).keySet().size() != columnNames.length) { throw new IllegalArgumentException("Column names does not match current table model!"); } rowData.addAll(resultSet); } } this.fireTableDataChanged(); }
4
private void txtnumtmovilKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnumtmovilKeyTyped char caracter = evt.getKeyChar();//Validacion del campo telefono movil if (caracter >= '0' && caracter <= '9' || caracter == 8 || caracter == KeyEvent.VK_BACK_SPACE || caracter == KeyEvent.VK_CAPS_LOCK || caracter == KeyEvent.VK_SHIFT) { } else { evt.consume(); } if (txtnumtmovil.getText().length() >= 7) { evt.consume(); } }//GEN-LAST:event_txtnumtmovilKeyTyped
7
@Override protected void onServerResponse(int code, String response) { if (code == 372 || code <= 5 || code == 375 || code == 376 || code == 396) { if (DarkIRC.currentChan.type == Channel.STATUS) { GUIMain.add_line(response); } else { Logs.makeLog("status.log", Logs.readLog("status.log") + response + "\n"); GUIMain.jTabbedPane2.setForegroundAt(0, Color.RED); } } }
6
public void countFolders() throws IOException { System.out.println("counting Folders"); finalPath = Paths.get(backupDir.substring(0,backupDir.lastIndexOf(System.getProperty("file.separator"))+ 1)); try {DirectoryStream<Path> stream = Files.newDirectoryStream(finalPath); { for (@SuppressWarnings("unused") Path file: stream) { folderNum++; System.out.println(folderNum); } }} catch (IOException x) { System.out.println(x); } if(folderNum > folderMax) { //run delete filetree with oldest as the path for (int i=0; i<folderNum-folderMax;i++){ try {DirectoryStream<Path> stream = Files.newDirectoryStream(finalPath); { for (Path file: stream) { folderNumber++; if(oldest == null) { oldest=file; BasicFileAttributes attrs = Files.readAttributes(oldest, BasicFileAttributes.class); oldestTime = attrs.creationTime(); } else { newFile = file; BasicFileAttributes attrs = Files.readAttributes(newFile, BasicFileAttributes.class); newFileTime = attrs.creationTime(); result = oldestTime.compareTo(newFileTime); if(result>0) { oldest=newFile; } } } }} catch (IOException x) { System.out.println(x); } System.out.print("num over max = "); System.out.println(folderNumber-folderMax); folderNumber=0; Delete d1 = new Delete(); System.out.println("Deleting folder " + oldest); Files.walkFileTree(oldest, d1); oldest = null; newFile = null; } } }
8
private Component toComponent( Object obj ) { Component ret; if( obj instanceof Object[] ) { ret = SJPanel.createVerticalIPanel(null); Object[] objs = (Object[]) obj; for( int i=0; i<objs.length; ++i ) { ((SJPanel)ret).add( toComponent(objs[i]) ); } } else if( obj instanceof String ) { String str = (String) obj; String strs[] = str.split("\n"); if( strs.length == 1 ) { String s = (String) obj; SJLabel xol; if( s.length() == 0 ) { xol = new SJLabel(" ", WidgetUtil.getOptionPaneProperty("main text filler")); Dimension d = xol.getPreferredSize(); d.height /= 2; xol.setPreferredSize( d ); } else { xol = new SJLabel(s, WidgetUtil.getOptionPaneProperty("main text")); } xol.setAlignmentX(0); return xol; } return toComponent( strs ); } else if( obj instanceof Icon ) { SJLabel xol = new SJLabel((Icon)obj, WidgetUtil.getOptionPaneProperty("main text icon")); xol.setAlignmentX(0); return xol; } else if( obj instanceof Component ) { if( obj instanceof JComponent ) ((JComponent)obj).setAlignmentX(0); return (Component) obj; } else { ret = new SJLabel(obj.toString(), WidgetUtil.getOptionPaneProperty("main text")); } return ret; }
8
private void createNewRoom() { String name = mainPanel.getNewChatRoomName(); if(name == null) { return; } if(name.isEmpty()) { return; } try { ChatRoom room = session.create(name); mainPanel.addChatRoom(room); } catch(RemoteException e) { fatalErrorExit("Fatal error", e); } catch(ChatRoomInvalidStateException e) { fatalErrorExit("Fatal error", e); } catch(ChatRoomAlreadyExistsException e) { warning("Room already exist."); } }
5
private static void errorMessage(String message, String expecting) { // Report error on input. if (readingStandardInput && writingStandardOutput) { // inform user of error and force user to re-enter. out.println(); out.print(" *** Error in input: " + message + "\n"); out.print(" *** Expecting: " + expecting + "\n"); out.print(" *** Discarding Input: "); if (lookChar() == '\n') out.print("(end-of-line)\n\n"); else { while (lookChar() != '\n') // Discard and echo remaining chars on the current line of input. out.print(readChar()); out.print("\n\n"); } out.print("Please re-enter: "); out.flush(); readChar(); // discard the end-of-line character inputErrorCount++; if (inputErrorCount >= 10) throw new IllegalArgumentException("Too many input consecutive input errors on standard input."); } else if (inputFileName != null) throw new IllegalArgumentException("Error while reading from file \"" + inputFileName + "\":\n" + message + "\nExpecting " + expecting); else throw new IllegalArgumentException("Error while reading from inptu stream:\n" + message + "\nExpecting " + expecting); }
6
public TreePath getPath(String fullName) { if (fullName == null || fullName.length() == 0) return new TreePath(root); int pos = -1; int length = 2; while ((pos = fullName.indexOf('.', pos + 1)) != -1) length++; TreeElement[] path = new TreeElement[length]; path[0] = root; int i = 0; pos = -1; next_component: while (pos < fullName.length()) { int start = pos + 1; pos = fullName.indexOf('.', start); if (pos == -1) pos = fullName.length(); String component = fullName.substring(start, pos); TreeElement[] childs = getChildrens(path[i]); for (int j = 0; j < childs.length; j++) { if (childs[j].getName().equals(component)) { path[++i] = childs[j]; continue next_component; } } return null; } return new TreePath(path); }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SequencePosition other = (SequencePosition) obj; if (position == null) { if (other.position != null) return false; } else if (!position.equals(other.position)) return false; if (setLength == null) { if (other.setLength != null) return false; } else if (!setLength.equals(other.setLength)) return false; return true; }
9
public List<String> getIDS() { List<String> citationIDS=new ArrayList<>(); String query="select distinct "+attr+" from "+tablename+" order by paperid asc limit "+cur+","+limit; ResultSet rsSet=sqLconnection.Query(query); try { while(rsSet.next()) { String id=rsSet.getString(attr); citationIDS.add(id); } } catch (SQLException e) { e.printStackTrace(); } this.sqLconnection.disconnectMySQL(); return citationIDS; }
2
private void doLogin (final String username, String password, String mojangData, String selectedProfile) { if (ModPack.getSelectedPack().getDisclaimer() != null && !ModPack.getSelectedPack().getDisclaimer().isEmpty()) { ErrorUtils.tossError(ModPack.getSelectedPack().getDisclaimer()); } if ((mojangData == null || mojangData.isEmpty()) && password.isEmpty()) { password = "password"; } Logger.logInfo("Logging in..."); tabbedPane.setEnabledAt(0, false); tabbedPane.setIconAt(0, LauncherStyle.getCurrentStyle().filterHeaderIcon(this.getClass().getResource("/image/tabs/news.png"))); tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, false); tabbedPane.setEnabledAt(4, false); tabbedPane.getSelectedComponent().setEnabled(false); launch.setEnabled(false); users.setEnabled(false); edit.setEnabled(false); serverbutton.setEnabled(false); mapInstall.setEnabled(false); mapInstallLocation.setEnabled(false); serverMap.setEnabled(false); tpInstall.setEnabled(false); tpInstallLocation.setEnabled(false); runGameUpdater(username); enableObjects(); }
5
private static Method findSuperMethod2(Class clazz, String name, String desc) { Method m = findMethod2(clazz, name, desc); if (m != null) return m; Class superClass = clazz.getSuperclass(); if (superClass != null) { m = findSuperMethod2(superClass, name, desc); if (m != null) return m; } return searchInterfaces(clazz, name, desc); }
3
public boolean dispatch(CommandSender sender, String commandName, String label, String[] args) { for (int argsIncluded = args.length; argsIncluded >= 0; argsIncluded--) { StringBuilder identifierBuilder = new StringBuilder(commandName); for(int i = 0; i < argsIncluded; i++) { identifierBuilder.append(' ').append(args[i]); } String identifier = identifierBuilder.toString(); Command cmd = getCmdFromIdent(identifier, sender); if (cmd != null) { String[] realArgs = (String[])Arrays.copyOfRange(args, argsIncluded, args.length); if (!cmd.isInProgress(sender)) { if ((realArgs.length < cmd.getMaxArguments()) || (realArgs.length > cmd.getMaxArguments())) { displayCommandHelp(cmd, sender); return true; } if ((realArgs.length > 0) && (realArgs[0].equals("?"))) { displayCommandHelp(cmd, sender); return true; } } if (!DonorTitles.perms.has(sender, cmd.getPermission())) { sender.sendMessage("Insufficient permission."); return true; } cmd.execute(sender, identifier, realArgs); return true; } } sender.sendMessage("Unrecognized command!"); return true; }
9
private static MavenJarFile downloadAndUnzipJarForUnix(MavenJarFile oldMavenJarFile, URL jarRepository, FileDAO fileDAO) throws MalformedURLException, IOException, XMLStreamException { MavenJarFile downloadedJarFile = null; URL archiveURL = WebDAO.getUrlOfZippedVersion(jarRepository, ".tar.gz", true); if (archiveURL != null) { downloadedJarFile = fileDAO.getMavenJarFileFromFolderWithArtifactId(fileDAO.unGzipAndUntarFile(new GZIPInputStream(archiveURL.openStream()), new File(fileDAO.getLocationToDownloadOnDisk(oldMavenJarFile.getAbsoluteFilePath()), archiveURL.getFile())), oldMavenJarFile.getArtifactId()); } else { archiveURL = WebDAO.getUrlOfZippedVersion(jarRepository, ".zip", true); try { downloadedJarFile = fileDAO.getMavenJarFileFromFolderWithArtifactId(fileDAO.unGzipAndUntarFile(new GZIPInputStream(archiveURL.openStream()), new File(fileDAO.getLocationToDownloadOnDisk(oldMavenJarFile.getAbsoluteFilePath()), archiveURL.getFile())), oldMavenJarFile.getArtifactId()); } catch (IOException ioex) { handleSilently(ioex); } } return downloadedJarFile; }
2
@Override public boolean equals (Object obj) { if (!(obj instanceof Entry)) { return false; } Entry e = (Entry) obj; return (piece == e.piece) && (pieceRange.equals(e.pieceRange)) && (file.equals(e.file)) && (fileRange.equals(e.fileRange)); }
4
public void createFileProtocol(String protocolName, String className) { try { Class theClass = Class.forName(className); FileProtocol fileProtocol = (FileProtocol) theClass.newInstance(); fileProtocol.setName(protocolName); boolean success = addProtocol(fileProtocol); if (success) { if (VERBOSE) { System.out.println(" File Protocol: " + className + " -> " + protocolName); } } else { System.out.println(" Duplicate File Protocol Name: " + protocolName); } } catch (ClassNotFoundException cnfe) { System.out.println("Exception: " + className + " " + cnfe); } catch (Exception e) { e.printStackTrace(); } }
4
public void addRecentFile( String filename ) { boolean notListed = true; //true if file is not on list, false if on list int index = 0; //determine if filename exists in list for(int i=0; i<numRecentFiles; i++) { String rf = getRecentFile( i ); if( rf!=null && !rf.equalsIgnoreCase("null") ) if( rf.equalsIgnoreCase( filename ) ) { notListed = false; index = i; } } //increment #files for this file if not already on list and menu not full if( notListed && (this.numRecentFiles < this.MAX_NUM_RECENT_FILES) ) numRecentFiles++; if( notListed ) { //remove oldest file from list (push all files down the list) for( int i=numRecentFiles-1; i>0 ; i--) recentFile[ i ] = getRecentFile( i-1 ); } else //shuffle file order { String temp = recentFile[ index ]; for( int i=index; i>0; i-- ) { recentFile[ i ] = recentFile[ i-1 ]; } recentFile[0] = temp; } //put newest at top recentFile[ 0 ] = filename; }
9
private boolean dadosValidos() { return !StringHelper.estaNulaOuVazia(txtCpf.getText()) && !StringHelper.estaNulaOuVazia(txtLogin.getText()) && !StringHelper.estaNulaOuVazia(txtNome.getText()) && !StringHelper.estaNulaOuVazia(txtSenha.getText()) && !StringHelper.estaNulaOuVazia(txtConfirmarSenha.getText()) && !StringHelper.estaNulaOuVazia(txtSobrenome.getText()) && cboPerfil.getSelectedItem() != null; }
6
static void round(int nr) { writeln("Round "+nr); int correct = 0; for(int i = 0; i < Q_PER_ROUND; i++) { if(question(i+1)) correct++; } writeln("Round grade: "+correct+"/"+Q_PER_ROUND); writeln("---------------------------------"); }
2
private void print(byte[] bytes, String name) { System.out.print("byte[" + name + "]:"); for (int i = 0 ; i < bytes.length ; ++i) { System.out.print("" + bytes[i]); if (i < bytes.length ) { System.out.print(", "); } } System.out.println(); }
2
public double[] distributionForInstance(Instance instance) throws Exception { double[] result = new double[instance.numClasses()]; switch (m_CombinationRule) { case AVERAGE_RULE: result = distributionForInstanceAverage(instance); break; case PRODUCT_RULE: result = distributionForInstanceProduct(instance); break; case MAJORITY_VOTING_RULE: result = distributionForInstanceMajorityVoting(instance); break; case MIN_RULE: result = distributionForInstanceMin(instance); break; case MAX_RULE: result = distributionForInstanceMax(instance); break; case MEDIAN_RULE: result[0] = classifyInstance(instance); break; default: throw new IllegalStateException("Unknown combination rule '" + m_CombinationRule + "'!"); } if (!instance.classAttribute().isNumeric() && (Utils.sum(result) > 0)) Utils.normalize(result); return result; }
8
public MySplash(Rectangle progressArea, Color progressColor, Point statusPosition, Color statusColor) { this.progressColor = progressColor; this.statusPosition = statusPosition; this.statusColor = statusColor; this.progressArea = progressArea; if ((splash == null) || (!splash.isVisible())) { graphics = null; return; } synchronized (splash) { if (instanceCreated) throw new RuntimeException("Only one single instance accepted."); instanceCreated = true; } graphics = splash.createGraphics(); graphics.setColor(progressColor); graphics.drawRect(progressArea.x, progressArea.y, progressArea.width, progressArea.height); splash.update(); statusLastWidth = 0; }
3
public static Clock makeClock(String clockType, Hosts hosts, String hostName){ Clock clock = null; if(clockType.equals("vector")){ clock = (Clock)(new VectorClock(hosts, hostName)); } else{ clock = (Clock)(new LogicClock()); } return clock; }
1
public static mxObjectCodec getCodec(String name) { String tmp = aliases.get(name); if (tmp != null) { name = tmp; } mxObjectCodec codec = codecs.get(name); // Registers a new default codec for the given name // if no codec has been previously defined. if (codec == null) { Object instance = getInstanceForName(name); if (instance != null) { try { codec = new mxObjectCodec(instance); register(codec); } catch (Exception e) { // ignore } } } return codec; }
4
public void test_01() { String args[] = { "-v" // , "-noStats" // , "-i", "vcf", "-o", "vcf" // , "-classic" // , "-onlyTr", "tests/filterTranscripts_01.txt"// , "testHg3765Chr22" // , "tests/test_filter_transcripts_001.vcf" // }; SnpEff cmd = new SnpEff(args); SnpEffCmdEff cmdEff = (SnpEffCmdEff) cmd.snpEffCmd(); List<VcfEntry> vcfEntries = cmdEff.run(true); for (VcfEntry ve : vcfEntries) { System.out.println(ve); // Get effect string String effs = ve.getInfo(VcfEffect.VCF_INFO_EFF_NAME); for (String effStr : effs.split(",")) { VcfEffect veff = new VcfEffect(effStr); System.out.println("\ttrId:" + veff.getTranscriptId() + "\t" + veff); Assert.assertEquals("ENST00000400573", veff.getTranscriptId()); } } }
2
@Override public void mouseClicked(MouseEvent arg0) { String[] values = ((String) productsComboBox.getSelectedItem()).split("\\t"); if (productsComboBox.getItemAt((productsComboBox.getSelectedIndex())).equals( "<html><font color='red'>Add New Product</font></html>")) { if (values != null && !automaticItemSelection) { driver.getGui().getTabbedPane().setSelectedComponent( driver.getGui().getProductTab()); driver.getGui().getProductTab().getNewSupplierProductButton(person).doClick(); } } else if (productsComboBox.isEnabled()) { driver.getGui().getTabbedPane().setSelectedComponent(driver.getGui().getProductTab()); driver.getGui().getProductTab().setSelectedProduct( driver.getStockDB().getStockItem(Integer.parseInt(values[1].trim()))); } }
4
public boolean onCommand(CommandSender sender, Command command, String label,String[] args) { //we know that command is 'event', but check anyways if(!command.getName().equalsIgnoreCase("event")){ return false; } if (args.length < 1){return false;} String subCommand = args[0]; switch(subCommand){ case "create": return createEvent(sender,args); case "delete": return deleteEvent(sender,args); case "setLocation": return setLocation(sender,args); case "setTime": return setTime(sender,args); case "list": return listEvents(sender,args); case "setMessage": return setMessage(sender,args); case "addNotification": return addNotification(sender,args); } return false; }
9
@Override public void setGUITreeComponentID(String id) {this.id = id;}
0
public int zerosCount() { int a = bits; int count = 0; for(int i = 0 ; i < 32 ; i ++){ if((a & 0x1) != 0x1){ count ++ ; } a = a >> 1; } return count; }
2
public OpenFileFormat getDefaultImportFileFormat() { return defaultImportFileFormat; }
0
public static String executeShellCommandWithOutput(String command, String logFileName) { try { StringBuilder stdErr = new StringBuilder(); int exitVal = TestShared.executeShellCommand(command, stdErr); if (exitVal != 0) { return ""; } String stdOut = TestShared.readFileAsString(TestShared.formatCardPersonalizedOutputLogFilePath(logFileName)); return stdOut; } catch (IOException ex) { return ""; } }
2
public String getProtocoleJdbc() { return protocoleJdbc; }
0
public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source.equals(buttonSave)) { // Start Cash initialize controller.start(getCredit()); this.dispose(); } else if (source.equals(buttonClose)) { // Exit controller.start(STARTCASH); this.dispose(); } }
2
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(MainWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainWindows().setVisible(true); } }); }
6
public boolean placeDownStairs() { boolean success = true; Room downStairsRoom = getDeepestRoom(); Tile downStairsTile; if (downStairsRoom.getFreeTiles().size() == 0) { ArrayList<Tile> edgeTilesCopy = (ArrayList<Tile>) downStairsRoom.getEdgeTiles().clone(); downStairsTile = (Tile) chooseRandom(edgeTilesCopy); int x = downStairsTile.getX(); int y = downStairsTile.getY(); while (edgeTilesCopy.size() > 0 && (getTile(x + 1, y) == TILE_DOOR || getTile(x - 1, y) == TILE_DOOR || getTile(x, y + 1) == TILE_DOOR || getTile(x, y - 1) == TILE_DOOR)) { edgeTilesCopy.remove(downStairsTile); if (edgeTilesCopy.size() > 0) { downStairsTile = (Tile) chooseRandom(edgeTilesCopy); x = downStairsTile.getX(); y = downStairsTile.getY(); } else { success = false; } } if (success) { downStairsRoom.removeEdgeTile(downStairsTile.getX(), downStairsTile.getY()); downStairsRoom.setTile(downStairsTile.getX(), downStairsTile.getY(), TILE_DOWNSTAIRS); setTile(downStairsTile.getX(), downStairsTile.getY(), TILE_DOWNSTAIRS); } } else { downStairsTile = (Tile) chooseRandom(downStairsRoom.getFreeTiles()); downStairsRoom.removeFreeTile(downStairsTile.getX(), downStairsTile.getY()); downStairsRoom.setTile(downStairsTile.getX(), downStairsTile.getY(), TILE_DOWNSTAIRS); setTile(downStairsTile.getX(), downStairsTile.getY(), TILE_DOWNSTAIRS); } return success; }
8
private static void write(String s, DataTag obj){ try { File theDir = new File("saves/"+s+".json"); theDir.getParentFile().mkdirs(); FileWriter file = new FileWriter(theDir); file.write(obj.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
1
@Override public Scanner scan(Lexer lexer) { loop: while (true) { if (lexer.hasNext()) { final char ch = lexer.next(); switch (ch) { case '\\': if (lexer.hasNext()) { final char chn = lexer.next(); if (chn != '\n') { break; } } case '\n': return error(lexer); case '\'': break loop; } } else { return error(lexer); } } lexer.emit(TokenType.CHAR_CONSTANT); return new InsideActionScanner(); }
7
public void update(Vector<Event> events) { if (isServer) sendBroadcastPacket(); if(isServer) { for (InetAddress ip : clients.keySet()) { clients.put(ip, clients.get(ip).floatValue() + Time.deltaTime()); } removeInactiveClients(); } for (Event ev : events) { try { if (isServer) broadcastPacket(ev); else if (ev.getAddress().equals(myAdress) && ev.isSentOverNetwork()) { sendPacket(ev); } } catch (IOException e) {e.printStackTrace();} } }
8
public Vector<BluetoothService> loadServices(){ Vector<BluetoothService> ret = new Vector<>(); File bt_services = new File(SERVICE_DIR); String[] bt_services_filenames = bt_services.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".bts"); } }); for(String s:bt_services_filenames){ try { BufferedReader br = new BufferedReader(new FileReader(SERVICE_DIR+s)); String name = br.readLine(); String uuid = br.readLine(); br.close(); BluetoothServiceEntity retI = new BluetoothServiceEntity(name,uuid); ret.add(retI); } catch (IOException e) { e.printStackTrace(); } } return ret; }
2
public static void qSort(int[] a, int begin, int end) { if (begin > end) return; int temp = a[begin]; int lbegin = begin; int right = end; while (lbegin < right) { while (lbegin < right && a[right] >= temp) right--; a[lbegin] = a[right]; while (lbegin < right && a[lbegin] < temp) lbegin++; a[right] = a[lbegin]; } if (lbegin == right) a[lbegin] = temp; qSort(a, begin, lbegin - 1); qSort(a, lbegin + 1, end); }
7
public static byte[] inetAddress2Bytes(InetAddress val) { if (val == null){ return null; } if (!(val instanceof Inet4Address)) { throw new IllegalArgumentException("Adress must be of subclass Inet4Address"); } return val.getAddress(); }
2
public static boolean isDisplayModeBetter(DisplayMode current, DisplayMode isBetter){ //Formatted weirdly to quickly see what the preferred settings are if( isBetter.getWidth() >= current.getWidth() && isBetter.getHeight() >= current.getHeight() && isBetter.getFrequency() >= current.getFrequency() && isBetter.getBitsPerPixel() >= current.getBitsPerPixel() && isBetter.isFullscreenCapable() ){ return true; } return false; }
5
public void parse(String[] inputarray){ switch(inputarray[0].toLowerCase()){ case "exit": IO.logln("[EXIT] User called exit"); System.exit(0); break; case "commands": IO.println("> calc_speed @speed @force @airrestistance (per m/s) @mass @initialtime @finaltimee or @acel @initialtime @finaltime"); IO.println("> calc_acel @force @mass"); IO.println("> calc_brake @speed @brakerate"); IO.println("> calc_mass @acel @force"); IO.println("> convert-mk - Converts between m/s and km/h"); IO.println("> convert-km - Converts between km/h and m/s"); break; case "calc_speed": CalcSpeed.set(Double.parseDouble(inputarray[1]), Double.parseDouble(inputarray[2]), Double.parseDouble(inputarray[3]), Double.parseDouble(inputarray[4]), Double.parseDouble(inputarray[5]), Double.parseDouble(inputarray[6])); CalcSpeed.printSpeed(); break; case "calc_acel": CalcAcel ca = new CalcAcel(); ca.set(Double.parseDouble(inputarray[1]), Double.parseDouble(inputarray[2])); ca.printAcel(); break; case "calc_mass": CalcMass cm = new CalcMass(); cm.set(Double.parseDouble(inputarray[1]), Double.parseDouble(inputarray[2])); cm.printMass(); break; case "calc_brake": CalcBrake cb = new CalcBrake(); cb.set(Double.parseDouble(inputarray[1]), Double.parseDouble(inputarray[2])); cb.printBrake(); break; case "covert-mk": IO.println("> " + Convert.mToKm(Double.valueOf(inputarray[1]))); break; case "convert-km": IO.println("> " + Convert.kmToM(Double.valueOf(inputarray[1]))); break; default: IO.println("> Invalid input"); String[] cmd = new String[1]; cmd[0] = "commands"; parse(cmd); waitforin(); break; } waitforin(); }
8
public static void populateTable() { ///////////////////////////////////CHANGE MUSIC FOLDER PATH HERE/////////////////////////////////////////////////// //String MusicFolder = "C:\\Users\\TomDoug\\Music"; String MusicFolder = "C:\\Users\\Matt\\Music\\Music"; int IDCount = 0; File folder = new File(MusicFolder); File[] listOfArtists = folder.listFiles(); for (int i = 0; i < listOfArtists.length; i++) { String ArtistFolder = MusicFolder + '\\' + listOfArtists[i].getName(); System.out.println(ArtistFolder); File ArtFol = new File(ArtistFolder); File[] listOfAlbs = ArtFol.listFiles(); if (listOfAlbs != null) { for (int j = 0; j < listOfAlbs.length; j++) { String AlbumFolder = ArtistFolder + '\\' + listOfAlbs[j].getName(); File AlbFol = new File(AlbumFolder); File[] listOfSongs = AlbFol.listFiles(); if (listOfSongs != null) { for (int k = 0; k < listOfSongs.length; k++) { String artist = listOfArtists[i].getName(); String album = listOfAlbs[j].getName(); String song = listOfSongs[k].getName(); String path = AlbumFolder + '\\' + listOfSongs[k].getName(); if (song.contains(".mp3") || song.contains(".m4a")) { try { PreparedStatement PS; PS = c.prepareStatement("INSERT INTO MUSIC (ID,ARTIST,ALBUM,SONG,PATH) VALUES (?,?,?,?,?)"); PS.setInt(1, IDCount); PS.setString(2, artist); PS.setString(3, album); PS.setString(4, song); PS.setString(5, path); PS.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } IDCount++; } } } } } } try { c.close(); System.out.println("Database Connection Closed"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
public edit() { this.requireLogin = true; this.info = "edit an appointment"; this.addParamConstraint("id", ParamCons.INTEGER); this.addParamConstraint("venueId", ParamCons.INTEGER, true); this.addParamConstraint("startTime", ParamCons.INTEGER, true); this.addParamConstraint("endTime", ParamCons.INTEGER, true); this.addParamConstraint("name", true); this.addParamConstraint("info", true); this.addParamConstraint("frequency", ParamCons.INTEGER, true); this.addParamConstraint("lastDay", ParamCons.INTEGER, true); this.addParamConstraint("reminderAhead", ParamCons.INTEGER, true); this.addParamConstraint("aWaitingId"); this.addRtnCode(405, "appointment not found"); this.addRtnCode(406, "permission denied"); this.addRtnCode(407, "venue not found"); this.addRtnCode(408, "illegal time"); this.addRtnCode(409, "illegal frequency"); }
0
public RemoteTestRunnerGui() { super(); Utils.checkJMeterVersion(); try { testPanel = TestPanel.getTestPanel(); } catch (Exception e) { BmLog.error("Failed to construct RemoteTestRunnerGui instance:" + e); } init(); getFilePanel().setVisible(false); }
1
public void calculateDimensions() { // Reset all the outside points to 0 leftmostPoint = rightmostPoint = 0; lowestPoint = highestPoint = 0; farthestPoint = nearestPoint = 0; // For each triangle, for (int triangle = 0; triangle < triangles.length; triangle++) { // Get the triangle Triangle checkTriangle = (Triangle) triangles[triangle]; // For each vertex in that triangle for (int vertex = 1; vertex <= 3; vertex++) { Vertex checkVertex = checkTriangle.getPoint(vertex); if (checkVertex.pos.x < leftmostPoint) { leftmostPoint = checkVertex.pos.x; } else if (checkVertex.pos.x > rightmostPoint) { rightmostPoint = checkVertex.pos.x; } if (checkVertex.pos.y < lowestPoint) { lowestPoint = checkVertex.pos.y; } else if (checkVertex.pos.y > highestPoint) { highestPoint = checkVertex.pos.y; } if (checkVertex.pos.z < nearestPoint) { nearestPoint = checkVertex.pos.z; } else if (checkVertex.pos.z > farthestPoint) { farthestPoint = checkVertex.pos.z; } } } }
8
private void exportFileborr() { JFileChooser fileChooser = new JFileChooser("."); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("打开文件夹"); int ret = fileChooser.showOpenDialog(null); if (ret == JFileChooser.APPROVE_OPTION) { final String filePath = fileChooser.getSelectedFile().getAbsolutePath(); // 文件夹路径 System.out.println("报表生成路径:" + fileChooser.getSelectedFile().getAbsolutePath()); Thread t = new Thread() { public void run() { boolean flag = true; try { ReportServiceBorr app = new ReportServiceBorr(); app.readExcel(jfPath); app.produceExcel(templetPath, filePath);// 生成Excel,必须为.xls格式的Excel System.out.println(""); System.out.println("完成"); } catch (Exception e2) { flag = false; e2.printStackTrace(); } new Dialog(flag, filePath); } }; t.start(); } }
2
public int[] getBorderStyles() { int[] styles = new int[5]; if( borderElements.get( "top" ) != null ) { styles[0] = borderElements.get( "top" ).getBorderStyle(); } if( borderElements.get( "left" ) != null ) { styles[1] = borderElements.get( "left" ).getBorderStyle(); } if( borderElements.get( "bottom" ) != null ) { styles[2] = borderElements.get( "bottom" ).getBorderStyle(); } if( borderElements.get( "right" ) != null ) { styles[3] = borderElements.get( "right" ).getBorderStyle(); } if( borderElements.get( "diagonal" ) != null ) { styles[4] = borderElements.get( "diagonal" ).getBorderStyle(); } return styles; }
5
@Override public int hashCode() { int result = 0; for(LinkedList<E> bucket : buckets) { if(bucket != null) { for(E e : bucket) { if(e != null) { result += e.hashCode(); } } } } return result; }
4
public static double doSpecialItemMod(Pokemon attacker, Move move, double damage) { if (attacker.hasItem(Item.CHOICE_SPECS)) { damage *= 1.5; } else if (attacker.hasItem(Item.LIGHT_BALL) && attacker.isSpecies(Species.PIKACHU)) { damage *= 2.0; damage = (int) damage; } else if (attacker.hasItem(Item.SOUL_DEW) && (attacker.isSpecies(Species.LATIAS) || attacker.isSpecies(Species.LATIOS))) { damage *= 1.5; } else if (attacker.hasItem(Item.DEEPSEATOOTH) && (attacker.isSpecies(Species.CLAMPERL))) { damage *= 2.0; } return damage; }
8
public ValueFormatType getPINEncoding() { return pinEncoding; }
0
void createExampleWidgets () { /* Compute the widget style */ int style = getDefaultStyle(); if (topButton.getSelection ()) style |= SWT.TOP; if (bottomButton.getSelection ()) style |= SWT.BOTTOM; if (borderButton.getSelection ()) style |= SWT.BORDER; if (flatButton.getSelection ()) style |= SWT.FLAT; if (closeButton.getSelection ()) style |= SWT.CLOSE; /* Create the example widgets */ tabFolder1 = new CTabFolder (tabFolderGroup, style); for (int i = 0; i < CTabItems1.length; i++) { CTabItem item = new CTabItem(tabFolder1, SWT.NONE); item.setText(CTabItems1[i]); Text text = new Text(tabFolder1, SWT.READ_ONLY); text.setText(ControlExample.getResourceString("CTabItem_content") + ": " + i); item.setControl(text); } tabFolder1.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { lastSelectedTab = tabFolder1.getSelectionIndex(); } }); tabFolder1.setSelection(lastSelectedTab); }
6
public static Map<String, Integer> countWords(ArrayList<String> list) { HashMap<String, Integer> result = new HashMap<String, Integer>(); for (String word : list) { if (result.containsKey(word)) { result.put(word, result.get(word) + 1); } else { result.put (word, 1); } } return result; }
2
@Override public Musteri getMusteri(HashMap<String, String> values) { try { String ad = values.get("ad"); String soyad = values.get("soyad"); String telefon = values.get("telefon"); String resimURL = values.get("resimURL"); String kullaniciAdi = values.get("kullaniciAdi"); String sifre1 = values.get("sifre1"); String sifre2 = values.get("sifre2"); int kullanilanSure = Integer.parseInt(values.get("kullanilanSure")); int kalanSure = Integer.parseInt(values.get("kalanSure")); int yil = Integer.parseInt(values.get("bitisTarihYil")) - 1900; int ay = Integer.parseInt(values.get("bitisTarihAy")); int gun = Integer.parseInt(values.get("bitisTarihGun")); double borc = Double.parseDouble(values.get("borc")); int indirim = Integer.parseInt(values.get("indirim")); String ucretSecenek = values.get("ucretSecenek"); String odemeSecenek = values.get("odemeSecenek"); if(kullaniciAdi.equals("")) JOptionPane.showMessageDialog(null, "Kullanıcı adı boş olamaz!", "Hata", JOptionPane.ERROR_MESSAGE); else if(sifre1.length() < 4) JOptionPane.showMessageDialog(null, "Şifre en az 4 haneli olmalıdır", "Hata", JOptionPane.ERROR_MESSAGE); else if(!sifre1.equals(sifre2)) JOptionPane.showMessageDialog(null, "Şifreler uyuşmuyor!", "Hata", JOptionPane.ERROR_MESSAGE); else if(kalanSure < 0 ) JOptionPane.showMessageDialog(null, "Kalan süre negatif olamaz!", "Hata", JOptionPane.ERROR_MESSAGE); else return new Musteri(kalanSure, kullanilanSure, borc, indirim, ucretSecenek, odemeSecenek, resimURL, new Date(yil, ay, gun), -1, ad, soyad, telefon, kullaniciAdi, sifre1,MUSTERI); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Geçersiz alan. \n" + "(Kullanılan Sure, Kalan Sure, Borc " + "veya indirim bilgileri karakter içeremez)", "Hata", JOptionPane.ERROR_MESSAGE); } return null; }
5