text
stringlengths
14
410k
label
int32
0
9
private void CompileShader() { glLinkProgram(m_resource.GetProgram()); if(glGetProgrami(m_resource.GetProgram(), GL_LINK_STATUS) == 0) { System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); System.exit(1); } glValidateProgram(m_resource.GetProgram()); if(glGetProgrami(m_resource.GetProgram(), GL_VALIDATE_STATUS) == 0) { System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); System.exit(1); } }
2
@SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (obj instanceof Tuple<?,?>) { if(x.equals(((Tuple<X,Y>)obj).x) && y.equals(((Tuple<X,Y>)obj).y)) { return true; } } return false; }
5
public void action(Player player, boolean doublePay) { if(getOwner() != null && !player.equals(getOwner()) && doublePay && !isInMortgage()) { player.pay(getBill(player) * 2); getOwner().addMoney(getBill(player) * 2); } else { action(player); } }
4
public MaxAmountIterableClass() { IterableWithAnnot = new ArrayList<String>(); IterableWithoutAnnot = new ArrayList<String>(); int i = 0; while (i < 6) { IterableWithAnnot.add("e" + i); IterableWithoutAnnot.add(i, "e" + i); i++; } }
1
public OMLFileFormat() { super(); }
0
public static String formatDurationWords( long durationMillis, boolean suppressLeadingZeroElements, boolean suppressTrailingZeroElements) { // This method is generally replacable by the format method, but // there are a series of tweaks and special cases that require // trickery to replicate. String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'"); if (suppressLeadingZeroElements) { // this is a temporary marker on the front. Like ^ in regexp. duration = " " + duration; String tmp = StringUtils.replaceOnce(duration, " 0 days", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 hours", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 minutes", ""); duration = tmp; if (tmp.length() != duration.length()) { duration = StringUtils.replaceOnce(tmp, " 0 seconds", ""); } } } if (duration.length() != 0) { // strip the space off again duration = duration.substring(1); } } if (suppressTrailingZeroElements) { String tmp = StringUtils.replaceOnce(duration, " 0 seconds", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 minutes", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 hours", ""); if (tmp.length() != duration.length()) { duration = StringUtils.replaceOnce(tmp, " 0 days", ""); } } } } // handle plurals duration = " " + duration; duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second"); duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute"); duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour"); duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day"); return duration.trim(); }
9
private void addCatchers(BasicBlock[] blocks, ExceptionTable et) throws BadBytecode { if (et == null) return; int i = et.size(); while (--i >= 0) { BasicBlock handler = find(blocks, et.handlerPc(i)); int start = et.startPc(i); int end = et.endPc(i); int type = et.catchType(i); handler.incoming--; for (int k = 0; k < blocks.length; k++) { BasicBlock bb = blocks[k]; int iPos = bb.position; if (start <= iPos && iPos < end) { bb.toCatch = new Catch(handler, type, bb.toCatch); handler.incoming++; } } } }
5
public void loadGame(JFrame frame) { JFileChooser fileChooser = new JFileChooser("."); int result = fileChooser.showOpenDialog(frame); if (result == JFileChooser.APPROVE_OPTION) { try { FileInputStream fis = new FileInputStream( fileChooser.getSelectedFile()); ObjectInputStream inStream = new ObjectInputStream(fis); controller.setCellsFromLoad((String) inStream.readObject()); inStream.close(); } catch (IOException e) { createErrorMessage(e, frame); } catch (ClassNotFoundException e) { createErrorMessage(e, frame); } catch (IndexOutOfBoundsException e) { createErrorMessage(e, frame); } catch (Exception e) { //in case there is an unexpected exception createErrorMessage(e, frame); } } }
5
public void applyNews(){ News item = news.pop(); appliedNews.add(item); String[] tags = item.getTags(); for (int i = 0; i < tags.length; i++){ String searching = tags[i]; for (int j = 0; j < stocks.size(); j++){ Stock checking = stocks.get(j); String tick = checking.getTicker(); if (searching.equals(tick)){ checking.applyNews(item); // stock's applyNews method break; } } } }
3
public void sortBySuit() { ArrayList newHand = new ArrayList(); while (hand.size() > 0) { int pos = 0; // Position of minimal card. Card c = (Card)hand.get(0); // Minimal card. for (int i = 1; i < hand.size(); i++) { Card c1 = (Card)hand.get(i); if ( c1.getSuit() < c.getSuit() || (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) { pos = i; c = c1; } } hand.remove(pos); newHand.add(c); } hand = newHand; }
5
public static String complete(String main, int start) { String[] args = main.split(" "); StringBuilder string = new StringBuilder(); for (int i = start; i < args.length; i++) { string.append(args[i] + " "); } return string.toString().substring(0, string.length() - 1); }
1
public int get (K key, int defaultValue) { int hashCode = key.hashCode(); int index = hashCode & mask; if (!key.equals(keyTable[index])) { index = hash2(hashCode); if (!key.equals(keyTable[index])) { index = hash3(hashCode); if (!key.equals(keyTable[index])) return getStash(key, defaultValue); } } return valueTable[index]; }
3
public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String b = in.nextLine().trim(); if (b.equals("0") ) break; int sum = 0; for(int i = 0;i < b.length();i++) { sum += (b.charAt(i) - '0'); } while ( sum >= 10 ) { int a = sum % 10; while(sum >= 10 ) { sum/=10; a+=(sum%10); } sum=a; } System.out.println(sum); } }
5
protected void handleView(final View view) { List<Address> new_mbrs=null; if(local_view != null) new_mbrs=Util.newMembers(local_view.getMembers(), view.getMembers()); local_view=view; coord=view.getMembers().iterator().next(); boolean create_bridge=false; boolean is_new_coord=Util.isCoordinator(view, local_addr); if(is_coord) { if(!is_new_coord) { if(log.isTraceEnabled()) log.trace("I'm not coordinator anymore, closing the channel"); Util.close(bridge); is_coord=false; bridge=null; } } else if(is_new_coord) is_coord=create_bridge=true; if(is_coord) { // need to have a local view before JChannel.connect() returns; we don't want to change the viewAccepted() semantics sendViewOnLocalCluster(remote_view, generateGlobalView(view, remote_view, view instanceof MergeView), true, new_mbrs); if(create_bridge) createBridge(); sendViewToRemote(ViewData.create(view, null), false); } }
7
Deserializer_3(@SuppressWarnings("hiding") final SongData sdc) { super(sdc); final String entry = this.idx.getFilename().replace(".idx", "") .replace(".zip", ""); this.inFile = this.idx.resolve("..", entry); this.tmp = this.idx.getParent().resolve(entry + ".tmp"); final Set<String> zip = this.io.openZipIn(this.idx); if ((zip == null) || !zip.contains(entry)) { if (this.tmp.exists()) { this.tmp.renameTo(this.inFile); this.in = this.io.openIn(this.inFile.toFile()); } else { this.in = null; } } else { this.in = this.io.openIn(this.inFile.toFile()); } if (!this.tmp.getParent().exists()) { this.out = null; } else { this.out = this.io.openOut(this.tmp.toFile()); this.io.write(this.out, VERSION); } }
4
public void learn(DataPoint dp) { /* Properly set all neurons. */ /* Calculate the constant part of the derivative. */ double precomputed = 2*(dp.getExpected() - outputNeuron.evaluate()); /* Modify weights. */ outputNeuron.setBias(outputNeuron.getBias()+ alpha*precomputed); for(Neuron i : inputNeurons) { outputNeuron.setWeight(i, outputNeuron.getWeight(i)+ alpha*precomputed*i.evaluate()); } }
1
public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); }
3
public void update(int delta, boolean onBeat, int bpm) { if (onBeat) { lastFire++; if (lastFire % beatsPerEmission == 0) { if (projectileCount == 1) { projectiles.add(emitProjectile(bpm, directionMin)); } else { int dirDiff = (directionMax - directionMin) / projectileCount; for (int i = 0; i < projectileCount; i++) { projectiles.add(emitProjectile(bpm, dirDiff * i)); } } lastFire = 0; } } }
4
public static String getVariableType(String s) { s = s.toLowerCase(); if (s.equals("i")) { return "int"; } else if (s.equals("l")) { return "long"; } else if (s.equals("s")) { return "short"; } else if (s.equals("b")) { return "byte"; } else if (s.equals("c")) { return "char"; } else if (s.equals("f")) { return "float"; } else if (s.equals("d")) { return "double"; } else if (s.equals("v")) { return "void"; } //if its not one of the above, it's an object reference, so just return the original return s; }
8
public void delete() { if(isReadOnly()) return; try { fdbf.seek( recordpos() ); } catch (IOException e) {} writeChars(0,1,"*"); deleted = true; }
2
private boolean generate(Painter painter, int resolutionX, int resolutionY, String filename, String imgformat) { // create a buffered image object using RGB+A pixel format BufferedImage image = new BufferedImage(resolutionX, resolutionY, BufferedImage.TYPE_INT_ARGB); // Set a color for each pixel. Y pixel indices are flipped so that the origin (0,0) // is at the bottom left of the image. for (int i = 0; i < resolutionX; i++) for (int j = 0; j < resolutionY; j++) image.setRGB( i, j, painter.pixelColorAt(i, resolutionY-j-1, resolutionX, resolutionY).toAwtColor() ); // Write the image to disk. try { File file = new File(filename); ImageIO.write(image, imgformat, file); } catch (IOException e) { e.printStackTrace(); return false; } // success return true; }
3
public void save() { try { sql.Query.save(this); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
2
public static Supply createRandomSupply(Position pos){ Supply s; int random=(int) (Math.random()*100); if (random<33){ s=createRandomAmmo(pos); } else if (random < 66){ s=createRandomFood(pos); } else { s=createRandomHealth(pos); } return s; }
2
@EventHandler private void onInventoryClickEvent(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); //Make sure that the player is being watched before continuing if (!InventoryMenuManager.isPlayerWatched(player)) return; //Cancel the event to prevent players from adding/removing items to the menu event.setCancelled(true); //Get the menu we should be watching for InventoryMenu im = InventoryMenuManager.getWatchedMenu(player); //Make sure that the menu exists before continuing if (im == null) return; //Make sure that we have the right inventory before continuing if (!im.getTitle().equals(event.getInventory().getTitle())) return; if (event.getClick() == ClickType.LEFT || event.getClick() == ClickType.RIGHT) { //Get the matching option for the event, via the clicked item Option o = im.matchOption(event.getCurrentItem()); //Make sure the option exists before continuing if (o != null) { //Execute the option's code and close the menu o.execute(player); event.getWhoClicked().closeInventory(); } } }
6
private boolean check(int row, int col, int[][] columnForRow) { for (int i = 0; i < row; i++) if (columnForRow[i][col] == 1) return false; // 右对角线(只需要判断对角线上半部分,因为后面的行还没有开始放置) for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) if (columnForRow[i][j] == 1) return false; // 左对角线(只需要判断对角线上半部分,因为后面的行还没有开始放置) for (int i = row - 1, j = col + 1; i >= 0 && j < columnForRow.length; i--, j++) if (columnForRow[i][j] == 1) return false; return true; }
8
@EventHandler public void onDeath(PlayerDeathEvent e) { Player p = e.getEntity(); if (p.getKiller() instanceof Player) { Player killer = p.getKiller(); if (CTF.gm.isPlaying(p)) { p.setFireTicks(0); p.setHealth(20.0); CTF.lh.teleportPlayerToTeamSpawn(p, CTF.tm.getTeam(p)); e.setDeathMessage(""); CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2was killed by §r" + CTF.tm.getPlayerNameInTeamColor(killer) + "§2!"); p.setGameMode(GameMode.ADVENTURE); } } else { if (CTF.gm.isPlaying(p)) { p.setFireTicks(0); p.setHealth(20.0); CTF.lh.teleportPlayerToTeamSpawn(p, CTF.tm.getTeam(p)); e.setDeathMessage(""); CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2died!"); p.setGameMode(GameMode.ADVENTURE); } } if (CTF.fm.hasFlag(p)) { Team flag = CTF.fm.getFlag(p); for (PotionEffect effect : p.getActivePotionEffects()) { p.removePotionEffect(effect.getType()); } if (flag==Team.RED) { CTF.fm.getRedFlagSpawn().getBlock().setType(Material.WOOL); CTF.fm.getRedFlagSpawn().getBlock().setData(DyeColor.RED.getData()); CTF.fm.removeFlag(p); CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2dropped the §cRed flag§9!"); } else if (flag==Team.BLUE) { CTF.fm.getBlueFlagSpawn().getBlock().setType(Material.WOOL); CTF.fm.getBlueFlagSpawn().getBlock().setData(DyeColor.BLUE.getData()); CTF.fm.removeFlag(p); CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2dropped the Blue flag!"); } } }
7
private boolean aDown(int x){ boolean ret = false; for (int i =3; i > 0 ; i--){ if (grid.get(i).get(x) != null && grid.get(i-1).get(x)!= null){ if (grid.get(i).get(x).getValue() == grid.get(i-1).get(x).getValue()){ //ADDING grid.get(i).get(x).addValue(grid.get(i-1).get(x).getValue()); //NULLING grid.get(i-1).set(x, null); ret = true; } } } if (ret){ for (int i=3; i > -1 ; i --){ mDown(x, i); } } return ret; }
6
private TableColumn<Object, ?> getNextColumn(boolean forward) { List<TableColumn<Object, ?>> columns = new ArrayList<>(); for (TableColumn<Object, ?> column : getTableView().getColumns()) { columns.addAll(getLeaves(column)); } //There is no other column that supports editing. if (columns.size() < 2) { return null; } int currentIndex = columns.indexOf(getTableColumn()); int nextIndex = currentIndex; if (forward) { nextIndex++; if (nextIndex > columns.size() - 1) { nextIndex = 0; } } else { nextIndex--; if (nextIndex < 0) { nextIndex = columns.size() - 1; } } return columns.get(nextIndex); }
8
private long getPosition(int length){ long bestPos = 0; int bestLeng = 0; for (Long pos : freePointers.keySet()){ int leng = freePointers.get(pos); if (length <= leng){ if (bestLeng == 0 || bestLeng > leng){ bestLeng = leng; bestPos = pos; } } } if (bestPos == 0) bestPos = dataStorage.length(); return bestPos; }
5
public void setCharacter(int character) { this.character = character; }
0
public void putAll(Map other) { if (!(other instanceof CoordinateMap)) return; CoordinateMap coords = (CoordinateMap) other; if (!this.ofSameType(coords)) return; for (CoordinateEntry entry : coords.data) this.put(entry); }
3
public static void main(String[] args) { try { ////////////////////////////////////////// // Step 1: Initialize the GridSim package. It should be called // before creating any entities. We can't run this example without // initializing GridSim first. We will get run-time exception // error. // number of grid user entities + any Workload entities. int num_user = 5; Calendar calendar = Calendar.getInstance(); boolean trace_flag = false; // mean trace GridSim events // Initialize the GridSim package without any statistical // functionalities. Hence, no GridSim_stat.txt file is created. System.out.println("Initializing GridSim package"); GridSim.init(num_user, calendar, trace_flag); ////////////////////////////////////////// // Step 2: Creates one or more GridResource entities int totalResource = 2; // total number of Grid resources int rating = 100; // rating of each PE in MIPS int totalPE = 1; // total number of PEs for each Machine int totalMachine = 1; // total number of Machines int i = 0; String[] resArray = new String[totalResource]; for (i = 0; i < totalResource; i++) { String resName = "Res_" + i; createGridResource(resName, rating, totalMachine, totalPE); // add a resource name into an array resArray[i] = resName; } ////////////////////////////////////////// // Step 3: Get the list of trace files. The format should be: // ASCII text, gzip or zip. // In this example, I use the trace files from: // http://www.cs.huji.ac.il/labs/parallel/workload/index.html String[] fileName = { "l_lanl_o2k.swf.zip", // LANL Origin 2000 Cluster (Nirvana) "l_sdsc_blue.swf.txt.gz", // SDSC Blue Horizon }; String dir = "../"; // location of these files String customFile = "custom_trace.txt"; // custom trace file format // total number of Workload entities int numWorkload = fileName.length + 1; // including custom trace ////////////////////////////////////////// // Step 4: Creates one or more Workload trace entities. // Each Workload entity can only read one trace file and // submit its Gridlets to one grid resource entity. int resID = 0; Random r = new Random(); ArrayList load = new ArrayList(); for (i = 0; i < fileName.length; i++) { resID = r.nextInt(totalResource); Workload w = new Workload("Load_"+i, dir + fileName[i], resArray[resID], rating); // add into a list load.add(w); } // for the custom trace file format Workload custom = new Workload("Custom", dir + customFile, resArray[resID], rating); // add into a list load.add(custom); // tells the Workload entity what to look for. // parameters: maxField, jobNum, submitTime, runTime, numPE custom.setField(4, 1, 2, 3, 4); custom.setComment("#"); // set "#" as a comment ////////////////////////////////////////// // Step 5: Creates one or more grid user entities. // number of grid user entities int numUserLeft = num_user - numWorkload; int totalGridlet = 5; double baud_rate = 100; User[] userList = new User[numUserLeft]; for (i = 0; i < numUserLeft; i++) { User user = new User("User_"+i, baud_rate, totalGridlet); userList[i] = user; } ////////////////////////////////////////// // Step 6: Starts the simulation GridSim.startGridSimulation(); ////////////////////////////////////////// // Final step: Prints the Gridlets when simulation is over // prints the Gridlets inside a Workload entity for (i = 0; i < load.size(); i++) { Workload obj = (Workload) load.get(i); obj.printGridletList(trace_flag); } // prints the Gridlet inside a grid user entity for (i = 0; i < userList.length; i++) { User userObj = userList[i]; userObj.printGridletList(trace_flag); } } catch (Exception e) { e.printStackTrace(); } }
6
public TreeNode findSubTree(int start,int end,int[] array){ if(end - start < 0 ){ return null; } else{ TreeNode root = null; int mid = (start +end) /2; root = new TreeNode(array[mid]); root.left = findSubTree(start,mid-1,array); root.right = findSubTree(mid+1,end,array); return root; } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataWrapper other = (DataWrapper) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }
6
public boolean isValidMove(int startCol, int startRow, int endCol, int endRow) { final int MAXBOUNDS = 8; return ((startRow == endRow && Math.abs(startCol - endCol) <= MAXBOUNDS) || (startCol == endCol && Math.abs(startRow - endRow) <= MAXBOUNDS) || (endCol != startCol && startRow != endRow && (Math.abs(endRow - startRow) == Math.abs(endCol - startCol)))); }
6
private void inputFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_inputFieldFocusGained if ("Type your message here...".equals(inputField.getText()) && inputField.getFont() == fontI) { inputField.setFont(fontD); inputField.setText(""); } inputField.setForeground(new Color(255, 255, 255)); }//GEN-LAST:event_inputFieldFocusGained
2
@Override public void lockFile(FileHandle handle, long byteOffset, long length) throws PathNotFoundException, AccessDeniedException, NotAFileException, UnsupportedFeatureException, AlreadyLockedException { if (hardlinks) { if (RedirectedFileHandle.class.isInstance(handle)) { handle = ((RedirectedFileHandle)handle).getRedirectedFileHandle(); } } if (fileLocking) { FileLock lock = getFileLockWithinOffset(handle.getFilePath(), byteOffset, byteOffset + length); if (lock != null) throw new AlreadyLockedException(); LinkedList<FileLock> list = getFileLockList(handle.getFilePath(), true); list.add(new FileLock(handle, byteOffset, byteOffset + length)); } else innerFs.lockFile(handle, byteOffset, length); }
4
public static DaoFactory getFactory() throws DaoException { if (factory == null) { factory = new XmlDaoFactory(); // factory = Class.forName("org.training.d4.dao.xml.XmlDaoFactory"); } return factory; }
1
private static String before(String s){ //System.out.println("befoe input"+s); int closed=0; int countdownIndex=0; int i=s.length()-1; //gets an xtra char but thts alright i hope for (;i>=0&&countdownIndex==0;i--){ if(s.charAt(i)==']'){ closed++; countdownIndex=i; } } int x=countdownIndex-1; for(;x>=0&&closed>0;x--){ if(s.charAt(x)==']'){ closed++; } if(s.charAt(x)=='['){ closed--; } } //System.out.println("before["+s.substring(x+1,s.length())+"]"); String answer=s.substring(x+1,s.length()); //System.out.println(answer); if(answer.indexOf("not")==-1 && answer.indexOf("is")==-1) return answer; else return before(s.substring(0,x+1)); }
9
private void getCertificate() throws IOException { try { SavingTrustManager tm = openSocketWithCert(); // Try to handshake the socket boolean success = false; try { sslsocket.startHandshake(); success = true; } catch (SSLException e) { sslsocket.close(); } // If we failed to handshake, save the certificate we got and try again if (!success) { // Set up the directory if needed File dir = new File("certs"); if (!dir.isDirectory()) { dir.delete(); dir.mkdir(); } // Reload (default) KeyStore KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); File file = new File(System.getProperty("java.home") + "/lib/security/cacerts"); InputStream in = new FileInputStream(file); ks.load(in, passphrase); // Add certificate X509Certificate[] chain = tm.chain; if (chain == null) throw new Exception("Failed to obtain server certificate chain"); X509Certificate cert = chain[0]; String alias = server + "-1"; ks.setCertificateEntry(alias, cert); // Save certificate OutputStream out = new FileOutputStream("certs/" + server + ".cert"); ks.store(out, passphrase); out.close(); System.out.println("Installed cert for " + server); } } catch (Exception e) { // Hitting an exception here is very bad since we probably won't recover // (unless it's a connectivity issue) // Rethrow as an IOException throw new IOException(e.getMessage()); } }
5
public GameObject getObject(int x, int y) { if (x >= Realm.WORLD_WIDTH || y >= Realm.WORLD_HEIGHT || x < 0 || y < 0){ return null; } return scenobjects[x][y]; }
4
private void setSpots(int r, int c, int spots, String color) { if (!_board.exists(r, c)) { throw error("board does not exist at %d %d", r , c); } if (spots < 0) { throw error("can only set a nonnegative number of spots"); } if (spots <= _board.neighbors(r, c)) { Color player = null; if (spots == 0) { player = WHITE; } else if (color.equalsIgnoreCase("r")) { player = RED; } else if (color.equalsIgnoreCase("b")) { player = BLUE; } _board.set(r, c, spots, player); } else { throw error("invalid request to put %d spots" + " on square %d %d", spots, r, c); } }
6
@Override public void draw(Graphics g){ if (state ==1){ //<editor-fold defaultstate="collapsed" desc="SAT Polygon vs. Circle Test"> cam.applyCamera(g); g.setColor(Color.WHITE.getRGB()); Vector2D point = cam.projectPoint(new Vector2D(Mouse.x, Mouse.y)); if(rect.containsPoint(point))g.setColor(Color.RED.getRGB()); g.drawOval(point.x-2, point.y-2, 4, 4); g.drawRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); newCircle.setPosition(circle.getPosition()); rect.debugDraw(g); rect1.debugDraw(g); circle.debugDraw(g); circle2.debugDraw(g); CollisionResult s; if((s=rect.collides(circle))!=null){ g.setColor(Color.RED.getRGB()); newCircle.setPosition(newCircle.getPosition().add(s.mts)); newCircle.debugDraw(g); } if((s=rect.collides(circle2))!=null){ circle2.setPosition(circle2.getPosition().add(s.mts)); g.drawOval(s.poc[0].x-2,s.poc[0].y-2, 4, 4); } if((s=circle2.collides(circle))!=null){ g.drawLine(circle.getPosition().x, circle.getPosition().y, circle.getPosition().add(s.mts).x, circle.getPosition().add(s.mts).y); g.drawOval(s.poc[0].x-2,s.poc[0].y-2, 4, 4); } if((s=rect.collides(rect1))!=null){ rect1.setPosition(rect1.getPosition().add(s.mts)); for(int i =0; i <s.poc.length; i ++){ if(s.poc[i]!=null) g.drawOval(s.poc[i].x-2,s.poc[i].y-2, 4, 4); } } cam.unApplyCamera(g); g.setColor(new Color(77,77,77).getRGB()); g.fillRect(0, 0, GamePanel.WIDTH, 80); g.setColor(Color.WHITE.getRGB()); g.setFont("Arial",Graphics.BOLD,25); g.drawString("Separating Axis Theorem: Circle vs. Polygon - With Working Camera!", 10, 40); g.setFont("Arial",Graphics.PLAIN,15); g.drawString("W S A D to move the rectangle - Arrow Keys (Up & Down) to rotate", 10, 60); g.drawString("Mouse: " + new Vector2D(Mouse.x, Mouse.y).toString() + " Project: " + point.toString() +" Zoom: " + cam.getZoom(), 10,100); //</editor-fold> } else if (state ==2) { //<editor-fold defaultstate="collapsed" desc="Text Box testing"> g.drawImage(0, 0, ImageLoader.BACKGROUND, GamePanel.WIDTH,GamePanel.HEIGHT); g.setColor(new Color(77,77,77).getRGB()); g.fillRect(0, 0, GamePanel.WIDTH, 80); g.setColor(Color.WHITE.getRGB()); g.setFont("Arial",Graphics.BOLD,25); g.drawString("Text Box Test bench", 10, 40); g.setFont("Arial",Graphics.PLAIN,15); g.drawString("Basic Chat infrastructure - has two text boxes which communicate with each other", 10, 60); //</editor-fold> } }
9
public boolean isEdgeInArea(Point p1, Point p2) { double x1 = p1.getX(); double y1 = p1.getY(); double x2 = p2.getX(); double y2 = p2.getY(); if (x1 > x2) { double temp = x1; x1 = x2; x2 = temp; } if (y1 > y2) { double temp = y1; y1 = y2; y2 = temp; } if (getCenterX() >= x1 && getCenterX() <= x2 && getCenterY() >= y1 && getCenterY() <= y2) { return true; } return false; }
6
public Bank() { setTitle("Bank Application"); //remove all listener that we have first for (ActionListener al : JButton_PerAC.getActionListeners()) { JButton_PerAC.removeActionListener(al); } for (ActionListener al : JButton_CompAC.getActionListeners()) { JButton_CompAC.removeActionListener(al); } for (ActionListener al : JButton_Deposit.getActionListeners()) { JButton_Deposit.removeActionListener(al); } for (ActionListener al : JButton_Withdraw.getActionListeners()) { JButton_Withdraw.removeActionListener(al); } JButton_CompAC.addActionListener(new AddCompanyController()); JButton_PerAC.addActionListener(new AddPersonController()); JButton_Deposit.addActionListener(new DepositController()); JButton_Withdraw.addActionListener(new WithdrawController()); }
4
private int remap(final int var, final Type type) { if (var + type.getSize() <= firstLocal) { return var; } int key = 2 * var + type.getSize() - 1; int size = mapping.length; if (key >= size) { int[] newMapping = new int[Math.max(2 * size, key + 1)]; System.arraycopy(mapping, 0, newMapping, 0, size); mapping = newMapping; } int value = mapping[key]; if (value == 0) { value = newLocalMapping(type); setLocalType(value, type); mapping[key] = value + 1; } else { value--; } if (value != var) { changed = true; } return value; }
4
@Override public void removeItem(String item) { try { fTPConnector.deleteFile(item); items.remove(item); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
1
@Override public void refreshView(Graphics2D g2d) { List<Shape> shapes = shapeManager.getShapes(); for (Shape s : shapes) { if (s instanceof Rectangle) drawRectangle(g2d, (Rectangle)s); if (s instanceof Square) drawSquare(g2d, (Square)s); if (s instanceof Line) drawLine(g2d, (Line)s); if (s instanceof Ellipse) drawEllipse(g2d, (Ellipse)s); if (s instanceof Circle) drawCircle(g2d, (Circle)s); if (s instanceof Triangle) drawTriangle(g2d, (Triangle)s); } if (controller.buttonSelected == ButtonSelected.SELECT && handleManager.isSomethingSelected()) { drawSquare(g2d, handleManager.getUpperLeft()); drawSquare(g2d, handleManager.getUpperRight()); drawSquare(g2d, handleManager.getBottomLeft()); drawSquare(g2d, handleManager.getBottomRight()); } // System.out.println("Number of shapes: " + shapes.size()); }
9
private static void testVarkaDemote(L2PcInstance player) { if (player.isAlliedWithVarka()) { // Drop the alliance (old friends become aggro). player.setAllianceWithVarkaKetra(0); final PcInventory inventory = player.getInventory(); // Drop by 1 the level of that alliance (symbolized by a quest item). for (int i = 7225; i >= 7221; i--) { L2ItemInstance item = inventory.getItemByItemId(i); if (item != null) { // Destroy the badge. player.destroyItemByItemId("Quest", i, item.getCount(), player, true); // Badge lvl 1 ; no addition of badge of lower level. if (i != 7221) player.addItem("Quest", i - 1, 1, player, true); break; } } for (String mission : varkaMissions) { QuestState pst = player.getQuestState(mission); if (pst != null) pst.exitQuest(true); } } }
6
public void setTelefon(String telefon) { this.telefon = telefon; }
0
@Override protected void solidifyComponent() { slots = new Slot[this.getNumSubComponents()]; for (int i = 0; i < slots.length; i++) { slots[i] = new Slot(); slots[i].setSize(componentSize, componentSize); if (this.getSubComponent(i) != null) { slots[i].socket(this.getSubComponent(i)); } } determineOrbits(); for (int c = 0; c < this.getNumSubComponents(); c++) { this.getSubComponent(c).getTracker().setTrackPath(new OrbitTrackerPath(orbits[c/orbitCounts[0]], rotationPref)); } needsAligned = true; }
3
static final void method3230(int[] is, int[] is_1_, int i) { try { anInt9606++; if (is == null || is_1_ == null) { Class348_Sub40_Sub6.aByteArrayArrayArray9134 = null; Class190.anIntArray2552 = null; Class59_Sub2_Sub2.anIntArray8684 = null; } else { Class59_Sub2_Sub2.anIntArray8684 = is; Class190.anIntArray2552 = new int[is.length]; Class348_Sub40_Sub6.aByteArrayArrayArray9134 = new byte[is.length][][]; for (int i_2_ = i; i_2_ < Class59_Sub2_Sub2.anIntArray8684.length; i_2_++) Class348_Sub40_Sub6.aByteArrayArrayArray9134[i_2_] = new byte[is_1_[i_2_]][]; } } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("db.D(" + (is != null ? "{...}" : "null") + ',' + (is_1_ != null ? "{...}" : "null") + ',' + i + ')')); } }
6
public void testGetArg2() { System.out.println("\n**** testGetArg2 ****"); CycAccess cycAccess = null; try { try { if (connectionMode == LOCAL_CYC_CONNECTION) { cycAccess = new CycAccess(testHostName, testBasePort); } else if (connectionMode == SOAP_CYC_CONNECTION) { cycAccess = new CycAccess(endpointURL, testHostName, testBasePort); } else { fail("Invalid connection mode " + connectionMode); } } catch (Throwable e) { fail(StringUtils.getStringForException(e)); } try { CycFort cycAdministrator = cycAccess.getKnownConstantByName("CycAdministrator"); Object obj = cycAccess.getArg2(isa, cycAdministrator); assertNotNull(obj); assertTrue(obj instanceof CycFort || obj instanceof CycList); if (!cycAccess.isOpenCyc()) { final String predName = "scientificName"; final String termName = "Emu"; final String mtName = "AllEnglishValidatedLexicalMicrotheoryPSC"; obj = cycAccess.getArg2(predName, termName, mtName); System.out.println(obj); assertNotNull(obj); CycFort predicate = cycAccess.getKnownConstantByName(predName); CycFort arg1 = cycAccess.getKnownConstantByName(termName); CycFort mt = cycAccess.getKnownConstantByName(mtName); obj = cycAccess.getArg2(predicate, arg1, mt); System.out.println(obj); assertNotNull(obj); } } catch (Throwable e) { e.printStackTrace(); fail(e.toString()); } } finally { if (cycAccess != null) { cycAccess.close(); cycAccess = null; } } System.out.println("**** testGetArg2 OK ****"); }
7
public static Priority valueOf(int v) { switch (v) { case 1: return HIGH; case 2: return MEDIUM; case 3: return LOW; default: throw new IllegalArgumentException("priority out of range"); } }
3
public void populationInfer() { // TODO Auto-generated method stub debugPrint.print("Starting Population Inference Engine step", 5); /*Setup data strucutre to pass to Yifang's code*/ HashMap<String, HashMap<String, HashSet<String>>> data = new HashMap<String, HashMap<String, HashSet<String>>>(); //<User ID <Attribute Name, <Values>> HashMap<String, HashSet<String>> valueSet = new HashMap<String, HashSet<String>>(); for(Attribute attr: coreAttributes.values()){ if(!valueSet.containsKey(attr.getName())) { valueSet.put(attr.getName(), new HashSet<String>()); } valueSet.get(attr.getName()).add(attr.getVal()); } data.put("" + gtId, valueSet); WebFootPrint2 popInferenceEngine = new WebFootPrint2(dbWrapper.populationDbConn); ArrayList<WebUser> popResults = popInferenceEngine.getInferences(data); ArrayList<Attribute> populationInferenceAttributes = new ArrayList<Attribute>(); for(int i = 0; i < popResults.size(); i++) { WebUser user = popResults.get(i); System.out.println("USER: " + user.getProfile().getUserId()); Inference inference = user.getInference(); for(int j = 0; j < inference.size(); j++) { String attribute = inference.getAttribute(j); ArrayList array = inference.getAttributeValue(attribute); for(int k = 0; k < array.size(); k++) { Predict predict = (Predict)array.get(k); String algorithm; String confidence; switch(predict.getAlgorithm()) { case(Constants.ASSOCIATION_RULE_MINING): algorithm = "APRIORI"; confidence = "apriori_confidence"; break; case(Constants.NAIVE_BAYES): algorithm = "NAIVE_BAYES"; confidence = "naive_bayes_majority_confidence"; break; case(Constants.LDA): default: algorithm = "LDA"; confidence = "lda_majority_vote_confidence"; break; } System.out.println("ATTRIBUTE: " + attribute + "\tALGRORITHM: " + algorithm + "\tANSWER: " + predict.getAnswer() + "\tCONFIDENCE: " + (Double)predict.getUserData().getUserDatum(confidence)); double attrConf = (Double)predict.getUserData().getUserDatum(confidence); if(attrConf >= ExperimentConstants.populationThreshold) { populationInferenceAttributes.add(new Attribute(attribute, predict.getAnswer(), attrConf, "PopulationEngine-" + algorithm)); debugPrint.print("Attribute added from population inference engine", 5); } } } } debugPrint.print("Ending Population Inference Engine Step", 5); updateCore(populationInferenceAttributes); }
9
public static int cmpSrcMaj(final int[] buffer, final int first, final int second) { // if (buffer[first + IDX_SRC] < buffer[second + IDX_SRC]) return SMALLER; if (buffer[first + IDX_SRC] > buffer[second + IDX_SRC]) return BIGGER; if (buffer[first + IDX_DST] < buffer[second + IDX_DST]) return SMALLER; if (buffer[first + IDX_DST] > buffer[second + IDX_DST]) return BIGGER; // return EQUAL; }
4
public void setTableFieldString(String tableFieldString) { this.tableFieldString = tableFieldString; }
0
public void move(StringBuffer output) throws EndGameException { Direction directionToMove = getDirectionToMove(); //directionToMove should be crossable if(myPosition.isCrossable(directionToMove)){ if (myPosition.hasCharacter(directionToMove))//attack { Character defender= myPosition.getCharacter(directionToMove); if(attack(defender)){ this.myPosition=myPosition.moveCharacter(directionToMove); //move monster to the next tile output.append("Monster attacked and killed " + defender +". Monster moved " + directionToMove); if(defender.isDead()) throw new EndGameException("Player has died. GAME OVER!"); } else//player is still alive. { output.append("Monster attacked: \n" + defender.toString() +"\n"+ this.toString()); } } else //just move the monster { this.myPosition=myPosition.moveCharacter(directionToMove); //move character to the next tile } } }
4
public void setObtained(boolean value) { this.obtained = value; }
0
private void appendFriendlyClassName(StringBuilder sb, Class<?> cl) { if (cl == null) { sb.append(cl); return; } if (cl.isPrimitive()) { sb.append(cl.getName()); } else if (cl.isArray()) { appendFriendlyClassName(sb, cl.getComponentType()); sb.append("[]"); } else if (cl == String.class) { sb.append("String"); } else if (cl == Date.class) { sb.append("Date"); } else if (Number.class.isAssignableFrom(cl) && cl.getName().startsWith("java.lang.") || cl.getName().startsWith("java.math.")) { sb.append(cl.getName().substring(10)); } else { sb.append(cl.getName()); } }
9
public static void mouseExited(MouseEvent mouseEvent) { Iterator<PComponent> it = components.iterator(); while(it.hasNext()) { PComponent comp = it.next(); if(comp == null) continue; if (shouldHandleMouse) { if (comp.shouldHandleMouse()) comp.mouseExited(mouseEvent); } else { if (comp instanceof PFrame) { for (PComponent component : ((PFrame) comp).getComponents()) if (component.forceMouse()) component.mouseExited(mouseEvent); } else if (comp.forceMouse()) comp.mouseExited(mouseEvent); } } }
8
public Product inputProduct() { Product product = null; String reply = keyboard("Select product (y - Yes, n - No)"); if (reply.equals("y")) { product = selectProduct(); } if (product != null) { return product; } String typeOfTheProduct = keyboard("Select the type of the product(1 = Botinki. 2 = Foto.)"); String title = keyboard("Enter the name of the product"); String price = keyboard("Enter the price of the product"); Double dPrice = null; try { dPrice = Double.valueOf(price); } catch (NumberFormatException e){ System.err.println(ERROR_MSG); System.exit(1); } if(Integer.valueOf(typeOfTheProduct) == 1) { BotinkiProduct productBotinki = new BotinkiProduct(); String color = keyboard("Enter the color of the shoes"); productBotinki.setColor(color); product = productBotinki; } else if (Integer.valueOf(typeOfTheProduct) == 2) { FotoProduct productFoto = new FotoProduct(); try { String megapx = keyboard("Enter the number of megapixels "); productFoto.setMegapx(Double.valueOf(megapx)); String digital = keyboard("Does it digital(True or False)"); productFoto.setDigital(Boolean.valueOf(digital)); } catch (NumberFormatException e){ System.err.println(ERROR_MSG); System.exit(1); } product = productFoto; } else { System.err.println(ERROR_MSG); System.exit(1); } try { product.setTitle(title); product.setPrice(dPrice); } catch (NumberFormatException e){ System.err.println(ERROR_MSG); System.exit(1); } // Adding product to cache this.products.add(product); return product; }
7
public static void main(String args[]) { Thread t = new Thread(() -> { while (true) { // updateBalance(); //use synchronized updateBalance2(); // don't use synchronized } }); t.start(); t = new Thread(() -> { while (true) { monitorBalance(); } }); t.start(); }
2
public static void GenerateReport() { System.out.println("The term is finally done! Lets see how Damon did this term."); DamonMarksReport(); DamonGamingReport(); DamonSportsReport(); }
0
public static List<ITileObject> loadMap(String file) { try { InputStream stream = MapLoader.class.getClassLoader().getResourceAsStream("res/maps/" + file); BufferedImage bufferedImage = ImageIO.read(stream); final byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData(); final int width = bufferedImage.getWidth(); List<ITileObject> tiles = new ArrayList<ITileObject>(0); final int pixelLength = 3; for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) { TileType tile = TileType.getFromRGB(new RGB( (int) pixels[pixel + 2] & 0xff, (int) pixels[pixel + 1] & 0xff, (int) pixels[pixel] & 0xff )); if (tile != null) { if (tile == TileType.CHAR_START) { CharacterSpawn spawn = new CharacterSpawn(col, row); tiles.add(spawn); tiles.add(new RenderMapTile(spawn.getTileType(), col, row)); } else if (tile == TileType.CRATE) { PushableCrate crate = new PushableCrate(col, row); tiles.add(crate); tiles.add(new RenderMapTile(crate.getTileType(), col, row)); } else { tiles.add(new RenderMapTile(tile, col, row)); } } col++; if (col == width) { col = 0; row++; } } return tiles; } catch (Exception exception) { Logger.logException(exception); } return null; }
6
@Override public boolean equals(Object obj2) { if (obj2 instanceof Token) { Token tok2 = (Token) obj2; if (this.value.getClass() != tok2.value.getClass()) { return false; } if (this.count != tok2.count) { return false; } if (this.value instanceof StringBuffer) { return this.value.toString().equals(tok2.value.toString()); } else if (this.value instanceof Number) { return this.value.equals(tok2.value); } else { return this.value == tok2.value; } } return false; }
5
public ListNode reverseKGroup(ListNode head, int k) { ListNode header = new ListNode(0); header.next = head; ListNode[] nodes = new ListNode[k]; int count = 0; ListNode pre = header; ListNode p = head; while (p!=null){ while(p!=null && count<k){ nodes[count] = p; p = p.next; count++; } if (p!=null || count==k){ ListNode temp = nodes[k-1].next; for (int i = k-1; i >= 0; i--) { pre.next = nodes[i]; pre = pre.next; } pre.next = temp; } else{ pre.next = nodes[0]; } count = 0; } return header.next; }
7
public void setCell(int x, int y, Cell cell) { this.cells[x][y] = cell; }
0
public static boolean wasKeyReleased(char c) { if (!keyrCheckInitiated) { keyrCheckInitiated = true; keyrLastUpdate = System.currentTimeMillis(); } if (keyrLastUpdate + TIMEOUT < System.currentTimeMillis()) { app.keysReleased.clear(); } Character n = new Character(c); try { for (int i = 0; i < app.keysReleased.size(); i++) { if (app.keysReleased.get(i).equals(n)) { //app.keysReleased.remove(i); return true; } } }// end try catch (Exception e) { } return false; } // end waskey released
5
public void setIn(Node node, Object o) { if(this.in == null) { this.in = new Hashtable<Node,Object>(1); } if(o != null) { this.in.put(node, o); } else { this.in.remove(node); } }
2
public void createPartControl(Composite frame) { final ToolTipHandler tooltip = new ToolTipHandler(frame.getShell()); GridLayout layout = new GridLayout(); layout.numColumns = 3; frame.setLayout(layout); String platform = SWT.getPlatform(); String helpKey = "F1"; if (platform.equals("gtk")) helpKey = "Ctrl+F1"; if (platform.equals("carbon") || platform.equals("cocoa")) helpKey = "Help"; ToolBar bar = new ToolBar (frame, SWT.BORDER); for (int i=0; i<5; i++) { ToolItem item = new ToolItem (bar, SWT.PUSH); item.setText (getResourceString("ToolItem.text", new Object[] { new Integer(i) })); item.setData ("TIP_TEXT", getResourceString("ToolItem.tooltip", new Object[] { item.getText(), helpKey })); item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() { public String getHelpText(Widget widget) { Item item = (Item) widget; return getResourceString("ToolItem.help", new Object[] { item.getText() }); } }); } GridData gridData = new GridData(); gridData.horizontalSpan = 3; bar.setLayoutData(gridData); tooltip.activateHoverHelp(bar); Table table = new Table (frame, SWT.BORDER); for (int i=0; i<4; i++) { TableItem item = new TableItem (table, SWT.PUSH); item.setText (getResourceString("Item", new Object[] { new Integer(i) })); item.setData ("TIP_IMAGE", images[hhiInformation]); item.setText (getResourceString("TableItem.text", new Object[] { new Integer(i) })); item.setData ("TIP_TEXT", getResourceString("TableItem.tooltip", new Object[] { item.getText(), helpKey })); item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() { public String getHelpText(Widget widget) { Item item = (Item) widget; return getResourceString("TableItem.help", new Object[] { item.getText() }); } }); } table.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL)); tooltip.activateHoverHelp(table); Tree tree = new Tree (frame, SWT.BORDER); for (int i=0; i<4; i++) { TreeItem item = new TreeItem (tree, SWT.PUSH); item.setText (getResourceString("Item", new Object[] { new Integer(i) })); item.setData ("TIP_IMAGE", images[hhiWarning]); item.setText (getResourceString("TreeItem.text", new Object[] { new Integer(i) })); item.setData ("TIP_TEXT", getResourceString("TreeItem.tooltip", new Object[] { item.getText(), helpKey})); item.setData ("TIP_HELPTEXTHANDLER", new ToolTipHelpTextHandler() { public String getHelpText(Widget widget) { Item item = (Item) widget; return getResourceString("TreeItem.help", new Object[] { item.getText() }); } }); } tree.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL)); tooltip.activateHoverHelp(tree); Button button = new Button (frame, SWT.PUSH); button.setText (getResourceString("Hello.text")); button.setData ("TIP_TEXT", getResourceString("Hello.tooltip")); tooltip.activateHoverHelp(button); }
6
@Override public boolean InitBase(int ptra_v2m) { int d = 0; m_base.timediv = v2mBuffer.getInt(d); //System.out.println(m_base.timediv); m_base.timediv2 = 10000 * m_base.timediv; //System.out.println(m_base.timediv2); m_base.maxtime = v2mBuffer.getInt(d + 4); //System.out.println(m_base.maxtime); m_base.gdnum = v2mBuffer.getInt(d + 8); //System.out.println(m_base.gdnum); d += 12; m_base.ptrgptr = d; //System.out.println(m_base.ptrgptr); d += 10 * m_base.gdnum; //System.out.println("d:" + Integer.toHexString(0x0042c000 + d)); //System.out.println("--------"); for (int ch = 0; ch < 16; ch++) { //int ch=0; //V2MBase.Channel c = m_base.chan[ch]; m_base.chan[ch].notenum = v2mBuffer.getInt(d); //System.out.println(c.notenum); d += 4; if (m_base.chan[ch].notenum > 0) { m_base.chan[ch].ptrnoteptr = d; //System.out.println(Integer.toHexString(d)); d += 5 * m_base.chan[ch].notenum; m_base.chan[ch].pcnum = v2mBuffer.getInt(d); //System.out.println(c.pcnum); d += 4; m_base.chan[ch].ptrpcptr = d; //System.out.println(Integer.toHexString(0x0042c000+c.ptrpcptr)); d += 4 * m_base.chan[ch].pcnum; m_base.chan[ch].pbnum = v2mBuffer.getInt(d); //System.out.println(c.pbnum); d += 4; m_base.chan[ch].ptrpbptr = d; //System.out.println(Integer.toHexString(0x0042c000+c.ptrpbptr)); d += 5 * m_base.chan[ch].pbnum; for (int cn = 0; cn < 7; cn++) { //int cn = 0; //V2MBase.Channel.CC cc = c.ctl[cn]; m_base.chan[ch].ctl[cn].ccnum = v2mBuffer.getInt(d); //System.out.println(cc.ccnum); d += 4; m_base.chan[ch].ctl[cn].ptrccptr = d; //System.out.println(Integer.toHexString(0x0042c000+cc.ptrccptr)); d += 4 * m_base.chan[ch].ctl[cn].ccnum; //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); } } } //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); int size = v2mBuffer.getInt(d); //System.out.println(size); if (size > 16384 || size < 0) return false; d += 4; m_base.ptrglobals = d; //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); d += size; size = v2mBuffer.getInt(d); //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); if (size > 1048576 || size < 0) return false; d += 4; m_base.ptrpatchmap = d; //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); d += size; int spsize = v2mBuffer.getInt(d); //System.out.println("d:" + Integer.toHexString(0x0042c000+d)); d += 4; if (spsize == 0 || spsize >= 8192) { /*for(int i = 0; i < 256; i++) { m_base.ptrspeechptrs[i] = " "; }*/ } else { m_base.ptrspeechdata = d; d += spsize; } //System.out.println("InitBase: "+m_base.chan[0].notenum); return true; }
9
public boolean isPalindrome(int x) { if(x < 0) return false; int y=0; int val = x; while(val > 0){ y = y*10+ (val % 10 ); val = val /10; } return y == x; }
2
public static List<?> arrayToList(Object source) { return Arrays.asList(SpringObjectUtils.toObjectArray(source)); }
1
private boolean doAction(final String action, final SceneObject obj) { if(Players.getLocal().getAnimation() == -1 && !Players.getLocal().isMoving()) { if(obj.getLocation().distanceTo() > 5) { Walking.walk(obj.getLocation()); } else { if(!obj.isOnScreen()) { Camera.turnTo(obj); } else { if(obj.interact(action, obj.getDefinition().getName())) { final Timer timeout = new Timer(3000); while(Players.getLocal().getAnimation() == -1 && timeout.isRunning()) { Task.sleep(50); } return true; } } } } return false; }
7
public Provider() { this.products = new HashMap<>(); }
0
public void lopetaTaso() { this.osuikoJohonkin = EsteenTyyppi.QUIT; }
0
private boolean vecInList(ArrayList<Node> list, Vector2 vector){ for(Node n : list) { if(n.tile.x == vector.x && n.tile.y == vector.y) return true; } return false; }
3
public String render(){ String s = ""; //keep track of whether the previous part of the term was wrapped with parentheses //this is so we can distinguish between 62 and 6(2), etc. boolean prevHadPar = true; String prevClass = "";//the name of the class of the previous part of the term for(int i = 0; i < this.parts.size(); i++){ AlgebraicParticle p = this.parts.get(i); String curClass = p.getClass().getSimpleName(); //if the exponent is not 1, the other class will take care of pars (if they're needed) //or if the sign is negative and it's not the first element, then it needs parentheses boolean needsPar = p.exponent() == 1 && (!p.sign() && i != 0 || curClass.equals("Expression") || curClass.equals("Fraction")); //MixedNumber and Number should only be wrapped with pars if the previous part was a number and it didn't have pars if((curClass.equals("MixedNumber") || curClass.equals("Number")) && prevClass.equals("Number")) needsPar = !prevHadPar; s += needsPar ? "(" + p.render() + ")" : p.render(); prevClass = curClass; prevHadPar = needsPar; } return wrapWithSignParAndExponent(s, true); }
9
private void fullStrize(){ for(int i = 0; i<n;i++) stroki[i]=new Stroka(A[i]); stolbiki = new Stolbec[m]; for(int i=0; i<m;i++) { stolbiki[i] = new Stolbec(n); for(int j=0; j<n; j++){ stolbiki[i].setone(j, stroki[j].get(i) ); } } }
3
private Color interpolateColor(final Stop LOWER_BOUND, final Stop UPPER_BOUND, final double POSITION) { final double POS = (POSITION - LOWER_BOUND.getOffset()) / (UPPER_BOUND.getOffset() - LOWER_BOUND.getOffset()); final double DELTA_RED = (UPPER_BOUND.getColor().getRed() - LOWER_BOUND.getColor().getRed()) * POS; final double DELTA_GREEN = (UPPER_BOUND.getColor().getGreen() - LOWER_BOUND.getColor().getGreen()) * POS; final double DELTA_BLUE = (UPPER_BOUND.getColor().getBlue() - LOWER_BOUND.getColor().getBlue()) * POS; final double DELTA_OPACITY = (UPPER_BOUND.getColor().getOpacity() - LOWER_BOUND.getColor().getOpacity()) * POS; double red = LOWER_BOUND.getColor().getRed() + DELTA_RED; double green = LOWER_BOUND.getColor().getGreen() + DELTA_GREEN; double blue = LOWER_BOUND.getColor().getBlue() + DELTA_BLUE; double opacity = LOWER_BOUND.getColor().getOpacity() + DELTA_OPACITY; red = red < 0 ? 0 : (red > 1 ? 1 : red); green = green < 0 ? 0 : (green > 1 ? 1 : green); blue = blue < 0 ? 0 : (blue > 1 ? 1 : blue); opacity = opacity < 0 ? 0 : (opacity > 1 ? 1 : opacity); return Color.color(red, green, blue, opacity); }
8
public static void main(String[] args) { EvolvingGlobalProblemSetInitialisation starter = new EvolvingGlobalProblemSetInitialisation(); starter.initLanguage(new char[] { '0', '1' }, 10, "(1(01*0)*1|0)*"); int solutionFoundCounter = 0; int noSolutionFound = 0; List<Long> cycleCount = new LinkedList<Long>(); long tmpCycle; long timeStamp; int[] problemCount = new int[5]; int[] candidatesCount = new int[5]; int[] noCycles = new int[2]; problemCount[0] = 10; problemCount[1] = 20; problemCount[2] = 30; problemCount[3] = 40; problemCount[4] = 50; candidatesCount[0] = 10; candidatesCount[1] = 20; candidatesCount[2] = 30; candidatesCount[3] = 40; candidatesCount[4] = 50; noCycles[0] = 250; noCycles[1] = 500; int pc = 0; int cc = 0; int nc = 0; for (int x = 0; x < 1; x++) { System.out.println("x:" + x); for (int n = 0; n < 25; n++) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss"); Logger l = new Logger("E_G_" + df.format(new Date()) + ".log", true); pc = problemCount[n % 5]; cc = candidatesCount[(int) Math.floor(n / 5)]; nc = noCycles[1]; l.log("Problem Count: " + pc); l.log("CandidatesCount: " + cc); l.log("Max Cycles: " + nc); solutionFoundCounter = 0; noSolutionFound = 0; cycleCount = new LinkedList<Long>(); for (int i = 0; i < 100; i++) { timeStamp = System.currentTimeMillis(); starter.initProblems(pc); starter.initCandidates(cc); tmpCycle = starter.startEvolution(nc); l.log(i + ": finished (" + (System.currentTimeMillis() - timeStamp) + "ms, " + tmpCycle + "cycles)"); if (starter.getWinner() != null) { solutionFoundCounter++; cycleCount.add(tmpCycle); l.log(i + ": Solution found."); // GraphvizRenderer.renderGraph(starter.getWinner().getObj(), // "winner.svg"); } else { noSolutionFound++; l.log(i + ": No solution found."); } } long max = 0; long min = 10000; long sum = 0; for (long no : cycleCount) { sum += no; max = (no > max ? no : max); min = (no < min ? no : min); } l.log("Solution Found: " + solutionFoundCounter); l.log("Avg cycles: " + (cycleCount.size() > 0 ? sum / cycleCount.size() : '0')); l.log("Max cycles: " + max); l.log("Min cycles: " + min); l.log("No solution found: " + noSolutionFound); l.finish(); } } }
8
@Override public AssertionResult getResult(SampleResult samplerResult) { AssertionResult result = new AssertionResult(getName()); byte[] responseData = samplerResult.getResponseData(); if (responseData.length == 0) { return result.setResultForNull(); } if (isJsonValidation()) { try { if (checkJSONPathWithValidation(new String(responseData,"UTF-8"), getJsonPath(), getExpectedValue())) { result.setFailure(false); result.setFailureMessage(""); } } catch (ParseException e) { result.setFailure(true); result.setFailureMessage(e.getClass().toString() + " - " + e.getMessage()); } catch (Exception e) { result.setFailure(true); result.setFailureMessage(e.getMessage()); } } if (!isJsonValidation()) { try { if (checkJSONPathWithoutValidation(new String(responseData), getJsonPath())) { result.setFailure(false); result.setFailureMessage(""); } } catch (ParseException e) { result.setFailure(true); result.setFailureMessage(e.getClass().toString() + " - " + e.getMessage()); } catch (Exception e) { result.setFailure(true); result.setFailureMessage(e.getMessage()); } } return result; }
9
public static int[] Verprofit(int[] prices) { int len = prices.length; int max = prices[len-1]; int maxPosition = len; int min = prices[len-1]; int minPosition = len; int lastPoint = prices[len-1]; int newMax = -1; int newMaxPosition = -1; int[] result = new int[len+1]; result[len] = 0; result[len-1] = 0; for(int i=len-2;i>=0;i--) { int currentPoint = prices[i]; if(currentPoint < lastPoint) { if(newMax != -1) { int trend = newMax - currentPoint; if(trend > result[i+1]) { max = newMax; maxPosition = newMaxPosition; min = currentPoint; minPosition = i; newMax = -1; newMaxPosition = -1; result[i] = trend; } else { result[i] = result[i+1]; } }else if(currentPoint < min) { result[i] = result[i+1] + (min-currentPoint); min = currentPoint; minPosition = i; } else { result[i] = result[i+1]; } } else if(currentPoint > lastPoint) { if(currentPoint > max) { newMax = currentPoint; newMaxPosition = i; } result[i] = result[i+1]; } else { result[i] = result[i+1]; } lastPoint = currentPoint; } return result; }
7
@Test public void heapTest(){ long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++){ binaryheap.insert(i); } for (int i = 0; i < 1000000; i++){ binaryheap.delete(); } long end = System.currentTimeMillis(); long totaltime = end - start; System.out.println("Time spent inserting and deleting 1000000: " + totaltime + "ms = " + (totaltime*1.0)/1000 + "s"); }
2
public void acceptCmd(UUID idClient, byte[] data) { int index = getIndex(data); byte cmd = getCmd(data); if (index < 0 || index >= locks.keySet().size()) { if (!send(idClient, false)) error("acceptCmd", "failed to send fail to client: " + idClient); } else if (cmd == 0 && (locks.get(index).peek() == null || !locks.get(index).peek().equals(idClient))) { if (!send(idClient, false)) error("acceptCmd", "failed to send fail to client: " + idClient); } else { if (cmd == 1) acquireLock(idClient, index); else releaseLock(idClient, index); } }
8
public static Color getCurrentSecondary(ColorType c) { if (c == ColorType.WALL || c == ColorType.SLOW_WALL) if (beatCount % 2 == 0) return getAltSecondary(); return SECONDARY_COLOR_MAP.get(getColor(c)); }
3
public static void printlocOutDegVsWheightedMeanPersonSocScore(){ HashMap<Integer,Integer> outDegree = new HashMap<Integer,Integer>(numLocations); HashMap<Integer,Double> meanSoc = new HashMap<Integer,Double>(numLocations); try { Connection con = dbConnect(); Statement getOutDeg = con.createStatement(); ResultSet getOutDegQ = getOutDeg.executeQuery( "SELECT locationID,outbound FROM "+llCountTbl+" ORDER BY outbound DESC"); while (getOutDegQ.next()){ outDegree.put(new Integer(getOutDegQ.getInt("locationID")), new Integer(getOutDegQ.getInt("outbound"))); } getOutDegQ.close(); PreparedStatement getPeopleAtLoc = con.prepareStatement( "SELECT personID FROM "+locPeopleSocRankTbl+" WHERE locationID = ? ORDER BY rank ASC"); PreparedStatement getPersonSoc = con.prepareStatement( "SELECT tally FROM "+EpiSimUtil.conCountTbl+" WHERE personID = ?"); Iterator<Integer> locs = outDegree.keySet().iterator(); while(locs.hasNext()){ double mean = 0.0; Integer location = locs.next(); getPeopleAtLoc.setInt(1, location.intValue()); ResultSet getPeopleAtLocQ = getPeopleAtLoc.executeQuery(); while(getPeopleAtLocQ.next()){ int person = getPeopleAtLocQ.getInt("personID"); getPersonSoc.setInt(1, person); ResultSet getPersonSocQ = getPersonSoc.executeQuery(); if (getPersonSocQ.first()) mean += (double)getPersonSocQ.getInt("tally"); } getPeopleAtLocQ.last(); if (getPeopleAtLocQ.getRow() > 0) mean /= (double)getPeopleAtLocQ.getRow(); meanSoc.put(location, mean); } con.close(); Iterator<Integer> locItr = outDegree.keySet().iterator(); while(locItr.hasNext()){ Integer location = locItr.next(); System.out.println(outDegree.get(location)+"\t"+meanSoc.get(location)); } } catch (Exception e){ System.out.println(e); } }
7
public int sum(String inputNumbers) { if (inputNumbers.isEmpty()) return 0; else { return sumNumbers(parseInput(inputNumbers)); } }
1
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
private float[] popFloatArray() throws PDFParseException { Object obj = stack.pop(); if (!(obj instanceof Object[])) { throw new PDFParseException("Expected an [array] here."); } Object[] source = (Object[]) obj; float[] ary = new float[source.length]; for (int i = 0; i < ary.length; i++) { if (source[i] instanceof Double) { ary[i] = ((Double) source[i]).floatValue(); } else { throw new PDFParseException("This array doesn't consist only of floats."); } } return ary; }
3
private boolean isLinked(File file, List<File> list) { String s = file.getName(); BufferedReader br = null; String line; for (File f : list) { if (!f.equals(file)) { try { br = new BufferedReader(new FileReader(f)); line = br.readLine(); while (line != null) { if (line.indexOf(s) != -1) return true; line = br.readLine(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } } return false; }
7
public int getNumberOfMarkerOwners(String matchName){ try { cs = con.prepareCall("{ call GET_MARKEROWNERCOUNT(?,?) }"); cs.setString(1, matchName); cs.registerOutParameter(2, Types.INTEGER); cs.executeQuery(); //System.out.println("number of players in team: " + cs.getInt(3)); return cs.getInt(2); } catch (SQLException e) { e.printStackTrace(); } return 0; }
1
public TransactionSet findKItemSubsets(ItemSet itemSet, int k) { TransactionSet allSubsets = new TransactionSet();/*New subset of transactions to return in a TransactionSet*/ int subsetCount = (int) Math.pow(2, itemSet.getItemSet().size());/*index control for loop*/ int itemSetSize = itemSet.getItemSet().size();/*size control for inner loop*/ for (int i = 0; i < subsetCount; i++) { if (k == 0 || GetOnCount(i, itemSet.getItemSet().size()) == k){ ItemSet subset = new ItemSet(); for (int bitIndex = 0; bitIndex < itemSetSize; bitIndex++) { if (GetBit(i, bitIndex) == 1) { subset.getItemSet().add(itemSet.getItemSet().get(bitIndex)); } } allSubsets.getTransactionSet().add(new Transaction(subset));//add the new transaction subset } } return (allSubsets);/*final combination of all possible subsets based on the size of k*/ }
5
public void actionPerformed(ActionEvent e) { result = new StringBuilder(); try { String patternText = patternMatcher.patternText(); MatcherPreferences.storePatternText(patternText); final List<String> testStringTexts = patternMatcher .testStringTexts(); for (int i = 0, n = testStringTexts.size(); i < n; i++) { String testStringText = testStringTexts.get(i); if (testStringText.trim().isEmpty()) { MatcherPreferences.removeTestStringText(i); continue; } MatcherPreferences.storeTestStringText(i, testStringText); Pattern compiledPattern = Pattern.compile(patternText); Matcher matcher = compiledPattern.matcher(testStringText); String resultLabel = "Field " + (i + 1) + ": " + testStringText.substring(0, Math.min(testStringText.length(), 20)) + (testStringText.length() >= 20 ? "..." : ""); result.append("--- matches() for " + resultLabel + " ---\n"); if (!matcher.matches()) { result.append("string does not match regex\n"); } else { appendMatchedGroups(matcher); } Matcher matcher2 = compiledPattern.matcher(testStringText); result.append("\n--- find() for " + resultLabel + " ---\n"); boolean find = matcher2.find(); if (!find) { result.append("no matches found\n"); } int iteration = 1; do { if (find) { result.append("Iteration " + iteration++ + ":\n"); appendMatchedGroups(matcher2); result.append("\n"); } } while (find = matcher2.find()); result.append("\n"); } PatternMatcher r = this.patternMatcher; this.patternMatcher.result.setRows(TextComponentUtilities .estimatedRows(this.patternMatcher.result)); showResult(); } catch (Exception ex) { JTextArea textarea = new JTextArea(ex.getMessage()); textarea.setFont(new Font("Monospaced", Font.PLAIN, 16)); JOptionPane.showMessageDialog(this.patternMatcher, textarea, ex .getClass().getName(), JOptionPane.ERROR_MESSAGE); } }
8
private static void playAgainstOpponentOnServer(int gameId, int color, int teamNumber, String secret) { PlayChess ourTeam = new PlayChess(color, gameId, teamNumber, secret); while (true) { System.out.println("POLLING AND MOVING FOR " + color); Response r = ourTeam.poll(); System.out.println(r); if (ourTeam.board.gameIsOver()) { break; } if (r.ready) { if (r.lastmove != null && r.lastmove.length() > 0) { MoveHandler.handleMove(ourTeam.board, r); } Node nextNode = MiniMax.performMiniMax(ourTeam.board, ourTeam.color, PlayChess.plyLookhead, r); ourTeam.move(MoveHandler.convertMoveToServerNotation(ourTeam.board, nextNode.m)); ourTeam.board.handleMove(nextNode.m); } } }
5
public boolean hasHepatitis(String player) { String query = "SELECT * FROM nosecandy WHERE hepatitis='1';"; ResultSet result = null; result = this.sqlite.query(query); boolean hepatitis = false; try { if (result != null && result.next()) { hepatitis = result.getBoolean(Column.HEPATITIS.getName()); } result.close(); } catch (SQLException e) { e.printStackTrace(); } return hepatitis; }
3
public static int calculatePreferredHeight(FontMetrics fm, int maxWidth, String text) { if("".equals(text)) { return 0; } // utility that helps us to break the lines final BreakIterator bi = BreakIterator.getLineInstance(); bi.setText(text); int lineCount = 0; final int lineHeight = fm.getHeight(); // offsets for String.substring(start, end); int startOffset = bi.first(); int endOffset = bi.next(); // we go over each possible line break that BreakIterator suggests. do { if(endOffset == text.length()) { // we are at the end. this would cause IllegalArgumentException // so we just subtract 1 endOffset--; } // get the width of the current substring // and check if we are over the maximum width final String substring = text.substring(startOffset, endOffset); final int stringWidth = fm.stringWidth(substring); if(stringWidth > maxWidth) { // calculate how many lines we have to add. // If there is a very long string with no spaces // it could be that we have to add more than 1 line. int toAdd = (int) (Math.ceil((double) stringWidth / (double) maxWidth) - 1); lineCount+= toAdd; // we need to advance the startOffset so // we can start to search for a new line startOffset = bi.preceding(endOffset); bi.next(); } } while((endOffset = bi.next()) != BreakIterator.DONE); // ensure that the rest of a line also gets a line lineCount++; return lineHeight * lineCount; }
4
public static void startupHtmlUtilities() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/ONTOSAURUS", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { OntosaurusUtil.SGT_LOGIC_LOGIC_OBJECT = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("LOGIC-OBJECT", Stella.getStellaModule("/LOGIC", true), 1))); OntosaurusUtil.SGT_STELLA_MODULE = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("MODULE", Stella.getStellaModule("/STELLA", true), 1))); OntosaurusUtil.SYM_ONTOSAURUS_STARTUP_HTML_UTILITIES = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-HTML-UTILITIES", null, 0))); } if (Stella.currentStartupTimePhaseP(4)) { OntosaurusUtil.$POWERLOOM_COPYRIGHT_TRAILER$ = Logic.$POWERLOOM_VERSION_STRING$ + "<BR>" + "Copyright 2000-" + Native.integerToString(((long)(CalendarDate.makeCurrentDateTime().getCalendarDate(Stella.getLocalTimeZone(), new Object[3])))) + " University of Southern California Information Sciences Institute"; } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("MAKE-HTML-BODY-TAG", "(DEFUN (MAKE-HTML-BODY-TAG STRING) ((BACKGROUNDCOLOR STRING)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "makeHtmlBodyTag", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("HTML-LINE-BREAK", "(DEFUN HTML-LINE-BREAK ((STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlLineBreak", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("HTML-WRITE-URL-IN-DETAIL", "(DEFUN HTML-WRITE-URL-IN-DETAIL ((STREAM NATIVE-OUTPUT-STREAM) (ACTION STRING) (OBJECTTYPE STRING) (CONTEXTNAME STRING) (OBJECTNAME STRING)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteUrlInDetail", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("HTML-WRITE-3PART-HREF-IN-DETAIL", "(DEFUN HTML-WRITE-3PART-HREF-IN-DETAIL ((STREAM NATIVE-OUTPUT-STREAM) (TARGET STRING) (ACTION STRING) (OBJECT-TYPE STRING) (CONTEXT-NAME STRING) (OBJECT-NAME STRING) (OBJECT-TITLE-PREFIX STRING) (OBJECT-TITLE STRING) (OBJECT-TITLE-SUFFIX STRING) (RAWTITLE? BOOLEAN)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWrite3PartHrefInDetail", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("HTML-WRITE-HREF-IN-DETAIL", "(DEFUN HTML-WRITE-HREF-IN-DETAIL ((STREAM NATIVE-OUTPUT-STREAM) (TARGET STRING) (ACTION STRING) (OBJECTTYPE STRING) (CONTEXTNAME STRING) (OBJECTNAME STRING) (OBJECTTITLE STRING) (RAWTITLE? BOOLEAN)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteHrefInDetail", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), java.lang.Boolean.TYPE}), null); Stella.defineFunctionObject("HTML-WRITE-HREF", "(DEFUN HTML-WRITE-HREF ((STREAM NATIVE-OUTPUT-STREAM) (ACTION STRING) (OBJECTTYPE STRING) (OBJECT STANDARD-OBJECT)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteHref", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.StandardObject")}), null); Stella.defineFunctionObject("HTML-WRITE-URL", "(DEFUN HTML-WRITE-URL ((STREAM NATIVE-OUTPUT-STREAM) (ACTION STRING) (OBJECT STANDARD-OBJECT)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteUrl", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.stella.StandardObject")}), null); Stella.defineFunctionObject("HTML-WRITE-JAVASCRIPT", "(DEFUN HTML-WRITE-JAVASCRIPT ((STREAM NATIVE-OUTPUT-STREAM) (JS STRING)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteJavascript", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("HTML-WRITE-HEADER-WITH-TABLE", "(DEFUN HTML-WRITE-HEADER-WITH-TABLE ((STREAM NATIVE-OUTPUT-STREAM) (TITLE STRING) (HEAD STRING)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlWriteHeaderWithTable", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("WRITE-BOOKMARK-ICON", "(DEFUN WRITE-BOOKMARK-ICON ((INSTANCE LOGIC-OBJECT) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "writeBookmarkIcon", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.LogicObject"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("HTML-EMIT-IMAGE", "(DEFUN HTML-EMIT-IMAGE ((STREAM NATIVE-OUTPUT-STREAM) (IMAGEURL STRING) (ALTERNATETEXT STRING) (WIDTH INTEGER) (HEIGHT INTEGER) (ALIGNMENT STRING) (BORDER INTEGER)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlEmitImage", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream"), Native.find_java_class("java.lang.String"), Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE, java.lang.Integer.TYPE, Native.find_java_class("java.lang.String"), java.lang.Integer.TYPE}), null); Stella.defineFunctionObject("HTML-DISPLAY-STRING-IN-PARAGRAPHS", "(DEFUN HTML-DISPLAY-STRING-IN-PARAGRAPHS ((S STRING) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "htmlDisplayStringInParagraphs", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("WRITE-POWERLOOM-TRAILER", "(DEFUN WRITE-POWERLOOM-TRAILER ((STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "writePowerloomTrailer", new java.lang.Class [] {Native.find_java_class("java.io.PrintStream")}), null); Stella.defineFunctionObject("STARTUP-HTML-UTILITIES", "(DEFUN STARTUP-HTML-UTILITIES () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.ontosaurus._StartupHtmlUtilities", "startupHtmlUtilities", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(OntosaurusUtil.SYM_ONTOSAURUS_STARTUP_HTML_UTILITIES); KeyValueList.setDynamicSlotValue(function.dynamicSlots, OntosaurusUtil.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupHtmlUtilities"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("ONTOSAURUS"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ERROR-BACKGROUND-COLOR* STRING \"FF9999\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *STANDARD-BACKGROUND-COLOR* STRING \"99CCFF\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MODULE-BACKGROUND-COLOR* STRING \"9999CC\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CONTROL-BACKGROUND-COLOR* STRING \"6699CC\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ANSWER-BACKGROUND-COLOR* STRING \"99FFFF\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FORM-BACKGROUND-COLOR* STRING \"6699CC\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HREF-PREFIX-TAG* STRING \"FONT COLOR='#666666' SIZE=-1\" :DOCUMENTATION \"Tag used for prefix part of HREF generation in\n`html-write-3part-href-in-detail'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HREF-SUFFIX-TAG* STRING \"FONT COLOR='#666666' SIZE=-1\" :DOCUMENTATION \"Tag used for suffix part of HREF generation in\n`html-write-3part-href-in-detail'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *POWERLOOM-COPYRIGHT-TRAILER* STRING (CONCATENATE *POWERLOOM-VERSION-STRING* \"<BR>\" \"Copyright 2000-\" (INTEGER-TO-STRING (GET-CALENDAR-DATE (MAKE-CURRENT-DATE-TIME) (GET-LOCAL-TIME-ZONE))) \" University of Southern California Information Sciences Institute\"))"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
6
public void shouldBeEqual(PrintWriter oo, Heaper original, Heaper imported, Heaper importedAgain) { boolean oi; boolean oa; boolean ia; oi = original.isEqual(imported); oa = original.isEqual(importedAgain); ia = imported.isEqual(importedAgain); if (oi && ( ! oa && ( ! ia))) { oo.print("2nd import "); oo.print(importedAgain); oo.print(" is different from "); oo.print(original); oo.print("\n"+ ""); } if (oa && ( ! oi && ( ! ia))) { oo.print("import "); oo.print(imported); oo.print(" is different from "); oo.print(original); oo.print("\n"+ ""); } if (ia && ( ! oa && ( ! oi))) { oo.print("original "); oo.print(importedAgain); oo.print(" is different from "); oo.print(original); oo.print("\n"+ ""); } /* udanax-top.st:59974:IDTester methodsFor: 'testing'! {void} shouldBeEqual: oo {ostream reference} with: original {Heaper} with: imported {Heaper} with: importedAgain {Heaper} | oi {BooleanVar} oa {BooleanVar} ia {BooleanVar} | oi := original isEqual: imported. oa := original isEqual: importedAgain. ia := imported isEqual: importedAgain. (oi and: [oa not and: [ia not]]) ifTrue: [oo << '2nd import ' << importedAgain << ' is different from ' << original << ' ']. (oa and: [oi not and: [ia not]]) ifTrue: [oo << 'import ' << imported << ' is different from ' << original << ' ']. (ia and: [oa not and: [oi not]]) ifTrue: [oo << 'original ' << importedAgain << ' is different from ' << original << ' '].! */ }
9