method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
8cd3bca9-b499-45c4-bf88-dfed2e42d004
4
public void animate() throws InterruptedException { Thread.sleep(1000); for(char c:"ANGRY NERDS STUDIO PRESENTS".toCharArray()) { stringShownANSP.append(c); image.repaint(); int sleepVal = 250; sleepVal -= stringShownANSP.length() * 6; Thread.sleep(sleepVal); } Thread.sleep(1000); int i = 1; for(; xCoordOfANSP > -226; xCoordOfANSP -= i++) { image.repaint(); Thread.sleep(150 - (i + 5)); } image.repaint(); Thread.sleep(1000); for(char c:"YAMG".toCharArray()) { stringShownYAMG.append(c); image.repaint(); Thread.sleep(500); } for(String str:new String[] {"Yet ", "Another ", "Mining ", "Game"}) { stringShownYAMG2.append(str); image.repaint(); Thread.sleep(500); } Thread.sleep(500); status = 2; image.repaint(); }
12fba655-fc33-45d8-bb2e-0e357ecc457f
7
public void build(Polygon[] polygons) { if (polygons.length == 0) return; if (plane == null) plane = polygons[0].getPlane().clone(); ArrayList<Polygon> front = new ArrayList<Polygon>(); ArrayList<Polygon> back = new ArrayList<Polygon>(); for (int i = 0; i < polygons.length; i++) plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back); if (!front.isEmpty()) { if (this.front == null) this.front = new Node(null); this.front.build(front.toArray(new Polygon[0])); } if (!back.isEmpty()) { if (this.back == null) this.back = new Node(null); this.back.build(back.toArray(new Polygon[0])); } }
73c875c5-3853-4e7e-8d69-ee0e63eb3bcb
1
private static final void exchange(Object a[], int i, int j) { if (i == j) return; Object tmp = a[i]; a[i] = a[j]; a[j] = tmp; }
5ec6ab92-bfce-4d58-ad77-c3798a47ce81
3
public int winnerIs() { for (int i = 0; i < cl.length; i++) { if (getScore(cl[i])==4) { return PLAYER_ONE; } else if(getScore(cl[i])==-4) return PLAYER_TWO; } return 0; }
9db77354-9775-47b3-a446-0f6d7f6012ff
1
public List<Product> getAll() { List<Product> products = null; try { beginTransaction(); products = session.createCriteria(Product.class).list(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { closeSesion(); } return products; }
90279bca-d70a-4a1a-a0f8-7f4b0c11af44
6
private boolean checkUpdate(Integer[] current, Integer[] online) { if (current.length > online.length) { Integer[] newOnline = new Integer[current.length]; System.arraycopy(online, 0, newOnline, 0, online.length); for (int i = online.length; i < newOnline.length; i++) { newOnline[i] = 0; } online = newOnline; } else if (online.length > current.length) { Integer[] newCurrent = new Integer[online.length]; System.arraycopy(current, 0, newCurrent, 0, current.length); for (int i = current.length; i < newCurrent.length; i++) { newCurrent[i] = 0; } current = newCurrent; } for (int i = 0; i < current.length; i++) { if (online[i] > current[i]) { return true; } } return false; }
3e4360af-4666-41a3-aed9-2d09c73771ab
3
public JSONObject toJSONObject() throws ParseException { JSONObject obj = new JSONObject(); obj.put(KEY_TYPE, bonusType.toString()); obj.put(KEY_PROMPT, prompt); obj.put(KEY_ANSWER, answer); JSONArray sChoice = new JSONArray(); if(choices!=null){ for (String c : choices) { if (c != null) sChoice.add(c); } } obj.put(KEY_CHOICES, sChoice); obj.put(KEY_WEEK, week); obj.put(KEY_NUMBER, number); return obj; }
cc4c1a4e-53bc-430a-af7f-911c4086c4ad
6
private static Boolean checkIfTrue(String[] complete) { int max=0; String temp; int temp1; int[] a=new int[complete.length]; for(int i=0;i<complete.length;i++){ //Establish our Max for the Column for(int j=0;j<complete[i].length();j++){ temp=complete[i].charAt(j)+""; temp1=Integer.parseInt(temp); if(temp1>max){ max=temp1; } } //Compare our max to each character for(int j=0;j<complete[i].length();j++){ temp=complete[i].charAt(j)+""; temp1=Integer.parseInt(temp); if(temp1!=0){ if(temp1<max){ return false; } } } max=0; } return true; }
98721567-4083-4c21-a3ea-c08330a9f0d3
0
public void itemStateChanged(ItemEvent aa) { setChangeDate(); }
02799b2b-1a6b-4c40-ac7a-3c50f56782e4
4
public Thread acquirePackets(final List<Packet> buffer, final int count) { // ArrayList of packets called List final PacketReceiver receiver = new PacketReceiver() { // Declaration of // a new // packetReciever // called // receiver @Override public void receivePacket(Packet packet) { // Method to process the // packet synchronized (buffer) { buffer.add(packet); // Adds the packet to the ArrayList } if (count > -1) { System.out.println("received packet.."); // Prints a line to // confirm // packet was // received } if (done || packetsRecieved == count) captor.breakLoop(); packetsRecieved++; } }; // End of InnerClass // captor.loopPacket(count, receiver); Runnable runnable = new Runnable() { @Override public void run() { captor.loopPacket(count, receiver); // Loop for packets until // closed } }; Thread snifferThread = new Thread(runnable); snifferThread.setName("Sniffer"); snifferThread.start(); try { snifferThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return snifferThread; }
39cd57bd-032e-48b0-922d-7bf04d45d4de
5
public void appLoop(double mult) { //Loads a flat surface as the base terrain baseScene = new Scene(objLib.FlatSurf()); //Increases the terrains size by a multiple of 5 //Initializes an array of objects equal to the size the scene allows actors = new int[baseScene.objindex]; //Adds a prebuilt box object from the object library actors[0] = baseScene.addobj(objLib.Box(), new Vector(0.0, 0.0, 0.0)); actors[0] = baseScene.addobj(objLib.Box(), new Vector(0.0, 0.0, 0.0)); //Camera Creation time, creates a camera at the point 3, 3, 3 obvs = new Camera(new Vector(1.0, 1.0, -5.0), new Vector(0.0, 0.0, 0.0)); //err check baseScene.objlist[0].SizeInc(2.0); //err check boolean done = false; double bouncex = 0.004; double bouncey = 0.004; while(done==false) { if(obvs.pos.xV>=6.0) { bouncex = -0.0001; } else if(obvs.pos.xV<=-6.0) { bouncex = 0.0001; } if(obvs.pos.yV>=4.0) { bouncey = -0.0003; } else if(obvs.pos.yV<=-2.5) { bouncey = 0.0002; } obvs.pos.xV += bouncex; obvs.pos.yV += bouncey; this.drawScene(obvs, actors, mult); repaint(); } }
0ea01851-f1f1-4b4e-b3d7-0e84fe04a54c
8
public static void main(String[] args) { try { ui = new SwingWolves(); } catch (HeadlessException e){ ui = new TextWolves(); ui.displayString("Headless environment detected.\nSwitched to text only mode."); } NumPlayers = ui.getNumPlayers(); NumWolves = ui.getNumWolves(); DebugMode = ui.getDebugMode(); History = new ChoiceHistory(); SetNames(); ui.displayPlayerIDs(getPlayerIDs()); RunningGame = new Game(NumPlayers, NumWolves); // Game Object created, initialised, and probabilities updated. boolean GameOver = false; while(!GameOver){ // Each turn, one must: // Take input from each player RunningGame.UpdateProbabilities(); int[] WolfTargets = EachPlayerIO(); RunningGame.UpdateProbabilities(); RunningGame.CollapseAllDead(); WinCodes WinCode = RunningGame.CheckWin(); GameOver = (WinCode != WinCodes.GameNotOver); if(GameOver) break; if(DebugMode) ui.displayAllStates(RunningGame.getAllStates()); // Update gamestates based on attacks RunningGame.AttackAllStates(WolfTargets); // Wake players RunningGame.UpdateProbabilities(); RunningGame.CollapseAllDead(); DayTimeDisplay(); WinCode = RunningGame.CheckWin(); GameOver = (WinCode != WinCodes.GameNotOver); if(GameOver) break; if(DebugMode) ui.displayAllStates(RunningGame.getAllStates()); // Take Lynching target int LynchTarget = InputLynchTarget(); // Update gamestates based on lynch RunningGame.LynchAllStates(LynchTarget); RunningGame.UpdateProbabilities(); // run CollapseAllDead() RunningGame.CollapseAllDead(); DayTimeDisplay(); WinCode = RunningGame.CheckWin(); GameOver = (WinCode != WinCodes.GameNotOver); if(DebugMode) ui.displayAllStates(RunningGame.getAllStates()); } // Game is now over ui.displayEndGame(RunningGame.getRoundNum(), RunningGame.CheckWin(), RunningGame.getKnownRoles()); DayTimeDisplay(); ui.displayAllStates(RunningGame.getAllStates()); if(RunningGame.getNumStates() != 1) { // If there are multiple states, one is randomly chosen. ui.displayString("At this point, the choices made\n" + "still leave more than one final outcome.\n" + "Therefore, one outcome is now being\n" + "randomly selected." ); RunningGame.SelectEndState(); RunningGame.UpdateProbabilities(); ui.displayEndGame(RunningGame.getRoundNum(), RunningGame.CheckWin(), RunningGame.getKnownRoles()); } printHistory(); }
798dd861-efe1-4f33-a382-b376013c542d
1
private ServerSocketChannel createServerSocket(int port) throws IOException { try { ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking(false); ssChannel.socket().bind(new InetSocketAddress(port)); return ssChannel; } catch (IOException e) { logger.info("Port " + port + " is busy"); throw e; } }
783af427-0537-4d87-b257-b2acadd3a483
0
protected Icon getIcon() { java.net.URL url = getClass().getResource("/ICON/collapse.gif"); return new ImageIcon(url); }
4086dd12-1012-488b-a718-66a7ce20827f
0
public void addVillage(Village v) { this.village = v; }
f105db06-6d71-45f2-9d21-3125dc5b473e
2
public void loadGame() { System.out.println("What is the filename? For maders.rsbxl2, type maders."); try { mainfileName = cache.readLine(); } catch (IOException ex) { System.out.println(ex.getMessage()); System.exit(-1); } ReadFile read = new ReadFile("./Saves/" + mainfileName + ".rsbxl2"); String[] lines = new String[4]; try { lines = read.OpenFile(); } catch (IOException ex) { System.out.println(ex.getMessage()); System.exit(-1); } name = lines[0]; age = Integer.parseInt(lines[1]); testname = lines[2]; savefileName = lines[3]; System.out.println("Load Successful."); this.startGame(); }
cbbf8204-c680-453b-a784-f2c06e230c28
3
public void testReadWithVorbisAudio() throws IOException { OggFile ogg = new OggFile(getTheoraVorbisFile()); tf = new TheoraFile(ogg); // Check the Info assertEquals("3.2.1", tf.getInfo().getVersion()); assertEquals(3, tf.getInfo().getMajorVersion()); assertEquals(2, tf.getInfo().getMinorVersion()); assertEquals(1, tf.getInfo().getRevisionVersion()); assertEquals(40, tf.getInfo().getFrameWidthMB()); assertEquals(30, tf.getInfo().getFrameHeightMB()); assertEquals(640, tf.getInfo().getFrameWidth()); assertEquals(480, tf.getInfo().getFrameHeight()); assertEquals(640, tf.getInfo().getPictureRegionWidth()); assertEquals(480, tf.getInfo().getPictureRegionHeight()); assertEquals(0, tf.getInfo().getPictureRegionXOffset()); assertEquals(0, tf.getInfo().getPictureRegionYOffset()); assertEquals(1, tf.getInfo().getFrameRateNumerator()); assertEquals(1, tf.getInfo().getFrameRateDenominator()); assertEquals(0, tf.getInfo().getPixelAspectNumerator()); assertEquals(0, tf.getInfo().getPixelAspectDenomerator()); assertEquals(0, tf.getInfo().getColourSpace()); assertEquals(0, tf.getInfo().getNominalBitrate()); assertEquals(38, tf.getInfo().getQualityHint()); assertEquals(6, tf.getInfo().getKeyFrameNumberGranuleShift()); assertEquals(0, tf.getInfo().getPixelFormat()); // Check the Comments assertEquals( "Xiph.Org libtheora 1.1 20090822 (Thusnelda)", tf.getComments().getVendor() ); assertEquals( "ffmpeg2theora-0.27", tf.getComments().getComments("ENCODER").get(0) ); assertEquals(2, tf.getComments().getAllComments().size()); // TODO - proper setup packet checking assertEquals(255*12+0x90, tf.getSetup().getData().length); // Doesn't have a skeleton stream assertEquals(null, tf.getSkeleton()); // Has a single, vorbis soundtrack assertNotNull(tf.getSoundtracks()); assertNotNull(tf.getSoundtrackStreams()); assertEquals(1, tf.getSoundtracks().size()); assertEquals(1, tf.getSoundtrackStreams().size()); assertEquals(OggStreamIdentifier.OGG_VORBIS, tf.getSoundtracks().iterator().next().getType()); // Has a handful of video and audio frames interleaved OggStreamAudioVisualData avd = null; int numTheora = 0; int numVorbis = 0; while ((avd = tf.getNextAudioVisualPacket()) != null) { if (avd instanceof TheoraVideoData) numTheora++; if (avd instanceof VorbisAudioData) numVorbis++; } assertTrue("Not enough video, found " + numTheora, numTheora > 0); assertTrue("Not enough audio, found " + numVorbis, numVorbis > 5); avd = tf.getNextAudioVisualPacket(); assertNull( avd ); }
5f0ac3c2-85e6-478d-b932-925f01d76d87
2
* @return this */ public Request clear(String name) { Iterator<NameValuePair> it = mParams.iterator(); while (it.hasNext()) { if (it.next().getName().equals(name)) { it.remove(); } } return this; }
699c0521-a999-4d7f-b7a5-1bbadb5b03e8
0
@Override public ArrayList<Excel> getColoredExes() { return coloredEx; }
2072d29b-ee44-41ac-bba2-11846b665215
5
public static void drawVerticalLine(int x, int y, int height, int colour) { if (x < topX || x >= bottomX) return; if (y < topY) { height -= topY - y; y = topY; } if (y + height > bottomY) height = bottomY - y; int pointer = x + y * DrawingArea.width; for (int row = 0; row < height; row++) pixels[pointer + row * DrawingArea.width] = colour; }
55ff7dd0-9053-4de6-bfce-1b9aaa485563
3
@Override public void displayTable(String tableName, ResultSet rs) throws IOException, SQLException { println("create table " + tableName + " ("); while (rs.next()) { print("\t" + rs.getString(4) + ' ' + rs.getString(6)); int nullable = rs.getInt(11); if (nullable == ResultSetMetaData.columnNoNulls) { print(" not null"); } String defaultValue = rs.getString(13); if (defaultValue != null) { print(" default('" + defaultValue + "')"); } println(","); } println(");"); }
fdfea43f-0fb7-4c9d-9f07-93a30cf49b42
8
public int strStr(String haystack, String needle) { if (haystack == null || needle == null) return -1; if (needle.length() > haystack.length()) return -1; int base = 29; long patternHash = 0; long tempBase = 1; long hayHash = 0; for (int i = needle.length() - 1; i >= 0; i--) { patternHash += (int) needle.charAt(i) * tempBase; tempBase *= base; } tempBase = 1; for (int i = needle.length() - 1; i >= 0; i--) { hayHash += (int) haystack.charAt(i) * tempBase; tempBase *= base; } tempBase /= base; if (hayHash == patternHash) { return 0; } for (int i = needle.length(); i < haystack.length(); i++) { hayHash = (hayHash - (int) haystack.charAt(i - needle.length()) * tempBase) * base + (int) haystack.charAt(i); if (hayHash == patternHash) return i - needle.length() + 1; } return -1; }
ffdf5082-e57c-481c-9a24-8ee04372bd72
1
public void send(Message message) throws IllegalStateException { synchronized (this.exchangeLock) { if (this.isBound()) { this.exchange.send(message); } } }
08218a26-c716-4c24-983f-8cfa2f910023
9
public static void main(String[] args) { System.out.println("Digite 2 caracteres para usar de chave."); String readConsole = Main.readConsole(); KeySchedule key = new KeySchedule(readConsole); MiniAes miniAes = new MiniAes(); miniAes.setKey(key); key.print(); while (true) { try { System.out.println("\nDigite 1 e enter para cifrar um texto.\nDigite 2 e enter para decifrar um texto.\n" + "Digite 3 e enter para trocar de chave.\nDigite qualquer coisa e enter para sair."); readConsole = Main.readConsole(); if (readConsole.equals("1")) { // cifra a mensagem digitada no console pegando de 16 em 16 bits e cifrando, modo ECB. System.out.println("\nDigite a mensagem a cifrar."); byte[] bytes = Main.readConsole().getBytes("UTF-8"); int blocos = bytes.length / 2; if (bytes.length % 2 != 0) { blocos++; } BitSet bits = BitSet.valueOf(bytes); byte[] result = new byte[blocos * 2]; int count = 0; int countR = 0; for (int i = 0; i < blocos; i++) { miniAes.setValue(bits.get(count, count + 16)); count += 16; miniAes.encrypt(); byte[] bytes2 = miniAes.getBytes(); result[countR++] = bytes2[0]; result[countR++] = bytes2[1]; } System.out.println("Mensagem cifrada."); System.out.println(new BigInteger(result).toString(36)); } else if (readConsole.equals("2")) { // decifra a mensagem digitada no console pegando de 16 em 16 bits e decifrando, modo ECB. System.out.println("\nDigite a mensagem a decifrar."); byte[] bytes = new BigInteger(Main.readConsole(), 36).toByteArray(); int blocos = bytes.length / 2; if (bytes.length % 2 != 0) { blocos++; } BitSet bits = BitSet.valueOf(bytes); byte[] result = new byte[blocos * 2]; int count = 0; int countR = 0; for (int i = 0; i < blocos; i++) { miniAes.setValue(bits.get(count, count + 16)); count += 16; miniAes.decrypt(); byte[] bytes2 = miniAes.getBytes(); result[countR++] = bytes2[0]; result[countR++] = bytes2[1]; } System.out.println("Mensagem decifrada."); System.out.println(new String(result, "UTF-8")); } else if (readConsole.equals("3")) { System.out.println("\nDigite a nova chave."); readConsole = Main.readConsole(); key = new KeySchedule(readConsole); miniAes.setKey(key); key.print(); } else { return; } } catch (Exception e) { e.printStackTrace(); } } }
3fc94454-3c37-425a-9c97-afe34f320a9b
5
public void GameStart() { boolean passFlg = false; int gameCnt = 0; Bord bord = new Bord(); bord.BordInit(); System.out.println("ゲームスタート"); System.out.println(bord.toString()); // おける場所がある間はループ while (bord.GetCount(Stone.NONE) > 0) { // 現在の手版を取得 AiBase turnPlayer = PlayerList.get(gameCnt % 2); System.out.println(turnPlayer.getMyColor().getName() + "の番"); //プレイヤーから石を置く位置を取得する。 AIが盤をいじらないようクローンを渡す Pos setHand = new Pos(); setHand = turnPlayer.WhereSet(bord.clone(),null); //設置場所がNULLの場合パスとする if (setHand == null) { System.out.println(turnPlayer.getMyColor().getName() + "はパスします"); //両プレイヤーがパスをした場合、ゲーム終了とする if (passFlg) { System.out.println("どちらもパスしたため、ゲームを終了します。"); break; } passFlg = true; } else { // 石を設置する bord.DoSet(setHand, turnPlayer.getMyColor(), true); passFlg = false; } gameCnt++; //版情報を描画 System.out.println(bord.toString()); } ////// //ゲーム終了-結果判断 ////// int player1Cnt = bord.GetCount(PlayerList.get(0).getMyColor()); int player2Cnt = bord.GetCount(PlayerList.get(1).getMyColor()); System.out.println(player1Cnt + ":" + player2Cnt); if (player1Cnt > player2Cnt) { System.out.println(PlayerList.get(0).getMyColor().getName() + "の勝利"); } else if (player1Cnt == player2Cnt) { System.out.println("引き分け"); } else { System.out.println(PlayerList.get(1).getMyColor().getName() + "の勝利"); } }
0ac0cf65-c40a-42de-925d-ebda79f0bd28
4
@Override public boolean accept(File file) { if (file.isDirectory()) { return true; } int count = extensions.length; String path = file.getAbsolutePath(); for (int i = 0; i < count; i++) { String ext = extensions[i]; if (path.endsWith(ext) && (path.charAt(path.length() - ext.length()) == '.')) { return true; } } return false; }
bc0f660b-426a-45be-961d-8e3a794aba87
1
public final void removeJump() { if (jump != null) { jump.prev = null; jump = null; } }
24f1bcf3-c5f3-4466-9716-87ccf7224376
8
private void myEvent(){ saveItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { if(file == null){ saveDia.setVisible(true); String dirPath = saveDia.getDirectory(); String fileName = saveDia.getFile(); if(dirPath==null || fileName==null) return; file = new File(dirPath, fileName); } try{ BufferedWriter bufw = new BufferedWriter(new FileWriter(file)); String text = ta.getText(); bufw.write(text); bufw.close(); }catch(IOException e1){ e1.printStackTrace(); } } }); openItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ openDia.setVisible(true); String dirPath = openDia.getDirectory(); String fileName = openDia.getFile(); System.out.println(dirPath+"..."+fileName); if(dirPath==null || fileName ==null) return; ta.setText(""); file = new File(dirPath, fileName); try{ BufferedReader bufr = new BufferedReader(new FileReader(file)); String line = null; while((line = bufr.readLine()) != null){ ta.append(line+"\r\n"); } bufr.close(); }catch(IOException e1){ e1.printStackTrace(); } } }); closeItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); }
2e4aac63-0085-48c4-8180-cee6a4181159
8
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (jTextField1.getText() != "") { int a = 1; String gend = "Male"; try { ResultSet rs = DB.myConnection().createStatement().executeQuery("select * from librian where LibrianID='" + jTextField1.getText() + "'"); while (rs.next()) { a = 2; jTextField2.setText(rs.getString("LibrianName")); jTextField3.setText(rs.getString("LibrianMiddleName")); jTextField6.setText(rs.getString("LibrianSurname")); jTextField5.setText(rs.getString("HomeAddress")); jTextField4.setText(rs.getString("TemperaryAddress")); jTextField7.setText(rs.getString("MobileNumper")); jTextField9.setText(rs.getString("HomeTelephone")); jTextField8.setText(rs.getString("Age")); gend = rs.getString("Gender"); jLabel16.setText(rs.getString("RegisteringLibrian")); jLabel14.setText(rs.getString("RegisteredDate")); } if (a == 1) { jRadioButton1.setSelected(false); radbtnFemale.setSelected(false); } else if (a == 2 && gend == "Male") { jRadioButton1.setSelected(true); radbtnFemale.setSelected(false); a = 1; } else if (a == 2 && gend == "Female") { System.out.println("Gend = " + gend + " a= " + a); radbtnFemale.setSelected(true); jRadioButton1.setSelected(false); } } catch (Exception e) { System.out.print("exception Librian details 441"); } } else { JOptionPane.showMessageDialog(this, "please enter Librian id"); } }//GEN-LAST:event_jButton1ActionPerformed
70d1e491-3297-4f9a-92bc-465f82091d30
5
public static void remove(CommandSender sender, String[] args){ //team + player + add + player if(args.length < 2+2){ sender.sendMessage(ErrorMessage.MissingParameters); } else{ String playerName = args[3]; String playerTeam = TeamsManager.getInstance().retrievePlayerTeam(playerName); //If player has a team if(!playerTeam.equals("")){ //If user allowed (permission or admin of player team) if(sender.hasPermission("battlegrounds.team.player.remove") || TeamsManager.getInstance().isAdminOfPlayer(sender.getName(), args[3])){ //If player can be added if(TeamsManager.getInstance().removePlayerFromTeam(playerName)){ sender.sendMessage(ChatColor.GREEN + String.format("[%s] removed from [%s].", playerName, playerTeam)); Bukkit.getServer().getPlayer(playerName).sendMessage(ChatColor.GOLD + String.format("You leave the %s team.", playerTeam)); } else{ sender.sendMessage(ChatColor.RED + String.format("Can not remove [%s] from [%s].", playerName, playerTeam)); } } //Else not allowed else{ sender.sendMessage(ErrorMessage.NotAllowed); } } else{ sender.sendMessage(ChatColor.RED + String.format("%s has no team.", playerName)); } } }
2d40dfe9-c1bb-44f3-9f3b-6897f76677b0
2
public static boolean isBold(JTextPane pane) { AttributeSet attributes = pane.getInputAttributes(); if (attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE)) { return true; } if (attributes.getAttribute(CSS.Attribute.FONT_WEIGHT) != null) { Object fontWeight = attributes .getAttribute(CSS.Attribute.FONT_WEIGHT); return fontWeight.toString().equals("bold"); } return false; }
c6e5f1a8-6fd7-4569-8a11-b23285cb441f
5
public FolderHandler(File album) { Logger.getLogger(FolderHandler.class.getName()).entering(FolderHandler.class.getName(), "FolderHandler", album); File[] allfiles = album.listFiles(); try { allfiles = album.listFiles(); } catch(SecurityException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "rights", album); } if (allfiles == null) { return; } Arrays.sort(allfiles); for (File allfile : allfiles) { if (!allfile.isHidden() && isAnImage(allfile.getName())) { imagefiles.add(allfile); } } Logger.getLogger(FolderHandler.class.getName()).exiting(FolderHandler.class.getName(), "FolderHandler"); }
a09b19ba-80d5-44f0-81be-25f002fe769b
4
public void saveSupModel(String filename){ double[] weights = m_libModel.getWeights(); int class0 = m_libModel.getLabels()[0]; double sign = class0 > 0 ? 1 : -1; try{ PrintWriter writer = new PrintWriter(new File(filename)); if(m_bias) writer.write(sign*weights[m_featureSize]+"\n"); else writer.write(0); for(int i=0; i<m_featureSize; i++) writer.write(weights[i]+"\n"); writer.close(); } catch(IOException e){ e.printStackTrace(); } }
7a82d15c-c21c-4683-af2c-a147076673c7
2
public String[] getPhonenumberByUID(Statement statement,String UID)//根据用户ID获取手机号 { int i = 0; String[] result = new String[20]; sql = "select phonenumber from CarNumber where UID = '" + UID +"'"; try { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { result[i] = rs.getString("phonenumber"); i++; } } catch (SQLException e) { System.out.println("Error! (from src/Fetch/CarNumber.getPhonenumberByUID())"); // TODO Auto-generated catch block e.printStackTrace(); } return result; }
ca368b97-4cc5-4626-950d-70a12c44f5c3
4
private static String[] format(Deck in){ if(!in.repeated){ return in.cards.toArray(new String[0]); } int size = 0; for(int i = 0; i<in.quantity.size(); i++){ size += in.quantity.get(i); } String[] cards = new String[size]; int position = 0; int count = 0; for(int i = 0; i<size; i++){ cards[i] = in.cards.get(position); count++; if(count==in.quantity.get(position)){ count = 0; position++; } } return cards; }
d5e71d63-3d3c-4a8f-8ef9-c353ea299069
7
protected int[] getOneSeq(int node_index){ double[][] winnerCode=new double[numF1][maxIdEvents]; for(int i=0;i<numF1;i++){ System.arraycopy(weight[node_index][i],0, winnerCode[i], 0, maxIdEvents); } /* for(int i=0;i<weight[node_index].length;i++){ for(int j=0;j<weight[node_index][i].length;j++){ System.out.print(weight[node_index][i][j]+"\t"); } System.out.println(""); } System.out.println("");*/ Vector<Integer> winnerSeq=new Vector<Integer>(0); double maxWeight=0; int maxEvent_1=-1; int maxEvent_2=-1; do{ for(int i=0;i<numF1;i++){ for(int j=0;j<this.maxIdEvents;j++){ if(maxWeight<winnerCode[i][j]){ maxWeight=winnerCode[i][j]; maxEvent_1=i; maxEvent_2=j; } } } if(maxWeight>0){ winnerSeq.add(0,new Integer(maxEvent_1)); winnerCode[maxEvent_1][maxEvent_2]=0; maxWeight=0; maxEvent_1=-1; maxEvent_2=-1; } else{ break; } }while(true); int[] learnSeq=new int[winnerSeq.size()]; for(int i=0;i<learnSeq.length;i++){ learnSeq[i]=winnerSeq.get(i).intValue(); } //emptyAccumulated(); return learnSeq; }
bf36bcce-c05a-479b-abce-3a378dbf9f4f
4
public static void splitPivotFirst(int low, int high) { int i = low + 1; for (int j = low + 1; j <= high; j++) { countFirst++; if (result[j] < result[low]) { exchange(j, i); i++; } } exchange(low, i - 1); if (low < i - 2) splitPivotFirst(low, i - 2); if (i < high) splitPivotFirst(i, high); }
597173af-3a07-431b-b4c6-f429fe85f8af
2
@SuppressWarnings("unchecked") public static Float restoreFloat(String findFromFile) { Float dataSet = null; try { FileInputStream filein = new FileInputStream(findFromFile); ObjectInputStream objin = new ObjectInputStream(filein); try { dataSet = (Float) objin.readObject(); } catch (ClassCastException cce) { cce.printStackTrace(); return null; } objin.close(); } catch (Exception ioe) { //ioe.printStackTrace(); System.out.println("NO resume: saver"); return null; } return dataSet; } // /////////// ////////////////////////////
66c5ad38-0eab-4f70-9005-7905cf99edde
9
private Token<T, ?> skipIgnored(Token<T, ?> next, final TokenListener<T, ?> capturingListener) throws IOException { if (next != null && ignoreWhitespace && capturingListener.isCapturingWhitespace()) { next = next(); } else if (next != null && capturingListener.isCapturingNewline()) { lineNumber++; if (ignoreNewline) { next = next(); } } return next; }
7626b7a7-799b-432d-af59-d58e69f0e674
2
public principal(){ comboBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String idioma_cadena = comboBox1.getSelectedItem().toString(); set.setIdioma(getIdioma(idioma_cadena)); } }); comenzarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if(textField1.getText() == "" || textField2.getText() == "") JOptionPane.showMessageDialog(null,"Nombre de Jugadores Vacios"); else{ set.setNombreJugador1(textField1.getText()); set.setNombreJugador2(textField2.getText()); set.setEstado(true); } System.out.print("algo"); } }); }
02b24c9b-b105-4e56-a0a1-35789298500b
7
private void searchTable() { while (model.getRowCount() != 0) { model.removeRow(0); } if (!tfEmployeeNr.getText().isEmpty()) { Employee employee = RoosterProgramma.getInstance().getEmployee(Integer.parseInt(tfEmployeeNr.getText())); if (employee != null) { insertEmployeeIntoTable(employee); } } else { if (!tfFirstName.getText().isEmpty() || !tfFamilyName.getText().isEmpty()) { for (Employee employee : RoosterProgramma.getInstance().searchEmployee(tfFirstName.getText(), tfFamilyName.getText())) { insertEmployeeIntoTable(employee); } } else { for (Employee employee : RoosterProgramma.getInstance().getEmployees()) { insertEmployeeIntoTable(employee); } } } }
a466fbc2-3413-4bf2-ae95-854ffdbc0a2f
0
public PrimaryInput(String input) { name = input; inputTable.put(input, new Double(0.0)); }
32b2c0e2-d3d0-4a2a-9d10-54ed26f051d2
9
public void moverse() { Tablero.getTablero().removerNave(this); ArrayList<Parte> partesFinal = new ArrayList<Parte>(); for (Parte parte : partes) { Coordenada posicionInicial = parte.getPosicion(); Coordenada posicionFinal; if (direccionMovimiento == DireccionMovimiento.ESTE) { posicionFinal = this.moverseAlEste(posicionInicial, partesFinal.size()+1); } else if (direccionMovimiento == DireccionMovimiento.OESTE) { posicionFinal = this.moverseAlOeste(posicionInicial); } else if (direccionMovimiento == DireccionMovimiento.SUR) { posicionFinal = this.moverseAlSur(posicionInicial, partesFinal.size()+1); } else if (direccionMovimiento == DireccionMovimiento.NORTE) { posicionFinal = this.moverseAlNorte(posicionInicial); } else if (direccionMovimiento == DireccionMovimiento.NORESTE) { posicionFinal = this.moverseAlNoreste(posicionInicial, partesFinal.size()+1); } else if (direccionMovimiento == DireccionMovimiento.NOROESTE) { posicionFinal = this.moverseAlNoroeste(posicionInicial); } else if (direccionMovimiento == DireccionMovimiento.SUROESTE) { posicionFinal = this.moverseAlSuroeste(posicionInicial, partesFinal.size()+1); } else { posicionFinal = this.moverseAlSureste(posicionInicial, partesFinal.size()+1); } parte.setPosicion(posicionFinal); if(partesFinal.size() == 0) { this.coordenadaInicio = new Coordenada(posicionFinal.getX(), posicionFinal.getY()); } partesFinal.add(parte); } partes = partesFinal; Tablero.getTablero().reubicarNave(this); }
341de1c9-831b-42cc-abd3-ed7905e1c8d2
2
public double getDouble(String key, double def) { if(fconfig.contains(key)) { return fconfig.getDouble(key); } else { fconfig.set(key, def); try { fconfig.save(path); } catch (IOException e) { e.printStackTrace(); } return def; } }
e6c952cb-a2dc-4dc9-a2d6-30a04b87aa1c
4
private void asetaLisavalinnat(ArrayList<Tilausrivi> tilausrivit, String oregStr, String vsipStr, String ltonStr, String gtonStr, int index) { if (oregStr != null) { tilausrivit.get(index).setOreg(true); } else { tilausrivit.get(index).setOreg(false); } if (vsipStr != null) { tilausrivit.get(index).setVsip(true); } else { tilausrivit.get(index).setVsip(false); } if (ltonStr != null) { tilausrivit.get(index).setLton(true); } else { tilausrivit.get(index).setLton(false); } if (gtonStr != null) { tilausrivit.get(index).setGton(true); } else { tilausrivit.get(index).setGton(false); } }
976bdc74-e2c4-4403-a23a-f35ee03ef691
8
public void line(WritableImage source, int x1, int y1, int x2, int y2) { if (source == null) return; PixelWriter pw = source.getPixelWriter(); int argb = 255 << 24 | 0 << 16 | 0 << 8 | 0; int sx = x1 < x2 ? 1 : -1; int sy = y1 < y2 ? 1 : -1; int dx = Math.abs(x2 - x1); int dy = Math.abs(y2 - y1); if (dy < dx) { int dE = 2 * dy; int dNE = 2 * (dy - dx); int d = 2 * dy - dx; while ((x1 - x2) * sx < 0) { drawBrush(x1, y1, SIZE, argb, pw); drawBrush(x2, y2, SIZE, argb, pw); x1 += sx; x2 -= sx; if (d < 0) d += dE; else { d += dNE; y1 += sy; y2 -= sy; } } } else { int dE = 2 * dx; int dNE = 2 * (dx - dy); int d = 2 * dx - dy; while ((y1 - y2) * sy < 0) { drawBrush(x1, y1, SIZE, argb, pw); drawBrush(x2, y2, SIZE, argb, pw); y1 += sy; y2 -= sy; if (d < 0) d += dE; else { d += dNE; x1 += sx; x2 -= sx; } } } drawBrush(x1, y1, SIZE, argb, pw); drawBrush(x2, y2, SIZE, argb, pw); }
3da5a86c-46a5-45b3-ad48-8cfad0e4b781
9
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((sprung) &&(affected!=null) &&(!disabled()) &&(tickDown>=0)) { if(((msg.targetMinor()==CMMsg.TYP_LEAVE) ||(msg.targetMinor()==CMMsg.TYP_FLEE)) &&(msg.amITarget(affected))) { msg.source().tell(L("The exits are blocked! You can't get out!")); return false; } else if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.amITarget(affected))) { msg.source().tell(L("The entry to that room is blocked!")); return false; } } return super.okMessage(myHost,msg); }
887d4dfe-f463-42f3-96f0-92e77070ee77
6
public void updateData() { data = username + (location != null ? " l" + location.toString() : "") + (health > -1 ? " h" + health : "") + (toggleAdmin ? " a" : "") + (toggleFlyMode ? " f" : "") + (toggleGodMode ? " g" : "") + (toggleVisibility ? " v" : ""); }
7b5e2752-d983-427b-bd2c-dfbfcfb8d995
3
public int getWood(int size){ if (resource1==3){ if (size==1){ return sgenrate1; } else if (size==2){ return mgenrate1; } else { return lgenrate1; } } else{ return 0; } }
6918f1e1-2a41-4da4-82c6-e535a426477c
6
double microbial_tournament(int[][] actionGenome, StateObservation stateObs, StateHeuristic heuristic) throws TimeoutException { int a, b, c, W, L; int i; a = (int) ((POPULATION_SIZE - 1) * randomGenerator.nextDouble()); do { b = (int) ((POPULATION_SIZE - 1) * randomGenerator.nextDouble()); } while (a == b); double score_a = simulate(stateObs, heuristic, actionGenome[a]); double score_b = simulate(stateObs, heuristic, actionGenome[b]); if (score_a > score_b) { W = a; L = b; } else { W = b; L = a; } int LEN = actionGenome[0].length; for (i = 0; i < LEN; i++) { if (randomGenerator.nextDouble() < RECPROB) { actionGenome[L][i] = actionGenome[W][i]; } } for (i = 0; i < LEN; i++) { if (randomGenerator.nextDouble() < MUT) actionGenome[L][i] = randomGenerator.nextInt(N_ACTIONS); } return Math.max(score_a, score_b); }
87ad92ee-58da-4872-abb4-0a2d85e8b5f0
6
public void run() { //double fCyclePosition = 0; try { AudioFormat format = new AudioFormat(44100, 16, 2, true, true); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format, BUFFER); if (!AudioSystem.isLineSupported(info)) throw new LineUnavailableException(); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); } catch (LineUnavailableException e) { System.out.println("Line of that type is not available"); e.printStackTrace(); System.exit(-1); } V2Mplayer player = new V2Mplayer(); ByteBuffer cBuf = ByteBuffer.allocate(BUFFER * 2 * 2); float[][] fBuf = new float[BUFFER][2]; int c = 0; while (bExitThread == false) { //double fCycleInc = fFreq / SAMPLING_RATE; //Fraction of cycle between samples cBuf.clear(); //Toss out samples from previous pass /*for (int i = 0; i < SINE_PACKET_SIZE / SAMPLE_SIZE; i++) { cBuf.putShort((short) (Short.MAX_VALUE * Math.sin(2 * Math.PI * fCyclePosition))); fCyclePosition += fCycleInc; if (fCyclePosition > 1) fCyclePosition -= 1; }*/ player.Render(fBuf, BUFFER); /*FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream("testxx.raw", true); dos = new DataOutputStream(fos); } catch (IOException e){ System.out.println("Error opening flie"); }*/ for(int i = 0; i < BUFFER; i++) { short t1 = (short)(Math.round(fBuf[i][0] * (Short.MAX_VALUE / 2))); short t2 = (short)(Math.round(fBuf[i][1] * (Short.MAX_VALUE / 2))); //if(c >7030 && c < 7050) { System.out.printf("%d %f %d\n",i ,fBuf[i][0], t);} //for (int j = 0; i < 128; i++) { /*try { dos.writeShort(t); } catch (IOException e) { e.printStackTrace(); }*/ //} /*if (t > 32767) System.out.println("clip pos"); if (t < -32768) System.out.println("clip neg");*/ cBuf.putShort(t1); cBuf.putShort(t2); //cBuf.putShort((short) (fBuf[i][1] * Short.MAX_VALUE / 2)); //cBuf.putFloat(fBuf[i][0]); //cBuf.putFloat(fBuf[i][1]); //cBuf.put((byte)(fBuf[i][0]*255)); //System.out.printf("%f ", fBuf[i][0]); } //System.out.println(); line.write(cBuf.array(), 0, cBuf.position()); /*try { dos.close(); } catch (IOException e1) { e1.printStackTrace(); }*/ try { while (getLineSampleCount() > BUFFER * 2 * 2) Thread.sleep(5L); // Give UI a chance to run } catch (InterruptedException e) { // We don't care about this } } line.drain(); line.close(); }
f90b83ce-5635-42d8-87ad-e7154d58a282
9
private static Mummy[] mummyFight(Mummy[] mummyType1, Mummy[] mummyType2) {//First type win Mummy[] mm1 = mummyType1; Mummy[] mm2 = mummyType2; if ((mm1.length == 0) || (mm2.length == 0)) { //No conflict for void arrays return mm2; } if (mm1.getClass() != mm2.getClass()) { for (int i = 0; i < mm1.length; i++) { for (int j = 0; j < mm2.length; j++) { if (mm1[i].samePlace(mm2[j])) { //Delete second type mm2 = deleteMummy(mm2, j); } } } } else { for (int i = 0; i < mm1.length; i++) { for (int j = i + 1; j < mm2.length; j++) { if (mm1[i].samePlace(mm2[j])) { //Delete second type mm2 = deleteMummy(mm2, j); } } } } return mm2; }
29fb2fdf-6859-4771-b290-58dbf265a29c
1
public void testWithChronologyRetainFields_invalidInNewChrono() { YearMonthDay base = new YearMonthDay(2005, 1, 31, ISO_UTC); try { base.withChronologyRetainFields(COPTIC_UTC); fail(); } catch (IllegalArgumentException ex) { // expected } }
5dd07203-5c70-4790-b205-5a44c25e969e
2
public Fighter(int courtWidth, int courtHeight) { super(INIT_VEL_X, INIT_VEL_Y, INIT_X, INIT_Y, SIZE, SIZE, courtWidth, courtHeight); // Set img1 to picture of the fighter jet try { img1 = ImageIO.read(new File(img_file1)); } catch (IOException e) { System.out.println("Internal Error:" + e.getMessage()); } // Set img2 to the picture of blood try { img2 = ImageIO.read(new File(img_file2)); } catch (IOException e) { System.out.println("Internal Error:" + e.getMessage()); } }
75e44262-24a1-41d9-ac03-436f5aac07a1
1
public void mergeInfo(Instruction instr, StackLocalInfo info) { if (instr.getTmpInfo() == null) { instr.setTmpInfo(info); info.instr = instr; info.enqueue(); } else ((StackLocalInfo) instr.getTmpInfo()).merge(info); }
684c958d-762d-40bd-acca-fb2a199eefa6
8
void formEdit(ActivityList al, CaseList caselist, ContactList contactlist, boolean createRow) { Vector<String> attorneyNames = new Vector<String>(); // creates array of Attorney and Paralegal names for JCombo Box Vector<String> caseNames = new Vector<String>(); // creates array of Case names for JCombo Box // This will search through the entire list of contacts but will only add the names of contact types: Attorney and Paralegal // NOTE: only these two contact types will be performing activities that is why only these two are selected. for (int i =0; i < contactlist.rowCount(); i++) { Contact contact = contactlist.getRowContact(i); if (contact.getContactType().equals("Attorney")) attorneyNames.add(contact.getLastname()); else if (contact.getContactType().equals("Paralegal")) attorneyNames.add(contact.getLastname()); } // This will search through the entire list of case and grabs the name of each case for (int i =0; i < caselist.caseList.getRowCount(); i++) { Case cases = caselist.getRowCase(i); caseNames.add(cases.getCaseName()); } attorneyNames.add("No Attorney"); // Place holder just in case no Attorney is assigned to an activity caseNames.add("No Case"); // Place holder just in case no Case is assigned to an activity // Build a panel JPanel panel1 = new JPanel(new GridLayout(0, 2)); // Window Size here panel1.setPreferredSize(new Dimension(400, 200)); // Adding Fields to the form panel1.add(new JLabel("Activity Form")); panel1.add(new JLabel("")); JTextField tfType = new JTextField(this.getActType()); panel1.add(new JLabel("Activity Type: ")); panel1.add(tfType); JTextField tf2Desc = new JTextField(this.getActDesc()); panel1.add(new JLabel("Description: ")); panel1.add(tf2Desc); JTextField fl5 = new JTextField(this.getStartDate()); panel1.add(new JLabel("Start Date: ")); panel1.add(fl5); JTextField fl6 = new JTextField(this.getEndDate()); panel1.add(new JLabel("End Date: ")); panel1.add(fl6); JComboBox fl3 = new JComboBox(caseNames); fl3.setSelectedItem("No Case"); panel1.add(new JLabel("Case: ")); panel1.add(fl3); JComboBox fl4 = new JComboBox(attorneyNames); fl4.setSelectedItem(this.getActAttorney()); panel1.add(new JLabel("Attorney: ")); panel1.add(fl4); String[] items3 = {"Inactive", "Active"}; JComboBox cf6 = new JComboBox(items3); panel1.add(new JLabel("Activity Status: ")); panel1.add(cf6); panel1.add(new JLabel("")); panel1.add(new JLabel("")); int result = JOptionPane.showConfirmDialog(null, panel1, "Activity Module", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { // Submits Activity for creation // Firsts validates activity fields have required text fields occupied *NOTE: not all text fields are required for Activities //Load this.setActType(tfType.getText()); this.setActDesc(tf2Desc.getText()); this.setStartDate(fl5.getText()); this.setEndDate(fl6.getText()); this.setActCase(fl3.getSelectedItem().toString()); this.setActAttorney(fl4.getSelectedItem().toString()); if (cf6.getSelectedIndex()==0) this.setStatus(false); else this.setStatus(true); if (this.validateRecord()) { this.setLoaded(true);// setting flag. if (createRow) { this.saveRecord(al); } } else { this.setLoaded(false);// setting flag. this.formEdit(al, caselist, contactlist, createRow); } } else { // Set defaults and close this.initRecord(); this.setLoaded(false); } }
97768d09-f2f1-4a9d-bd2c-0df96a0ed3da
0
@SuppressWarnings("deprecation") @Test public void test() { Date start = new Date(113, 12, 20, 14, 10, 00); Date end = new Date(113, 12, 21, 14, 10, 00); int d = TimeCalculator.duration(start, end); assertTrue(d == 86400); assertEquals("24小时0分0秒", TimeCalculator.HMSFormatDuration(start, end)); IRule rule = (IRule) context.getBean("TollCallRule"); CallInfo c = CallInfoFactory.getCallInfo(1, 1, 1, 1, start, end); double p = CallManager.getPrice(c, rule); assertTrue(p == 432); }
4f7a1ec8-5aa5-47a3-bafe-f3d9a5b37d97
3
@Override public void execute(Game game, HashMap<String, String> strings, Entity target) throws ScriptException { if (args[0].toLowerCase().equals("p")) { game.getPlayer().setCoords(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); } else if (args[0].toLowerCase().equals("t")) { target.setCoords(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); } else { Entity e = game.getWorld().getEntity(args[0]); if (e != null) { e.setCoords(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); } else { throw new ScriptException(ScriptException.BAD_ARGS); } } }
b2355cc0-ccd8-43e0-ba30-8ac3f7a4171b
8
public void execute(RPSAgent agent) { Set<Peer> slaves = agent.getSlaves(); agent.log("It was time to prepare the tournament."); agent.log("First I had to find out how many of the " + slaves.size() + " participants was still willing to take part in the tournament."); //Find out how many slaves are still there Set<Peer> liveSlaves = new java.util.HashSet<Peer>(); Map<Peer, RPSAgent> liveAgents = new java.util.HashMap<Peer, RPSAgent>(); for(Agent neighbour : agent.getServer().getResidingAgents()) { if(slaves.contains(neighbour.getHome())) { if(liveSlaves.add(neighbour.getHome())) liveAgents.put(neighbour.getHome(), (RPSAgent)neighbour); } } agent.setSlaves(liveSlaves); if(liveSlaves.size() > 1) { agent.log("It turned out to be " + liveSlaves.size() + ". Enough for a tournament to be held."); //Create match schema List<Match> matches = createMatchSchema(agent); //Send match schema to every slave agent.log("As soon I had created a match schema, I handed it out to all participants."); agent.log("There would be " + matches.size() + " matches."); for(Entry<Peer, RPSAgent> e : liveAgents.entrySet()) { e.getValue().postMessage(new Message(agent, MessageTypes.MATCHLIST, matches)); } //Send start to each slave. agent.log("I can not describe the joy I felt when I finally could raise my voice and cry: 'Let the tournament begin!'"); for(Entry<Peer, RPSAgent> e : liveAgents.entrySet()) { e.getValue().postMessage(new Message(agent, MessageTypes.START)); } agent.setState(new RunTournamentState(matches)); } else { //To few participants agent.log("Unfortunately, there were only " + liveSlaves.size() + " of them left."); agent.log("I had to cancel the tournament."); //Tell agents to go home Message goHome = new Message(agent, MessageTypes.GO_HOME, "There are not enough participants in the tournament. I'm sorry."); for(Entry<Peer, RPSAgent> e : liveAgents.entrySet()) { e.getValue().postMessage(goHome); } if(liveAgents.size() > 0) agent.log("It was a sad job to inform the remaining participants, but it had to be done."); agent.setState(new MoveHomeState()); } }
a1affe87-c079-4dce-85fd-6d38f8ac0c04
2
public void waitForConnection() throws IOException { conn = serverSocket.accept(); outStream = new PrintWriter(conn.getOutputStream()); inStream = new BufferedReader(new InputStreamReader(conn.getInputStream())); // Negotiation while (true) { String[] msg = inStream.readLine().split(" "); if (msg[0].equals("JOIN")) { this.name = msg[1]; break; } } }
9895956b-f5c6-4a2e-94c6-08485f0a62a9
1
public void joinChannel(Channel channel) { synchronized (channels) { if (channels.isEmpty()) { // logged in Server.get().addClient(this); } channels.add(channel); } }
64905bea-a3dd-4f8e-9248-85a479afbb1a
0
public Framework() { // call constructor of extended Canvas object super(); //set the game state gameState = GameState.VISUALIZING; //We start game in new thread. Thread gameThread = new Thread() { @Override //start th game thread and call gameloop to control the game public void run() { GameLoop(); } }; gameThread.start(); }
e3d2bd69-b9d4-42b0-b62f-35dfc7747222
4
public Set<Move> getAllLegalMoves() { Set<Move> legalMoves = new HashSet<Move>(); for (int i = 0; i < NUMBER_OF_COLS; i++) { for (int j = 0; j < NUMBER_OF_ROWS; j++) { Coordinate startCoord = new Coordinate(i, j); Piece piece = getPiece(startCoord); if (!piece.isNone() && piece.getColor() == currentTurnColor) { legalMoves.addAll(getLegalMoves(startCoord)); } } } return legalMoves; }
15b2e54b-1298-4f0e-8c0c-af10dffea9e3
8
public static TranslationEntry swapIn(int pid, int vpn, LoaderForCoff loader) { VMKernel.printDebug("Beginning swap in sequence!!!"); TranslationEntry entry; int ppn = pageReplacementAlgorithm.findSwappedPage(); try { swapOut(ppn);//if only if it's already in the memory } catch (IllegalArgumentException e) { return null; } //now perform Swap In SwapPageManager.SwapPage swapPage = SwapPageManager.getSwapPage(pid, vpn); // if the swapIn Page is on the disk if (swapPage != null) { entry = swapPage.getDiskPage().entry; if (printSwapFlag) { VMKernel.printDebug(" Loading a swap entry-> VPN: " + entry.vpn + "PPN: " + entry.ppn + " IsValid: " + entry.valid + " Used: " + entry.used + " ReadOnly: " + entry.readOnly + " Dirty: " + entry.dirty); } entry.valid = true; entry.used = false; entry.dirty = false; if (printSwapFlag) { VMKernel.printDebug(" Rewrite entry-> VPN: " + entry.vpn + "PPN: " + entry.ppn + " IsValid: " + entry.valid + " Used: " + entry.used + " ReadOnly: " + entry.readOnly + " Dirty: " + entry.dirty); } boolean success = SwapPageManager.accessSwapFile(swapPage,ppn, false); if (!success) { // read error and kill proceess VMKernel.printDebug("Read error, unable to swap in file!"); return null; } } else { entry = loader.loadData(pid, vpn, ppn); } //found a page by now, map virtual to physical InvertedPageTable.put(pid, vpn, ppn);//update ipt MemoryPage newPage = new MemoryPage(pid, vpn, entry); VMKernel.physicalDiskMap[ppn] = newPage;//update Core Map of tracking all ppn //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ VMKernel.printDebug(" ****END OF SWAPPING!"); if (printAllTables) { VMKernel.printDebug(" ****Printing the inverted page table"); VMKernel.printDebug(InvertedPageTable.getString()); VMKernel.printDebug(" ****Printing the physical page table"); for (int tempPpn = 0; tempPpn < VMKernel.physicalDiskMap.length; tempPpn++) { if (VMKernel.physicalDiskMap[tempPpn] == null) { continue; } VMKernel.printDebug(" **vpn: " + VMKernel.physicalDiskMap[tempPpn].getVirtualPageNumber() + ", ppn: " + tempPpn); VMKernel.printDebug(VMKernel.physicalDiskMap[tempPpn].entry); }//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ } return entry; }
acb460f0-ba85-4c93-9544-708f748d26b8
6
public static Double valueOf(Object o) { if (o == null) { return null; } else if (o instanceof Float) { return (double)(Float)o; } else if (o instanceof Double) { return (Double)o; } else if (o instanceof Byte) { return (double)(Byte)o; } else if (o instanceof Integer) { return (double)(Integer)o; } else if (o instanceof Long) { return (double)(Long)o; } else { return null; } }
97ac5130-8a9f-469a-9408-c35ae9d40723
9
public static void copyProperties(Object dest, Object orig, boolean boo) throws Exception{ Class<?> clazzOrig = orig.getClass(); Class<?> clazzDest = dest.getClass(); Field[] fList = clazzOrig.getFields(); // 此方法可以取public参数包括父类 //if (fList == null || fList.length == 0) { fList = clazzOrig.getDeclaredFields(); // 此方法可取所有参数,但不能取父类 //} Method method = null; Object value = null; for(Field field : fList){ String proName = field.getName(); Class<?> type = field.getType(); try { method = clazzOrig.getMethod(GETER_START + StringUtils.capitalize(proName)); } catch (Exception e) { continue; } value = method.invoke(orig); if(boo){ if(value==null||"0".equals(value.toString())){ continue; } } try { method = clazzDest.getMethod(SET_START + StringUtils.capitalize(proName),type); method.invoke(dest,value); } catch (Exception e) { continue; } } }
d48e7a84-73aa-4b67-acd6-41fc31a3b5e9
1
void create_file (Object doc,String fpath) { Path logfile = FileSystems.getDefault().getPath(fpath); //fileW=fpath; String s = (String) doc; byte data[] = s.getBytes(); try (OutputStream out = new BufferedOutputStream( Files.newOutputStream(logfile,CREATE))) { out.write(data, 0, data.length); System.out.println("Log file created"); } catch (IOException x) { System.err.println(x); } }
7ce4a2f9-427d-4045-b104-1f0229efa6ac
5
public String getDescr() { if( cxnSp != null ) { return cxnSp.getDescr(); } if( sp != null ) { return sp.getDescr(); } if( pic != null ) { return pic.getDescr(); } if( graphicFrame != null ) { return graphicFrame.getDescr(); } if( grpSp != null ) { return grpSp.getDescr(); } return null; }
2510da9b-54f5-481d-b29e-839f909ab077
2
public static void main(final String[] args) { Server server = null; if (args.length > 0) { server = Server.getInstance(Integer.parseInt(args[0])); } else { server = Server.getInstance(5042); } server.start(); try { server.join(); } catch (final InterruptedException e) { e.printStackTrace(); } }
b62bc497-5390-42d1-8924-29d3ec97642b
1
public void normalizePercentage() { percentage = (1.0 * curValue) / maxValue; if(percentage > 0.99) { percentage = 1.0; } }
78f9f50d-2943-43ae-96a3-65f309d86793
0
@Override public int getRank() { return rank; }
c75a0b75-2785-4a7d-8fdb-c73b42d4a327
4
public float get_halffloat(int offset) { int signbit; int mantissa; int exp; float result; if(offset >= 0) if (pb[5] < (offset + 2)) { val = -1; // insufficient payload length return 0; } result = ((pb[offset + 7] & 0x80) != 0) ? (float) -1.0 : (float) 1.0; mantissa = ((((int) pb[offset + 7]) & 0x3) << 8) | (((int) pb[offset + 6]) & 0xff); exp = (pb[offset + 7] & 0x7c) >> 2; //System.out.println("pb[offset+7] pb[offset + 6]: " + pb[offset + 7] + " " + pb[offset +6] // + " exp: " + exp + " mantissa: " + mantissa ); if (exp != 0) { // non-zero exponent // subtracting 1 from exp is required so that left shift by // exp == 31 does not produce negative result. Compensated for in // exponent of scaling factor following if expression result *= ((float) ((1 << HALF_MBITS) + mantissa)) * ((float) ( 1 << exp - 1)); } else { // 0 exponent result *= mantissa; } result *= ((float) 1.0) / (float) (1 << (HALF_EBIAS + HALF_MBITS - 1)); return result; }
b1337f6c-1af2-4afe-897a-673985c6df43
8
public static void main(String[] args) throws Throwable{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for(int c = 0, C = parseInt(in.readLine().trim()); c < C; c++){ if(c == 0)in.readLine(); TreeMap<Character, Character> cypher = new TreeMap<Character, Character>(); char[] plainText = in.readLine().toCharArray(); char[] substitution = in.readLine().toCharArray(); for(int i = 0; i < plainText.length; i++)cypher.put(plainText[i], substitution[i]); sb.append(new String(substitution) + "\n"); sb.append(new String(plainText) + "\n"); for(String ln; (ln = in.readLine()) != null && !ln.equals("");){ char[] str = ln.toCharArray(); for(char ch:str) if(cypher.containsKey(ch))sb.append(cypher.get(ch)); else sb.append(ch); sb.append("\n"); } if(c<C-1)sb.append("\n"); } System.out.print(new String(sb)); }
2b576890-751c-4b4e-8f91-267a4d5aa717
4
@Override public boolean createPosition(Position position) { String sql = INSERT_POSITION; Connection connection = new DbConnection().getConnection(); PreparedStatement preparedStatement = null; boolean flag = false; String positionId = position.getPositionId(); String positionName = position.getPositionName(); String createdBy = position.getCreatedBy(); String status = "OPEN"; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, positionId); preparedStatement.setString(2, positionName); preparedStatement.setString(3, createdBy); preparedStatement.setString(4, status); preparedStatement.executeUpdate(); flag = true; addPositionDetails(position); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } finally { try { if (connection != null) connection.close(); if (preparedStatement != null) preparedStatement.close(); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } } return flag; }
bf650e50-54ac-41b5-b0b7-7e65a3993432
7
@Override public String getNextTask() { if (this.initialized == false) { throw new IllegalStateException("Scheudlers must be initialized before they can be used."); } else if (this.scheduleable == false) { throw new IllegalStateException("Task set is not scheduleable."); } refreshTasks(); String nextTask = null; PeriodicTask pt = periodicTasks.peek(); if (pt != null) { if (pt.getName().equals("SERVER")) { /* If the periodic server task is to be run, check that an aperiodic task is ready to run. If not, the aperiodi server will not run until its next period arrives. */ nextTask = this.aperiodicTasks.getTaskAtTime(time); if (nextTask == null) { this.refreshList.add(this.periodicTasks.remove()); pt = this.periodicTasks.peek(); if (pt != null) { nextTask = pt.getName(); updateTask(pt); } } else { updateTask(pt); } } else { nextTask = pt.getName(); updateTask(pt); } } this.time += 1; return (nextTask != null) ? nextTask : ""; }
9dbef0b6-da9e-422a-b4b6-7b220418b38f
4
public void calculateLR(int x) { Doodle doodle2 = (Doodle) myGuys.get(0); int doodleX = doodle2.getX(); // if already facing left, dont do anything, same with right if ((x < doodleX)) { myImages.set(0, doodleLImg); doodle2.setX(doodle2.getX()); hFacing = -1; doodle2.setHFacing(-1); } else if ((x > doodleX + doodle2.getWidth()) && (hFacing < 1)) { myImages.set(0, doodleRImg); doodle2.setX(doodle2.getX()); hFacing = 1; doodle2.setHFacing(1); } else if (hFacing != 0) { hFacing = 0; doodle2.setHFacing(0); } myGuys.set(0, doodle2); }
1c46aa50-58b8-437c-b875-204d4f5af4f6
8
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("rowset")) { String name = getString(attrs, "name"); if (name.equals("skills")) skills = true; else if (name.equals("requiredSkills")) requiredSkills = true; else if (name.equals("skillBonusCollection")) skillBonusCollection = true; } else if (qName.equals("row")) { if (skillBonusCollection) { ApiBonus bonus = new ApiBonus(); bonus.setBonusType(getString(attrs, "bonusType")); bonus.setBonusValue(getString(attrs, "bonusValue")); skill.add(bonus); } else if (requiredSkills) { ApiRequirement requirement = new ApiRequirement(); requirement.setTypeID(getInt(attrs, "typeID")); requirement.setSkillLevel(getInt(attrs, "skillLevel")); skill.add(requirement); } else if (skills) { skill = new ApiSkill(); skill.setTypeName(getString(attrs, "typeName")); skill.setTypeID(getInt(attrs, "typeID")); skill.setGroupID(getInt(attrs, "groupID")); skill.setPublished(getBoolean(attrs, "published")); skillGroup.add(skill); } else { skillGroup = getItem(attrs); } } else super.startElement(uri, localName, qName, attrs); }
7881ae70-b940-415f-b0ad-3215938d3c70
8
boolean ComprovarRes(Clausula c, ClausulaNom cn) { boolean b = true; for( RestGrupSessio gs : restriccionsGrupSesio){ String dia = cn.getDia(); int i; if (dia.equals("dilluns")) i = 0; else if (dia.equals("dimarts")) i = 1; else if (dia.equals("dimecres")) i = 2; else if (dia.equals("dijous")) i = 3; else if (dia.equals("divendres")) i = 4; else if (dia.equals("dissabte")) i = 5; else i = 6; if ( gs.CompleixRes( c.getAssignatura().getNom(), c.getGrup(), i, cn.getHora() )) return true; else b = false; } return b; }
13411df9-ae21-4300-bd3a-e9f5447a1203
1
public void inject(ARPPacket p) { // Injects the poison on the network try { sender = JpcapSender.openDevice(devices[deviceIndex]); sender.sendPacket(p); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6f1e1229-6824-4d5d-8460-b36e00128b1f
0
public void setValue(int newValue) { value = newValue; }
cc1ce2c7-56da-4943-99a6-3771f05b7687
9
public void uimsg(String msg, Object... args) { if (msg == "tabfocus") { setfocustab(((Integer) args[0] != 0)); } else if (msg == "act") { canactivate = (Integer) args[0] != 0; } else if (msg == "cancel") { cancancel = (Integer) args[0] != 0; } else if (msg == "autofocus") { autofocus = (Integer) args[0] != 0; } else if (msg == "focus") { Widget w = ui.widgets.get((Integer) args[0]); if (w != null) { if (w.canfocus) setfocus(w); } } else if (msg == "curs") { if (args.length == 0) cursor = null; else cursor = Resource.load((String) args[0], (Integer) args[1]); } else { System.err.println("Unhandled widget message: " + msg); } }
1689732a-2092-4fe1-892a-ff30a6efa2b3
2
public void visitSource(final String file, final String debug) { if (file != null) { sourceFile = newUTF8(file); } if (debug != null) { sourceDebug = new ByteVector().putUTF8(debug); } }
92d05e89-e3a2-47d2-b4a0-856a7a990bc2
6
public static String unescape(String s) { int len = s.length(); StringBuffer b = new StringBuffer(); for (int i = 0; i < len; ++i) { char c = s.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < len) { int d = JSONTokener.dehexchar(s.charAt(i + 1)); int e = JSONTokener.dehexchar(s.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } b.append(c); } return b.toString(); }
7929e057-9bc7-4951-bcd8-78bc8fdbd7c9
0
private ParcelDestination(String whereTo) { label = whereTo; }
bd475257-faa4-4117-86a9-7892895d8141
8
public static void main(String[] args) throws Exception { int numThreads = 1; try { Options opt = new Options(); opt.addOption("h", false, "print help"); opt.addOption("t", true, "number of threads"); opt.addOption("v", false, "verbose"); opt.addOption("V", false, "version"); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opt, args); if ( cl.hasOption('h') ) { HelpFormatter f = new HelpFormatter(); f.printHelp("OptionsTip", opt); System.exit(1); } if ( cl.hasOption('V') ) { System.out.println("version:" + VERSION); System.exit(1); } if ( cl.hasOption('v') ) { Logger.setVerbose(true); } if (cl.hasOption('t')) { numThreads = Integer.parseInt(cl.getOptionValue('t')); if (numThreads < 1) { numThreads = 1; } } } catch (ParseException e) { e.printStackTrace(); } if (args.length < 1) { throw new IllegalArgumentException("source directory is not given"); } if (args.length < 2) { throw new IllegalArgumentException("target directory is not given"); } String localDir = args[0]; String remotePath = args[1]; String strs[] = parseS3path(remotePath); String bucket = strs[0]; String targetDir = strs[1]; Logger.log(localDir +" , "+ bucket +" , "+ targetDir +" , "+ numThreads); AmazonS3 s3 = new AmazonS3Client(new EnvironmentVariableCredentialsProvider()); s3.setEndpoint(endpoint); Uploader uploader = new Uploader(s3, localDir, bucket, targetDir, numThreads); uploader.upload(); }
5765274a-8acd-456b-aa40-df9f8b4ec849
5
@BeforeSuite public void initalize(){ try{ config = new Properties(); FileInputStream fp = new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\nike\\automation\\smartcart\\config\\config.properties"); config.load(fp); //loading the object repository OR = new Properties(); fp = new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\nike\\automation\\smartcart\\config\\OR.properties"); OR.load(fp); datatable= new Xls_Reader(System.getProperty("user.dir")+"\\src\\com\\nike\\automation\\smartcart\\xls\\Controller.xlsx"); //loading the data file data = new Properties(); fp = new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\nike\\automation\\smartcart\\config\\data.properties"); OR.load(fp); //checking the type of browser if(config.getProperty("browserType").equalsIgnoreCase("IE")){ driver = new InternetExplorerDriver(); }else if(config.getProperty("browserType").equalsIgnoreCase("Firefox")){ driver = new FirefoxDriver(); }else if(config.getProperty("browserType").equalsIgnoreCase("Chrome")){ System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\Tools\\chromedriver.exe"); driver = new ChromeDriver(); }else if(config.getProperty("browserType").equalsIgnoreCase("Firefox_Profile")){ File profiler = new File(System.getProperty("user.dir")+"\\src\\com\\nike\\automation\\smartcart\\profile\\Nike.FirefoxProfile"); FirefoxProfile profile = new FirefoxProfile(profiler); driver = new FirefoxDriver(profile); } }catch(Exception e){ e.printStackTrace(); Assert.fail("failing since configuration, OR, controller sheet has not loaded successfully"); } //ProfilesIni prof =new ProfilesIni(); //FirefoxProfile p =prof.getProfile("Webdriver.Nike"); //FirefoxDriver driver = new FirefoxDriver(p); }
0f98b6b1-a69a-4a08-9404-d13d2420130a
8
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void invokeListeners(String interfaceName, Executable executable, boolean returnsResults) { List<BusListener> specificListeners = getListenersFor(interfaceName, listeners); if (returnsResults && specificListeners == null) throw new IllegalArgumentException("Cannot return results when no listeners are registered for " + interfaceName); if (specificListeners == null) return; // create unmodifiable copy so that additions/removals of listeners // during an invocations don't mingle with the order of listeners specificListeners = new ArrayList<BusListener>(specificListeners); boolean oldCallActive = callActive; callActive = true; Set<Throwable> exceptions = null; for (BusListener listener : specificListeners) { if (!callActive) break; try { Object result = executable.execute(listener); executable.addItemToResults(result); } catch (Throwable t) { if (exceptions == null) exceptions = new HashSet<Throwable>(); exceptions.add(t); } } callActive = oldCallActive; lastInvocationResults = executable.results; if (exceptions != null) throw new UmbrellaException(exceptions); }
78cc1dd6-8739-46ad-9bdd-7c9d1d88227c
4
public void keyReleased(KeyEvent key) { int code = key.getKeyCode(); if(code == KeyEvent.VK_LEFT) { player.setLeft(false); } if(code == KeyEvent.VK_RIGHT) { player.setRight(false); } if(code == KeyEvent.VK_DOWN) { player.setDown(false); } if(code == KeyEvent.VK_C) { player.setWeaponUse(false); } }
6e7673d8-6c1b-4139-98f6-4f976fbb0621
7
public void generateMoves(Piece[][] squares, ArrayList<Move> validMoves, ArrayList<Move> validCaptures) { // for each possible direction (NE, SE, SW, NW) int xPos; int yPos; for (int direction = 0; direction < xMoves.length; direction++) { xPos = xPosition + xMoves[direction]; yPos = yPosition + yMoves[direction]; //Make sure the move would still be inside the board if (0 <= xPos && xPos <= 7 && 0 <= yPos && yPos <= 7) { if (squares[xPos][yPos] == null) { //if the square is empty validMoves.add(new Move(xPosition, yPosition, xPos, yPos)); } else { //if the square contains a piece if (squares[xPos][yPos].colour == this.colour) { //if the square contains a friendly piece do nothing } else { validCaptures.add(new Move(xPosition, yPosition, xPos, yPos)); //if the square contains an enemy piece } } } } }
40cf039b-17fd-459b-8df9-c0969cc0062f
9
public void run() { Selector selector = SocketAcceptor.this.selector; for (;;) { try { int nKeys = selector.select(); registerNew(); if (nKeys > 0) { processSessions(selector.selectedKeys()); } cancelKeys(); if (selector.keys().isEmpty()) { synchronized (lock) { if (selector.keys().isEmpty() && registerQueue.isEmpty() && cancelQueue.isEmpty()) { worker = null; try { selector.close(); } catch (IOException e) { ExceptionMonitor.getInstance() .exceptionCaught(e); } finally { SocketAcceptor.this.selector = null; } break; } } } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } }
d1126297-073a-4f4f-bd45-1bcfb76b1cc0
4
public static void saveFile() { System.out.println("Pokedex save started."); PrintWriter fout = null; try{ fout = new PrintWriter(new FileWriter(fileName)); } catch(Exception e) { e.printStackTrace(); System.out.println("Pokedex save file not found. Making new one"); try{ fout = new PrintWriter(new FileWriter(new File(fileName))); } catch(IOException ignored){} } for(int i=0; i<151; i++) fout.println(seen[i] + ""); for(int i=0; i<151; i++) fout.println(caught[i]); fout.println(totalSeen + "\n" + totalCaught); fout.close(); JokemonDriver.saveEncryptionKey(fileName, JokemonDriver.encrypt(fileName)); System.out.println("Pokedex save complete."); }
191bab76-ec8d-4a4a-82ef-b8f8d1216185
4
public void DisplayOpenSeats(){ int aisleTotal=0, winTotal=0; for(int i=0;i<wSeats.length;i++){ if(wSeats[i].equals("NA") ) winTotal++; } for(int i=0;i<aSeats.length;i++){ if(aSeats[i].equals("NA") ) aisleTotal++; } System.out.println("Open Window Seats " +winTotal+"; Open Aisle Seats " +aisleTotal); }
aa57fdca-3ba2-4c82-be41-2d9452af5eda
4
@Test public void testHashMapString() { long minTime = Long.MAX_VALUE; long maxTime = Long.MIN_VALUE; long avgTime = 0; long beforeTime = 0; long afterTime = 0; long curTime = 0; Random random = new Random(); int value; AbstractProcessor<String> processor = new ValueFrequencyProcessor(); //warmup value = random.nextInt(255); beforeTime = System.nanoTime(); result = processor.process(value + 1); afterTime = System.nanoTime(); for (int i = 1; i < MAX_CYCLES; i++) { value = random.nextInt(255); beforeTime = System.nanoTime(); result = processor.process(value + 1); afterTime = System.nanoTime(); curTime = afterTime - beforeTime; avgTime = (avgTime + curTime) / 2; if (i % DISPLAY_TIME == 0) { maxTime = (avgTime > maxTime) ? avgTime : maxTime; minTime = (avgTime < minTime) ? avgTime : minTime; stringBuilder.append(String.format("Time: \t avg: %1$8dns\t min: %2$8dns\t max: %3$8dns\n", avgTime, minTime, maxTime)); avgTime = curTime; } } }
cadc2cc2-18f1-45f0-b519-7e0e9461ba19
0
public int getIdColor() { return idColor; }
51bf7bcc-cfb7-4cc8-862d-44a7666b11c7
7
public static String generateJavaCode(GUIObject guiObject, HashMap<String, String> allImports, Interface blueJInterface) { StringBuilder code = new StringBuilder(); code.append(getJavaImports(guiObject, allImports)).append('\n');//Add imports String clName = (blueJInterface != null ? blueJInterface.getOpenGUIName() : guiObject.getClassName()); String clExtends = (blueJInterface != null ? "guibuilder.GUI" : "Application"); code.append("public class ").append(clName).append(" extends ").append(clExtends).append(" {\n\n");//Open class tag //Add declarations for (Node node : guiObject.getChildren()) { declaration(node, code); } code.append('\n'); //Add properties code.append(" private Parent getRoot() {\n"); code.append(" AnchorPane root = new AnchorPane();\n"); code.append(" root.getChildren().addAll("); String prefix = ""; for (Node node : guiObject.getChildren()) { GObject gObj = (GObject) node; code.append(prefix); prefix = ", "; code.append(gObj.getFieldName()); } code.append(");\n"); //Build a list of panes so that we can add each node into that pane's pane. ArrayList<Pane> paneList = buildPaneList(guiObject); for (Pane p : paneList) { code.append(" ").append(((GObject) p).getFieldName()).append(".getChildren().addAll("); prefix = ""; for (Node node : p.getChildren()) { GObject gObj = (GObject) node; code.append(prefix); prefix = ", "; code.append(gObj.getFieldName()); } code.append(");\n"); } code.append("\n"); for (Node node : guiObject.getChildren()) { panelProperties(node, code); } code.append(" return root;\n"); code.append(" }\n\n"); // Add show method code.append(" public void show() {\n" + " new JFXPanel();\n" + " Platform.runLater(new Runnable() {\n" + " @Override\n" + " public void run() {\n" + " start(new Stage());\n" + " }\n" + " });\n" + " }\n\n"); //Add start method code.append(" @Override\n" + " public void start(Stage primaryStage) {\n" + " Scene scene = new Scene(getRoot(), " + guiObject.getWidth() + ", " + guiObject.getHeight() + ");\n" + " \n" + " primaryStage.setTitle(\"" + guiObject.getGUITitle() + "\");\n" + " primaryStage.setScene(scene);\n" + " primaryStage.show();\n" + " }\n\n"); //Add main method code.append(" /**\n" + " * The main() method is ignored in correctly deployed JavaFX application.\n" + " * main() serves only as fallback in case the application can not be\n" + " * launched through deployment artifacts, e.g., in IDEs with limited FX\n" + " * support. NetBeans ignores main().\n" + " *\n" + " * @param args the command line arguments\n" + " */\n" + " public static void main(String[] args) {\n" + " launch(args);\n" + " }\n");; code.append('}');//Close class tag return code.toString(); }
ad7616be-f4d4-4f70-b787-00a9326e5fe0
0
public YamlPermissionRcon(ConfigurationSection config) { super("rcon", config); }
3867fdf0-479f-4db3-88d5-2cfbad83d7ea
5
@SuppressWarnings({ "deprecation", "static-access" }) @EventHandler public void CheckforBasicStoof(PlayerInteractEvent evt){ if(evt.getPlayer().getInventory().contains(Keys.BasicCaseKey) && evt.getPlayer().getInventory().contains(Cases.BasicCase)){ if(evt.getPlayer().getItemInHand().equals(Keys.BasicCaseKey)){ if(evt.getAction().equals(Action.RIGHT_CLICK_AIR) || evt.getAction().equals(Action.LEFT_CLICK_AIR)){ evt.getPlayer().getInventory().remove(Cases.BasicCase); evt.getPlayer().getInventory().removeItem(Keys.BasicCaseKey); Cases.BasicCaseContents(evt.getPlayer()); evt.getPlayer().updateInventory(); plugin.getServer().broadcastMessage(plugin.prefix+ChatColor.GREEN+"Congratulations "+evt.getPlayer().getName()+"! you unlocked a Basic Case."); } } } }
cab4706a-4ede-486d-80bb-e866c9062da2
1
protected String getFileName(URL url) { String fileName = url.getFile(); if (fileName.contains("?")) { fileName = fileName.substring(0, fileName.indexOf("?")); } return fileName.substring(fileName.lastIndexOf('/') + 1); }
fd0522ce-b8df-4b10-b981-d30b9472ba09
4
@Override public void handleStartTag(HTML.Tag foundTag, MutableAttributeSet attrs, int pos) { for (HTML.Tag wantedTag : wantedComplexTags) { if (wantedTag==foundTag) { if (debug) { System.out.print("COMPLEX: "); } HTMLComponent comp = HTMLComponentFactory.create(foundTag, attrs); if (debug) { System.out.println(comp); } pageElements.add(comp); } } }
a8c66b3a-3330-44b7-bad8-cc86c5fafd11
0
public ForwarderWorker(Socket clientSocket, String serverText) { this.clientSocket = clientSocket; this.serverText = serverText; Setup.println("[ForwardingService] Conexion abierta desde: " + clientSocket.getRemoteSocketAddress()); }