method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
48dae354-de86-4a19-b4c6-3fc4e710b46b
8
protected void createDOMElement() { Document doc = BLXUtility.createDOMDocument(); if(this.getObjectType() == this.OBJECT_TYPE) domElement = doc.createElementNS("blx", BLX_NS+":"+this.BLX_OBJ_NODE_NAME); else domElement = doc.createElementNS("blx", BLX_NS+":"+this.BLX_COMP_NODE_NAME); //Populate domElement with correct information domElement.setAttribute(BLX_CLASS_NAME_ATTR, this.getClassName()); //Service Name if(serviceName != null) { domElement.setAttribute(BLX_SERVICE_NAME_ATTR, serviceName); } else { //Ext Name if(extName != null) domElement.setAttribute(BLX_EXT_NAME_ATTR, extName); //Ext Version if(extVersion != null) domElement.setAttribute(BLX_EXT_VERSION_ATTR, extVersion); //Ext HREF if(extHREF != null) domElement.setAttribute(BLX_EXT_HREF_ATTR, extHREF); } //HREF of Data if(getHREF()!=null) domElement.setAttribute(BLX_HREF_ATTR, this.getHREF()); //ID if(getID()!=null) domElement.setAttribute(BLX_OBJ_ID, getID()); //Popukate Component Information if(getObjectType() == this.COMP_TYPE) { domElement.setAttribute(BLX_COMP_X_ATTR, "" + getX()); domElement.setAttribute(BLX_COMP_Y_ATTR, "" + getY()); domElement.setAttribute(BLX_COMP_WIDTH_ATTR, "" + getWidth()); domElement.setAttribute(BLX_COMP_HEIGHT_ATTR, "" + getHeight()); } }
132badf2-32e3-46fb-a64d-d3feac7ed780
2
protected void addConnection(int x, int y, boolean input, String name) { for (Component c : getComponents()) if (c.getName().equals(name)) throw new InvalidParameterException("Connection already exists with name: " + name); Connection c = new Connection(name, input); c.setBounds(x * Logicator.gridSize, y * Logicator.gridSize, Logicator.gridSize, Logicator.gridSize); add(c); }
94374ad6-80f4-4c30-9340-cec80670e3ac
8
private List<Arg> getArgs(String[] args) { List<Arg> argumentList = new ArrayList<Arg>(); if (args.length == 0 || args[0].charAt(0) != '-') { argumentList.add(Arg.CODE_GENERATOR); return argumentList; } else { for (String parameterizedArg : args) { if (parameterizedArg.charAt(0) == '-') { boolean isValidArgument = false; for (Arg arg : Arg.values()) { if (parameterizedArg.equals(arg.toString())) { argumentList.add(arg); isValidArgument = true; break; } } if (!isValidArgument) { return ExceptionHandler.getInstance().throwException(Exception.INVALID_ARGS, ExceptionStrength.STRONG); } } } if (argumentList.size() > 2) { return ExceptionHandler.getInstance().throwException(Exception.NUMBER_OF_ARGS, ExceptionStrength.STRONG); } else { return argumentList; } } }
68ff1d9d-1049-4e8e-b37e-00cc4200a9ec
5
private JSONObject getResponseFromCookie(HttpServletRequest request) { Map<String, String> previousIdps = new HashMap<String, String>(); String last = ""; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String name = cookie.getName(); if (name.equals("previousIdPs")) { try { String decoded = Base64Coder.decodeString(cookie.getValue()); getCookieValues(decoded, previousIdps); } catch (Exception ex) { getCookieValues("", previousIdps); } } if (name.equals("lastIdp")) { last = cookie.getValue(); } } } return getResponseJson(last, previousIdps, true, true); }
41a0b9fb-70ac-4013-b025-8937d407c25c
1
public void ARPStorm(byte[] targetIP) { // Generates a storm of poison ARPs boolean kill = true; // A kill control variable while (kill == true) { // While kill is true ARPPacket p = this.ARPGen(targetIP); // Generate a new ARP packet targeted at the targetIP parameter inject.inject(p); // Injects the poison } }
2d33ff1a-36bf-4271-a3c6-48da3ed79413
6
protected int countDifferences(Vector<Boolean> oldValue, Vector<Boolean> newValue) { if (oldValue.equals(newValue)) { return 0; } if (oldValue.size() <= newValue.size()) { int result = 0; for (int i = 0; i < oldValue.size(); i++) { if (oldValue.get(i) != newValue.get(i)) { result = result + 1; } } for (int j = oldValue.size(); j < newValue.size(); j++) { if (newValue.get(j)) { result = result + 1; } } return result; } return countDifferences(newValue, oldValue); }
7f59b1ab-b1bf-4444-930a-0e34cc01985d
9
private boolean step() throws LexicalError, SyntaticError, SemanticError { if (currentToken == null) { int pos = 0; if (previousToken != null) pos = previousToken.getPosition()+previousToken.getLexeme().length(); currentToken = new Token(DOLLAR, "$", pos); } int x = ((Integer)stack.pop()).intValue(); int a = currentToken.getId(); if (x == EPSILON) { return false; } else if (isTerminal(x)) { if (x == a) { if (stack.empty()) return true; else { previousToken = currentToken; currentToken = scanner.nextToken(); return false; } } else { throw new SyntaticError(PARSER_ERROR[x], currentToken.getPosition()); } } else if (isNonTerminal(x)) { if (pushProduction(x, a)) return false; else throw new SyntaticError(PARSER_ERROR[x], currentToken.getPosition()); } else // isSemanticAction(x) { if(executaAcoesSemanticas) { semanticAnalyser.executeAction(x-FIRST_SEMANTIC_ACTION, previousToken); } return false; } }
8ba43955-597a-49e1-b7ad-80768b05023a
0
public String toString() { return super.toString(); }
fa50288c-f147-45b7-a195-933b4204c71c
4
public void toTwoD(){ double[] hold0 = (double[])this.point.clone(); double[] hold1 = new double[2]; boolean test1 = true; for(int i=2; i<this.nDimensions; i++){ if(hold0[i]!=0.0)test1 = false; } if(test1){ for(int i=0; i<2; i++)hold1[i] = hold0[i]; this.point = hold1; this.nDimensions = 2; } else{ throw new IllegalArgumentException("There are non-zero values in the coordinate positions greater than 2D"); } }
fa5b5d07-ef32-4800-b5cc-338a6ff912c0
2
public static SaleType build(String saleTypeStr) { switch(saleTypeStr) { case("分销"): return DISTRIBUTION; case("承销"): return UNDERWRITTING; } throw new IllegalArgumentException("错误的销售方式字符串{" + saleTypeStr + "}"); }
ca90be96-feda-4b54-92ba-8b3a636cf6ff
3
private boolean isaNonFoodItem(Material item){ Material i = item; if(i == Material.WATER_BUCKET || i == Material.BOWL || i == Material.POTION){ return true; }else{ return false; } }
3106abc9-4c8b-4cb2-8ace-a997e25f4f55
1
public Stats mutateClone() { HashMapStats myClone = new HashMapStats(); for (Stat stat : stats.values()) { myClone.put(new Stat(stat.getType(), stat.getValue() * Random.getGaussian(0.5, 1.5))); } return myClone; }
a10052de-6b73-467a-861d-eedae9a651fe
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(McDsAd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(McDsAd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(McDsAd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(McDsAd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new McDsAd().setVisible(false); } }); }
1cc345a5-ccf3-40f3-963f-e49a833e7ebd
2
@Override public void caseAExplist(AExplist node) { inAExplist(node); if(node.getExp() != null) { node.getExp().apply(this); } { List<PExprest> copy = new ArrayList<PExprest>(node.getExprest()); for(PExprest e : copy) { e.apply(this); } } outAExplist(node); }
fbf70e5f-9e2c-4137-8569-48b6d6958f68
1
private double calcMLon () { double add = 0; for (int i = 0; i < nbrPoints; i++) { add = add + positions.get(i).getLongitude(); } double result = add / nbrPoints; return (result); }
cd16a260-a360-4bb5-8452-68e6ea0c26b4
6
public Configuration start(String[] args) { try { // Load and validate properties System.out.println(" -- Loading and validating configuration"); Configuration config = loadAndValidateProperties(); if (config.inputDir == null || config.inputDir.trim().length() == 0) { System.out.println(" -- No configuration found, using defaults and command line parameters"); } else { System.out.println(" -- Configuration loaded and validated"); } // Load command line arguments loadCommandLineArgs(args, config); // Make sure we have at least an input dir if (config.inputDir == null) { return null; } if (config.faultyFileCopyDir == null || config.faultyFileCopyDir.trim().length() == 0) { System.out.println("No output directory has been configured or specified, faulty files will not be copied"); } return config; } catch (Exception e) { logManager.logGeneral(e.getMessage()); logManager.logGeneral("Program exiting"); System.err.println(e.getMessage()); System.err.println("Program exiting"); } return null; }
1c93b91d-dad1-47da-ae69-1c990e660e40
7
@SuppressWarnings("deprecation") @EventHandler public void onEntityRegainHealth(EntityRegainHealthEvent event) { if (enabled) { if (event.getEntity() instanceof Player) { if (victims.containsValue(((Player) event.getEntity()).getName())) { for (String name : victims.keySet()) { Player attacker = Bukkit.getPlayer(name); Player victim = Bukkit.getPlayer(victims.get(name)); if (victim == event.getEntity()) { if (attacker.hasPermission("bossbar.use") && BarAPI.hasBar(attacker)) { new SetBossBar(attacker, victim, prefix, suffix).runTaskLater(this, 0L); } } } } } } }
a1076dcd-94aa-44d0-9b28-39d9b67d5b9b
2
public PdfDocument addAbsolutePosition(PdfElement element) { try { if (!element.setPosition(pdfwriter.getDirectContent(), document .getPageSize().getWidth(), document.getPageSize() .getHeight())) { document.add(element.getPdfElement()); } } catch (DocumentException e) { e.printStackTrace(); } return this; }
995f2dd4-d3c9-4615-93e4-baa54c1165e3
3
@SuppressWarnings("unchecked") private static void loader() { try { for(String name : typeNames) types.add( (Class<? extends Pet>)Class.forName(name)); } catch(ClassNotFoundException e) { throw new RuntimeException(e); } }
14efa211-6e19-4514-814e-573558c6b801
2
public boolean isCarrying() { Layered layered = gob().getattr(Layered.class); if (layered != null) { return layered.containsLayerName("gfx/borka/body/standing/arm/banzai/") || layered.containsLayerName("gfx/borka/body/walking/arm/banzai/"); } return false; }
6ab96f50-f44f-4c6d-8f19-ac21472206c6
5
public void keyboard() { String defualt_key = config.getKeyBinding(); log.logDebug("The defualt keyboard key is: " + defualt_key); KeyBindingManager bindingmanager = SpoutManager.getKeyBindingManager(); bindingmanager.registerBinding("Start vote!", keyboard_translate.Translate(defualt_key), "Starts a new voting session.", new BindingExecutionDelegate() { @Override public void keyPressed(KeyBindingEvent arg0) { // Check if player is in chat if (arg0.getScreenType() == ScreenType.GAME_SCREEN) { log.logDebug("Player: " + arg0.getPlayer().getName() + " has pressed the keybind!"); // Make sure that the player doesn't start another vote on a separate world if (player_started_a_vote.containsKey(arg0.getPlayer())) { if (!player_started_a_vote.get(arg0.getPlayer())) { if (votestarthandler.onCommand(arg0.getPlayer(), vote_session_world, votes, voted)) { runVote(arg0.getPlayer().getWorld()); vote_session_world = votestarthandler.vote_session_world(); votes = votestarthandler.votes(); voted = votestarthandler.voted(); player_world.put(arg0.getPlayer(), arg0.getPlayer().getWorld()); player_started_a_vote.put(arg0.getPlayer(), true); } } else { arg0.getPlayer().sendMessage(chat.chatWarning(languagehandler.voteAlreadyStarted())); } } else { if (votestarthandler.onCommand(arg0.getPlayer(), vote_session_world, votes, voted)) { runVote(arg0.getPlayer().getWorld()); vote_session_world = votestarthandler.vote_session_world(); votes = votestarthandler.votes(); voted = votestarthandler.voted(); player_world.put(arg0.getPlayer(), arg0.getPlayer().getWorld()); player_started_a_vote.put(arg0.getPlayer(), true); } } } } @Override public void keyReleased(KeyBindingEvent arg0) { // Unused } }, this); }
ad81929f-d067-4f84-ab02-1ccdf770b1d2
8
public static void main(String[] args) { //1.) System.out.println("1.)\n"); OrderedSet<Description> s = new OrderedSet<Description>(); Description d1 = new Description("abcdefg\nhijklmnop\nqrstuvw\nxyz"); Description d2 = new Description("111111111\n222222"); Description d3 = new Description("ABC\n123\n987"); Description d4 = new Description("*****\n**-**\n*---*\n**-**\n*****"); s.insert(d1); s.insert(d2); s.insert(d3); s.insert(d4); Iterator<Description> it1 = s.iterator(); Description d = null; while(it1.hasNext()) { d = it1.next(); System.out.println(d.toString()); System.out.println("Rows: " +d.countRows()+ "\n"); } System.out.println("**************"); OrderedSet<Description> s2 = new OrderedSet<Description>(); s2.insert(d2); s2.insert(d3); s2.insert(d1); s2.insert(d4); Iterator<Description> it2 = s2.iterator(); while(it2.hasNext()) { d = it2.next(); System.out.println(d.toString()); System.out.println("Rows: " +d.countRows()+ "\n"); } System.out.println(); //2.) System.out.println("2.)\n"); OrderedMap<MeanElapsedTime, CompositeTime> m = new OrderedMap<MeanElapsedTime, CompositeTime>(); MeanElapsedTime e1 = new MeanElapsedTime(); MeanElapsedTime e2 = new MeanElapsedTime(); e1.addTime(3.98); e1.addTime(5.03); e1.addTime(0.01); e1.addTime(8.99); e2.addTime(1.03); e2.addTime(65.4); e2.addTime(7.28); e2.addTime(9.14); m.insert(e1); m.insert(e2); CompositeTime e3 = new CompositeTime(new Double[]{2.03, 4.5, 1.09, 7.8}); CompositeTime e4 = new CompositeTime(new Double[]{1.5, 3.01, 50.4, 80.0}); OrderedMap.MapIterator<MeanElapsedTime, CompositeTime> it3 = m.iterator(); MeanElapsedTime e = null; while(it3.hasNext()) { e = it3.next(); OrderedMap.MapElementIterator<CompositeTime> w = it3.iterator(); w.add(e3); System.out.println("MeanElapsedTime:"); System.out.print(e.toString()); System.out.println("maxval: " +e.getMaxValue()+ "\n"); for(CompositeTime ct : it3) { System.out.println("CompositeTime:"); System.out.print(ct.toString()); System.out.println("minval: " +ct.getMinValue()); } System.out.println(); } System.out.println("***********"); OrderedMap<MeanElapsedTime, CompositeTime> m2 = new OrderedMap<MeanElapsedTime, CompositeTime>(); m2.insert(e2); m2.insert(e1); it3 = m2.iterator(); while(it3.hasNext()) { e = it3.next(); OrderedMap.MapElementIterator<CompositeTime> w = it3.iterator(); w.add(e4); System.out.println("MeanElapsedTime:"); System.out.print(e.toString()); System.out.println("maxval: " +e.getMaxValue()+ "\n"); for(CompositeTime ct : it3) { System.out.println("CompositeTime:"); System.out.print(ct.toString()); System.out.println("minval: " +ct.getMinValue()); } System.out.println(); } //3.) System.out.println("3.)"); OrderedSet<MeanElapsedTime> s3 = m; MeanElapsedTime e5 = new MeanElapsedTime(); MeanElapsedTime e6 = new MeanElapsedTime(); e5.addTime(1.2); e5.addTime(6.3); e6.addTime(7.0); e6.addTime(4.11); s3.insert(e5); s3.insert(e6); Iterator<MeanElapsedTime> it4 = s3.iterator(); while(it4.hasNext()) { e = it4.next(); System.out.println("maxval: " +e.getMaxValue()); } System.out.println(); //4.) System.out.println("4.)"); OrderedSet<ElapsedTime> s4 = new OrderedSet<ElapsedTime>(); s4.insert(e1); s4.insert(e2); s4.insert(e3); s4.insert(e4); Iterator<ElapsedTime> it = s4.iterator(); ElapsedTime et = null; while(it.hasNext()) { et = it.next(); System.out.print(et); System.out.println("size = " + et.count()); System.out.println(); } }
70ff106d-1549-4cad-a036-8c7e6e341a65
3
public Rectangle getVisibleBoundaries( Graphics g ){ Rectangle result = null; for( GraphPaintable paintable : paintables ){ Rectangle boundaries = paintable.getVisibleBoundaries( g ); result = union( result, boundaries ); } for( Component child : canvas.getComponents() ){ Rectangle boundaries = child.getBounds(); result = union( result, boundaries ); } if( result == null ){ result = new Rectangle( 0, 0, 50, 50 ); } return result; }
a45e2e75-4715-4ca9-92e4-40461a41947c
4
public int climbStairs(int n) { if (n ==0 || n == 1 || n == 2){ return n; } else{ int result = 0; int First = 1, Second = 2; for (int i = 2; i < n; i++){ result = First + Second; First = Second; Second = result; } return result; } }
608e5e19-2d93-41b2-973b-dec99462a0ec
5
public void updateAction() { if(actionList.hasAction() || currentAction != null) { if(currentAction == null) { currentAction = actionList.poolCurrentAction(); currentAction.setStartTime(System.nanoTime()); } else { if(currentAction.isOver()) { currentAction.endAction(); currentAction = null; } else if(currentAction.isReady()) { currentAction.performAction(); } } } }
c5b78baa-7833-4769-8358-b8444ee02ac7
1
public CategoryDAO CategoryDAO(){ if (categoryDAO == null){ categoryDAO = new CategoryDAOImpl(); } return categoryDAO; }
3ceb37cd-ee91-416b-893f-5613ac770024
5
public boolean isSyncMark(int headerstring, int syncmode, int word) { boolean sync = false; if (syncmode == INITIAL_SYNC) { //sync = ((headerstring & 0xFFF00000) == 0xFFF00000); sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 } else { sync = ((headerstring & 0xFFF80C00) == word) && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if (sync) sync = (((headerstring >>> 10) & 3)!=3); // filter out invalid layer if (sync) sync = (((headerstring >>> 17) & 3)!=0); // filter out invalid version if (sync) sync = (((headerstring >>> 19) & 3)!=1); return sync; }
64f767b6-912c-4b88-9797-053130b308c3
2
public Torrent getMode(String str) { if (str.equals("single")) return Torrent.SINGLE; else if (str.equals("multi")) return Torrent.MULTI; else return Torrent.UNKNOWN; }
a4e53a3b-6869-4e03-835c-13cd62ae06aa
5
public static void merge(double[] input, int lo, int mid, int hi) { // Must use auxilliary array. In-place merge is a lot harder. See book. double[] aux = new double[hi - lo]; // Merge into aux int i = lo; int j = mid; for (int m = 0; m < aux.length; m++) { if (i >= mid) { aux[m] = input[j++]; } else if (j >= hi) { aux[m] = input[i++]; } else if (Helper.less(input, i, j)) { aux[m] = input[i++]; } else { aux[m] = input[j++]; } } // Copy back for (int m = 0; m < aux.length; m++) { input[m + lo] = aux[m]; Helper.exch(input, m + lo, m + lo); // Hack to draw the copy process } }
5c3886c4-cb77-4d31-a4b4-86fb0ea2059e
0
@Test public void storeAndRetrieve() { final String expected = "stored object"; cache.put(cacheKey, expected); String actual = cache.get(cacheKey, String.class); assertSame(expected, actual); }
25db89b0-4301-4b2d-9190-6c208203e5c1
4
private void write(SelectionKey key) throws IOException { try{ SocketChannel socketChannel = (SocketChannel) key.channel(); synchronized (this.pendingData) { List<ByteBuffer> queue = (List<ByteBuffer>) this.pendingData.get(socketChannel); // Write until there's not more data ... while (!queue.isEmpty()) { ByteBuffer buf = (ByteBuffer) queue.get(0); socketChannel.write(buf); if (buf.remaining() > 0) { // ... or the socket's buffer fills up break; } queue.remove(0); } if (queue.isEmpty()) { // We wrote away all data, so we're no longer interested // in writing on this socket. Switch back to waiting for // data. key.interestOps(SelectionKey.OP_READ); } } }catch(Exception e){e.printStackTrace();} }
4c87fc07-a560-445e-bb04-8bc7705f4040
0
public PeerID(byte[] data, int tries) { this.data = data; this.tries = tries; }
808ef7b2-8b47-4748-808f-62b76782f4cb
8
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException { try { org.apache.axis.client.Call _call = super._createCall(); if (super.maintainSessionSet) { _call.setMaintainSession(super.maintainSession); } if (super.cachedUsername != null) { _call.setUsername(super.cachedUsername); } if (super.cachedPassword != null) { _call.setPassword(super.cachedPassword); } if (super.cachedEndpoint != null) { _call.setTargetEndpointAddress(super.cachedEndpoint); } if (super.cachedTimeout != null) { _call.setTimeout(super.cachedTimeout); } if (super.cachedPortName != null) { _call.setPortName(super.cachedPortName); } java.util.Enumeration keys = super.cachedProperties.keys(); while (keys.hasMoreElements()) { java.lang.String key = (java.lang.String) keys.nextElement(); _call.setProperty(key, super.cachedProperties.get(key)); } return _call; } catch (java.lang.Throwable _t) { throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t); } }
49ab215e-55d1-4103-aaad-d32827a17322
8
public void testCanHaveImprovement() { for (TileType tileType : spec().getTileTypeList()) { if (tileType.isWater()) { if (highSeas.equals(tileType)) { assertFalse(tileType.canHaveImprovement(fishBonusLand)); assertFalse(tileType.canHaveImprovement(fishBonusRiver)); } else { assertTrue(tileType.canHaveImprovement(fishBonusLand)); assertTrue(tileType.canHaveImprovement(fishBonusRiver)); } assertFalse(tileType.canHaveImprovement(river)); assertFalse(tileType.canHaveImprovement(road)); assertFalse(tileType.canHaveImprovement(plow)); assertFalse(tileType.canHaveImprovement(clearForest)); } else { if (tileType.isForested()) { assertTrue(tileType.canHaveImprovement(clearForest)); } else { assertFalse(tileType.canHaveImprovement(clearForest)); } if (arctic.equals(tileType) || hills.equals(tileType) || mountains.equals(tileType)) { assertFalse(tileType.canHaveImprovement(river)); assertFalse(tileType.canHaveImprovement(plow)); } else { assertTrue(tileType.canHaveImprovement(river)); if (tileType.isForested()) { assertFalse(tileType.canHaveImprovement(plow)); } else { assertTrue(tileType.canHaveImprovement(plow)); } } assertTrue(tileType.canHaveImprovement(road)); } } }
7861ab30-a89b-4817-95c4-8f33ceb0e873
0
public TrayIcon getTrayIcon() { return trayIcon; }
b125822d-ea68-4ad5-a08d-966579dd7583
8
private void smoothingFilter(int rad) { int size = 2*rad+1; float [] k = getBlurKernel(2*rad+1); for (int y=0; y < height; y++) { for (int x=0; x < width; x++) { int i = y*width + x; if (plotList[i] != null) { float sum = 0; float n = 0; for (int dy = -rad, ky = 0; dy<=rad; dy++, ky+=size ){ int y_ = Math.max(Math.min(y+dy,height-1),0); int offset = y_*width; for (int dx = -rad, kx = 0; dx<=rad; dx++, kx++ ) { int x_ = x+dx; if (x_ < 0) x_ = 0; if (x_ > width-1) x_ = width-1; //int x_ = Math.max(Math.min(x+dx,width-1),0); int j = offset + x_; if (plotList[j] != null) { float f = k[ky+kx]; sum += f* (plotList[j].lumt -128); n += f; } } } // plotList[i].lumf = (int) (sum / n); // plotList[i].z = plotList[i].lumf - 128; plotList[i].z = (int) (sum / n); plotList[i].lumf = plotList[i].z + 128; } } } }
9fd47106-d843-4a8b-9d2e-0d4dfdc6b6c7
1
@Override public int rowsY() { return isNotPlayerInventory() ? 1 : 2; }
5b9f8c8e-f551-4288-acec-c1d0456776b8
4
private double internalReadDouble(int code) throws IOException { switch (code) { case Codes.DOUBLE: return is.readRawDouble(); case Codes.DOUBLE_0: return 0.0D; case Codes.DOUBLE_1: return 1.0D; default: { Object o = read(code); if (o instanceof Double) { return (Double) o; } else { throw expected("double", code, o); } } } }
9daf4511-a78a-495d-bb06-e9e87962c002
9
public short deinitialize() { short ret = MsgDumperCmnDef.MSG_DUMPER_SUCCESS; if (t.isAlive()) { try { // If the user does NOT notify the thread to die, notify it before waiting for its death if (!exit.get()) { ret = notify_to_deinitialize(); if (MsgDumperCmnDef.CheckMsgDumperFailure(ret)) { MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Fail to notify to de-initialize the MsgDumper%s object", msg_dumper.get_facility_name()); return ret; } } t.join(3000); String debug_msg = "The thread is dead"; MsgDumperCmnDef.WriteDebugSyslog(__FILE__(), __LINE__(), debug_msg); if (!silent_mode) System.out.println("The thread is dead"); } catch (InterruptedException e) { String warn_msg = "Error occur while waiting for thread's death: " + e.toString(); MsgDumperCmnDef.WriteWarnSyslog(__FILE__(), __LINE__(), warn_msg); if (!silent_mode) System.out.println(warn_msg); } catch(Exception e) { String errmsg = "Error: " + e.toString(); MsgDumperCmnDef.WriteErrorSyslog(__FILE__(), __LINE__(), errmsg); if (!silent_mode) System.out.println(errmsg); } } // De-initialize the msg_dumper object ret = msg_dumper.deinitialize(); if (MsgDumperCmnDef.CheckMsgDumperFailure(ret)) { MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Fail to de-initialize the MsgDumper%s object", msg_dumper.get_facility_name()); return ret; } return MsgDumperCmnDef.MSG_DUMPER_SUCCESS; }
c56522d2-75d4-4dfe-aa86-6c0587e27fad
9
public static void main(String[] args) throws IOException{ InputStream entradaSistema = System.in; InputStreamReader leitor = new InputStreamReader(entradaSistema); BufferedReader leitorEntrada = new BufferedReader(leitor); String entradaTeclado; char menuOpcao; char opcao='0'; ControleConta umControle = new ControleConta(); ContaPoupanca contaPoupanca = new ContaPoupanca(); ContaCorrente contaCorrente = new ContaCorrente(); do{ System.out.println("Bem vindo ao Conta Bancaria.\n"); System.out.println(" - Menu - \n"); System.out.println("1- Adicionar nova conta; \n"); System.out.println("2- Acessar conta.\n"); System.out.println("Opcao escolhida: \n"); entradaTeclado = leitorEntrada.readLine(); menuOpcao = entradaTeclado.charAt(0); switch(menuOpcao){ case '1': System.out.println("Digite o nome do titular: \n"); entradaTeclado = leitorEntrada.readLine(); String umTitular = entradaTeclado; System.out.println("Digite o numero da conta: \n"); entradaTeclado = leitorEntrada.readLine(); String umNumero = entradaTeclado; System.out.println("Digite a agencia da conta: \n"); entradaTeclado = leitorEntrada.readLine(); String umaAgencia = entradaTeclado; System.out.println("Digite o saldo inicial da conta: \n"); entradaTeclado = leitorEntrada.readLine(); double umSaldo = Double.parseDouble(entradaTeclado); System.out.println("Digite a senha da conta: \n"); entradaTeclado = leitorEntrada.readLine(); String umaSenha = entradaTeclado; System.out.println("Digite o tipo de conta: \n 1- Conta Corrente\n 2- Conta Poupanca\n "); entradaTeclado = leitorEntrada.readLine(); double tipo = Double.parseDouble(entradaTeclado); if(tipo==1){ System.out.println("Digite o rendimento de Poupanca: \n "); entradaTeclado = leitorEntrada.readLine(); double rendimento = Double.parseDouble(entradaTeclado); contaPoupanca.setTitular(umTitular); contaPoupanca.setNumero(umNumero); contaPoupanca.setAgencia(umaAgencia); contaPoupanca.setSaldo(umSaldo); contaPoupanca.setSenha(umaSenha); contaPoupanca.setRendimento(rendimento); umControle.adicionar(contaPoupanca); } else if(tipo==2){ System.out.println("Digite o limite do Cheque Especial: \n "); entradaTeclado = leitorEntrada.readLine(); double limite = Double.parseDouble(entradaTeclado); contaCorrente.setTitular(umTitular); contaCorrente.setNumero(umNumero); contaCorrente.setAgencia(umaAgencia); contaCorrente.setSaldo(umSaldo); contaCorrente.setSenha(umaSenha); contaCorrente.setLimiteChequeEspecial(limite); umControle.adicionar(contaCorrente); } else{ System.out.println("Tipo inválido! \n "); } break; case'2': System.out.println("Digite o numero da sua conta: \n"); entradaTeclado = leitorEntrada.readLine(); umNumero = entradaTeclado; System.out.println("Digite sua senha: \n"); entradaTeclado = leitorEntrada.readLine(); umaSenha = entradaTeclado; Conta conta = umControle.validaConta(umNumero, umaSenha); if(umControle.validaConta(umNumero, umaSenha)==null){ System.out.println("Dados incorretos, tente novamente!"); } else{ System.out.println("Bem vindo a sua conta, "); System.out.println("\nSelecione uma opcao: \n"); System.out.println("1- Saque\n"); System.out.println("2- Depósito\n"); System.out.println("3- Saldo\n"); entradaTeclado = leitorEntrada.readLine(); opcao = entradaTeclado.charAt(0); } switch(opcao){ case'1': System.out.println("Insira o valor a ser sacado: "); entradaTeclado = leitorEntrada.readLine(); double valor = Double.parseDouble(entradaTeclado); String retorno = umControle.sacar(valor, conta); System.out.println(retorno); break; case '2': System.out.println("Insira o valor a ser depositado: "); entradaTeclado = leitorEntrada.readLine(); valor = Double.parseDouble(entradaTeclado); retorno = umControle.depositar(valor, conta); System.out.println(retorno); break; case '3': System.out.println("Saldo disponível: R$ "+conta.getSaldo()); break; default: } break; default: } } while(menuOpcao != 0); }
583b7277-6899-4e82-8dd8-463a8ca19ee7
5
private void benchmark() { stage.hide(); secondaryStage = new Stage(StageStyle.UTILITY); secondaryStage.setTitle("Benchmarking..."); StackPane sp = new StackPane(); benchmarkBar = new ProgressBar(); benchmarkBar.setPrefWidth(400); benchmarkBar.setPrefHeight(30); benchmarkBar.setProgress(-1); sp.getChildren().add(benchmarkBar); secondaryStage.setScene(new Scene(sp, 400, 30)); secondaryStage.show(); benchSide = mazeGrid.getSideCount(); benchWalls = mazeGrid.getWalls(); benchDiag = noDiagonal.isSelected(); benchmarkData = new long[BENCHMARK_ITERATIONS]; if (mazeGrid.hasStartAndEnd()) { perfectRoute = Math.sqrt(Math.pow(mazeGrid.getGoal().x - mazeGrid.getStart().x, 2) + Math.pow(mazeGrid.getGoal().y - mazeGrid.getStart().y, 2)); final Task<List<Point>> tsk = new Task<List<Point>>() { @Override protected List<Point> call() { long timeStamp; for(int i=0; i<MazeFramework.BENCHMARK_ITERATIONS-1; i++) { if(!isCancelled()) { timeStamp = System.nanoTime(); MazeFramework.algorithm.initPathfinder(mazeGrid.getConvertedGrid(), mazeGrid.getStart(), mazeGrid.getGoal()); MazeFramework.algorithm.startPathfinder(noDiagonal.isSelected()); benchmarkData[i] = (System.nanoTime() - timeStamp); updateProgress(i, MazeFramework.BENCHMARK_ITERATIONS); } } timeStamp = System.nanoTime(); List<Point> res = MazeFramework.algorithm.startPathfinder(noDiagonal.isSelected()); benchmarkData[MazeFramework.BENCHMARK_ITERATIONS-1] = (System.nanoTime()-timeStamp); if(res!=null) { steps = res.size(); } return res; } }; tsk.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { secondaryStage.hide(); showBenchmarkResults(); mazeGrid.overlaySolution((List<Point>) t.getSource().getValue()); } }); tsk.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { secondaryStage.hide(); stage.show(); try { throw t.getSource().getException(); } catch (Throwable ex) { Logger.getLogger(MazeFramework.class.getName()).log(Level.SEVERE, null, ex); } } }); secondaryStage.setOnHidden(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent t) { tsk.cancel(); stage.show(); } }); benchmarkBar.progressProperty().bind(tsk.progressProperty()); Thread thrd = new Thread(tsk); thrd.start(); } else { JOptionPane.showMessageDialog(null, "Goal and Start positions are not set!", "Can't run!", JOptionPane.WARNING_MESSAGE); stage.show(); } }
666c60d5-58f1-44c7-b74c-0eccd9f47dea
8
public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException { ByteBuffer buffer = ws.outQueue.peek(); WrappedByteChannel c = null; if( buffer == null ) { if( sockchannel instanceof WrappedByteChannel ) { c = (WrappedByteChannel) sockchannel; if( c.isNeedWrite() ) { c.writeMore(); } } } else { do {// FIXME writing as much as possible is unfair!! /*int written = */sockchannel.write( buffer ); if( buffer.remaining() > 0 ) { return false; } else { ws.outQueue.poll(); // Buffer finished. Remove it. buffer = ws.outQueue.peek(); } } while ( buffer != null ); } if( ws.outQueue.isEmpty() && ws.isFlushAndClose() /*&& ( c == null || c.isNeedWrite() )*/) { synchronized ( ws ) { ws.closeConnection(); } } return c != null ? !( (WrappedByteChannel) sockchannel ).isNeedWrite() : true; }
bdb6f86b-56dd-4b0d-a40d-4f4aa3395ebc
2
private void sqrtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sqrtActionPerformed if (!"".equals(text.getText())) { double value = Double.parseDouble(text.getText()); value = Math.sqrt(value); if (value >= 0) { printer(value); } else { JOptionPane.showMessageDialog(rootPane, "Argument under Root should be > 0"); text.setText(""); } } }//GEN-LAST:event_sqrtActionPerformed
e6a7f231-99ae-4ad9-8470-5401c6ae4aae
7
private static void setDestination(IControl control)throws Exception{ //coordinates of parking slot double back_X = destination.getBackBoundaryPosition().getX(); double back_Y = destination.getBackBoundaryPosition().getY(); double front_X = destination.getFrontBoundaryPosition().getX(); double front_Y = destination.getFrontBoundaryPosition().getY(); //midpoint of parking slot double middle_X = (back_X+front_X)/2; double middle_Y = (back_Y+front_Y)/2; float phi = 0; if(middle_Y<0){ phi = 0; } if(middle_X>1.8){ phi = (float)Math.PI*1/2; } if(middle_Y>0.5){ phi = (float)Math.PI; } //coordinates on black line, which are supposed to be driven to before parking double distance_slot_to_line = 0.3; double distance_to_go = 0.2; double line_X = middle_X + distance_to_go*Math.cos(phi) - distance_slot_to_line*Math.sin(phi); double line_Y = middle_Y + distance_slot_to_line*Math.cos(phi) + distance_to_go*Math.sin(phi); //offset to improve parking behaviour double middle_X_co = middle_X + 0.1*Math.cos (phi); double middle_Y_co = middle_Y - 0.1*Math.sin (phi); //avoid parking maneuver while in the middle of the second corner if (line_Y>0.55){ line_Y = line_Y-0.03; } destination_pose.setHeading(phi); //control is only told the the destination if a parking maneuver is supposed to start //this triggers the calculation of the trajectory if((currentSubStatus == CurrentSubStatus.MOVE_TO_PARKING_POSITION)||(currentSubStatus == CurrentSubStatus.FIND_BLACK_LINE)){ destination_pose.setLocation((float)line_X, (float)line_Y); } if(currentSubStatus == CurrentSubStatus.PARK){ destination_pose.setLocation((float)middle_X_co, (float)middle_Y_co); control.setDestination(phi, middle_X_co, middle_Y_co); } else { //make sound if method fails Sound.buzz();; } }
778f71fa-3dfd-4e82-9c2d-4a0bd3fa6038
1
protected void printProgression(int n){ System.out.println(firstValue()); for(int i=2;i<=n;i++){ System.out.println(nextValue()); } }
33cbf1be-62a8-4653-8687-0d4cd3bec09f
2
public boolean contains(String nickname) { for (User user : model) { if ( user.getNickname().equalsIgnoreCase(nickname) ) return true; } return false; }
6e8faf19-8f2e-46e8-a2c7-ac66061f4213
3
public static void writeAllSentences(List<List<String>> sentences, String outputFilePath) throws IOException { File output = new File(outputFilePath); if (!output.exists()) { output.createNewFile(); } BufferedWriter bw = new BufferedWriter(new FileWriter(output)); StringBuilder builder = new StringBuilder(); for (List<String> group : sentences) { for (String sentence : group) { builder.append(sentence); builder.append("\n"); } builder.append("\n"); } bw.write(builder.toString()); bw.close(); }
2dd53921-2da1-4715-a9ae-a5ce2d22a606
3
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Author)) return false; Author author = (Author) o; if (!name.equals(author.name)) return false; return true; }
634fd904-3a8f-4f8f-ace6-c2e18270eb9a
1
public int getModifiers() { if ((status & HIERARCHY) == 0) loadInfo(HIERARCHY); return modifiers; }
201a34b1-a181-4b60-a60c-1e15077ebb65
2
private CoreConstants() { properties = new Properties(); LOG.info("The properties file is being loaded: " + APP_PROPERTIES); try (FileInputStream inputStream = new FileInputStream(APP_PROPERTIES)) { properties.load(inputStream); LOG.info("Properties file load successful"); } catch (FileNotFoundException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } }
fa53c878-f477-4db3-a0f9-d3ee2c203661
3
@Override public void run() { // TODO Auto-generated method stub CImedWrapper wrapper = new CImedWrapper(this.getProxy(), this.getUsername(), this.getPwd()); boolean bServiceAvailable = false; boolean bReportingAvailable = false; try{ bServiceAvailable = wrapper.CheckServiceAvailable(); LOGGER.debug("Service Available"+bServiceAvailable); bReportingAvailable = wrapper.CheckReportingAvailable(); LOGGER.debug("Reporting Available"+bReportingAvailable); } catch(Exception ex) { LOGGER.error("Error in Imed Calls",ex); } if(bServiceAvailable && bReportingAvailable) { // Collect facts & figures } }
65b45b7d-b014-41c0-b688-f89eeb0e5d30
3
@Override public A set(A a, B b) { try { setMethod.invoke(a, b); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return a; }
d5c44041-fe6e-4d91-888c-58d10412b888
8
public boolean setInputFormat(Instances instanceInfo) throws Exception { if ((instanceInfo.classIndex() > 0) && (!getFillWithMissing())) { throw new IllegalArgumentException("TimeSeriesTranslate: Need to fill in missing values " + "using appropriate option when class index is set."); } super.setInputFormat(instanceInfo); // Create the output buffer Instances outputFormat = new Instances(instanceInfo, 0); for(int i = 0; i < instanceInfo.numAttributes(); i++) { if (i != instanceInfo.classIndex()) { if (m_SelectedCols.isInRange(i)) { if (outputFormat.attribute(i).isNominal() || outputFormat.attribute(i).isNumeric()) { outputFormat.renameAttribute(i, outputFormat.attribute(i).name() + (m_InstanceRange < 0 ? '-' : '+') + Math.abs(m_InstanceRange)); } else { throw new UnsupportedAttributeTypeException("Only numeric and nominal attributes may be " + " manipulated in time series."); } } } } outputFormat.setClassIndex(instanceInfo.classIndex()); setOutputFormat(outputFormat); return true; }
9ee1028a-7121-45c4-a22c-86572aabbee3
9
void bondAminoHydrogen(int indexDonor, Point3f hydrogenPoint, BitSet bsA, BitSet bsB) { AminoMonomer source = (AminoMonomer)monomers[indexDonor]; Point3f sourceAlphaPoint = source.getLeadAtomPoint(); Point3f sourceNitrogenPoint = source.getNitrogenAtomPoint(); int energyMin1 = 0; int energyMin2 = 0; int indexMin1 = -1; int indexMin2 = -1; for (int i = monomerCount; --i >= 0; ) { if ((i == indexDonor || (i+1) == indexDonor) || (i-1) == indexDonor) continue; AminoMonomer target = (AminoMonomer)monomers[i]; Point3f targetAlphaPoint = target.getLeadAtomPoint(); float dist2 = sourceAlphaPoint.distanceSquared(targetAlphaPoint); if (dist2 > maxHbondAlphaDistance2) continue; int energy = calcHbondEnergy(source.getNitrogenAtom(), sourceNitrogenPoint, hydrogenPoint, target); if (energy < energyMin1) { energyMin2 = energyMin1; indexMin2 = indexMin1; energyMin1 = energy; indexMin1 = i; } else if (energy < energyMin2) { energyMin2 = energy; indexMin2 = i; } } if (indexMin1 >= 0) { mainchainHbondOffsets[indexDonor] = (short)(indexDonor - indexMin1); min1Indexes[indexDonor] = (short)indexMin1; min1Energies[indexDonor] = (short)energyMin1; createResidueHydrogenBond(indexDonor, indexMin1, bsA, bsB); if (indexMin2 >= 0) { createResidueHydrogenBond(indexDonor, indexMin2, bsA, bsB); min2Indexes[indexDonor] = (short)indexMin2; min2Energies[indexDonor] = (short)energyMin2; } } }
57c7ae25-0ceb-45d2-a7ea-a4b66542ee0e
4
private static void insertObs(Difficulty diff, Point enter, Orientation orientation){ Random random = new Random(); int recAccuracy = GetConfigByDiff.setRecAccuracy(diff); float x, y, h, l; x = y = h = l = 0; switch (orientation){ case left: { l = recAccuracy/2; h = (2+random.nextFloat())*recAccuracy; x = (float) enter.getX(); y = (float) enter.getY() - h/2; } case right:{ l = recAccuracy/2; h = (2+random.nextFloat())*recAccuracy; x = (float) enter.getX() - l; y = (float) enter.getY() - h/2; } case up: { l = (2+random.nextFloat())*recAccuracy; h = recAccuracy/2; x = (float) enter.getX() - l/2; y = (float) enter.getY() + h; } case down: { l = (2+random.nextFloat())*recAccuracy; h = recAccuracy/2; x = (float) enter.getX() - l/2; y = (float) enter.getY(); } } new Obstacle(Math.round(x), Math.round(y), Math.round(l)+1, Math.round(h)+1); // System.out.println("Obs: "+Math.round(x) + Math.round(y)); }
af48a7e3-dd59-44d2-a0d0-530ed14172b1
5
@Override public int getCount(E data) { // We traverse the list until the node with data as its value is found, then return its count // If no such node is found we return 0 if(head == null){ // Empty list has no node with data as its value return 0; } // Does head match? If so, return its count ListNode current = head; if(comparator.compare(data, current.value) ==0){ return current.count; } // Search the list for a match while(current.next != null && comparator.compare(data, current.next.value) !=0){ current = current.next; } // No match was found if(current.next == null){ return 0; // Found a match. // TODO: is the node supposed to be moved to the front of the list here? }else{ ListNode temp = current.next; current.next = temp.next; temp.next = head; head = temp; return head.count; } }
68489845-e6ed-4865-b779-24fa7b968d4d
2
static LookAndFeel getFactory(CHOICE choice) { LookAndFeel lookAndFeel = null; switch (choice) { case WINDOWS: lookAndFeel = new WindowsLookAndFeel(); break; case MOTIF: lookAndFeel = new MotifLookAndFeel(); break; } return lookAndFeel; }
9886e08f-1f59-4f09-be74-c92aea5a12e2
9
private void expand(SyrianGraph g, SimpleHeuristicNode hn, AbstractList<SimpleHeuristicNode> toBeExpanded, AbstractList<SimpleHeuristicNode> alreadyExpanded) { this.setExpansions(this.getExpansions() + 1); // trivial expansion AbstractCollection<SyrianEdge> edges = g.getAllEdgesForVertex(hn .getRoot()); for (SyrianEdge e : edges) { SyrianVertex destination = e.getOther(hn.getRoot()); int sourceDistanceFromTarget = this.distancesFromTarget.get(hn .getRoot().getNumber()); int destinationDistanceFromTarget = this.distancesFromTarget .get(destination.getNumber()); this.addNewHeuristicNode(destination, hn, e, false, false, hn.getHn(), toBeExpanded, alreadyExpanded); if (hn.getRoot().hasChemicals() || hn.hasChemicals()) { // expand with chemicals this.addNewHeuristicNode( destination, hn, e, true, false, hn.getHn() - ((sourceDistanceFromTarget - destinationDistanceFromTarget) * 2), toBeExpanded, alreadyExpanded); } if (hn.getRoot().hasEscort() || hn.hasEscort()) { // expand with escort this.addNewHeuristicNode(destination, hn, e, false, true, hn.getHn(), toBeExpanded, alreadyExpanded); } if ((hn.getRoot().hasEscort() || hn.hasEscort()) && (hn.getRoot().hasChemicals() || hn.hasChemicals())) { // expand with chemicals and escort this.addNewHeuristicNode( destination, hn, e, true, true, hn.getHn() - ((sourceDistanceFromTarget - destinationDistanceFromTarget) * 2), toBeExpanded, alreadyExpanded); } } }
054f2e67-ddc5-487e-8ddf-0190da45296e
8
void setPendingViewOffset(int xofs,int yofs) { if (!pf_wrapx) { if (xofs < 0) xofs=0; if (xofs > tilex*(nrtilesx-viewnrtilesx)) xofs = tilex*(nrtilesx-viewnrtilesx); } if (!pf_wrapy) { if (yofs < 0) yofs=0; if (yofs > tiley*(nrtilesy-viewnrtilesy)) yofs = tiley*(nrtilesy-viewnrtilesy); } pendingxofs = xofs; pendingyofs = yofs; // update parallax level 0 for(int i = 0; i<bg_images.size(); i++){ BGImage bgimg = (BGImage) bg_images.elementAt(i); if (bgimg!=null) { bgimg.xofs = xofs; bgimg.yofs = yofs; } } }
3d9258c2-3bdd-4306-a483-43804bddbf8e
4
public static String decrypt(String cipher) { if(firstTime) {initTabel();firstTime = false;} cipher = cipher.toUpperCase(); char[] crypt = cipher.toCharArray(); String tmp=""; String plain = ""; int x,y,pos = 0; for(int i=0;i<crypt.length;i+=2) { //luam doua cate doua tmp = crypt[i]+""+crypt[i+1]; //cautam in matricea de substitutie(vector vazut ca matrice mai exact) for(int j=0;j<subst.length;j++) { if(subst[j].equals(tmp)) { pos = j; break; } } //calculam linia si coloana in matrice x = pos/27; y = pos%27; //grupul descifrat plain += charAtIndex(x)+""+charAtIndex(y); } return plain; }
72c48846-8476-470a-87c7-be671c61ac3b
6
public void addRock(int x, int y, int size) { if ((size <= 3) && (size > 0)) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if ((y+j<this.ourMap.length) && (x+i<this.ourMap[j].length)) { this.ourMap[y+j][x+i] = new Tile(2); } } } } }
3ec5b7c2-b06d-4bd0-88f6-f84809922cc0
1
public static String getFix() { char c = automata.turing.Tape.BLANK; StringBuffer b = new StringBuffer(); for (int i = 0; i < 20; i++) b.append(c); return b.toString(); }
3aa11f50-b941-4621-b0e4-6a7faa67ed3f
8
public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_plotInstances != null && m_plotInstances.numInstances() > 0 && m_plotInstances.numAttributes() > 0) { if (m_plotCompanion != null) { m_plotCompanion.prePlot(gx); } m_JRand = new Random(m_JitterVal); paintAxis(gx); if (m_axisChanged || m_plotResize) { int x_range = m_XaxisEnd - m_XaxisStart; int y_range = m_YaxisEnd - m_YaxisStart; if (x_range < 10) { x_range = 10; } if (y_range < 10) { y_range = 10; } m_drawnPoints = new int[x_range + 1][y_range + 1]; fillLookup(); m_plotResize = false; m_axisChanged = false; } paintData(gx); } }
7358dbc9-ea4b-4faf-91be-6432124fb72e
0
public void setItemId(int itemId) { this.itemId = itemId; }
f5f33043-d99f-43cf-b8ec-fef9a9f9c714
4
public void methodExplorer(File folder) { methods = new MethodVisitor(); for (File file : folder.listFiles()) { if (file.isDirectory()) { methodExplorer(file); } else { if (file.getName().endsWith(".java")) { String fileName = file.getName().substring(0, file.getName().length() - 5); methods.visit(parsedInput, classes); List<String> results = methods.returnSearchResults(); if (results != null) { System.out.println(fileName + " uses " + results); } } } } }
b8a9b347-c8d7-4e4e-9511-807de9cef5c4
3
private static void fillBuffer() { // Wait for user to type a line and press return, try { buffer = in.readLine(); } catch (Exception e) { if (readingStandardInput) throw new IllegalArgumentException("Error while reading standard input???"); else if (inputFileName != null) throw new IllegalArgumentException("Error while attempting to read from file \"" + inputFileName + "\"."); else throw new IllegalArgumentException("Errow while attempting to read form an input stream."); } pos = 0; floatMatcher = null; integerMatcher = null; }
3b8209fd-f372-474e-aad2-434858ceec73
1
@Override public void destroy() { if(currentSector > -1) { Application.get().getLogic().getGame().getSector(currentSector).releaseLocation(owner); } }
b9c047fe-0bd4-44c3-b03a-839e968da924
4
public void handleInput() { int in = input.getInput(); if(in == Keys.W){this.velocity.thisAdd(new Vector2D(0,-8));} if(in == Keys.S){this.velocity.thisAdd(new Vector2D(0,8));} if(in == Keys.A){this.velocity.thisAdd(new Vector2D(-8,0));} if(in == Keys.D){this.velocity.thisAdd(new Vector2D(8,0));} // if(Keys.isDown(Keys.W)){this.velocity.thisAdd(new Vector2D(0,-8));} // if(Keys.isDown(Keys.S)){this.velocity.thisAdd(new Vector2D(0,8));} // if(Keys.isDown(Keys.A)){this.velocity.thisAdd(new Vector2D(-8,0));} // if(Keys.isDown(Keys.D)){this.velocity.thisAdd(new Vector2D(8,0));} }
1523a7dd-cb3e-4056-9b7f-56d5351085a4
8
private List<Gate> getIncrementedGates(List<Gate> parsedGates){ List<Gate> res = new ArrayList<Gate>(); int incNumber = largestAugOutputWire + 1 - numberOfOriginalInputs; for (Gate g: parsedGates) { if(!g.isXOR()){ g.setGateNumber(g.getGateNumber() + numberOfNonXORGatesAdded); } //If left wire is y, increment it, else increment wires with new added wire size int leftWireIndex = g.getLeftWireIndex(); if (leftWireIndex < numberOfOriginalInputs && leftWireIndex > t_a - 1) { g.setLeftWireIndex(leftWireIndex + l); } else if (leftWireIndex >= numberOfOriginalInputs) { g.setLeftWireIndex(leftWireIndex + incNumber); } // Same, but for right wire int rightWireIndex = g.getRightWireIndex(); if (rightWireIndex < numberOfOriginalInputs && rightWireIndex > t_a - 1) { g.setRightWireIndex(rightWireIndex + l); } else if (rightWireIndex >= numberOfOriginalInputs) { g.setRightWireIndex(g.getRightWireIndex() + incNumber); } // Output wires should always be incremented int newIndex = g.getOutputWireIndex() + incNumber; g.setOutputWireIndex(newIndex); largestOutputWire = Math.max(largestOutputWire, g.getOutputWireIndex()); res.add(g); } return res; }
22dc57c2-c483-4869-aff7-4364f2d073fa
8
protected List <Segment> installedBetween(Tile start, Tile end) { final List <Segment> installed = super.installedBetween(start, end) ; if (installed == null || installed.size() < 4) return installed ; // // If the stretch to install is long enough, we cut out the middle two // segments and install a set of Blast Doors in their place- final World world = start.world ; final int cut = installed.size() / 2 ; final ShieldWall a = (ShieldWall) installed.atIndex(cut), b = (ShieldWall) installed.atIndex(cut - 1) ; if (a.facing != b.facing || a.facing == CORNER) return installed ; // // The doors occupy the exact centre of this area, with the same facing- final Vec3D centre = a.position(null).add(b.position(null)).scale(0.5f) ; final BlastDoors doors = new BlastDoors(a.base(), a.facing) ; doors.setPosition(centre.x - 1.5f, centre.y - 1.5f, world) ; final Box2D bound = doors.area(null) ; for (Venue v : installed) { if (v == a || v == b) continue ; if (v.area(null).cropBy(bound).area() > 0) return installed ; } // // Update and return the list- installed.remove(a) ; installed.remove(b) ; installed.add(doors) ; return installed ; }
7cffc302-e5a2-46ee-b4d1-6bcbf33ede83
5
public ConstOperator deobfuscateString(ConstOperator op) { ClassAnalyzer clazz = methodAnalyzer.getClassAnalyzer(); MethodAnalyzer ma = clazz.getMethod(methodName, methodType); if (ma == null) return null; Environment env = new Environment("L" + methodAnalyzer.getClazz().getName().replace('.', '/') + ";"); Interpreter interpreter = new Interpreter(env); env.interpreter = interpreter; String result; try { result = (String) interpreter.interpretMethod(ma.getBytecodeInfo(), null, new Object[] { op.getValue() }); } catch (InterpreterException ex) { if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INTERPRT) != 0) { GlobalOptions.err.println("Warning: Can't interpret method " + methodName); ex.printStackTrace(GlobalOptions.err); } return null; } catch (InvocationTargetException ex) { if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INTERPRT) != 0) { GlobalOptions.err.println("Warning: Interpreted method throws" + " an uncaught exception: "); ex.getTargetException().printStackTrace(GlobalOptions.err); } return null; } return new ConstOperator(result); }
674d869c-f019-4db1-8437-1ee3a92a019c
1
@Override public int down() throws ParsingException { if (!canStepDown) { throw new InvalidParseCommandException("Can't step down. Element " + currentElement.getName() + " does not have any unparsed child elements", lastEvent.getLocation().getLineNumber(), lastEvent .getLocation().getColumnNumber()); } // Add the current element to the stack, then tell the parser that it should parse the children of this element // next time. parseStack.push(currentElement); ++targetDepth; currentElement = null; canStepDown = false; return parseStack.size(); }
81addf9e-1253-42c2-8f54-95ac623503ed
3
@Override public boolean addClient(Client client) { int shortestLineIndex = 0; int shortestLineTime = Integer.MAX_VALUE; for(int i = 0; i < cashiers; i++){ int currentLineTime = 0; for(int j = 0; j < lines[i].size(); j++){ currentLineTime += lines[i].get(j).getExpectedServiceTime(); } if(currentLineTime < shortestLineTime){ shortestLineTime = currentLineTime; shortestLineIndex = i; } } lines[shortestLineIndex].add(client); return true; }
f12383f0-cb56-417e-a0bf-654dfb8d487d
1
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (Exception ex) { Logger.getLogger(ControlJson.class .getName()).log(Level.SEVERE, null, ex); } }
c955291a-e9e6-41ee-8145-6c965bf0f11d
8
public void move(Direction theD){ if(theD == null) { return; } switch(theD) { case UP: this.y--; facingDirection = Direction.UP; break; case DOWN: this.y++; facingDirection = Direction.DOWN; break; case LEFT: this.x--; facingDirection = Direction.LEFT; break; case RIGHT: this.x++; facingDirection = Direction.RIGHT; break; default: break; } if(y == transferY) { if(x == leftTransferX) { x = rightTransferX; } else if(x == rightTransferX) { x = leftTransferX; } } }
51368b75-f344-4b40-be20-8c86b1f9284d
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UtilisateurVue other = (UtilisateurVue) obj; if (nom == null) { if (other.nom != null) return false; } else if (!nom.equals(other.nom)) return false; if (rang != other.rang) return false; return true; }
67d0c56b-977f-49e2-ae04-69227a969e1d
4
private void assertEquals(String text, Object expected, Object result) { boolean equal; // tests equality between expected and result accounting for null if (expected == null) { equal = result == null; } else { equal = result != null && expected.equals(result); } if (!equal) { // prints the description if necessary if (!isPrinted) { System.out.println(" Test: " + description); // now the description is printed isPrinted = true; } System.out.println(" " + text); System.out.println(" Expected: " + expected); System.out.println(" Result: " + result); errors++; } }
0f238eb7-7e7f-42cf-a92b-348ff9973537
8
public void addToGroup(Group g, Piece p) { if (p == null || g.pieces.contains(p) || (g.pieces.size() > 0 && g.pieces.toArray(new Piece[0])[0].team != p.team)) { return; } int row = p.where.row; int col = p.where.col; g.pieces.add(p); if (col > 0) { addToGroup(g, squares[row][col - 1].piece); } if (row > 0) { addToGroup(g, squares[row - 1][col].piece); } if (row < 8) { addToGroup(g, squares[row + 1][col].piece); } if (col < 8) { addToGroup(g, squares[row][col + 1].piece); } }
10ab8fca-c6ce-43f7-9efa-045b5d5628b5
5
public Analyser(StringBuilder builder, Logger log) { this.log = log; this.code = builder.toString(); if(log_level >= 3) log.log(3, key, "Analyser is doing stuff please wait ...", "\n"); types = new TYPES(log); program_stack = new intStack(100); function_stack = new intStack(100); function_block_stack = new intStack(100); var_stack = new intStack(100); case_stack = new intStack(100); for_stack = new intStack(100); while_stack = new intStack(100); repeat_stack = new intStack(100); if_stack = new intStack(100); program_map = new TreeMap<>(); function_map = new TreeMap<>(); function_block_map = new TreeMap<>(); var_map = new TreeMap<>(); case_map = new TreeMap<>(); for_map = new TreeMap<>(); while_map = new TreeMap<>(); repeat_map = new TreeMap<>(); if_map = new TreeMap<>(); context_varname_var = new HashMap<>(); address_mappedbyte_in = new HashMap<>(); address_mappedbyte_out = new HashMap<>(); com_channel_queue = new LinkedBlockingQueue<>(); functioname_inputid_var = new HashMap<>(); program_startpoint = new HashMap<>(); function_startpoint = new HashMap<>(); var_global_start = -1; var_config_start = -1; if(log_level >= 4) log.log(4, key, "run analyse()", "\n"); analyse(); if(log_level >= 4) log.log(4, key, "analyse() finished", "\n"); if(log_level >= 4) log.log(4, key, "run build_function_structure()", "\n"); build_function_structure(); if(log_level >= 4) log.log(4, key, "build_function_structure finished", "\n"); generate_symbols_list(); }
174f57fd-63b4-4d5e-9c26-03ce562b1870
3
public double resolveCollisionX(AABB other, double moveAmtX) { double newAmtX = moveAmtX; if (moveAmtX == 0.0) { return moveAmtX; } if (moveAmtX > 0) { // Our max == their min newAmtX = other.getMinX() - maxX; } else { // Our min == their max newAmtX = other.getMaxX() - minX; } if (Math.abs(newAmtX) < Math.abs(moveAmtX)) { moveAmtX = newAmtX; } return moveAmtX; }
61818047-f72d-4ebe-b80f-fade6acf678d
7
public void sort(SortArray points, SortCanvas c) { int max = 6; // too dangerous to take more int i; // remove the unused points from view for( i = max + 1; i < points.length(); i++) points.put(i, -100); c.clearWindow(); Random rand = new Random(new Random().nextInt()); for (i = 1; i <= max; i++) { // init a points.put(i, (int)(((double)rand.nextInt(100) / 20.0 + 1.0) * 20.0)); } while (true) { boolean isSorted = true; for( i = 1; i < max; i++ ){ if( points.greater(i, i+1) ){ // order is broken at one point: set the flag and jump out isSorted = false; break; } } c.paintNumbers(); if( isSorted ) { // if the order is ok, stop the algorithm break; } else { rand = new Random(new Random().nextInt()); for (i = 1; i <= max; i++) { points.get(i); points.put(i, (int)(((double)rand.nextInt(100) / 20.0 + 1.0) * 20.0)); } c.paintNumbers(); } } }
a559bbd0-439e-43b4-b750-d206cc84ad47
8
protected void buildIndexMap(RootDoc root) { PackageDoc[] packages = root.specifiedPackages(); ClassDoc[] classes = root.classes(); if (!classesOnly) { if (packages.length == 0) { Set<PackageDoc> set = new HashSet<PackageDoc>(); PackageDoc pd; for (int i = 0; i < classes.length; i++) { pd = classes[i].containingPackage(); if (pd != null && pd.name().length() > 0) { set.add(pd); } } adjustIndexMap(set.toArray(packages)); } else { adjustIndexMap(packages); } } adjustIndexMap(classes); if (!classesOnly) { for (int i = 0; i < classes.length; i++) { if (shouldAddToIndexMap(classes[i])) { putMembersInIndexMap(classes[i]); } } } sortIndexMap(); }
c4800c3c-df96-400e-acd7-a7b8da77700f
8
@Override public void addEdge(Edge edge) { // check to see if it is a valid edge if (!edge.validGameEdge()) { throw new IllegalArgumentException("Invalid edge inserted. Edges must have both of their endpoints defined."); } // Check to see that both nodes have been added to the ship for (Node n : edge.getAdjacent()) { if (!nodeMap.containsValue(n)) { throw new IllegalStateException("Both nodes must be added before an edge can be added"); } } // Check to see if there are no contradictions // For each node in the edge for (Node n : edge.getAdjacent()) { // For each edge in each one of those nodes for (Edge e : nodeMap.get(n.getCoordinates()).getAdjacent()) { // If there is an edge that connects the same // two nodes as the one being added if (e.getAdjacent().equals(edge.getAdjacent())) { // They better match edge states or else // there is a contradiction if (!e.getEdgeState().equals(edge.getEdgeState())) { throw new IllegalStateException("There is a contradiction in the edge states"); } } } } // Add the edge to both nodes for (Node n : edge.getAdjacent()) { nodeMap.get(n.getCoordinates()).addEdge(edge); } // Add the edge to the edgeMap edgeMap.put(edge.getAdjacent(), edge); }
19d40785-d157-46a7-9b0b-c1e952a5ae48
8
private boolean cellaValida(Cella cella){ // contolla se la cella cliccata è una mossa valida mangiate = new MangiateValide(); if (mangiate.trovaMangiateBianche(damiera).isEmpty()) { // cerca tra i movimenti MosseValide mosse = new MosseValide(damiera, mossaUtente[0].getx(), mossaUtente[0].gety(), true); SortedSet<Mossa> listaMovimenti = new TreeSet<Mossa>(); listaMovimenti = mosse.getMosseValide(); for (Mossa m:listaMovimenti){ if (cella.equals(m.getFine())) return true; } } else { // cerca tra le mangiate TreeSet<Mossa> listaMangiate = mangiate.trovaMangiateBianche(damiera); for (Mossa m:listaMangiate) if(m.getPercorso() != null && m.getPercorso().length > 2){ // se la mangiata è multipla if (cella.equals(m.getPercorso()[2])) return true; }else if (cella.equals(m.getFine())) return true; } return false; }
7756e240-ebf9-48ff-ac39-543a185f81d9
0
@Override public void setMobile(String mobile) { super.setMobile(mobile); }
1296ed74-f41a-4b08-9a8a-65bc43cac68d
6
public KeyNodeIntPair dealWithPromote(int newKey, Node rightChild, InternalNodeInt node) { // if new key is greater than the key in the last element of list // insert child into the node if (newKey > node.getKeys().get(node.size() - 1)) { node.getKeys().add(newKey); node.getChildren().add(rightChild); } else { int size = node.size(); for (int i = 0; i < size; i++) { if (newKey < node.getKeys().get(i)) { node.getKeys().add(i, newKey); node.getChildren().add(i + 1, rightChild); break; } } } // determine the return value if (node.size() <= MAX_NODE_KEYS) { return null; } InternalNodeInt sibling = new InternalNodeInt(); int mid = (node.size() + 1) / 2 - 1; // move node.keys from mid - node.size to sibling.node starting from 0 int size = node.size(); for (int i = mid + 1; i < size; i++) { sibling.getKeys().add(node.getKeys().get(mid + 1)); node.getKeys().remove(mid + 1); } // move node.child from mid - node.size to sibling.child starting from // 0 for (int i = mid + 1; i < size + 1; i++) { sibling.getChildren().add(node.getChildren().get(mid + 1)); node.getChildren().remove(mid + 1); } int promoteKey = node.getKeys().get(mid); // remove key which is promoted from node node.getKeys().remove(mid); return new KeyNodeIntPair(promoteKey, sibling); }
ec8af9cb-0b5e-42ad-af34-ab0710572666
7
protected TNorm extractTNorm(String line) { List<String> token = Op.split(line, ":"); if (token.size() != 2) { throw new RuntimeException("[syntax error] " + "expected property of type (key : value) in line: " + line); } String name = token.get(1).trim(); String className = null; if ("MIN".equals(name)) { className = Minimum.class.getSimpleName(); } else if ("PROD".equals(name)) { className = AlgebraicProduct.class.getSimpleName(); } else if ("BDIF".equals(name)) { className = BoundedDifference.class.getSimpleName(); } else if ("DPROD".equals(name)) { className = DrasticProduct.class.getSimpleName(); } else if ("EPROD".equals(name)) { className = EinsteinProduct.class.getSimpleName(); } else if ("HPROD".equals(name)) { className = HamacherProduct.class.getSimpleName(); } return FactoryManager.instance().tnorm().createInstance(className); }
1b7d85c2-8eb7-4868-8851-cc7c5fbfe21e
9
public static String normalizeNewlines(String input) { String result = input; if (input != null) { char[] chars = input.toCharArray(); final int length = chars.length; int startWritePos = 0; StringBuffer resultBuffer = null; char previousChar = 0; for (int index = 0; index < length; index++) { char ch = chars[index]; switch (ch) { case '\r': if (resultBuffer == null) { resultBuffer = new StringBuffer(); } resultBuffer.append(chars, startWritePos, index - startWritePos); if (previousChar != '\n') { resultBuffer.append("\n"); previousChar = ch; } else { // reset so only pairs are ignored previousChar = 0; } startWritePos = index + 1; break; case '\n': if (resultBuffer == null) { resultBuffer = new StringBuffer(); } resultBuffer.append(chars, startWritePos, index - startWritePos); if (previousChar != '\r') { resultBuffer.append("\n"); previousChar = ch; } else { // reset so only pairs are ignored previousChar = 0; } startWritePos = index + 1; break; default: previousChar = 0; break; } } // Write any pending data if (resultBuffer != null) { resultBuffer.append(chars, startWritePos, length - startWritePos); result = resultBuffer.toString(); } } return result; }
4911c0b8-1152-4e37-aeab-e43c8d33d82d
9
private ArrayList<Integer> generateAgeColumnCodes(ArrayList<String> columnLabels) { ArrayList<Integer> columnCodes = new ArrayList<Integer>(); for(int i = 0; i < columnLabels.size(); i++) { String curLabel = columnLabels.get(i); if(curLabel.equals(Constants.APTA_AGE_0_14_LBL)) columnCodes.add(i, Constants.APTA_AGE_0_14); else if(curLabel.equals(Constants.APTA_AGE_15_19_LBL)) columnCodes.add(i, Constants.APTA_AGE_15_19); else if(curLabel.equals(Constants.APTA_AGE_20_24_LBL)) columnCodes.add(i, Constants.APTA_AGE_20_24); else if(curLabel.equals(Constants.APTA_AGE_25_34_LBL)) columnCodes.add(i, Constants.APTA_AGE_25_34); else if(curLabel.equals(Constants.APTA_AGE_35_44_LBL)) columnCodes.add(i, Constants.APTA_AGE_35_44); else if(curLabel.equals(Constants.APTA_AGE_45_54_LBL)) columnCodes.add(i, Constants.APTA_AGE_45_54); else if(curLabel.equals(Constants.APTA_AGE_55_64_LBL)) columnCodes.add(i, Constants.APTA_AGE_55_64); else if(curLabel.equals(Constants.APTA_AGE_65_OVER_LBL)) columnCodes.add(i, Constants.APTA_AGE_65_OVER); else columnCodes.add(i, -1); } return columnCodes; }
f874696c-9441-484f-a6e2-0e7722014a14
0
public CommandCwlookup(CreeperWarningMain plugin) { this.plugin = plugin; }
c7c39a76-f820-4825-8063-25bc8184757e
0
public void setNomFichier( String nomFichier ) { this.nomFichier = nomFichier; }
a66ecd45-390f-4124-b7c7-871dbd836341
8
static void validateSymbolName(final GenericDescriptor descriptor) throws DescriptorValidationException { final String name = descriptor.getName(); if (name.length() == 0) { throw new DescriptorValidationException(descriptor, "Missing name."); } else { boolean valid = true; for (int i = 0; i < name.length(); i++) { final char c = name.charAt(i); // Non-ASCII characters are not valid in protobuf identifiers, even // if they are letters or digits. if (c >= 128) { valid = false; } // First character must be letter or _. Subsequent characters may // be letters, numbers, or digits. if (Character.isLetter(c) || c == '_' || (Character.isDigit(c) && i > 0)) { // Valid } else { valid = false; } } if (!valid) { throw new DescriptorValidationException(descriptor, '\"' + name + "\" is not a valid identifier."); } } }
fa09d252-716c-4df8-b15e-88687579f7b7
1
public boolean estEnCours(){ if(this.etat == EN_COURS){ return true ; } else { return false ; } }
a503daa6-87d9-4d74-9e5a-ebf0383571e1
5
public static void main(String[] args) { String fileName; if (args.length > 0) { fileName = args[0]; } else { fileName = "jenkinslamps.properties"; } try { LampConfig config = LampConfigReader.read(new FileInputStream(new File(fileName))); List<LampController> lampControllers = new ArrayList<LampController>(); for (Lamp lamp : config.getLamps()) { lampControllers.add(new ExternalCommandController(lamp.getName(), lamp.getOnCommand(), lamp.getOffCommand())); } BuildIndicator controller = new BuildIndicator( config, new JenkinsJobStatusFetcher(config.getJenkinsUrl()), lampControllers); while (true) { controller.check(); try { Thread.sleep(config.getPollTimeMsec()); } catch (InterruptedException ignore) { } } } catch (IOException e) { System.out.println("Failed to read config file " + fileName + ":" + e.getMessage()); } }
60684e2d-5204-47cb-aea6-73f6f3f656ed
3
public void loseALife(boolean passed, boolean boss){ if (passed == true){ if (!boss){ lives--; } else{ lives -= 10; } } if (lives <= 0){ lives = 0; } }
f6441da8-816e-4114-b459-25f9b4721332
4
public static Drilling nextDrillFor(Actor actor) { if (actor.base() == null) return null ; if (! (actor.mind.work() instanceof Venue)) return null ; final World world = actor.world() ; final Batch <DrillYard> yards = new Batch <DrillYard> () ; world.presences.sampleFromKey(actor, world, 5, yards, DrillYard.class) ; final Choice choice = new Choice(actor) ; for (DrillYard yard : yards) if (yard.base() == actor.base()) { ///I.sayAbout(actor, "Can drill at "+yard) ; final Drilling drilling = new Drilling(actor, yard) ; choice.add(drilling) ; } return (Drilling) choice.pickMostUrgent() ; }
1565c1bb-6377-4101-9d2d-be1ae72b7797
2
@Override public void collideWith(Element e) { if (isActive()) { if (e instanceof Player) { collideWithPlayer((Player) e); getGrid().removeElement(this); } } }
911d744c-a59e-4684-8d1a-be408af1f149
3
public void setReaders(BytePacket[] value) { for(BytePacket packet : value) { if(readers.get(packet.type) != null) try { throw new Exception("try to override reader in DataReader"); } catch (Exception e) { e.printStackTrace(); } log.debug("add reader " + packet.type); readers.put(packet.type, packet); } }
a947c24c-190b-4213-8609-87bc57c7f208
0
public String getType() { return type; }
01ecc3f2-fa8f-43e2-a186-55e56f40fe02
5
public static void main(String[] args) { Graph G = null; try { G = new Graph(new In(args[0])); } catch (Exception e) { System.out.println(e); System.exit(1); } int s = Integer.parseInt(args[1]); IPaths paths = new Paths(G, s); for (int v = 0; v < G.V(); v++) { System.out.print(s + " to " + v + " : "); if (paths.hasPathTo(v)) for (int x : paths.pathTo(v)) if (x == s) System.out.print(x); else System.out.print("-" + x); System.out.println(); } }