method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
4805434a-acdb-4b53-9ce2-a59a10325c23
0
@Override protected void fireEditingStopped() { super.fireEditingStopped(); }
4e2c6b2e-5bfb-4ac6-9891-a233b0afe2d0
0
public int getMinRANGE() { return inventory.getItem(0).getMinRANGE(); }
8ce94ca4-4543-4fc1-b127-324619e92af7
1
@EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoin(PlayerJoinEvent e) { if (e.getPlayer().hasPermission("playtime.updatenotice")) { e.getPlayer().sendMessage(this.message); } }
5c47ab1d-9483-48d9-ae75-71462f98dfad
1
public List<String[]> getAttributes() { List <String[]> l = new ArrayList<String[]>(); String[] s = new String[2]; s = new String[2]; s[0] = "CAT2OSMSHAPEID"; s[1] = getShapeId(); l.add(s); if (ttggss != null){ l.addAll(ttggssParser(ttggss)); } return l; }
6cf650d8-ce4c-445c-a0f7-df9a19f3e16b
6
private boolean promptForNew(boolean brandNew) { // SO NOW ASK THE USER FOR A LEVEL NAME String levelName = JOptionPane.showInputDialog( view, LEVEL_NAME_REQUEST_TEXT, LEVEL_NAME_REQUEST_TITLE_TEXT, JOptionPane.QUESTION_MESSAGE); // IF THE USER CANCELLED, THEN WE'LL GET A fileName // OF NULL, SO LET'S MAKE SURE THE USER REALLY // WANTS TO DO THIS ACTION BEFORE MOVING ON if ((levelName != null) && (levelName.length() > 0)) { // WE ARE STILL IN DANGER OF AN ERROR DURING THE WRITING // OF THE INITIAL FILE, SO WE'LL NOT FINALIZE ANYTHING // UNTIL WE KNOW WE CAN WRITE TO THE FILE String fileNameToTry = levelName + LEVEL_FILE_EXTENSION; File fileToTry = new File(LEVELS_PATH + fileNameToTry); if (fileToTry.isDirectory()) { return false; } int selection = JOptionPane.OK_OPTION; if (fileToTry.exists()) { selection = JOptionPane.showConfirmDialog(view, OVERWRITE_FILE_REQUEST_TEXT_A + fileNameToTry + OVERWRITE_FILE_REQUEST_TEXT_B, OVERWRITE_FILE_REQUEST_TITLE_TEXT, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); } if (selection == JOptionPane.OK_OPTION) { // MAKE OUR NEW LEVEL if (brandNew) { model.startNewLevel(levelName); } // NOW SAVE OUR NEW LEVEL save(fileToTry); // NO ERROR, SO WE'RE HAPPY saved = true; // UPDATE THE FILE NAMES AND FILE currentFileName = fileNameToTry; currentFile = fileToTry; // SELECT THE ROOT NODE, WHICH SHOULD FORCE A // TRANSITION INTO THE REGION VIEWING STATE // AND PUT THE FILE NAME IN THE TITLE BAR view.setTitle(APP_NAME + APP_NAME_FILE_NAME_SEPARATOR + currentFileName); // WE DID IT! return true; } } // USER DECIDED AGAINST IT return false; }
1200226d-5ca3-4a62-ba5c-7f4c69ec956a
0
public AttributesButtonCellEditor(AbstractAttributesPanel panel) { super(new JCheckBox()); this.panel = panel; }
cd7b7d98-3fc9-4641-a1a6-c0a14a212788
8
public void selectChoice() { boolean cease; String _open = "Open new account"; String _log = "Log into existing account"; String _help = "Help"; String _quit = "Quit"; do { cease = false; do { try { prompt(_open, _log, _help, _quit); cease = true; } catch (InputMismatchException exception) { System.out.println("Error: Please enter a numeric value, thank you."); } } while (!cease); } while (select > 4 || select < 1); switch (select) { case 1: System.out.println(_open); break; case 2: System.out.println(_log); break; case 3: System.out.println(_help); break; case 4: System.out.println(_quit); break; } }
2053ae45-16c3-4b01-9c57-bed29fd8d916
9
public static String normalize(final String s) { if (s == null) { return ""; } final StringBuffer str = new StringBuffer(); final int len = s.length(); for (int i = 0; i < len; i++) { final char ch = s.charAt(i); switch (ch) { case '<': { str.append("&lt;"); break; } case '>': { str.append("&gt;"); break; } case '&': { str.append("&amp;"); break; } case '"': { str.append("&quot;"); break; } case '\n': { if (i > 0) { final char lastChar = str.charAt(str.length() - 1); if (lastChar != '\r') { str.append(getLineSeparator()); } else { str.append('\n'); } } else { str.append(getLineSeparator()); } break; } default : { str.append(ch); } } } return (str.toString()); }
e78882df-9ab3-4a95-a2d3-30f7b4ab109a
4
public void cliqueFinTour() { /* en mode conquete, confirmé, et possède au moins un territoire (sinon il ne peut pas redéployer...) */ if( joueurEnCours.getPeuple().getTerritoiresOccupes().isEmpty() ){ new WinWarn("Veuillez tout d'abord prendre au moins un territoire"); }else if((etape == 0 || etape == 1) && Game.getInstance().askConf("Confirmer la fin du tour ?") ) { redeploiement(); } }
a4305e6a-4198-4a80-9117-13b622069eb5
1
private boolean jj_2_74(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_74(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(73, xla); } }
a0e3333a-6224-44b6-b0e9-b9707adf3359
2
public void execute( Stack stack ) { for (int i = actions.length-1; i >= 0; i--){ if( Compiler.extendedDebug ){ //System.out.println(actions[i]); } actions[i].execute( stack ); } }
9826914f-adb6-4902-80e4-06bbca4bca47
8
public static HDRExposure scaleTo( HDRExposure exp, int width, int height ) { if( !aspectRatioPreserved(exp.width, exp.height, width, height) ) { throw new UnsupportedOperationException("Cannot change aspect ratio"); } double scale = width / exp.width; if( scale == 0 ) { return new HDRExposure(0, 0); } else if( scale < 1 ) { double ratio = exp.width / width; if( (int)ratio != ratio ) { throw new UnsupportedOperationException("Cannot scale down by non-integer ratio "+scale); } return scaleDown( exp, (int)ratio ); } else { int iScale = (int)scale; if( iScale != scale ) { throw new UnsupportedOperationException("Cannot scale by non-integer "+scale); } while( iScale > 0 && (iScale & 1) == 0) { exp = scaleUp(exp); iScale >>= 1; } if( iScale != 1 ) { throw new UnsupportedOperationException("Cannot scale by non-power-of-2 "+scale); } return exp; } }
919f2423-d41b-41e1-ba1f-147f7d679e28
3
private void CommandNewSource( boolean priority, boolean toStream, boolean toLoop, String sourcename, FilenameURL filenameURL, float x, float y, float z, int attModel, float distORroll ) { if( soundLibrary != null ) { if( filenameURL.getFilename().matches( SoundSystemConfig.EXTENSION_MIDI ) && !SoundSystemConfig.midiCodec() ) { soundLibrary.loadMidi( toLoop, sourcename, filenameURL ); } else { soundLibrary.newSource( priority, toStream, toLoop, sourcename, filenameURL, x, y, z, attModel, distORroll ); } } else errorMessage( "Variable 'soundLibrary' null in method 'CommandNewSource'", 0 ); }
167ff953-e8ba-4407-823e-0cd18ee8a117
7
public static File getWorkPath(String workDir){ String userHome = System.getProperty("user.home", "."); File workingDirectory; switch (getPlatform().ordinal()) { case 0: case 1: workingDirectory = new File(userHome, '.' + workDir + '/'); break; case 2: String applicationData = System.getenv("APPDATA"); if (applicationData != null) workingDirectory = new File(applicationData, "." + workDir + '/'); else workingDirectory = new File(userHome, '.' + workDir + '/'); break; case 3: workingDirectory = new File(userHome, "Library/Application Support/" + workDir); break; default: workingDirectory = new File(userHome, workDir + '/'); } if ((!workingDirectory.exists()) && (!workingDirectory.mkdirs())) throw new RuntimeException("The working directory could not be created: " + workingDirectory); return workingDirectory; }
d47fb407-050d-46c9-bd93-6f638485db73
6
public void tabSpecificProcess(String s) { if(s.startsWith("/nick")) { if(action == -1) { addMessage("Changing default nick to " + s.substring(6) + "."); Main.saveDefaultNickname(Main.user); } else { getServer().changeNick(s.substring(6)); addMessage("Nick changed to " + s.substring(6)); } } if(action == -1) { // Console specific code goes here. } else if(action == 0) { // Server specific code goes here. } else if(action == 1) { // Channel specific code goes here. } else if(action == 2) { // Private message specific code goes here. } else { Main.debug("Unknown processing " + s); } }
f3f1bd40-6ecd-43b7-a5d0-9f5c97699f9a
1
Object[] getAttribute(String elName, String name) { Hashtable attlist; Object attribute[]; attlist = getElementAttributes(elName); if (attlist == null) { return null; } attribute = (Object[]) attlist.get(name); return attribute; }
f71175a4-b988-4195-8c77-834b5b43e653
9
@Override public void run() { char read; try { while ((read = (char) inputStream.read()) != -1) { if (read == '\n' || read == '\r') { command = inputBuffer.toString(); printOutputStream.print("\r\nServer: " + command + "\r\n"); inputBuffer = new StringBuffer(); } else if (read == '\u007f') { printOutputStream.print("\b \b"); if (inputBuffer.length() >= 1) { inputBuffer.deleteCharAt(inputBuffer.length() - 1); } } else if (read == '\u0003') { return; } else { inputBuffer.append(read); printOutputStream.print(read); } printOutputStream.flush(); if ("quit".equals(command) || "exit".equals(command)) { return; } } } catch (IOException e) { e.printStackTrace(); } finally { exitCallback.onExit(0); } }
40f5bac0-83d6-4e2a-a54b-091bfa2d7a5b
0
public void setPhoneNumber(int phoneNumber) { this.phoneNumber = phoneNumber; }
adbaa08a-0a4b-486a-8cb2-fa3b0d8a0ef3
9
private void jComboBoxServerContractsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxServerContractsActionPerformed System.out.println("In Action for Server Combo main tab"); /*String nymID = Utility.getKey(nymMap, (String) jComboBox1.getSelectedItem()); String assetID = Utility.getKey(assetMap, (String) jComboBox3.getSelectedItem()); String serverID = Utility.getKey(serverMap, (String) jComboBox2.getSelectedItem());*/ String nymID = "ALL"; String assetID = "ALL"; String serverID = "ALL"; if (nymMap != null && nymMap.size() > 0 && jComboBox_Nyms.getSelectedIndex() > 0) { nymID = ((String[]) nymMap.get((Integer) jComboBox_Nyms.getSelectedIndex() - 1))[1]; } if (assetMap != null && assetMap.size() > 0 && jComboBox_AssetContracts.getSelectedIndex() > 0) { assetID = ((String[]) assetMap.get((Integer) jComboBox_AssetContracts.getSelectedIndex() - 1))[1]; } if (serverMap != null && serverMap.size() > 0 && jComboBoxServerContracts.getSelectedIndex() > 0) { serverID = ((String[]) serverMap.get((Integer) jComboBoxServerContracts.getSelectedIndex() - 1))[1]; } System.out.print("serverID----------------------------:" + serverID); loadAccount(assetID, serverID, nymID); clearDetailPage(); }
31ce7886-4d32-4129-8d9c-3b036d8f45e9
2
public static VisitBathroom getSingleton(){ // needed because once there is singleton available no need to acquire // monitor again & again as it is costly if(singleton==null) { synchronized(VisitBathroom.class){ // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton = new VisitBathroom(); } } return singleton; }
4c29db97-f199-4f5f-8852-d3513f881796
4
private SQLite() { this.prefix = "storm__"; this.dbg = true; String dbPath = "jdbc:sqlite::memory:"; try { Class.forName("org.sqlite.JDBC"); this.con = DriverManager.getConnection(dbPath); } catch (SQLException e) { if (this.dbg) { e.printStackTrace(); } } catch (ClassNotFoundException e) { if (this.dbg) { e.printStackTrace(); } } }
62318d8c-fcee-4c5e-a50e-ede880272854
7
private boolean testSign(Player player, Block block) { Sign sign = null; if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) sign = (Sign) block.getState(); if (sign != null) if (sign.getLine(0).equals( "" + ChatColor.GRAY + ChatColor.BOLD + "[" + ChatColor.YELLOW + "ATM" + ChatColor.GRAY + "]")) { if (tgym.Vault.HasPermissions(player, "tgym.atm.use")) { final double result = tgym.Bank.CashOut(player.getName()); final Object val = tgym.Settings._( "Group." + tgym.Vault.GetGroup(tgym.getServer().getPlayer( player.getName())) + ".MoneyPerMinute", (double) -1); double mps = -1; if (val instanceof Integer) mps = ((Integer) val).doubleValue(); else mps = (Double) val; if (mps == -1) mps = 1; player.sendMessage(ChatColor.YELLOW + "[TimeGivesYouMoney] " + ChatColor.GOLD + tgym.Lang ._("Command.Cashout.Success.Self") .replaceAll("%MONEY%", result + tgym.Vault.GetEconomy().currencyNamePlural()) .replaceAll("%TIME%", (result / mps) + "")); } return true; } return false; }
b76fe174-4a80-47ec-b7f7-c0b4710c3cec
4
public double computeSimilarity(int user1, int user2) { double sim = 0; // generate arrays containing ratings from users which rated both movies List<Integer> sharedMovies = findSharedMovies(user1, user2); if (sharedMovies.isEmpty()) { return sim; } Double[] userOneRatings = new Double[sharedMovies.size()]; Double[] userTwoRatings = new Double[sharedMovies.size()]; for (int i = 0; i < sharedMovies.size(); i++) { userOneRatings[i] = userMovieRatings.get(user1).get(sharedMovies.get(i)); userTwoRatings[i] = userMovieRatings.get(user2).get(sharedMovies.get(i)); } // Calculate the similarity using the defined metric if (sMetric.toLowerCase().equals("cosinesimilarity")) { sim = Similarity.calculateCosineSimilarity(userOneRatings, userTwoRatings); } else if (sMetric.toLowerCase().equals("pearsoncorrelation")) { sim = Similarity.calculatePearsonCorrelation(userOneRatings, userTwoRatings, averageRatings.get(user1), averageRatings.get(user2)); } return sim; }
ecd5cb46-a1da-44c5-9275-d2c94d569dec
8
@SuppressWarnings("deprecation") public static void main(String[] args) { HashMap<String, ArrayList<Integer>> finalMap = new HashMap<String, ArrayList<Integer>>(); HashMap<String, HashMap<Integer,Integer>> dayCountForStnMap = new HashMap<String, HashMap<Integer,Integer>>(); HashMap<Integer, String> stationIdNameMap = new HashMap<Integer, String>(); HashMap<Integer, String> stationCommMap = new HashMap<Integer, String>(); try { Integer lineCount = 0; CsvReader trips = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\trips_updated.csv"); //CsvReader trips = new CsvReader("C:\\Users\\ThejaSwarup\\Desktop\\Test.csv"); CsvReader stations = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\stations_final.csv"); stations.readHeaders(); //Map: stationName, dayList while (stations.readRecord()){ ++lineCount; stationIdNameMap.put(new Integer(stations.get("id")), stations.get("stationName")); stationCommMap.put(new Integer(stations.get("id")), stations.get("CommunityArea")); finalMap.put(stations.get("id"), new ArrayList<Integer>()); dayCountForStnMap.put(stations.get("id"), new HashMap<Integer,Integer>()); } stations.close(); //read headers from input file trips.readHeaders(); while (trips.readRecord()) { ArrayList<Integer> valList = new ArrayList<Integer>(); String startTime = trips.get("starttime"); String fromStnId = trips.get("from_station_id"); Date dt1 = new Date(); try { //System.out.println(++lineNum); //++lineNum; dt1 = getDateFromString(startTime,"MM/dd/yyyy HH:mm"); valList = finalMap.get(fromStnId); valList.add(new Integer(dt1.getDay())); finalMap.put(fromStnId, valList); } catch (Exception e) { e.printStackTrace(); } } trips.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Now from your final map count no.of occurrences of days for each station Iterator<Map.Entry<String, ArrayList<Integer>>> iterator = finalMap.entrySet().iterator(); while(iterator.hasNext()){ HashMap<Integer, Integer> mainMapValue = new HashMap<Integer, Integer>(); int days[] = new int[]{0,0,0,0,0,0,0}; Map.Entry<String, ArrayList<Integer>> entry = iterator.next(); ArrayList<Integer> valueList = entry.getValue(); if(valueList.size() > 0){ for(Integer ind = 0; ind < 7 ; ind++){ days[ind] = getOccurencesOfDays(valueList,ind); mainMapValue = dayCountForStnMap.get(entry.getKey()); mainMapValue.put(new Integer(ind),new Integer(days[ind])); } } dayCountForStnMap.put(entry.getKey(), mainMapValue); iterator.remove(); } //create JSON Object System.out.println(dayCountForStnMap); createJSON(dayCountForStnMap,stationIdNameMap,stationCommMap); System.out.println("Program Executed"); }
d9fa9c8d-ec96-4174-a047-722d4657f5eb
6
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
8a4686f4-327a-4938-95d4-05ae17b81c60
8
public static void main(String[] args) throws Exception { if(args.length < 2) { System.out.print("Usage : scdecoder -f <file> \n" + " : scdecoder -s <string1> [string2] ...\n"); return ; } String argument; if(args[0].equals("-f")) { argument = args[1]; File file = new File(argument); if(!file.exists()) { System.out.println("File \""+ file +"\" does not exsits !"); } else { List<String> brands = FileUtils.readLines(file); int i=1; for(String brand : brands) { try { System.out.println("[" + i + "]PASSED:"+decode(brand.trim())); } catch (Exception e) { System.out.println("[" + i + "]FAILED:"+(brand.trim())); } i++; } } } else if(args[0].equals("-s")){ for(int i=1; i<args.length; i++) { argument = args[i]; try { System.out.println("[" + i + "]PASSED:"+decode(argument.trim())); } catch (Exception e) { System.out.println("[" + i + "]FAILED:"+(argument.trim())); } } } }
879eccc9-055f-48b9-b92c-1e3e638cdde5
7
@Override public void run() { Envelope e = null; try { /* * Loop to check for incoming messages. */ while((e=(Envelope)in.readObject()) != null) { //Special server message that adds to the user list. if(e.sender().equals("Server") && e.message().equals("Join.")) { usersModel.removeAllElements(); for(String s : e.recipiants()) usersModel.addElement(s); } //Special server message that removes from the user list. if(e.message().equals("Leave.")) { System.out.println(e.sender() + "left."); usersModel.removeElement(e.sender()); } //Print out the message. chat.setText(chat.getText() + e.sender() + ": "+ e.message() +"\n"); } } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } }
bcfcac05-d2b6-430d-b2a1-fd0bb8d7eb6d
9
protected void processKeyEvent (java.awt.event.KeyEvent e) { // TODO: Convert into Actions and put into InputMap/ActionMap? if (e.getID()==KeyEvent.KEY_PRESSED) { switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: boolean extend = e.isShiftDown(); int offs = Math.max(leadSelectionIndex-1, 0); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_RIGHT: extend = e.isShiftDown(); offs = Math.min(leadSelectionIndex+1, model.getByteCount()-1); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_UP: extend = e.isShiftDown(); offs = Math.max(leadSelectionIndex-16, 0); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_DOWN: extend = e.isShiftDown(); offs = Math.min(leadSelectionIndex+16, model.getByteCount()-1); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_PAGE_DOWN: extend = e.isShiftDown(); int visibleRowCount = getVisibleRect().height/getRowHeight(); offs = Math.min(leadSelectionIndex+visibleRowCount*16, model.getByteCount()-1); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_PAGE_UP: extend = e.isShiftDown(); visibleRowCount = getVisibleRect().height/getRowHeight(); offs = Math.max(leadSelectionIndex-visibleRowCount*16, 0); changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_HOME: extend = e.isShiftDown(); offs = (leadSelectionIndex/16)*16; changeSelectionByOffset(offs, extend); e.consume(); break; case KeyEvent.VK_END: extend = e.isShiftDown(); offs = (leadSelectionIndex/16)*16 + 15; offs = Math.min(offs, model.getByteCount()-1); changeSelectionByOffset(offs, extend); e.consume(); break; } } super.processKeyEvent(e); }
fbea9aff-81a8-4b01-99f3-9d3e2fe5338a
3
public void closeChannels() { try { if (socketChannel != null) { socketChannel.close(); } if (serverChannel != null) { serverChannel.close(); } } catch (IOException e) { stdOut.printError(TAG + " Error while closing socket"); } }
72cf5064-aa1b-4342-82c9-b1b8dfa73bb8
4
private static byte[] decryptBloc(byte[] input){ byte[] tmp = new byte[input.length]; int t,u; int aux; int[] data = new int[input.length/4]; for(int i =0;i<data.length;i++) data[i] = 0; int off = 0; for(int i=0;i<data.length;i++){ data[i] = ((input[off++]&0xff))| ((input[off++]&0xff) << 8) | ((input[off++]&0xff) << 16) | ((input[off++]&0xff) << 24); } int A = data[0],B = data[1],C = data[2],D = data[3]; C = C - S[2*r+3]; A = A - S[2*r+2]; for(int i = r;i>=1;i--){ aux = D; D = C; C = B; B = A; A = aux; u = rotl(D*(2*D+1),5); t = rotl(B*(2*B + 1),5); C = rotr(C-S[2*i + 1],t) ^ u; A = rotr(A-S[2*i],u) ^ t; } D = D - S[1]; B = B - S[0]; data[0] = A;data[1] = B;data[2] = C;data[3] = D; for(int i = 0;i<tmp.length;i++){ tmp[i] = (byte)((data[i/4] >>> (i%4)*8) & 0xff); } return tmp; }
40ccc09b-df7c-48cb-875d-a8c9e17af0e4
9
public static String parseAndExecute(String statement, Map<String, String> parameters, DB db) { String result = null; List<String> sqlParams = new ArrayList<String>(); StringBuffer sb = new StringBuffer(); int prevIdx = 0; int idx = -1; while(((idx=statement.indexOf("{", idx+1)))>=0) { log.finest(sb.toString() + " " + idx + " " + prevIdx + " " + statement); sb.append(statement.substring(prevIdx, idx)); String paramName = statement.substring(idx+1, statement.indexOf("}", idx)); log.finest("Adding: " + paramName + " as " + parameters.get(paramName)); if (parameters.containsKey(paramName)) { sqlParams.add(parameters.get(paramName)); } else { sqlParams.add(""); // we'll assume zero length string is a null - sql needs to accomodate this } sb.append("?"); // replace {NAME} with ? prevIdx = statement.indexOf("}", idx)+1; } sb.append( statement.substring(prevIdx) ); if (statement.toLowerCase().startsWith("select ")) { int pageSize = 20; int page = 0; try { if (parameters.containsKey("PAGE")) { page = Integer.parseInt(parameters.get("PAGE")); } if (parameters.containsKey("PAGE_SIZE")) { pageSize = Integer.parseInt(parameters.get("PAGE_SIZE")); } } catch (NumberFormatException nfe) { pageSize = 20; page = 0; } // avoid daft values if (page<0) page=0; if (pageSize<0) pageSize=0; if (pageSize>32768) pageSize=32768; // big but should be sufficient... result = db.query(sb.toString(), sqlParams, page, pageSize); } else { result = db.execute(sb.toString(), sqlParams); } // System.out.println(result); return result; }
47f5cbf5-8f29-4f56-b253-ad6999c222f1
0
public void makeSallary() { method1(); method2(); method3(); }
2066ac4e-d0a2-45b5-aadd-9ef68b21ac44
7
private void powrotDoOknaGlownego() { widokUstawien.setVisible(false); if(oknoMacierzyste.equals("OknoGlowne")) widokUstawien.widokGlowny.setVisible(true); if(oknoMacierzyste.equals("OknoDolacz")) widokUstawien.widokGlowny.widokDolacz.setVisible(true); if(oknoMacierzyste.equals("OknoUtworz")) widokUstawien.widokGlowny.widokUtworz.setVisible(true); if(oknoMacierzyste.equals("OknoOpisAplikacji")) widokUstawien.widokGlowny.widokOpisAplikacji.setVisible(true); if(oknoMacierzyste.equals("OknoRozmiesc")) widokUstawien.widokGlowny.widokDolacz.widokRozmiesc.setVisible(true); if(oknoMacierzyste.equals("OknoGry")) widokUstawien.widokGlowny.widokDolacz.widokRozmiesc.widokGry.setVisible(true); if(oknoMacierzyste.equals("OknoWynikow")) widokUstawien.widokGlowny.widokDolacz.widokRozmiesc.widokGry.widokGryZdarzenia.widokWynikow.setVisible(true); }
98442600-a00a-4bab-9499-45bd2e02b727
7
public void run() { println ("This program find the largest and smallest numbers."); int n = readInt ("? "); if ( n == SENTINEL) { println ("The program is terminated by your input of the setinel number. "); } /* variable amountInput is for counting the amount of numbers we've input. * variable largestNum and smallestNum is for the recording of the largest and the smallest number respectively.*/ int amountInput = 0; int largestNum = n; int smallestNum = n; while (n != SENTINEL) { n = readInt ("? "); amountInput ++; if (n > largestNum){ largestNum = n; } if (n < smallestNum){ smallestNum = n; } } /* reports the result of the largest and the smallest numbers. */ if (amountInput != 0){ if (amountInput != 1){ println ("smallest: " + smallestNum); println ("largest: " + largestNum); /* the following part deals with the situation when only one value is input before * the user input the sentinel value. That value is reported as both the largest and * the smallest value. */ }else { if ( largestNum-n == 0 ){ println ("smallest: " + smallestNum); println ("largest: " + smallestNum); }else { println ("smallest: " + largestNum); println ("largest: " + largestNum); } } } }
3d3cfa57-222c-4f5c-a426-74ef25cb74f5
0
public static byte[] decrypt(byte[] data, String key, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException { Key k = toKey(SecurityCoder.base64Decoder(key), algorithm); Cipher cipher = Cipher.getInstance(DES); cipher.init(Cipher.DECRYPT_MODE, k); return cipher.doFinal(data); }
075b03a7-e93f-4851-bef6-21c52a61fdb6
4
private static BigInteger findPrime(BigInteger number) { boolean prime = false; Random r = new Random(); while (!prime) { prime = true; for (int j = 0; j < 100; j++) { BigInteger a = BigInteger.valueOf(number.compareTo(BigInteger .valueOf(Integer.MAX_VALUE)) == -1 ? (int) number .intValue() - 1 : r.nextInt(Integer.MAX_VALUE)); BigInteger res = a.modPow(number, number); if(!a.equals(res)) { prime = false; number = number.add(BigInteger.ONE); break; } } } return number; }
9a2e8d2f-c734-492b-9b4a-de4356ac5702
6
public final DccChat dccSendChatRequest(String nick, int timeout) { DccChat chat = null; try { ServerSocket ss = null; int[] ports = getDccPorts(); if (ports == null) { // Use any free port. ss = new ServerSocket(0); } else { for (int i = 0; i < ports.length; i++) { try { ss = new ServerSocket(ports[i]); // Found a port number we could use. break; } catch (Exception e) { // Do nothing; go round and try another port. } } if (ss == null) { // No ports could be used. throw new IOException("All ports returned by getDccPorts() are in use."); } } ss.setSoTimeout(timeout); int port = ss.getLocalPort(); InetAddress inetAddress = getDccInetAddress(); if (inetAddress == null) { inetAddress = getInetAddress(); } byte[] ip = inetAddress.getAddress(); long ipNum = ipToLong(ip); sendCTCPCommand(nick, "DCC CHAT chat " + ipNum + " " + port); // The client may now connect to us to chat. Socket socket = ss.accept(); // Close the server socket now that we've finished with it. ss.close(); chat = new DccChat(this, nick, socket); } catch (Exception e) { // Do nothing. } return chat; }
44780b5f-5882-4235-9d95-b478a7baf67d
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(SignupIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SignupIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SignupIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SignupIssuer.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 SignupIssuer().setVisible(true); } }); }
f75b962e-081e-4e27-9674-7800f1d8c8f9
8
public static ArchiveDataKindCombination getADKCombination(boolean oa, boolean on, boolean na, boolean nn) { List<ArchiveDataKind> dataKinds = new ArrayList<ArchiveDataKind>(); if(oa) dataKinds.add(ArchiveDataKind.ONLINE); if(on) dataKinds.add(ArchiveDataKind.ONLINE_DELAYED); if(na) dataKinds.add(ArchiveDataKind.REQUESTED); if(nn) dataKinds.add(ArchiveDataKind.REQUESTED_DELAYED); switch(dataKinds.size()) { case 1: return new ArchiveDataKindCombination(dataKinds.get(0)); case 2: return new ArchiveDataKindCombination(dataKinds.get(0), dataKinds.get(1)); case 3: return new ArchiveDataKindCombination(dataKinds.get(0), dataKinds.get(1), dataKinds.get(2)); case 4: return new ArchiveDataKindCombination(dataKinds.get(0), dataKinds.get(1), dataKinds.get(2), dataKinds.get(3)); default: return null; // Falls keine Datensatzart gewaehlt worden ist } }
8528361d-45af-48f1-b66a-c13cd5824e0f
4
private void paivitaTetriminonTippuminen() { if(pelitilanne.onTauolla() || pelitilanne.peliOnPaattynyt()) return; int vauhti = pelitilanne.arvo(Pelitilanne.Tunniste.VAIKEUSTASO) * 50; if(vauhti >= 500) vauhti = 450; if(pelitilanne.tiputusAjastin().onKulunut(500 - vauhti )) tiputaTetriminoa(); }
67de65fe-8092-4537-9c6d-1a7a32c75df7
7
public void run() { try { s = new ServerSocket(GAME_PORT); incoming = s.accept(); inStream = incoming.getInputStream(); outStream = incoming.getOutputStream(); in = new BufferedReader(new InputStreamReader(inStream)); out = new PrintWriter(outStream,true); sendInitialValues(); while(true) { //if user has made a move if(game.isSendMove()) sendMove(); //if wants to send chat message if(game.isSendMsg()) sendMessage(); //read input if(in.ready()) { line = in.readLine(); //if input is a move if( !line.equals("") && line.charAt(0) == '#') { updateBoard(); } //if input is a chat message else { gameFrame.updateChatArea("\n" + opponentNickname + " says: " + line); } } } } catch (IOException ex) { Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Server runtime error reading input or output."); } }
16f221da-df77-4424-abfd-fc7ad026a507
3
public int getSpawnpointNumber(){ int spawnpoints = 0; Tile currentJTile = topTile; for(int j = 0; j < dimension; j++){ Tile currentKTile = currentJTile; for(int k = 0; k < dimension; k++){ if(currentKTile.tileType == TileType.SPAWN){ spawnpoints++; } currentKTile = currentKTile.rightDown; } currentJTile = currentJTile.leftDown; } return spawnpoints; }
e307b9e0-de8b-469a-93f3-f0109ad2e60d
2
public void inOrder() { // 1 Linker Knoten, 2 Konten selber , 3 Rechter Knoten if (left != null) { left.inOrder(); } print(); if (right != null) { right.inOrder(); } }
beb46d0a-24db-4f8b-b6e9-55364db40a0e
1
public void updateReward(State s) { double outputReward = s.stateScore(); if (outputReward != 0) { visits++; double alpha = (double)(1/(double)visits); double secondpart = alpha * gamma * outputReward; double firstpart = (1-alpha) * reward; reward = firstpart + secondpart; } }
1dcec763-1362-4fdf-b78b-69deaff7c05e
0
public FlowersTile(Sprite sprite, String id){ super(sprite, id); }
0f5e3bce-ffe4-4db8-877f-ee351cbbc46c
0
public static StateManager getInstance() { return ourInstance; }
56c68d42-045b-44b6-b56d-ef9a0d0bd1f8
4
@Override public boolean equals(Object obj) { if (obj instanceof AbstractAnswer) { AbstractAnswer o = (AbstractAnswer) obj; if ((ignoreCase == o.ignoreCase) && variants.size() == o.variants.size() && o.variants.containsAll(variants)) { return true; } } return false; }
195d224f-754e-4da4-b9d8-0209e30d1cd8
6
void countFile(String fileName) { String fl = fileName.toLowerCase(); if (fl.endsWith(".bam") || fl.endsWith(".sam")) countSamFile(fileName); else if (fl.endsWith(".vcf") || fl.endsWith(".vcf.gz")) countVcfFile(fileName); else if (fl.endsWith(".bed") || fl.endsWith(".bed.gz")) countBedFile(fileName); else throw new RuntimeException("Unrecognized file extention. Supported types: BAM, SAM, BED, VCF."); }
20d9b5ea-d516-46d6-bc90-3b39238b193e
9
private void SetItem() { if (!jtfTitle.getText().isEmpty()) title = jtfTitle.getText(); if (!jtfAuthor.getText().isEmpty()) author = jtfAuthor.getText(); try { if (!jtfRating.getText().isEmpty()) rating = Integer.valueOf(jtfRating.getText()); if (jtfLength.getText().isEmpty()) length = Double.valueOf(jtfLength.getText()); } catch (NumberFormatException e) { System.err.print("Input must be a number"); } if (!jtfGenre.getText().isEmpty()) genre = jtfGenre.getText(); try { switch (type) { case BOOK : Archive.instance.setItem(new Book(title, author, length, genre, rating, type), index); break; case MUSIC : Archive.instance.setItem(new Music(title, author, length, genre, rating, type), index); break; } } catch (IllegalItemException e) { System.err.println("Illegal type"); } ListPanel.updateList(); Archive.instance.setSaved(false); dispose(); }
b0c619e3-c923-411c-a16a-04ec382ec594
6
static Smelter[] siteSmelterStrip( final ExcavationSite site, final Service mined ) { final World world = site.world() ; final Tile init = Spacing.pickRandomTile(site.origin(), 4, world) ; final Smelter strip[] = new Smelter[2] ; final TileSpread spread = new TileSpread(init) { protected boolean canAccess(Tile t) { if (t.owner() == site) return true ; if (t.owningType() >= Element.FIXTURE_OWNS) return false ; return true ; } protected boolean canPlaceAt(Tile t) { final int off = Rand.index(4) ; for (int n = 4 ; n-- > 0 ;) { final int dir = STRIP_DIRS[(n + off) % 4] ; strip[0] = new Smelter(site, mined, dir, strip) ; strip[1] = new Smelter(site, mined, dir, strip) ; strip[0].setPosition(t.x, t.y, world) ; strip[1].setPosition( t.x + (N_X[dir] * 3), t.y + (N_Y[dir] * 3), world ) ; if (! Placement.checkPlacement(strip, world)) continue ; return true ; } return false ; } } ; spread.doSearch() ; if (spread.success()) { I.say("Total tiles searched: "+spread.allSearched(Tile.class).length) ; for (Smelter s : strip) { s.doPlace(s.origin(), null) ; s.updateSprite(0) ; } return strip ; } return null ; }
ecd2c5b1-f225-42bb-a45a-76549bdfef5b
2
public void setMessage(String message) { this.message = message; if(this.message != null && this.message.equals("")) this.message = null; }
633cc596-d333-42cb-9e97-eaa0d1b876ab
3
public void setElement(int i, int j, double a) { if (i == j + 1) lower[j - 1] = a; else if (i == j) diag[i - 1] = a; else if (i == j - 1) upper[i - 1] = a; else System.out.println("(i,j) liegt nicht auf der Tridiagonalen!"); }
7d3d662e-4a45-438f-99b2-ad4c7c5559e3
7
protected java.security.cert.X509Certificate[] getX509Certificates(SSLSession session) throws IOException { Certificate[] certs = null; try { certs = session.getPeerCertificates(); } catch (Throwable t) { log.debug("Error getting client certs", t); return null; } if (certs == null) return null; java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[certs.length]; for (int i = 0; i < certs.length; i++) { if (certs[i] instanceof java.security.cert.X509Certificate) { // always currently true with the JSSE 1.1.x x509Certs[i] = (java.security.cert.X509Certificate) certs[i]; } else { try { byte[] buffer = certs[i].getEncoded(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream stream = new ByteArrayInputStream(buffer); x509Certs[i] = (java.security.cert.X509Certificate) cf .generateCertificate(stream); } catch (Exception ex) { log.info("Error translating cert " + certs[i], ex); return null; } } if (log.isTraceEnabled()) log.trace("Cert #" + i + " = " + x509Certs[i]); } if (x509Certs.length < 1) return null; return x509Certs; }
5eb69dfa-bd00-42d5-96ae-d837ad715aa2
9
static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
58ab2662-fdc8-4ed5-b114-12f938025be6
6
public static DataEntry[] getKNearestNeighbours(List<DataEntry> dataSet, final double[] x, int k){ Comparator<DataEntry> distanceComparator = new Comparator<DataEntry>(){ @Override public int compare(DataEntry arg0, DataEntry arg1) { double distA = distance(arg0.getX(), x); double distB = distance(arg1.getX(), x); if(distA < distB) return 1; else if(distA == distB) return 0; return -1; } }; PriorityQueue<DataEntry> pe = new PriorityQueue<DataEntry>(k, distanceComparator); double fjernest = Double.MIN_VALUE; int i = 0; for(DataEntry tse : dataSet){ if(i < k){ //Not full pe.add(tse); fjernest = distance(pe.peek().getX(), x); } else{ double distance = distance(x,tse.getX()); if(distance < fjernest){ pe.poll(); pe.add(tse); fjernest = distance(pe.peek().getX(),x); } } i++; } DataEntry[] retur = new DataEntry[k]; i = 0; for(DataEntry d : pe){ retur[i] = d; i++; } return retur; }
aca40446-ccf7-44e1-a22d-f54dbd6d4400
1
public static List<String> decodificarActualizacion(String actualizacionJSON) { List<String> resultado = new ArrayList<String>(); JSONParser parser = new JSONParser(); try { Object objeto = parser.parse(actualizacionJSON); JSONObject objetoJSON = (JSONObject) objeto; String cantFilas = (String) objetoJSON.get(CANTFILAS); resultado.add(CANTFILAS); resultado.add(cantFilas); } catch (ParseException e) { e.printStackTrace(); } return resultado; }
efa10aa1-d32e-4686-a031-273762ed02dc
2
public void output() { mSender.sendMessage(ChatColor.GOLD + "Rules being exceeded currently: "); if(mReport.isEmpty()) mSender.sendMessage(ChatColor.GREEN + " None"); else { for(Entry<GroupSettings, StringBuilder> entry : mReport.entrySet()) mSender.sendMessage(ChatColor.YELLOW + " " + entry.getKey().getName() + ChatColor.GRAY + ": " + entry.getValue().toString()); } }
9f75079c-8882-4df6-9500-acade6796427
5
public String describePages() { StringBuilder sb = new StringBuilder(32); int sz = pages.size(); for (int i = 0; i < sz; i++) { boolean oddIndex = ((i % 2) == 1); boolean closingRangeForSinglePage = false; if (oddIndex) { closingRangeForSinglePage = pages.get(i).equals(pages.get(i-1)); if (!closingRangeForSinglePage) { sb.append('-'); } } else if (i > 0) { sb.append(", "); } if (!closingRangeForSinglePage) { sb.append(pages.get(i).toString()); } } return sb.toString(); }
40fbdfe7-39f5-4bcf-a6e0-43b5ddec85c9
5
public int[] maxHeapify(int[] A, int position, int heapSize){ int positionLeft = left(position); int positionRight = right(position); int largest = position; //store the largest element between left right and parent if(positionLeft <= heapSize && A[positionLeft] > A[largest]){ largest = positionLeft; } if(positionRight <= heapSize && A[positionRight] > A[largest]){ largest = positionRight; } if(largest != position){ exchange(A, largest, position); maxHeapify(A, largest, heapSize); } return A; }
ef6e5ee7-b389-4550-91c2-e5220e9ef331
1
private JTextField getJTextFieldSpellDictionaryFilename() { if (jTextFieldSpellDictionaryFilename == null) { jTextFieldSpellDictionaryFilename = new JTextField(); } return jTextFieldSpellDictionaryFilename; }
c603fdf3-271b-42da-8cda-eb0b21940fc8
4
public static List<ShopAddressInfo> getShopAddresses(int shopId)throws HibernateException { List<ShopAddressInfo> shopAddressList = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try { // Begin unit of work session.beginTransaction(); String hqlString = "select sa from ShopAddressInfo as sa where sa.shopId=" + shopId; Query query = session.createQuery(hqlString); @SuppressWarnings("unchecked") List<ShopAddressInfo> list = query.list(); if (list.size() > 0) { shopAddressList = new ArrayList<ShopAddressInfo>(); for (int i = 0; i < list.size(); i++) { shopAddressList.add(list.get(i)); } } // End unit of work session.getTransaction().commit(); } catch (HibernateException hex) { logger.error(hex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } catch (Exception ex) { logger.error(ex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } return shopAddressList; }
4b545ac3-7cce-422b-b51f-1625e655520f
9
public void checkCollision(Dimension rec) { boolean alive = true; for(int i = snakeLength; i > 0; i--){ if((i > 4) && (X[0] == X[i]) && (Y[0] == Y[i])) alive = false; } if(Y[0] >= rec.height) alive = false; if(Y[0] < 0) alive = false; if(X[0] >= rec.width) alive = false; if(X[0] < 0) alive = false; if(!alive) b.setState(STATE.GAMEOVER); }
8f5d3950-d259-4217-a1d2-ed95a3c97948
4
public void createXmlFromTemplate(String templateFileName, String fileName, HashMap<String, String> hmap) { try { DocumentBuilder rBuilder = init(); Document rDoc = rBuilder.parse(templateFileName); Element rRoot = rDoc.getDocumentElement(); DocumentBuilder wBuilder = init(); Document wDoc = wBuilder.newDocument(); if (wDoc != null) { Element wRoot = iterativeCreateElement(rRoot, hmap, wDoc); wDoc.appendChild(wRoot); // transform wDoc to streamOutput ((org.apache.crimson.tree.XmlDocument)wDoc).write(new FileOutputStream(fileName)); // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(wDoc); // StreamResult result = new StreamResult(new File(fileName)); // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // transformer.transform(source, result); } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } // catch (TransformerException e) { // System.out.println(e.getMessage()); // } }
f2712126-97db-497a-a127-3a9f8c64e8b1
3
public void run() { setName(this.getClass().getSimpleName() + " [" + actors.playerId + "]"); setPriority(NORM_PRIORITY + 2); while (gameState != STATE_STOPPED) { int frames = waitForNextFrame(); for (Updateable c: callbacks) c.update(gameState == STATE_PAUSED); // Don't update the game state if we are paused if(gameState == STATE_PAUSED) continue; checkCollision(); // Update the actors actors.update(frames); } }
8630d341-dcc8-4e7a-9fdb-d82757788de2
7
private ClassLoader getBaseClassLoader() throws LogConfigurationException { ClassLoader thisClassLoader = getClassLoader(LogFactoryImpl.class); if (useTCCL == false) { return thisClassLoader; } ClassLoader contextClassLoader = getContextClassLoader(); ClassLoader baseClassLoader = getLowestClassLoader( contextClassLoader, thisClassLoader); if (baseClassLoader == null) { // The two classloaders are not part of a parent child relationship. // In some classloading setups (e.g. JBoss with its // UnifiedLoaderRepository) this can still work, so if user hasn't // forbidden it, just return the contextClassLoader. if (allowFlawedContext) { if (isDiagnosticsEnabled()) { logDiagnostic( "[WARNING] the context classloader is not part of a" + " parent-child relationship with the classloader that" + " loaded LogFactoryImpl."); } // If contextClassLoader were null, getLowestClassLoader() would // have returned thisClassLoader. The fact we are here means // contextClassLoader is not null, so we can just return it. return contextClassLoader; } else { throw new LogConfigurationException( "Bad classloader hierarchy; LogFactoryImpl was loaded via" + " a classloader that is not related to the current context" + " classloader."); } } if (baseClassLoader != contextClassLoader) { // We really should just use the contextClassLoader as the starting // point for scanning for log adapter classes. However it is expected // that there are a number of broken systems out there which create // custom classloaders but fail to set the context classloader so // we handle those flawed systems anyway. if (allowFlawedContext) { if (isDiagnosticsEnabled()) { logDiagnostic( "Warning: the context classloader is an ancestor of the" + " classloader that loaded LogFactoryImpl; it should be" + " the same or a descendant. The application using" + " commons-logging should ensure the context classloader" + " is used correctly."); } } else { throw new LogConfigurationException( "Bad classloader hierarchy; LogFactoryImpl was loaded via" + " a classloader that is not related to the current context" + " classloader."); } } return baseClassLoader; }
dacfab51-08bb-4dbc-a26a-b9ff105e04d8
4
public static Set getSet(int id) { Set set = new Set(); Node node = nodeList.item(id); set.height = new Integer(node.getAttributes().getNamedItem("height").getNodeValue()); NodeList nnm = node.getChildNodes(); set.entities = new Entity[nnm.getLength()]; for (int j = 0; j < nnm.getLength(); j++) { NamedNodeMap n = nnm.item(j).getAttributes(); int x = new Integer(n.getNamedItem("x").getNodeValue()); int y = new Integer(n.getNamedItem("y").getNodeValue()); String ent = n.getNamedItem("entity").getNodeValue(); if (ent.contains("solid")) set.entities[j] = new SoildEntity(x * 8, y * 8); if (ent.contains("coin")) set.entities[j] = new CoinEntity(x * 8, y * 8); if (ent.contains("end")) set.entities[j] = new EndEntity(x * 8, y * 8); } return set; }
73e2bae0-c1d4-4abe-8f5d-40bc89e20f70
8
public void buildClassifier(Instances insts) throws Exception { m_Filter = null; if (!isPresent()) throw new Exception("libsvm classes not in CLASSPATH!"); // remove instances with missing class insts = new Instances(insts); insts.deleteWithMissingClass(); if (!getDoNotReplaceMissingValues()) { m_ReplaceMissingValues = new ReplaceMissingValues(); m_ReplaceMissingValues.setInputFormat(insts); insts = Filter.useFilter(insts, m_ReplaceMissingValues); } // can classifier handle the data? // we check this here so that if the user turns off // replace missing values filtering, it will fail // if the data actually does have missing values getCapabilities().testWithFail(insts); if (getNormalize()) { m_Filter = new Normalize(); m_Filter.setInputFormat(insts); insts = Filter.useFilter(insts, m_Filter); } Vector vy = new Vector(); Vector vx = new Vector(); int max_index = 0; for (int d = 0; d < insts.numInstances(); d++) { Instance inst = insts.instance(d); Object x = instanceToArray(inst); int m = Array.getLength(x); if (m > 0) max_index = Math.max(max_index, ((Integer) getField(Array.get(x, m - 1), "index")).intValue()); vx.addElement(x); vy.addElement(new Double(inst.classValue())); } // calculate actual gamma if (getGamma() == 0) m_GammaActual = 1.0 / max_index; else m_GammaActual = m_Gamma; // check parameter String error_msg = (String) invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_check_parameter", new Class[]{ Class.forName(CLASS_SVMPROBLEM), Class.forName(CLASS_SVMPARAMETER)}, new Object[]{ getProblem(vx, vy), getParameters()}); if (error_msg != null) throw new Exception("Error: " + error_msg); // train model m_Model = invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_train", new Class[]{ Class.forName(CLASS_SVMPROBLEM), Class.forName(CLASS_SVMPARAMETER)}, new Object[]{ getProblem(vx, vy), getParameters()}); // save internal model? if (!m_ModelFile.isDirectory()) { invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_save_model", new Class[]{ String.class, Class.forName(CLASS_SVMMODEL)}, new Object[]{ m_ModelFile.getAbsolutePath(), m_Model}); } }
774acad4-8594-4ccb-9791-925afab18b0e
2
public String getRate(String r){ if (r == null)return null; int pos = r.lastIndexOf("="); r = r.substring(pos + 1); pos = r.lastIndexOf("."); r = r.substring(0, pos + 6); if (r.contains(",")){ pos = r.lastIndexOf(","); r = (r.substring(0, pos) + r.substring(pos+1)); //System.out.println(r); } return r; }
2449bbdb-3c3f-4a15-8ab1-22b7df3d814b
7
public void rescale(){ double xmin = Double.MAX_VALUE; double xmax = Double.MIN_VALUE; double ymin = Double.MAX_VALUE; double ymax = Double.MIN_VALUE; for(drawNode N : nodes) { xmin = xmin < N.x ? xmin : N.x; xmax = xmax > N.x ? xmax : N.x; ymin = ymin < N.y ? ymin : N.y; ymax = ymax > N.y ? ymax : N.y; } for(drawNode N : nodes) { N.x = (N.x-xmin)/(xmax-xmin); N.y = (N.y-ymin)/(ymax-ymin); } for(drawLink L : links) { L.xs = (L.xs-xmin)/(xmax-xmin); L.ys = (L.ys-ymin)/(ymax-ymin); L.xe = (L.xe-xmin)/(xmax-xmin); L.ye = (L.ye-ymin)/(ymax-ymin); } }
78ac1f88-167b-4d2c-a85e-027eaf3c6d4e
2
public boolean playerOnPoint(Player p){ Block b = p.getLocation().getBlock(); return Team.blockMaterialIsTeamMaterial(b) || Team.blockMaterialIsTeamMaterial(b.getRelative(BlockFace.DOWN, 1)) || Team.blockMaterialIsTeamMaterial(b.getRelative(BlockFace.DOWN, 2)); }
b987ea4c-d542-4eb1-bcfb-4420635bff21
0
@Override public void removeExtension(String ext) { extensions.remove(ext); }
41c211fd-bcf0-4293-adcb-6de2c0acff13
7
public addGUI(final String lastData) { answer = true; setTitle("20 Questions"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Main.exitCheck(getContentPane()); } }); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setBounds(0, 0, 384, 288); setMinimumSize(new Dimension(166, 286)); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); final JLabel titleLbl = new JLabel("20 Questions:"); titleLbl.setHorizontalAlignment(SwingConstants.CENTER); titleLbl.setFont(new Font("Tahoma", Font.PLAIN, 18)); contentPane.add(titleLbl); final JLabel awkLbl = new JLabel("Oh... awkward."); awkLbl.setHorizontalAlignment(SwingConstants.CENTER); awkLbl.setFont(new Font("Tahoma", Font.PLAIN, 12)); contentPane.add(awkLbl); final JPanel panel = new JPanel(); contentPane.add(panel); panel.setLayout(null); final JLabel objectLbl = new JLabel("What was the object?"); objectLbl.setHorizontalAlignment(SwingConstants.CENTER); objectLbl.setFont(new Font("Tahoma", Font.PLAIN, 12)); panel.add(objectLbl); final JLabel openingLbl = new JLabel( "What is a question that would help me pick between "); openingLbl.setHorizontalAlignment(SwingConstants.CENTER); openingLbl.setFont(new Font("Tahoma", Font.PLAIN, 12)); panel.add(openingLbl); editLbl = new JLabel("an ... and a " + lastData + "?"); editLbl.setHorizontalAlignment(SwingConstants.CENTER); editLbl.setFont(new Font("Tahoma", Font.PLAIN, 12)); panel.add(editLbl); objectTxt = new JTextField(); objectTxt.setHorizontalAlignment(SwingConstants.CENTER); panel.add(objectTxt); objectTxt.setColumns(10); questionTxt = new JTextField(); questionTxt.setHorizontalAlignment(SwingConstants.CENTER); panel.add(questionTxt); questionTxt.setColumns(10); final JButton finishBtn = new JButton("Next"); finishBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(!(objectTxt.getText().length() > 0 && questionTxt //if a field is blank, don't add a Q&A if user doesn't want to .getText().length() > 0)) { if(JOptionPane .showConfirmDialog( getContentPane(), "You have left a field or two blank, do you not want to add anything to the game?", "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) return; else EventQueue.invokeLater(new Runnable() { public void run() { try { finishGUI frame = new finishGUI(false); frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } }); setVisible(false); return; } if(JOptionPane //confirms they are adding a compatible Q&A to the game .showConfirmDialog(getContentPane(), "If you answer yes to the question: \"" + questionTxt.getText() + "\" does it lead to \"" + (answer ? objectTxt.getText() : lastData) + "?\"", "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) return; yesBtn.setEnabled(false); questionTree.add(objectTxt.getText(), //adds Q&A to the tree questionTxt.getText(), answer); questionTree.write(); setVisible(false); EventQueue.invokeLater(new Runnable() { public void run() { try { finishGUI frame = new finishGUI(false); frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } }); } }); getRootPane().setDefaultButton(finishBtn); yesBtn = new JRadioButton("Yes"); yesBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { answer = true; } }); final JLabel ansLbl = new JLabel("Answer:"); ansLbl.setFont(new Font("Tahoma", Font.PLAIN, 12)); panel.add(ansLbl); yesBtn.setSelected(true); buttonGroup.add(yesBtn); panel.add(yesBtn); final JRadioButton noBtn = new JRadioButton("No"); noBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { answer = false; } }); buttonGroup.add(noBtn); panel.add(noBtn); panel.add(finishBtn); titleLbl.setBounds(10, 10, getWidth() - 36, 14); awkLbl.setBounds(10, 34, getWidth() - 36, 14); panel.setBounds(10, 48, getWidth() - 36, getHeight() - 96); objectLbl.setBounds(10, 10, panel.getWidth() - 20, 14); objectTxt.setBounds(0, 36, panel.getWidth(), 20); openingLbl.setBounds(10, 67, panel.getWidth() - 20, 14); editLbl.setBounds(10, 92, panel.getWidth() - 20, 14); questionTxt.setBounds(0, 117, panel.getWidth(), 20); ansLbl.setBounds((panel.getWidth() - 131) / 2, 145, 45, 14); yesBtn.setBounds(ansLbl.getX() + ansLbl.getWidth() + 6, ansLbl.getY(), 42, 14); noBtn.setBounds(yesBtn.getX() + yesBtn.getWidth(), ansLbl.getY(), 38, 14); finishBtn.setBounds(panel.getWidth() - 89, panel.getHeight() - 23, 89, 23); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { titleLbl.setBounds(10, 10, getWidth() - 36, 14); awkLbl.setBounds(10, 34, getWidth() - 36, 14); panel.setBounds(10, 48, getWidth() - 36, getHeight() - 94); objectLbl.setBounds(10, 10, panel.getWidth() - 20, 14); objectTxt.setBounds(0, 36, panel.getWidth(), 20); openingLbl.setBounds(10, 67, panel.getWidth() - 20, 14); editLbl.setBounds(10, 92, panel.getWidth() - 20, 14); questionTxt.setBounds(0, 117, panel.getWidth(), 20); ansLbl.setBounds((panel.getWidth() - 131) / 2, 145, 45, 14); yesBtn.setBounds(ansLbl.getX() + ansLbl.getWidth() + 6, ansLbl.getY(), 42, 14); noBtn.setBounds(yesBtn.getX() + yesBtn.getWidth(), ansLbl.getY(), 38, 14); finishBtn.setBounds(panel.getWidth() - 89, panel.getHeight() - 23, 89, 23); } }); }
ec8d56e9-6a99-4a62-a225-47523140d22e
5
public void dispose() { for (int i = 0; i < resources.size(); i++) { Object obj = resources.get(i); if (obj != null && obj instanceof Resource) ((Resource) obj).dispose(); } resources = new ArrayList(); if (menu1 != null) { menu1.dispose(); menu1 = null; } if (menu2 != null) { menu2.dispose(); menu2 = null; } }
83915167-5902-4a46-a262-4ffe28affefc
4
private String buildItemString(ItemStack[] items) { StringBuilder sbItems = new StringBuilder(); StringBuilder sbAmount = new StringBuilder(); StringBuilder sbDurability = new StringBuilder(); StringBuilder sbEnchants = new StringBuilder(); for (ItemStack item : items) { int itemId = 0; int amount = 0; short durability = 0; Map<Enchantment, Integer> enchants = null; if (item != null) { itemId = item.getTypeId(); amount = item.getAmount(); durability = item.getDurability(); enchants = item.getEnchantments(); if (!enchants.keySet().isEmpty()) { for (Enchantment enchant : enchants.keySet()) { int id = enchant.getId(); int level = enchants.get(enchant); sbEnchants.append(id + ":" + level + "-"); } sbEnchants.deleteCharAt(sbEnchants.lastIndexOf("-")); } } sbItems.append(itemId).append(","); sbAmount.append(amount).append(","); sbDurability.append(durability).append(","); sbEnchants.append(","); } sbItems.deleteCharAt(sbItems.lastIndexOf(",")); sbAmount.deleteCharAt(sbAmount.lastIndexOf(",")); sbDurability.deleteCharAt(sbDurability.lastIndexOf(",")); sbEnchants.deleteCharAt(sbEnchants.lastIndexOf(",")); return sbItems.append(";").append(sbAmount).append(";").append(sbDurability).append(";").append(sbEnchants).toString(); }
74e23747-afbc-4cba-bf28-e4456c7b0a2f
5
@Override public Handshakedata translateHandshake( ByteBuffer buf ) throws InvalidHandshakeException { HandshakeBuilder bui = translateHandshakeHttp( buf, role ); // the first drafts are lacking a protocol number which makes them difficult to distinguish. Sec-WebSocket-Key1 is typical for draft76 if( ( bui.hasFieldValue( "Sec-WebSocket-Key1" ) || role == Role.CLIENT ) && !bui.hasFieldValue( "Sec-WebSocket-Version" ) ) { byte[] key3 = new byte[ role == Role.SERVER ? 8 : 16 ]; try { buf.get( key3 ); } catch ( BufferUnderflowException e ) { throw new IncompleteHandshakeException( buf.capacity() + 16 ); } bui.setContent( key3 ); } return bui; }
05b61ac6-5fe3-45d2-a76b-95e4ad5be865
6
@Override public boolean runTest(){ return ((notString("candy").equals("not candy")) && (notString("x").equals("not x")) && (notString("not bad").equals("not bad")) && (notString("bad").equals("not bad")) && (notString("not").equals("not")) && (notString("is not").equals("not is not")) && (notString("no").equals("not no"))); }
959e8b23-4586-482b-838b-50a286f70314
7
public String toString(){ String s = ""; if (value == 1) s += "Ace"; else if (value == 11) s += "Jack"; else if (value == 12) s += "Queen"; else if (value == 13) s += "King"; else s += "" + value; if (suit == 0) s += " of clubs"; else if (suit == 1) s += " of diamonds"; else if (suit == 2) s+= " of hearts"; else s+= " of spades"; return s; }
496fbb9d-3616-419a-bdd6-8a2056569f9e
7
public double parseDouble() throws IOException { int sign = 1; int c = nextNonWhitespace(); if( c == '+' ) { // Unclear if whitespace is allowed here or not c = read(); } else if( c == '-' ) { sign = -1; // Unclear if whitespace is allowed here or not c = read(); } if( c == '0' ) { int d = read(); if( d == 'x' || d == 'X' ) { long val = (int)parseIntString(16, "hexidecimal"); return Double.longBitsToDouble(val) * sign; } else if( d == 'b' || d == 'B' ) { return Double.longBitsToDouble(parseIntString(1, "binary")) * sign; } else { pushBack(d); } } // If we got here then we didn't use the original character // we read at the top of the method... or the one we read to // replace it pushBack(c); // Else read the number while we have digits double result = parseFloatString() * sign; return result; }
89f4cddc-aefd-4842-9e75-17cd165211dd
8
public void updateFileLinksOnWindows() { if (currentFiles == null) { currentFiles = getFiles(); } toUpdate.clear(); List<ServerFile> toDelete = new ArrayList<>(); for (ServerFile file : currentFiles) { if (file.getFlag() == ServerFile.DELETED) { file.tryDelete(getController().getConfig().getProperty( "mount.testdir") + "/categories/"); toDelete.add(file); } } this.getController().getDb().delete(toDelete); for (ServerFile serverfile : currentFiles) { if (serverfile.getFlag() != ServerFile.CREATED && serverfile.getFlag() != ServerFile.UPDATED) { continue; } File file = new File(getController().getConfig().getProperty( "mount.testdir") + "/categories/" + serverfile.getPath()); file.getParentFile().mkdirs(); try { Files.write(file.toPath(), serverfile.getServerpath() .getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { e.printStackTrace(); } // Prevent history spam after reconnects. if(!isJustReconnected()) { getController().track(serverfile); } serverfile.setFlag(ServerFile.UP_TO_DATE); serverfile.setModified(); toUpdate.add(serverfile); } this.saveChanges(); }
4088dd67-c090-498e-944f-646508fd76ad
5
private static void manageArgs(String[] args) { for (int i = 0; i < args.length; i++) { switch (args[i].trim().toLowerCase()) { case "nogui": nogui = true; break; case "server": startServer = true; break; case "port": if (i < args.length - 1) { port = parsePositiveInt(args[++i]); } else { System.err.println("Found argument 'port', but no port was given"); System.exit(1); } break; default: System.err.println("Unknown command: " + args[i].trim().toLowerCase()); System.exit(1); break; } } }
ed081da9-8164-4d3f-b815-2573af8087c8
2
public void setCity(String city) { if(city == null || city.isEmpty()){ throw new IllegalArgumentException(); } this.city = city; }
e9471174-588e-4d07-a9fb-0a4f9970218c
1
public void setType(ReleaseType type) { if (type == null) throw new IllegalArgumentException("Release type cannot be null"); this.type = type; }
e362e6b5-f547-4efa-b5bc-a59794ff6f03
3
private static void Search(int[] array2) { // TODO Auto-generated method stub if(array2.length == 1){ return; } if(key == array2[(array2.length)/2]){ exists = true; }else{ if(key < array2[(array2.length)/2] ){ array2 = Arrays.copyOfRange(array2,0, array2.length/2); Search(array2); }else{ array2 = Arrays.copyOfRange(array2, array2.length/2, array2.length); Search(array2); } } }
d4500dba-cd2d-4583-9e20-dfeed1c4c5e8
6
public void create(){ init = true; String sound; float yOff=0; //initial body shit switch(ID){ case"boulderFist": yOff = -1.2f*height; break; default: //do nothing special } //define hitbox physics PolygonShape shape = new PolygonShape(); shape.setAsBox((rw)/PPM, (rh)/PPM); bdef.position.set(x/PPM, (y+yOff)/PPM); bdef.type = BodyType.KinematicBody; body = world.createBody(bdef); body.setUserData(this); fdef.shape = shape; fdef.isSensor = isSensor; fdef.filter.maskBits = (short) Vars.BIT_GROUND | Vars.BIT_LAYER1 | Vars.BIT_PLAYER_LAYER | Vars.BIT_LAYER3; fdef.filter.categoryBits = layer; body.createFixture(fdef).setUserData("damageField"); //make body do shit //determine sound/light for creation and initial offset Color c; switch(ID){ case "electricField": sound = "sparking"; c = new Color(Vars.SUNSET_GOLD); c.a =.5f; light = new PointLight(main.getRayHandler(), Vars.LIGHT_RAYS, c, 200, x, y); break; case "fireyField": sound = "crackling"; c = new Color(Vars.SUNSET_ORANGE); c.a =.5f; light = new PointLight(main.getRayHandler(), Vars.LIGHT_RAYS, c, 150, x, y); break; case "chillyWind": sound = "air1"; break; case "boulderFist": sound = "boulderFist"; body.setLinearVelocity(new Vector2(0, 2f)); break; default: sound = ""; } if(!sound.isEmpty()) damageSound = new PositionalAudio(getPosition(), sound, main); }
8cfdf91c-5835-491a-8cf8-ff34994575da
6
public void drawImage(int i, int k) { i += drawOffsetX; k += drawOffsetY; int l = i + k * DrawingArea.width; int i1 = 0; int j1 = imageHeight; int k1 = imageWidth; int l1 = DrawingArea.width - k1; int i2 = 0; if (k < DrawingArea.topY) { int j2 = DrawingArea.topY - k; j1 -= j2; k = DrawingArea.topY; i1 += j2 * k1; l += j2 * DrawingArea.width; } if (k + j1 > DrawingArea.bottomY) j1 -= (k + j1) - DrawingArea.bottomY; if (i < DrawingArea.topX) { int k2 = DrawingArea.topX - i; k1 -= k2; i = DrawingArea.topX; i1 += k2; l += k2; i2 += k2; l1 += k2; } if (i + k1 > DrawingArea.bottomX) { int l2 = (i + k1) - DrawingArea.bottomX; k1 -= l2; i2 += l2; l1 += l2; } if (!(k1 <= 0 || j1 <= 0)) { method362(j1, DrawingArea.pixels, imagePixels, l1, l, k1, i1, palette, i2); } }
00030104-e246-438d-bdf8-52dbd27dfa44
1
@Override public Box recupera(Integer id) throws RemoteException, ObjetoNaoEncontradoException { Box box = h.get(id); //If there is a object in box, return it, other wise throws a exception if(box != null) { return box; } else //throws a exception { throw new ObjetoNaoEncontradoException(id.toString()); } }
ff6ddcc4-5738-4b95-9b71-644bdb114a14
8
public boolean checkId(String id) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConnection(); pstmt = conn.prepareStatement("select id from member where id=?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; }
0f354e6c-ebc3-4fb4-a37b-883b234bd23d
4
private void removeAny(Gameboy gb, List<ListState> listStates, StateBuffer initialStates) { HashMap<Integer, ListState> listStateMap = new HashMap<>(); for (ListState listState : listStates) { for (State state : initialStates.getStates()) { State s = listState == null ? state : listState.toState(gb, state, false); if (!listStateMap.containsKey(s.rngState)) listStateMap.put(s.rngState, listState); } } listStates.retainAll(listStateMap.values()); }
09fb3789-bdf4-4ff4-8772-33236db70dea
7
@Override public void importRead(String path) { InputStream is = null; try { is = new FileInputStream(path); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStreamReader isr = new InputStreamReader(is); Scanner scan = new Scanner(is); // skip the first lines String numNodes = scan.nextLine(); while (numNodes != null && !numNodes.equals(separator)) { numNodes = scan.nextLine(); } while (scan.hasNext()) { String line = scan.nextLine(); if (line == null) { throw new PositionFileException( "The specified file contains not enough informations"); } try { String[] parts = line.split(" "); if (parts.length < 2) { throw new PositionFileException( "Illegal line: expected two ints, separated by space. Found \n" + line); } int nId = Integer.parseInt(parts[0]); int shots = Integer.parseInt(parts[1]); ((AbstractRoutingNode) Tools.getNodeByID(nId)).setTraffic(60.0, shots); // setTrafficToNode((InterfaceRequiredMethods) // Tools.getNodeByID(n), 60, shots); } catch (NumberFormatException e) { throw new PositionFileException( "Illegal line: expected two ints, separated by comma. Found \n" + line); } } }
d1439424-7a13-43b6-a3b1-e2d1562073a0
9
private void setCIMs(IModel<Double, CTDiscreteNode> model, SufficientStatistics lData[]) throws RuntimeException { // Parameter calculation NodeIndexing nodeIndexing = model.getNodeIndexing(); for( int iNode = 0; iNode < nodeIndexing.getNodesNumber(); ++iNode) { CTDiscreteNode node = model.getNode(iNode); if( node.isStaticNode()) { for( int pE = 0; pE < node.getNumberParentsEntries(); ++pE) { // Probability distribution calculation double[][] prob = new double[1][node.getStatesNumber()]; for( int sE = 0; sE < node.getStatesNumber(); ++sE) prob[0][sE] = lData[iNode].Px[pE][0][sE] / lData[iNode].counts[pE]; node.setCIM( pE, prob); } }else { for( int pE = 0; pE < node.getNumberParentsEntries(); ++pE) { double[][] cim = new double[node.getStatesNumber()][node.getStatesNumber()]; for( int fsE = 0; fsE < node.getStatesNumber(); ++fsE) { // CIM calculation cim[fsE][fsE] = -lData[iNode].Mx[pE][fsE] / lData[iNode].Tx[pE][fsE]; for( int ssE = 0; ssE < node.getStatesNumber(); ++ssE) if( fsE != ssE) cim[fsE][ssE] = lData[iNode].Mxx[pE][fsE][ssE] / lData[iNode].Tx[pE][fsE]; // cim[fsE][ssE] = -cim[fsE][fsE] * (lData[iNode].Mxx[pE][fsE][ssE] / lData[iNode].Mx[pE][fsE]); } node.setCIM(pE, cim); } } int check = node.checkCIMs(); if( check != -1) throw new RuntimeException("Error: unexpected error in CIM validation for node " + node.getName() + " and parent entry " + check + " (the inserting of the priors imaginary counts can solve this exception)"); } }
76737956-4969-4a63-b7c4-8a88da50bf72
5
public void render(Screen screen, int xScroll, int yScroll) { screen.renderSprite(tileset.getBackground(), 0, 0, 0, false); // Render background first // Then the tiles screen.setOffset(xScroll, yScroll); int x0 = xScroll >> 4; int x1 = (xScroll + game.getScaledWidth() + 16) >> 4; int y0 = yScroll >> 4; int y1 = (yScroll + game.getScaledHeight() + 16) >> 4; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { Tile tile = getTile(x, y); tile.render(screen, x, y); if (game.showHitboxes && tile.isSolid()) screen.drawQuad(0xff0000, x << 4, y << 4, tileset.getTileSize(), tileset.getTileSize()); } } for (int i = 0; i < entities.size(); i++) { entities.get(i).render(screen); } }
1b181c2d-0498-46fa-9f4c-56ec5a27df23
8
public boolean attemptDirection(String dir, double x, double y) { Rectangle nextLoc = new Rectangle(boundingBox); boolean isDirectionFree = false; if(dir.equals("up")) { nextLoc.setLocation( (int)(x+0*speed), (int)(y-1*speed) ); if(room.isLocationFree(nextLoc,isEaten)) { isDirectionFree = true; } else { isDirectionFree = false; } } else if(dir.equals("down")) { nextLoc.setLocation( (int)(x+0*speed), (int)(y+1*speed) ); if(room.isLocationFree(nextLoc,isEaten)) { isDirectionFree = true; } else { isDirectionFree = false; } } else if(dir.equals("left")) { nextLoc.setLocation( (int)(x-1*speed), (int)(y+0*speed) ); if(room.isLocationFree(nextLoc,isEaten)) { isDirectionFree = true; } else { isDirectionFree = false; } } else if(dir.equals("right")) { nextLoc.setLocation( (int)(x+1*speed), (int)(y+0*speed) ); if(room.isLocationFree(nextLoc,isEaten)) { isDirectionFree = true; } else { isDirectionFree = false; } } return isDirectionFree; }
5b44376c-2025-47ba-8d9e-f7cad710aedc
4
public boolean equals(Object o){ StockItem nimi=(StockItem)o; return nimi.getId()==getId() && nimi.getName()== getName() && nimi.getDescription()== getDescription() && nimi.getPrice()== getPrice() && nimi.getQuantity()==getQuantity(); }
76d3c69d-301a-4471-bbe1-fc0df844ee37
1
public static void main(String[] args) { while(condition()) System.out.println("Inside �while�"); // do // System.out.println("Inside �do-while�"); // while(condition()); System.out.println("Exited �while�"); }
c0992772-9a59-4e16-a396-d17773f69dfb
1
private void determineTransitions() { remainingTransitions = new HashSet(); State[] states = minDfa.getStates(); for (int i = 0; i < states.length; i++) remainingTransitions.addAll(minimizer.getTransitionsForState( states[i], minDfa, dfa, tree)); }
6de9d9ae-6f9e-429f-ad17-ad3f2da8547a
4
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pose other = (Pose) obj; if (type != other.type) { return false; } return true; }
826b9da0-bf87-42d0-80d6-f4ab4441278e
4
@OnLoad public void onLoad() { super.onLoad(); TeamModel team = null; if(getParis_sched()!=null) { if(paris_team_select == Teams.HOME) team = DataStore.getTeam(((ScheduleTeamModel)getParis_sched()).getSched_home_team_id()); else if(paris_team_select == Teams.AWAY) team = DataStore.getTeam(((ScheduleTeamModel)getParis_sched()).getSched_away_team_id()); } if(team!=null) this.paris_team = team; }
1693c344-86d8-4405-9ff9-440abc6b31a7
3
String getHandleFileResult(final AndroidDevice aDevice, SubType subType, String localFile, String remoteFile) { try { switch (subType) { case PULL: aDevice.getDevice().pullFile(remoteFile, localFile); break; case PUSH: aDevice.getDevice().pushFile(localFile, remoteFile); break; default: break; } } catch (SyncException | IOException | AdbCommandRejectedException | TimeoutException e) { e.printStackTrace(); return "Command failed:" + e.getLocalizedMessage(); } return "Command success"; }
61b2a2e6-3a94-4feb-b9bc-4afd10929395
3
public int isCurrencySlot(int slot) { if (slot == smallCurrencySlot) return smallCurrency; if (slot == mediumCurrencySlot) return mediumCurrency; if (slot == largeCurrencySlot) return largeCurrency; return 0; }
d5771485-7d46-4052-ae7c-7d4bf5d3ab63
8
@EventHandler(priority = EventPriority.HIGH) public void onPlayerDie(EntityDamageByEntityEvent event) { Entity entity = event.getEntity(); if (entity instanceof Player) { Player victim = (Player) entity; Entity entity2 = event.getDamager(); if (entity2 instanceof Player) { Player damager = (Player) entity2; Bukkit.getScheduler().runTaskLater(main, new CheckIfPlayerIsDead(victim, damager), 2L); } else if (entity2 instanceof Arrow) { Arrow arrow = (Arrow) entity2; ProjectileSource source = arrow.getShooter(); if (source instanceof Player) { Player shooter = (Player) source; if (shooter.getName().equalsIgnoreCase("IronCrystal")) { event.setDamage(0); List<Entity> entities = victim.getNearbyEntities(10, 5, 10); for (Entity e : entities) { if (e instanceof Player) { Player p = (Player) e; if (!p.getName().equalsIgnoreCase("IronCrystal")) { EntityDamageByEntityEvent playerEvent = new EntityDamageByEntityEvent(p, victim, DamageCause.ENTITY_ATTACK, victim.getHealth()); // Create the event here Bukkit.getServer().getPluginManager().callEvent(playerEvent); // Call the event break; } } } } } } } }