method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e0e4017e-157c-4dc2-9b98-84e939fc0b3a
8
public void addParamsFromFile(String fName){ BufferedReader bufread = null; String curLine = null; boolean done = false; // First attempt to open and read the config file try{ FileInputStream is = new FileInputStream(fName); bufread = new BufferedReader(new InputStreamReader(is)); curLine = bufread.readLine(); while (curLine != null){ done = false; while (!done) { if (curLine.charAt(0) == '%'){ curLine = bufread.readLine(); } else { done = true; } if (curLine == null) done = true; } if (curLine != null){ String paramName = getToken(curLine,1); int ind = getParamInd(paramName); if (ind>=0){ //parameter already read, but only one definition should exist System.out.println("ERROR: parameter "+paramName+" already read"); System.exit(1); } else { // new parameter if (curNum>=params.length){ //double the size of the arrays String tmp[] = new String[2*params.length]; System.arraycopy(params, 0, tmp, 0, params.length); params = tmp; tmp = new String[2*values.length]; System.arraycopy(values,0,tmp,0,values.length); values = tmp; } params[curNum] = getToken(curLine,1); values[curNum] = curLine.substring(params[curNum].length()+1); curNum++; curLine = bufread.readLine(); } } } bufread.close(); } catch(Exception ex) { System.out.println("ERROR: An error occurred reading configuration file "+fName); System.exit(1); } }
26b9d8aa-53f6-4f1a-a62e-d5f6b644eb1e
0
@Override public String getDesc() { return "HammerFall"; }
3bc23d57-e654-439d-ae1b-7b100ac0cf6c
7
@Override public int castingQuality(MOB mob, Physical target) { if((mob!=null)&&(target!=null)) { final Set<MOB> h=properTargets(mob,target,false); if(h.size()<2) return Ability.QUALITY_INDIFFERENT; for(final MOB M : h) if((M.rangeToTarget()<0)||(M.rangeToTarget()>0)) h.remove(M); if(h.size()<2) return Ability.QUALITY_INDIFFERENT; } return super.castingQuality(mob,target); }
5f0d4115-75f1-40ec-b467-5b4551d8d846
5
private MoveAndCost findBestMoveInternal(int[][] board, int allowedCallCnt) { allowedCallCnt--; //this call double minCost = Double.POSITIVE_INFINITY; int[][] bestBoard = null; Move bestMove = null; int[][][] newBoards = getNewBoards(board); int needCalls = getNeedCallsForNextDepth(newBoards); if(needCalls == 0) { return new MoveAndCost(null, evaluator.getFailCost()); } int nextLevelCalls = allowedCallCnt / needCalls; //todo proper rounding? for (int dir = 0; dir < 4; dir++) { int[][] newBoard = newBoards[dir]; if(newBoard == null) { continue; } double cost = getCost(nextLevelCalls, newBoard); if (cost < minCost) { minCost = cost; bestMove = Move.ALL[dir]; bestBoard = newBoard; } } if (allowedCallCnt+1 == maxCallCnt) { copyBoard(board, bestBoard); } return new MoveAndCost(bestMove, minCost); }
2474d2ef-c38b-40be-a4e7-8f02bf55b120
8
public LinkedList getQuery(){ LinkedList result = new LinkedList(); if(!intervalBtns.isEmpty()) { if(firstBtn == null) { System.out.println("Error: firstBtn is null but intervalBtns list is not empty. Check."); } else { /* * * If it's a groupInterval, add all its interval and relation descriptions * between parentheses, then check forward relation. * Else, add the interval description and check forward relation. * */ System.out.println("It should run."); Object currentBtn = firstBtn; while(currentBtn != null) { if(currentBtn.getClass() == GroupIntervalBtn.class) { /* * Let the recursion take care of grouped intervals. */ GroupIntervalBtn groupBtn = (GroupIntervalBtn)currentBtn; System.out.println("Enters group, gonna go recursive."); getGroupQuery(result, groupBtn); currentBtn = groupBtn.nextRelBtn; } else if(currentBtn.getClass() == IntervalBtn.class) { System.out.println("Enters Interval."); //It's an interval, just add it and make current its nextRelBtn. IntervalBtn intBtn = (IntervalBtn)currentBtn; IntervalDescription id = (IntervalDescription)intBtn.dialog.intDesc; /* * Add exclusions, if any. */ for(ExclusionBtn excBtn: intBtn.exclusions) { Exclusion newExc = new Exclusion(); newExc.intervalDescription = excBtn.dialog.intDesc; newExc.relationDescription = excBtn.relationBtn.relDialog.relDesc; id.exclusions.add(newExc); } /* * Check if it has items. * If not, just add it. * If yes, add the OR relation. */ if(intBtn.dialog.itemsPanel.itemPanels.isEmpty()) { result.add(id); } else { /* * It has items. * Iterate thorugh the items, creating a concatenated * or relation that includes them all, as well as the original * interval, enclosed by parentheses. */ RelationDescription lPar = new RelationDescription(RelationType.LPARENTHESIS); result.add(lPar); result.add(id); for(ItemPanel itemPanel: intBtn.dialog.itemsPanel.itemPanels) { RelationDescription rOr = new RelationDescription(RelationType.OR); IntervalDescription itemIntDesc = itemPanel.intDesc; result.add(rOr); result.add(itemIntDesc); } RelationDescription rPar = new RelationDescription(RelationType.RPARENTHESIS); result.add(rPar); } currentBtn = intBtn.nextRelBtn; numIntervals++; } else { System.out.println("Enters Relation."); //It's a relation, just add it and make current its endButton. RelationBtn relBtn = (RelationBtn)currentBtn; RelationDescription rd = (RelationDescription)relBtn.relDialog.relDesc; result.add(rd); numRelations++; currentBtn = relBtn.endBtn; } /* * * Should check if size (without parentheses) matches amount of buttons. * If not, the query is wrong (a relation is missing in between). * */ } } } return result; }
a37994fb-ef63-4613-b737-3cb427667a7f
5
public ArrayList<Integer> getShortestPaths(int src, GraphAPI gapi) { ArrayList<Integer> shPaths = new ArrayList<Integer>(); for(int i=0; i<gapi.N; i++) { if(i==src) shPaths.add(0); else shPaths.add(INT_MAX_VAL); } // Loop over V-1 vertices for(int i=0; i<gapi.N-i; i++) { // Loop over all edges for(int j=0; j<gapi.edges.size(); j++) { int u = gapi.edges.get(j).u; int v = gapi.edges.get(j).v; int wt = gapi.edges.get(j).weight; if(shPaths.get(u) != INT_MAX_VAL) { shPaths.set(v, Math.min(shPaths.get(v), shPaths.get(u)+wt)); printDistances(shPaths); } } } return shPaths; }
3050e490-8b72-4578-abd9-50eff20baf5d
8
public ClientUpdaterModContainer() { super(new ModMetadata()); ModMetadata meta = super.getMetadata(); meta.authorList = Arrays.asList(new String[] {"robin4002"}); meta.modId = "clientupdater"; meta.version = "1.7.2"; meta.name = "Client Updater"; meta.version = "@VERSION@"; if(FMLCommonHandler.instance().getEffectiveSide().isClient()) { Configuration cfg = new Configuration(new File(new File(ClientUpdaterPlugins.mcDir, "config"), "ClientUpdater.cfg")); try { cfg.load(); versionFileURL = cfg.get(cfg.CATEGORY_GENERAL, "Version File URL", "http://files.minecraftforgefrance.fr/installercustom/version.txt").getString(); installerName = cfg.get(cfg.CATEGORY_GENERAL, "Installer Name", "Installer").getString(); } catch(Exception ex) { ex.printStackTrace(); } finally { if(cfg.hasChanged()) cfg.save(); } File updater = new File(Minecraft.getMinecraft().mcDataDir, installerName + ".jar"); File newUpdater = new File(Minecraft.getMinecraft().mcDataDir, installerName + "new.jar"); if(newUpdater.exists()) { updater.delete(); newUpdater.renameTo(updater); } if(!VersionUtils.isUpdated()) { System.out.println(updater.getAbsolutePath()); if(!updater.exists()) { try { throw(new IOException("Fatal error, updater no found, please run the installer manually")); } catch(IOException e) { e.printStackTrace(); System.exit(-1); } } try { Runtime.getRuntime().exec("java -jar " + updater.getAbsolutePath() + " --update"); System.exit(0); } catch(IOException e) { e.printStackTrace(); } } } }
5161aeb8-9b0b-4d6f-af53-334a220ba233
7
private void rotateLeft( final Node node ) { final Node right = node.mRight; if( right == null ) { return; } node.mRight = right.mLeft; if( node.mRight != null ) { node.mRight.mParent = node; } right.mLeft = node; if( node == mRoot ) { mRoot = right; right.mParent = null; node.mParent = right; } else { right.mParent = node.mParent; node.mParent = right; if( node == right.mParent.mLeft ) { right.mParent.mLeft = right; } else { right.mParent.mRight = right; } } // Interval tree: Must update mMaxStop values. // "right" is now the top of subtree previously rooted under "node" and // thus inherits maxStop. right.mMaxStop = node.mMaxStop; // "node" needs to check the mMaxStop values of it's children. if( node.mMaxStop != node ) { node.mMaxStop = node; if( node.mRight != null ) { node.mMaxStop = maxStopNode( node.mMaxStop, node.mRight.mMaxStop ); } if( node.mLeft != null ) { node.mMaxStop = maxStopNode( node.mMaxStop, node.mLeft.mMaxStop ); } } }
a4e5a0c3-5973-4bbc-b3a8-aab4abc63f8e
8
static Object tryInstantiate(final Class<?> clazz) throws InstantiationException { Class<?> cl = clazz; while (cl != Object.class) { if (!isProxy(cl)) { try { return cl.newInstance(); } catch (ReflectiveOperationException goNext) {} } cl = cl.getSuperclass(); } if (Set.class.isAssignableFrom(clazz)) { return new HashSet<>(); } else if (Map.class.isAssignableFrom(clazz)) { return new HashMap<>(); } else if (Collection.class.isAssignableFrom(clazz)) { return new ArrayList<>(); } throw new InstantiationException(String.format( "Cannot find no-arg constructor in class %s or any its superclasses", clazz.getCanonicalName())); }
40fb8219-819e-4f5d-bf12-1edd836c9a23
5
public static Time toTime(Object length) { if (length != null && String.class.isAssignableFrom(length.getClass())) { String text = (String) length; if(text.matches("\\d{1,2}:\\d{1,2}:\\d{1,2}")){ return Time.valueOf(text); } else if(text.matches("\\d{1,2}:\\d{1,2}")){ return Time.valueOf(String.format("00:%s",text)); } else if(text.matches("\\d{1,2}")){ return Time.valueOf(String.format("00:00:%s", text)); } return Time.valueOf("00:00:00"); } return Time.valueOf("00:00:00"); }
848f7220-4afc-4abb-bb25-2c2f26627332
7
private void exerciseObjectList(List<ObjectTypes> list, long length) { assertEquals(length, list.size()); gcPrintUsed(); ObjectTypes.A a = new ObjectTypes.A(); ObjectTypes.B b = new ObjectTypes.B(); ObjectTypes.C c = new ObjectTypes.C(); ObjectTypes.D d = new ObjectTypes.D(); long start = System.currentTimeMillis(); do { System.out.println("Updating"); long startWrite = System.nanoTime(); for (ObjectTypes mb : list) { mb.setA(a); mb.setB(b); mb.setC(c); mb.setD(d); } long timeWrite = System.nanoTime() - startWrite; System.out.printf("Took %,d ns per object write%n", timeWrite / list.size()); System.out.println("Checking"); long startRead = System.nanoTime(); for (ObjectTypes mb : list) { { ObjectTypes.A v = mb.getA(); ObjectTypes.A expected = a; if (v != expected) assertEquals(expected, v); } { ObjectTypes.B v = mb.getB(); ObjectTypes.B expected = b; if (v != expected) assertEquals(expected, v); } { ObjectTypes.C v = mb.getC(); ObjectTypes.C expected = c; if (v != expected) assertEquals(expected, v); } { ObjectTypes.D v = mb.getD(); ObjectTypes.D expected = d; if (v != expected) assertEquals(expected, v); } } long timeRead = System.nanoTime() - startRead; System.out.printf("Took %,d ns per object read/check%n", timeRead / list.size()); System.gc(); } while (System.currentTimeMillis() - start < 10 * 1000); System.out.println("Finished"); }
d850973a-5e3e-4548-937e-b395a9dc2458
3
public void acceptConnection(Connection con){ if(connectionTimer!=null){ connectionTimer.cancel(); } //stop broadcasting if(bcast!=null && bcast.isRunning()){ bcast.stop(); } waitingOnPassword = false; client_connected = true; conID = con.getID(); ServerMsg msg = new ServerMsg(); msg.connectionAccepted = true; con.sendTCP(msg); client_ip = con.getRemoteAddressTCP().getHostString(); changedStatus(); changedIP(); // send the QL list sendQuickLaunchFiles(); }
b38bd5fa-9965-471c-8366-4bc08b9ffe21
9
public static void main(String[] args) { BufferedReader input= new BufferedReader(new InputStreamReader(System.in)); boolean prima; try{ System.out.print("Masukan batas bawah:"); int batas_bawah=Integer.parseInt(input.readLine()); System.out.print("Masukan batas atas:"); int batas_atas=Integer.parseInt(input.readLine()); System.out.print("Genap\t:"); for (int i =batas_bawah+1; i<batas_atas; i++) { if(i%2==0) System.out.print(i+" "); } System.out.print("\nGanjil\t:"); for (int i =batas_bawah+1; i <batas_atas; i++) { if(i%2!=0) System.out.print(i+" "); } System.out.print("\nPrima\t:"); for (int i =batas_bawah+1; i < batas_atas; i++) { prima=true; for (int j = 2; j < i; j++) { if(i%j==0){ prima=false; break; } else{ } } if(prima==true) System.out.print(i+" "); } }catch(IOException e){ System.out.println("Masukan salah"); } }
3fe11ee5-97ea-4d0a-bd38-c23d276afaa7
7
public static void setZero(int[][] array){ boolean[] col = new boolean[array[0].length]; boolean[] row = new boolean[array.length]; for(int i=0;i<array.length;i++){ for(int j=0;j<array[0].length;j++){ if(array[i][j] == 0){ col[j] = true; row[i] = true; } } } for(int i=0;i<array.length;i++){ for(int j=0;j<array[0].length;j++){ if(col[j] || row[i]){ array[i][j] = 0; } } } }
10d44217-a33c-4dfa-9cd7-4149f800179a
5
public void run() { super.init(Properties.PORT);//initialize the RMI registry while (running) { // send a message to each resource manager, requesting its load for (String rmUrl : resourceManagerLoad.keySet()) { /* * TODO This part needs to be changed from localsocket to using RMI */ //ControlMessage cMessage = new ControlMessage(ControlMessageType.RequestLoad); //cMessage.setUrl(this.getUrl()); //socket.sendMessage(cMessage, "localsocket://" + rmUrl); } // schedule waiting messages to the different clusters for (Job job : jobQueue) { String leastLoadedRM = getLeastLoadedRM(); if (leastLoadedRM!=null) { ControlMessage cMessage = new ControlMessage(ControlMessageType.AddJob); cMessage.setJob(job); socket.sendMessage(cMessage, "localsocket://" + leastLoadedRM); jobQueue.remove(job); // increase the estimated load of that RM by 1 (because we just added a job) int load = resourceManagerLoad.get(leastLoadedRM); resourceManagerLoad.put(leastLoadedRM, load+1); } } // sleep try { Thread.sleep(pollSleep); } catch (InterruptedException ex) { assert(false) : "Grid scheduler runtread was interrupted"; } } }
01201e72-6ded-436f-8b2c-f5e3627b6c87
9
public void clearRows() { boolean [] notFullRows = new boolean[board.length]; for (int r = board.length - 1; r >= 0; r--) { for (int c = 0; c < board[r].length && !notFullRows[r]; c++) { if (board[r][c] == EMPTY) notFullRows[r] = true; } } boolean temp = false; for (boolean b : notFullRows) { if (!b) temp =true; } if (temp) { int pointerNew = board.length - 1; int [][] newBoard = new int[board.length][board[0].length]; for (int i = notFullRows.length - 1; i >= 0 ; i--) { if(notFullRows[i]) System.arraycopy(board[i], 0, newBoard[pointerNew--], 0, board[i].length); } board = newBoard; commit(); } }
0b9d8752-70b6-49dc-95b4-5a072a8a890e
5
public int compareTo(Duration other) { if (other == null) { throw new NullPointerException("Cannot compare Duration to null."); } if (this.millis == other.millis) { return nanos < other.nanos ? -1 : nanos == other.nanos ? 0 : 1; } return this.millis < other.millis ? -1 : 1; }
d0a1fa6c-19e7-44fb-9052-aeb217bbb9e3
0
@Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; }
08052eea-d0a0-42ad-8f8b-0dac7b0bb960
4
public void createHexagons(int hexagonColumns, int hexagonRows, int r, int x, int y){ int originalX = x; for(int j=0; j<hexagonRows; j++){ for(int i=0; i<hexagonColumns; i++){ singleHexagon = new Polygon(); for(int k=0; k<6; k++) { singleHexagon.addPoint((int)(x + r * Math.cos(k * 2 * Math.PI / 6 + Math.toRadians(30))), (int)(y + r * Math.sin(k * 2 * Math.PI/6 + Math.toRadians(30)))); } hexagonArray[i][j] = singleHexagon; x = x + 2*r; } if(j % 2 == 0) { x = originalX + r; } else { x = originalX; } y = y + 2 * r - originalX/4; } }
ee2368d7-3fd5-4a3d-9742-aed135cc632c
0
private void initUpperBars(){ upperBars = new JPanel(); upperBars.setLayout(new BorderLayout()); upperBars.add(menuBar, BorderLayout.NORTH); upperBars.add(menuBarWithButtons, BorderLayout.SOUTH); add(upperBars, BorderLayout.NORTH); }
eea07f58-d0ba-4c0d-a893-5f844a8bbafe
5
public void setTypeNumber() { if (type == Type.AIR) typeNumber = 0; if (type == Type.DIRT) typeNumber = 1; if (type == Type.WOOD) typeNumber = 2; if (type == Type.STONE) typeNumber = 3; if (type == Type.GLASS) typeNumber = 4; }
5032ac7a-1102-4784-9df5-af85fa9fd518
4
public Color[] fileToColorArray(File file) throws IOException { int lim; File2Hex converter = new File2Hex(); String hexString = converter.convertToHex(file); Scanner hexStringScanner = new Scanner(hexString); ArrayList<String> snipArray = new ArrayList<>(); while(hexStringScanner.hasNext()) { snipArray.add(hexStringScanner.next()); } //Add EOF indicator. for (int i = 0; i < 12; i++) { snipArray.add("FF"); } lim = snipArray.size(); //Stores secret as an array of hex Strings. String[] hexArray = snipArray.toArray(new String[0]); //Stores secret as an array of Color. Color[] colorArray = new Color[getSize()]; //Populate Hex Array. for (int counter = 0; counter < lim; counter++) { hexArray[counter] = "00" + hexArray[counter]; } //Populate Color Array. for (int counter2 = 0; counter2 < lim; counter2++) { colorArray[counter2] = new Color((int) Long.parseLong(hexArray[counter2], 16)); } return (colorArray); }
7813c7bf-92d7-4dba-a5fd-4ae9acdf347a
2
public void deposit (int amount) { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("deposit", true); $out.write_ulong (amount); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { deposit (amount ); } finally { _releaseReply ($in); } } // deposit
2d4bcc1c-7043-4c12-a162-ba3f7e14e94b
9
/* */ public String attemptingToConnect(String username, char[] password) /* */ { /* 76 */ Config.USERNAME = username.toLowerCase(); /* 77 */ String serverResponse = null; /* */ /* 80 */ Player player = new Player(0, -1, username, 0, 193, 423, "cache/graphics/sprites/character.png", null); /* 81 */ PlayerList.getInstance().overwritePlayer(player); /* */ try /* */ { /* 85 */ String actualPassword = ""; /* */ /* 87 */ for (int i = 0; i < password.length; i++) /* */ { /* 89 */ actualPassword = actualPassword + password[i]; /* */ } /* */ /* 92 */ String rawStringToSend = username + "," + actualPassword + "," + "0.61"; /* */ /* 94 */ byte[] encryptedBytesToSend = PublicKeyManager.encrypt(rawStringToSend, Config.PUBLIC_KEY); /* 95 */ int byteLength = encryptedBytesToSend.length; /* */ /* 99 */ this.socket = new Socket("38.89.137.25", 3336); /* 100 */ DataOutputStream outputStream = new DataOutputStream(this.socket.getOutputStream()); /* 101 */ outputStream.writeInt(byteLength); /* 102 */ outputStream.write(encryptedBytesToSend); /* 103 */ outputStream.flush(); /* */ /* 107 */ BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); /* */ /* 110 */ serverResponse = inputBuffer.readLine(); /* 111 */ System.out.println(serverResponse); /* */ } /* */ catch (UnknownHostException e) { /* 114 */ e.printStackTrace(); /* */ } catch (IOException e) { /* 116 */ System.out.println("Server offline"); /* 117 */ return "Server Offline"; /* */ } /* */ /* 121 */ if (serverResponse.equalsIgnoreCase("INVALIDPASSWORDORUSERNAME")) /* */ { /* 123 */ return "You username or password is incorrect."; /* */ } /* 125 */ if (serverResponse.equalsIgnoreCase("ALREADYLOGGEDIN")) /* */ { /* 127 */ return "Your account is already logged in. OH OH!"; /* */ } /* 129 */ if (serverResponse.equalsIgnoreCase("VERSIONERROR")) /* */ { /* */ try { /* 132 */ Desktop.getDesktop().browse(new URI("http://www.diamondhunt.co/mmo/play.php")); /* */ } catch (IOException localIOException1) { /* */ } catch (URISyntaxException localURISyntaxException) { /* */ } /* 136 */ return "This client is outdated, please download the newest version."; /* */ } /* */ /* 139 */ if (serverResponse.equalsIgnoreCase("GRANTED")) /* */ { /* 141 */ start(); /* */ /* 144 */ this.game.setSocket(this.socket); /* 145 */ this.game.init(); /* 146 */ this.gameEngine = new GameEngine(this.game); /* 147 */ this.gameEngine.start(); /* */ /* 149 */ return username; /* */ } /* */ /* 152 */ return "ERROR - CONTACT ADMIN"; /* */ }
ab254b4c-ea65-4aae-b9ae-b2b229b4b2b7
1
public void updateSubTypes() { if (!staticFlag) subExpressions[0].setType(Type.tSubType(classType)); }
30b8e0cd-786a-4022-a4c5-5e5c5d9a1930
2
private TreeRow getBeforeFirstSelectedRow() { TreeRow prior = null; for (TreeRow row : new TreeRowViewIterator(this, mRoot.getChildren())) { if (mSelectedRows.contains(row)) { return prior; } prior = row; } return null; }
7bf809a0-4741-4f65-b9c7-fe95fdfbf1e0
5
public static void loadOtherTabAccount(String serverID) { Account account = null; for (int i = 0; i < Account.allAccounts.length; i++) { try { if (!"OpenTransactionAccount".equals(Account.allAccounts[i]) && !"CashPurseAccount".equals(Account.allAccounts[i])) { Class obj = Class.forName("com.moneychanger.core." + Account.allAccounts[i]); account = (Account) obj.newInstance(); if (i == 0) { account.clearAccountList(); } account.loadAccount("", serverID, ""); } } catch (Exception e) { e.printStackTrace(); } } ((OtherTabAccountModel) jTable3.getModel()).setValue(account.getAccountList(), jTable3); }
c3b7ba4b-9523-4641-b2f6-1239bcf7e36b
7
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if((affected!=null) &&(affected instanceof MOB) &&(msg.amISource((MOB)affected)||msg.amISource(((MOB)affected).amFollowing())||(msg.source()==invoker())) &&(msg.sourceMinor()==CMMsg.TYP_QUIT)) { unInvoke(); if(msg.source().playerStats()!=null) msg.source().playerStats().setLastUpdated(0); } }
dcdf2bc1-3ced-451a-a821-8b9ecd5c8b9c
0
public RSAKeyValueType createRSAKeyValueType() { return new RSAKeyValueType(); }
a92adf18-30b3-46fd-9014-01187c082446
4
private void LoadFriends() throws SQLException { Grizzly.GrabDatabase().SetQuery("SELECT * FROM server_friendships WHERE user_id = '" + this.ID + "'"); if (Grizzly.GrabDatabase().RowCount() > 0) { ResultSet AsFirstFriend = Grizzly.GrabDatabase().GrabTable(); while(AsFirstFriend.next()) { Friends.put( new Integer(AsFirstFriend.getInt("id")), UserHandler.GenerateUser(AsFirstFriend.getInt("friend_id"))); } } Grizzly.GrabDatabase().SetQuery("SELECT * FROM server_friendships WHERE friend_id = '" + this.ID + "'"); if (Grizzly.GrabDatabase().RowCount() > 0) { ResultSet AsSecondFriend = Grizzly.GrabDatabase().GrabTable(); while(AsSecondFriend.next()) { Friends.put( new Integer(AsSecondFriend.getInt("id")), UserHandler.GenerateUser(AsSecondFriend.getInt("user_id"))); } } }
1cb28fb8-76ff-4ffc-a2bc-3e83eb13db96
3
public void die(){ if (sound.Manager.enabled) { sound.Event effect = new sound.Event(getPosition(), getVelocity(),sound.Library.findByName(DEATH_EFFECT)); effect.gain = EFFECT_VOLUME; sound.Manager.addEvent(effect); } velocity.timesEquals(0); if(ParticleSystem.isEnabled()) ParticleSystem.addEvent((new Explosion<Fire>(Fire.class,this)).setIntensity(96)); if(ParticleSystem.isEnabled()) ParticleSystem.removeGenerator(particleGenerator); delete(); }
e7a7fec2-270b-4446-811e-f30ced1c5706
2
private int getDistanceBetweenTiles(Tile from, Tile to) { int distance = 14; if (from.getX() == to.getX()) { distance = 10; } if (from.getY() == to.getY()) { distance = 10; } return distance; }
014365fc-fda2-4f51-9980-8feffddc72bb
6
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); String url = "/"; String action = (String)req.getParameter("action"); LoginViewHelper loginViewHelper = ViewHelperFactory.getInstance().getLoginViewHelper(req); req.setAttribute("loginViewHelper", loginViewHelper); switch (action) { case "login": url += "Login.jsp"; break; case "login-submit": if (loginViewHelper.containsValidLoginDetails() && loginViewHelper.emailPasswordComboIsInDatabase()) { Customer customer = DAOFactory.getInstance().getCustomerDAO() .findCustomerByEmail(loginViewHelper.getEmail()); session.setAttribute("loggedInCustomer", customer); if ("purchase".equals(req.getParameter("requestAction"))) { url += "purchaseController"; } else { req.setAttribute("msg", "" + customer.getForename() + ", welcome back to GAMER.com !"); req.setAttribute("link", "start shopping " + "<a href=\"/GAMER/shop?action=home\">here</a>"); url += "UserMsg.jsp"; } } else { if ("purchase".equals(req.getParameter("requestAction"))) { req.setAttribute("requestAction", "purchase"); } url += "LoginSubmitted.jsp"; } break; } getServletContext().getRequestDispatcher(url).forward(req, res); }
99e2adab-87e2-4412-8dd2-401ce4e8ce39
2
public static int createMenu(Menu menu, String accessToken) { int result = 0; // ƴװ˵url String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); // ˵תjsonַ String jsonMenu = JSONObject.fromObject(menu).toString(); // ýӿڴ˵ JSONObject jsonObject = httpRequest(url, "POST", jsonMenu); if (null != jsonObject) { if (0 != jsonObject.getInt("errcode")) { result = jsonObject.getInt("errcode"); log.error("˵ʧ errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; }
3e89a3f7-d637-4bd5-a943-15aa85f5a809
8
public void loadConfiguration() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(configurationFile); // Get the root element <configuration> Element rootNode = doc.getDocumentElement(); NodeList nodeList = rootNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); if (childNode.getNodeType() != Node.ELEMENT_NODE) { continue; } if ("classpath".equals(childNode.getNodeName())) { //$NON-NLS-1$ parseClassPathEntry(childNode); } else if ("connections".equals(childNode.getNodeName())) { //$NON-NLS-1$ parseConnections(childNode); } else if ("tagertProject".equals(childNode.getNodeName())) { //$NON-NLS-1$ tagertProject = parseElementNodeValue(childNode); } else if ("basePackage".equals(childNode.getNodeName())) { //$NON-NLS-1$ basePackage = parseElementNodeValue(childNode); } else if ("moduleName".equals(childNode.getNodeName())) { //$NON-NLS-1$ moduleName = parseElementNodeValue(childNode); } else if ("templates".equals(childNode.getNodeName())) { //$NON-NLS-1$ parseTemplates(childNode); } } }
a1c500d4-3d4f-4fa8-8df6-a7fb3e8ece37
4
public void testBinaryCycAccess2() { System.out.println("\n**** testBinaryCycAccess 2 ****"); CycAccess cycAccess = null; try { try { if (connectionMode == LOCAL_CYC_CONNECTION) { cycAccess = new CycAccess(testHostName, testBasePort); } else if (connectionMode == SOAP_CYC_CONNECTION) { cycAccess = new CycAccess(endpointURL, testHostName, testBasePort); } else { fail("Invalid connection mode " + connectionMode); } } catch (Throwable e) { e.printStackTrace(); fail(e.toString()); } // cycAccess.traceOnDetailed(); // cycAccess.traceNamesOn(); doTestCycAccess2(cycAccess); } finally { if (cycAccess != null) { cycAccess.close(); cycAccess = null; } } System.out.println("**** testBinaryCycAccess 2 OK ****"); }
20b35737-0628-4f79-a5be-c6cb715b0f1b
8
public void ShowHelp(CommandSender sender, String cmdLabel, int page) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add("/" + cmdLabel + " help " + prekick.language.GetText("PreKickCommand.Help.Help").replaceAll("%CMDLABEL%", cmdLabel)); if (p(sender, "prekick.blacklist.switch")) cmds.add("/" + cmdLabel + " on - " + prekick.language.GetText("PreKickCommand.Help.Switch.On").replaceAll("%CMD%", "blacklist")); if (p(sender, "prekick.blacklist.switch")) cmds.add("/" + cmdLabel + " off - " + prekick.language.GetText("PreKickCommand.Help.Switch.On").replaceAll("%CMD%", "blacklist")); if (p(sender, "prekick.blacklist.add")) cmds.add("/" + cmdLabel + " add " + prekick.language.GetText("PreKickCommand.Help.Blacklist.Add")); if (p(sender, "prekick.blacklist.remove")) cmds.add("/" + cmdLabel + " remove " + prekick.language.GetText("PreKickCommand.Help.Blacklist.Remove")); int maxpage = 1 + cmds.size() / 6; if (page < 1) page = 1; else if (page > maxpage) page = maxpage; sender.sendMessage(prekick.language.GetText("PreKickCommand.Help.Page").replaceAll("%VERSION%", prekick.version).replaceAll("%PAGE%", page + "").replaceAll("%MAXPAGE%", maxpage + "")); try { for (int i = (page - 1) * 6; i < ((page - 1) * 6) + 6; i++) { sender.sendMessage(cmds.get(i)); } } catch (Exception e) { } }
039958d5-b67d-431e-9896-faf48e2c15c7
0
public void setLastActivity(int lastActivity) { this.lastActivity = lastActivity; }
dde0773a-ad5d-46cc-9802-fc6fe51029c4
1
private void createPlayHistory(int drawnCard){ DataInstance pdi = new DataInstance(playNet.inputNodes()); //Rack int[] cur_rack = rack.getCards(); pdi.addFeature(cur_rack, game.card_count); //Probabilities if (USE_PROB_PLAY){ double[][] prob = rack.getProbabilities(false, 0); pdi.addFeature(prob[0], 1); pdi.addFeature(prob[1], 1); } //The card that was drawn pdi.addFeature(drawnCard, game.card_count); play_instance = pdi; }
50ccb333-93a1-4773-8f8a-6d364aaffcfe
5
public boolean setNewValue(int depth, int value) { if(isFull()) { return false; } if(depth==1) { if(o0==null) { set0(new HuffmanNode(this, value)); return true; } else if(o1==null) { set1(new HuffmanNode(this, value)); return true; } else { return false; } } else { return get0().setNewValue(depth-1, value)? true: get1().setNewValue(depth-1, value); } }
7b0ab5b1-4c41-4d47-9ca9-3cf3d054c12e
4
private Vector<String> getAvailableLF() { final LookAndFeelInfo lfs[] = UIManager.getInstalledLookAndFeels(); lookNFeelHashMap = new HashMap<>(lfs.length); final Vector<String> v = new Vector<>(lfs.length); for (final LookAndFeelInfo lf2: lfs) { lookNFeelHashMap.put(lf2.getName(), lf2.getClassName()); v.add(lf2.getName()); if (utils.Properties.getLookAndFeel().equals(lf2.getClassName())) { currentLookAndFeel = lf2.getName(); } } // SUBSTANCE LookAndFeels TreeMap<String, SkinInfo> treemap = (TreeMap<String, SkinInfo>) SubstanceLookAndFeel.getAllSkins(); Iterator<Entry<String,SkinInfo>> it = treemap.entrySet().iterator(); while(it.hasNext()) { Entry<String,SkinInfo> e = (Entry<String,SkinInfo>)it.next(); v.add(e.getKey()); lookNFeelHashMap.put(e.getKey(), e.getValue().getClassName()); if (utils.Properties.getLookAndFeel().equals(e.getValue().getClassName())) { currentLookAndFeel = e.getKey(); } } return v; }
1d901aca-977e-4458-9a8a-2c5eb1bc924c
7
protected void execute(final String action) throws MojoExecutionException, MojoFailureException { final Properties properties; try { properties = PropertiesUtil.getInstance().loadProperties(propertiesPath); } catch (IOException e) { throw new MojoFailureException("Could not load properties file"); } final String org = properties.getProperty("aiq.orgname"); final String username = properties.getProperty("aiq.username"); final String password = properties.getProperty("aiq.password"); final String aiqUrl = properties.getProperty("aiq.url"); final String solution = properties.getProperty("aiq.solution"); final String accessToken = authenticate(aiqUrl, username, password, org, solution).getAccessToken(); getLog().info("Tailing logs from the org [" + org + "]"); final HttpClient client = new DefaultHttpClient(); String since = null; try { while (true) { HttpGet get = new HttpGet(buildIntegrationURI(url, org, action)); get.setHeader(HttpHeaders.AUTHORIZATION, "BEARER " + accessToken); if (since != null) get.setHeader(HttpHeaders.IF_MODIFIED_SINCE, since); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { since = response.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue(); final InputStream input = response.getEntity().getContent(); IOUtils.copy(input, System.out); input.close(); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { // just wait } else { throw new MojoFailureException("Failed to tail logs, the status code is [" + response.getStatusLine().getStatusCode() + "] and error message is [" + response.getStatusLine().getReasonPhrase() + "]"); } Thread.sleep(5*1000); } } catch (IOException e) { throw new MojoFailureException(e.getMessage()); } catch (InterruptedException ignore) { // just exit } }
fffd89a3-003a-485c-9b04-0fa7fd834be0
2
public void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int res = 0; for (int i = 1; i <= n; i++) { if (gcd(i, n) == 1) { res++; } } System.out.println(res); }
e33da5f0-5c89-4bff-b8d4-5a5ada1f446c
2
public static void main (String[] args) { int[] a = new int[14]; int[] b = new int[4]; for (int i=0; i !=4 ; i++) { a[i] = i * i; } for ( int i=0; i != b.length; ++i ) { b[i] = i * 2; } mergeB2A(a, b, 4, b.length); System.out.println( Arrays.toString(a) ); }
1e187a64-4602-4523-a9af-50ba28122b05
2
public void loadChannels() throws SQLException { sql.initialise(); ResultSet res = sql.sqlQuery("SELECT * FROM BungeeChannels"); while(res.next()){ ChatChannel newchan = new ChatChannel(res.getString("ChannelName"), res.getString("ChannelFormat"),res.getString("Owner"), res.getBoolean("isServerChannel")); plugin.chatChannels.put(newchan.getName(), newchan); } res.close(); ResultSet res2 = sql.sqlQuery("SELECT * FROM BungeeInvites"); while(res2.next()){ ChatChannel c = plugin.getChannel(res2.getString("ChannelName")); c.invitePlayer(res.getString("PlayerName")); } sql.closeConnection(); }
3f9bc699-f620-449c-a0e8-07405012c1dd
6
private static void applyHysteresis(Image image, double t1, double t2, ChannelType c) { ChannelType color = c == null ? RED : c; for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { double pixel = image.getPixel(x, y, color); double val = pixel; if (pixel < t1) { val = 0; } else if (pixel > t2) { val = Image.MAX_VAL; } if (c == null) { image.setPixel(x, y, RED, val); image.setPixel(x, y, GREEN, val); image.setPixel(x, y, BLUE, val); } else { image.setPixel(x, y, c, val); } } } }
7c03b85c-a9ff-4b1e-85bf-e00ff68f9091
2
public int[][] getActualGrid() { int[][] gridActual = new int[sudokuSize][sudokuSize]; for (int i = 0; i < sudokuSize; i++) { for (int j = 0; j < sudokuSize; j++) { gridActual[i][j] = cells[i][j].current; } } return gridActual; }
4f432ef6-3670-4297-adbd-9221b43ed102
5
@Override public void controllAnts(LinkedList<MyAnt> freeAnts, long time) { for (MyAnt ant : freeAnts) { Logger.printLine(ant + " tries to survive"); LinkedList<Field> neighbors = new LinkedList<Field>(); for (Field neighbor : ant.getField().getTurnNeighbors()) { if (!neighbor.hasWater()) neighbors.add(neighbor); } Collections.sort(neighbors, Field.getDangerComparator()); while (!neighbors.isEmpty() && !ant.setNextField(neighbors.pop(), false, false)) ; } }
0c0fc0b5-ca55-4733-9d42-7976dc829f06
7
public boolean collidesRectAgainstRect(double x1, double y1, int width1, int height1, double x2, double y2, int width2, int height2) { double right1 = x1 + width1; double right2 = x2 + width2; double bottom1 = y1 + height1; double bottom2 = y2 + height2; return (x1 <= x2 && x2 < right1 || x2 <= x1 && x1 < right2) && (y1 <= y2 && y2 < bottom1 || y2 <= y1 && y1 < bottom2); }
ea196fa1-c330-47aa-b8c6-47f9f21cb624
2
public ArrayList<Employee> searchEmployee(String name) { ArrayList<Employee> _searchResults = new ArrayList<Employee>(); for (Employee emp : employees) { if(emp.getFullName().contains(name)) { _searchResults.add(emp); } } return _searchResults; }
4af6f30b-ece5-487b-9629-25480df17d94
5
private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCadastrarActionPerformed //Tela de Cadastro de Departamento if (txtNomeDep.getText().equals("") || txtCodDep.getText().equals("")) { JOptionPane.showMessageDialog(null, " Preencha todos os campos!!!", "Cadastro de Departamento", JOptionPane.ERROR_MESSAGE); } else { Departamento DEP = new Departamento(); String Nome = txtNomeDep.getText(); String CodDep = txtCodDep.getText(); DEP.setNome(Nome); DEP.setCodigo(CodDep); DepartamentoBO depBO = new DepartamentoBO(); logSegurancaDados log = null; try { depBO.criarDep(DEP); JOptionPane.showMessageDialog(null, "Departamento Cadastrado com Sucesso !!!", "Cadastro de Departamento", JOptionPane.INFORMATION_MESSAGE); log = new logSegurancaDados("INFO", "Cadastro de Departamento realizado com sucesso pelo " + usuarioLogado.getTipo() + " : " + usuarioLogado.getNome()); txtCodDep.setText(""); txtNomeDep.setText(""); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao Cadastrar o departamento", "Cadastro de Departamento", JOptionPane.ERROR_MESSAGE); } catch (excecaoDepartamento ex) { JOptionPane.showMessageDialog(null, "Ja existe um Departamento cadastrado\n" + " Com este nome ou código!!!", "Cadastro de Departamento", JOptionPane.ERROR_MESSAGE); } catch (excecaoCodDepartamentoInavlido ex) { JOptionPane.showMessageDialog(null, "É obrigatório digitar um codigo com 3 letras", "Cadastro de Departamento", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_btnCadastrarActionPerformed
66ede95b-ad81-44c9-b02a-df6df55916f9
9
public static Direction findDirection(Point source, Point dest) { if(source.equals(dest)) return null; long p = source.getX(); long q = source.getY(); long r = dest.getX(); long s = dest.getY(); if(p<r && q>s) return Direction.SOUTHEAST; else if(p<r && q<s) return Direction.NORTHEAST; else if(p>r && q>s) return Direction.SOUTHWEST; else if(p>r && q<s) return Direction.NORTHWEST; else return null; }
bcd16057-15d7-46aa-b59b-748f272895f0
2
private int[] hideLay(int[][] lay) { int hiddenLay[] = new int[HEIGHT * HEIGHT]; int k = 0; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < HEIGHT; j++) { hiddenLay[k++] = lay[i][j]; } } return hiddenLay; }
50441a68-f505-42ec-825e-5dd1fef911b2
6
public void tableChanged(TableModelEvent e) { // If we're not sorting by anything, just pass the event along. if (!isSorting()) { clearSortingState(); fireTableChanged(e); return; } // If the table structure has changed, cancel the sorting; the // sorting columns may have been either moved or deleted from // the model. if (e.getFirstRow() == TableModelEvent.HEADER_ROW) { cancelSorting(); fireTableChanged(e); return; } // We can map a cell event through to the view without widening // when the following conditions apply: // // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and, // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and, // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and, // d) a reverse lookup will not trigger a sort (modelToView != null) // // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS. // // The last check, for (modelToView != null) is to see if modelToView // is already allocated. If we don't do this check; sorting can become // a performance bottleneck for applications where cells // change rapidly in different parts of the table. If cells // change alternately in the sorting column and then outside of // it this class can end up re-sorting on alternate cell updates - // which can be a performance problem for large tables. The last // clause avoids this problem. int column = e.getColumn(); if (e.getFirstRow() == e.getLastRow() && column != TableModelEvent.ALL_COLUMNS && getSortingStatus(column) == NOT_SORTED && modelToView != null) { int viewIndex = getModelToView()[e.getFirstRow()]; fireTableChanged(new TableModelEvent(YTableSorter.this, viewIndex, viewIndex, column, e.getType())); return; } // Something has happened to the data that may have invalidated the row order. clearSortingState(); fireTableDataChanged(); return; }
f347d238-6275-49c2-a865-09953529c142
7
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if((myHost==null)||(!(myHost instanceof MOB))) return; final MOB mob=(MOB)myHost; if(msg.amISource(mob)&&(msg.tool() instanceof Ability)) { final Ability A=(Ability)msg.tool(); if((mob.isMine(A)) &&(!CMLib.ableMapper().getDefaultGain(ID(),false,A.ID())) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)) { mob.delAbility(A); mob.recoverMaxState(); } } }
f204179e-3e8c-4a7c-a40b-4cd1f50c3257
9
public static void main(String[] args) throws InterruptedException{ int iloscProcesowA = 3; int iloscProcesowB = 3; int iloscProcesowAB = 3; Thread procesyA[] = new Thread[iloscProcesowA]; Thread procesyB[] = new Thread[iloscProcesowB]; Thread procesyAB[] = new Thread[iloscProcesowAB]; Zasoby zasoby = new Zasoby(); for(int i=0; i<iloscProcesowA; ++i){ procesyA[i] = new ProcesA(i, zasoby); } for(int i=0; i<iloscProcesowB; ++i){ procesyB[i] = new ProcesB(i, zasoby); } for(int i=0; i<iloscProcesowAB; ++i){ procesyAB[i] = new ProcesAB(i, zasoby); } for(int i=0; i<iloscProcesowA; ++i){ procesyA[i].start(); } for(int i=0; i<iloscProcesowB; ++i){ procesyB[i].start(); } for(int i=0; i<iloscProcesowAB; ++i){ procesyAB[i].start(); } for(int i=0; i<iloscProcesowA; ++i){ procesyA[i].join(); } for(int i=0; i<iloscProcesowB; ++i){ procesyB[i].join(); } for(int i=0; i<iloscProcesowAB; ++i){ procesyAB[i].join(); } }
9bbb0350-6f09-49c0-973c-f1387c7a19ff
3
private void repaintChangedRollRow(Row rollRow) { if (rollRow != mRollRow) { Column column = mModel.getColumnAtIndex(0); Rectangle bounds; if (mRollRow != null) { bounds = getCellBounds(mRollRow, column); bounds.width = mModel.getIndentWidth(mRollRow, column); repaint(bounds); } if (rollRow != null) { bounds = getCellBounds(rollRow, column); bounds.width = mModel.getIndentWidth(rollRow, column); repaint(bounds); } mRollRow = rollRow; } }
f8188f3c-90fe-444a-9443-650a7c78399a
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhpposSalesItemsEntityPK that = (PhpposSalesItemsEntityPK) o; if (itemId != that.itemId) return false; if (saleId != that.saleId) return false; return true; }
125ae831-078c-4f93-91c0-a84773893e60
7
private static double calculatePeptideMass(AminoAcidSequence aminoAcidSequence, List<PTModification> modifications, boolean monoMass, double... massCorrections) { // calculate peptide mass double mass = monoMass ? aminoAcidSequence.getMonoMass() : aminoAcidSequence.getAvgMass(); // add modifications if (modifications != null) { for (PTModification modification : modifications) { List<Double> massDeltas = monoMass ? modification.getMonoMassDeltas() : modification.getAvgMassDeltas(); if (massDeltas != null && !massDeltas.isEmpty()) { mass += massDeltas.get(0); } } } // add corrections for (double massCorrection : massCorrections) { mass += massCorrection; } return mass; }
1960f7da-cdfd-419e-80dc-fd2673909fcb
8
public byte[] getNetworkBytes() { ByteArrayOutputStream buf = new ByteArrayOutputStream(); buf.write((byte) 0x23); buf.write((byte) 0x54); buf.write((byte) 0x26); buf.write((byte) 0x68); for (int i = 7; i >= 0; i--) { buf.write((byte) ((tstamp >> 8*i) & 0xff)); } for (BLImageViewport viewport : viewports) { byte[] pixelData = AbstractFramePacket.extractPixelData(viewport); buf.write((byte) viewport.getScreenId()); buf.write((byte) (viewport.getBpp() & 0xff)); // height (16-bit) buf.write((byte) ((viewport.getImageHeight() >> 8) & 0xff)); buf.write((byte) (viewport.getImageHeight() & 0xff)); // width (16-bit) buf.write((byte) ((viewport.getImageWidth() >> 8) & 0xff)); buf.write((byte) (viewport.getImageWidth() & 0xff)); for (int j = 0; j < viewport.getImageHeight(); j++) { if (viewport.getBpp() == 4) { for (int i = 0; i < viewport.getImageWidth(); i += 2) { int left = pixelData[i + (j * viewport.getImageWidth())] >> 4; int right; if(i + 1 < viewport.getImageWidth()) { right = pixelData[i + (j * viewport.getImageWidth()) + 1] >> 4; } else { right = 0; } buf.write((byte)((left << 4 | (right & 0x0f)) & 0xff)); } } if (viewport.getBpp() == 8) { for (int i = 0; i < viewport.getImageWidth(); i++) { buf.write(pixelData[i + (j * viewport.getImageWidth())]); } } } } return buf.toByteArray(); }
2f9b0874-5bef-4df9-8c4b-92a236e13c60
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(VerInformacionCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VerInformacionCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VerInformacionCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VerInformacionCliente.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 VerInformacionCliente().setVisible(true); } }); }
1328acc7-a45d-49e5-a861-519963a8abee
9
public Counter winningMove(Move lastMove, Board b) { boolean end = false; int x = Board.MINWIDTH; int y = b.getHeight(); Counter winner = Counter.EMPTY; while((y >= Board.MINHEIGHT) && !end) { while ((x <= b.getWidth() && !end)) { //Check up end = Util.checkCellInDirection(b, x, y, DirectionX.NOTHING, DirectionY.UP); //Check right if (!end) end = Util.checkCellInDirection(b, x, y, DirectionX.RIGHT, DirectionY.NOTHING); //Check up-left diagonal if (!end) end = Util.checkCellInDirection(b, x, y, DirectionX.LEFT, DirectionY.UP); //Check up-right diagonal if (!end) end = Util.checkCellInDirection(b, x, y, DirectionX.RIGHT, DirectionY.UP); //Increase x counter if(!end) x++; } if (end) { winner = b.getPosition(x, y); } x = Board.MINWIDTH; y--; } return winner; }
594e21e1-e6bb-450c-926e-d544988d29a2
5
public void endEditingTurn() { if(myTurnEditing) //finish with player 1 { if(Main.isTwoPlayers) { myTurnEditing = false; mySea.renderEditingShip = false; theirSea.renderEditingShip = true; editingPos = -1; editNextShip(); Main.manualAdding = true; Main.editingMode = true; Main.swap(); theirSea.clearShips(); } else { Main.manualAdding = true; ArrayList<Ship> proposedAIFleet = BattleShipAI.getShips(theirSea.sea); if(theirSea.isValidFleet(proposedAIFleet)) { theirSea.clearShips(); for(Ship ship : proposedAIFleet) theirSea.fleet.add(ship); theirSea.updateNums(); // endEditingTurn(); //try without it for now mySea.renderEditingShip = false; theirSea.renderEditingShip = false; Main.editingMode = false; Main.placingShips = false; } else { System.err.println("BUG IN AI - ILLEGAL SHIP PLACEMENT"); } } } else if(!myTurnEditing) //finish with player 2 { mySea.renderEditingShip = false; theirSea.renderEditingShip = false; Main.editingMode = false; Main.swap(); Main.placingShips = false; } }
b66bc972-83cd-4e52-b219-6f0518406a67
7
protected boolean stepSearch() { if (maxSearched > 0 && flagged.size() > maxSearched) { if (verbose) I.say("Reached maximum search size ("+maxSearched+")") ; return false ; } final Object nextRef = agenda.leastRef() ; final T next = agenda.refValue(nextRef) ; agenda.deleteRef(nextRef) ; if (endSearch(next)) { success = true ; bestEntry = entryFor(next) ; totalCost = bestEntry.total ; if (verbose) I.say( " ...search complete at "+next+", total cost: "+totalCost+ " all searched: "+flagged.size() ) ; return false ; } for (T near : adjacent(next)) if (near != null) { tryEntry(near, next, cost(next, near)) ; } return true ; }
8b827aca-0de5-49bb-8553-a2a9be7f6802
3
private Status testForTrack(int x, int y, int z) { World world = tile.getWorldObj(); for (int jj = -2; jj < 4; jj++) { if (!world.blockExists(x, y - jj, z)) return Status.UNKNOWN; if (RailTools.isRailBlockAt(world, x, y - jj, z)) { trackLocation = new WorldCoordinate(world.provider.dimensionId, x, y - jj, z); return Status.VALID; } } return Status.INVALID; }
ffd4e28c-8392-40f2-aa5d-1dee1858c252
7
public void objectGroundCollision() { long time = System.currentTimeMillis(); if (gcontact==null) gcontact = new Contact(new Vector(), new Vector(), 0); for (ObjectProperties object : scene.getObjects()) { if (!object.isPinned && scene.getCount() > 0 && object != null && scene.getGround() != null) { // get the collision coordinates the object points to Ground ground = scene.getGround(); Util.ground = ground; Util.object = object; Double xn = Util.newtonIteration(); object.last_intersection.setX( xn ); object.last_intersection.setY( ground.function(xn) ); double x = object.last_intersection.getX(); double y = object.last_intersection.getY(); // calculate smallest distance between object and ground IFunction func = new IFunction() { @Override public double function(double x) { return scene.getGround().function((int) x); } }; double range = object.getRadius() * 5; de.engine.math.Vector nextPos = object.getNextPosition(); distCalcer.setPoint(nextPos); distCalcer.setFunction(func); double dist = distCalcer.calculateDistanceBetweenFunctionPoint(nextPos.getX() - range, nextPos.getX() + range); object.closest_point = new de.engine.math.Vector(distCalcer.getLastSolvedX(), scene.getGround().function((int) distCalcer.getLastSolvedX())); // check the object collision if (dist < object.getRadius()) { Vector coll_normal = new Vector(Util.u, Util.getNormalFuncValue(object.last_intersection, x + Util.u) - y).norm(); Vector r_o1 = new Vector( object.getPosition().getX()-x, object.getPosition().getY() - y).norm(); double r_o1_cross_n = Util.crossProduct(r_o1, coll_normal); double j_z = -Util.scalarProduct(object.velocity, coll_normal) * (1d + object.surface.elasticity()/ground.surface.elasticity()); double j_n = (1d / object.getMass()) + (r_o1_cross_n * r_o1_cross_n) / object.getMoment_of_inertia(); double j = j_z / j_n; object.velocity.add( coll_normal.multi( j / object.getMass()) ); object.angular_velocity -= Util.crossProduct(Util.minus(object.closest_point, object.getPosition()), coll_normal.multi(j)) / object.getMoment_of_inertia(); } } } DebugMonitor.getInstance().updateMessage("groundColl", "" + (System.currentTimeMillis() - time)); }
899cf0c7-300d-4e91-b596-f60c0177edd5
3
public byte[] decoding(byte[] data) { int bufLen = data.length - (data.length + 31) / 32 * 2; ByteBuffer buf = ByteBuffer.allocate(bufLen); ByteBuffer inDataBuf = ByteBuffer.wrap(data); for(int i = 0; i != data.length / 2; i++) { if(i % 16 == 15 || i == data.length / 2 - 1) { currentData = inDataBuf.getShort(); } else { currentData = inDataBuf.getShort(); convertData = inDataBuf.getShort(); inDataBuf.position(inDataBuf.position() - 2); short convertBit = BitTable.getShortBit(14 - (i % 16)); currentData &= convertBit; convertBit = BitTable.getShortBit(13 - (i % 16)); convertData = (short)(convertData & (~convertBit)); convertData = (short)(convertData << 1); short value = (short)(currentData |convertData); buf.putShort(value); } } return buf.array(); }
9bc2e8c3-f3ba-4623-a7f8-5c5f5fcbb9c7
6
@Override public final String generateHtmlCode() { final StringBuilder sb = new StringBuilder(); sb.append("<!-- TableHelper Generated Code -->\n"); sb.append("<table>\n"); if (this.headersTopRow != null) { sb.append("\t<tr>\n"); if (this.headersLeftRow != null) { sb.append("\t\t<th>&nbsp;</th>\n"); } for (int c = 0; c < this.headersTopRow.length; ++c) { sb.append("\t\t<th>" + this.headersTopRow[c].toString() + "</th>\n"); } sb.append("\t</tr>\n"); } for (int r = 0; r < this.contents.length; ++r) { sb.append("\t<tr>\n"); if (this.headersLeftRow != null) { sb.append("\t\t<th>"); sb.append(this.headersLeftRow[r].toString()); sb.append("</th>\n"); } for (int c = 0; c < this.contents[r].length; ++c) { sb.append("\t\t<td>"); sb.append(this.contents[r][c].toString()); sb.append("</td>\n"); } sb.append("\t</tr>\n"); } sb.append("</table>\n"); return sb.toString(); }
3e2f7521-2796-4243-81fa-3ecea5d3ae82
1
@SuppressWarnings("deprecation") public void testConstructor_RP_RP_PeriodType4() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); YearMonthDay dt2 = null; try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} }
b579ea54-4561-49f9-905e-4a0835c3554d
1
public List<Punto> ObtenerPunto(String consulta){ List<Punto> lista=new ArrayList<Punto>(); if (!consulta.equals("")) { lista=cx.getObjects(consulta); }else { lista=null; } return lista; }
de33c096-9a9c-4728-924f-9931379fa1f4
3
public void validatePassword(ComponentSystemEvent event) { UIComponent components = event.getComponent(); UIInput uiInputPassword = (UIInput) components .findComponent("password"); password = uiInputPassword.getLocalValue() == null ? "" : uiInputPassword.getLocalValue().toString(); UIInput uiInputConfirmPassword = (UIInput) components .findComponent("repassword"); rePassword = uiInputConfirmPassword.getLocalValue() == null ? "" : uiInputConfirmPassword.getLocalValue().toString(); if (!getPassword().equals(getRePassword())) { FacesMessage msg = new FacesMessage( "Password must match Re password"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(null, msg); } else { setConfirmPassword(true); } }
69b2df7b-f215-4bf7-a383-fb29ce3e1fd8
0
public String getTableName() { return tableName; }
d7986fee-411a-4381-a4e2-6f4045e91b36
8
public static void fillHex(int i, int j, double wi, double hi, String n, int xWorm, int yWorm, Graphics2D g2) { int xFrom, yFrom; int xTo = (int) ((i * (s + t)) + s + BORDERS); int yTo = (int) ((j * h + (i % 2) * h / 2) + r + BORDERS); int x = i * (s + t); int y = j * h + (i % 2) * h / 2; MapObject temp = Game.getMapObject(xWorm, yWorm); if (temp instanceof Bacteria) { //Filling Hex g2.setColor(GameWindow.COLOURONE); g2.fillPolygon(hex(x, y)); //Painting Text g2.setColor(GameWindow.COLOURONETXT); g2.drawString(n, (int) (x + r + BORDERS - wi / 4), (int) (y + r + BORDERS + hi / 4)); } if (temp instanceof Worm) { //Filling Hex g2.setColor(GameWindow.COLOURTWO); g2.fillPolygon(hex(x, y)); //Painting Movement Arrow Worm worm = (Worm) temp; g2.setColor(GameWindow.COLOURDIRARROW); if (worm.getDirection().toString().equals("TL")) { xFrom = (int) (((i + 1) * (s + t)) + s + BORDERS); yFrom = (int) ((j * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo + 18); g2.drawLine(xTo, yTo, xTo + 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("TR")) { xFrom = (int) (((i - 1) * (s + t)) + s + BORDERS); yFrom = (int) ((j * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xTo - 10, yTo + 18); g2.drawLine(xTo, yTo, xTo - 20, yTo); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("BL")) { xFrom = (int) (((i + 1) * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo - 18); g2.drawLine(xTo, yTo, xTo + 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("BR")) { xFrom = (int) (((i - 1) * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + h / 2 + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo - 10, yTo - 18); g2.drawLine(xTo, yTo, xTo - 20, yTo); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("T")) { xFrom = (int) ((i * (s + t)) + s + BORDERS); yFrom = (int) (((j + 1) * h + (i % 2) * h / 2) + r + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo + 18); g2.drawLine(xTo, yTo, xTo - 10, yTo + 18); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } else if (worm.getDirection().toString().equals("B")) { xFrom = (int) ((i * (s + t)) + s + BORDERS); yFrom = (int) (((j - 1) * h + (i % 2) * h / 2) + r + BORDERS); g2.drawLine(xTo, yTo, xFrom, yFrom); g2.drawLine(xTo, yTo, xTo + 10, yTo - 18); g2.drawLine(xTo, yTo, xTo - 10, yTo - 18); g2.fillOval(xFrom - 3, yFrom - 3, 6, 6); } //Painting Text g2.setColor(GameWindow.COLOURTWOTXT); g2.drawString(n, (int) (x + r + BORDERS - wi / 3), (int) (y + r + BORDERS + hi / 3)); } }
7f7784ab-c3e7-428a-8a1a-59fb9cbec71d
1
private static void output (ArrayList <String> pseudographics){ for (String e : pseudographics){ System.out.println(e); } }
b4353dc4-4eea-43ad-a17f-e4774e873901
3
public static Object load(String path){ if(! new File(path).exists()){ return null; } Object object = null; try { FileInputStream fis = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fis); try{ object = ois.readObject(); } finally { try { ois.close(); } finally { fis.close(); } } } catch(IOException ioe) { ioe.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return object; }
0c60bcec-92c7-4f5d-8397-38188b1a066b
9
private void readTrunks(File pngFile) throws IOException { DataInputStream input = new DataInputStream(new FileInputStream(pngFile)); try { byte[] nPNGHeader = new byte[8]; input.readFully(nPNGHeader); trunks = new ArrayList<PNGTrunk>(); if ((nPNGHeader[0] == -119) && (nPNGHeader[1] == 0x50) && (nPNGHeader[2] == 0x4e) && (nPNGHeader[3] == 0x47) && (nPNGHeader[4] == 0x0d) && (nPNGHeader[5] == 0x0a) && (nPNGHeader[6] == 0x1a) && (nPNGHeader[7] == 0x0a)) { PNGTrunk trunk; do { trunk = PNGTrunk.generateTrunk(input); trunks.add(trunk); } while (!trunk.getName().equalsIgnoreCase("IEND")); } nPNGHeader = null; System.gc(); } finally { input.close(); input = null; } }
3a1412ed-38bc-499c-b9a7-23f22b1ae0de
8
public static int convertType(String type) throws Exception { int t = 0; if (SESSION_TRANSACTED.equals(type) || String.valueOf(Session.SESSION_TRANSACTED).equals(type)) { t = Session.SESSION_TRANSACTED; } else if (CLIENT_ACKNOWLEDGE.equals(type) || String.valueOf(Session.CLIENT_ACKNOWLEDGE).equals(type)) { t = Session.CLIENT_ACKNOWLEDGE; } else if (DUPS_OK_ACKNOWLEDGE.equals(type) || String.valueOf(Session.DUPS_OK_ACKNOWLEDGE).equals(type)) { t = Session.DUPS_OK_ACKNOWLEDGE; } else if (AUTO_ACKNOWLEDGE.equals(type) || String.valueOf(Session.AUTO_ACKNOWLEDGE).equals(type)) { t = Session.AUTO_ACKNOWLEDGE; } else { throw new Exception("Invalid type: " + type + "."); } return t; }
5353bc8d-a4d4-4903-9a93-89af0aba3954
6
public static void main(String[] args) { CL.setExceptionsEnabled(true); int numPlatformsArray[] =new int[1]; int buffersize=0; int n=1024*1024*10; float srcArrayA[] = new float[n]; float srcArrayB[] = new float[n]; float dstArray[] = new float[n]; for (int i=0; i<n; i++) { srcArrayA[i] = 1; srcArrayB[i] = 1000; } Pointer srcA = Pointer.to(srcArrayA); Pointer srcB = Pointer.to(srcArrayB); Pointer dst = Pointer.to(dstArray); CL.clGetPlatformIDs(0, null, numPlatformsArray); int numPlatforms = numPlatformsArray[0]; cl_platform_id platforms[]=new cl_platform_id[numPlatforms]; CL.clGetPlatformIDs(platforms.length,platforms,null); cl_platform_id platform=platforms[0]; cl_context_properties contextproperties =new cl_context_properties(); contextproperties.addProperty(CL.CL_CONTEXT_PLATFORM, platform); int numDevicesArray[] = new int[1]; CL.clGetDeviceIDs(platform, CL.CL_DEVICE_TYPE_GPU, 0, null, numDevicesArray); int numDevices = numDevicesArray[0]; cl_device_id devices[] = new cl_device_id[numDevices]; CL.clGetDeviceIDs(platform, CL.CL_DEVICE_TYPE_GPU, numDevices, devices, null); System.out.println("numDevices"+numDevices); cl_device_id device = devices[0]; cl_context context =CL.clCreateContextFromType(contextproperties, CL.CL_DEVICE_TYPE_GPU, null, null, null); cl_command_queue command_queue=CL.clCreateCommandQueue(context, device, CL.CL_QUEUE_PROFILING_ENABLE, null); cl_mem memObject[]=new cl_mem[3]; if(args[0].equals("int")) buffersize=Sizeof.cl_int; if(args[0].equals("float")) buffersize=Sizeof.cl_float*n; memObject[0]=CL.clCreateBuffer(context, CL.CL_MEM_READ_ONLY| CL.CL_MEM_COPY_HOST_PTR, buffersize, srcA, null); memObject[1]=CL.clCreateBuffer(context, CL.CL_MEM_READ_ONLY| CL.CL_MEM_COPY_HOST_PTR, buffersize, srcB, null); memObject[2]=CL.clCreateBuffer(context, CL.CL_MEM_READ_WRITE, buffersize, null, null); cl_program program=CL.clCreateProgramWithSource(context, 1, new String[]{floatins}, null, null); CL.clBuildProgram(program, 0, null,null, null, null); cl_kernel kernel=CL.clCreateKernel(program, "sampleKernel", null); CL.clSetKernelArg(kernel, 0, Sizeof.cl_mem, Pointer.to(memObject[0])); CL.clSetKernelArg(kernel, 1, Sizeof.cl_mem, Pointer.to(memObject[1])); CL.clSetKernelArg(kernel, 2, Sizeof.cl_mem, Pointer.to(memObject[2])); long global_work_size[] = new long[]{n}; long local_work_size[] = new long[]{160}; System.out.println(Arrays.toString(local_work_size)); long startTime[] = new long[1]; long endTime[] = new long[1]; cl_event kEvent=new cl_event(); for(int i=0;i<1;i++){ for(int j=0;j<1;j++){ for(int k=0;k<5;k++){ CL.clEnqueueNDRangeKernel(command_queue, kernel, 1, null, global_work_size, null, 0, null, kEvent); CL.clWaitForEvents(1, new cl_event[]{kEvent}); System.out.println(kEvent.toString()); CL.clGetEventProfilingInfo(kEvent,CL.CL_PROFILING_COMMAND_START, Sizeof.cl_ulong, Pointer.to(startTime), null); CL.clGetEventProfilingInfo(kEvent,CL.CL_PROFILING_COMMAND_END, Sizeof.cl_ulong, Pointer.to(endTime), null); double dur=endTime[0]-startTime[0]; dur=dur/(double)1000000000; long speed=(long) (n/dur); // speed=speed; System.out.println("Time:"+dur+" "); System.out.println("Speed:"+speed+"Hz"); } } } cl_event mEvent=new cl_event(); CL.clEnqueueReadBuffer(command_queue, memObject[2], CL.CL_TRUE, 0, 1, dst, 0, null, mEvent); CL.clWaitForEvents(1, new cl_event[]{mEvent}); CL.clGetEventProfilingInfo(mEvent,CL.CL_PROFILING_COMMAND_START, Sizeof.cl_ulong, Pointer.to(startTime), null); CL.clGetEventProfilingInfo(mEvent,CL.CL_PROFILING_COMMAND_END, Sizeof.cl_ulong, Pointer.to(endTime), null); long dur=endTime[0]-startTime[0]; dur=dur/(long)1000000; long speed=(n/dur); System.out.println("MTime:"+dur+" ");System.out.println("MSpeed:"+speed+"MHz"); // System.out.println("Result: "+java.util.Arrays.toString(dstArray)); CL.clReleaseMemObject(memObject[0]); CL.clReleaseMemObject(memObject[1]); CL.clReleaseMemObject(memObject[2]); CL.clReleaseKernel(kernel); CL.clReleaseProgram(program); CL.clReleaseCommandQueue(command_queue); CL.clReleaseContext(context); }
950f922e-11d8-4a66-87ca-a07c3b46b9b4
4
public void getEnvironmentExits () { ResultSet rs = Main.mysql.getData("SELECT * FROM `environments_exits`"); try { while (true) { String[] tempString = new String[6]; tempString[0] = rs.getString(2); // Name tempString[1] = rs.getString(3); // Trigger tempString[2] = String.valueOf(rs.getInt(5)); // Links to tempString[3] = rs.getString(6); // State tempString[4] = rs.getString(7); // Creator tempString[5] = rs.getString(8); // Password environmentExits.put(rs.getInt(4) + ":" + rs.getInt(1), tempString); // Room ID rs.next(); } } catch (SQLException e) { if (!e.toString().contains("After end of result set")) { System.err.println("MySQL Error: " + e.toString()); } } catch (NullPointerException e) { System.err.println("MySQL Error: " + e.toString()); } finally { System.out.println("Found " + environmentExits.size() + " exit(s)"); } }
99473351-4b85-4c55-9ed4-b8676a3bd567
8
public final int partitionByBarCode(int left, int right) // see the name version of this method { Product pivotElement = products[left]; int max = logicalSize; int lb = left, ub = right; Product temp; while (left < right) { while((products[left].getBarCode() <= pivotElement.getBarCode()) && left +1 < max) { left++; } while((products[right].getBarCode() > pivotElement.getBarCode()) && right -1 >= 0) { right--; } if (left < right) { temp = products[left]; products[left] = products[right]; products[right] = temp; } } for(left = lb; left <= right && left +1 < max; left++) { products[left] = products[left +1]; } products[right] = pivotElement; return right; }
d89fe708-7982-415a-89a9-09deade9d794
3
private int ssMedian3 (final int Td, final int PA, int v1, int v2, int v3) { final int[] SA = this.SA; final byte[] T = this.T; int T_v1 = T[Td + SA[PA + SA[v1]]] & 0xff; int T_v2 = T[Td + SA[PA + SA[v2]]] & 0xff; int T_v3 = T[Td + SA[PA + SA[v3]]] & 0xff; if (T_v1 > T_v2) { final int temp = v1; v1 = v2; v2 = temp; final int T_vtemp = T_v1; T_v1 = T_v2; T_v2 = T_vtemp; } if (T_v2 > T_v3) { if (T_v1 > T_v3) { return v1; } return v3; } return v2; }
214bf01f-d60a-4878-bc27-6be3909c2ef6
0
@Test public void findDuplicateTypeHand_whenThreePairsExist_returnsHighestTwoPair() { Hand hand = findDuplicateTypeHand(twoKingsTwoQueensTwoJacksSix()); assertEquals(HandRank.TwoPair, hand.handRank); assertEquals(Rank.King, hand.ranks.get(0)); assertEquals(Rank.Queen, hand.ranks.get(1)); assertEquals(Rank.Jack, hand.ranks.get(2)); }
11af33d9-5033-46e6-879e-43a9b60a1c7d
6
public static void staticExportSets() { HashSet<ItemSet> setnames = new HashSet<>(); for (Shoes s : shoes) { setnames.add(s.getItemset()); } for (Pants s : pants) { setnames.add(s.getItemset()); } for (Gloves s : gloves) { setnames.add(s.getItemset()); } for (Armor s : armors) { setnames.add(s.getItemset()); } for (Helm s : helms) { setnames.add(s.getItemset()); } isets = setnames; try { File outd = new File("data" + File.separator); outd.mkdirs(); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("data" + File.separator + "_sets.xml"), "UTF-8")); JAXBContext context = JAXBContext.newInstance(ItemSets.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(new ItemSets(setnames), out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
70b6f87d-b2cd-445c-89f9-a0619316573d
2
public void replace(int depth, final Expr expr) { for (int i = stack.size() - 1; i >= 0; i--) { final Expr top = (Expr) stack.get(i); if (depth == 0) { stack.set(i, expr); return; } depth -= top.type().stackHeight(); } throw new IllegalArgumentException("Can't replace below stack bottom."); }
973a0f78-a266-44e5-a65b-ea783cb1d686
0
public SimpleStringProperty countryCodeProperty() { return countryCode; }
9ef7aeb4-2e23-4f0a-a3ea-23df72b941e1
5
@Override public boolean onMouseDown(int mX, int mY, int button) { if(button == 0 && mX > x && mX < x + width && mY > y && mY < y + height) { Application.get().getHumanView().popScreen(); return true; } return false; }
f7d7d3db-f784-4bfc-89f0-4e33b7c54e4e
7
@RequestMapping(value = "/ay", method = RequestMethod.POST, params = "refresh") public String salvestaAyl(@Valid @ModelAttribute("ayw") ayView ayw, // BindingResult // result, ModelMap model) { System.out.println("kas siia ays POST jouab"); String liik_ID = ayw.getCurrent().getLiik_id(); // to do - id järgi teha kindlaks, kes on selle liigi alluvad ja kellele // ta ise allub List<AdminYksLiik> liigid = ayw.getLiigid(); Long ylemusID = null; List<Long> alluvateIDd = new ArrayList<Long>(); Long ayl_ID = Long.parseLong(liik_ID, 10); // null on tühi if (ayl_ID > 0||ayl_ID!=null) { for (AdminYksLiik liik : liigid) { // võtame kõik liigid Long liigiID = liik.getId(); if (liigiID!=null) { List<AdminYksLiik> liigiAlluvad = (List<AdminYksLiik>) liik .getSubordinates(); for (AdminYksLiik alluv : liigiAlluvad) { if (ayl_ID == liigiID) { alluvateIDd.add(alluv.getId());// leitakse alluvate // ID-d } Long alluvaID = alluv.getId(); if (ayl_ID == alluvaID) { ylemusID = liik.getId(); // leitakse ülemusüksuse ID } } } } } //kysi välja kõik võimalikud ylemused ja pane view külge //kysi välja kõik võimalikud alluvad ja pane view külge model.addAttribute("ayw", ayw); return "ay"; }
99f76fb3-b213-484c-b7f4-6ad39555c4b8
3
public boolean isWarningStopCodon() { if (!Config.get().isTreatAllAsProteinCoding() && !isProteinCoding()) return false; // Not even one codon in this protein? Error String cds = cds(); if (cds.length() < 3) return true; String codon = cds.substring(cds.length() - 3); return !codonTable().isStop(codon); }
eb832f33-f2a8-4515-b3ad-58107f78d630
0
public void setId(Long id) { this.id = id; }
51da66ce-b384-48c4-bc0f-1de888e20cd1
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(ScheduleSelection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ScheduleSelection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ScheduleSelection.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ScheduleSelection.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 ScheduleSelection().setVisible(true); } }); }
5f7754ba-8aa6-4861-8201-3af00cb8fe27
9
public org.apache.xalan.templates.ElemVariable getElemVariable() { // Get the current ElemTemplateElement, and then walk backwards in // document order, searching // for an xsl:param element or xsl:variable element that matches our // qname. If we reach the top level, use the StylesheetRoot's composed // list of top level variables and parameters. org.apache.xalan.templates.ElemVariable vvar = null; org.apache.xpath.ExpressionNode owner = getExpressionOwner(); if (null != owner && owner instanceof org.apache.xalan.templates.ElemTemplateElement) { org.apache.xalan.templates.ElemTemplateElement prev = (org.apache.xalan.templates.ElemTemplateElement) owner; if (!(prev instanceof org.apache.xalan.templates.Stylesheet)) { while ( prev != null && !(prev.getParentNode() instanceof org.apache.xalan.templates.Stylesheet) ) { org.apache.xalan.templates.ElemTemplateElement savedprev = prev; while (null != (prev = prev.getPreviousSiblingElem())) { if(prev instanceof org.apache.xalan.templates.ElemVariable) { vvar = (org.apache.xalan.templates.ElemVariable) prev; if (vvar.getName().equals(m_qname)) { return vvar; } vvar = null; } } prev = savedprev.getParentElem(); } } if (prev != null) vvar = prev.getStylesheetRoot().getVariableOrParamComposed(m_qname); } return vvar; }
76edbedd-ab29-4bc4-becf-660aaeac21ad
7
public void checkConsistent() { StructuredBlock[] subs = getSubBlocks(); for (int i = 0; i < subs.length; i++) { if (subs[i].outer != this || subs[i].flowBlock != flowBlock) { throw new AssertError("Inconsistency"); } subs[i].checkConsistent(); } if (jump != null && jump.destination != null) { Jump jumps = (Jump) flowBlock.getJumps(jump.destination); for (; jumps != jump; jumps = jumps.next) { if (jumps == null) throw new AssertError("Inconsistency"); } } }
ebb13432-9b2d-41f1-9d81-d13671c5d007
5
static boolean multipliable(AlgebraicParticle a, AlgebraicParticle b){ return a.getClass().equals(b.getClass()) && a.almostEquals(b) //mixed number need to be converted to fractions first || Util.constant(a) && Util.constant(b) && !(a instanceof MixedNumber) && !(b instanceof MixedNumber); }
82ec9edf-fa83-43ab-a894-325fce35d8a3
9
private void paintBlock(Graphics2D g2d, ThreesBlock block){ int blockWidth = MAX_WIDTH/4; int blockHeight = MAX_HEIGHT/4; // Image redTwoImage = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("E:\\javaProject\\Threes\\src\\threes\\2.png")); // Image blueOneImage = new ImageIcon("E:\\javaProject\\Threes\\src\\threes\\1.jpg").getImage(); // Image blankBlockImage = new ImageIcon(".\\blank.png").getImage(); //draw backgroud if(block.getNumber()==0){ g2d.setColor(new Color(255,255,255)); }else if(block.getNumber()==1){ g2d.setColor(new Color(95,169,242)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-2, 20, 20); g2d.setColor(new Color(102,203,255)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-12, 20, 20); //g2d.drawImage(blueOneImage, 0, 0, 100, 150, null); }else if(block.getNumber()==2){ g2d.setColor(new Color(204,82,123)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-2, 20, 20); g2d.setColor(new Color(255,102,128)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-12, 20, 20); //g2d.drawImage(redTwoImage, 0, 0, null); }else{ g2d.setColor(new Color(255,204,102)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-2, 20, 20); g2d.setColor(new Color(254,255,255)); g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-12, 20, 20); } // if(block.getNumber()!=0){ // g2d.fillRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-2, 10, 10); // } //draw border // if(block.getNumber()!=0){ // g2d.setColor(new Color(0,0,0)); // g2d.drawRoundRect(block.getX(), block.getY(), blockWidth-2, blockHeight-2, 10, 10); // } //draw number if(block.getNumber()==0){ g2d.setColor(new Color(255,255,255)); }else if(block.getNumber()==1){ g2d.setColor(new Color(255,255,255)); }else if(block.getNumber()==2){ g2d.setColor(new Color(255,255,255)); }else{ g2d.setColor(new Color(0,0,0)); } Font font = new Font("Comic Sans MS",Font.BOLD,36); if(block.getNumber()!=0){ g2d.setFont(font); String num = ""+block.getNumber(); int numWidth = g2d.getFontMetrics().stringWidth(num); g2d.drawString(num, block.getX()+blockWidth/2-numWidth/2, block.getY()+blockHeight/2+5); // 居中对齐文本绘制公式 } //game over, draw scores if(status.isGameOver()){ int score = block.computeScore(); if(score > 0){ g2d.setColor(new Color(255,102,128)); font = new Font("Comic Sans MS",Font.BOLD,15); g2d.setFont(font); String blockScore = "+"+score; int scoreWidth = g2d.getFontMetrics().stringWidth(blockScore); g2d.drawString(blockScore, block.getX()+blockWidth/2-scoreWidth/2, block.getY()+blockHeight/2+25); } } }
45c0fa09-bec7-48a1-ba05-95014b8d34d7
1
public static String toString(long[] message) { StringBuilder out = new StringBuilder(); for (int i = 0; i < message.length; i++) { out.append(message[i]); out.append(' '); } return out.toString(); }
e9d63394-8863-48c0-a3ca-bc376f26090b
4
protected float transmitChance(Actor has, Actor near) { // // if (! near.health.organic()) return 0 ; if (has.species() != near.species()) return 0 ; if (near.traits.traitLevel(this) != 0) return 0 ; if (near.traits.test(VIGOUR, virulence / 2, 0.1f)) return 0 ; // // TODO: THERE HAS GOT TO BE A MORE ELEGANT WAY TO EXPRESS THIS float chance = 0.1f ; /* // // Increase the risk substantially if you're fighting or humping the // subject- float chance = 0.1f ; if (has.isDoing(Combat.class, near)) chance *= 2 ; final Performance PR = new Performance( has, has.aboard(), Recreation.TYPE_EROTICS, near ) ; if (has.isDoing(PR)) chance *= 2 ; //*/ return chance ; }
a91c7bf5-3387-4bb1-b3a3-bf318f82ec5a
0
private void Order(ArrayList<Company> companies) { Collections.sort(Companies, new Comparator<Company>() { @Override public int compare(Company p1, Company p2) { return new String(p1.getName()).compareTo(p2.getName()); } }); }
0f6aab10-5fe8-4dc7-a89b-3fe937676765
4
public int _setValue(int key,String valueName, String value) throws RegistryErrorException { try { Integer ret = (Integer)setValue.invoke(null, new Object[] {new Integer(key), getString(valueName), getString(value)}); if(ret != null) return ret.intValue(); else return -1; } catch (InvocationTargetException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalArgumentException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalAccessException ex) { throw new RegistryErrorException(ex.getMessage()); } }
34c8e5eb-fa4c-47d5-8613-d20c7c0a05f4
1
public void removeAllOutgoingTransitions() { for(Transition t:outgoingTransitions) { t.getToState().removeIncomingTransition(t); } outgoingTransitions = new ArrayList<Transition>(); }
90b002bf-51d4-4850-a893-341a06042ffa
9
public Set<Element> calcFermeture() { List<Item> generators = new ArrayList<Item>();//Liste des générateurs List<Double> support = new ArrayList<Double>();//Liste des supports List<Set<Item>> fermeture = new ArrayList<Set<Item>>();//Liste des fermetures Set<Element> retTable = new HashSet<Element>(); //Table à retourner (FF1) //Calcule les générateurs for (int k:inputData.keySet()) { for (Item l : inputData.get(k)) { if (!generators.contains(l)) { generators.add(l); fermeture.add(new HashSet<Item>()); support.add(0.0); } } } System.out.println("generators FF1:"+generators); for (int k : inputData.keySet()) { for (Item l : inputData.get(k)) { support.set(generators.indexOf(l), support.get(generators.indexOf(l)) + 1); if (fermeture.get(generators.indexOf(l)).isEmpty()) { fermeture.get(generators.indexOf(l)).addAll(inputData.get(k)); } else { fermeture.get(generators.indexOf(l)).retainAll(inputData.get(k)); } } } System.out.println("fermeture FF1 :"+fermeture); for (Item i : generators) { Set<Item> set = new HashSet<Item>(); set.add(i); Element e = new Element(set); e.setClosure(fermeture.get(generators.indexOf(i))); e.setSupport(support.get(generators.indexOf(i))/(inputData.size())); if (e.getSupport() >= minSupport) { retTable.add(e); } } System.out.println("ret FF1:"+retTable); itemsSet = new ArrayList<Element>(); for (Element i : retTable) { itemsSet.add(i); } return retTable; }