method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
ddbaf1a9-8be7-4ab3-a5e5-1e674249e759
2
@Override public void onEnable(){ getDataFolder().mkdirs(); instance = this; FruitManager fm = new FruitManager(); try { FruitManager.getInstance().loadFruits(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.getCommand("devilfruits").setExecutor(new CommandListener()); this.getServer().getPluginManager().registerEvents(new PlayerListener(), this); this.getServer().getPluginManager().registerEvents(new EntityListener(), this); this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new FruitTask(), 0L, 20L*TASK_PERIOD); }
10aa21c1-0003-4292-b3ff-8f70605e1a4e
9
@Override public void run() { Session session = plugin.getSession(); while (true) { try { List<String> queuedJobs = plugin.getQueuedJobs(); for (String jobID : queuedJobs) { int status = -1; try { System.out.println("Getting status of job " + jobID); status = session.getJobProgramStatus(jobID); System.out.println("Status: " + status); if (status != Session.DONE) { if (status == Session.RUNNING) { plugin.fireEvent(new EventRunning(jobID, "1")); plugin.removeQueuedJob(jobID); } else { //logger.log(Level.SEVERE, "getJobProgramStatus of " + job + " returned status: " + status); } } } catch (DrmCommunicationException ex) { if (ex.getMessage().contains("GDI mismatch")) { // ignore this } else { System.err.println("Unable to getJobProgramStatus of job " + jobID); ex.printStackTrace(); } } catch (InvalidJobException ex) { plugin.removeQueuedJob(jobID); } catch (Exception ex) { System.err.println("Unable to getJobProgramStatus of job " + jobID); ex.printStackTrace(); } } sleep(1000); } catch (InterruptedException ex) { System.err.println("DRMAA Plugin Job Status Checker failure"); ex.printStackTrace(); } } }
913fb3ee-fb69-4a7d-b90e-c94059702097
7
public static void main(String[] args) throws FileNotFoundException, IOException{ Set<String> sw = StopWord.getStopWords(); List<String> dataFiles = new ArrayList<String>(); File[] files = new File("data").listFiles(); // Detect what files to clean. for (File file : files) { if (file.isFile()) { String fileName = file.getName(); String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); if(fileEnd.equals("artist")) { dataFiles.add(fileName); } } } // Clean all files and save them to new file 'fileName.artistcleaned'. for(String fileName : dataFiles) { List<String> cleanedBio = new LinkedList<String>(); try(BufferedReader br = new BufferedReader(new FileReader("data/" + fileName))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String bio = sb.toString(); //Separate all words String[] words = bio.split(" |\t|\n"); for(String s : words) { cleanedBio.add(s); } } //Clean the bio and remove stop words. cleanedBio = DataCleaner.firstCleanOfText(cleanedBio); DataCleaner.removeStopWords(sw, cleanedBio); cleanedBio = DataCleaner.secondCleanOfText(cleanedBio); //Print to new file PrintWriter pw = new PrintWriter("data/" + fileName + "cleaned"); for(String s : cleanedBio) { pw.println(s); } pw.close(); } System.out.println("Data is now cleaned!"); }
b5c65ea2-c977-4fcf-bfc0-03f8c8c0752d
5
public synchronized void scheduleLeakCheck(Object target, String desc, final boolean forceClean) { try { if (forceClean) scheduledThreadPoolExecutor.schedule(new CleanerTask(target), Math.min(waitTimeSeconds / 2, 20), TimeUnit.SECONDS); final long id = UnsafeUtils.addressOf(target); final String oDescription = (desc == null ? "" : desc + " : ") + target.getClass() + '@' + System.identityHashCode(target) + ':' + id; scheduledObjects.put(id, new LeakCheckEntry(target, oDescription)); scheduledThreadPoolExecutor.schedule(new Runnable() { @Override public void run() { LeakCheckEntry leakCheckEntry = scheduledObjects.remove(id); if (leakCheckEntry.o != null && leakCheckEntry.o.get() != null) fail(leakCheckEntry); } }, waitTimeSeconds, TimeUnit.SECONDS); } catch (Throwable t) { exception("Failed to schedule a leak check for object " + target.hashCode() + ", desc `" + desc + "`", t); } }
43dc953f-145b-4796-bdfb-d770e5222681
3
public Node<Integer> partition(Node<Integer> head, int x) { if (head == null) return null; Node<Integer> newHead = head; Node<Integer> tail = head; Node<Integer> p = head.next; while (p != null) { Node<Integer> q = p; p = p.next; if (q.data <= x) { q.next = newHead; newHead = q; } else { tail.next = q; q.next = null; tail = q; } } return newHead; }
6a2cef20-3b86-4cfe-8400-ad100bbee5df
8
public void move() { int roverXCor = getXCoordinate(); int roverYCor = getYCoordinate(); if (direction.equals("S") && plateau.isSpaceValid(roverXCor, roverYCor - 1)) { y -= 1; } else if (direction.equals("W") && plateau.isSpaceValid(roverXCor - 1, roverYCor)) { x -= 1; } else if (direction.equals("N") && plateau.isSpaceValid(roverXCor, roverYCor + 1)) { y += 1; } else if(direction.equals("E") && plateau.isSpaceValid(roverXCor + 1, roverYCor)){ x += 1; } else { error = true; } }
b21c32de-307b-4023-8fd4-a9d42932e017
3
public static void IfPotion() { for (int i = 0; i < playerInventory.length; i++) { Item playerInventoryVariable = playerInventory[i]; if (playerInventoryVariable != null) { if (playerInventory[i].getId() == 2) { // playerInventoryVariable = true; playerHealth = playerHealth + 125; System.out.println("Your current health is now: " + playerHealth); System.out.println(); } } } System.out.println("You do not have any health potions"); }
f327ad72-19cc-41cd-8dc7-d1b2657a98c6
7
public static void main(String[] args) { final String method = CLASS_NAME + ".main()"; try { if (3 != args.length) { throw new IllegalArgumentException("Invalid number of arguments. " + USAGE_HELP); } if (!Peer.start(args)) { throw new RuntimeException("Peer Server could not be initialized."); } LogUtil.log(method, "Peer started successfully."); LogUtil.log(method, "Starting Client."); PeerClient.getInstance().startShell(); } catch (RemoteException e) { LogUtil.causedBy(e); } catch (MalformedURLException e) { LogUtil.log(method, LogUtil.causedBy(e)); } catch (NumberFormatException e) { LogUtil.log(method, LogUtil.causedBy(e)); } catch (IOException e) { LogUtil.log(method, LogUtil.causedBy(e)); } catch (ClientNullException e) { LogUtil.log(method, LogUtil.causedBy(e)); } }
05adf280-b285-4592-bef6-37c148a637d9
7
protected <R extends Model> R[] getConnectionArray(String field, Class<R> type, Connection c) { field = field.toLowerCase(); if (!fetched.containsKey(field)) { R[] objs = (R[]) factory.fetch(type, this, c); List<Model> list = new ArrayList<Model>(); String id = factory.getCache().getModelId(type); if (objs != null) for (R o : objs) list.add(o); fetched.put(field, list); /* * It contains elements, but they're added by hand and they've not * been fetched from the database. */ } else if (isFetched.containsKey(field) && !isFetched.get(field)) { R[] objs = (R[]) factory.fetch(type, this, c); List<R> list = (List<R>) fetched.get(field); if (objs != null) for (R o : objs) list.add(o); } isFetched.put(field, true); List<R> back = (List<R>) fetched.get(field); return back.toArray((R[]) java.lang.reflect.Array.newInstance(type, back.size())); }
1646e16e-3470-4c9a-9bef-993609f50c8e
1
protected HttpURLConnection makeConnection(String localMd5) throws IOException { HttpURLConnection connection = (HttpURLConnection)this.url.openConnection(this.proxy); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setRequestProperty("Cache-Control", "no-store,max-age=0,no-cache"); connection.setRequestProperty("Expires", "0"); connection.setRequestProperty("Pragma", "no-cache"); if (localMd5 != null) connection.setRequestProperty("If-None-Match", localMd5); connection.connect(); return connection; }
2a50fbc4-a8c8-43f6-8682-a769b9790395
6
public static String extractWord(List<Location> wordPlayed){ if(wordPlayed == null || getDirection(wordPlayed)==INVALID_DIR || !isContinuous(wordPlayed)){ return null; } StringBuffer sb = new StringBuffer(); sortLocation(wordPlayed); for(int i=0;i<wordPlayed.size();i++){ Location loc = wordPlayed.get(i); Tile t = loc.getTile(); if(t== null) throw new NullPointerException("Tile is null" + loc); if(t instanceof LetterTile){ sb.append(t.getName()); } else{ throw new IllegalArgumentException("Tile is not a letter tile."); } } return sb.toString(); }
66aaaac4-5dcd-46de-b4fe-b47b9a1a2524
8
public long count(int[] skill){ int total=0; int max=0; for(int value : skill){ total+=value; max=Math.max(value, max); } int lower = total/2+1; int upper = Math.min(max+(total-1)/2, total-1); long result=0; for(int i=0; i<skill.length; i++){ int realUpper = Math.min(upper, skill[i]+(total-1)/2); long[] numberOfWayToCreate = new long[upper+1]; numberOfWayToCreate[0] = 1; for(int j=0; j<skill.length; j++){ if(skill[j]>skill[i] || (skill[j]==skill[i] && j>i)) for(int value=realUpper-skill[j]; value>=0; value--){ numberOfWayToCreate[value+skill[j]] += numberOfWayToCreate[value]; } } int realLower = Math.max(lower,skill[i]); for(int strong=realLower; strong<=realUpper; strong++){ result+=numberOfWayToCreate[strong-skill[i]]; } } return result; }
77bae8df-bafb-4936-b593-38cad79bd1c7
8
public PrimitiveOperator combineRightNRightOnLeft(PrimitiveOperator other) { boolean[] newTruthTable = new boolean[8]; // the other gate is on the left side - on the MSB newTruthTable[0] = truthTable[((other.truthTable[0]) ? 4 : 0) | 0]; //000 newTruthTable[1] = truthTable[((other.truthTable[1]) ? 4 : 0) | 1]; //001 newTruthTable[2] = truthTable[((other.truthTable[0]) ? 4 : 0) | 2]; //010 newTruthTable[3] = truthTable[((other.truthTable[1]) ? 4 : 0) | 3]; //011 newTruthTable[4] = truthTable[((other.truthTable[2]) ? 4 : 0) | 0]; //100 newTruthTable[5] = truthTable[((other.truthTable[3]) ? 4 : 0) | 1]; //101 newTruthTable[6] = truthTable[((other.truthTable[2]) ? 4 : 0) | 2]; //110 newTruthTable[7] = truthTable[((other.truthTable[3]) ? 4 : 0) | 3]; //111 return new PrimitiveOperator(newTruthTable); }
aae18467-3054-409d-a80e-d3b26dcde907
1
public void reloadPlugins() { try { createNewClassLoader(); } catch(MalformedURLException ex) { // big problem here, should not happen because of check at // construction ex.printStackTrace(); } erasePluginClasses(); loadPlugins(); }
220838a7-1bdf-45a2-a800-7ac96a14ace7
6
public boolean[][] read() throws IOException{ if (size<=0) return null; boolean[][] polyomino = new boolean[size][size]; int numBytes = (polyomino.length * polyomino[0].length + 7)/ 8; byte[] b = new byte[numBytes]; if (-1 == i.read(b)) return null; byte currentByte=0; for (int x=0; x<polyomino.length; x++){ for (int y=0; y<polyomino[0].length; y++){ int count = (x*polyomino[0].length + y); if (count%8 == 0) currentByte=b[count/8]; polyomino[x][y] = ((currentByte >> (count%8)) & 1) == 1; } } if (polyomino==null){ i.close(); } return polyomino; }
fb4d0c9e-88e4-4fee-a19d-69859e086f93
4
public void modifyBookLanguage(BookLanguage lng) { Connection con = null; PreparedStatement pstmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); pstmt = con.prepareStatement("Update bookLanguage Set lan_code=?, " +"lan_name=? Where lan_id=?"); pstmt.setString(1, lng.getCode()); pstmt.setString(2, lng.getName()); pstmt.setLong(3, lng.getId()); pstmt.executeUpdate(); } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (pstmt != null) { pstmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } }
6c6bdb28-8f85-47bb-a55a-49be5c89197f
6
public static <E extends Comparable<E>> E[] getTop(E[] array, int k) { if (array == null || array.length == 0 || k <= 0) return null; MinHeap<E> minHeap = new MinHeap<E>(); minHeap.add(array[0]); for (int i = 1; i < array.length; i++) { if (minHeap.size() < k) minHeap.add(array[i]); else if (array[i].compareTo(minHeap.findMin()) > 0) { minHeap.deleteMin(); minHeap.add(array[i]); } } return minHeap.toArray(); }
d4fe79e5-362d-4a59-aa90-af7b8e672d02
7
@Override public void run() { //Bandera para salir del hilo si una de las conexiones falla boolean continuar = false; /*Gavarela: se pasará la excepción para poner en pantalla en mensaje de esta switch(pruebaOlib()){ case 0://Conexión Exitosa continuar = true; break; case 1://Falla debido a usuario/contraseña Ejecutable.getControl().errorAccesoOlib(1); break; case 2://Falla del Driver JDBC de Oracle Ejecutable.getControl().errorAccesoOlib(2); } */ try { pruebaOlib(); continuar = true; } catch (SQLException ex) { Ejecutable.getControl().errorAccesoOlib(ex.getMessage()); } catch (ClassNotFoundException ex) { Ejecutable.getControl().errorAccesoOlib(ex.getMessage()); } if (continuar) { continuar = false; /*Gavarela: se pasará la excepción para poner en pantalla en mensaje de esta switch (pruebaDSpace()) { case 0://Conexión Exitosa continuar = true; break; case 1://Falla debido a usuario/contraseña Ejecutable.getControl().errorAccesoDSpace(1); break; case 2://Falla del Driver JDBC de Oracle Ejecutable.getControl().errorAccesoDSpace(2); } */ try { pruebaDSpace(); continuar = true; } catch (SQLException ex) { Ejecutable.getControl().errorAccesoDSpace(ex.getMessage()); } catch (ClassNotFoundException ex) { Ejecutable.getControl().errorAccesoDSpace(ex.getMessage()); } } if (continuar) { if (pruebaSamba()) {//Conexión Exitósa Ejecutable.getControl().setUsuOlib(usuarioOlib); Ejecutable.getControl().setPassOlib(new String(claveOlib)); Ejecutable.getControl().setConexiónOlib(conexiónOlib); Ejecutable.getControl().setUsuDspace(usuarioDSpace); Ejecutable.getControl().setPassDspace(new String(claveDSpace)); Ejecutable.getControl().setConexiónDSpace(conexiónDSpace); Ejecutable.getControl().setUsuSamba(usuarioSamba); Ejecutable.getControl().setPassSamba(new String(claveSamba)); Ejecutable.getControl().setUrlSamba(urlSamba); Ejecutable.getControl().servidoresAccedidos(); } else {//Falla en la conexión Ejecutable.getControl().errorAccesoSamba(); } } }
9f7fbd5c-3970-4954-8e2d-3c2ed2949daa
0
public int getMin() { return this.lowerBound; }
143babde-b002-44bc-a429-128b5a1bc9f3
9
public void addMark(Service service) { // Service service = (Service) node.getUserObject(); List<Mark> markList = service.getMark(); List<BigInteger> mIdList = new ArrayList<BigInteger>(); for (Mark m : markList) { mIdList.add(m.getId()); } List<BigInteger> idList = new ArrayList<BigInteger>(); List<String> markNameList = new ArrayList<String>(); for (Def def : this.db.getMarkDefs().getDef()) { if (!idList.contains(def.getId()) && !mIdList.contains(def.getId())) { idList.add(def.getId()); markNameList.add(def.getName()); } } String newMark = "新規マーク"; markNameList.add(newMark); String selection = (String) JOptionPane.showInputDialog(this.mainFrame, "サービスにマークを追加します.", "マーク追加", JOptionPane.QUESTION_MESSAGE, null, markNameList.toArray(), newMark); if (selection != null) { Def def = null; if (selection.equals(newMark)) { def = createNewMark(this.db.getMarkDefs().getDef()); } else { def = getDef(selection, this.db.getMarkDefs().getDef()); } if (def != null && !mIdList.contains(def.getId())) { Mark mark = new Mark(); mark.setId(def.getId()); service.getMark().add(mark); this.selectService(service); int count = 1; if (this.markCountMap.containsKey(def.getId())) { count = this.markCountMap.get(def.getId()); } this.markCountMap.put(def.getId(), count); this.edited = true; } } }
5ad247b1-d751-4e47-9f51-ff9e417018e6
0
public void setCityCode(String cityCode) { this.cityCode.set(cityCode); }
46f31e65-7865-4683-b710-ede73da578eb
6
public static String htmlEscape(String text) { if (text == null) { return ""; } StringBuilder escapedText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '<') escapedText.append("&lt;"); else if (ch == '>') escapedText.append("&gt;"); else if (ch == '&') escapedText.append("&amp;"); else if (ch == '\"') escapedText.append("&quot;"); else escapedText.append(ch); } String result = escapedText.toString(); return result; }
2ddec8b8-3c83-4da5-820a-11e48fa93c98
1
public double bonusDefense(Territoire t, Peuple attaquant) { return t.has(SallePartiel.class) ? Double.POSITIVE_INFINITY : 0; }
ec2f4421-a87d-4aba-86dc-96c98fa8f572
4
private static void initModules() { for (File f : ModuleUtil.getModuleList()) { ModuleUtil.loadModule(f); ModuleUtil.loadExtJars(f.getParentFile().getAbsolutePath()); } Settings setting = SettingsUtils.getSettings(); ArrayList<BaseModule> modules = ModuleUtil.getModules(); for (BaseModule m : modules) { System.out.println(m.getModuleName()); if (setting.hasModule(m.getModuleName())) { if (setting.isEnable(m.getModuleName())) { ModuleUtil.importModule(m); } } else { ModuleUtil.importModule(m); setting.addModule(m.getModuleName(), true); } } }
7e695ced-155c-4352-8b28-085d638279c3
7
@EventHandler public void SkeletonSpeed(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Skeleton.Speed.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof Arrow) { Arrow a = (Arrow) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getSkeletonConfig().getBoolean("Skeleton.Speed.Enabled", true) && shooter instanceof Skeleton && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getSkeletonConfig().getInt("Skeleton.Speed.Time"), plugin.getSkeletonConfig().getInt("Skeleton.Speed.Power"))); } } }
3e299a93-1c03-4e4d-afd0-98a0c489a87b
4
public int[] minmax(Board curr) { // base case if(curr.children.size()==0||curr.isOver())//has no children { this.bottom=curr.player; int [] result=new int [2]; result[0]=curr.computeUtility(curr.player); return result; } // recursive case ArrayList<Board> myChildren=curr.children; int mySize=myChildren.size(); int [] utility=new int [mySize]; for (int i=0;i<mySize;i++) { int [] tmp=minmax(myChildren.get(i)); utility[i]=tmp[0]; } COLOR childColor=curr.children.get(0).player; if(bottom==childColor) return getUtility(utility,true); else return getUtility(utility,false); }
2102e853-0bdd-4a4a-81e6-c809d72521e2
0
public DtoExtractor(ArrayList<ClientHandeler> clients){ this.clients = clients; }
19983055-e205-4c39-b939-e178df8afad0
4
private boolean turn_left_or_right() { boolean has_turned; Random random = new Random(); int r = random.nextInt(2); boolean keep_right; if(r == 0) { keep_right = false; } else { keep_right = true; } Direction d = new Direction(dx,dy); //has_turned = true; if(keep_right && can_go_right()) { d.turnRight(); has_turned = true; } else if(can_go_left()) { d.turnLeft(); has_turned = true; } else { has_turned = false; } dx = d.x; dy = d.y; return has_turned; }
f55a58e5-3aa3-45d7-a17e-a60609071936
4
public boolean check(BattleFunction iface, PokeInstance user, PokeInstance target, Move move) { if (disabled && target.battleStatus.flags[4]) { iface.print("The move failed..."); return false; } if (isAsleep && target.status != Status.Sleep) { iface.print("The move failed..."); return false; } return true; }
1b9e8789-5016-4d6d-9584-9acd263d11b1
2
public static AccommodationFacilityEnumeration fromValue(String v) { for (AccommodationFacilityEnumeration c: AccommodationFacilityEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
4cebfe06-f302-4c12-bb2d-6413efa2c719
5
private void put(JsonElement value) { if (pendingName != null) { if (!value.isJsonNull() || getSerializeNulls()) { JsonObject object = (JsonObject) peek(); object.add(pendingName, value); } pendingName = null; } else if (stack.isEmpty()) { product = value; } else { JsonElement element = peek(); if (element instanceof JsonArray) { ((JsonArray) element).add(value); } else { throw new IllegalStateException(); } } }
76590125-8480-40f4-9742-60c041209a08
6
public void remove(int key) { HashPrinter.tryRemove(key); /** Run along the array */ int runner = 0; int hash = (key % table.length); while (table[hash] != null && runner < table.length) { if (table[hash].getKey() == key) { break; } runner++; hash = ((key + runner) % table.length); } if (runner == table.length || table[hash].getKey() != key) { HashPrinter.notFound(key); } else if (table[hash].getKey() == key) { size--; table[hash] = DeletedNode.getUniqueDeletedNode(); HashPrinter.remotionSuccessful(key, hash); } }
7ff9ef15-8562-4c79-9135-88456317b7a5
3
@Override public void playbackFinished(PlaybackEvent playbackEvent) { if(gamePlayList != null) { if(playOnce) { gamePlayList.removeByFileName(filePath); } } stop(); if(gamePlayList != null) { gamePlayList.stoppedCurrentSong(); } }
d6147e2c-09f2-417e-94cf-93040b07967b
9
public boolean unifyStatement(Statement rule, Structure query) { if (unify(rule.left, query)) { HashMap<String, Argument> tempMap = new HashMap<String, Argument>(); boolean ok = true; if (rule.right==null) return true; // pullUpVariables(); LinkedList<Structure> list = new LinkedList<Structure>(); for (Structure rightStructure : rule.right) { list.add(replaceVariables(rightStructure)); } for (Structure rightStructure : list) { Unificator newUnificator = new Unificator(rightStructure); ok = newUnificator.unifyProgram(); // System.out.println("====== Un "+newUnificator.map); if (!ok) return false; tempMap = resolve(tempMap, newUnificator.getMap()); if (tempMap==null) return false; } map =resolveUp(map,tempMap); // pullUpVariables(); //map = resolve(map, resolveUp(map,tempMap)); if (map==null) return false; //filterMap(); for (String key : tempMap.keySet()) { if (!map.containsKey(key)) { map.put(key, tempMap.get(key)); } } //pullUpVariables(); return ok; } return false; }
bd0bcbcb-f3d2-496b-803e-d9426e982006
2
private ArrayList<Node> getNodes() { Node node = null; try { //Get time, Connection and ResultSet Long time = System.currentTimeMillis(); String sql = "SELECT * FROM [jonovic_dk_db].[dbo].[nodes];"; Connection con = cpds.getConnection(); PreparedStatement pstatement = con.prepareStatement(sql); ResultSet rs = executeQuery(pstatement); time -= System.currentTimeMillis(); System.out.println("Time spent fetching elements: " + -time * 0.001 + " seconds..."); int i = 0; //Add nodes to node ArrayList, and count percentage for loading screen. while (rs.next()) { node = new Node(rs.getInt(1), new Point2D.Double(rs.getDouble(2), rs.getDouble(3))); // these subtractions needs to be done in the database. nodes.add(node); i++; nodesDownloadedPct += (double) 1 / 675902; } System.out.println("Total nodes: " + i); Collections.sort(nodes, nc); } catch (SQLException ex) { printSQLException(ex); } finally { closeConnection(cons, pstatements, resultsets); } nodesDownloadedPct = 1; return nodes; }
ed426d65-70c8-482d-afad-5ade55817207
6
public BlockMap$Slot init(float var1, float var2, float var3) { this.xSlot = (int)(var1 / 16.0F); this.ySlot = (int)(var2 / 16.0F); this.zSlot = (int)(var3 / 16.0F); if(this.xSlot < 0) { this.xSlot = 0; } if(this.ySlot < 0) { this.ySlot = 0; } if(this.zSlot < 0) { this.zSlot = 0; } if(this.xSlot >= BlockMap.getWidth(this.blockMap)) { this.xSlot = BlockMap.getWidth(this.blockMap) - 1; } if(this.ySlot >= BlockMap.getDepth(this.blockMap)) { this.ySlot = BlockMap.getDepth(this.blockMap) - 1; } if(this.zSlot >= BlockMap.getHeight(this.blockMap)) { this.zSlot = BlockMap.getHeight(this.blockMap) - 1; } return this; }
e4c13b29-f745-400f-a275-a21f2663abc8
7
public boolean crafting() { if (playerLevel[playerCrafting] >= crafting[1] && playerEquipment[playerWeapon] >= 0) { if (actionTimer == 0 && crafting[0] == 1) { actionAmount++; actionTimer = 4; OriginalShield = playerEquipment[playerShield]; OriginalWeapon = playerEquipment[playerWeapon]; playerEquipment[playerShield] = useitems[0]; playerEquipment[playerWeapon] = useitems[1]; setAnimation(0x8DD); crafting[0] = 2; } if (actionTimer == 0 && crafting[0] == 2) { deleteItem(useitems[1], useitems[2], playerItemsN[useitems[2]]); addItem(crafting[4], 1); if (crafting[4] == 1633) { sendMessage("You crushed the gem."); } else { addSkillXP((crafting[2] * crafting[3]), playerCrafting); sendMessage("You successfully cut the gem."); } playerEquipment[playerWeapon] = OriginalWeapon; playerEquipment[playerShield] = OriginalShield; OriginalWeapon = -1; OriginalShield = -1; resetAnimation(); resetCR(); } } else { sendMessage("You need "+crafting[1]+" "+statName[playerCrafting]+" to cut this gem."); resetCR(); return false; } return true; }
954bcb9c-b1df-40fb-9251-7655831adae0
3
private Unit getAppCntxtInsPt(){ for(Unit u : b.getUnits()){ Iterator it = u.getUseBoxes().iterator(); while(it.hasNext()){ Value v = ((ValueBox)it.next()).getValue(); if(v instanceof IdentityRef){ //includes ThisRef and ParameterRef continue; } else{ return u; } } } return null; }
a52bbfda-3bca-4af0-a6ac-301d584b4138
8
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
97361851-f762-4206-a6db-4ada023f015f
4
public static <T> Set<T> getAdjecentTrackObjects(World world, int x, int y, int z, Class<T> type) { Set<T> tracks = new HashSet<T>(); T object = getTrackObjectFuzzyAt(world, x, y, z - 1, type); if (object != null) tracks.add(object); object = getTrackObjectFuzzyAt(world, x, y, z + 1, type); if (object != null) tracks.add(object); object = getTrackObjectFuzzyAt(world, x - 1, y, z, type); if (object != null) tracks.add(object); object = getTrackObjectFuzzyAt(world, x + 1, y, z, type); if (object != null) tracks.add(object); return tracks; }
e2b500c6-9ca2-44d1-af2c-0ea5b113637a
3
public HashMap<String,String> getFileMsg(String IP_PORT,String apiKey,String id){ HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://"+IP_PORT+"/cms/api/file?apikey="+apiKey+"&id="+id); String backRes = "-1"; try { HttpResponse httpResponse = httpClient.execute(httpGet); int state = httpResponse.getStatusLine().getStatusCode(); if(state==200){ String strBack = InputStreamUtils.inputStream2String(httpResponse.getEntity().getContent()); JSONObject jsonBack = JSONObject.fromObject(strBack); backRes = jsonBack.getString("status"); HashMap<String,String> backInf = new HashMap<String, String>(); backInf.put("status",backRes); if(backRes.equals("0")){ JSONObject meta_file = jsonBack.getJSONObject("meta_file"); backInf.put("id",meta_file.getString("id")); backInf.put("name",meta_file.getString("name")); backInf.put("size",meta_file.getString("size")); backInf.put("url",meta_file.getString("url")); } return backInf; } } catch (IOException e) { e.printStackTrace(); } return null; }
d683e4cc-bc93-435c-9e16-1e0cbc3c9030
5
public WarGameGUI() { setTitle("War"); going=true; this.setBounds(100, 100, 800, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); buildPanel(); add(panel); setVisible(true); while(going) { while(start.isVisible()) { start.doClick(); } while(fight.isVisible()) { fight.doClick(); } while(war.isVisible()) { war.doClick(); } while(reset.isVisible()) { reset.doClick(); } } }
be7fad85-b91b-48de-8a3e-65bec22ebfea
4
public static Date parsDateString2Date(String theDateStr) throws ParseException { theDateStr = theDateStr.trim(); if (!startsWithYear(theDateStr)) { theDateStr = getCurrentDate("yyyy")+"-"+theDateStr; } String sepRegEx = "[^0-9]"; Pattern pattern = Pattern.compile(sepRegEx); String[] terms = pattern.split(theDateStr); terms = removeEmptyElements(terms); String formatStr = "yyyy-MM-dd"; String dateStr = String .format("%s-%s-%s", terms[0], terms[1], terms[2]); if (terms.length > 3) { formatStr += " HH"; dateStr += " " + terms[3]; } if (terms.length > 4) { formatStr += ":mm"; dateStr += ":" + terms[4]; } if (terms.length > 5) { formatStr += ":ss"; dateStr += ":" + terms[5]; } SimpleDateFormat sdf = new SimpleDateFormat(formatStr); Date date = sdf.parse(dateStr); return date; }
6fc332c8-c2d8-4e25-9caf-cbb762f476b1
2
@Override public void render() { Game.getUserInterface().drawTextCentered(Game.WIDTH / 2, 100, UserInterface.PRIMARY_FONT_SIZE, "Tank Game", Color.white); Game.getUserInterface().drawTextCentered(Game.WIDTH / 2, 150, UserInterface.SECONDARY_FONT_SIZE, "Singleplayer", selectedOption == 0 ? Color.red : Color.white); Game.getUserInterface().drawTextCentered(Game.WIDTH / 2, 200, UserInterface.SECONDARY_FONT_SIZE, "Exit", selectedOption == 1 ? Color.red : Color.white); }
683f23fa-fb6c-44b9-9aa2-8dd879ec2c00
4
public int pageout(Page og){ // all we need to do is verify a page at the head of the stream // buffer. If it doesn't verify, we look for the next potential // frame while(true){ int ret=pageseek(og); if(ret>0){ // have a page return (1); } if(ret==0){ // need more data return (0); } // head did not start a synced page... skipped some bytes if(unsynced==0){ unsynced=1; return (-1); } // loop. keep looking } }
1c774542-8eba-452e-831b-b5d71815a565
3
public Boolean actualizar_propietario(String propietario, String propietarioNuevo) { Boolean est = false; List DNList = new cDN().leer_por_propietario(propietario); System.out.println("tamanio con propietario igual:" + DNList.size()); Transaction trns = null; sesion = HibernateUtil.getSessionFactory().openSession(); try { trns = sesion.beginTransaction(); for (Iterator it = DNList.iterator(); it.hasNext();) { DocumentoNotificacion objDN = (DocumentoNotificacion) it.next(); DocumentoNotificacion objDNActualizar = new cDN().leer_cod(objDN.getCodDocumentoNotificacion()); objDNActualizar.setPropietario(propietarioNuevo); sesion.update(objDNActualizar); } sesion.getTransaction().commit(); } catch (Exception e) { if (trns != null) { trns.rollback(); } e.printStackTrace(); setError("Tabla_actualizar_registro: " + e.getMessage()); } finally { sesion.flush(); sesion.close(); } return est; }
85ebac1b-930b-4e48-897a-d7441e9453b5
5
public static void main(String []arg) throws IOException{ int numBanks, i, loanCount; double limit; Bank[] bankList; Stack<Integer> unsafeBanks = new Stack<Integer>(); String filepath; Scanner fileinput = new Scanner(System.in); Scanner input = null; try { //gets the location of the file containing the number of banks, limits, and their loan dependencies System.out.print("Please enter the location of the bank data file: "); filepath = fileinput.nextLine(); //create and open a file reader to read the values of the file specified by the user input = new Scanner(new BufferedReader (new FileReader (filepath))); numBanks = input.nextInt(); limit = input.nextDouble(); //create an array of bank objects given number of banks provided by the file bankList = new Bank[numBanks]; for (i = 0; i < numBanks; i++) { bankList[i] = new Bank(); //create a new bank object in each cell of the bankList array bankList[i].baseBalance = input.nextDouble(); bankList[i].numLoans = input.nextInt(); //given the number of loans a specific bank has, create and initialize the loan list for that bank bankList[i].initializeLoanList(); for (loanCount = 0; loanCount < bankList[i].numLoans; loanCount++) { //for the number of loans that the bank has, fill the relevant data bankList[i].loanList[loanCount].loanee = input.nextInt(); bankList[i].loanList[loanCount].amount = input.nextDouble(); } } } finally { //closing the scanners at the end if (input != null) { input.close(); } if (fileinput != null) { fileinput.close(); } } //once all the bank data has been populated, check to see which banks are unsafe given the limit imposed //via the findUnsafe method and the values returned in a stack. //alternatively, the values can be returned as an array for a more permanent storage solution unsafeBanks = findUnsafe(bankList, limit, unsafeBanks); System.out.print("The following banks are unsafe: "); //outputs which banks are unsafe while (!unsafeBanks.empty()) { System.out.print(unsafeBanks.pop() + " "); } System.out.println("."); }
068c6e0c-6569-4d12-9c5b-cbb1a373cdc8
1
public boolean addModerator(User mod){ if(isModerator(mod)) return false; this.moderators.add(mod); save(); return true; }
f097b46f-54b6-48fb-82a1-b8f393654db9
4
public void CopyBlock(int distance, int len) throws IOException { int pos = _pos - distance - 1; if (pos < 0) { pos += _windowSize; } for (; len != 0; len--) { if (pos >= _windowSize) { pos = 0; } _buffer[_pos++] = _buffer[pos++]; if (_pos >= _windowSize) { Flush(); } } }
dd85b777-bb28-4a3e-b023-ed3d6f59bf06
8
static public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[14]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 7; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } } } } for (int i = 0; i < 14; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
f2dcc92e-4bcc-41e1-b50b-1aa166ee3030
7
public void moveItem(final ThePacman theItem, final PacmanItem.Direction theDirection) { controlTouch = false; if (theDirection == null) { return; } theItem.setFacingDirection(theDirection); final byte itemInNextDirection = getItemInNextMove(pacman, theDirection); if (itemInNextDirection == OUT) { return; } if (itemInNextDirection == GHOST) { if (isFrightened()) { eatGhost(theDirection); } else { hitGhost(); } return; } if (itemInNextDirection == DOT) { pacmanScore += 10; } if (itemInNextDirection != WALL) { board[pacman.getY()][pacman.getX()] = FREE; pacman.move(theDirection); } if (itemInNextDirection == ENERGIZER) { hitEnergizerAt = System.currentTimeMillis(); pacmanScore += 100; gameMode = Mode.FRIGHTENED; modeStart = System.currentTimeMillis(); } board[pacman.getY()][pacman.getX()] = PACMAN; updateLabels(); }
f9386c27-f355-4db6-9ac0-70572c172df9
1
public boolean estEnLocation(){ if(this.situation == LOUE){ return true ; } else { return false ; } }
fe8c1b51-0dfb-4dc7-bda1-859249c226ef
9
void mutateSelectedAtom() { if (!(selectedComponent instanceof Atom)) return; final Atom at = (Atom) selectedComponent; if (at.isAminoAcid()) { EventQueue.invokeLater(new Runnable() { public void run() { if (acidPopupMenu == null) acidPopupMenu = new AminoAcidPopupMenu(); acidPopupMenu.setAtom(at); acidPopupMenu.show(AtomisticView.this, (int) at.getRx(), (int) at.getRy()); } }); } else if (at.isNucleotide() && at.getID() != Element.ID_SP) { EventQueue.invokeLater(new Runnable() { public void run() { if (nucleotidePopupMenu == null) nucleotidePopupMenu = new NucleotidePopupMenu(); nucleotidePopupMenu.setAtom(at); nucleotidePopupMenu.show(AtomisticView.this, (int) at.getRx(), (int) at.getRy()); } }); } else if (at.getID() != Element.ID_SP && at.getID() != Element.ID_MO) { EventQueue.invokeLater(new Runnable() { public void run() { if (atomMutationPopupMenu == null) atomMutationPopupMenu = new AtomMutationPopupMenu(); atomMutationPopupMenu.setAtom(at); atomMutationPopupMenu.show(AtomisticView.this, (int) at.getRx(), (int) at.getRy()); } }); } }
374468d7-7f46-40cb-9973-c2513b4e79d9
3
public void render(Graphics g){ // render the header and footer g.drawImage(header_ss.grabImage(1, 4, 642, 50), 0, 50, null); g.drawImage(header_ss.grabImage(1, 5, 642, 50), 0, Cong.HEIGHT * Cong.SCALE - 65, null); // render the score for(int i = maxScore; i >= 1; i--){ if(p1.getScore() >= i){ // Score for p1 g.drawImage(scoreboard_ss.grabImage(2, 1, 12, 12), (gameboard_spacing_x * i) - 15, Cong.HEIGHT * Cong.SCALE - 48, null); } else{ // no score for p1 g.drawImage(scoreboard_ss.grabImage(1, 1, 12, 12), (gameboard_spacing_x * i) - 15, Cong.HEIGHT * Cong.SCALE - 48, null); } if(p2.getScore() >= i){ // Score for p2 g.drawImage(scoreboard_ss.grabImage(2, 1, 12, 12), (Cong.WIDTH * Cong.SCALE) - (gameboard_spacing_x * i) + 5, Cong.HEIGHT * Cong.SCALE - 48, null); } else{ // no score for p2 g.drawImage(scoreboard_ss.grabImage(1, 1, 12, 12), (Cong.WIDTH * Cong.SCALE) - (gameboard_spacing_x * i) + 5, Cong.HEIGHT * Cong.SCALE - 48, null); } } p1.render(g); p2.render(g); b.render(g); clock.render(g); //Graphics2D g2d = (Graphics2D) g; //g2d.setColor(Color.green); //g2d.draw(gameWindow); }
ea15452f-72a2-4694-818d-9cb222e1edc7
5
public void setTopics4GibbsCluster(int k, double[] alpha, int clusterNum, int vocalSize){ createSpace(k, 0); setWordTopicStatCluster(k, vocalSize); boolean xid = false; m_alphaDoc = 0; for (int i = 0; i < k; i++) { xid = m_rand.nextBoolean(); m_topicIndicator[i] = xid; if (xid == true) { m_indicatorTrue_stat++; m_alphaDoc += alpha[i]; } } m_clusterIndicator = m_rand.nextInt(clusterNum); int wIndex = 0, wid, tid; for(_SparseFeature fv:m_x_sparse){ wid = fv.getIndex(); for(int j=0; j<fv.getValue(); j++){ do { tid = m_rand.nextInt(k); } while (m_topicIndicator[tid] == false); m_words[wIndex] = new _Word(wid, tid); m_sstat[tid] ++; m_wordTopic_stat[tid][wid] ++; wIndex ++; } } }
87574d31-81a6-4898-b79f-f81409546fa2
6
public ResultSet preencherTabelaEncarregado(String Departamento) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_SELECT_TODOS_ENCARREGADO_TABELA); comando.setString(1, Departamento); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
05ca1df2-9646-4805-9ebf-997cb79b50f2
4
public void drawBackground(Graphics g) { // draw the background graphics from the superclass super.drawBackground(g); ImageManager im = ImageManager.getSingleton(); Image img; Position p; // draw the map as a matrix of tiles with cities on top for ( int r = 0; r < GameConstants.WORLDSIZE; r++ ) { for ( int c = 0; c < GameConstants.WORLDSIZE; c++ ) { p = new Position(r,c); int xpos = GfxConstants.getXFromColumn(c); int ypos = GfxConstants.getYFromRow(r); // Draw proper terrain Tile t = game.getTileAt(p); if(t == null) continue; String image_name = t.getTypeString(); // special handling of ocean coasts if ( image_name == GameConstants.OCEANS ) { image_name = image_name + MapAlgorithms.getCoastlineCoding(game, p ); } img = im.getImage( image_name ); g.drawImage( img, xpos, ypos, null ); } } }
4af1e1bd-1a38-4284-aa78-52ef8a5c8d4f
7
public static int minPathSum(int[][] grid) { int r = grid.length; int c = grid[0].length; int[][] s = new int[r][c]; for (int i = 0 ; i < r ; i++) { for (int j = 0 ; j < c ; j++) { int v1 = Integer.MAX_VALUE; int v2 = Integer.MAX_VALUE; int max_v = 0; try { v1 = s[i-1][j]; } catch(Exception e) {} try { v2 = s[i][j-1]; } catch(Exception e) {} max_v = v1 < v2 ? v1 : v2 ; if (i == 0 && j == 0) max_v = 0; s[i][j] = grid[i][j] + max_v; } } return s[r-1][c-1]; }
7661261b-6aba-465c-bffc-1e84b6a4c0de
2
@Override public void close() throws IOException { if (fileChannel != null) { fileChannel.close(); } if (rf != null) { rf.close(); } }
052e3b55-25eb-4e65-8c83-756b65e45b0c
2
@Override public void close() { //Connection connection = open(); try { if (connection != null) connection.close(); } catch (Exception e) { this.writeError("Failed to close database connection: " + e.getMessage(), true); } }
b023fc44-8ffe-45ab-ba07-63e26f6cc488
8
public void capture (int i, int j, Node n) // capture neighboring groups without liberties // capture own group on suicide { int c = -P.color(i, j); captured = 0; if (i > 0) capturegroup(i - 1, j, c, n); if (j > 0) capturegroup(i, j - 1, c, n); if (i < S - 1) capturegroup(i + 1, j, c, n); if (j < S - 1) capturegroup(i, j + 1, c, n); if (P.color(i, j) == -c) { capturegroup(i, j, -c, n); } if (captured == 1 && P.count(i, j) != 1) captured = 0; if ( !GF.getParameter("korule", true)) captured = 0; }
3d387d3a-cb90-425f-ae56-88d165017822
2
public Quantity add (Quantity target) throws IllegalArgumentException { if(target.unit == null || !target.unit.equals(this.unit)) { throw new IllegalArgumentException(); } Quantity result = new Quantity (this.value + target.value, target.numerator, target.denominator); return result; }
0428df61-562e-43e3-bb58-07d2a4a5d5e8
4
@Override public boolean accept(File f) { // Allow directories to be seen if (f.isDirectory()) { return true; } // Exit if no extensions exist if (extensions == null) { return false; } // Only show files with extensions we defined for (String ext : extensions) { if (f.getName().toLowerCase().endsWith("." + ext)) { return true; } } // Otherwise file is not shown return false; }
d6c54c78-b7ea-4094-b1aa-520c11364eb8
1
public static AccesBDInfo getInstance() { if (instance == null) { instance = new AccesBDInfo(); } return instance; }
447a1ea1-bc32-414c-ae12-d7670a9747e6
7
public boolean matches(int material, int data) { if (this.material != material) { return false; } if (this.data == null) { return true; } for (int i = 0; i < this.data.length; i++) { int val = this.data[i]; // Range if (val == -1) { int min = this.data[i + 1]; int max = this.data[i + 2]; i += 2; if (data >= min || data <= max) { return true; } } else { if (val == data) { return true; } } } return false; }
1187f19e-92da-4b20-943e-b830fa4f05cb
2
@Override public BencodeDictionary parse(BufferedInputStream inputStream) throws IOException, BencodeParseException { readAndCheckFirstByte(inputStream); TreeMap<BencodeString, BencodeType> bencodeValuesMap = new TreeMap<BencodeString, BencodeType>(); int currentByte; while ((currentByte = readByteAndMarkPosition(inputStream)) > -1) { char currentChar = (char) currentByte; if (currentChar == getPostfix()){ return new BencodeDictionary(bencodeValuesMap); } else { inputStream.reset(); BencodeString key = ParserFactory.getStringParser().parse(inputStream); char prefix = (char) readWithoutExtractionOfByte(inputStream); BencodeParser bencodeParser = ParserFactory.getResponsibleParserByFirstChar(prefix); BencodeType value = bencodeParser.parse(inputStream); bencodeValuesMap.put(key, value); } } throw new InvalidFormatException(); }
bd8b93f5-e86f-4541-8d29-11ab77c435e8
1
public void act() { if (canMove()) move(); else turn(); }
ad054da6-ae9f-4f6a-b8fd-200de5ff7376
7
public void mouseEntered(MouseEvent paramMouseEvent) { String str = null; if (ImageButton.this.Enabled) { if (ImageButton.this.MouseOverImage != null) { if (ImageButton.this.ImageMap != null) { str = ImageButton.this.checkMap(paramMouseEvent.getX(), paramMouseEvent.getY()); if (str != null) ImageButton.this.rawSetImage(ImageButton.this.MouseOverImage); } else { ImageButton.this.rawSetImage(ImageButton.this.MouseOverImage); } } if (ImageButton.this.VerboseEvents) if (ImageButton.this.ImageMap != null) { if (str != null) { ImageButton.this.event(paramMouseEvent); return; } } else { ImageButton.this.event(paramMouseEvent); } } }
606642df-88bd-43e2-a56e-ef33f23913ea
4
@Override public ValueType returnedType(ValueType... types) throws Exception { // Check the number of argument if (types.length == 1) { // if array if (types[0] == ValueType.NONE) { return ValueType.NONE; } // If numerical if (types[0].isNumeric()) { return ValueType.DOUBLE; } // if array if (types[0] == ValueType.ARRAY) { return ValueType.ARRAY; } // the type is incorrect throw new EvalException(this.name() + " function does not handle " + types[0].toString() + " type"); } // number of argument is incorrect throw new EvalException(this.name() + " function only allows one numerical parameter"); }
a795be98-1473-4d9b-af60-311fbbf18a62
1
public void testGetIntervalConverterRemovedNull() { try { ConverterManager.getInstance().removeIntervalConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getIntervalConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addIntervalConverter(NullConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); }
a7031fe9-1534-4c82-8cc2-cda0386164b3
2
public void nextScene() { if (current_scene < scene_texture.size()) { current_scene++; } else if (current_scene == scene_texture.size()) { current_scene = scene_texture.size(); } }
766c6832-ee1f-459c-a4a7-b4f5e94ed6e2
3
@Override public void leenUit(Product product) throws DomainException { if(product.getStaat().equals(UitgeleendState.class)) throw new DomainException("Product is al uitgeleend"); if(product.getStaat().equals(BeschadigdState.class)) throw new DomainException("Product is beschadigd"); if(product.getStaat().equals(VerwijderdState.class)) throw new DomainException("Product is niet meer beschikbaar"); product.setStaat(new UitgeleendState()); }
4fa0361a-a1a8-423d-9215-e76c4badfb69
7
private void collisionCheck() { Map<Double, Double> corners = new HashMap<Double, Double>(); corners.put(ball.getX(), ball.getY()); //left-top corners.put(ball.getX(), ball.getY() + diameter); //left-bottom corners.put(ball.getX() + diameter, ball.getY()); //right-top corners.put(ball.getX() + diameter, ball.getY() + diameter);//right-bottom for (Map.Entry<Double, Double> corner : corners.entrySet()) { //bounce of vertical walls if ((corner.getKey() <= 0) || (corner.getKey() >= gameObj.getWidth())) { invertXspeed(); break; } //bounce from top if ((corner.getValue() <= 0)) { invertYspeed(); break; } //ball hit bottom if ((corner.getValue() >= gameObj.getHeight())) { gameObj.remove(ball); gameObj.ballUnderFloorAction(); break; } GObject obj = gameObj.getElementAt(corner.getKey(), corner.getValue()); if (obj != null) { /* Check if collision happened in upper half. */ if (corner.getValue() < (gameObj.getHeight() / 2)) { //it's a brick gameObj.removeBrick(obj); } invertYspeed(); break; } } }
dc209e9f-feae-439e-b70a-0d52d832c3ba
7
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if((affected instanceof Item) &&(((Item)affected).owner() instanceof Room) &&(((Room)((Item)affected).owner()).isContent((Item)affected)) &&(msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(invoker!=null) &&(invoker.location()!=((Room)((Item)affected).owner())) &&(msg.othersMessage()!=null)) invoker.executeMsg(invoker,msg); }
1920bb32-d37a-4bbc-967f-ad67edc48c79
6
public int[] remplissageMax(){ int positionMax = 0; // On veut bien commencer par la premiere case non null // pour ne pas avoir des problemes a la comparaison plus tard for (int i=0; i<table.length; i++) if (table[i] != null){ positionMax = i; break; // Interrempre la boucle for } /* Dans le cas ou tout la TableDeHachage est vide * l'index positionMax sera surement ==0 * et la Liste associee surement null ! */ if ( table[positionMax] == null ) return new int[] {0, 0}; else { for (int i=positionMax+1; i<table.length; i++) if (table[i]!=null) // Eviter NullPointerException ! if (table[i].longueur() > table[positionMax].longueur()) positionMax = i; return new int[] {positionMax, table[positionMax].longueur()}; } }
997bf6ad-256f-4e53-967b-4d3ba29a3c6e
6
private void getRoom(Element roomElement) { String spriteName=roomElement.getAttribute("sprite"); String name=getTextValue(roomElement,"name"); String description=getTextValue(roomElement,"description"); String backgroundLayer=getTextValue(roomElement, "background"); String objectLayer=getTextValue(roomElement,"object"); SerializableBufferedImage sprite = new SerializableBufferedImage(spriteName); //Create a new Room with the value read from the xml nodes Room2D room = new Room2D(description,sprite); room.setBackground(backgroundLayer); room.setObjectLayer(objectLayer); rooms.put(name, room); //get a nodelist of item elements NodeList nl = roomElement.getElementsByTagName("item"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { //get the item element Element el = (Element)nl.item(i); //get the Item object Item item = getItem(el); room.drop(item); } } //get a nodelist of monster elements nl = roomElement.getElementsByTagName("monster"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { //get the item element Element el = (Element)nl.item(i); //get the Monster object Monster monster = getMonster(el); room.addMonster(monster); } } }
a106e9b7-fee2-46ac-9df4-cb452900bb3f
3
public static void polygon(boolean fill, double... points) { int[] xPoints = new int[points.length / 2]; int[] yPoints = new int[points.length / 2]; for (int i = 0; i < points.length; i ++) { if (i % 2 == 0) { xPoints[i/2] = (int)points[i]; } else { yPoints[i/2] = (int)points[i]; } } if (fill) { graphics.fillPolygon(xPoints, yPoints, xPoints.length); } else { graphics.drawPolygon(xPoints, yPoints, xPoints.length); } }
b1073eb6-c4b6-4d22-b90c-f85f0541a642
8
public static String cleanPath(String path) { if (path == null) { return null; } String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. int prefixIndex = pathToUse.indexOf(":"); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); pathToUse = pathToUse.substring(prefixIndex + 1); } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; pathToUse = pathToUse.substring(1); } String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); List<String> pathElements = new LinkedList<String>(); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { String element = pathArray[i]; if (CURRENT_PATH.equals(element)) { // Points to current directory - drop it. } else if (TOP_PATH.equals(element)) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with element corresponding to top path. tops--; } else { // Normal path element found. pathElements.add(0, element); } } } // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.add(0, TOP_PATH); } return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); }
b28417dd-5b94-4664-a461-4d093c2967c2
6
public Boolean checkBalance(privAVLNode x) { if(x == null) return true; int bal = 0; if(x.getChild(0) != null) bal = x.getChild(0).getHeight()+1; if(x.getChild(1) != null) bal = bal-(x.getChild(1).getHeight()+1); if(!(bal==-1 || bal==0 || bal==1)) return false; return true; }
1222e763-d9e0-4d66-8eee-c17484da846a
3
public static boolean resetSeason() { File f = new File(pathGame); f.delete(); File fB = new File(pathBonus); fB.delete(); List<User> users=GameData.getCurrentGame().getAllUsers(); File fUser; //remove all of users previous answers for(User u:users){ fUser = new File(pathUserAnswer+u.getID()+".dat"); if(fUser.exists()) fUser.delete(); } return (f.exists() && fB.exists()); }
9604c8b7-1a5e-4a91-9cae-8cb0c4bb1242
5
public void update() { if (end) gsm.setState(lastState); handleInput(); ticks++; if (ticks > wait) { if (speed == 0) pos--; else if (ticks % speed == 0) pos--; } if ((pos + line(8) + (lineGap / 2)) < 0) end = true; }
1fbcd55c-04d4-41c8-a408-86631a6a1a05
8
private static Normalization determineNormalization(Element model) { Normalization normMethod = Normalization.NONE; String normName = model.getAttribute("normalizationMethod"); if (normName.equals("simplemax")) { normMethod = Normalization.SIMPLEMAX; } else if (normName.equals("softmax")) { normMethod = Normalization.SOFTMAX; } else if (normName.equals("logit")) { normMethod = Normalization.LOGIT; } else if (normName.equals("probit")) { normMethod = Normalization.PROBIT; } else if (normName.equals("cloglog")) { normMethod = Normalization.CLOGLOG; } else if (normName.equals("exp")) { normMethod = Normalization.EXP; } else if (normName.equals("loglog")) { normMethod = Normalization.LOGLOG; } else if (normName.equals("cauchit")) { normMethod = Normalization.CAUCHIT; } return normMethod; }
3197a487-e509-4904-8638-843c65a107e1
4
public void addCarEventCount(int count) { if(count < 0) count = 0; if(carEvents.getSize() == 0) { carEventMin = count; carEventMax = count; } else { if(count < carEventMin) carEventMin = count; if(count > carEventMax) carEventMax = count; } carEvents.addDataPoint(count); }
c7fb4034-88f2-4a3d-8c88-626f57859a5e
4
private void update() { if(menu==null){ if(story==null){ lvl.update(inHandler); long timeElapsed = System.currentTimeMillis() - oldTime; // System.out.println(timeElapsed); if (timeElapsed < 40) { try { Thread.sleep((long) 40 - timeElapsed); // ~25 updates per second } catch (InterruptedException e) { System.out.println("Couldn't start sleeping:" + e); e.printStackTrace(); } } oldTime = System.currentTimeMillis(); }else { story.update(this,inHandler); } }else{ menu.update(this, inHandler); } }
51422f3e-dbd0-45ec-9df9-a9cf1adef3c6
2
String readFile(String fileName) { File file = new File(fileName); if (!file.exists()) fatalError("No such file '" + fileName + "'"); if (!file.canRead()) fatalError("Cannot open file '" + fileName + "'"); return Gpr.readFile(fileName); }
89bbb758-50d4-457d-927f-f79a1b8ea572
7
@Override public int compareTo(Card o) { if (o == null) { throw new NullPointerException(); } if (getSorting() == o.getSorting()) { int sign = Main.ascending ? 1 : -1; if (rank == 1 && o.rank != 1) { return sign; } else if (o.rank == 1 && rank != 1) { return -sign; } return sign * Integer.compare(rank, o.getRank()); } else { return Integer.compare(getSorting().order, o.getSorting().order); } }
dcc1197c-d6ac-4c02-8e73-bd2d00102265
3
public static void Read(String book) { if(!book.startsWith("Book:")) { book = "Book:" + book; } for(int j=0; j<Inventory.length; j++) { if(GetItemName(Inventory[j]).equalsIgnoreCase(book)) { GUI.log(Books.getName(Inventory[j]) + "\n~~~~\n" + Books.getBook(Inventory[j])); break; } } }
bb7b9c52-0135-4336-ba0b-9ef3fa5b94e0
3
public ResultSet retrieveStockData() throws SQLException { try { databaseConnector = medicineConnector.getConnection(); stmnt = databaseConnector.createStatement(); SQLQuery = "SELECT * FROM familydoctor.medicine"; dataSet = stmnt.executeQuery(SQLQuery); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (stmnt != null) { stmnt.close(); } if (databaseConnector != null) { databaseConnector.close(); } } return dataSet; }
ffcbc899-6a02-48e4-9dd8-f0aaa6a0f09b
9
public void updateStatus(Object obj) { Space p = (Space) obj; if (spaceObj_.getName() == p.getName()) { spaceObj_ = p; String status = ""; status += spaceObj_; bg_pic.setToolTipText(status); if (spaceObj_ instanceof PropertySpace) { PropertySpace propSpace = (PropertySpace) obj; //System.out.println("reached updateStatus"); Player tempPlayer = propSpace.getOwner(); if (tempPlayer == null) { } else { int ownerIndex = propSpace.getOwner().getIndex(); int level = propSpace.getState().getLevel(); if ((propSpace.getType().equals("Purple")) || (propSpace.getType().equals("Light Blue"))) { level = level + 1; } if ((propSpace.getType().equals("Brown")) || (propSpace.getType().equals("Orange"))) { level = level + 2; } if ((propSpace.getType().equals("Red")) || (propSpace.getType().equals("Yellow"))) { level = level + 3; } updateSpaceFilling(level, ownerIndex); } //TODO // //System.out.println("property space: " + status); } else { // System.out.println("normal space: " + status); } } }
30e75ca0-5740-4ecc-b996-ca678abf0916
2
public PlayerPanel(Player p) { this.player = p; this.hand = this.player.getHand(); this.books = this.player.getBooks(); this.playerName = new JLabel(p.getName()); this.add(this.playerName); // Add the player's books to the panel BookStack bs; for (int i = 0; i < this.books.size(); i++) { bs = new BookStack(this.books.get(i).getBookNum()); this.add(bs); } // Add the player's cards to the panel ArrayList<Card> cards = hand.getList(); for (int i = 0; i < cards.size(); i++) { this.add(cards.get(i)); } this.setBackground(new Color(127, 226, 255)); }
e938bb68-9bf6-4a51-bbf0-bd1357832983
6
@Override public void processPacket(Client c, int packetType, int packetSize) { int itemId = c.getInStream().readSignedWordA(); if (!c.getItems().playerHasItem(itemId,1)) return; switch (itemId) { case 11694: c.getItems().deleteItem(itemId,1); c.getItems().addItem(11690,1); c.getItems().addItem(11702,1); c.sendMessage("You dismantle the godsword blade from the hilt."); break; case 11696: c.getItems().deleteItem(itemId,1); c.getItems().addItem(11690,1); c.getItems().addItem(11704,1); c.sendMessage("You dismantle the godsword blade from the hilt."); break; case 11698: c.getItems().deleteItem(itemId,1); c.getItems().addItem(11690,1); c.getItems().addItem(11706,1); c.sendMessage("You dismantle the godsword blade from the hilt."); break; case 11700: c.getItems().deleteItem(itemId,1); c.getItems().addItem(11690,1); c.getItems().addItem(11708,1); c.sendMessage("You dismantle the godsword blade from the hilt."); break; default: if (c.playerRights == 3) Misc.println(c.playerName+ " - Item3rdOption: "+itemId); break; } }
ed674d18-38a6-40df-94b7-b7946a774259
1
public void testConstructor_long_long3() throws Throwable { DateTime dt1 = new DateTime(2005, 7, 10, 1, 1, 1, 1); DateTime dt2 = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { new MutableInterval(dt1.getMillis(), dt2.getMillis()); fail(); } catch (IllegalArgumentException ex) {} }
7b26e898-7322-4fa4-a053-2ae4a5463582
2
@SuppressWarnings("empty-statement") public JDialog initJdAdd() { jd_add = new JDialog(this); jd_add.setModal(true); if (temp == false) { jd_add.setTitle("添加键值对"); } else { jd_add.setTitle("编辑键值对"); } jd_add.setLayout(null); // jd_add.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jd_add.getContentPane().setPreferredSize(new Dimension(240, 140)); jd_add.pack(); jd_add.setLocationRelativeTo(null); jd_add.setResizable(false); // jd_add.setModal(true); // jd_add.setBorder(BorderFactory.createTitledBorder("添加键值对")); jp_input = new JPanel(new GridLayout(2, 2)); jl_key = new JLabel("Key:"); jl_value = new JLabel("Value:"); jf_key = new JTextField(10); jf_value = new JTextField(10); jp_input.add(jl_key); jp_input.add(jf_key); jp_input.add(jl_value); jp_input.add(jf_value); if (temp == true) { jf_key.setEditable(false); } jp_input.setBounds(10, 10, 230, 80); btn_ok = new JButton("Ok"); btn_ok.setBounds(50, 110, 80, 30); btn_ok.addActionListener(new Add_Listener(this, jlang)); btn_cancel = new JButton("Cancel"); btn_cancel.setBounds(140, 110, 80, 30); btn_cancel.addActionListener(new Add_Listener(this, jlang));; jd_add.add(jp_input); jd_add.add(btn_ok); jd_add.add(btn_cancel); // jd_add.setVisible(true); return jd_add; }
d16e5e43-0c4b-400e-82e4-157865bccfab
2
@Override public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) { if (!Commands.isPlayer(sender)) return false; Player p = (Player) sender; if (args.length != 1) return false; channel.removeChannel(p, args[0]); return true; }
78679942-a04a-4a26-8b4d-f191b5df912d
5
public void removeIrrelevantArtists() throws SQLException { List<Integer> nonPersonnel = new LinkedList<Integer>(); String sql = "select * from artist LEFT JOIN personnel ON artist_id = artistnumber WHERE artistnumber IS NULL"; PreparedStatement ps = Connect.getConnection().getPreparedStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { Integer val = rs.getInt(1); nonPersonnel.add(val); } rs.close(); ps.close(); System.out.println("Found " + nonPersonnel.size() + " non personnel artists"); List<Integer> nonGroups = new LinkedList<Integer>(); String sql2 = "select * from artist LEFT JOIN lineupdetails ON artist_id = artistnumber WHERE artistnumber IS NULL"; PreparedStatement ps2 = Connect.getConnection().getPreparedStatement(sql2); ResultSet rs2 = ps2.executeQuery(); while (rs2.next()) nonGroups.add(rs2.getInt(1)); rs.close(); ps.close(); System.out.println("Found " + nonGroups.size() + " non group artists"); List<Integer> overall = new LinkedList<Integer>(); for (Integer intV : nonPersonnel) if (nonGroups.contains(intV)) overall.add(intV); System.out.println("Found " + overall.size() + " artists to be deleted"); for (Integer value : overall) { Artist art = GetArtists.create().getArtist(value); System.out.println("Deleting " + art.getShowName()); GetArtists.create().deleteArtist(art); } }
794bbb81-6a10-4204-a6a0-e084aaf03dda
2
public void HangupBridgeCalls(){ Iterator<Entry<CallFrame, List<String>>> bridgeIterator = bridgeLines.entrySet().iterator(); while (bridgeIterator.hasNext()) { Entry<CallFrame, List<String>> entry = bridgeIterator.next(); List<String> bridgeList = (List<String>) entry.getValue(); if(bridgeList.get(0).startsWith(Phone.MainExtension)) { PrintWriter writer = MainFrame.TelnetWriter(); writer.print("Action: Hangup\r\n"); writer.print("Channel: SIP/" + bridgeList.get(0) + "\r\n\r\n"); writer.flush(); bridgeIterator.remove(); removeFromList(((CallFrame) entry.getKey())); ((CallFrame) entry.getKey()).setVisible(false); ((CallFrame) entry.getKey()).dispose(); } } }
114cd470-49b0-40e7-911f-c9651aeb3254
2
public static int search_function_by_name(Function_table function_table, String name) { int num = function_table.function_name.size(); for (int i = 0; i < num; i++) { if (function_table.function_name.get(i).toString().equals(name)) { return i; } } return -1; }
741cc140-c885-4105-9e5a-fa1cee6e817d
8
private void formLine(boolean create, int playBookNumber, int setNumber, int formationNumber, int playNumber, Connection database, PrintWriter webPageOutput) { String disabledText=""; String selectText=""; disabledText="DISABLED "; if(!create) { selectText="CHECKED "; } try { Statement sql=database.createStatement(); ResultSet queryResult; Routines.tableDataStart(true,false,false,true,false,5,0,"scoresrow",webPageOutput); webPageOutput.print("<INPUT TYPE=\"CHECKBOX\" NAME=\"" + playBookNumber + "\" VALUE=\"true\" " + selectText + " " + disabledText + ">"); Routines.tableDataEnd(false,false,false,webPageOutput); Routines.tableDataStart(true,false,false,false,false,20,0,"scoresrow",webPageOutput); webPageOutput.println("<SELECT NAME=\"setNumber\">"); queryResult=sql.executeQuery("SELECT SetNumber,SetName " + "FROM defaultsets " + "ORDER BY SetNumber ASC"); int tempSetNumber=0; String setName=""; while(queryResult.next()) { tempSetNumber=queryResult.getInt(1); setName=queryResult.getString(2); if(setNumber==tempSetNumber) { selectText="SELECTED "; } else { selectText=""; } webPageOutput.println(" " + "<OPTION " + selectText + "VALUE=\"" + tempSetNumber + "\">" + setName); } Routines.tableDataEnd(false,false,false,webPageOutput); Routines.tableDataStart(true,false,false,false,false,45,0,"scoresrow",webPageOutput); webPageOutput.println("<SELECT NAME=\"FormPlay\">"); queryResult=sql.executeQuery("SELECT defaultformations.FormationNumber,FormationName,PlayNumber,PlayName " + "FROM defaultformations,defaultplays " + "WHERE defaultformations.FormationNumber=defaultplays.FormationNumber " + "AND defaultformations.Defense=1 " + "ORDER BY defaultformations.FormationNumber ASC, defaultplays.PlayNumber ASC"); int tempFormationNumber=0; int tempPlayNumber=0; String formationName=""; String playName=""; int selection=0; while(queryResult.next()) { selection++; tempFormationNumber=queryResult.getInt(1); formationName=queryResult.getString(2); tempPlayNumber=queryResult.getInt(3); playName=queryResult.getString(4); if(formationNumber==tempFormationNumber&& playNumber==tempPlayNumber) { selectText="SELECTED "; } else { selectText=""; } webPageOutput.println(" " + "<OPTION " + selectText + "VALUE=\"" + selection + "\">" + formationName + " formation, " + playName); } selection=0; queryResult.beforeFirst(); while(queryResult.next()) { selection++; tempFormationNumber=queryResult.getInt(1); tempPlayNumber=queryResult.getInt(3); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"formation" + selection + "\" VALUE=\"" + tempFormationNumber + "\">"); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"play" + selection + "\" VALUE=\"" + tempPlayNumber + "\">"); } Routines.tableDataEnd(false,false,false,webPageOutput); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"playBookNumber\" VALUE=\"" + playBookNumber + "\">"); } catch(SQLException error) { Routines.writeToLog(servletName,"Unable to find playbook entries : " + error,false,context); } }
ec84b2f1-d510-48c1-a423-7228dfd1870f
5
public void paint( Graphics g ){ super.paint(g); // actualizamos dimensiones int cantAtr = getSizeAtributos(); int cantMet = getSizeMetodos(); int px=this.getX(); int py=this.getY(); int w=this.getWidth(); int h=this.getHeight(); // pintamos el relleno g.setColor(new Color(81, 237, 255)); g.fill3DRect( px, py, w, h, true ); // luego pintamos los contornos g.setColor(Color.black); g.draw3DRect( px, py, w, tamLetra+yn, true ); int y = (2*tamLetra) + (2*yn); int size = getSizeAtributos(); if (size>0) y = y + ((size-1)*tamLetra) + (size*yn) + yn; g.draw3DRect( px, py, w, y, true ); // nos preguntamos antes si esta seleccionado esta clase if ( this.isSelect() ) g.setColor( this.getColorSelect() ); else g.setColor( this.getColorNormal() ); g.draw3DRect( px, py, w, h, true ); g.setColor(Color.black); g.setFont( new Font("Times New Rooman",Font.BOLD, tamLetra) ); g.drawString( clase.getNombre(), px+(w/7), py+tamLetra ); y = (2*yn) + tamLetra; y = y + py; LinkedList<Atributo> la=clase.getListaAtributos(); for ( int i = 0 ; i<cantAtr ; i++ ) { Atributo a = la.get(i); y = y + yn + tamLetra; g.drawString( a.toStringGrafico(), px+2, y ); } if ( cantAtr>0 ){ y = ((2*yn)+ (tamLetra*2))+((cantAtr-1)*tamLetra)+(cantAtr*yn)+yn; }else{ y = (2*yn)+ (tamLetra*2); } y = y + py; LinkedList<Metodo> lm=clase.getListaMetodos(); for ( int i = 0 ; i<cantMet ; i++ ) { Metodo m = lm.get(i); y = y + yn + tamLetra; g.drawString( m.toStringGrafico(), px+2, y ); } }
6b5168a3-f705-4ad2-abbd-ea279b03007a
5
public void click(Point loc) { Rectangle[] rects = buildHeaders(); for (int i = 0; i < rects.length; i++) { if (rects[i].contains(loc)) { if (i == defaultTab) defaultTab = -1; else defaultTab = i; break; } } if (curTab != -1) { Rectangle rect = getMainRect(curTab); if (rect.contains(loc)) { tabs.get(curTab).click(new Point(loc.x - rect.x, loc.y - rect.y)); } } }