method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2472e3ca-da58-4e78-ba4f-0345ad3d3abe
5
@Override public void paint(Graphics2D g2, boolean tmp) { // TODO Auto-generated method stub int diffX = sx - ex; int diffY = sy - ey; int tempx = ex; int tempy = ey; if (tmp == false) { // float[] dash = { 10, 2 }; g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, new float[] { 8.0f, 6.0f }, 0.0f)); if (diffX < 0 && diffY < 0) { ex = sx; ey = sy; } g2.drawRect(sx - Math.abs(sx - ex), sy - Math.abs(sy - ey), Math.abs(diffX), Math.abs(diffY)); } else { if (diffX < 0 && diffY < 0) { ex = sx; ey = sy; } g2.setStroke(new BasicStroke(strokeThickness)); g2.setColor(strokeColor); g2.drawRect(sx - Math.abs(sx - ex), sy - Math.abs(sy - ey), Math.abs(diffX), Math.abs(diffY)); ex = tempx; ey = tempy; } }
9824036c-abe8-453e-92c9-048fc8fc1103
4
public MainWindow() { //basic window configuration super(); super.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); super.setLocationRelativeTo(null); super.setTitle(WINDOW_TITLE); super.setResizable(false); super.setUndecorated(false); //changing L&F try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (ClassNotFoundException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); } //Programming the closing of the app super.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); super.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { sair(); } }); //setting the icon setIconImage(icon); //setting the menu super.setJMenuBar(createMenuBar()); super.setVisible(true); }
8b155c2c-ccd7-45f4-8a9c-b13465d7d1c8
1
@Test public void random_test() { try{ double []mat= {1.0,2.0,3.0,1.0}; int m=4; double[]result = Vector.random(m); double exp[]={1.0,2.0,3.0,1.0}; Assert.assertNotSame(exp, result); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
2504a60e-eaae-4d41-ae90-b0539f1a4935
1
public void getFps() { delta = getTime() - currentTime; currentTime = getTime(); lastLoopTime += delta; fps++; if(lastLoopTime >= 1000) { screen.updateHeader(); fps = 0; lastLoopTime = 0; /*if(debug) { System.out.println("Load Time: " + loadTime + "ms\nDraw Time: " + Screen.drawTime + "ms\nAct Time: " + Stage.actTime + "ms"); System.out.println("Draws per frame: " + Theater.drawcount); }*/ } }
cf001e87-128a-4ae6-9b88-506fafddee96
6
public void process() { for (int j = 0; j < globalObjects.size(); j++) { if (globalObjects.get(j) != null) { Objects o = globalObjects.get(j); if(o.objectTicks > 0) { o.objectTicks--; } if (o.objectTicks == 1) { Objects deleteObject = objectExists(o.getObjectX(), o.getObjectY(), o.getObjectHeight()); removeObject(deleteObject); o.objectTicks = 0; placeObject(o); removeObject(o); if (isObelisk(o.objectId)) { int index = getObeliskIndex(o.objectId); if (activated[index]) { activated[index] = false; teleportObelisk(index); } } } } } }
6fcad342-49a4-4408-83a7-351bf0e1135d
1
public boolean resume() { if (state == EnumStopWatchState.PAUSE) { state = EnumStopWatchState.RUNNING; log.info("resume stopwatch, it's state:" + state + ", elapseTime:" + elapseTime); return true; } return false; }
96170547-678c-493a-b616-6c8c10960da1
1
public UserDao getUserDao() { if (userDao == null) userDao = new UserDaoImp(); return userDao; }
015d6d9e-102b-4552-801c-9e8956aae686
0
public void setUserid(String userid) { this.userid = userid; }
19a851d6-9373-419a-892d-34b642d03870
7
public boolean[] getAction() { // this Agent requires observation integrated in advance. if (mergedObservation[11][13] != 0 || mergedObservation[11][12] != 0 || DangerOfGap()) { if (isMarioAbleToJump || ( !isMarioOnGround && action[Mario.KEY_JUMP])) { action[Mario.KEY_JUMP] = true; } ++trueJumpCounter; } else { action[Mario.KEY_JUMP] = false; trueJumpCounter = 0; } if (trueJumpCounter > 16) { trueJumpCounter = 0; action[Mario.KEY_JUMP] = false; } action[Mario.KEY_SPEED] = DangerOfGap(); return action; }
2dc2b828-4e8a-4611-b822-0847988ffcfc
3
public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget (); int count = data.size(); GC gc = new GC (this); int titleWidth = gc.stringExtent (title).x; Point valueSize = gc.stringExtent (new Integer(valueMax).toString()); int itemWidth = 0; for (int i = 0; i < count; i++) { Object [] dataItem = (Object []) data.elementAt(i); String itemLabel = (String)dataItem[0]; itemWidth = Math.max(itemWidth, gc.stringExtent (itemLabel).x); } gc.dispose(); int width = Math.max(titleWidth, count * (itemWidth + GAP) + GAP) + 3 * GAP + AXIS_WIDTH + valueSize.x; int height = 3 * GAP + AXIS_WIDTH + valueSize.y * ((valueMax - valueMin) / valueIncrement + 3); if (wHint != SWT.DEFAULT) width = wHint; if (hHint != SWT.DEFAULT) height = hHint; int border = getBorderWidth (); Rectangle trim = computeTrim (0, 0, width + border*2, height + border*2); return new Point (trim.width, trim.height); }
a06b73fd-8d85-4033-97b3-d4271e9895d4
2
@Override public void statsChanged(PlayerEvent e) { if(e.getPlayer().isDead()) { MouseListener[] mlis = this.getMouseListeners(); for(MouseListener m: mlis) { this.removeMouseListener(m); } } }
eb999f28-6e20-4d48-b87e-c5417aa91bf5
9
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
229a1b96-7e33-479c-9060-f30b180463a3
1
public V remove(Object key) { CachedValue<V> oldVal = cache.remove((K)key); return (oldVal == null) ? null : oldVal.get(); }
6468e0cc-35fd-4702-9e92-e74912dbcdaa
4
public Script[][][] load(AssetManager assets, MapHandler map, String mapName) { Script[][][] s = new Script[map.getLayer()][map.getX()][map.getY()]; for (Trigger t : triggers) { if(t.script.startsWith("$Warp:")) { String[] arg = t.script.split(":"); s[t.layer][t.x][t.y] = new Script((Script) assets.get("res/scripts/Warp.ps")); s[t.layer][t.x][t.y].strings.put("area", arg[1]); s[t.layer][t.x][t.y].strings.put("x", arg[2]); s[t.layer][t.x][t.y].strings.put("y", arg[3]); s[t.layer][t.x][t.y].strings.put("layer", arg[4]); } else if(t.script.startsWith("$DWarp:")) { String[] arg = t.script.split(":"); s[t.layer][t.x][t.y] = new Script((Script) assets.get("res/scripts/DWarp.ps")); s[t.layer][t.x][t.y].strings.put("area", arg[1]); s[t.layer][t.x][t.y].strings.put("x", arg[2]); s[t.layer][t.x][t.y].strings.put("y", arg[3]); s[t.layer][t.x][t.y].strings.put("layer", arg[4]); } else { try { s[t.layer][t.x][t.y] = (Script) assets.get("res/maps/" + mapName + "/" + t.script + ".ps"); } catch (NullPointerException e) { System.out.println("Error loading script " + t.script + " from map " + mapName); throw e; } } } return s; }
806e0a82-9164-4934-bbc9-2d85309e92d0
0
public void animateParticle(Node particle, Shape path) { PathTransition transition = new PathTransition(); transition.setPath(path); transition.setNode(particle); transition.setDuration(Duration.seconds(getRandom())); transition.setCycleCount(-1); animations.add(transition); transition.play(); }
a1796ae3-f27d-4bc7-877c-cd957fe49ff1
8
public static double[] box_box_p(double ax0, double ay0, double ax1, double ay1, double bx0, double by0, double bx1, double by1){ double[] result = NONE; double topA = FastMath.min(ay0, ay1); double botA = FastMath.max(ay0, ay1); double leftA = FastMath.min(ax0, ax1); double rightA = FastMath.max(ax0, ax1); double topB = FastMath.min(by0, by1); double botB = FastMath.max(by0, by1); double leftB = FastMath.min(bx0, bx1); double rightB = FastMath.max(bx0, bx1); if(botA <= topB || botB <= topA || rightA <= leftB || rightB <= leftA) return result; double leftO = (leftA < leftB) ? leftB : leftA; double rightO = (rightA > rightB) ? rightB : rightA; double botO = (botA > botB) ? botB : botA; double topO = (topA < topB) ? topB : topA; result = new double[] {leftO, topO, rightO, botO}; return result; }
3fe6707a-9c65-4caa-96d9-ab3e2bfde0a1
1
public void progressEnd() { --block; if (block == 0) { } }
ed2e7a67-a7c6-47f6-9c29-3e0eb14984b1
4
@Override public void prepareInternal(int skips, boolean assumeOnSkip) { if(!assumeOnSkip) if (metric != null) twoFrames = EflUtil.runToNextInputFrameForMetricNoLimit(move, metric); else twoFrames = EflUtil.runToNextInputFrameNoLimit(move); while(skips-- > 0) { curGb.step(); if (metric != null) twoFrames = EflUtil.runToNextInputFrameForMetricNoLimit(move, metric); else twoFrames = EflUtil.runToNextInputFrameNoLimit(move); } }
cdda274c-af5e-49db-84bd-8a6d7971a6f0
4
public boolean[] tallyPieces() throws IOException { boolean[] myPieces = new boolean[torrentInfo.piece_hashes.length]; byte[] comparator = new byte[]{ 0, 0, 0, 0,}; byte[] temp = new byte[4]; int i = 0; for (i = 0; i < torrentInfo.piece_hashes.length; i += 1) { raf.seek(i * torrentInfo.piece_length); raf.read(temp, 0, 4); if (Arrays.equals(comparator, temp)) { myPieces[i] = false; // System.out.println("tallyPieces has found that piece: " + i + " is " + myPieces[i]); } else { byte[] piece; if (i == torrentInfo.piece_hashes.length - 1) { piece = new byte[torrentInfo.file_length % torrentInfo.piece_length]; // System.out.println("Last Piece, piece index: " + i + " is " + piece.length + " bytes long."); } else piece = new byte[torrentInfo.piece_length]; raf.seek(i * torrentInfo.piece_length); raf.read(piece, 0, piece.length); PieceMessage tempPM = new PieceMessage(i, 0, piece); if(manager.verifyPiece(tempPM)) myPieces[i] = true; else myPieces[i] = false; // System.out.println("tallyPieces has found that piece: " + i + " is " + myPieces[i]); } } return myPieces; }
aad5380f-2df5-462c-9df3-1cf8bd5c8ebc
3
private int jjMoveStringLiteralDfa1_1(long active0){ try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return 1; } switch(curChar) { case 47: if ((active0 & 0x80L) != 0L) return jjStopAtPos(1, 7); break; default : return 2; } return 2; }
f53968be-67c9-4a6d-8b3f-18fd045cb313
3
void setItemForeground () { if (!instance.startup) { textNode1.setForeground (itemForegroundColor); imageNode1.setForeground (itemForegroundColor); } /* Set the foreground button's color to match the foreground color of the item. */ Color color = itemForegroundColor; if (color == null) color = textNode1.getForeground (); TableItem item = colorAndFontTable.getItem(ITEM_FOREGROUND_COLOR); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (colorImage(color)); }
e4da84b1-9569-423d-ad24-d1f02b3a538f
7
@Override public void enumerate(String uid, String connectedUid, char position, short[] hardwareVersion, short[] firmwareVersion, int deviceIdentifier, short enumerationType) { // configure bricks on first connect (ENUMERATION_TYPE_CONNECTED) // or configure bricks if enumerate was raised externally (ENUMERATION_TYPE_AVAILABLE) if (enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED || enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE) { // configure master brick if (deviceIdentifier == BrickMaster.DEVICE_IDENTIFIER) { master = new BrickMaster(uid, ipcon); try { master.setWifiPowerMode(BrickMaster.WIFI_POWER_MODE_LOW_POWER); } catch (Exception e) { e.printStackTrace(); } } // configure IR if(deviceIdentifier == BrickletDistanceIR.DEVICE_IDENTIFIER){ ir = new BrickletDistanceIR(uid, ipcon); try { ir.setDebouncePeriod(1000); ir.addDistanceReachedListener(this); if(thresholdSet){ ir.setDistanceCallbackThreshold('<', (short)(threshold), (short)0); } } catch (Exception e) { e.printStackTrace(); } } } }
8912e1e4-ba62-4aed-a35e-f5e10f1325f2
3
public void checkCells() { for (Cell temp : cells) { if (temp.openValues.size() == 1) { for (Cell temp1 : jointCell(temp)) { temp1.removeOpenValues(temp.returnValue()); } } } }
65b37090-ee65-47fe-90c4-7c3b679eff40
6
public void drawRoad(Road r, boolean highlighted, Graphics2D g2) { Player player = r.getOwner(); Graphics2D g2c = (Graphics2D) g2.create(); if (player == null) { if (highlighted) g2c.setColor(Color.WHITE); else return; } else { if (highlighted) return; else g2c.setColor(player.getColor()); } //System.out.println("Painted Road"); AffineTransform transformer = new AffineTransform(); //Polygon poly = new Polygon(); Point tileCenter = findCenter(r.getLocation().getXCoord(), r.getLocation().getYCoord()); int y = (int) tileCenter.getY(); int x = (int) tileCenter.getX(); int o = r.getLocation().getOrientation(); int height = hexagonSide / 10; Rectangle rect = new Rectangle(x,y, (int) (0.8 * hexagonSide), height); //System.out.println(y); //System.out.println(x); //System.out.println(o); if (o == 0){ transformer.rotate(Math.toRadians(150), x, y); transformer.translate(-(int)(0.45 * hexagonSide), (int)(0.80 * hexagonSide)); } else if (o == 1) { transformer.rotate(Math.toRadians(30), x, y); transformer.translate(-(int)(0.35 * hexagonSide), -(int)(0.90 * hexagonSide)); } else if (o == 2) { //transformer.translate(-(int) (0.4 * hexagonSide),-height/2); transformer.rotate(Math.toRadians(90), x, y); transformer.translate(-(int)(0.4 * hexagonSide),-(int)(0.92 * hexagonSide)); } g2c.transform(transformer); g2c.fill(rect); g2c.setColor(Color.BLACK); g2c.draw(rect); }
5d0395e1-b4cb-43ef-abb4-fc6b83d519cf
2
@Test public void getNextQuestionNumbers() { for (int i = 1; i < 10; i++) { assertEquals(i, st.getNextQuestionNumber()); if (i % 2 == 0) { st.incRightQuestions(); } else { st.incMistakeQuestions(); } } }
8cb765fc-0201-404c-8124-92d47b1c39f4
3
public void move(int xa, int ya, List<Block> blocks) { if (xa != 0 && ya != 0) { move(xa, 0, blocks); move(0, ya, blocks); return; } if (!collision(xa, ya, blocks)) { x += xa * speed; y += ya * speed; } }
41b75468-f706-4591-943c-120e11c2e2e3
0
public MainMenu(ProBotGame game) { super(game); // TODO Auto-generated constructor stub }
03a6e056-8fb0-42bb-adb7-ee078490898e
2
@Override public PixelEval call() throws Exception { for (int row = rs; row < re; row++) { for (int col = cs; col < ce; col++) { Ray ray = getRay(row, col, dx, dy); Color color = scene.getColor(scene.getClosest(ray)); image.setPixel(col, row, color); } } return this; }
556d9d30-1926-4d44-9f5d-da3328d6853f
7
public File saveSVGDialog(final JComponent parent) { File start = HOME; if(LAST_DIR.exists()) { try { final Scanner s = new Scanner(LAST_DIR, UTF8); if(s.hasNextLine()) { start = new File(s.nextLine().trim()); } s.close(); } catch(final IOException e) { // no worries } } final JFileChooser choose = new JFileChooser(start); choose.setFileFilter(new FileNameExtensionFilter("Vector image (*.svg)", "svg")); final boolean approved = choose.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION; final File res = approved ? choose.getSelectedFile() : null; if(res == null) return null; final File par = res.getParentFile(); final String name = res.getName(); try { final PrintWriter pw = new PrintWriter(LAST_DIR, UTF8); pw.println(par.toString()); pw.close(); } catch(final IOException e) { // no worries } if(!name.contains(".")) return new File(par, name + ".svg"); return res; }
338c50e2-9660-41e4-a8c0-b5800ad27ada
1
public static void main( String[] args ) throws UnknownHostException, IOException { WriteLog.initLogging(); try { MyBatisManager.initDBFactory("development", "Projects"); MyBatisManager.initDBFactory("development", "Data"); RequestProjectsSessionManager.initialize(); RequestDataSessionManager.initialize(); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } //число рабочих потоков, максимум памяти на 1 канал, максимальный суммарный размер памяти, время жизни //(int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit) ExecutorService bossExec = new OrderedMemoryAwareThreadPoolExecutor(1, 400000000, 2000000000, 60, TimeUnit.SECONDS); ExecutorService ioExec = new OrderedMemoryAwareThreadPoolExecutor(4 /* число рабочих потоков */, 400000000, 2000000000, 60, TimeUnit.SECONDS); // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory(bossExec, ioExec, 4 /* то же самое число рабочих потоков */)); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new ServerPipelineFactory()); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); }
6cdba56d-00e3-4228-a0a4-99a58781a7c9
8
@Override public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { final long lastPlayed = ( sender instanceof Player ? ((Player) sender).getLastPlayed() : System.currentTimeMillis() ); final List<Declaration> history = this.records.getHistory(); final int bodySize = History.PAGE_SIZE - (Main.courier.getBase().getString("history.footer").split("\\n").length); final int pageTotal = (history.size() / bodySize) + ( history.size() % bodySize > 0 ? 1 : 0 ); final int pageCurrent = ( args.length >= 1 ? History.parseInt(args[0], 1) : 1 ); if (pageCurrent <= 0 || pageCurrent > pageTotal) { Main.courier.send(sender, "unknown-argument", "page", 0, pageCurrent); return false; } final int first = (pageCurrent - 1) * bodySize; final int last = Math.min(first + bodySize, history.size()); int index = first; for (final Declaration message : history.subList(first, last)) { Main.courier.send(sender, "history.body", ( message.set > lastPlayed ? 1 : 0 ) , message.set, message.from, message.text , RecordKeeper.duration(System.currentTimeMillis() - message.set) , index); index++; } Main.courier.send(sender, "history.footer", pageCurrent, pageTotal, ( pageCurrent < pageTotal ? pageCurrent + 1 : 1 )); return true; }
24b20a8a-9842-484b-b628-3a1b2df24a4c
9
protected void processCommand(JSONModel jsonModel){ String type = ""; try { type = jsonModel.getString("_type"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } L.i("type", type); if (type.equals("launch_url")) { try { JSONObject obj = jsonModel.jsonObject; JSONObject argsObj = obj.getJSONObject("args"); String url = argsObj.getString("url"); launchUrl(url); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } waitForRequest(); } else if (type.equals("download_files")) { try { JSONObject obj = jsonModel.jsonObject; JSONObject argsObj = obj.getJSONObject("args"); JSONArray filesArr = argsObj.getJSONArray("files"); for (int i = 0; i < filesArr.length(); ++i) { JSONObject fileObj = filesArr.getJSONObject(i); String url = fileObj.getString("url"); String targetDir = fileObj.getString("targetdir"); downloadFile(url, targetDir); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (type.equals("upload_files")) { try { JSONObject obj = jsonModel.jsonObject; JSONObject cookieObj = obj.getJSONObject("request_cookie"); JSONObject argsObj = obj.getJSONObject("args"); JSONArray filesArr = argsObj.getJSONArray("files"); for (int i = 0; i < filesArr.length(); ++i) { String fname = filesArr.getString(i); uploadFile(fname, url); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
66700a31-e591-4535-a3a2-68fbe5a94a9a
4
Map<Pair<Class<?>, Class<?>>, TypeConverter<?, ?>> getRegistry() { return registry; }
20dca92f-db19-4cce-a517-67cdd20d03f6
6
public Face getOpposingFace() throws UnsupportedOperationException { switch ( this ) { case LEFT: return RIGHT; case RIGHT: return LEFT; case BOTTOM: return TOP; case TOP: return BOTTOM; case BACK: return FRONT; case FRONT: return BACK; } throw new UnsupportedOperationException( "Something's wrong about this face; index: " + value ); }
2f257d33-b0b0-4002-ae4f-17d7a14fbb89
2
public Money execute() throws IOException { Currency currency; Number amount = null; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean gotCorrect = false; while(!gotCorrect){ try{ System.out.println("Introduzca una cantidad de dinero"); amount = new Number(Double.parseDouble(reader.readLine())); gotCorrect = true; }catch(Exception e){ System.out.println(); System.out.println("Error: no se ha introducido una cantidad de dinero"); System.out.println(); continue; } } ConsoleCurrencyDialog currencyDialog = new ConsoleCurrencyDialog(); currency = currencyDialog.execute(); money = new Money(amount, currency); return money; }
93b5cbf7-2e24-4675-8f0a-2b92500bbf5b
6
@Override public int compareTo(Datum o) { // TODO: is there a better way of coding this? if (this.jaar > o.jaar) { return 1; } else if (this.jaar < o.jaar) { return -1; } else { // this.jaar == o.jaar if (this.maand > o.maand) { return 1; } else if (this.maand < o.maand) { return -1; } else { // this.maand == o.maand if (this.dag > o.dag) { return 1; } else if (this.dag < o.dag) { return -1; } else { // this.dag == o.dag; return 0; } } } }
c5dc1694-4aec-4ddd-8706-5bd0b246fb4b
0
public MultipleChoiceQuestView() { super(); this.add(new JLabel("Multi")); // quest = QuestFactory.createQuest(QuestType.CHOICEQUEST); addAnswersTable(); }
40b9d5c3-25eb-4efe-ac2e-cfb50494a897
1
protected Widget wdg() { Object wdg = local_widgets.get(wdgid); if (wdg instanceof Widget) { return (Widget) wdg; } else return null; }
58157011-480d-42f2-8edf-d094b9638583
2
public double rawAllResponsesMaximum(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawAllResponsesMaximum; }
3fc18622-9464-470b-a62c-5d02cb1dcaa1
3
private double[] computeTransform() { double[] frequencyData = null; FastFourierTransformer transformer = new FastFourierTransformer( DftNormalization.STANDARD); try { Complex[] complx = transformer.transform(dataToTransform, TransformType.FORWARD); frequencyData = new double[complx.length]; System.out.print("--->"); for (int i = 0; i < complx.length / 2; i++) { double rr = (complx[i].getReal()); double ri = (complx[i].getImaginary()); frequencyData[i] = Math.sqrt((rr * rr) + (ri * ri)); if (isLocalMax(frequencyData, i - 1)) { // System.out.println("----->" + i); long frequency = (long) (2 * Math.PI * i / (power2Size * 1f)); double magnitude = frequencyData[i]; frequencies.put(magnitude, frequency); // System.out.print(", " + (2 * Math.PI * i / (power2Size * // 1f))); } // int freqCoeff = (int) (TWO_POWER * frequencyData[i] / i); } //WaveDisplay frequency = new WaveDisplay(frequencyData, 0.02, 300); // System.out.println(Arrays.toString(frequencyData)); } catch (IllegalArgumentException e) { System.out.println(e); } return frequencyData; }
6ce571ae-3b77-4372-9d0e-8c8260413c50
0
public DcClient(String alias){ super(alias); inputAvailable = new Semaphore(0); inputBuffer = new LinkedList<byte[]>(); scheduler = DCConfig.schedulingMethod.getScheduler(); mb = new MessageBuffer(DCPackage.PAYLOAD_SIZE - scheduler.getScheduleSize()); // We initially don't know the current round of the network // therefore this is initialized to a sentinel value nextRound = -1; // -1 is the sentinel value for 'no round is scheduled for us' nextScheduledRound = -1; lastScheduledRound = -1; }
1d9cdddc-62eb-45e6-a56a-9663ac34077d
2
private static String createNode(HardwareAlternative hardwareAlternative, boolean showAllAlternativeComponents) { String node = ""; if (showAllAlternativeComponents) for (HardwareComponent hardwareComponent : hardwareAlternative.getHardwareComponents()) node += "\t\t<nestedNode xmi:id=\"" + hardwareComponent.getId() + "\" name=\"" + hardwareComponent.getName() + "\"/>\n"; else node += "\t\t<nestedNode xmi:id=\"" + hardwareAlternative.getId() + "\" name=\"" + hardwareAlternative.getName() + "\"/>\n"; return node; }
b2aae2e1-2b5c-4f88-abe0-2a6cb895b930
9
public void ignoreMultiLineComment() { // this method is called by nextChar() in the event that a '/*' // has been encountered. The method will simply pull off all characters // until the stop sequence of '*/' is encountered. lookedAhead = false; boolean removingComments = true; char pluckedChar = ' '; System.out.println("ignoreMultiLineComment called..."); int num = 0; while (removingComments) { try { num = inputStream.read(); if (num < 0) { num = '$'; eot = true; break; } } catch (IOException e) { e.printStackTrace(); } pluckedChar = (char) num; System.out.println("pluckedChar: " + pluckedChar); System.out.println("lookedAhead: " + lookedAhead); // System.out.println(""); if (pluckedChar == '*') { char next = ' '; if (lookedAhead) { next = previewedChar; lookedAhead = false; } else { next = peek(); lookedAhead = true; } System.out.println("next: " + next); if (next == '/') { lookingForFirstCharOfToken = true; previewedChar = ' '; lookedAhead = false; currentChar = ' '; break; } else if (next == '*') { System.out.println("next is a star!!"); while (next == '*') { next = peek(); if (next == '/') { System.out .println("peeked and found slash after star."); removingComments = false; lookingForFirstCharOfToken = true; previewedChar = ' '; lookedAhead = false; currentChar = ' '; break; } } } } }// end while loop }// end of method
6d976ef7-3c36-4ae0-b084-3ffc869566b4
3
public void updateUI() { privatekey.setEnabled(!DaEncrypter.symmetric()); if (input.getText().isEmpty()) { output.setText(""); return; } if (key.getText().isEmpty()) { return; } String outputTxt; if (decrypt) { outputTxt = DaEncrypter.decrypt(input.getText(), (String) cipher.getSelectedItem()); } else { outputTxt = DaEncrypter.encrypt(input.getText(), (String) cipher.getSelectedItem()); } output.setText(outputTxt); }
92f1e91f-f725-482f-976f-35bcc9931434
0
@RequestMapping(value = "getById.json", method = RequestMethod.GET) public String getModelById(@RequestParam int id, ModelMap model) { List<Employee> employee = employeeDao.getAll(); model.addAttribute(employee); return "jsonView"; }
3fee3c70-ce52-4110-b226-b07bc300bc39
7
public void paintComponent(Graphics g) { paintScreens(g); if(startGame) { g.setColor(new Color(75,75,75)); //background color g.fillRect(0, 0, getWidth(), getHeight()); //Clear screen. g.setColor(new Color(0, 0, 0)); //border color for(int i = 0; i < myBorder + 1; i++) { g.drawLine( room.block[0][room.worldWidth-1].x + room.blockSize + i, 0, room.block[0][room.worldWidth-1].x + room.blockSize + i, room.block[room.worldHeight-1][0].y + room.blockSize ); //right border g.drawLine( room.block[0][0].x - i, 0, room.block[0][0].x - i, room.block[room.worldHeight-1][0].y + room.blockSize + i ); //left border g.drawLine( room.block[0][0].x - myBorder + 1, room.block[room.worldHeight-1][0].y + room.blockSize + i, room.block[0][room.worldWidth-1].x + room.blockSize + myBorder, room.block[room.worldHeight-1][0].y + room.blockSize + i ); //drawing bottom border. } room.draw(g); //Drawing the room. for(int i = 0; i < mobs.length; i++) { if(mobs[i].inGame) { mobs[i].draw(g); } } store.draw(g); //Drawing the store. if(health < 1) { g.setColor(new Color(240, 20, 20)); g.fillRect(0, 0, myWidth, myHeight); g.setColor(new Color(255, 255, 255)); g.setFont(new Font("Courier New", Font.BOLD, 14)); g.drawString("GAME OVER, GET BACK TO WORK YOU BAFOON!", 10, 10); } if(isWin) { g.setColor(new Color(255,255,255)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(0, 0, 0)); g.setFont(new Font("Courier New", Font.BOLD, 14)); if(level > maxLevel) { g.drawString("Congratulations you beat the game! The window will now close...", 10, 10); } else { g.drawString("You beat the level! Please wait for next level...", 10, 10); } } } }
c064db97-96a8-43ba-8b1f-06dd27a0725d
2
public List<Map<TableArticle, Integer>> getBestSellers(Connection conn) { String sql = "select id_article, sum(qty_contains) as qty_sold " + "from article natural join cart_contains_article " + "where ( " + "select date_checkout " + "from cart where cart.id_cart = cart_contains_article.id_cart " + ") >= DATE_SUB( NOW(), INTERVAL 7 DAY ) " + "group by id_article " + "order by qty_sold desc ;"; PreparedStatement pstm = preparedStatementWrapper(conn, sql); ResultSet rset = queryWrapper(pstm); List<Map<TableArticle, Integer>> result = new ArrayList<Map<TableArticle, Integer>>() ; Map<TableArticle, Integer> row; try { while(rset.next()){ row = new HashMap<TableArticle, Integer>(); row.put( read(conn, rset.getInt(1) ), rset.getInt(2) ); result.add(row); } } catch (SQLException e) { e.printStackTrace(); } return result; }
2e2ded09-9251-4b90-b87f-c42244a8c300
4
@Override public void create() { addPart(new Explosion(new Position(getNextPosition().getX(), getNextPosition().getY()))); if(currentDir == -1) { //Special case to handle starting position. currentDir++; } else { distance++; } if((distance == power || stopNextStep) && currentDir < getDirectionList().size() - 1) { stopNextStep = false; currentDir++; distance = 0; } }
c3265734-6564-4075-b511-d73b299d1b33
6
public HashMap<String, LiveRange> getLiveRanges() { HashMap<String, LiveRange> liveRanges = new HashMap<String, LiveRange>(); for(int i = 0; i < lines.size(); i++) { String[] lineParams = lines.get(i).split(","); for(int j = 1; j < lineParams.length; j++) { String key = lineParams[j].replaceAll("\\s", ""); if(SymbolTable.getVariable(key) != null || SymbolTable.getTemporary(key) != null || SymbolTable.getArray(key) != null) { if(liveRanges.keySet().contains((key))) { //Find the LiveRange for this variable in the hashmap liveRanges.get(key).setEnd(i); } else { //This is the first time this variable has been seen liveRanges.put(key, new LiveRange(i)); } } } } return liveRanges; }
86c74f1a-693b-44c4-bf95-6510ac322861
9
private void downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { URL fileUrl = new URL(this.versionLink); final int fileLength = fileUrl.openConnection().getContentLength(); in = new BufferedInputStream(fileUrl.openStream()); fout = new FileOutputStream(new File(this.updateFolder, file.getName())); final byte[] data = new byte[Updater.BYTE_SIZE]; int count; if (this.announce) { this.plugin.getLogger().info("About to download a new update: " + this.versionName); } long downloaded = 0; while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); final int percent = (int) ((downloaded * 100) / fileLength); if (this.announce && ((percent % 10) == 0)) { this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } } catch (Exception ex) { this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } } catch (final IOException ex) { this.plugin.getLogger().log(Level.SEVERE, null, ex); } try { if (fout != null) { fout.close(); } } catch (final IOException ex) { this.plugin.getLogger().log(Level.SEVERE, null, ex); } } }
846ee318-e2dc-45dc-acbf-713081f3669f
6
private boolean loadPoints() { clearCollections(); int retval = fc.showOpenDialog(this); if(retval == JFileChooser.APPROVE_OPTION) { points_loaded = false; File file= fc.getSelectedFile(); String filename = file.getAbsolutePath(); log.append("Loading points from " + filename + "\n"); try { Scanner in = new Scanner(new File(filename)); ArrayList<Point> pointList = new ArrayList<Point>(3000); while (in.hasNext()) { int x = in.nextInt(); int y = in.nextInt(); if(x > maxX) maxX = x; if(y > maxY) maxY = y; pointList.add(new Point(x,y)); /* Scanner scan = new Scanner(in.nextLine()); ArrayList<Integer> ps = new ArrayList<Integer>(3); while(scan.hasNext()) ps.add(scan.nextInt()); points.add(new Point(ps)); */ } points = new QuadTree(pointList); points_loaded = true; } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not load file " + filename+", file not found", "Critical Error", JOptionPane.ERROR_MESSAGE); } catch (InputMismatchException e) { JOptionPane.showMessageDialog(null, "Could not load file " + filename+". This file does not match input format of n" + " whitespace separated integers on each line", "Critical Error", JOptionPane.ERROR_MESSAGE); } } tglbtnStart.setEnabled(true); return points_loaded; }
05ebf1b2-1cb7-4faf-ba5d-c1c7649aad38
7
@Override public boolean next(PixelRayBuffer b) { if( totalSamples == targetSamples ) return false; b.vectorSize = (int)Math.min(targetSamples - totalSamples, b.maxVectorSize); if( screenX == null || screenX.length < b.vectorSize ) { screenX = new double[b.vectorSize]; screenY = new double[b.vectorSize]; } int i; for( i=0; i<b.vectorSize; ++i, ++x ) { if( x >= imageWidth ) { x = 0; ++y; } if( y >= imageHeight ) { y = 0; } b.index[i] = x + y*imageWidth; screenX[i] = (x + rand.nextDouble()) * (viewX1 - viewX0) / imageWidth + viewX0; screenY[i] = (y + rand.nextDouble()) * (viewY1 - viewY0) / imageHeight + viewY0; } projection.project(b.vectorSize, screenX, screenY, b.ox, b.oy, b.oz, b.dx, b.dy, b.dz); for( i=0; i<b.vectorSize; ++i ) { // Apply transformation!! pixelOffset.set(b.ox[i], b.oy[i], b.oz[i]); pixelDirection.set(b.dx[i], b.dy[i], b.dz[i]); MatrixMath.multiply( cameraTransform, pixelOffset, rayOffset ); MatrixMath.multiplyRotationOnly( cameraTransform, pixelDirection, rayDirection ); b.ox[i] = rayOffset.x; b.oy[i] = rayOffset.y; b.oz[i] = rayOffset.z; b.dx[i] = rayDirection.x; b.dy[i] = rayDirection.y; b.dz[i] = rayDirection.z; } totalSamples += b.vectorSize; return true; }
f1eeff7d-2c97-4f17-b187-a066d7000159
3
@Override public void caseAParanthesisHexp(AParanthesisHexp node) { //for(int i=0;i<indent;i++) System.out.print(" "); //indent++; //System.out.println("("); inAParanthesisHexp(node); if(node.getLPar() != null) { node.getLPar().apply(this); } if(node.getExp() != null) { node.getExp().apply(this); } if(node.getRPar() != null) { node.getRPar().apply(this); } outAParanthesisHexp(node); }
cfc54531-7438-441f-86ae-ea96533e0ca8
6
public Status solve() { Object solved = this.solvedCopy(); if (solved.getClass() != Grid.class) { return (Status) solved; } history.add(Change.marker()); for (int i = 0; i < size*size; i++) { for (int j = 0; j < size*size; j++) { if (grid[i][j].value() == 0) { grid[i][j].fill(((Grid) solved).grid[i][j].value()); history.add(new Change(i, j, 0, Change.NORMAL, false)); if (autoPossBasic) { for (int n : grid[i][j].poss()) { grid[i][j].poss().remove(n); history.add(new Change(i, j, n, Change.POSS_ADD, false)); } } } } } return Status.SOLVED; }
76d5c3b6-3730-4863-b2d7-cacf44ac5cbd
7
public int countWords(String s){ int wordCount = 0; boolean word = false; int endOfLine = s.length() - 1; for (int i = 0; i < s.length(); i++) { // if the char is a letter, word = true. if (Character.isLetter(s.charAt(i)) && i != endOfLine) { word = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(s.charAt(i)) && word) { wordCount++; word = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) { wordCount++; } } return wordCount; }
58baab94-3a58-4fc6-a0ae-4dd9ca40edf7
4
@Override public List<Frage> getZufallsFragen(Modul modul) { List<Frage> result = new ArrayList<Frage>(); try { PersistenceService database = PersistenceServiceImpl.getInstance(); ResultSet rSet = database.sendQuery("Select * from frage LIMIT 10"); Vector<Vector<String>> vec = database.getResultVector(rSet); if (database.hasResults(vec)) { for(int j = 0; j<=vec.size(); j++){ int i = 1; //Werte aus der Datenbank holen int fragenummer = Integer.parseInt(vec.get(0).get(i++)); Minutes loesungszeit = Minutes.valueOf(Integer.parseInt(vec.get(0).get(i++))); String fragestellung = vec.get(0).get(i++); String musterloesung = vec.get(0).get(i++); int fragenartInt = Integer.parseInt(vec.get(0).get(i++)); // fragenartInt der Klasse FreitextFrage zuweisen FreitextFrage fragenart = null; switch (fragenartInt) { case 3: FreitextFrage.valueOf(); break; default: ; break; } //Objekt frage erzeugen und dem Rückgabeliste hinzufügen Frage frage = FrageImpl.valueOf(fragenummer, loesungszeit, fragestellung, musterloesung, fragenart); result.add(frage); } } System.out.println(vec.toString()); database.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
917eea67-c681-469c-9239-3ef949697755
7
private void run() { while(running) { if(derpMode) { table.setBackground(new Color(rng.nextInt(256),rng.nextInt(256),rng.nextInt(256))); } if(filterString != null) { if(searchBar != null) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (searchBar.getText()!=null && !filterString.equals(searchBar.getText().toLowerCase())) { filterString = searchBar.getText().toLowerCase(); updateTable(); } } } else { System.out.println("Da heck is this?"); } } destroy(); }
e112a5ff-f0c5-4722-8582-d995c706e9b2
9
public void update() throws MaltChainedException { // Retrieve the address value final AddressValue arg1 = addressFunction1.getAddressValue(); final AddressValue arg2 = addressFunction2.getAddressValue(); try { if (arg1.getAddress() == null || arg2.getAddress() == null) { featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE)); featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE)); featureValue.setNullValue(true); } else { final DependencyNode node1 = (DependencyNode)arg1.getAddress(); final DependencyNode node2 = (DependencyNode)arg2.getAddress(); int head1 = -1; int head2 = -1; if ( node1.hasHead() ) { head1 = node1.getHead().getIndex(); //lines below don't seem to work //head1 = Integer.parseInt(node1.getHeadEdgeLabelSymbol(column.getSymbolTable())); //if ( node1.hasHeadEdgeLabel(column.getSymbolTable()) ) // head1 = Integer.parseInt(node1.getHeadEdgeLabelSymbol(column.getSymbolTable())); } if ( node2.hasHead() ) { head2 = node2.getHead().getIndex(); //lines below don't seem to work //head2 = Integer.parseInt(node2.getHeadEdgeLabelSymbol(column.getSymbolTable())); //if ( node2.hasHeadEdgeLabel(column.getSymbolTable()) ) // head2 = Integer.parseInt(node2.getHeadEdgeLabelSymbol(column.getSymbolTable())); } if (!node1.isRoot() && head1 == node2.getIndex()) { featureValue.setIndexCode(table.getSymbolStringToCode("LEFT")); featureValue.setSymbol("LEFT"); featureValue.setNullValue(false); } else if (!node2.isRoot() && head2 == node1.getIndex()) { featureValue.setIndexCode(table.getSymbolStringToCode("RIGHT")); featureValue.setSymbol("RIGHT"); featureValue.setNullValue(false); } else { featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE)); featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE)); featureValue.setNullValue(true); } } } catch (NumberFormatException e) { throw new FeatureException("The index of the feature must be an integer value. ", e); } // featureValue.setKnown(true); featureValue.setValue(1); }
67659b08-a391-49d1-bc4c-ce4f7af47559
1
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated if (!ACTIVATED) { reloadTimer(); ACTIVATED = true; } }//GEN-LAST:event_formWindowActivated
0863f73e-2568-47a2-a32e-11a4f82c1207
0
public List getDecoders() { return Collections.unmodifiableList(decoders); }
627c1c8e-e440-4274-991f-c2286e680dff
1
@Test public void testArray() throws Exception{ FileWriter FW = getFileWriter(); TestClass[] tests = FW.getArray("arr",new TestClass()); assert tests.length == testArray.length; for(int i=0;i<tests.length;i++){ assert tests[i].val==testArray[i]; } }
7c09b787-0000-498b-94d3-a40ae946d53e
6
public boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); }
f3bbe6be-4554-4f0a-98b0-334309e23a6f
7
private void search(TrieNode node, int row, int col) { if (row < 0 || row >= rows || col < 0 || col >= cols) { return; } if (visited[row][col]) { return; } char boardChar = board[row][col]; TrieNode next = node.getNext(boardChar); if (next == null) { return; } if (next.end != null) { result.add(next.end); } visited[row][col] = true; search(next, row, col + 1); search(next, row, col - 1); search(next, row + 1, col); search(next, row - 1, col); visited[row][col] = false; }
2d1fd85e-c54d-4768-b708-751828ae4053
8
public void run() { while (true) { try { loadWorlds(); } catch (DynmapInitException e) { logger.warn("Error in getting new Worlds", e); } players = new ArrayList<>(); alreadyPlayers = new ArrayList<>(); for (Map.Entry<String, DynmapWorldConfig> dynmapWorldConfig : new HashMap<>(dynmapWorldConfigs).entrySet()) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(getFile("standalone" + File.separator + "dynmap_" + dynmapWorldConfig.getKey() + ".json").getInputStream()))) { dynmapWorldConfig.setValue(gson.fromJson(reader, DynmapWorldConfig.class)); dynmapWorldConfigs.put(dynmapWorldConfig.getKey(), dynmapWorldConfig.getValue()); for (Player player : dynmapWorldConfig.getValue().getPlayers()) { if (!alreadyPlayers.contains(player.getName())) { alreadyPlayers.add(player.getName()); players.add(player); } } } catch (FileNotFoundException e) { logger.warn("Could not update Dynmap World", e); } catch (IOException e) { logger.warn("Could not update Dynmap World", e); } } try { Thread.sleep(updateInterval * 1000); } catch (InterruptedException e) { logger.warn("Interrupted", e); return; } } }
b8c44c22-8bfc-41b3-96c4-d635490bf7f9
9
void doStep() { boolean v1 = volts[0] > 2.5; boolean v2 = volts[1] > 2.5; if (v1 && !pins[0].value) ff1 = true; if (v2 && !pins[1].value) ff2 = true; if (ff1 && ff2) ff1 = ff2 = false; double out = (ff1) ? 5 : (ff2) ? 0 : -1; //System.out.println(out + " " + v1 + " " + v2); if (out != -1) sim.stampVoltageSource(0, nodes[2], pins[2].voltSource, out); else { // tie current through output pin to 0 int vn = sim.nodeList.size()+pins[2].voltSource; sim.stampMatrix(vn, vn, 1); } pins[0].value = v1; pins[1].value = v2; }
64fcf5a9-2629-428f-90a6-590297dd59d6
2
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub BDConexion bd = new BDConexion(); bd.conectar(); ResultSet consulta = bd.seleccionar(); try { while(consulta.next()){ response.getWriter().print("fila en base de datos <br>"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
236f733f-98db-48e5-af7d-284ef754085b
1
public DBBasedCobweb(){ // init data for(int i=0;i<2;i++){ this.staticList.add("a"); } }
3ed5e7b3-cf12-4b3c-943f-f62d37897f58
7
byte[] buildBrushAA(byte[] brush, CPBrushInfo brushInfo) { int intSize = (int) (brushInfo.curSize + .99f); float center = intSize / 2.f; float sqrRadius = (brushInfo.curSize / 2) * (brushInfo.curSize / 2); float sqrRadiusInner = ((brushInfo.curSize - 2) / 2) * ((brushInfo.curSize - 2) / 2); float sqrRadiusOuter = ((brushInfo.curSize + 2) / 2) * ((brushInfo.curSize + 2) / 2); float xFactor = 1f + brushInfo.curSqueeze * MAX_SQUEEZE; float cosA = (float) Math.cos(brushInfo.curAngle); float sinA = (float) Math.sin(brushInfo.curAngle); int offset = 0; for (int j = 0; j < intSize; j++) { for (int i = 0; i < intSize; i++) { float x = (i + .5f - center); float y = (j + .5f - center); float dx = (x * cosA - y * sinA) * xFactor; float dy = (y * cosA + x * sinA); float sqrDist = dx * dx + dy * dy; if (sqrDist <= sqrRadiusInner) { brush[offset++] = (byte) 0xff; } else if (sqrDist > sqrRadiusOuter) { brush[offset++] = 0; } else { int count = 0; for (int oj = 0; oj < 4; oj++) { for (int oi = 0; oi < 4; oi++) { x = i + oi * (1.f / 4.f) - center; y = j + oj * (1.f / 4.f) - center; dx = (x * cosA - y * sinA) * xFactor; dy = (y * cosA + x * sinA); sqrDist = dx * dx + dy * dy; if (sqrDist <= sqrRadius) { count += 1; } } } brush[offset++] = (byte) Math.min(count * 16, 255); } } } return brush; }
16265f7d-d9e2-4785-a754-63ec1aad9edc
6
public void charger(Element deplacement,Partie partie) { //ATTENTION A NE PAS TOUCHER int positionDepart = Integer.valueOf(deplacement.getChildText("caseDepart")); int positionArriver = Integer.valueOf(deplacement.getChildText("caseArriver")); CouleurCase couleur; if (positionDepart==0) couleur = CouleurCase.BLANC; else if (positionDepart==25) couleur = CouleurCase.NOIR; else if (positionArriver==0) couleur = CouleurCase.NOIR; else if (positionArriver==25) couleur = CouleurCase.BLANC; else if(positionDepart < positionArriver) couleur = CouleurCase.BLANC; else if(positionDepart > positionArriver) couleur = CouleurCase.NOIR; else couleur = CouleurCase.VIDE; caseDepart = partie.getTablier().getCase(positionDepart,couleur); caseArriver = partie.getTablier().getCase(positionArriver,couleur); siCaseBattue = Boolean.valueOf(deplacement.getChildText("siCaseBattue")); }
aa646743-99aa-4c33-aae6-2d27345d99ef
0
@RequestMapping(method = RequestMethod.POST, value = "") public Task postTask(@RequestBody TaskCreateRequest request) { Integer taskId = tasksService.createTask(request.getJournalId(), request.getTaskName()).getId(); return tasksService.getById(taskId); }
b8a14e57-528a-4084-8e08-73a81bfeaff4
8
public Event createItemFromElement(DomElement element) { // if (element == null) // return null; Event event = new Event(); ImageHolder.loadImages(event, element); event.id = Integer.parseInt(element.getChildText("id")); event.title = element.getChildText("title"); event.description = element.getChildText("description"); event.url = element.getChildText("url"); if (element.hasChild("attendance")) event.attendance = Integer.parseInt(element.getChildText("attendance")); if (element.hasChild("reviews")) event.reviews = Integer.parseInt(element.getChildText("reviews")); try { event.startDate = DATE_FORMAT.parse(element.getChildText("startDate")); if (element.hasChild("endDate")) { event.endDate = DATE_FORMAT.parse(element.getChildText("endDate")); } } catch (ParseException e1) { // Date format not valid !?, should definitely not happen. } event.headliner = element.getChild("artists").getChildText("headliner"); event.artists = new ArrayList<String>(); for (DomElement artist : element.getChild("artists").getChildren("artist")) { event.artists.add(artist.getText()); } event.website = element.getChildText("website"); event.tickets = new ArrayList<TicketSupplier>(); if (element.hasChild("tickets")) { for (DomElement ticket : element.getChild("tickets").getChildren("ticket")) { event.tickets.add(new TicketSupplier(ticket.getAttribute("supplier"), ticket.getText())); } } if(element.hasChild("venue")) event.venue = ResponseBuilder.buildItem(element.getChild("venue"), Venue.class); return event; }
f52d1a2a-eed7-45f9-ae04-d357f67dd0ee
2
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doGet(req, res); header("Programme de la saison"); if (!testConnection()){ footer(); return; } try { out.println(ConvertHTML.vectorProgrammeToHTML(BDRequetes.getRepresentations(null), false)); } catch (BDException e) { out.println("<h1>"+e.getMessage()+"</h1>"); } footer(); }
42580dad-c2ed-45bb-94a7-ae42440a631c
7
public void stats(Stage stage) { if(Keybinds.CANCEL.clicked()) { closeMenu(); } else if(Keybinds.MENU_RIGHT.clicked()) { gameMenuType = GameMenuType.EQUIPMENT; buildGameMenu(stage); } else if(Keybinds.MENU_LEFT.clicked()) { gameMenuType = GameMenuType.OPTIONS; buildGameMenu(stage); } else if(Keybinds.MENU_DOWN.clicked()) { if(partyMember + 1 < stage.party.getMembers().size()) partyMember++; else partyMember = 0; } else if(Keybinds.MENU_UP.clicked()) { if(partyMember > 0) partyMember--; else partyMember = stage.party.getMembers().size() - 1; } }
a8c227ba-0a87-4681-85af-93b2fda08fb5
6
private void updatePlayingBall() { if (ballY >= 0.95 || ballY <= -0.95) { ballYSpeed = -ballYSpeed; } //Left Paddle (AI) if (ballX <= -0.9) { if (isLeftPaddlePresent(ballY)) { this.ballXSpeed = -this.ballXSpeed; } else { playerScore+=1; resetRandomBall(); } } else if (ballX >= 0.9) { if (isRightPaddlePresent(ballY)) { this.ballXSpeed = -this.ballXSpeed; } else { AIScore+=1; resetRandomBall(); } } ballX += ballXSpeed; ballY += ballYSpeed; updateAIPaddle(); updatePlayerPaddle(); }
733f8bc0-9260-4320-93d8-535c96e97156
6
@Override public void run() { if (Updater.this.url != null) { // Obtain the results of the project's file feed if (Updater.this.read()) { if (Updater.this.versionCheck(Updater.this.versionName)) { if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { String name = Updater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (Updater.this.versionLink.endsWith(".zip")) { final String[] split = Updater.this.versionLink.split("/"); name = split[split.length - 1]; } Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); } else { Updater.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } }
28513443-edcf-4db2-9e53-cbf2f76d4611
7
static void add(File f, int index) throws FileNotFoundException, IOException { File in = new File (ExtractorModel.appDir + "/" + "bookmarks.txt"); File out = new File(ExtractorModel.appDir + "/" + "tmp.txt"); out.createNewFile(); try(FileOutputStream fout = new FileOutputStream(out); PrintWriter pw = new PrintWriter(fout); FileInputStream fin = new FileInputStream(in)) { BufferedReader br = new BufferedReader(new InputStreamReader(fin)); String s = br.readLine(); String sink; boolean flag = false; int hash = hash(f.getName()); while(s != null) { StringTokenizer test = new StringTokenizer(s); sink = s; if(Integer.parseInt(test.nextToken()) == hash) { for(int i = 0; i < 4; i++) { bookmarksIndex[i] = Integer.parseInt(test.nextToken()); } sink = "" + hash; if(bookmarksIndex[0] == -1) { bookmarksIndex[0] = index; } else if(bookmarksIndex[1] == -1) { bookmarksIndex[1] = index; } else if(bookmarksIndex[2] == -1) { bookmarksIndex[2] = index; } else { bookmarksIndex[2] = index; } sink += " " + bookmarksIndex[0] + " " + bookmarksIndex[1] + " " + bookmarksIndex[2] + " " + bookmarksIndex[3]; flag = true; } pw.append(sink + "\n"); s = br.readLine(); } if(!flag) { pw.append(hash + " "+ index + " -1 -1 -1\n"); } } in.delete(); out.renameTo(in); }
06e1fdd5-3926-4bd7-bcf6-5b9f75ca84b2
7
private void sortHeap(int[] array) { if(array==null || array.length==0) { return; } for(int i=array.length-1;i>0;i--) { int biggest = array[0]; array[0] = array[i]; array[i] = biggest; // percolateDown int hole = 0+1; int child = 0; int current = array[hole-1]; for(;hole*2<=i;hole=child) { child = hole*2; if(child!=i&&array[child]>array[child-1]) { child++; } if(current<array[child-1]) { array[hole-1] = array[child-1]; } else { break; } } array[hole-1] = current; } }
649a6da3-5979-4b48-815b-bdfd1501cfe2
6
public int getFromMemory(int start, int offset) { if(start >= 0x10010000 && start <= 0x10010000 + 4*1024) return data.get(start+offset); if(start <= 0x7FFFEFFF && start >= 0x7FFFEFFF-2*1024) return stack.get(start+offset); if(start >= 0x00400000 && start <= 0x00400000 + 2*1024) return instr.get(start+offset); return 0; }
c8771f8d-11f2-4d9d-8a3b-97c2cc81759f
2
public static final boolean isObjectiveC(String fileName) { for (String file : OBJECTIVE_C) { if (file.equals(fileName)) { return true; } } return false; }
fe7b9ed0-2526-42f6-a3af-ad7f1bb5efd4
1
private void visiteurQuitter() { if (ctrlMenu == null) { ctrlMenu = new CtrlMenu(this); } ctrlVisiteur.getVue().setVisible(false); ctrlMenu.getVue().setEnabled(true); ctrlMenu.getVue().setVisible(true); }
b8794679-8ebb-458e-ab26-16049cdfa974
4
public void setPlayer2Score(int score){ boolean test = false; if (test || m_test) { System.out.println("Drawing :: setPlayer2Score() BEGIN"); } m_player2Score.setText("" + score); if (test || m_test) System.out.println("Drawing:: setPlayer2Score() - END"); }
85859561-5d1b-4dc6-99ef-80c498951570
1
@Test public void laskeRivitTest(){ List<Palikka> palikat = new ArrayList<Palikka>(); for (int i = 1; i < 10; i++){ palikat.add(new Palikka(i, 19)); } ai.lisaaKentalle(palikat); Muodostelma muod = new Muodostelma(Muoto.L, peli); ai.siirraMuodostelma(muod, 0); ai.pudotaMuodostelma(muod); int rivit = ai.laskeRivit(muod); assertEquals(1, rivit); }
a2158afe-a9c8-4ece-b64b-99f6215be1e9
6
public Set<Map.Entry<K,Short>> entrySet() { return new AbstractSet<Map.Entry<K,Short>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TObjectShortMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if ( o instanceof Map.Entry ) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TObjectShortMapDecorator.this.containsKey( k ) && TObjectShortMapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator<Map.Entry<K,Short>> iterator() { return new Iterator<Map.Entry<K,Short>>() { private final TObjectShortIterator<K> it = _map.iterator(); public Map.Entry<K,Short> next() { it.advance(); final K key = it.key(); final Short v = wrapValue( it.value() ); return new Map.Entry<K,Short>() { private Short val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals( key ) && ( ( Map.Entry ) o ).getValue().equals( val ); } public K getKey() { return key; } public Short getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Short setValue( Short value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<K,Short> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked K key = ( ( Map.Entry<K,Short> ) o ).getKey(); _map.remove( key ); modified = true; } return modified; } public boolean addAll(Collection<? extends Map.Entry<K,Short>> c) { throw new UnsupportedOperationException(); } public void clear() { TObjectShortMapDecorator.this.clear(); } }; }
6acd9c22-7bb4-4597-b658-c78fe9102e4e
9
public String getNExt(String name) { String res = ""; int lastposOflang = name.lastIndexOf("_"); if (lastposOflang == -1) { // pas de _XX if (verbose) { System.out.println("no extension _XX:" + name); } return res; } // System.out.println("last:" + name.substring(lastposOflang, lastposOflang + 3)); // System.out.println("dot:" + name.substring(lastposOflang+ 3, lastposOflang + 4)); if (!name.substring(lastposOflang + 3, lastposOflang + 4).equals(".")) { // pas de _XX. if (verbose) { System.out.println("no dot _XX.:" + name); } return res; } res = name.substring(lastposOflang, lastposOflang + 3); String ok = extension.get(res); if (ok == null) { if (verbose) { System.out.println("not in corpus languages:" + name); } return ""; } if (lastposOflang < 3) { // seulement une seule extensiion return res; } lastposOflang -= 3; // positionne sur l'extension d'avant while (extension.get(name.substring(lastposOflang, lastposOflang + 3)) != null) { // oui une nouvelle extension res = name.substring(lastposOflang, lastposOflang + 3) + res; if (lastposOflang < 3) { // plus possible return res; } lastposOflang -= 3; } return res; }
6dfd4ef4-4020-4236-b826-835bdd8f0e60
7
static void dradb4(int ido,int l1,float[] cc,float[] ch, float[] wa1, int index1, float[] wa2, int index2, float[] wa3, int index3){ int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8; float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4; t0=l1*ido; t1=0; t2=ido<<2; t3=0; t6=ido<<1; for(k=0;k<l1;k++){ t4=t3+t6; t5=t1; tr3=cc[t4-1]+cc[t4-1]; tr4=cc[t4]+cc[t4]; tr1=cc[t3]-cc[(t4+=t6)-1]; tr2=cc[t3]+cc[t4-1]; ch[t5]=tr2+tr3; ch[t5+=t0]=tr1-tr4; ch[t5+=t0]=tr2-tr3; ch[t5+=t0]=tr1+tr4; t1+=ido; t3+=t2; } if(ido<2)return; if(ido!=2){ t1=0; for(k=0;k<l1;k++){ t5=(t4=(t3=(t2=t1<<2)+t6))+t6; t7=t1; for(i=2;i<ido;i+=2){ t2+=2; t3+=2; t4-=2; t5-=2; t7+=2; ti1=cc[t2]+cc[t5]; ti2=cc[t2]-cc[t5]; ti3=cc[t3]-cc[t4]; tr4=cc[t3]+cc[t4]; tr1=cc[t2-1]-cc[t5-1]; tr2=cc[t2-1]+cc[t5-1]; ti4=cc[t3-1]-cc[t4-1]; tr3=cc[t3-1]+cc[t4-1]; ch[t7-1]=tr2+tr3; cr3=tr2-tr3; ch[t7]=ti2+ti3; ci3=ti2-ti3; cr2=tr1-tr4; cr4=tr1+tr4; ci2=ti1+ti4; ci4=ti1-ti4; ch[(t8=t7+t0)-1]=wa1[index1+i-2]*cr2-wa1[index1+i-1]*ci2; ch[t8]=wa1[index1+i-2]*ci2+wa1[index1+i-1]*cr2; ch[(t8+=t0)-1]=wa2[index2+i-2]*cr3-wa2[index2+i-1]*ci3; ch[t8]=wa2[index2+i-2]*ci3+wa2[index2+i-1]*cr3; ch[(t8+=t0)-1]=wa3[index3+i-2]*cr4-wa3[index3+i-1]*ci4; ch[t8]=wa3[index3+i-2]*ci4+wa3[index3+i-1]*cr4; } t1+=ido; } if(ido%2 == 1)return; } t1=ido; t2=ido<<2; t3=ido-1; t4=ido+(ido<<1); for(k=0;k<l1;k++){ t5=t3; ti1=cc[t1]+cc[t4]; ti2=cc[t4]-cc[t1]; tr1=cc[t1-1]-cc[t4-1]; tr2=cc[t1-1]+cc[t4-1]; ch[t5]=tr2+tr2; ch[t5+=t0]=sqrt2*(tr1-ti1); ch[t5+=t0]=ti2+ti2; ch[t5+=t0]=-sqrt2*(tr1+ti1); t3+=ido; t1+=t2; t4+=t2; } }
076ed160-5732-475f-83ad-ac2be7014844
8
public void lerpToGameObject(GameObject object, double xOffset, double yOffset, double delta, double pps) { if (x < object.getX() + xOffset) { x += delta * pps; if (x > object.getX() + xOffset) { x = object.getX() + xOffset; } } else if (x > object.getX() + xOffset) { x -= delta * pps; if (x < object.getX() + xOffset) { x = object.getX() + xOffset; } } if (y < object.getY() + yOffset) { y += delta * pps; if (y > object.getY() + yOffset) { y = object.getY() + yOffset; } } else if (y > object.getY() + yOffset) { y -= delta * pps; if (y < object.getY() + yOffset) { y = object.getY() + yOffset; } } }
56b64504-cb9c-4d18-8441-eca89543fc53
3
private String makeKingPilesMove(CardGame game) { switch (moveTypeTo) { case TO_ACE_PILES: return game.moveCardOntoAceFromKing(indexFrom, indexTo); case TO_KING_PILES: return "Can only move to a pile of the same suit"; case TO_HAND: return "Cannot move to hand."; } return "ERROR"; }
9e482a83-888d-4b92-9cd0-0bd331dbe88b
0
public void setVisiteur(String visiteur) { this.visiteur = visiteur; }
197afd6d-5658-4ad9-845a-981b6c8a1efb
7
public Result iddfs_helper(Integer i) { Deque<Node> stack = new ArrayDeque<Node>(); int nodesProcessed = 0; stack.addFirst(initial); while(!stack.isEmpty()) { Node temp = stack.removeFirst(); nodesProcessed++; if(temp.getCost() <= i) { if(temp.getState().equals(finalState)) { long endTime = System.currentTimeMillis(); Deque<Grid.Direction> pathStack = new ArrayDeque<Grid.Direction>(); pathStack.add(temp.getDirection()); Node temp2 = temp.getParent(); while(temp2.getParent() != null) { pathStack.addFirst(temp2.getDirection()); temp2 = temp2.getParent(); } StringBuilder pathTaken = new StringBuilder(pathStack.size()); if(!pathStack.peek().toString().equals(null)) { while(!pathStack.isEmpty()) { pathTaken.append(pathStack.removeFirst().toString()); } } return new Result(pathTaken.toString(), nodesProcessed, endTime); } else { for(Node n: temp.successors()) { stack.addFirst(n); } } } } return new Result("n", nodesProcessed, 0); }
659e2f20-db74-4121-8cdb-e39c39a86504
1
public void Listen() { if (reader == null) return; readerthread = new Reader(this); readerthread.start(); pm.server.Log("Listening.."); }
634bac6a-74c5-4aee-8ed1-e0e198a599f4
7
public static void playSound(String pathToFX) { try { soundFile = new File(pathToFX); } catch (Exception e) { e.printStackTrace(); } try { audioStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e) { e.printStackTrace(); } audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } sourceLine.start(); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { @SuppressWarnings("unused") int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); } } sourceLine.drain(); sourceLine.close(); }
e90b03ad-18bb-461e-8757-cb23fbfdd77e
3
void incluirValoracion(UsuarioRegistrado usuario, float puntuacion){ boolean existe = existeContenidoValorado(usuario); if (existe){ for (ContenidoValorado contenidoValorado : misvaloraciones) { if (contenidoValorado.getAutor() == usuario) contenidoValorado.modificarPuntiacion(puntuacion); } }else{ ContenidoValorado nuevo = new ContenidoValorado(puntuacion, usuario); misvaloraciones.add(nuevo); } }
40227f17-5af7-4ec1-80d7-d165ea0b6f95
8
public Matrix solve (Matrix B) { if (B.getRowDimension() != n) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!isspd) { throw new RuntimeException("Matrix is not symmetric positive definite."); } // Copy right hand side. double[][] X = B.getArrayCopy(); int nx = B.getColumnDimension(); // Solve L*Y = B; for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { for (int i = 0; i < k ; i++) { X[k][j] -= X[i][j]*L[k][i]; } X[k][j] /= L[k][k]; } } // Solve L'*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { for (int i = k+1; i < n ; i++) { X[k][j] -= X[i][j]*L[i][k]; } X[k][j] /= L[k][k]; } } return new Matrix(X,n,nx); }
67c0dfe6-8fe5-4565-a21f-6abf1811d9aa
4
public static List<String[]> getData() throws IOException { final List<String[]> data = new ArrayList<String[]>(); final URL url = new URL("http://fluid.com/repo/info.php"); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Fluid"); conn.setRequestProperty("Cookie", getCookie(url)); final PrintWriter writer = new PrintWriter(conn.getOutputStream()); writer.write("id=" + VBLogin.self.getUserId()); writer.flush(); conn.connect(); if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) { String line; final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = reader.readLine(); if (line != null) { final Matcher arrays = Pattern.compile("\\[(.*?)\\]").matcher(line); while (arrays.find()) { final Matcher items = Pattern.compile("\\{(.*?)\\}").matcher(arrays.group(1)); final String[] info = new String[13]; int i = 0; while (items.find()) { info[i++] = items.group(1); } data.add(info); } } } return data; }
e60aec38-f06f-419e-9912-6dce3a64caed
2
private void lab(EnvironnementAbs environnement){ int x; int y; x = environnement.taille_envi/2; for(y = environnement.taille_envi/8; y < environment.taille_envi-(environnement.taille_envi/8) + 1; y++){ environment.grille[x][y] = new Mur("Mure", x, y); environment.grille[y][x] = new Mur("Mure", y, x); } x = environment.taille_envi/3; for (y = 0;y< environment.taille_envi/3+1;y++){ environment.grille[x][y] = new Mur("Mure", x, y); environment.grille[y][(environment.taille_envi - 1) - x] = new Mur("Mure", y, (environment.taille_envi - 1) - x); environment.grille[(environment.taille_envi - 1) - x][(environment.taille_envi - 1) - y] = new Mur("Mure", (environment.taille_envi - 1) - x, (environment.taille_envi - 1) - y); environment.grille[(environment.taille_envi - 1) - y][x] = new Mur("Mure", (environment.taille_envi - 1) - y, x); } }
3ef30f33-164b-44b2-af09-429dfeee4812
0
public void setActive(Component component) { tabbed.setSelectedComponent(component); // The change event should be automatically distributed by the // model of the tabbed pane }
bee11c0b-099b-4566-a0be-c14baf3361e8
0
public void setMonthStored(Month m) { monthStored = new Month (m); }
b8336a27-ad5a-4111-9a22-736dbf4b8540
9
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("DisassemblyTool [-f <format style>] <file or class name>"); System.out.println(); System.out.println("The format style may be \"assembly\" (the default) or \"builder\""); return; } String style; String name; if ("-f".equals(args[0])) { style = args[1]; name = args[2]; } else { style = "assembly"; name = args[0]; } ClassFileDataLoader loader; InputStream in; try { final File file = new File(name); in = new FileInputStream(file); loader = new ClassFileDataLoader() { public InputStream getClassData(String name) throws IOException { name = name.substring(name.lastIndexOf('.') + 1); File f = new File(file.getParentFile(), name + ".class"); if (f.exists()) { return new FileInputStream(f); } return null; } }; } catch (FileNotFoundException e) { if (name.endsWith(".class")) { System.err.println(e); return; } loader = new ResourceClassFileDataLoader(); in = loader.getClassData(name); if (in == null) { System.err.println(e); return; } } in = new BufferedInputStream(in); ClassFile cf = ClassFile.readFrom(in, loader, null); PrintWriter out = new PrintWriter(System.out); Printer p; if (style == null || style.equals("assembly")) { p = new AssemblyStylePrinter(); } else if (style.equals("builder")) { p = new BuilderStylePrinter(); } else { System.err.println("Unknown format style: " + style); return; } p.disassemble(cf, out); out.flush(); }
2546e741-720d-4f5b-8505-e8984f725188
3
void activateProject(String idx) { try { int i = Integer.parseInt(idx); if (i > -1 && i < workCombo.getItemCount()) { workCombo.setSelectedIndex(i); } } catch (NumberFormatException E) { } }
6e0ff176-df7f-472c-ae7c-b8a3e53a6164
6
public void reorderList(ListNode head) { if (head == null || head.getNext() == null || head.getNext().getNext() == null) { return; } //use the slow and fast, to divide the list into two parts ListNode slow = head; ListNode fast = head; while (fast != null && fast.getNext() != null) { slow = slow.getNext(); fast = fast.getNext().getNext(); } ListNode secondHead = slow.getNext(); //avoid loop slow.setNext(null); secondHead = reverse(secondHead); ListNode current = head; //link the two parts together while (secondHead != null) { ListNode temp = secondHead.getNext(); secondHead.setNext(current.getNext()); current.setNext(secondHead); current = current.getNext().getNext(); secondHead = temp; } }